问:
Search in nested documents in mongodb
Hi I have the following issue with a collection that saves the contact info from a user, and it looks like this.

```<code>[{
  "_id": {
    "$oid": "5836b917885383034437d26b"
  },
  "Nombre": "Juan",
  "Email": "jsanzrobles@hotmail.es",
  "Edad": 34,
  "País": "España",
  "Contactos": [
    {
      "Usuario_contacto": {
        "_id": {
          "$oid": "5836b916885383034437d23d"
        },
        "Nombre": "Alejandro",
        "Email": "aamericagarzon@hotmail.es",
        "Edad": 32,
        "País": "España",
        "Tipo": "Usuario individual",
        "Apellidos": "América Garzón",
        "Teléfono": 639123123,
        "Ciudad": "Salamanca",
        "Identificador": "U-3491",
        "Información_creación": {
          "Fecha_creación": {
            "Mes": 7,
            "Día": 14,
            "Año": 2016
          },
          "Hora_creación": {
            "Hora": 5,
            "Minutos": 22,
            "Segundos": 16
          }
        }
      },
      "Fecha_alta": {
        "Mes": 10,
        "Día": 27,
        "Año": 2016
      },
      "Hora_alta": {
        "Hora": 23,
        "Minutos": 2,
        "Segundos": 31
      }
    },
    {
      "Usuario_contacto": {
        "_id": {
          "$oid": "5836b916885383034437d21f"
        },
        "Nombre": "Alfonso",
        "Email": "amartinezosorio@hotmail.es",
        "Edad": 23,
        "País": "España",
        "Tipo": "Usuario individual",
        "Apellidos": "Martínez Osorio",
        "Teléfono": 612311456,
        "Ciudad": "Bilbao",
        "Identificador": "U-3461",
        "Información_creación": {
          "Fecha_creación": {
            "Mes": 8,
            "Día": 22,
            "Año": 2016
          },
          "Hora_creación": {
            "Hora": 7,
            "Minutos": 22,
            "Segundos": 30
          }
        }
      },
      "Fecha_alta": {
        "Mes": 10,
        "Día": 27,
        "Año": 2016
      },
      "Hora_alta": {
        "Hora": 12,
        "Minutos": 7,
        "Segundos": 48
      }
    },
    {
      "Usuario_contacto": {
        "_id": {
          "$oid": "5836b916885383034437d232"
        },
        "Nombre": "Mercedes",
        "Email": "mreysordo@gmail.es",
        "Edad": 50,
        "País": "España",
        "Tipo": "Usuario individual",
        "Apellidos": "Rey Sordo",
        "Teléfono": 635456989,
        "Ciudad": "Castellón",
        "Identificador": "U-3480",
        "Información_creación": {
          "Fecha_creación": {
            "Mes": 4,
            "Día": 28,
            "Año": 2016
          },
          "Hora_creación": {
            "Hora": 15,
            "Minutos": 22,
            "Segundos": 15
          }
        }
      },
      "Fecha_alta": {
        "Mes": 10,
        "Día": 24,
        "Año": 2016
      },
      "Hora_alta": {
        "Hora": 14,
        "Minutos": 35,
        "Segundos": 26
      }
    }
  ],
  "Información_creación": {
    "Fecha_creación": {
      "Mes": 10,
      "Día": 23,
      "Año": 2016
    },
    "Hora_creación": {
      "Hora": 10,
      "Minutos": 12,
      "Segundos": 10
    }
  },
  "Apellidos": "Sanz Robles",
  "Identifier": "U-3455",
  "Tipo": "Usuario individual",
  "Teléfono": 675456789,
  "Ciudad": "Granada"
}
</code>```

The exercise ive been asked to do is to create a new document for every user that has 2 or more contacts in the same city("Ciudad"). and it has to look like this

```<code>[...{
      _id : { Identifier:    ...
                  Ciudad:   ... },
      Counter:  3
}, ...
]
</code>```

Im new in mongo, I tried a lot and I know i have to create an aggregate but i dont know how to filter like that.

答:
To start with I'm going to work with a simplified data structure as we only need to know about the city and the document id.

So let's insert some records:

db.test.insertMany([
   { "_id": 1, "contacts" : [
     { "name": "Name-1", "city" : "Manchester" },
     { "name": "Name-2", "city" : "Manchester" },
     { "name": "Name-3", "city" : "Manchester" }]
   },
   { "_id": 2, "contacts" : [
     { "name": "Name-4", "city" : "York" },
     { "name": "Name-5", "city" : "Manchester" },
     { "name": "Name-6", "city" : "Sheffield" }]
   },
   { "_id": 3, "contacts" : [
     { "name": "Name-7", "city" : "Sheffield" },
     { "name": "Name-8", "city" : "York" },
     { "name": "Name-9", "city" : "Sheffield" }]
   }
])
```

<p>Then we'll need an aggragation pipeline that unwinds the sub documents of <code>contacts</code> the regroups them so we can count them with a <code>$sum</code>:</p>

<pre class="lang-js prettyprint-override"><code>db.test.aggregate([
  { "$unwind": "$contacts" },
  { "$group": { "_id": { "_id": "$_id", "city": "$contacts.city" }, "count": { $sum: 1 } } }
]);

{ "_id" : { "_id" : 2, "city" : "Manchester" }, "count" : 1 }
{ "_id" : { "_id" : 2, "city" : "Sheffield" }, "count" : 1 }
{ "_id" : { "_id" : 3, "city" : "York" }, "count" : 1 }
{ "_id" : { "_id" : 1, "city" : "Manchester" }, "count" : 3 }
{ "_id" : { "_id" : 2, "city" : "York" }, "count" : 1 }
{ "_id" : { "_id" : 3, "city" : "Sheffield" }, "count" : 2 }
</code>```

Then we'll need to filter out the ones with less than 2 in the count, this can be done with a $match stage with a grater than or equal to operator ($gte):

db.test.aggregate([
  { "$unwind": "$contacts" },
  { "$group": { "_id": { "_id": "$_id", "city": "$contacts.city" }, "count": { $sum: 1 } } },
  { "$match" : { "count" : { "$gte" : 2 } } }
]);

{ "_id" : { "_id" : 1, "city" : "Manchester" }, "count" : 3 }
{ "_id" : { "_id" : 3, "city" : "Sheffield" }, "count" : 2 }
```

<p>This then gets our required results, so now just to pipe these in to another collection, this is achieved with a <code>$out</code> stage:</p>

<pre class="lang-js prettyprint-override"><code>db.test.aggregate([
  { "$unwind": "$contacts" },
  { "$group": { "_id": { "_id": "$_id", "city": "$contacts.city" }, "count": { $sum: 1 } } },
  { "$match" : { "count" : { "$gte" : 2 } } },
  { "$out" : "test2" }
]);

</code>```

This will output all the results into a collection called test2 now we'll be able to query that directly.

