问:
Propagate all arguments in a Bash shell script
I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing.

For instance, my script name is foo.sh and calls bar.sh.

foo.sh:

```<code>bar $1 $2 $3 $4
</code>```

How can I do this without explicitly specifying each parameter?

答:
bar "$@" will be equivalent to bar "$1" "$2" "$3" "$4"

Notice that the quotation marks are important!

"$@", $@, "$*" or $* will each behave slightly different regarding escaping and concatenation as described in this stackoverflow answer.

One closely related use case is passing all given arguments inside an argument like this:

bash -c "bar \"$1\" \"$2\" \"$3\" \"$4\"".

I use a variation of @kvantour's answer to achieve this:

bash -c "bar $(printf -- '"%s" ' "$@")"

Body:
I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing.

For instance, my script name is foo.sh and calls bar.sh.

foo.sh:

bar $1 $2 $3 $4

How can I do this without explicitly specifying each parameter?


来源: stackexchange

问:
How to show a button after a specific time period?
I am developing an android app in which when user click  on the in button, out button should be hidden for 8 hours or hours given by the user and after 8 hours out button should be visible and if the user forgot to click on the out button it should automatically mark him out.

I searched I come to know about android services but I didn't understand how to achieve this by using service.

Thanks for the help.

答:
Use alaram manager & pending intent with broadcast reciver like this</p>

```<code>Intent intent = new Intent(activity, AlarmBroadCast.class);

pendingIntent = PendingIntent.getBroadcast(activity, 0, intent, 0);
alarmManager = (AlarmManager) activity.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 2); //Set your time here
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

//Broadcast reciver
public class AlarmBroadCast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
       //Implement your logic
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Use alaram manager & pending intent with broadcast reciver like this

Intent intent = new Intent(activity, AlarmBroadCast.class);

pendingIntent = PendingIntent.getBroadcast(activity, 0, intent, 0);
alarmManager = (AlarmManager) activity.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 2); //Set your time here
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

//Broadcast reciver
public class AlarmBroadCast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
       //Implement your logic
    }
}


问:
ASP.NET Core 2.2 Lockout not activating
I am using PasswordSignInAsync to verify my users like this:

```<code>var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
</code>```

However, I noticed that I am unable to get locked when I purposely enter the wrong password.

This is my startup.cs:

```<code>var lockoutOptions = new LockoutOptions()
{
    AllowedForNewUsers = true,
    DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5),
    MaxFailedAccessAttempts = 5
};

services.AddIdentity<User, Role>(
    options => {
        options.Lockout = lockoutOptions;
    }
)
.AddEntityFrameworkStores<AppDbContext>();
</code>```

I checked in the database when I purposely enter the wrong password, the AccessFailedCount increases by 1 until it hits 5 then it goes to 0 again so that means its actually working. Its just the locking part is not working.

答:
If you have Extended the built in IdentityUser and IdentityRole to your respective Custom User and Role, then you have to Implement IUserLockoutStore On your custom UserStore and write respective code for each implementation to update your AccessFailCount.

```<code>public class UserStore :  IUserStore<User>, IUserEmailStore<User>, IUserPasswordStore<User>, IUserRoleStore<User> IUserLockoutStore<User>
{

    #region Other Interface Implementation
    #endregion

    #region  IUserLockoutStore

    public Task<DateTimeOffset?> GetLockoutEndDateAsync(User user, CancellationToken cancellationToken)
    {

        cancellationToken.ThrowIfCancellationRequested();

        //Get user from Database and Set User LockoutEnd Date
        User user = FromDatabase(user.Id);

        return Task.FromResult(user.LockoutEnd);

    }

    public Task SetLockoutEndDateAsync(User user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        user.LockoutEnd = lockoutEnd;

        return Task.FromResult(0);
    }

    public Task<int> IncrementAccessFailedCountAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        user.AccessFailedCount += 1;

        return Task.FromResult(user.AccessFailedCount);
    }

    public Task ResetAccessFailedCountAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        user.AccessFailedCount = 0;

        return Task.FromResult(0);
    }

    public Task<int> GetAccessFailedCountAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        //Get user from database and assign accessFailedCount
          User user = FromDatabase(user.Id);

        return Task.FromResult(user.accessFailedCount);
    }

    public Task<bool> GetLockoutEnabledAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        //Get user from database and assign isLockOutEnabled
        User user = FromDatabase(user.Id);

        return Task.FromResult(user.isLockOutEnabled);
    }

    public Task SetLockoutEnabledAsync(User user, bool enabled, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        user.LockoutEnabled = enabled;

        return Task.FromResult(0);
    }

    #endregion

    public User FromDataBase(string Id)
    {
        //Code to retrieve User from Database
    }
}
</code>```

And in the StartUp File you have to write the following in the ConfigureService Section

```<code>public void ConfigureServices(IServiceCollection services)
    {

       //Other Configurations
        services.AddIdentity<User, Role>(
            options =>
            {

                options.Lockout.AllowedForNewUsers = true;
                options.Lockout.MaxFailedAccessAttempts = 3;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
            }
            ).AddDefaultTokenProviders();
    }
</code>```

Title: ASP.NET Core 2.2 Lockout not activating

Body:
I am using PasswordSignInAsync to verify my users like this:

var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);

However, I noticed that I am unable to get locked when I purposely enter the wrong password.

This is my startup.cs:

var lockoutOptions = new LockoutOptions()
{
    AllowedForNewUsers = true,
    DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5),
    MaxFailedAccessAttempts = 5
};

services.AddIdentity<User, Role>(
    options => {
        options.Lockout = lockoutOptions;
    }
)
.AddEntityFrameworkStores<AppDbContext>();

I checked in the database when I purposely enter the wrong password, the AccessFailedCount increases by 1 until it hits 5 then it goes to 0 again so that means its actually working. Its just the locking part is not working.

Body:
If you have Extended the built in IdentityUser and IdentityRole to your respective Custom User and Role, then you have to Implement IUserLockoutStore On your custom UserStore and write respective code for each implementation to update your AccessFailCount.

public class UserStore :  IUserStore<User>, IUserEmailStore<User>, IUserPasswordStore<User>, IUserRoleStore<User> IUserLockoutStore<User>
{

    #region Other Interface Implementation
    #endregion

    #region  IUserLockoutStore

    public Task<DateTimeOffset?> GetLockoutEndDateAsync(User user, CancellationToken cancellationToken)
    {

        cancellationToken.ThrowIfCancellationRequested();

        //Get user from Database and Set User LockoutEnd Date
        User user = FromDatabase(user.Id);

        return Task.FromResult(user.LockoutEnd);

    }

    public Task SetLockoutEndDateAsync(User user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        user.LockoutEnd = lockoutEnd;

        return Task.FromResult(0);
    }

    public Task<int> IncrementAccessFailedCountAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        user.AccessFailedCount += 1;

        return Task.FromResult(user.AccessFailedCount);
    }

    public Task ResetAccessFailedCountAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        user.AccessFailedCount = 0;

        return Task.FromResult(0);
    }

    public Task<int> GetAccessFailedCountAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        //Get user from database and assign accessFailedCount
          User user = FromDatabase(user.Id);

        return Task.FromResult(user.accessFailedCount);
    }

    public Task<bool> GetLockoutEnabledAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        //Get user from database and assign isLockOutEnabled
        User user = FromDatabase(user.Id);

        return Task.FromResult(user.isLockOutEnabled);
    }

    public Task SetLockoutEnabledAsync(User user, bool enabled, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        user.LockoutEnabled = enabled;

        return Task.FromResult(0);
    }

    #endregion

    public User FromDataBase(string Id)
    {
        //Code to retrieve User from Database
    }
}

And in the StartUp File you have to write the following in the ConfigureService Section

public void ConfigureServices(IServiceCollection services)
    {

       //Other Configurations
        services.AddIdentity<User, Role>(
            options =>
            {

                options.Lockout.AllowedForNewUsers = true;
                options.Lockout.MaxFailedAccessAttempts = 3;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
            }
            ).AddDefaultTokenProviders();
    }


问:
Switching from MVC to React. How do I write React correctly so that a table from the database is drawn on the page?
Prompt when worked through MVC that created Models then controllers and returned them to Razor for display. Everything worked. Now you need to write an application in .Net Core + React. I don't understand how to pass a value to it for display.

```<code>public class TableController : Controller
{

    List<TableInfo> tableInfo = new List<TableInfo>();
    public IActionResult Index()
    {
        using OracleConnection conn = DBUtils.GetDBConnection();
        using OracleCommand cmd = new OracleCommand($"select ID, IP from updater_srv", conn);

        conn.Open();

        using (OracleDataReader dateReader = cmd.ExecuteReader())
        {

            while (dateReader.Read())
            {
                tableInfo.Add(new TableInfo
                {
                    ID = Convert.ToString(dateReader.GetValue(0)),
                    IP = Convert.ToString(dateReader.GetValue(1)),
                });
            }
        }
        return View(tableInfo);
    }
    [HttpGet]
    public IEnumerable<TableInfo> Get()
    {
        return tableInfo;
    }
</code>```
```<code>import React, { Component } from 'react';

export class Table extends Component {
    static displayName = Table.name;

          constructor(props) {
                super(props);
          }

    componentDidMount() {
        axios.get('url').then(resopnse => {
            this.setState({ data: response })
        })
    }
    render() {
        return (
            <div>
                <table>
                    <thead>
                        <th>ID</th>
                        <th>IP</th>
                    </thead>
                    <tbody>
                        this.state.data.map(item => {
                      return (
                        <tr>
                            <td>{item.ID}</td>
                            <td>{item.IP}</td>
                        </tr>
                          );
                        }
                    </tbody>
                </table>
            </div>
        );
    }
}
</code>```

How do I write React correctly so that a table from the database is drawn on the page?

答:
You have to call your .net service from react and save data in redux store or state and then loop through each item

componentDidMount used to call api's

```<code>  constructor(props) {
        super(props);
    }

  componentDidMount(){
    axios.get('url').then(resopnse => {
      this.setState({ data: response})
    })
  }

  render() {
     return (
          <div>
           <table>
            <thead>
              <th>ID</th>
              <th>NAME</th>
            </thead>
            <tbody>
             this.state.data.map(item => {
              return (
                <tr>
                 <td>{item.id}</td>
                 <td>{item.name}</td>
                </tr>
              )
              })
           </tbody>
           </table>
          </div>

        );
    }
</code>```

Body:
Prompt when worked through MVC that created Models then controllers and returned them to Razor for display. Everything worked. Now you need to write an application in .Net Core + React. I don't understand how to pass a value to it for display.

public class TableController : Controller
{

    List<TableInfo> tableInfo = new List<TableInfo>();
    public IActionResult Index()
    {
        using OracleConnection conn = DBUtils.GetDBConnection();
        using OracleCommand cmd = new OracleCommand($"select ID, IP from updater_srv", conn);

        conn.Open();

        using (OracleDataReader dateReader = cmd.ExecuteReader())
        {

            while (dateReader.Read())
            {
                tableInfo.Add(new TableInfo
                {
                    ID = Convert.ToString(dateReader.GetValue(0)),
                    IP = Convert.ToString(dateReader.GetValue(1)),
                });
            }
        }
        return View(tableInfo);
    }
    [HttpGet]
    public IEnumerable<TableInfo> Get()
    {
        return tableInfo;
    }

import React, { Component } from 'react';

export class Table extends Component {
    static displayName = Table.name;

          constructor(props) {
                super(props);
          }

    componentDidMount() {
        axios.get('url').then(resopnse => {
            this.setState({ data: response })
        })
    }
    render() {
        return (

                        ID
                        IP

                        this.state.data.map(item => {
                      return (

                            {item.ID}
                            {item.IP}

                          );
                        }

        );
    }
}

How do I write React correctly so that a table from the database is drawn on the page?

Body:
You have to call your .net service from react and save data in redux store or state and then loop through each item

componentDidMount used to call api's

  constructor(props) {
        super(props);
    }

  componentDidMount(){
    axios.get('url').then(resopnse => {
      this.setState({ data: response})
    })
  }

  render() {
     return (
          <div>
           <table>
            <thead>
              <th>ID</th>
              <th>NAME</th>
            </thead>
            <tbody>
             this.state.data.map(item => {
              return (
                <tr>
                 <td>{item.id}</td>
                 <td>{item.name}</td>
                </tr>
              )
              })
           </tbody>
           </table>
          </div>

        );
    }


问:
What is the preferred way to load data from an API into BigQuery?
I am trying to get data from a REST API into BigQuery on the Google Cloud Platform (GCP). What is the best way to achieve that (without using any third party tools such as Funnel.io or Supermetrics)?

Most tutorials I could find suggest to write the data as CSV files to Cloud Storage and then use DataFlow to load the data into BigQuery. This however seems to be a bit cumbersome. There should be a way to do that without the intermediate step to write to CSV. Can this be achieved (within GCP) and if so, what is the best way?

PS: If the size of the data is relevant for the answer: I'm trying to load a total of about 10,000 rows of data (one-off) with about 100 new columns coming in every day - ideally updating every hour.

答:
Following up on the hint by @Kolban above, loading data from an API into BigQuery without using third party tools and without writing an intermediate file to Google Cloud Storage is possible, and indeed quite simple, by "streaming" data into BigQuery:

```<code>rows_to_insert = [(u"Phred Phlyntstone", 32), (u"Wylma Phlyntstone", 29)]

errors = client.insert_rows(table, rows_to_insert)  # Make an API request.
if errors == []:
    print("New rows have been added.")
</code>```

(From the BQ documentation)

In order to prepare the JSON data, it has to be turned into tuples. Here's an excerpt from my code to achieve this:

```<code># Turn JSON into tuples
data_tuples = []
for key,value in resp_json[product_id].items():
    data_tuples.append((
        value["product_id"],
        value["downloads"]
        )
    )

# Insert into BQ
errors = client.insert_rows(table, data_tuples)
if errors == []:
    print("New rows have been added.")
else:
    print(errors)
</code>```

Body:
Following up on the hint by @Kolban above, loading data from an API into BigQuery without using third party tools and without writing an intermediate file to Google Cloud Storage is possible, and indeed quite simple, by "streaming" data into BigQuery:

rows_to_insert = [(u"Phred Phlyntstone", 32), (u"Wylma Phlyntstone", 29)]

errors = client.insert_rows(table, rows_to_insert)  # Make an API request.
if errors == []:
    print("New rows have been added.")

(From the BQ documentation)

In order to prepare the JSON data, it has to be turned into tuples. Here's an excerpt from my code to achieve this:

# Turn JSON into tuples
data_tuples = []
for key,value in resp_json[product_id].items():
    data_tuples.append((
        value["product_id"],
        value["downloads"]
        )
    )

# Insert into BQ
errors = client.insert_rows(table, data_tuples)
if errors == []:
    print("New rows have been added.")
else:
    print(errors)


问:
stax xml validation
I know I can validate xml-file when I use sax. But can I validate when I use Stax?</p>

答:
There are two ways of XML validation possible with SAX and DOM:

validate alone - via Validator.validate()

validate during parsing - via DocumentBuilderFactory.setSchema() and SAXParserFactory.setSchema()

With StAX, validation is possible, but only the first way of doing it.

You can try something like this:

import javax.xml.validation.*;
import javax.xml.transform.stax.*;
import javax.xml.stream.*;
import javax.xml.*;
import java.io.*;

public class StaxValidation {

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

        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream("test.xml"));

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new File("test.xsd"));

        Validator validator = schema.newValidator();
        validator.validate(new StAXSource(reader));

        //no exception thrown, so valid
        System.out.println("Document is valid");

    }
}
```

ContentLicense: CC BY-SA 3.0

Title: stax xml validation


问:
POSTING XML USING GUZZLE CLIENT LARAVEL
I am a laravel junior developer and i have been using gazzle http for handling my requests, now i have a task of integrating Collections to a system. The provided API only wants me to post XML data. When i use Json, it works well, but now i have a task of posting xml through gazzle. how can i do it.

with Json,

```<code>$response = $client->request('POST', 'https://app.apiproviders.com/api/payment/donate', [
        'form_params'   => [
        'name'          => 'TIG Test',
        'amount'        => $amount,
        'number'        => str_replace('+', '',$this->senders_contact),
        'chanel'        => 'TIG',
        'referral'      => str_replace('+', '',$this->senders_contact)
        ]
        ]);

the desired XML format to post:

<?xml version="1.0" encoding="UTF-8"?>
<AutoCreate>
    <Request>
        <Method>acdepositfunds</Method>
        <NonBlocking></NonBlocking>
        <Amount>500</Amount>
        <Account>256702913454</Account>
        <AccountProviderCode></AccountProviderCode>
        <Narrative>Testing the API</Narrative>
        <NarrativeFileName>receipt.doc</NarrativeFileName>
        <NarrativeFileBase64>aSBhbSBwYXlpbmcgNjAwMDAgc2hpbGxpbmdz</NarrativeFileBase64>
    </Request>
</AutoCreate>

how can i pass this xml to gazzle in laravel??
</code>```

答:
I had a same problem a while ago, and I found a good solution using AttayToXml package. All you need to do is to create an array of your data:

```<code>$array = [
    'Request' => [
        'Method' => 'value',
        'NonBlocking' => 'value',
        'Amount' => 'value',
        //and so on...
    ]
];
</code>```

Then, you convert this array to xml, using the convert() method, where you pass the name of the root element of your xml:

```<code>$xml = ArrayToXml::convert($array, 'AutoCreate');
</code>```

And this will create your desired xml:

```<code><AutoCreate>
    <Request>
        <Method>acdepositfunds</Method>
        <NonBlocking></NonBlocking>
        <Amount>500</Amount>
        //and so on...
    </Request>
</AutoCreate>
</code>```

And then, send it through Guzzle client with something like this, which I used in on of my projects:

```<code>$request = $httpClient->post($yourUrl, [
                    'body' => $xml,
                    'http_errors' => true,
                    'verify' => false,
                    'defaults' => ['verify' => false]
                ]);
</code>```

Title: POSTING XML USING GUZZLE CLIENT LARAVEL

Body:
I am a laravel junior developer and i have been using gazzle http for handling my requests, now i have a task of integrating Collections to a system. The provided API only wants me to post XML data. When i use Json, it works well, but now i have a task of posting xml through gazzle. how can i do it.

with Json,

$response = $client->request('POST', 'https://app.apiproviders.com/api/payment/donate', [
        'form_params'   => [
        'name'          => 'TIG Test',
        'amount'        => $amount,
        'number'        => str_replace('+', '',$this->senders_contact),
        'chanel'        => 'TIG',
        'referral'      => str_replace('+', '',$this->senders_contact)
        ]
        ]);

the desired XML format to post:

<?xml version="1.0" encoding="UTF-8"?>
<AutoCreate>
    <Request>
        <Method>acdepositfunds</Method>
        <NonBlocking></NonBlocking>
        <Amount>500</Amount>
        <Account>256702913454</Account>
        <AccountProviderCode></AccountProviderCode>
        <Narrative>Testing the API</Narrative>
        <NarrativeFileName>receipt.doc</NarrativeFileName>
        <NarrativeFileBase64>aSBhbSBwYXlpbmcgNjAwMDAgc2hpbGxpbmdz</NarrativeFileBase64>
    </Request>
</AutoCreate>

how can i pass this xml to gazzle in laravel??

Body:
I had a same problem a while ago, and I found a good solution using AttayToXml package. All you need to do is to create an array of your data:

$array = [
    'Request' => [
        'Method' => 'value',
        'NonBlocking' => 'value',
        'Amount' => 'value',
        //and so on...
    ]
];

Then, you convert this array to xml, using the convert() method, where you pass the name of the root element of your xml:

$xml = ArrayToXml::convert($array, 'AutoCreate');

And this will create your desired xml:

<AutoCreate>
    <Request>
        <Method>acdepositfunds</Method>
        <NonBlocking></NonBlocking>
        <Amount>500</Amount>
        //and so on...
    </Request>
</AutoCreate>

And then, send it through Guzzle client with something like this, which I used in on of my projects:

$request = $httpClient->post($yourUrl, [
                    'body' => $xml,
                    'http_errors' => true,
                    'verify' => false,
                    'defaults' => ['verify' => false]
                ]);


问:
Helm - Spark operator examples/spark-pi.yaml does not exist
I've deployed Spark Operator to GKE using the Helm Chart to a custom namespace:

```<code>helm install --name sparkoperator incubator/sparkoperator --namespace custom-ns --set sparkJobNamespace=custom-ns
</code>```

and confirmed the operator running in the cluster with helm status sparkoperator.

However when I'm trying to run the Spark Pi example kubectl apply -f examples/spark-pi.yaml I'm getting the following error:

```<code>the path "examples/spark-pi.yaml" does not exist
</code>```

There are few things that I probably still don't get:

Where is actually examples/spark-pi.yaml located after deploying the operator?

What else should I check and what other steps should I take to make the example work?

答:
Please find the spark-pi.yaml file here.

You should copy it to your filesystem, customize it if needed, and provide a valid path to it with kubectl apply -f path/to/spark-pi.yaml.

Body:
I've deployed Spark Operator to GKE using the Helm Chart to a custom namespace:

helm install --name sparkoperator incubator/sparkoperator --namespace custom-ns --set sparkJobNamespace=custom-ns

and confirmed the operator running in the cluster with helm status sparkoperator.

However when I'm trying to run the Spark Pi example kubectl apply -f examples/spark-pi.yaml I'm getting the following error:

the path "examples/spark-pi.yaml" does not exist

There are few things that I probably still don't get:

Where is actually examples/spark-pi.yaml located after deploying the operator?

What else should I check and what other steps should I take to make the example work?


问:
Spring beans are not initializing in Spring REST
My Spring beans are not getting initialized in Spring Java Config which I am using to create a sample Spring REST Application(As No Web.xml is required I have deleted it) . And also getting 404 while calling the REST endpoint /dest/types.

Can anyone please help. Project Structure

Pom.xml :

<project xmlns="http://maven.apache.org/POM/4.0.0"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-
    instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.travel</groupId>
    <artifactId>patcyyRestApp</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>patcyyRestApp Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <springframework.version>5.0.9.RELEASE</springframework.version>
        <jackson.library>2.9.6</jackson.library>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <hibernate.core.version>5.3.6.Final</hibernate.core.version>
        <javax.servlet.api.version>3.1.0</javax.servlet.api.version>
        <lombok.version>1.18.12</lombok.version>
        <apache.commons.version>3.9</apache.commons.version>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servlet.api.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.library}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.core.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${apache.commons.version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>patcyyRestApp</finalName>
    </build>
</project>
```

<p>Dispatch Initializer : </p>

<pre class="lang-java prettyprint-override"><code>package com.patcyy.rest.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class PatcyyDispatcherServletInitializer  extends
    AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        System.out.println("Inside getServletConfigClasses");
        return new Class[] { PatcyyConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        System.out.println("Inside mapping");

        return new String[] { "/patcyy" };
    }

}
</code>```

Config :

package com.patcyy.rest.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan("com.patcyy.rest")
public class PatcyyConfig {

}
```

<p>Controller : </p>

<pre class="lang-java prettyprint-override"><code>package com.patcyy.rest.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.patcyy.rest.response.DestinationTypes;
import com.patcyy.rest.service.IDestinationService;

@RestController
@RequestMapping(path = "/dest", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces =
     MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DestinationController extends BaseController {

    private final IDestinationService iDestinationService;

    /**
     * @param iDestinationService
     */
    public DestinationController(@Autowired IDestinationService iDestinationService) {
        super();
        this.iDestinationService = iDestinationService;
    }

    @GetMapping("/types")
    public ResponseEntity<List<DestinationTypes>> getDestinationTypes() {
        List<DestinationTypes> destTypes = iDestinationService.getDestinationTypes();
        return new ResponseEntity<List<DestinationTypes>>(destTypes, HttpStatus.OK);
    }

}
</code>```

答:
i think the problem is in ComponentScan().
@ComponentScan annotation along with @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.
in your case you need to add basepackages="com.patcyy.rest"</p>

Body:
My Spring beans are not getting initialized in Spring Java Config which I am using to create a sample Spring REST Application(As No Web.xml is required I have deleted it) . And also getting 404 while calling the REST endpoint /dest/types.

Can anyone please help. Project Structure

Pom.xml :

<project xmlns="http://maven.apache.org/POM/4.0.0"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-
    instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.travel</groupId>
    <artifactId>patcyyRestApp</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>patcyyRestApp Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <springframework.version>5.0.9.RELEASE</springframework.version>
        <jackson.library>2.9.6</jackson.library>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <hibernate.core.version>5.3.6.Final</hibernate.core.version>
        <javax.servlet.api.version>3.1.0</javax.servlet.api.version>
        <lombok.version>1.18.12</lombok.version>
        <apache.commons.version>3.9</apache.commons.version>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servlet.api.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.library}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.core.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${apache.commons.version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>patcyyRestApp</finalName>
    </build>
</project>

Dispatch Initializer :

package com.patcyy.rest.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class PatcyyDispatcherServletInitializer  extends
    AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        System.out.println("Inside getServletConfigClasses");
        return new Class[] { PatcyyConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        System.out.println("Inside mapping");

        return new String[] { "/patcyy" };
    }

}

Config :

package com.patcyy.rest.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan("com.patcyy.rest")
public class PatcyyConfig {

}

Controller :

package com.patcyy.rest.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.patcyy.rest.response.DestinationTypes;
import com.patcyy.rest.service.IDestinationService;

@RestController
@RequestMapping(path = "/dest", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces =
     MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DestinationController extends BaseController {

    private final IDestinationService iDestinationService;

    /**
     * @param iDestinationService
     */
    public DestinationController(@Autowired IDestinationService iDestinationService) {
        super();
        this.iDestinationService = iDestinationService;
    }

    @GetMapping("/types")
    public ResponseEntity<List<DestinationTypes>> getDestinationTypes() {
        List<DestinationTypes> destTypes = iDestinationService.getDestinationTypes();
        return new ResponseEntity<List<DestinationTypes>>(destTypes, HttpStatus.OK);
    }

}


问:
Unable to Access Local Host From Docker Container

Problem

I have two Docker containers:

a server ran with fastapi;uvicorn

a client sending a GET request to http://0.0.0.0

The server seems to work just fine as bashing curl -X GET http://0.0.0.0 works as expected. However, my docker client seems unable to get access.

After building the client container (files below), when running docker run -it --name app_client_container app_client:latest I receive the following error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: Errno 111 Connection refused'))

Setup

My project looks like this

|- client.Dockerfile
|- client.py
|- client_req.txt
|- server.Dockerfile
|- server.py
|- server_req.txt
```

<p><strong>Client</strong></p>

<pre class="lang-py prettyprint-override"><code># client.Dockerfile
FROM python:3.8

WORKDIR /srv
WORKDIR /srv
ADD client_req.txt /srv/client_req.txt
RUN pip install -r client_req.txt

ADD . /srv
CMD python /srv/client.py

# client.py
import json
import requests
import traceback

try:
    response = requests.get('http://0.0.0.0', timeout=5)
    print(json.dumps(response.json(), indent=4))
except Exception as e:
    print('Connection could not be established :(')
    print('Here is more information:')
    traceback.print_exc()

# client_req.txt
requests
</code>```

Server

# server.Dockerfile
FROM python:3.8

WORKDIR /srv
ADD server_req.txt /srv/server_req.txt
RUN pip install -r server_req.txt

EXPOSE 80

ADD . /srv
CMD uvicorn server:app --host 0.0.0.0 --port 80 --reload

# server.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

# server_req.txt
fastapi
uvicorn
```

答:
You can also use default docker bridge network.

Set the IP address to: 172.17.0.1 (for mac it is docker.for.mac.host.internal)

This should work:

```<code>response = requests.get('http://172.17.0.1', timeout=5)
</code>```

Body:
Problem

I have two Docker containers:

a server ran with fastapi;uvicorn

a client sending a GET request to http://0.0.0.0

The server seems to work just fine as bashing curl -X GET http://0.0.0.0 works as expected. However, my docker client seems unable to get access.

After building the client container (files below), when running docker run -it --name app_client_container app_client:latest I receive the following error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: Errno 111 Connection refused'))

Setup

My project looks like this

|- client.Dockerfile
|- client.py
|- client_req.txt
|- server.Dockerfile
|- server.py
|- server_req.txt

Client

# client.Dockerfile
FROM python:3.8

WORKDIR /srv
WORKDIR /srv
ADD client_req.txt /srv/client_req.txt
RUN pip install -r client_req.txt

ADD . /srv
CMD python /srv/client.py

# client.py
import json
import requests
import traceback

try:
    response = requests.get('http://0.0.0.0', timeout=5)
    print(json.dumps(response.json(), indent=4))
except Exception as e:
    print('Connection could not be established :(')
    print('Here is more information:')
    traceback.print_exc()

# client_req.txt
requests

Server

# server.Dockerfile
FROM python:3.8

WORKDIR /srv
ADD server_req.txt /srv/server_req.txt
RUN pip install -r server_req.txt

EXPOSE 80

ADD . /srv
CMD uvicorn server:app --host 0.0.0.0 --port 80 --reload

# server.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

# server_req.txt
fastapi
uvicorn

Body:
You can also use default docker bridge network.

Set the IP address to: 172.17.0.1 (for mac it is docker.for.mac.host.internal)

This should work:

response = requests.get('http://172.17.0.1', timeout=5)


问:
How to direct the output of a process to stdout and pipe to another process in bash?
How to direct the output of a process to stdout and pipe to another process in bash?

I am using bash shell in mac

I have two python programs generate.py and sum.py

generate.py prints integers to stdout.

when run using python3 generate.py it generates

```<code>1
2
3
4
...
...
</code>```

sum.py just consumes the output of generate.py and keeps the counter and once the generate.py is done sum.py outputs the final value.

however when I run using the following bash command

python3 generate.py >&2 | python3 sum.py I cannot see the output of python3 sum.py

but if I do this python3 generate.py | python3 sum.py I can see the result from sum.py is printed to stdout but I dont see the output from generate.py in stdout.

so what I am looking is to see the output of both generate.py and sum.py while piping the data between them. any idea?

答:
Use the tee command to split your output between the tty and a program stdin

```<code>echo "hello" | tee /dev/tty | pbcopy
</code>```

In your case it would be

```<code>python3 generate.py | tee /dev/tty | python3 sum.py
</code>```

Body:
How to direct the output of a process to stdout and pipe to another process in bash?

I am using bash shell in mac

I have two python programs generate.py and sum.py

generate.py prints integers to stdout.

when run using python3 generate.py it generates

1
2
3
4
...
...

sum.py just consumes the output of generate.py and keeps the counter and once the generate.py is done sum.py outputs the final value.

however when I run using the following bash command

python3 generate.py >&2 | python3 sum.py I cannot see the output of python3 sum.py

but if I do this python3 generate.py | python3 sum.py I can see the result from sum.py is printed to stdout but I dont see the output from generate.py in stdout.

so what I am looking is to see the output of both generate.py and sum.py while piping the data between them. any idea?

Body:
Use the tee command to split your output between the tty and a program stdin

echo "hello" | tee /dev/tty | pbcopy

In your case it would be

python3 generate.py | tee /dev/tty | python3 sum.py


问:
What is a cluster and a node oriented to containers?
Sorry for this question, but I just started with Docker and Docker Compose and I really didn't need any of this until I read that I need to use Docker Swarn or Kuebernetes to have more stability in production. I started reading about Docker Swarn and they mentioned nodes and clusters.

I was really happy not knowing about this as I understood docker-compose:

Is that I could manage my services/containers from a single file
  and only have to run several commands to launch, build, delete, etc.
  all my services based on the docker-compose configuration.

But now the nodes and cluster have come out and I've really gone a bit crazy, and that's why if you can help me understand this next step in the life of containers. I've been googling and it's not very clear to me.

I hope you can help me and explain it to me in a way that I can understand.

Thank you!

答:
By default Docker Compose runs a set of containers on a single system.  If you need to run more containers than fit on one system, or you're just afraid of that system crashing, you need more than one system to do it.  The cluster is the group of all of the systems (physical computers, virtual machines, cloud instances) that are working together to run the containers.  Each of those individual systems is a node.

The other important part of the cluster container setups is that you can generally run multiple replicas of a give container, and you don't care where in the cluster they run.  Say you have five nodes, and a Web server container, and you'd like to run three copies of it for redundancy.  Instead of having to pick a node, ssh to it, and manually docker run there, you just tell the cluster manager "run me three of these", and it chooses a node and launches the container for you.  You can also scale the containers up and down at runtime, or potentially set the cluster to do the scaling on its own based on load.

If your workload is okay running a single copy of containers on a single server, you don't need a cluster setup.  (You might have some downtime during updates or if the single server dies.)  Swarm has the advantages of being bundled with Docker and being able to use Docker-native tools (docker-compose can deploy to a Swarm cluster).  Kubernetes is much more complex, but at this point most public cloud providers will sell you a preconfigured Kubernetes cluster, and it has better stories around security, storage management, and autoscaling.  There are also a couple other less-prominent alternatives like Nomad and Mesos out there.


问:
How can I divide one database to multi databases?
I want to decompose my application to adopt microservices architecture, and i will need to come up with a solid strategy to split my database (Mysql) into multiple small databases (mysql) aligned with my applications.</p>

答:
TL;DR: Depends on the scenario and from what each service will do

Although there is no clear answer to this, since it really depends on your needs and on what each service should do, you can come up with a general starting point (assuming you don't need to keep the existing database type).

Let's assume you have a monolithic application for an e-commerce, and you want to split this application into smaller services, each one with it's own database.
The approach you could use is to create some services that handles some parts of the website: for example you could have one service that handles users authentication,one for the orders, one for the products, one for the invoices and so on...

Now, each service will have it's own database, and here's come another question: which database a specific service should have? Because one of the advantages of this kind of architecture is that each service can have it's own kind of database, so for example the products service can have a non relational database, such as MongoDB, since all it does is getting details about products, so you don't have to manage any relation.

The orders service, on the other hand, could have a relational database, since you want to keep a relation between the order and the invoice for that order. But wait, invoices are handled by the invoice service, so how can you keep the relation between these two without sharing the database? Well, that's one of the "issues" of this approach: you have to keep services independent while also let them communicate each other. How can we do this? There is no clear answer here too... One approach could be to just pass all invoices details to the orders service as well, or you can just pass the invoice ID when saving the order and later retrieve the invoice via an API call to the invoice service, or you can pass all the relevant details you need for the invoice to an API endpoint in the order service that stores these data to a specific table in the database (since most of the times you don't need the entire actual object), etc... The possibilities are endless...


问:
How to convert from a list of string to a list of int in array in python
```<code>a= pd.DataFrame({"A": [['1','2'], '2','3']}).to_numpy()
</code>```

I want to get a = {"A": [[1, 2], 2, 3]}
I cannot use astype for the list in array

答:
Do you just want to convert from a = [['1', '2'], '2', '3'] to a = [[1, 2], 2, 3], or is the pandas bit important?

If it's from your pandas start point, the following works.

```<code>import pandas as pd

# Starting point
a = pd.DataFrame({"A": [['1','2'], '2','3']})

# Iterate over rows in dataframe
for index, row in a.iterrows():
    # If row contains a list
    if isinstance(row[0], list):
        # Convert each entry in list from string to int
        a.loc[index, 'A'] = [int(val) for val in row[0]]
    else:
        a.loc[index, 'A'] = int(row)

a = a.to_dict(orient='list')
print(a)
# {'A': [[1, 2], 2, 3]}
</code>```

If you just wanted from a = [['1', '2'], '2', '3'] to a = [[1, 2], 2, 3]:

```<code>a = [['1', '2'], '2', '3']
a = [list(map(int, x)) if isinstance(x, list) else int(x) for x in a]
print(a)
# [[1, 2], 2, 3]
</code>```

Body:
a= pd.DataFrame({"A": [['1','2'], '2','3']}).to_numpy()

I want to get a = {"A": [[1, 2], 2, 3]}
I cannot use astype for the list in array

Body:
Do you just want to convert from a = [['1', '2'], '2', '3'] to a = [[1, 2], 2, 3], or is the pandas bit important?

If it's from your pandas start point, the following works.

import pandas as pd

# Starting point
a = pd.DataFrame({"A": [['1','2'], '2','3']})

# Iterate over rows in dataframe
for index, row in a.iterrows():
    # If row contains a list
    if isinstance(row[0], list):
        # Convert each entry in list from string to int
        a.loc[index, 'A'] = [int(val) for val in row[0]]
    else:
        a.loc[index, 'A'] = int(row)

a = a.to_dict(orient='list')
print(a)
# {'A': [[1, 2], 2, 3]}

If you just wanted from a = [['1', '2'], '2', '3'] to a = [[1, 2], 2, 3]:

a = [['1', '2'], '2', '3']
a = [list(map(int, x)) if isinstance(x, list) else int(x) for x in a]
print(a)
# [[1, 2], 2, 3]


问:
No body data found in Laravel 5.3 with PUT request
Here is my route to update the contacts.

```<code>Route::put( 'contact-type/{id}', 'ContactTypeController@update' );
</code>```

Here is the controller to test if the request was there with the PUT request.

```<code>public function update(Request $request, $id)
{
    return response()->json([ 'id' => $id, 'req' => $request->all() ]);
}
</code>```

When i send a request using postman, the request is null!

Is the body payload is not allowed in laravel PUT requests? Or how we send additional data in a PUT request?

答:
If you had to use form-data (to upload images) as file input doesn't exists in x-www-form-urlencode

you can send a POST-Request and add a field with the name  _method and the value PUT or PATCH to the request body.

Body:
Here is my route to update the contacts.

Route::put( 'contact-type/{id}', 'ContactTypeController@update' );

Here is the controller to test if the request was there with the PUT request.

public function update(Request $request, $id)
{
    return response()->json([ 'id' => $id, 'req' => $request->all() ]);
}

When i send a request using postman, the request is null!

Is the body payload is not allowed in laravel PUT requests? Or how we send additional data in a PUT request?


问:
Android SMS Broadcast Receiver doesn't work
Hi I'm trying to catch the sms content and use in my app, so I made a BroadcastReceiver with Permission and Manifests But when the device receive sms, my code doesn't run which means that the BroadcastReceiver doesn't fire.
I also checked many Articles inside and outside here, there're some:

Android Sms Receiver Result to Main Activity
SMS receiver didn't work

Android SMS Receiver not working

Broadcast Receiver not working for SMS

Here is a part of my Manifest:

```<code><uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application.
...
...
<receiver android:name="com.example.android.receiver.SmsReceiver"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="2147483647">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
</application>
</code>```

And This is my Receiver

```<code>public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "SMS Received!", Toast.LENGTH_LONG).show();
    }
}
</code>```

I also tried to register the receiver dynamically inside activity onCreate() but nothing changed

```<code>IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
intentFilter.setPriority(2147483647);
registerReceiver(new SmsReceiver(), intentFilter);
</code>```

Does anyone know where is the problem? It should just Toast that a message is recieved so I can continue work but the receiver doesn't seem to even fire

答:
First make another app your default SMS app.

Then: Google Hangout --> Settings(Disable merged conversations) --> SMS (Disable SMS)

Or,

This example for mainfest:

```<code>         <receiver android:name=".SmsBroadcastReceiver"
            android:exported="true"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="999" >

                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                <action android:name="android.provider.Telephony.SMS_DELIVER" />
                <action android:name="android.provider.Telephony.SMS_DELIVER_ACTION" />
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
</code>```

Body:
Hi I'm trying to catch the sms content and use in my app, so I made a BroadcastReceiver with Permission and Manifests But when the device receive sms, my code doesn't run which means that the BroadcastReceiver doesn't fire.
I also checked many Articles inside and outside here, there're some:

Android Sms Receiver Result to Main Activity
SMS receiver didn't work

Android SMS Receiver not working

Broadcast Receiver not working for SMS

Here is a part of my Manifest:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application.
...
...
<receiver android:name="com.example.android.receiver.SmsReceiver"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="2147483647">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
</application>

And This is my Receiver

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "SMS Received!", Toast.LENGTH_LONG).show();
    }
}

I also tried to register the receiver dynamically inside activity onCreate() but nothing changed

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
intentFilter.setPriority(2147483647);
registerReceiver(new SmsReceiver(), intentFilter);

Does anyone know where is the problem? It should just Toast that a message is recieved so I can continue work but the receiver doesn't seem to even fire

Body:
First make another app your default SMS app.

Then: Google Hangout --> Settings(Disable merged conversations) --> SMS (Disable SMS)

Or,

This example for mainfest:

         <receiver android:name=".SmsBroadcastReceiver"
            android:exported="true"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="999" >

                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                <action android:name="android.provider.Telephony.SMS_DELIVER" />
                <action android:name="android.provider.Telephony.SMS_DELIVER_ACTION" />
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>


问:
Convert strings from horizontal to vertical
I'd like to know the process of turning the following strings:

```<code>Hi
Hello
Goodbye
</code>```

To look something like this:

```<code>    e
    y
  o b
  l d
  l o