db.test2.find()
{ "_id" : { "_id" : 1, "city" : "Manchester" }, "count" : 3 }
{ "_id" : { "_id" : 3, "city" : "Sheffield" }, "count" : 2 }
```

Here's some useful links to read more on the aggregation stages:

https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

https://docs.mongodb.com/manual/reference/operator/aggregation/match/

https://docs.mongodb.com/manual/reference/operator/aggregation/group/

https://docs.mongodb.com/manual/reference/operator/aggregation/out/

Title: Search in nested documents in mongodb

Body:
Hi I have the following issue with a collection that saves the contact info from a user, and it looks like this.

[{
  "_id": {
    "$oid": "5836b917885383034437d26b"
  },
  "Nombre": "Juan",
  "Email": "jsanzrobles@hotmail.es",
  "Edad": 34,
  "País": "España",
  "Contactos": [
    {
      "Usuario_contacto": {
        "_id": {
          "$oid": "5836b916885383034437d23d"
        },
        "Nombre": "Alejandro",
        "Email": "aamericagarzon@hotmail.es",
        "Edad": 32,
        "País": "España",
        "Tipo": "Usuario individual",
        "Apellidos": "América Garzón",
        "Teléfono": 639123123,
        "Ciudad": "Salamanca",
        "Identificador": "U-3491",
        "Información_creación": {
          "Fecha_creación": {
            "Mes": 7,
            "Día": 14,
            "Año": 2016
          },
          "Hora_creación": {
            "Hora": 5,
            "Minutos": 22,
            "Segundos": 16
          }
        }
      },
      "Fecha_alta": {
        "Mes": 10,
        "Día": 27,
        "Año": 2016
      },
      "Hora_alta": {
        "Hora": 23,
        "Minutos": 2,
        "Segundos": 31
      }
    },
    {
      "Usuario_contacto": {
        "_id": {
          "$oid": "5836b916885383034437d21f"
        },
        "Nombre": "Alfonso",
        "Email": "amartinezosorio@hotmail.es",
        "Edad": 23,
        "País": "España",
        "Tipo": "Usuario individual",
        "Apellidos": "Martínez Osorio",
        "Teléfono": 612311456,
        "Ciudad": "Bilbao",
        "Identificador": "U-3461",
        "Información_creación": {
          "Fecha_creación": {
            "Mes": 8,
            "Día": 22,
            "Año": 2016
          },
          "Hora_creación": {
            "Hora": 7,
            "Minutos": 22,
            "Segundos": 30
          }
        }
      },
      "Fecha_alta": {
        "Mes": 10,
        "Día": 27,
        "Año": 2016
      },
      "Hora_alta": {
        "Hora": 12,
        "Minutos": 7,
        "Segundos": 48
      }
    },
    {
      "Usuario_contacto": {
        "_id": {
          "$oid": "5836b916885383034437d232"
        },
        "Nombre": "Mercedes",
        "Email": "mreysordo@gmail.es",
        "Edad": 50,
        "País": "España",
        "Tipo": "Usuario individual",
        "Apellidos": "Rey Sordo",
        "Teléfono": 635456989,
        "Ciudad": "Castellón",
        "Identificador": "U-3480",
        "Información_creación": {
          "Fecha_creación": {
            "Mes": 4,
            "Día": 28,
            "Año": 2016
          },
          "Hora_creación": {
            "Hora": 15,
            "Minutos": 22,
            "Segundos": 15
          }
        }
      },
      "Fecha_alta": {
        "Mes": 10,
        "Día": 24,
        "Año": 2016
      },
      "Hora_alta": {
        "Hora": 14,
        "Minutos": 35,
        "Segundos": 26
      }
    }
  ],
  "Información_creación": {
    "Fecha_creación": {
      "Mes": 10,
      "Día": 23,
      "Año": 2016
    },
    "Hora_creación": {
      "Hora": 10,
      "Minutos": 12,
      "Segundos": 10
    }
  },
  "Apellidos": "Sanz Robles",
  "Identifier": "U-3455",
  "Tipo": "Usuario individual",
  "Teléfono": 675456789,
  "Ciudad": "Granada"
}

The exercise ive been asked to do is to create a new document for every user that has 2 or more contacts in the same city("Ciudad"). and it has to look like this

[...{
      _id : { Identifier:    ...
                  Ciudad:   ... },
      Counter:  3
}, ...
]

Im new in mongo, I tried a lot and I know i have to create an aggregate but i dont know how to filter like that.

Body:
To start with I'm going to work with a simplified data structure as we only need to know about the city and the document id.

So let's insert some records:

db.test.insertMany([
   { "_id": 1, "contacts" : [
     { "name": "Name-1", "city" : "Manchester" },
     { "name": "Name-2", "city" : "Manchester" },
     { "name": "Name-3", "city" : "Manchester" }]
   },
   { "_id": 2, "contacts" : [
     { "name": "Name-4", "city" : "York" },
     { "name": "Name-5", "city" : "Manchester" },
     { "name": "Name-6", "city" : "Sheffield" }]
   },
   { "_id": 3, "contacts" : [
     { "name": "Name-7", "city" : "Sheffield" },
     { "name": "Name-8", "city" : "York" },
     { "name": "Name-9", "city" : "Sheffield" }]
   }
])

Then we'll need an aggragation pipeline that unwinds the sub documents of contacts the regroups them so we can count them with a $sum:

db.test.aggregate([
  { "$unwind": "$contacts" },
  { "$group": { "_id": { "_id": "$_id", "city": "$contacts.city" }, "count": { $sum: 1 } } }
]);

{ "_id" : { "_id" : 2, "city" : "Manchester" }, "count" : 1 }
{ "_id" : { "_id" : 2, "city" : "Sheffield" }, "count" : 1 }
{ "_id" : { "_id" : 3, "city" : "York" }, "count" : 1 }
{ "_id" : { "_id" : 1, "city" : "Manchester" }, "count" : 3 }
{ "_id" : { "_id" : 2, "city" : "York" }, "count" : 1 }
{ "_id" : { "_id" : 3, "city" : "Sheffield" }, "count" : 2 }

Then we'll need to filter out the ones with less than 2 in the count, this can be done with a $match stage with a grater than or equal to operator ($gte):

db.test.aggregate([
  { "$unwind": "$contacts" },
  { "$group": { "_id": { "_id": "$_id", "city": "$contacts.city" }, "count": { $sum: 1 } } },
  { "$match" : { "count" : { "$gte" : 2 } } }
]);

{ "_id" : { "_id" : 1, "city" : "Manchester" }, "count" : 3 }
{ "_id" : { "_id" : 3, "city" : "Sheffield" }, "count" : 2 }

This then gets our required results, so now just to pipe these in to another collection, this is achieved with a $out stage:

db.test.aggregate([
  { "$unwind": "$contacts" },
  { "$group": { "_id": { "_id": "$_id", "city": "$contacts.city" }, "count": { $sum: 1 } } },
  { "$match" : { "count" : { "$gte" : 2 } } },
  { "$out" : "test2" }
]);

This will output all the results into a collection called test2 now we'll be able to query that directly.

db.test2.find()
{ "_id" : { "_id" : 1, "city" : "Manchester" }, "count" : 3 }
{ "_id" : { "_id" : 3, "city" : "Sheffield" }, "count" : 2 }

Here's some useful links to read more on the aggregation stages:

https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

https://docs.mongodb.com/manual/reference/operator/aggregation/match/

https://docs.mongodb.com/manual/reference/operator/aggregation/group/

https://docs.mongodb.com/manual/reference/operator/aggregation/out/


来源: stackexchange

问:
is there a way to remove the file attach icon in webchat?

i am looking for a way to remove this icon which is highlighted in the picture.

Additional information:

using webchat 4.8

implementing in an angular project.

答:
Yes, you can pass in the hideUploadButton: true in styleOptions. Then pass that is to the Web Chat renderer. For a full list of styleOptions parameters, reference this file.

const styleOptions = {
  hideUploadButton: true,
}

[ ... ]

window.WebChat.renderWebChat(
  {
    directLine: window.WebChat.createDirectLine( {
      token: token
    } ),
    styleOptions: styleOptions
  document.getElementById( 'webchat' )
);
```

Hope of help!

ContentLicense: CC BY-SA 4.0

Body:
Yes, you can pass in the hideUploadButton: true in styleOptions. Then pass that is to the Web Chat renderer. For a full list of styleOptions parameters, reference this file.

const styleOptions = {
  hideUploadButton: true,
}

[ ... ]