i e o
H H G
</code>```

So that the horizontal string is converted to vertical, however starts at a floor, rather than a ceiling.

If anyone could provide some advice to help me get to the right functions or commands then I would appreciate it. I would also like to know how to do this for a list of strings of length x, where x is any number greater than zero. I have experimented with a for x in list(): function, however cannot seem to produce the above output.

Thanks in advance!

答:
Interesting challenge to wake up the brain. Try this code:</p>

```<code>def vertical_print_generator(data, max_length):
    i = max_length
    while i > 0:
        i -= 1
        yield [s[i] for s in data]

if __name__ == '__main__':
    in_data = ('Hi', 'Hello', 'Goodbye')
    max_length = max(map(len, in_data))
    out_data = ['{:{max_length}}'.format(s, max_length=max_length) for s in in_data]
    for row in vertical_print_generator(out_data, max_length):
        print(' '.join(row))
</code>```

Body:
I'd like to know the process of turning the following strings:

Hi
Hello
Goodbye

To look something like this:

    e
    y
  o b
  l d
  l o
i e o
H H G

So that the horizontal string is converted to vertical, however starts at a floor, rather than a ceiling.

If anyone could provide some advice to help me get to the right functions or commands then I would appreciate it. I would also like to know how to do this for a list of strings of length x, where x is any number greater than zero. I have experimented with a for x in list(): function, however cannot seem to produce the above output.

Thanks in advance!

Body:
Interesting challenge to wake up the brain. Try this code:

def vertical_print_generator(data, max_length):
    i = max_length
    while i > 0:
        i -= 1
        yield [s[i] for s in data]

if __name__ == '__main__':
    in_data = ('Hi', 'Hello', 'Goodbye')
    max_length = max(map(len, in_data))
    out_data = ['{:{max_length}}'.format(s, max_length=max_length) for s in in_data]
    for row in vertical_print_generator(out_data, max_length):
        print(' '.join(row))


问:
How to import my python file in another file in visual studio code
I am using python/selenium in visual studio code. I am trying to import my another python class driverScript which resides in executionEngine module and in the file DriverScript. I have imported as below:

```<code>import driverScript from executionEngine.DriverScript
</code>```

It is producing error:

```<code>Traceback (most recent call last):
  File "c:/Selenium/Selenium-Python Framework/RK_Practice/Tests/mainTest.py", line 5, in <module>
  from executionEngine.DriverScript import driverScript