window.WebChat.renderWebChat(
  {
    directLine: window.WebChat.createDirectLine( {
      token: token
    } ),
    styleOptions: styleOptions
  document.getElementById( 'webchat' )
);

Hope of help!


问:
.gitignore not ignoring a folder within a directory
It seems a straightforward one, but having researched multiple ways to do it, I can't gitignore a folder within a directory.

I have a root directory which contains all of my code in it. Because it has some back-end NodeJS stuff in it, it has a 'node_modules' folder which contains hundreds of files. As a result, when I try to upload the entire parent folder, GitHub says there's too many files to upload and tells me to reduce the number I'm uploading.

The crucial part is though, the folder has to be uploaded as a whole, as it itself is within a GitHub repository with other files with different folders in.

That means when I go onto my repository, I need this folder's files to display within the folder, and not separately within the repository. I need all of the files to be within this folder, within the parent repository, excluding the node_modules folder.

For example ->

Parent repository -> Child Directory (what I'm uploading) -> Individual files

I've tried to add the node_modules folder to my gitignore through the following methods:

Adding: node_modules/ to my gitignore file
Writing: echo node_modules >> .gitignore through my terminal
Adding a separate gitignore file within my node_modules file with a * in it

None of them have worked and I can't find any other solutions. For reference I'm using a Mac.

Does anyone have any idea what I'm doing wrong, or how it'd be best to do it?

答:
By default, you do not need to include the node_modules folder in your repositories because the package.json file contains all of your project's dependency information. This means that anyone who clones your repository can run npm install and have the entire node_modules folder without problems.

To solve this you can create your own .gitignore file, creating a new file at the root of your project and renaming it to .gitignore (writing exactly that way). Then you can open it with any text editor and add */node_modules to one of the lines.

This will likely solve your problem.


问:
How to unable user to choose tags for one of the register form field?
I'm building a nodejs express app with mongoDB.
I want to make user be able to choose certain predefined tags when submitting a register form.

Register for studios, an attribute is "equipment”，want user to choose from tags "drums","guitar","amp","mic", etc.

And I want to use the tags for search bar function.

Thank you in advance!

答:
Firstly You want to open a tag system. If you do it for user when you search tags you will find users. But in your project there are articles which user can post, it is better to add tags to articles.

I will just show a example.

In your Model.js script just add:

```<code>tags:{
  type:String,
  required:True,//If you want to make tags as a obligation.
},
</code>```

You should look at here:
Mongodb Nodejs Regex Search

https://www.youtube.com/watch?v=9_lKMTXVk64

Fuzzy Searching with Mongodb?

Add a search.pug:(Or add form in your layout, it depends on your preferences)

```<code> form.form-inline.my-2.my-lg-0(action="/sonuc" method="GET")
    <input type="text" name="search" placeholder="Search Here..." class="form-control">
</code>```

After that in your app.js(or whatever you name it):

You can also look here:
https://docs.mongodb.com/manual/reference/operator/query/regex/#examples

```<code>app.get('/search', function(req, res){
  if (req.query.search) {
    const regex = new RegExp(escapeRegex(req.query.search), 'gi');
    Article.find({"tags": regex}, function(err, articles) {
        if(err) {
            console.log(err);
        } else {
           res.render("index", {
             articles: articles
            });
        }
    });
  }
});
</code>```

And in article.pug:

```<code>.
.
input.form-control(name='', type='text')
.
.
</code>```

In app.js you will just add these codes to add articles(post)

```<code>let article = new Article({
...
...
...
tags:req.body.tags,
});
</code>```

You can just change the codes and follow the steps. But I recomend you to write these scripts to your notebook. And then write the meanings of them.

In this project, you will use regex.

Please look at the links that I have send to you and then please write scripts in your notebook and write the meaning of codes.(To learn the structure and steps.)

Body:
Firstly You want to open a tag system. If you do it for user when you search tags you will find users. But in your project there are articles which user can post, it is better to add tags to articles.

I will just show a example.

In your Model.js script just add:

tags:{
  type:String,
  required:True,//If you want to make tags as a obligation.
},

You should look at here:
Mongodb Nodejs Regex Search

https://www.youtube.com/watch?v=9_lKMTXVk64

Fuzzy Searching with Mongodb?

Add a search.pug:(Or add form in your layout, it depends on your preferences)

 form.form-inline.my-2.my-lg-0(action="/sonuc" method="GET")
    <input type="text" name="search" placeholder="Search Here..." class="form-control">

After that in your app.js(or whatever you name it):

You can also look here:
https://docs.mongodb.com/manual/reference/operator/query/regex/#examples

app.get('/search', function(req, res){
  if (req.query.search) {
    const regex = new RegExp(escapeRegex(req.query.search), 'gi');
    Article.find({"tags": regex}, function(err, articles) {
        if(err) {
            console.log(err);
        } else {
           res.render("index", {
             articles: articles
            });
        }
    });
  }
});

And in article.pug:

.
.
input.form-control(name='', type='text')
.
.

In app.js you will just add these codes to add articles(post)

let article = new Article({
...
...
...
tags:req.body.tags,
});

You can just change the codes and follow the steps. But I recomend you to write these scripts to your notebook. And then write the meanings of them.

In this project, you will use regex.

Please look at the links that I have send to you and then please write scripts in your notebook and write the meaning of codes.(To learn the structure and steps.)


问:
C++ nested lambda bug in VS2010 with lambda parameter capture?
I'm using Visual Studio 2010, which apparently has some buggy behavior on lambdas, and have this nested lambda, where the inner lambda returns a second lambda wrapped as a std::function (cf. "Higher-order Lambda Functions" on MSDN):

```<code>int x = 0;
auto lambda = [&]( int n )
{
    return std::function<void()>(
        [&] // Note capture
        {
            x = n;
        }
    );
};

lambda( -10 )(); // Call outer and inner lambdas

assert( -10 == x ); // Fails!
</code>```

This compiles but fails at the assert. Specifically, n in the inner lambda is uninitialized (0xCCCCCCCC), but x is successfully modified to its value. If I change the inner lambda's capture clause to "[&,n]", the assert passes as expected. Is this a bug with VS2010 or have I not understood how lambda capture works?

答:
This is similar to the case of just returning a simple reference.  The thing that caught you was the compiler did not issue an warning.  So it is not a bug in the compiler, it is just a lack of a warning.</p>

```<code>std::function<int()> F(int n)
{
    return [&]{ return n; };  //no warning
}
int& F2(int n)
{
    return n; //warning
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using Visual Studio 2010, which apparently has some buggy behavior on lambdas, and have this nested lambda, where the inner lambda returns a second lambda wrapped as a std::function (cf. "Higher-order Lambda Functions" on MSDN):

int x = 0;
auto lambda = [&]( int n )
{
    return std::function<void()>(
        [&] // Note capture
        {
            x = n;
        }
    );
};

lambda( -10 )(); // Call outer and inner lambdas

assert( -10 == x ); // Fails!

This compiles but fails at the assert. Specifically, n in the inner lambda is uninitialized (0xCCCCCCCC), but x is successfully modified to its value. If I change the inner lambda's capture clause to "[&,n]", the assert passes as expected. Is this a bug with VS2010 or have I not understood how lambda capture works?

Body:
This is similar to the case of just returning a simple reference.  The thing that caught you was the compiler did not issue an warning.  So it is not a bug in the compiler, it is just a lack of a warning.

std::function<int()> F(int n)
{
    return [&]{ return n; };  //no warning
}
int& F2(int n)
{
    return n; //warning
}


问:
Policy pod start at eviction
I have a problem: I use eviction policies (evict-soft and evict-hard) and when my pods are being evicted out beacause of resource lack on one node, pod dies and starts on another node, so, that during this time service is down. What can I do to make pod first start on another node before being killed on the first?</p>

答: Run two of them and use a pod disruption budget so it won’t do a soft evict of both at the same time (or use affinity settings so they run on different nodes, or both).</p>

Title: Policy pod start at eviction


问:
"set is iterable,but set is not sequence"，I have some questions
I am reading the book fluent python. It says all collections such as list, set are iterable. But set is not a sequence. Dictionary is also not a sequence, that is to say, the item in sequence can not be accessed by index, such as set[9], am I right? It's a bit like both linked lists and lists can be traversed, but only arrays can quickly get values through an index. I was wondering How is dictionary traversed?

Please forgive me for my poor English

答:
The answer to your question can be found in the docs, as mentioned in the comments. The answer is

d = {'a': 'b', 'c': 'd'}

# Way 1
for key in d:
    print(key, d[key])

# Way 2
for key, value in d.items():
    print(key, value)
```


问:
SSH closed in 120 minutes when wget one file
In CENTOS7, I use wget command to get one file. But ssh session will be closed in 120 minutes. In every 20 minutes, the following information appeared.

```<code>Tue Jun  2 06:40:01 2020
Your terminal (/dev/pts/0) has been idle for 63 min.
Press Enter key or you will be logged out any time after 56 min.
</code>```

I modifed the parameter in /etc/ssh/sshd_config as following:

```<code>ClientAliveInterval      60
ClientAliveCountMax     5000000000000
</code>```

But the problem does still exist.

答: You can let wget run in the background with -b option. The ssh session can be closed but the ssh process runs on. source

Body:
In CENTOS7, I use wget command to get one file. But ssh session will be closed in 120 minutes. In every 20 minutes, the following information appeared.

Tue Jun  2 06:40:01 2020
Your terminal (/dev/pts/0) has been idle for 63 min.
Press Enter key or you will be logged out any time after 56 min.

I modifed the parameter in /etc/ssh/sshd_config as following:

ClientAliveInterval      60
ClientAliveCountMax     5000000000000

But the problem does still exist.


问:
Adding css & js files to wordpress theme
In order to add Css & Js files to my website pages, I wanna add the following code to the functions.php file:

```<code>function cssjsloading(){

    wp_enqueue_style('bootstrap-rtl', get_template_directory_uri() . '/css/bootstrap-rtl.css', false);
    wp_enqueue_style('style', get_template_directory_uri().'/style.css', false);
    wp_enqueue_style('header', get_template_directory_uri().'/css/header.css', false);
    wp_enqueue_style('footer', get_template_directory_uri().'/css/footer.css', false);

}

add_action('wp_enqueue_scripts','cssjsloading');
</code>```

instead of the following code in my  tag file, but it is not working!

```<code><link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/bootstrap-rtl.css" />
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/style.css" />
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/header.css" />
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/header.css" />
</code>```

I would be most grateful if you could help me

答:
I think you should remove your false from wp_enqueue_style parameters if you do not need versioning.

Try simple wp_enqueue_style('style', get_template_directory_uri().'/style.css''); and check if this is working.

Body:
In order to add Css & Js files to my website pages, I wanna add the following code to the functions.php file:

function cssjsloading(){

    wp_enqueue_style('bootstrap-rtl', get_template_directory_uri() . '/css/bootstrap-rtl.css', false);
    wp_enqueue_style('style', get_template_directory_uri().'/style.css', false);
    wp_enqueue_style('header', get_template_directory_uri().'/css/header.css', false);
    wp_enqueue_style('footer', get_template_directory_uri().'/css/footer.css', false);

}

add_action('wp_enqueue_scripts','cssjsloading');

instead of the following code in my  tag file, but it is not working!

<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/bootstrap-rtl.css" />
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/style.css" />
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/header.css" />
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/header.css" />

I would be most grateful if you could help me


问:
How do I create a Download button in HTML?
Hello I am trying to code an HTML button to download an image.

Here is the code I am using that seems like I am getting close but not quite there.

```<code><a href="https://assets.giftcardsuite.com/valentinesday/Valentines-Day-Theme-1.png" download>
  <img src="https://assets.giftcardsuite.com/valentinesday/Valentines-Day-Theme-1.png" class="img-responsive" alt="happy-valentines-day"> Click Here To Download
</a>
</code>```

Here is a screenshot of what it looks like when I download it:
https://snag.gy/tTC2ER.jpg

答:
I think your code is disarranged

Try this:

```<code><a href="https://assets.giftcardsuite.com/valentinesday/Valentines-Day-Theme-1.png" download>Click here</a> to download
</code>```

Body:
Hello I am trying to code an HTML button to download an image.

Here is the code I am using that seems like I am getting close but not quite there.

   Click Here To Download

Here is a screenshot of what it looks like when I download it:
https://snag.gy/tTC2ER.jpg

Body:
I think your code is disarranged

Try this:

<a href="https://assets.giftcardsuite.com/valentinesday/Valentines-Day-Theme-1.png" download>Click here</a> to download


问:
Positioning UITabBar at the top
I'm a beginner in iOS development. My question is: is it possible to position UITabBar at the top and how?
I can't position my UITabBar at the top of the view.</p>

答:
After Update to xCode 11.5. Added this code in my controller. work ios 13</p>

```<code>override func viewWillLayoutSubviews() {
        renderTabPosition()
        super.viewWillLayoutSubviews()
    }
private func renderTabPosition() {
        tabBar.frame = CGRect(x: 0, y: 0, width: tabBar.frame.size.width, height: tabBar.frame.size.height + 5)
}
</code>```

Title: Positioning UITabBar at the top

Body:
After Update to xCode 11.5. Added this code in my controller. work ios 13

override func viewWillLayoutSubviews() {
        renderTabPosition()
        super.viewWillLayoutSubviews()
    }
private func renderTabPosition() {
        tabBar.frame = CGRect(x: 0, y: 0, width: tabBar.frame.size.width, height: tabBar.frame.size.height + 5)
}


问:
Android - Dynamically Add Views into View
I have a layout for a view -

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_header"
        style="@style/Home.ListHeader" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_none"
        android:visibility="gone"
        style="@style/TextBlock"
        android:paddingLeft="6px" />

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_list" />

</LinearLayout>
</code>```

What I want to do, is in my main activity with a layout like this

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:id="@+id/item_wrapper">
</LinearLayout>
</code>```

I want to loop through my data model and inject multiple views consisting of the first layout into the main layout.  I know I can do this by building the controls completely within the code, but I was wondering if there was a way to dynamically build the views so that I can continue using a layout instead of putting everything in code.

答:
It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged() you have full control of the Views generation and rendering.

Take a look at these tutorials

http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/

http://developerlife.com/tutorials/?p=327

http://www.androidguys.com/2008/07/14/fancy-listviews-part-one/

Body:
I have a layout for a view -

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_header"
        style="@style/Home.ListHeader" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_none"
        android:visibility="gone"
        style="@style/TextBlock"
        android:paddingLeft="6px" />

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_list" />

</LinearLayout>

What I want to do, is in my main activity with a layout like this

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:id="@+id/item_wrapper">
</LinearLayout>

I want to loop through my data model and inject multiple views consisting of the first layout into the main layout.  I know I can do this by building the controls completely within the code, but I was wondering if there was a way to dynamically build the views so that I can continue using a layout instead of putting everything in code.


问:
Redux Thunk vs Redux custom Middleware
I am new to redux. So after reading lots of tutorials.I understood that, redux need redux thunk to dispatch async actions by returning another function.But if  I call http request inside custom middle-ware then

is it required redux thunk ?

is Redux custom middleware no side effects ? I mean no need to return another function.

If  i use redux thunk then my action creator looks like this. This I understood

```<code>function incrementAsync() {
  return (dispatch) => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}
</code>```

I have confusion in custom middle-ware.

https://blog.logrocket.com/managing-asynchronous-actions-in-redux-1bc7d28a00c6/

as per this blog

```<code>const httpMiddleware = store => next => action => {
  if (action[HTTP_ACTION]) {
    const actionInfo = action[HTTP_ACTION];
    const fetchOptions = {
      method: actionInfo.verb,
      headers: actionInfo.headers,
      body: actionInfo.payload || null
    };

    next({
      type: actionInfo.type + "_REQUESTED"
    });

    fetch(actionInfo.endpoint, fetchOptions)
      .then(response => response.json())
      .then(data => next({
        type: actionInfo.type + "_RECEIVED",
        payload: data
      }))
      .catch(error => next({
        type: actionInfo.type + "_FAILED",
        payload: error
     }));
  } else {
    return next(action);
  }
}
</code>```

they are not returning any dispatch function inside action. I know that store,next,action are the inner functions.

can any one help me to understand about this?

Thank you.

答:
As you asked by point list I'm gonna reply by point list:

If i call http request inside custom middleware then is it required
redux thunk ?

Redux thunk is a middleware per se, it's recommended if you want to dispatch an action that make (let's say, for example) an AJAX call and dispatch two different action based on the result of that AJAX call, one if it fails and one if it succeeds.

is Redux custom middleware no side effects ? i mean no need to return another function.

If I'm understanding correctly: A middleware will simply take the action you dispatched and pass it through the chain, it'll let you do something before sending the action to the reducer "phase". What it'll do is entirely up to you. You need at least to do next(action) or block the action based on some logic, if needed.

Finally, a custom middleware like the one you posted is modifying the action you passed based on the response of an AJAX call, making it more of an "interceptor" than a simple middleware. Written this way, it's not dispatching a new action, it's more related to modifying the action you passed.

If you want to dispatch a new action based on the result of an ajax call, but without creating a middleware/interceptor, you could do it this way:

```<code>const postSomethingAction = postObject => {
    return async dispatch => {
        dispatch(postSomethingPending())
        const response = await Api.postSomething(postObject)
        if (response.message) {
            dispatch(postSomethingError(response))
        }
        else {
            dispatch(postSomethingSuccess(response.data))
        }
    }
}
</code>```

In this example we're using Thunk do create an action that dispatch another action based on the result of Api.postSomething

Title: Redux Thunk vs Redux custom Middleware

Body:
I am new to redux. So after reading lots of tutorials.I understood that, redux need redux thunk to dispatch async actions by returning another function.But if  I call http request inside custom middle-ware then

is it required redux thunk ?

is Redux custom middleware no side effects ? I mean no need to return another function.

If  i use redux thunk then my action creator looks like this. This I understood

function incrementAsync() {
  return (dispatch) => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}

I have confusion in custom middle-ware.

https://blog.logrocket.com/managing-asynchronous-actions-in-redux-1bc7d28a00c6/

as per this blog

const httpMiddleware = store => next => action => {
  if (action[HTTP_ACTION]) {
    const actionInfo = action[HTTP_ACTION];
    const fetchOptions = {
      method: actionInfo.verb,
      headers: actionInfo.headers,
      body: actionInfo.payload || null
    };

    next({
      type: actionInfo.type + "_REQUESTED"
    });

    fetch(actionInfo.endpoint, fetchOptions)
      .then(response => response.json())
      .then(data => next({
        type: actionInfo.type + "_RECEIVED",
        payload: data
      }))
      .catch(error => next({
        type: actionInfo.type + "_FAILED",
        payload: error
     }));
  } else {
    return next(action);
  }
}

they are not returning any dispatch function inside action. I know that store,next,action are the inner functions.

can any one help me to understand about this?

Thank you.

Body:
As you asked by point list I'm gonna reply by point list:

If i call http request inside custom middleware then is it required
redux thunk ?

Redux thunk is a middleware per se, it's recommended if you want to dispatch an action that make (let's say, for example) an AJAX call and dispatch two different action based on the result of that AJAX call, one if it fails and one if it succeeds.

is Redux custom middleware no side effects ? i mean no need to return another function.

If I'm understanding correctly: A middleware will simply take the action you dispatched and pass it through the chain, it'll let you do something before sending the action to the reducer "phase". What it'll do is entirely up to you. You need at least to do next(action) or block the action based on some logic, if needed.

Finally, a custom middleware like the one you posted is modifying the action you passed based on the response of an AJAX call, making it more of an "interceptor" than a simple middleware. Written this way, it's not dispatching a new action, it's more related to modifying the action you passed.

If you want to dispatch a new action based on the result of an ajax call, but without creating a middleware/interceptor, you could do it this way:

const postSomethingAction = postObject => {
    return async dispatch => {
        dispatch(postSomethingPending())
        const response = await Api.postSomething(postObject)
        if (response.message) {
            dispatch(postSomethingError(response))
        }
        else {
            dispatch(postSomethingSuccess(response.data))
        }
    }
}

In this example we're using Thunk do create an action that dispatch another action based on the result of Api.postSomething


问:
Remove lock on environment at every transaction end
Since it possible for one JVM process to write to Xodus and other JVM to read to the same environment, what is the correct way for a JVM process or method to remove the lock of the environment at end of every transaction as such other JVM processes would be able to write to the same environment at their own respective transactions?

答:
The xd.lck file is never being removed, it is being locked by an Environment which is allowed to write. For implementation details, look at LockingManager.

If one Environment is in write mode, it is possbile to open another one (and several such) in read-only listening mode against the same physical database:

```<code>final EnvironmentConfig config = new EnvironmentConfig().
            setLogDataReaderWriterProvider("jetbrains.exodus.io.WatchingFileDataReaderWriterProvider");
final Environment env = Environments.newInstance(dir, config);
</code>```

This way to open Environment can be used in the same or another JVM.

Body:
The xd.lck file is never being removed, it is being locked by an Environment which is allowed to write. For implementation details, look at LockingManager.

If one Environment is in write mode, it is possbile to open another one (and several such) in read-only listening mode against the same physical database:

final EnvironmentConfig config = new EnvironmentConfig().
            setLogDataReaderWriterProvider("jetbrains.exodus.io.WatchingFileDataReaderWriterProvider");
final Environment env = Environments.newInstance(dir, config);

This way to open Environment can be used in the same or another JVM.


问:
How can I access IPython's "display" function?
I tried this code, expecting it to use IPython's display function:

```<code>import pandas as pd
data = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets'])

display(data.head(10))
</code>```

But I get an error message that says NameError: name 'display' undefined. Why? How do I make it so that I can use display?

答:
To solve the problem on pycaret, you have to open the below file -

```<code>..\env\Lib\site-packages\pycaret\datasets.py
</code>```

and add the line of code  -

```<code>from IPython.display import display
</code>```

Body:
I tried this code, expecting it to use IPython's display function:

import pandas as pd
data = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets'])

display(data.head(10))

But I get an error message that says NameError: name 'display' undefined. Why? How do I make it so that I can use display?

Body:
To solve the problem on pycaret, you have to open the below file -

..\env\Lib\site-packages\pycaret\datasets.py

and add the line of code  -

from IPython.display import display


问:
View schema of resultset in SQL Server Management Studio
Is there any way in Sql Server Management Studio (2008) whereby I can view the data types of each field in the result of a query?

In this case, I am running a stored procedure which returns a result set, and I would like to know the lengths of the nvarchar columns and precision of decimals.

In the past, I have created a view which contains the underlying query in the stored procedure, and then viewed the column list, but the query within the procedure is much too complex to do so in this case.

Any ideas?

答:
Your best bet may be to use OPENROWSET to store the output of the procedure into a table, then examine that table. Something like:</p>

```<code>SELECT * INTO YourHoldingTable
    FROM OPENROWSET('SQLNCLI', 'Server=YourServerName;Trusted_Connection=yes;', 'EXEC YourDatabase.YourSchema.YourProcedureName')
GO

sp_help 'YourHoldingTable'
GO

DROP TABLE 'YourHoldingTable'
GO
</code>```

Body:
Your best bet may be to use OPENROWSET to store the output of the procedure into a table, then examine that table. Something like:

SELECT * INTO YourHoldingTable
    FROM OPENROWSET('SQLNCLI', 'Server=YourServerName;Trusted_Connection=yes;', 'EXEC YourDatabase.YourSchema.YourProcedureName')
GO

sp_help 'YourHoldingTable'
GO

DROP TABLE 'YourHoldingTable'
GO


问:
anyway to tell which cloud provider current k8s cluster is running at?
I'm writing a k8s operator, with the knowledge of current cloud provider the k8s is currently running on, I can do some platform-specific tasks for users, such as prepare some default storage classes for users.

but how can an operator running in the k8s cluster know it is GCP or AWS?

After scanning through the APIs, the cloud provider leaves some clues here and there, for example, for the GKE cluster I am running now, it has an API named: /apis/nodemanagement.gke.io/v1alpha1

but I think it's a little bit too hack, and wonder if there is any more formal way to get this info.

答: No, this is not exposed in a consistent way. You should have the use put it in their config file or whatever.</p>


问:
Code getting into infinite loop in javascript
My code is getting into infinite loop even if I input "yes" or "yeah".

Below is my code:

```<code>var answer = prompt("Are we there yet?");
while(answer != "yes" || answer != "yeah" ){
    var answer = prompt("Are we there yet?");
}
alert("YAY! We made it!!");
</code>```

答:
Firstly, don't redefine answer (remove var from the loop). Secondly, think about the three possible cases your loop has:

```<code>answer = "yes"  ->  (answer != "yes") is false, (answer != "yeah") is true. The loop continues.
answer = "yes"  ->  (answer != "yes") is true, (answer != "yeah") is false. The loop continues.
answer = "anything else"  ->  (answer != "yes") is true, (answer != "yeah") is true. The loop continues.
</code>```

Using a logical AND && operator should resolve your issue:

var answer = prompt("Are we there yet?");
while (answer != "yes" && answer != "yeah") {
  answer = prompt("Are we there yet?");
}
alert("YAY! We made it!!");```

Body:
My code is getting into infinite loop even if I input "yes" or "yeah".

Below is my code:

var answer = prompt("Are we there yet?");
while(answer != "yes" || answer != "yeah" ){
    var answer = prompt("Are we there yet?");
}
alert("YAY! We made it!!");

Body:
Firstly, don't redefine answer (remove var from the loop). Secondly, think about the three possible cases your loop has:

answer = "yes"  ->  (answer != "yes") is false, (answer != "yeah") is true. The loop continues.
answer = "yes"  ->  (answer != "yes") is true, (answer != "yeah") is false. The loop continues.
answer = "anything else"  ->  (answer != "yes") is true, (answer != "yeah") is true. The loop continues.

Using a logical AND && operator should resolve your issue:

var answer = prompt("Are we there yet?");
while (answer != "yes" && answer != "yeah") {
  answer = prompt("Are we there yet?");
}
alert("YAY! We made it!!");


问:
how to get html content form flutterWebViewPlugin ( webview ) in flutter
My question is pretty simple. how can I get the html data form the loaded page in webview. The data is in JSON format. for a reason I cannot use a post request for any get request here so I need to get the data with webview only. how to achive this ?</p>

```<code>flutterWebViewPlugin.onUrlChanged.listen((String url) {
      if (url.contains('/recon?')) {
        print('printing url : $url');
        // need to get data ( html content ) on this url
        flutterWebViewPlugin.close();
        Navigator.of(context).pop(url);
      }
    });
});

</code>```

```<code>
WebviewScaffold(
                userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0",
                url: myurl,
              )

</code>```

答:
You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

To get HTML data, you can simply use var html = await controller.evaluateJavascript(source: "window.document.getElementsByTagName('html')[0].outerHTML;"); inside the onLoadStop event.

Here is an example using your userAgent:

import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  String myurl = "https://github.com/flutter";

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                  child: InAppWebView(
                    initialUrl: myurl,
                    initialHeaders: {},
                    initialOptions: InAppWebViewGroupOptions(
                      crossPlatform: InAppWebViewOptions(
                        debuggingEnabled: true,
                        userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0"
                      ),
                    ),
                    onWebViewCreated: (InAppWebViewController controller) {
                      webView = controller;
                    },
                    onLoadStart: (InAppWebViewController controller, String url) {

                    },
                    onLoadStop: (InAppWebViewController controller, String url) async {
                      if (url.contains('/recon?')) {
                        // if JavaScript is enabled, you can use
                        var html = await controller.evaluateJavascript(
                            source: "window.document.getElementsByTagName('html')[0].outerHTML;");

                        log(html);
                      }
                    },
                  ))
            ])),
      ),
    );
  }
}
```

Just set the myurl variable to your url.

Through window.document.getElementsByTagName('html')[0].outerHTML; you will get all the HTML string. Instead, if you need only the body text, you can change it with window.document.body.innerText;.