ModuleNotFoundError: No module named 'executionEngine'
</code>```

How can I import correctly? Your help is very much appreciated.

答:
If the script you are wishing to import is not in the current directory, you may want to take this approach:</p>

```<code>import sys

sys.path.insert(1, '/path/to/script/folder')

import driverScript from executionEngine.DriverScript
</code>```

Body:
I am using python/selenium in visual studio code. I am trying to import my another python class driverScript which resides in executionEngine module and in the file DriverScript. I have imported as below:

import driverScript from executionEngine.DriverScript

It is producing error:

Traceback (most recent call last):
  File "c:/Selenium/Selenium-Python Framework/RK_Practice/Tests/mainTest.py", line 5, in <module>
  from executionEngine.DriverScript import driverScript
ModuleNotFoundError: No module named 'executionEngine'

How can I import correctly? Your help is very much appreciated.

Body:
If the script you are wishing to import is not in the current directory, you may want to take this approach:

import sys

sys.path.insert(1, '/path/to/script/folder')

import driverScript from executionEngine.DriverScript


问:
Kubernetes without pod metrics
I´m trying to deploy metrics to kubernetes and something really strange is happening, I have one worker and one master. I have the following pods list:

```<code>NAMESPACE     NAME                                              READY   STATUS    RESTARTS   AGE     IP               NODE                      NOMINATED NODE   READINESS GATES
default       php-apache-774ff9d754-d7vp9                       1/1     Running   0          2m43s   192.168.77.172   master-node               <none>           <none>
kube-system   calico-kube-controllers-6b9d4c8765-x7pql          1/1     Running   2          4h11m   192.168.77.130   master-node               <none>           <none>
kube-system   calico-node-d4rnh                                 0/1     Running   1          4h11m   10.221.194.166   master-node               <none>           <none>
kube-system   calico-node-hwkmd                                 0/1     Running   1          4h11m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   coredns-6955765f44-kf4dr                          1/1     Running   1          4h20m   192.168.178.65   free5gc-virtual-machine   <none>           <none>
kube-system   coredns-6955765f44-s58rf                          1/1     Running   1          4h20m   192.168.178.66   free5gc-virtual-machine   <none>           <none>
kube-system   etcd-free5gc-virtual-machine                      1/1     Running   1          4h21m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   kube-apiserver-free5gc-virtual-machine            1/1     Running   1          4h21m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   kube-controller-manager-free5gc-virtual-machine   1/1     Running   1          4h21m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   kube-proxy-brvdg                                  1/1     Running   1          4h19m   10.221.194.166   master-node               <none>           <none>
kube-system   kube-proxy-lfzjw                                  1/1     Running   1          4h20m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   kube-scheduler-free5gc-virtual-machine            1/1     Running   1          4h21m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   metrics-server-86c6d8b9bf-p2hh8                   1/1     Running   0          2m43s   192.168.77.171   master-node               <none>           <none>
</code>```

When I try to get the metrics I see the following:

```<code>NAME         REFERENCE               TARGETS         MINPODS   MAXPODS   REPLICAS   AGE
php-apache   Deployment/php-apache   <unknown>/50%   1         10        1          3m58s
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl top nodes
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io)
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl top pods --all-namespaces
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get pods.metrics.k8s.io)
</code>```

Lastly, I see the log (v=6) the output of metrics-server:

```<code>free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl logs metrics-server-86c6d8b9bf-p2hh8  -n kube-system
I0206 18:16:18.657605       1 serving.go:273] Generated self-signed cert (/tmp/apiserver.crt, /tmp/apiserver.key)
I0206 18:16:19.367356       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 7 milliseconds
I0206 18:16:19.370573       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
I0206 18:16:19.373245       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
I0206 18:16:19.375024       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
[restful] 2020/02/06 18:16:19 log.go:33: [restful/swagger] listing is available at https://:4443/swaggerapi
[restful] 2020/02/06 18:16:19 log.go:33: [restful/swagger] https://:4443/swaggerui/ is mapped to folder /swagger-ui/
I0206 18:16:19.421207       1 healthz.go:83] Installing healthz checkers:"ping", "poststarthook/generic-apiserver-start-informers", "healthz"
I0206 18:16:19.421641       1 serve.go:96] Serving securely on [::]:4443
I0206 18:16:19.421873       1 reflector.go:202] Starting reflector *v1.Pod (0s) from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421891       1 reflector.go:240] Listing and watching *v1.Pod from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421914       1 reflector.go:202] Starting reflector *v1.Node (0s) from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421929       1 reflector.go:240] Listing and watching *v1.Node from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.423052       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/nodes?limit=500&resourceVersion=0 200 OK in 1 milliseconds
I0206 18:16:19.424261       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/pods?limit=500&resourceVersion=0 200 OK in 2 milliseconds
I0206 18:16:19.425586       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/nodes?resourceVersion=38924&timeoutSeconds=481&watch=true 200 OK in 0 milliseconds
I0206 18:16:19.433545       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/pods?resourceVersion=39246&timeoutSeconds=582&watch=true 200 OK in 0 milliseconds
I0206 18:16:49.388514       1 manager.go:99] Beginning cycle, collecting metrics...
I0206 18:16:49.388598       1 manager.go:95] Scraping metrics from 2 sources
I0206 18:16:49.395742       1 manager.go:120] Querying source: kubelet_summary:free5gc-virtual-machine
I0206 18:16:49.400574       1 manager.go:120] Querying source: kubelet_summary:master-node
I0206 18:16:49.413751       1 round_trippers.go:405] GET https://10.221.194.166:10250/stats/summary/ 200 OK in 13 milliseconds
I0206 18:16:49.414317       1 round_trippers.go:405] GET https://10.221.195.58:10250/stats/summary/ 200 OK in 18 milliseconds
I0206 18:16:49.417044       1 manager.go:150] ScrapeMetrics: time: 28.428677ms, nodes: 2, pods: 13
I0206 18:16:49.417062       1 manager.go:115] ...Storing metrics...
I0206 18:16:49.417083       1 manager.go:126] ...Cycle complete
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl logs metrics-server-86c6d8b9bf-p2hh8  -n kube-system
I0206 18:16:18.657605       1 serving.go:273] Generated self-signed cert (/tmp/apiserver.crt, /tmp/apiserver.key)
I0206 18:16:19.367356       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 7 milliseconds
I0206 18:16:19.370573       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
I0206 18:16:19.373245       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
I0206 18:16:19.375024       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
[restful] 2020/02/06 18:16:19 log.go:33: [restful/swagger] listing is available at https://:4443/swaggerapi
[restful] 2020/02/06 18:16:19 log.go:33: [restful/swagger] https://:4443/swaggerui/ is mapped to folder /swagger-ui/
I0206 18:16:19.421207       1 healthz.go:83] Installing healthz checkers:"ping", "poststarthook/generic-apiserver-start-informers", "healthz"
I0206 18:16:19.421641       1 serve.go:96] Serving securely on [::]:4443
I0206 18:16:19.421873       1 reflector.go:202] Starting reflector *v1.Pod (0s) from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421891       1 reflector.go:240] Listing and watching *v1.Pod from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421914       1 reflector.go:202] Starting reflector *v1.Node (0s) from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421929       1 reflector.go:240] Listing and watching *v1.Node from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.423052       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/nodes?limit=500&resourceVersion=0 200 OK in 1 milliseconds
I0206 18:16:19.424261       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/pods?limit=500&resourceVersion=0 200 OK in 2 milliseconds
I0206 18:16:19.425586       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/nodes?resourceVersion=38924&timeoutSeconds=481&watch=true 200 OK in 0 milliseconds
I0206 18:16:19.433545       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/pods?resourceVersion=39246&timeoutSeconds=582&watch=true 200 OK in 0 milliseconds
I0206 18:16:49.388514       1 manager.go:99] Beginning cycle, collecting metrics...
I0206 18:16:49.388598       1 manager.go:95] Scraping metrics from 2 sources
I0206 18:16:49.395742       1 manager.go:120] Querying source: kubelet_summary:free5gc-virtual-machine
I0206 18:16:49.400574       1 manager.go:120] Querying source: kubelet_summary:master-node
I0206 18:16:49.413751       1 round_trippers.go:405] GET https://10.221.194.166:10250/stats/summary/ 200 OK in 13 milliseconds
I0206 18:16:49.414317       1 round_trippers.go:405] GET https://10.221.195.58:10250/stats/summary/ 200 OK in 18 milliseconds
I0206 18:16:49.417044       1 manager.go:150] ScrapeMetrics: time: 28.428677ms, nodes: 2, pods: 13
I0206 18:16:49.417062       1 manager.go:115] ...Storing metrics...
I0206 18:16:49.417083       1 manager.go:126] ...Cycle complete
</code>```

Using the log output with v=10 I can see even the details of health of each pod, but nothing while running the kubectl get hpa or kubectl top nodes. Can someone give me a hint? Furthermore, my metrics manifest is:

```<code>---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: metrics-server
  namespace: kube-system
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: metrics-server
  namespace: kube-system
  labels:
    k8s-app: metrics-server