Body:
My question is pretty simple. how can I get the html data form the loaded page in webview. The data is in JSON format. for a reason I cannot use a post request for any get request here so I need to get the data with webview only. how to achive this ?

flutterWebViewPlugin.onUrlChanged.listen((String url) {
      if (url.contains('/recon?')) {
        print('printing url : $url');
        // need to get data ( html content ) on this url
        flutterWebViewPlugin.close();
        Navigator.of(context).pop(url);
      }
    });
});

WebviewScaffold(
                userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0",
                url: myurl,
              )

Body:
You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

To get HTML data, you can simply use var html = await controller.evaluateJavascript(source: "window.document.getElementsByTagName('html')[0].outerHTML;"); inside the onLoadStop event.

Here is an example using your userAgent:

import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  String myurl = "https://github.com/flutter";

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                  child: InAppWebView(
                    initialUrl: myurl,
                    initialHeaders: {},
                    initialOptions: InAppWebViewGroupOptions(
                      crossPlatform: InAppWebViewOptions(
                        debuggingEnabled: true,
                        userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0"
                      ),
                    ),
                    onWebViewCreated: (InAppWebViewController controller) {
                      webView = controller;
                    },
                    onLoadStart: (InAppWebViewController controller, String url) {

                    },
                    onLoadStop: (InAppWebViewController controller, String url) async {
                      if (url.contains('/recon?')) {
                        // if JavaScript is enabled, you can use
                        var html = await controller.evaluateJavascript(
                            source: "window.document.getElementsByTagName('html')[0].outerHTML;");

                        log(html);
                      }
                    },
                  ))
            ])),
      ),
    );
  }
}

Just set the myurl variable to your url.

Through window.document.getElementsByTagName('html')[0].outerHTML; you will get all the HTML string. Instead, if you need only the body text, you can change it with window.document.body.innerText;.


问:
How to configure mvn to download a npm dependency?
As part of the mvn build process, I do want to download/install a javascript file that is published as a npm package.

Currently that file was copied into war/scripts/foobar.js which means that if a newer version of the foobar is published to npm, we would have to manually download it from there and update our code.

Isn't possible to integrate this dependency in a similar way as java dependencies?

If you could provide me with one example of doing this it would be great.

答:
One method is to use npm which involves incorporation of download/run of node and npm during your build. Other approach is to use maven itself and do not invoke any NodeJS processes.

For bigger projects where you have many npm dependencies which probably change a lot during development it's easier to use package.json descriptor and npm itself.

For smaller project where you just need on file I prefer to use simple maven plugin setup like this one for example:

        <plugins>
            <plugin>
                <groupId>com.googlecode.maven-download-plugin</groupId>
                <artifactId>download-maven-plugin</artifactId>
                <version>1.5.0</version>
                <executions>
                    <execution>
                        <id>download-babel-js</id>
                        <phase>initialize</phase>
                        <goals>
                            <goal>wget</goal>
                        </goals>
                        <configuration>
                            <url>
https://coporate.nexus.instance/repository/npm-proxy/babel-standalone/-/babel-standalone-6.26.0.tgz
                            </url>
                            <unpack>true</unpack>
                            <outputDirectory>${project.build.directory}/babel</outputDirectory>
                            <md5>ed714bb8253fc6056902d8d0afd6b106</md5>
                        </configuration>
                    </execution>

                    <execution>
                        <id>download-redux</id>
                        <phase>initialize</phase>
                        <goals>
                            <goal>wget</goal>
                        </goals>
                        <configuration>
                            <url>https://coporate.nexus.instance/repository/unpkg/redux@4.0.5/dist/redux.min.js</url>
                            <unpack>false</unpack>
                            <outputDirectory>${project.build.directory}/${project.build.finalName}/js</outputDirectory>
                            <md5>8e679dc2c2ea96e12f8189d85485927b</md5>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
```

<p>To spice things up you can add minification and babel preprocessing to your scripts with following pure java maven plugins:</p>

<pre class="lang-xml prettyprint-override"><code>            <plugin>
                <groupId>com.jarslab.maven</groupId>
                <artifactId>babel-maven-plugin</artifactId>
                <version>1.3</version>
                <executions>
                    <execution>
                        <id>js-transpile</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>babel</goal>
                        </goals>
                        <configuration>
                            <encoding>UTF-8</encoding>
                            <verbose>true</verbose>
                            <babelSrc>${project.basedir}/target/babel/package/babel.min.js</babelSrc>
                            <sourceDir>${project.basedir}/src/main/es6</sourceDir>
                            <targetDir>${project.build.directory}/js</targetDir>
                            <jsSourceIncludes>
                                <jsSourceInclude>*.js</jsSourceInclude>
                            </jsSourceIncludes>
                            <presets>es2015</presets>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.github.blutorange</groupId>
                <artifactId>closure-compiler-maven-plugin</artifactId>
                <version>2.12.0</version>
                <executions>
                    <execution>
                        <id>default-minify</id>
                        <phase>process-resources</phase>
                        <configuration>

                            <!-- These are the defaults -->
                            <encoding>UTF-8</encoding>
                            <baseSourceDir>${project.build.directory}</baseSourceDir>
                            <baseTargetDir>${project.build.directory}/${project.build.finalName}</baseTargetDir>
                            <sourceDir>js</sourceDir>
                            <targetDir>js</targetDir>

                            <!-- List of files to process. May use wildcards. -->
                            <includes>
                                <include>my-script.js</include>
                            </includes>
                            <outputFilename>my-script.min.js</outputFilename>

                        </configuration>

                        <goals>
                            <goal>minify</goal>
                        </goals>

                    </execution>
                </executions>
            </plugin>
</code>```

Hereby I would like to thank great plugin maintainers for their great job!

Mickael and others from for google download plugin: https://github.com/maven-download-plugin/maven-download-plugin

Milosz for babel-maven-plugin: https://github.com/jarslab/babel-maven-plugin

Andre for closure-compiler-maven-plugin: https://github.com/blutorange/closure-compiler-maven-plugin

Body:
One method is to use npm which involves incorporation of download/run of node and npm during your build. Other approach is to use maven itself and do not invoke any NodeJS processes.

For bigger projects where you have many npm dependencies which probably change a lot during development it's easier to use package.json descriptor and npm itself.

For smaller project where you just need on file I prefer to use simple maven plugin setup like this one for example:

        <plugins>
            <plugin>
                <groupId>com.googlecode.maven-download-plugin</groupId>
                <artifactId>download-maven-plugin</artifactId>
                <version>1.5.0</version>
                <executions>
                    <execution>
                        <id>download-babel-js</id>
                        <phase>initialize</phase>
                        <goals>
                            <goal>wget</goal>
                        </goals>
                        <configuration>
                            <url>
https://coporate.nexus.instance/repository/npm-proxy/babel-standalone/-/babel-standalone-6.26.0.tgz
                            </url>
                            <unpack>true</unpack>
                            <outputDirectory>${project.build.directory}/babel</outputDirectory>
                            <md5>ed714bb8253fc6056902d8d0afd6b106</md5>
                        </configuration>
                    </execution>

                    <execution>
                        <id>download-redux</id>
                        <phase>initialize</phase>
                        <goals>
                            <goal>wget</goal>
                        </goals>
                        <configuration>
                            <url>https://coporate.nexus.instance/repository/unpkg/redux@4.0.5/dist/redux.min.js</url>
                            <unpack>false</unpack>
                            <outputDirectory>${project.build.directory}/${project.build.finalName}/js</outputDirectory>
                            <md5>8e679dc2c2ea96e12f8189d85485927b</md5>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

To spice things up you can add minification and babel preprocessing to your scripts with following pure java maven plugins:

            <plugin>
                <groupId>com.jarslab.maven</groupId>
                <artifactId>babel-maven-plugin</artifactId>
                <version>1.3</version>
                <executions>
                    <execution>
                        <id>js-transpile</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>babel</goal>
                        </goals>
                        <configuration>
                            <encoding>UTF-8</encoding>
                            <verbose>true</verbose>
                            <babelSrc>${project.basedir}/target/babel/package/babel.min.js</babelSrc>
                            <sourceDir>${project.basedir}/src/main/es6</sourceDir>
                            <targetDir>${project.build.directory}/js</targetDir>
                            <jsSourceIncludes>
                                <jsSourceInclude>*.js</jsSourceInclude>
                            </jsSourceIncludes>
                            <presets>es2015</presets>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.github.blutorange</groupId>
                <artifactId>closure-compiler-maven-plugin</artifactId>
                <version>2.12.0</version>
                <executions>
                    <execution>
                        <id>default-minify</id>
                        <phase>process-resources</phase>
                        <configuration>

                            <!-- These are the defaults -->
                            <encoding>UTF-8</encoding>
                            <baseSourceDir>${project.build.directory}</baseSourceDir>
                            <baseTargetDir>${project.build.directory}/${project.build.finalName}</baseTargetDir>
                            <sourceDir>js</sourceDir>
                            <targetDir>js</targetDir>

                            <!-- List of files to process. May use wildcards. -->
                            <includes>
                                <include>my-script.js</include>
                            </includes>
                            <outputFilename>my-script.min.js</outputFilename>

                        </configuration>

                        <goals>
                            <goal>minify</goal>
                        </goals>

                    </execution>
                </executions>
            </plugin>

Hereby I would like to thank great plugin maintainers for their great job!

Mickael and others from for google download plugin: https://github.com/maven-download-plugin/maven-download-plugin

Milosz for babel-maven-plugin: https://github.com/jarslab/babel-maven-plugin

Andre for closure-compiler-maven-plugin: https://github.com/blutorange/closure-compiler-maven-plugin


答:
All containers in Python can be traversed like this:

```<code>d = { 1: 'Blue', 2: 'Green' }
for k in d:
  print(k)
</code>```

This will iterate over the keys of the dictionary, i.e. 1 and 2, and is equivalent to this:

```<code>for k in d.keys():
  print(k)
</code>```

If you need only the values, this will do:

```<code>for v in d.values():
  print(v)
</code>```

And if you need both key and value at the same time, use this:

```<code>for k, v in d.items():
  print(k, v)
</code>```

One major difference between sequences and unordered containers such as set or dict is that during traversal, there is no guaranteed order.

See https://docs.python.org/3.8/library/stdtypes.html#dict for more details on the dict API.

Title: "set is iterable,but set is not sequence"，I have some questions

Body:
I am reading the book fluent python. It says all collections such as list, set are iterable. But set is not a sequence. Dictionary is also not a sequence, that is to say, the item in sequence can not be accessed by index, such as set[9], am I right? It's a bit like both linked lists and lists can be traversed, but only arrays can quickly get values through an index. I was wondering How is dictionary traversed?

Please forgive me for my poor English

Body:
All containers in Python can be traversed like this:

d = { 1: 'Blue', 2: 'Green' }
for k in d:
  print(k)

This will iterate over the keys of the dictionary, i.e. 1 and 2, and is equivalent to this:

for k in d.keys():
  print(k)

If you need only the values, this will do:

for v in d.values():
  print(v)

And if you need both key and value at the same time, use this:

for k, v in d.items():
  print(k, v)

One major difference between sequences and unordered containers such as set or dict is that during traversal, there is no guaranteed order.

See https://docs.python.org/3.8/library/stdtypes.html#dict for more details on the dict API.


问:
Plotting Panda Dataframe into 3D bar chart
There is one existing answer to this question here but it is wrong.

In the example dataframe from the previous question, the US has the highest number of python users (10,110), yet in the graph it appears as though France has the highest instead.

Can someone help me fix the solutions code?

Data Frame

Resulting Graph (incorrect)

EXAMPLE DATAFRAME:

```<code>EG

Language    C     C++     Java    Python    Perl

Country

USA          3222   343     2112   10110      89

France      5432   323     1019     678        789

Japan       7878   467       767     8788       40
</code>```

INCORRECT CODE:

```<code>from mpl_toolkits.mplot3d import Axes3D

# thickness of the bars
dx, dy = .8, .8

# prepare 3d axes
fig = plt.figure(figsize=(10,6))
ax = Axes3D(fig)

# set up positions for the bars
xpos=np.arange(eg.shape[0])
ypos=np.arange(eg.shape[1])

# set the ticks in the middle of the bars
ax.set_xticks(xpos + dx/2)
ax.set_yticks(ypos + dy/2)

# create meshgrid
# print xpos before and after this block if not clear
xpos, ypos = np.meshgrid(xpos, ypos)
xpos = xpos.flatten()
ypos = ypos.flatten()

# the bars starts from 0 attitude
zpos=np.zeros(eg.shape).flatten()

# the bars' heights
dz = eg.values.ravel()

# plot
ax.bar3d(xpos,ypos,zpos,dx,dy,dz)

# put the column / index labels
ax.w_yaxis.set_ticklabels(eg.columns)
ax.w_xaxis.set_ticklabels(eg.index)

# name the axes
ax.set_xlabel('Country')
ax.set_ylabel('Language')
ax.set_zlabel('Count')

plt.show()
</code>```

答:
To solve it, just change the ravel part of the code:

```<code># the bars' heights
dz = eg.values.ravel(order='F')
</code>```

That order='F'reads the data correctly for your problem:

‘F’ means to index the elements in column-major, Fortran-style order,
  with the first index changing fastest, and the last index changing
  slowest.

The code you provided does not work as you expected because the xpos and ypos positional arrays are not sorted as the dz array obtained via eg.values.ravel():

```<code>eg.values.ravel()
>> array([ 3222,   343,  2112, 10110,    89,  5432,   323,  1019,   678,
         789,  7878,   467,   767,  8788,    40], dtype=int64)
</code>```

This array (the 'heights' of the chart) concatenates the values of eg's rows. In another terms, dz grabs eg terms in the following order:

(0,0), (0,1), (0,2), (0,3), (1,0)...

xpos and ypos, however, are listing values along the columns:

```<code>list(zip(xpos, ypos))
>>[(0, 0),(1, 0),(2, 0),(0, 1),(1, 1),(2, 1),(0, 2),...]
</code>```

So your values get incorrectly assigned. For instance, (1,0) - that is, France, C - received the value from (0,1) - USA, C++. That's why the values on the chart are messed up.

Hope it helps!

Body:
There is one existing answer to this question here but it is wrong.

In the example dataframe from the previous question, the US has the highest number of python users (10,110), yet in the graph it appears as though France has the highest instead.

Can someone help me fix the solutions code?

Data Frame

Resulting Graph (incorrect)

EXAMPLE DATAFRAME:

EG

Language    C     C++     Java    Python    Perl

Country

USA          3222   343     2112   10110      89

France      5432   323     1019     678        789

Japan       7878   467       767     8788       40

INCORRECT CODE:

from mpl_toolkits.mplot3d import Axes3D

# thickness of the bars
dx, dy = .8, .8

# prepare 3d axes
fig = plt.figure(figsize=(10,6))
ax = Axes3D(fig)

# set up positions for the bars
xpos=np.arange(eg.shape[0])
ypos=np.arange(eg.shape[1])

# set the ticks in the middle of the bars
ax.set_xticks(xpos + dx/2)
ax.set_yticks(ypos + dy/2)

# create meshgrid
# print xpos before and after this block if not clear
xpos, ypos = np.meshgrid(xpos, ypos)
xpos = xpos.flatten()
ypos = ypos.flatten()

# the bars starts from 0 attitude
zpos=np.zeros(eg.shape).flatten()

# the bars' heights
dz = eg.values.ravel()

# plot
ax.bar3d(xpos,ypos,zpos,dx,dy,dz)

# put the column / index labels
ax.w_yaxis.set_ticklabels(eg.columns)
ax.w_xaxis.set_ticklabels(eg.index)

# name the axes
ax.set_xlabel('Country')
ax.set_ylabel('Language')
ax.set_zlabel('Count')

plt.show()

Body:
To solve it, just change the ravel part of the code:

# the bars' heights
dz = eg.values.ravel(order='F')

That order='F'reads the data correctly for your problem:

‘F’ means to index the elements in column-major, Fortran-style order,
  with the first index changing fastest, and the last index changing
  slowest.

The code you provided does not work as you expected because the xpos and ypos positional arrays are not sorted as the dz array obtained via eg.values.ravel():

eg.values.ravel()
>> array([ 3222,   343,  2112, 10110,    89,  5432,   323,  1019,   678,
         789,  7878,   467,   767,  8788,    40], dtype=int64)

This array (the 'heights' of the chart) concatenates the values of eg's rows. In another terms, dz grabs eg terms in the following order:

(0,0), (0,1), (0,2), (0,3), (1,0)...

xpos and ypos, however, are listing values along the columns:

list(zip(xpos, ypos))
>>[(0, 0),(1, 0),(2, 0),(0, 1),(1, 1),(2, 1),(0, 2),...]

So your values get incorrectly assigned. For instance, (1,0) - that is, France, C - received the value from (0,1) - USA, C++. That's why the values on the chart are messed up.