spec:
  selector:
    matchLabels:
      k8s-app: metrics-server
  template:
    metadata:
      name: metrics-server
      labels:
        k8s-app: metrics-server
    spec:
      serviceAccountName: metrics-server
      volumes:
      # mount in tmp so we can safely use from-scratch images and/or read-only containers
      - name: tmp-dir
        emptyDir: {}
      containers:
      - name: metrics-server
        image: k8s.gcr.io/metrics-server-amd64:v0.3.1
        args:
          - /metrics-server
          - --metric-resolution=30s
          - --requestheader-allowed-names=aggregator
          - --cert-dir=/tmp
          - --secure-port=4443
          - --kubelet-insecure-tls
          - --v=6
          - --kubelet-preferred-address-types=InternalIP,Hostname,InternalDNS,ExternalDNS,ExternalIP
            #- --kubelet-preferred-address-types=InternalIP
        ports:
        - name: main-port
          containerPort: 4443
          protocol: TCP
        securityContext:
          readOnlyRootFilesystem: true
          runAsNonRoot: true
          runAsUser: 1000
        imagePullPolicy: Always
        volumeMounts:
        - name: tmp-dir
          mountPath: /tmp
      nodeSelector:
        beta.kubernetes.io/os: linux
        kubernetes.io/arch: "amd64"
</code>```

And I can see the following:

```<code>free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl get apiservice v1beta1.metrics.k8s.io -o yaml
apiVersion: apiregistration.k8s.io/v1
kind: APIService
metadata:
  creationTimestamp: "2020-02-06T18:57:28Z"
  name: v1beta1.metrics.k8s.io
  resourceVersion: "45583"
  selfLink: /apis/apiregistration.k8s.io/v1/apiservices/v1beta1.metrics.k8s.io
  uid: ca439221-b987-4c13-b0e0-8d2bb237e612
spec:
  group: metrics.k8s.io
  groupPriorityMinimum: 100
  insecureSkipTLSVerify: true
  service:
    name: metrics-server
    namespace: kube-system
    port: 443
  version: v1beta1
  versionPriority: 100
status:
  conditions:
  - lastTransitionTime: "2020-02-06T18:57:28Z"
    message: 'failing or missing response from https://10.110.144.114:443/apis/metrics.k8s.io/v1beta1:
      Get https://10.110.144.114:443/apis/metrics.k8s.io/v1beta1: dial tcp 10.110.144.114:443:
      connect: no route to host'
    reason: FailedDiscoveryCheck
    status: "False"
    type: Available
</code>```

答:
I have reproduced your issue (on Google Compute Engine). Tried a few scenarios to find workaround/solution for this issue.

First thing I want to mention is that you have provided ServiceAccount and Deployment YAML. You also need ClusterRoleBinding, RoleBinding, ApiService, etc. All needed YAMLs can be found in this Github repo.

For fast deploy metrics-server with all required config you can use:

```<code>$ git clone https://github.com/kubernetes-sigs/metrics-server.git
$ cd metrics-server/deploy/
$ kubectl apply -f kubernetes/
clusterrole.rbac.authorization.k8s.io/system:aggregated-metrics-reader created
clusterrolebinding.rbac.authorization.k8s.io/metrics-server:system:auth-delegator created
rolebinding.rbac.authorization.k8s.io/metrics-server-auth-reader created
apiservice.apiregistration.k8s.io/v1beta1.metrics.k8s.io created
serviceaccount/metrics-server created
deployment.apps/metrics-server created
service/metrics-server created
clusterrole.rbac.authorization.k8s.io/system:metrics-server created
clusterrolebinding.rbac.authorization.k8s.io/system:metrics-server created
</code>```

The second thing I would advise you to check your CNI pods (calico-node-d4rnh and calico-node-hawked). Created 4h11m but Ready 0/1.

Last thing regarding gathering CPU and Memory data from pods and nodes.

Using Calico

If you are using one-node kubeadm, it will work correctly, however, when you are using more than 1 node in kubeadm, this will cause some issues. There are many similar threads on Github regarding this. I've tried with various flags in args:, but no success. In metrics-server logs (-v=6) you will be able to see that metrics are gathering. In this Github thread, one of the Github users posted answer which is a workaround for this issue. It's also mentioned in K8s docs about hostNetwork.

Adding hostNetwork: true is what finally got metrics-server working for me. Without it, nada. Without the kubelet-preferred-address-types line, I could query my master node but not my two worker nodes, nor could I query pods, obviously undesirable results. Lack of kubelet-insecure-tls also results in an inoperable metrics-server installation.

```<code>spec:
  hostNetwork: true
  containers:
  - args:
    - --kubelet-insecure-tls
    - --cert-dir=/tmp
    - --secure-port=4443
    - --kubelet-preferred-address-types=InternalIP
    - --v=6
    image: k8s.gcr.io/metrics-server-amd64:v0.3.6
    imagePullPolicy: Always