Hope it helps!


问:
Azure Function CORS Policy not settings reponse headers
I just set a CORS policy for my all operations like this:

```<code><policies>
    <inbound>
        <base />
        <cors>
            <allowed-origins>
                <origin>http://localhost:3000</origin>
            </allowed-origins>
            <allowed-methods>
                <method>GET</method>
                <method>POST</method>
            </allowed-methods>
        </cors>
        <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Failed.">
            <openid-config url="https://*/.well-known/openid-configuration" />
            <audiences>
                <audience>ticket-spa</audience>
            </audiences>
            <issuers>
                <issuer>https://*/</issuer>
            </issuers>
        </validate-jwt>
        <set-header name="X-JWT-SUB" exists-action="override">
            <value>@(context.Request.Headers["Authorization"].First().Split(' ')[1].AsJwt()?.Claims["sub"].FirstOrDefault())</value>
        </set-header>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>
</code>```

However the OPTIONS request to https://*.azure-api.net/myFunctions/items?param=1
results in the following response:

```<code>HTTP/1.1 200 OK
Request-Context: appId=*
Date: Wed, 03 Jun 2020 07:22:47 GMT
Content-Length: 0
</code>```

Which results in the browser not allowing communicating with my API because the CORS headers are missing.

答:
Seems like I had to add a few allowed headers like this:

```<code><allowed-headers>
                <header>content-type</header>
                <header>accept</header>
                <header>x-tfs-fedauthredirect</header>
                <header>user-agent</header>
                <header>authorization</header>
            </allowed-headers>
</code>```

Still weird how there's no error indicating why this failed.

Body:
I just set a CORS policy for my all operations like this:

<policies>
    <inbound>
        <base />
        <cors>
            <allowed-origins>
                <origin>http://localhost:3000</origin>
            </allowed-origins>
            <allowed-methods>
                <method>GET</method>
                <method>POST</method>
            </allowed-methods>
        </cors>
        <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Failed.">
            <openid-config url="https://*/.well-known/openid-configuration" />
            <audiences>
                <audience>ticket-spa</audience>
            </audiences>
            <issuers>
                <issuer>https://*/</issuer>
            </issuers>
        </validate-jwt>
        <set-header name="X-JWT-SUB" exists-action="override">
            <value>@(context.Request.Headers["Authorization"].First().Split(' ')[1].AsJwt()?.Claims["sub"].FirstOrDefault())</value>
        </set-header>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

However the OPTIONS request to https://*.azure-api.net/myFunctions/items?param=1
results in the following response:

HTTP/1.1 200 OK
Request-Context: appId=*
Date: Wed, 03 Jun 2020 07:22:47 GMT
Content-Length: 0

Which results in the browser not allowing communicating with my API because the CORS headers are missing.

Body:
Seems like I had to add a few allowed headers like this:

<allowed-headers>
                <header>content-type</header>
                <header>accept</header>
                <header>x-tfs-fedauthredirect</header>
                <header>user-agent</header>
                <header>authorization</header>
            </allowed-headers>

Still weird how there's no error indicating why this failed.


问:
Check for sequence in column of Pandas DataFrame
My DataFrame looks like this:

```<code>    Category       Date
81    Monate 2020-01-01
88    Monate 2020-01-02
58    Monate 2020-01-03
3     Monate 2020-01-04
23    Monate 2020-01-05
..       ...        ...
134   Wochen 2020-05-24
145     Tage 2020-05-25
147     Tage 2020-05-26
146     Tage 2020-05-27
148     Tage 2020-05-28
</code>```

It is ordered by Date. I need to run a check if on each row Monate follows Monate, Wochen follows Wochen and so on. It is allowed that Wochen follows Monate and Tage follows Wochen. I hope it is clear that I mean. Something looks this should cause an error, since the sequence is invalid.

```<code>    Category       Date
81    Monate 2020-01-01
88    Monate 2020-01-02
58    Tage   2020-01-03
3     Monate 2020-01-04
23    Monate 2020-01-05
..       ...        ...
134   Wochen 2020-05-24
145     Tage 2020-05-25
147     Tage 2020-05-26
146   Wochen 2020-05-27
148     Tage 2020-05-28
</code>```

I could try to write a pretty complicated and probably slow iteration over each row.

```<code>for row in result_df.iterrows():
    do xyz
</code>```

Is there a better and quicker way to check for an ongoing sequence in a Series or a maybe in a list, dictionary etc.?

答:
I believe you can create a numeric dictionary stating the order and replace the values of the Category column and check if series.diff is never negative with series.all:

```<code>def check(dataframe):
    d = {'Monate':1,'Wochen':2,'Tage':3}
    return dataframe['Category'].replace(d).diff().fillna(0).ge(0).all()
</code>```

Test Runs:

```<code>print(df,'\n\n',f"Valid? : {check(df)}",'\n\n',df1,'\n\n',f"Valid? : {check(df1)}")

 Category        Date
81    Monate  2020-01-01
88    Monate  2020-01-02
58    Monate  2020-01-03
3     Monate  2020-01-04
23    Monate  2020-01-05
134   Wochen  2020-05-24
145     Tage  2020-05-25
147     Tage  2020-05-26
146     Tage  2020-05-27
148     Tage  2020-05-28

 Valid? : True

     Category        Date
81    Monate  2020-01-01
88    Monate  2020-01-02
58      Tage  2020-01-03
3     Monate  2020-01-04
23    Monate  2020-01-05
134   Wochen  2020-05-24
145     Tage  2020-05-25
147     Tage  2020-05-26
146   Wochen  2020-05-27
148     Tage  2020-05-28

 Valid? : False
</code>```

Body:
My DataFrame looks like this:

    Category       Date
81    Monate 2020-01-01
88    Monate 2020-01-02
58    Monate 2020-01-03
3     Monate 2020-01-04
23    Monate 2020-01-05
..       ...        ...
134   Wochen 2020-05-24
145     Tage 2020-05-25
147     Tage 2020-05-26
146     Tage 2020-05-27
148     Tage 2020-05-28

It is ordered by Date. I need to run a check if on each row Monate follows Monate, Wochen follows Wochen and so on. It is allowed that Wochen follows Monate and Tage follows Wochen. I hope it is clear that I mean. Something looks this should cause an error, since the sequence is invalid.

    Category       Date
81    Monate 2020-01-01
88    Monate 2020-01-02
58    Tage   2020-01-03
3     Monate 2020-01-04
23    Monate 2020-01-05
..       ...        ...
134   Wochen 2020-05-24
145     Tage 2020-05-25
147     Tage 2020-05-26
146   Wochen 2020-05-27
148     Tage 2020-05-28

I could try to write a pretty complicated and probably slow iteration over each row.

for row in result_df.iterrows():
    do xyz

Is there a better and quicker way to check for an ongoing sequence in a Series or a maybe in a list, dictionary etc.?

Body:
I believe you can create a numeric dictionary stating the order and replace the values of the Category column and check if series.diff is never negative with series.all:

def check(dataframe):
    d = {'Monate':1,'Wochen':2,'Tage':3}
    return dataframe['Category'].replace(d).diff().fillna(0).ge(0).all()

Test Runs:

print(df,'\n\n',f"Valid? : {check(df)}",'\n\n',df1,'\n\n',f"Valid? : {check(df1)}")

 Category        Date
81    Monate  2020-01-01
88    Monate  2020-01-02
58    Monate  2020-01-03
3     Monate  2020-01-04
23    Monate  2020-01-05
134   Wochen  2020-05-24
145     Tage  2020-05-25
147     Tage  2020-05-26
146     Tage  2020-05-27
148     Tage  2020-05-28

 Valid? : True

     Category        Date
81    Monate  2020-01-01
88    Monate  2020-01-02
58      Tage  2020-01-03
3     Monate  2020-01-04
23    Monate  2020-01-05
134   Wochen  2020-05-24
145     Tage  2020-05-25
147     Tage  2020-05-26
146   Wochen  2020-05-27
148     Tage  2020-05-28

 Valid? : False