</code>```

If you will deploy with this config it will work.

```<code>$ kubectl describe apiservice v1beta1.metrics.k8s.io
Name:         v1beta1.metrics.k8s.io
...
Status:
  Conditions:
    Last Transition Time:  2020-02-20T09:37:59Z
    Message:               all checks passed
    Reason:                Passed
    Status:                True
    Type:                  Available
Events:                    <none>
</code>```

In addition, you can see the difference when using host network: true when you will check iptables. There is much more entries compare to deployment without this config.

After that, you can edit deployment, and remove or comment host network: true.

```<code>$ kubectl edit deploy metrics-server -n kube-system
deployment.apps/metrics-server edited

$ kubectl top pods
NAME                     CPU(cores)   MEMORY(bytes)
nginx-6db489d4b7-2qhzw   0m           3Mi
nginx-6db489d4b7-9fvrj   0m           2Mi
nginx-6db489d4b7-dgbf9   0m           2Mi
nginx-6db489d4b7-dvcz5   0m           2Mi
</code>```

Also, you will be able to find metrics using:

```<code>$ kubectl get --raw /apis/metrics.k8s.io/v1beta1/nodes
</code>```

For better visibility you can use also jq.

```<code>$ kubectl get --raw /apis/metrics.k8s.io/v1beta1/pods | jq .
</code>```

Using Weave Net

When you will use Weave Net and instead of Calico it will work without setting host network.

```<code>$ kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')"
</code>```

However, you will need to work with certificates. But if you don't care about security, you can just use --kubelet-insecure-tls like in the previous example, when Calico was used.

Title: Kubernetes without pod metrics

Body:
I´m trying to deploy metrics to kubernetes and something really strange is happening, I have one worker and one master. I have the following pods list:

NAMESPACE     NAME                                              READY   STATUS    RESTARTS   AGE     IP               NODE                      NOMINATED NODE   READINESS GATES
default       php-apache-774ff9d754-d7vp9                       1/1     Running   0          2m43s   192.168.77.172   master-node               <none>           <none>
kube-system   calico-kube-controllers-6b9d4c8765-x7pql          1/1     Running   2          4h11m   192.168.77.130   master-node               <none>           <none>
kube-system   calico-node-d4rnh                                 0/1     Running   1          4h11m   10.221.194.166   master-node               <none>           <none>
kube-system   calico-node-hwkmd                                 0/1     Running   1          4h11m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   coredns-6955765f44-kf4dr                          1/1     Running   1          4h20m   192.168.178.65   free5gc-virtual-machine   <none>           <none>
kube-system   coredns-6955765f44-s58rf                          1/1     Running   1          4h20m   192.168.178.66   free5gc-virtual-machine   <none>           <none>
kube-system   etcd-free5gc-virtual-machine                      1/1     Running   1          4h21m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   kube-apiserver-free5gc-virtual-machine            1/1     Running   1          4h21m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   kube-controller-manager-free5gc-virtual-machine   1/1     Running   1          4h21m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   kube-proxy-brvdg                                  1/1     Running   1          4h19m   10.221.194.166   master-node               <none>           <none>
kube-system   kube-proxy-lfzjw                                  1/1     Running   1          4h20m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   kube-scheduler-free5gc-virtual-machine            1/1     Running   1          4h21m   10.221.195.58    free5gc-virtual-machine   <none>           <none>
kube-system   metrics-server-86c6d8b9bf-p2hh8                   1/1     Running   0          2m43s   192.168.77.171   master-node               <none>           <none>

When I try to get the metrics I see the following:

NAME         REFERENCE               TARGETS         MINPODS   MAXPODS   REPLICAS   AGE
php-apache   Deployment/php-apache   <unknown>/50%   1         10        1          3m58s
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl top nodes
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io)
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl top pods --all-namespaces
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get pods.metrics.k8s.io)

Lastly, I see the log (v=6) the output of metrics-server:

free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl logs metrics-server-86c6d8b9bf-p2hh8  -n kube-system
I0206 18:16:18.657605       1 serving.go:273] Generated self-signed cert (/tmp/apiserver.crt, /tmp/apiserver.key)
I0206 18:16:19.367356       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 7 milliseconds
I0206 18:16:19.370573       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
I0206 18:16:19.373245       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
I0206 18:16:19.375024       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
[restful] 2020/02/06 18:16:19 log.go:33: [restful/swagger] listing is available at https://:4443/swaggerapi
[restful] 2020/02/06 18:16:19 log.go:33: [restful/swagger] https://:4443/swaggerui/ is mapped to folder /swagger-ui/
I0206 18:16:19.421207       1 healthz.go:83] Installing healthz checkers:"ping", "poststarthook/generic-apiserver-start-informers", "healthz"
I0206 18:16:19.421641       1 serve.go:96] Serving securely on [::]:4443
I0206 18:16:19.421873       1 reflector.go:202] Starting reflector *v1.Pod (0s) from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421891       1 reflector.go:240] Listing and watching *v1.Pod from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421914       1 reflector.go:202] Starting reflector *v1.Node (0s) from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421929       1 reflector.go:240] Listing and watching *v1.Node from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.423052       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/nodes?limit=500&resourceVersion=0 200 OK in 1 milliseconds
I0206 18:16:19.424261       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/pods?limit=500&resourceVersion=0 200 OK in 2 milliseconds
I0206 18:16:19.425586       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/nodes?resourceVersion=38924&timeoutSeconds=481&watch=true 200 OK in 0 milliseconds
I0206 18:16:19.433545       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/pods?resourceVersion=39246&timeoutSeconds=582&watch=true 200 OK in 0 milliseconds
I0206 18:16:49.388514       1 manager.go:99] Beginning cycle, collecting metrics...
I0206 18:16:49.388598       1 manager.go:95] Scraping metrics from 2 sources
I0206 18:16:49.395742       1 manager.go:120] Querying source: kubelet_summary:free5gc-virtual-machine
I0206 18:16:49.400574       1 manager.go:120] Querying source: kubelet_summary:master-node
I0206 18:16:49.413751       1 round_trippers.go:405] GET https://10.221.194.166:10250/stats/summary/ 200 OK in 13 milliseconds
I0206 18:16:49.414317       1 round_trippers.go:405] GET https://10.221.195.58:10250/stats/summary/ 200 OK in 18 milliseconds
I0206 18:16:49.417044       1 manager.go:150] ScrapeMetrics: time: 28.428677ms, nodes: 2, pods: 13
I0206 18:16:49.417062       1 manager.go:115] ...Storing metrics...
I0206 18:16:49.417083       1 manager.go:126] ...Cycle complete
free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl logs metrics-server-86c6d8b9bf-p2hh8  -n kube-system
I0206 18:16:18.657605       1 serving.go:273] Generated self-signed cert (/tmp/apiserver.crt, /tmp/apiserver.key)
I0206 18:16:19.367356       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 7 milliseconds
I0206 18:16:19.370573       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
I0206 18:16:19.373245       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
I0206 18:16:19.375024       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication 200 OK in 1 milliseconds
[restful] 2020/02/06 18:16:19 log.go:33: [restful/swagger] listing is available at https://:4443/swaggerapi
[restful] 2020/02/06 18:16:19 log.go:33: [restful/swagger] https://:4443/swaggerui/ is mapped to folder /swagger-ui/
I0206 18:16:19.421207       1 healthz.go:83] Installing healthz checkers:"ping", "poststarthook/generic-apiserver-start-informers", "healthz"
I0206 18:16:19.421641       1 serve.go:96] Serving securely on [::]:4443
I0206 18:16:19.421873       1 reflector.go:202] Starting reflector *v1.Pod (0s) from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421891       1 reflector.go:240] Listing and watching *v1.Pod from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421914       1 reflector.go:202] Starting reflector *v1.Node (0s) from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.421929       1 reflector.go:240] Listing and watching *v1.Node from github.com/kubernetes-incubator/metrics-server/vendor/k8s.io/client-go/informers/factory.go:130
I0206 18:16:19.423052       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/nodes?limit=500&resourceVersion=0 200 OK in 1 milliseconds
I0206 18:16:19.424261       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/pods?limit=500&resourceVersion=0 200 OK in 2 milliseconds
I0206 18:16:19.425586       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/nodes?resourceVersion=38924&timeoutSeconds=481&watch=true 200 OK in 0 milliseconds
I0206 18:16:19.433545       1 round_trippers.go:405] GET https://10.96.0.1:443/api/v1/pods?resourceVersion=39246&timeoutSeconds=582&watch=true 200 OK in 0 milliseconds
I0206 18:16:49.388514       1 manager.go:99] Beginning cycle, collecting metrics...
I0206 18:16:49.388598       1 manager.go:95] Scraping metrics from 2 sources
I0206 18:16:49.395742       1 manager.go:120] Querying source: kubelet_summary:free5gc-virtual-machine
I0206 18:16:49.400574       1 manager.go:120] Querying source: kubelet_summary:master-node
I0206 18:16:49.413751       1 round_trippers.go:405] GET https://10.221.194.166:10250/stats/summary/ 200 OK in 13 milliseconds
I0206 18:16:49.414317       1 round_trippers.go:405] GET https://10.221.195.58:10250/stats/summary/ 200 OK in 18 milliseconds
I0206 18:16:49.417044       1 manager.go:150] ScrapeMetrics: time: 28.428677ms, nodes: 2, pods: 13
I0206 18:16:49.417062       1 manager.go:115] ...Storing metrics...
I0206 18:16:49.417083       1 manager.go:126] ...Cycle complete

Using the log output with v=10 I can see even the details of health of each pod, but nothing while running the kubectl get hpa or kubectl top nodes. Can someone give me a hint? Furthermore, my metrics manifest is:

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: metrics-server
  namespace: kube-system
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: metrics-server
  namespace: kube-system
  labels:
    k8s-app: metrics-server
spec:
  selector:
    matchLabels:
      k8s-app: metrics-server
  template:
    metadata:
      name: metrics-server
      labels:
        k8s-app: metrics-server
    spec:
      serviceAccountName: metrics-server
      volumes:
      # mount in tmp so we can safely use from-scratch images and/or read-only containers
      - name: tmp-dir
        emptyDir: {}
      containers:
      - name: metrics-server
        image: k8s.gcr.io/metrics-server-amd64:v0.3.1
        args:
          - /metrics-server
          - --metric-resolution=30s
          - --requestheader-allowed-names=aggregator
          - --cert-dir=/tmp
          - --secure-port=4443
          - --kubelet-insecure-tls
          - --v=6
          - --kubelet-preferred-address-types=InternalIP,Hostname,InternalDNS,ExternalDNS,ExternalIP
            #- --kubelet-preferred-address-types=InternalIP
        ports:
        - name: main-port
          containerPort: 4443
          protocol: TCP
        securityContext:
          readOnlyRootFilesystem: true
          runAsNonRoot: true
          runAsUser: 1000
        imagePullPolicy: Always
        volumeMounts:
        - name: tmp-dir
          mountPath: /tmp
      nodeSelector:
        beta.kubernetes.io/os: linux
        kubernetes.io/arch: "amd64"

And I can see the following:

free5gc@free5gc-virtual-machine:~/Desktop/metrics-server/deploy$ kubectl get apiservice v1beta1.metrics.k8s.io -o yaml
apiVersion: apiregistration.k8s.io/v1
kind: APIService
metadata:
  creationTimestamp: "2020-02-06T18:57:28Z"
  name: v1beta1.metrics.k8s.io
  resourceVersion: "45583"
  selfLink: /apis/apiregistration.k8s.io/v1/apiservices/v1beta1.metrics.k8s.io
  uid: ca439221-b987-4c13-b0e0-8d2bb237e612
spec:
  group: metrics.k8s.io
  groupPriorityMinimum: 100
  insecureSkipTLSVerify: true
  service:
    name: metrics-server
    namespace: kube-system
    port: 443
  version: v1beta1
  versionPriority: 100
status:
  conditions:
  - lastTransitionTime: "2020-02-06T18:57:28Z"
    message: 'failing or missing response from https://10.110.144.114:443/apis/metrics.k8s.io/v1beta1:
      Get https://10.110.144.114:443/apis/metrics.k8s.io/v1beta1: dial tcp 10.110.144.114:443:
      connect: no route to host'
    reason: FailedDiscoveryCheck
    status: "False"
    type: Available

Body:
I have reproduced your issue (on Google Compute Engine). Tried a few scenarios to find workaround/solution for this issue.

First thing I want to mention is that you have provided ServiceAccount and Deployment YAML. You also need ClusterRoleBinding, RoleBinding, ApiService, etc. All needed YAMLs can be found in this Github repo.

For fast deploy metrics-server with all required config you can use:

$ git clone https://github.com/kubernetes-sigs/metrics-server.git
$ cd metrics-server/deploy/
$ kubectl apply -f kubernetes/
clusterrole.rbac.authorization.k8s.io/system:aggregated-metrics-reader created
clusterrolebinding.rbac.authorization.k8s.io/metrics-server:system:auth-delegator created
rolebinding.rbac.authorization.k8s.io/metrics-server-auth-reader created
apiservice.apiregistration.k8s.io/v1beta1.metrics.k8s.io created
serviceaccount/metrics-server created
deployment.apps/metrics-server created
service/metrics-server created
clusterrole.rbac.authorization.k8s.io/system:metrics-server created
clusterrolebinding.rbac.authorization.k8s.io/system:metrics-server created

The second thing I would advise you to check your CNI pods (calico-node-d4rnh and calico-node-hawked). Created 4h11m but Ready 0/1.

Last thing regarding gathering CPU and Memory data from pods and nodes.

Using Calico

If you are using one-node kubeadm, it will work correctly, however, when you are using more than 1 node in kubeadm, this will cause some issues. There are many similar threads on Github regarding this. I've tried with various flags in args:, but no success. In metrics-server logs (-v=6) you will be able to see that metrics are gathering. In this Github thread, one of the Github users posted answer which is a workaround for this issue. It's also mentioned in K8s docs about hostNetwork.

Adding hostNetwork: true is what finally got metrics-server working for me. Without it, nada. Without the kubelet-preferred-address-types line, I could query my master node but not my two worker nodes, nor could I query pods, obviously undesirable results. Lack of kubelet-insecure-tls also results in an inoperable metrics-server installation.

spec:
  hostNetwork: true
  containers:
  - args:
    - --kubelet-insecure-tls
    - --cert-dir=/tmp
    - --secure-port=4443
    - --kubelet-preferred-address-types=InternalIP
    - --v=6
    image: k8s.gcr.io/metrics-server-amd64:v0.3.6
    imagePullPolicy: Always

If you will deploy with this config it will work.

$ kubectl describe apiservice v1beta1.metrics.k8s.io
Name:         v1beta1.metrics.k8s.io
...
Status:
  Conditions:
    Last Transition Time:  2020-02-20T09:37:59Z
    Message:               all checks passed
    Reason:                Passed
    Status:                True
    Type:                  Available
Events:                    <none>

In addition, you can see the difference when using host network: true when you will check iptables. There is much more entries compare to deployment without this config.

After that, you can edit deployment, and remove or comment host network: true.

$ kubectl edit deploy metrics-server -n kube-system
deployment.apps/metrics-server edited

$ kubectl top pods
NAME                     CPU(cores)   MEMORY(bytes)
nginx-6db489d4b7-2qhzw   0m           3Mi
nginx-6db489d4b7-9fvrj   0m           2Mi
nginx-6db489d4b7-dgbf9   0m           2Mi
nginx-6db489d4b7-dvcz5   0m           2Mi

Also, you will be able to find metrics using:

$ kubectl get --raw /apis/metrics.k8s.io/v1beta1/nodes

For better visibility you can use also jq.

$ kubectl get --raw /apis/metrics.k8s.io/v1beta1/pods | jq .

Using Weave Net

When you will use Weave Net and instead of Calico it will work without setting host network.

$ kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')"

However, you will need to work with certificates. But if you don't care about security, you can just use --kubelet-insecure-tls like in the previous example, when Calico was used.