问:
SafetyNet offline verification
I am trying to follow the example here to perform an offline verification (https://github.com/googlesamples/android-play-safetynet/blob/master/server/java/src/main/java/OfflineVerify.java). However, when I tried to import the following classes, Android Studio indicated unresolved references

```<code>import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.webtoken.JsonWebSignature;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
</code>```

The unresolved references were api and DefaultHostnameVerifier.

Am I missing some settings?

答:
Because the SDK where the DefaultHostnameVerifier class is located is not synchronized in the local Android studio.
You need to add the dependency of two SDKs, google-http-client-jackson2 and httpclient, in the gradle file. You can see the corresponding configuration on GitHub:

https://github.com/googlesamples/android-play-safetynet/blob/master/server/java/build.gradle

```<code>dependencies {
    compile 'com.google.http-client:google-http-client-jackson2:1.22.0'

    // Apache HttpClient is used to verify the hostname against the signed certificate in OfflineVerify.
    compile 'org.apache.httpcomponents:httpclient:4.5.2'
}
</code>```

Title: SafetyNet offline verification

Body:
I am trying to follow the example here to perform an offline verification (https://github.com/googlesamples/android-play-safetynet/blob/master/server/java/src/main/java/OfflineVerify.java). However, when I tried to import the following classes, Android Studio indicated unresolved references

import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.webtoken.JsonWebSignature;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;

The unresolved references were api and DefaultHostnameVerifier.

Am I missing some settings?

Body:
Because the SDK where the DefaultHostnameVerifier class is located is not synchronized in the local Android studio.
You need to add the dependency of two SDKs, google-http-client-jackson2 and httpclient, in the gradle file. You can see the corresponding configuration on GitHub:

https://github.com/googlesamples/android-play-safetynet/blob/master/server/java/build.gradle

dependencies {
    compile 'com.google.http-client:google-http-client-jackson2:1.22.0'

    // Apache HttpClient is used to verify the hostname against the signed certificate in OfflineVerify.
    compile 'org.apache.httpcomponents:httpclient:4.5.2'
}


问:
Pandas - Read only first few lines of each rows
I have a large CSV file with about 10000 rows of text information and each row of my dataset consists of a number of lines. However I just want to read say first 20 lines of each of the rows of my CSV file.

I came across n_rows parameter in pandas read_csv method which helps us in limiting the number of rows of the dataset that we would like to load. Is there also a way where we could only read first 20 lines of data from each of the rows in pandas?

答:
If TiTo's answer is not what you are looking for, maybe the iloc method is. You can store the first 20 rows by doing firstRows = df.iloc[:20].

However, if you only ever need the first 20 rows, you shouldn't load the whole file into memory. As you mentioned, this can be achieved with the nrows parameter.


问:
Left join using hibernate criteria
I have two entity: Issue and Issue_Tracker. I am using Hibernate 3.6.

```<code>SELECT `issues`.`issue_id`,
       `issues`.`issue_raised_date`,
       `issues`.`issue_description`,
       `issue_tracker`.`tracker_status`
FROM `issues`
   LEFT JOIN  `issue_tracker` ON `issues`.`issue_id` = `issue_tracker`.`issue_id`
WHERE `issues`.`status`="Escalate To"
</code>```

How to achieve this using Hibernate Criteria, and most Important, I have to use it for pagination.

and My Dao is as follows to show the list of Issues in jqgrid

public List showHelpDeskIssues(DetachedCriteria dc, int from,
  int size) {

```<code>Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 try
  {

    Criteria criteria = dc.getExecutableCriteria(session);
    criteria.setFirstResult(from);
    criteria.setMaxResults(size);
    criteria.add(Restrictions.eq("status","Escalate To"));

    return criteria.list();
  }
  catch (HibernateException e)
  {
    e.printStackTrace();
    throw e;
  } }
</code>```

For brief explanation please refer this question how to show two tables data in jqgrid using struts2 - jqgrid plugin and hibernate
any help would be great.

答:
Note: In Hibernate criteria, inner outer join and inner join are one and the same. Do not get confused.

```<code>Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 try{
     Criteria criteria = session.createCriteria(Issues.class, "issues");
     criteria.setFirstResult(from);
     criteria.setMaxResults(size);
     criteria.createAlias("issues.issuestracker", "issuestracker", JoinType.LEFT_OUTER_JOIN);
     criteria.add(Restrictions.eq("issues.status", "Escalate To"));

     return criteria.list();
   }catch(HibernateException e){
       e.printStackTrace();
       throw e;
     }
</code>```

This should solve your issue. Let me know if you face any trouble.

Title: Left join using hibernate criteria

Body:
I have two entity: Issue and Issue_Tracker. I am using Hibernate 3.6.

SELECT `issues`.`issue_id`,
       `issues`.`issue_raised_date`,
       `issues`.`issue_description`,
       `issue_tracker`.`tracker_status`
FROM `issues`
   LEFT JOIN  `issue_tracker` ON `issues`.`issue_id` = `issue_tracker`.`issue_id`
WHERE `issues`.`status`="Escalate To"

How to achieve this using Hibernate Criteria, and most Important, I have to use it for pagination.

and My Dao is as follows to show the list of Issues in jqgrid

public List showHelpDeskIssues(DetachedCriteria dc, int from,
  int size) {

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 try
  {

    Criteria criteria = dc.getExecutableCriteria(session);
    criteria.setFirstResult(from);
    criteria.setMaxResults(size);
    criteria.add(Restrictions.eq("status","Escalate To"));

    return criteria.list();
  }
  catch (HibernateException e)
  {
    e.printStackTrace();
    throw e;
  } }

For brief explanation please refer this question how to show two tables data in jqgrid using struts2 - jqgrid plugin and hibernate
any help would be great.

Body:
Note: In Hibernate criteria, inner outer join and inner join are one and the same. Do not get confused.

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 try{
     Criteria criteria = session.createCriteria(Issues.class, "issues");
     criteria.setFirstResult(from);
     criteria.setMaxResults(size);
     criteria.createAlias("issues.issuestracker", "issuestracker", JoinType.LEFT_OUTER_JOIN);
     criteria.add(Restrictions.eq("issues.status", "Escalate To"));

     return criteria.list();
   }catch(HibernateException e){
       e.printStackTrace();
       throw e;
     }

This should solve your issue. Let me know if you face any trouble.


问:
Load image in a movieclip inside a movieclip
for some strange reasons I'm here to develop a desktop app in as3, and I am really rusty on it.
I can not remember how to load an image inside a slider that contains 6 thumbs.
This thumbs are movieclips (named icon1, icon2, icon3...etc) that contains a transparent button and an empty movieclip (named image) that should contains the image.
This image have to be loaded dynamically.
The following is the code I did:

```<code>var count = 1;

for (var i = 1; i < 7; i++) {
    var request: URLRequest = new URLRequest('img/img'+i+'.jpg');
    var loader: Loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoadComplete);
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);
    loader.load(request);
    count++;
}

function onImageLoadComplete(e: Event): void {
    trace('onImageLoadComplete()');
    var loaderInfo: LoaderInfo = LoaderInfo(e.target);
    loaderInfo.removeEventListener(Event.COMPLETE, onImageLoadComplete);
    loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);

    var bitmap: Bitmap = Bitmap(loaderInfo.content);
    slider["icon" + count]["image"].addChild(bitmap); ///at this line there's the error
}

function onImageLoadError(e: IOErrorEvent): void {
    trace('onImageLoadError(): ' + e.text);
    var loaderInfo: LoaderInfo = LoaderInfo(e.target);
    loaderInfo.removeEventListener(Event.COMPLETE, onImageLoadComplete);
    loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);
}
</code>```

but no way, doesn't work the error is: Error #1010:A term is undefined and has no properties.
I tried also:

1)

```<code>slider["icon" + count].image.addChild(bitmap);
</code>```

2)

```<code>var mc:MovieClip = ("icon"+ cont)as MovieClip;
slider.mc.image.addChild(bitmap);
</code>```

please, if someone still remember as3 help me!

答:
Thanks to the @Organis's answer, that put me in the right direction, I changed the place where the count was incremented, and now it works.
This is the right code:</p>

```<code>var count = 1;

for (var i = 1; i < 7; i++) {
    var request: URLRequest = new URLRequest('img/img'+i+'.jpg');
    var loader: Loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoadComplete);
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);
    loader.load(request);

}

function onImageLoadComplete(e: Event): void {
    trace('onImageLoadComplete()');
    var loaderInfo: LoaderInfo = LoaderInfo(e.target);
    loaderInfo.removeEventListener(Event.COMPLETE, onImageLoadComplete);
    loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);

    var bitmap: Bitmap = Bitmap(loaderInfo.content);
    slider["icon" + count]["image"].addChild(bitmap);
    count++;
}

function onImageLoadError(e: IOErrorEvent): void {
    trace('onImageLoadError(): ' + e.text);
    var loaderInfo: LoaderInfo = LoaderInfo(e.target);
    loaderInfo.removeEventListener(Event.COMPLETE, onImageLoadComplete);
    loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);
}
</code>```

Body:
for some strange reasons I'm here to develop a desktop app in as3, and I am really rusty on it.
I can not remember how to load an image inside a slider that contains 6 thumbs.
This thumbs are movieclips (named icon1, icon2, icon3...etc) that contains a transparent button and an empty movieclip (named image) that should contains the image.
This image have to be loaded dynamically.
The following is the code I did:

var count = 1;

for (var i = 1; i < 7; i++) {
    var request: URLRequest = new URLRequest('img/img'+i+'.jpg');
    var loader: Loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoadComplete);
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);
    loader.load(request);
    count++;
}

function onImageLoadComplete(e: Event): void {
    trace('onImageLoadComplete()');
    var loaderInfo: LoaderInfo = LoaderInfo(e.target);
    loaderInfo.removeEventListener(Event.COMPLETE, onImageLoadComplete);
    loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);

    var bitmap: Bitmap = Bitmap(loaderInfo.content);
    slider["icon" + count]["image"].addChild(bitmap); ///at this line there's the error
}

function onImageLoadError(e: IOErrorEvent): void {
    trace('onImageLoadError(): ' + e.text);
    var loaderInfo: LoaderInfo = LoaderInfo(e.target);
    loaderInfo.removeEventListener(Event.COMPLETE, onImageLoadComplete);
    loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);
}

but no way, doesn't work the error is: Error #1010:A term is undefined and has no properties.
I tried also:

1)

slider["icon" + count].image.addChild(bitmap);

2)

var mc:MovieClip = ("icon"+ cont)as MovieClip;
slider.mc.image.addChild(bitmap);

please, if someone still remember as3 help me!

Body:
Thanks to the @Organis's answer, that put me in the right direction, I changed the place where the count was incremented, and now it works.
This is the right code:

var count = 1;

for (var i = 1; i < 7; i++) {
    var request: URLRequest = new URLRequest('img/img'+i+'.jpg');
    var loader: Loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoadComplete);
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);
    loader.load(request);

}

function onImageLoadComplete(e: Event): void {
    trace('onImageLoadComplete()');
    var loaderInfo: LoaderInfo = LoaderInfo(e.target);
    loaderInfo.removeEventListener(Event.COMPLETE, onImageLoadComplete);
    loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);

    var bitmap: Bitmap = Bitmap(loaderInfo.content);
    slider["icon" + count]["image"].addChild(bitmap);
    count++;
}

function onImageLoadError(e: IOErrorEvent): void {
    trace('onImageLoadError(): ' + e.text);
    var loaderInfo: LoaderInfo = LoaderInfo(e.target);
    loaderInfo.removeEventListener(Event.COMPLETE, onImageLoadComplete);
    loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onImageLoadError);
}


问:
Media query/any other solution to apply CSS on both pop-up and desktop
I have the same content to be displayed on a pop-up and desktop view.
I already used media queries to adjust the content on desktop/mobile view. But in desktop view, the same content needs to be displayed on a pop-up with different margins.
How can I achieve this? Please help. Thank you.</p>

答:
Just add different margin that will overwrite default one based on parent class of the component - in your case it will be pop-up class.

If you do not want to increase CSS specificity - you may try add class modificator (eg component--big-margin) if you are using CSS methodology like BEM.