问:
How to compare input and Document in mongoDB
When I Register [ input Email / password to DB ] success. Then, I want to login. If input[email/pass] == document in collection >> go to next page, else console.log['wrong email/pass']

I try to wirte IF/else code but I don't know check condition.

This code is Register form

```<code>app.post('/register',function(req,res){
    MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");
  let myobj = { Email: req.body.email, Password: req.body.psw } ;

  dbo.collection("Register").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log(" document inserted");
    db.close();
  });
});

});
</code>```

This code is Login form

```<code>app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");

  let cursor = dbo.collection('Register').find();
   cursor.each(function(err,doc) {
    if (doc == req.body.email && req.body.psw){
      console.log("goto next page");

    }
    else{
      console.log('wrong');
    }

   });
    db.close();
  });
});
</code>```

Correct input and wrong input Output is = Wrong

Pls insert loop check all of array pls.

```<code>app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({}, function(err, result) {

    if (result.Email == req.body.email && result.Password == req.body.psw) {
      console.log("OK");
    }
    else{
      console.log(result.Email && result.Password);
    }
    db.close();
  });
});
});
</code>```

答:
You have to compare individual values, like so:</p>

```<code>if (doc.Email == req.body.email &&  doc.Password == req.body.psw){
  console.log("goto next page");

}
</code>```

Body:
When I Register [ input Email / password to DB ] success. Then, I want to login. If input[email/pass] == document in collection >> go to next page, else console.log['wrong email/pass']

I try to wirte IF/else code but I don't know check condition.

This code is Register form

app.post('/register',function(req,res){
    MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");
  let myobj = { Email: req.body.email, Password: req.body.psw } ;

  dbo.collection("Register").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log(" document inserted");
    db.close();
  });
});

});

This code is Login form

app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");

  let cursor = dbo.collection('Register').find();
   cursor.each(function(err,doc) {
    if (doc == req.body.email && req.body.psw){
      console.log("goto next page");

    }
    else{
      console.log('wrong');
    }

   });
    db.close();
  });
});

Correct input and wrong input Output is = Wrong

Pls insert loop check all of array pls.

app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({}, function(err, result) {

    if (result.Email == req.body.email && result.Password == req.body.psw) {
      console.log("OK");
    }
    else{
      console.log(result.Email && result.Password);
    }
    db.close();
  });
});
});

Body:
You have to compare individual values, like so:

if (doc.Email == req.body.email &&  doc.Password == req.body.psw){
  console.log("goto next page");

}


来源: stackexchange

问:
Why to put a property variable in the constructor
From other languages I am used to code a class property and afterwards I can access this without having it in the constructor like

```<code>Class MyClass:
    def __init__(self):
        self._value = 0
    @property
    my_property(self):
        print('I got the value:' & self._value)
</code>```

In almost every example I worked through the property variable was in the constructor self._value like this

```<code>Class MyClass:
    def __init__(self, value = 0):
        self._value = value
</code>```

To me this makes no sence since you want to set it in the property. Could anyone explain to me what is the use of placing the value variable in the constructor?

答:
Because @property is not a decorator for a variable, it is a decorator for function that allows it to behave like a property. You still need to create a class variable to use a function decorated by @property:

The @property decorator turns the voltage() method into a “getter” for a read-only attribute with the same name, and it sets the docstring for voltage to “Get the current voltage.”

A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example:

ContentLicense: CC BY-SA 4.0

Body:
From other languages I am used to code a class property and afterwards I can access this without having it in the constructor like

Class MyClass:
    def __init__(self):
        self._value = 0
    @property
    my_property(self):
        print('I got the value:' & self._value)

In almost every example I worked through the property variable was in the constructor self._value like this

Class MyClass:
    def __init__(self, value = 0):
        self._value = value

To me this makes no sence since you want to set it in the property. Could anyone explain to me what is the use of placing the value variable in the constructor?


问:
How to display inputted text along with some constant text in typing effect?
I am taking input using prompt and saving it in "a"
see:

```<code><script type="text/javascript" language="Javascript">
    var a=prompt("Please Enter Your Name ");
</script>
</code>```

and then i want the text stored in "a" and some text like "blah blah blah" printed in a single line with typewriter effect of css.

html {
  min-height: 100%;
  overflow: hidden;
}

body {
  display: flex;
  background-repeat: no-repeat;
  /* background-attachment: fixed;*/
  background-image: radial-gradient(black, white);
}

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation:
  typing 3.5s steps(40, end),
  blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <script type="text/javascript" language="Javascript">
    var a = prompt("Please Enter Your Name ");
  </script>
  <div class="typewriter">
    <h1>
      <script>
        docment.write(a)
      </script>blah blah
    </h1>
  </div>
</body></code>```

When i run it i onle see blah blah blah ani mation not the text stored in "a"

答:
There is a typo in your code please check developer console for errors.

```<code>{
  "message": "Uncaught ReferenceError: docment is not defined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 60,
  "colno": 17
}
</code>```

html {
      min-height: 100%;
      overflow: hidden;
}
body
    {
        display: flex;
        background-repeat: no-repeat;
       /* background-attachment: fixed;*/
        background-image: radial-gradient(black,white);
    }

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
     animation:
    typing 3.5s steps(40, end),
    blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange; }
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<!--Google Analytics code Here -->
<title>HAPPY INDEPENDANCE DAY</title>
<link rel="stylesheet" href="full.css">

</head>
<body>
    <script type="text/javascript" language="Javascript">
                 var a=prompt("Please Enter Your Name ");
                </script>
<div class="typewriter">
    <h1><script>document.write(a) </script> blah blah</h1>
</div>
</body>
</html></code>```

Body:
I am taking input using prompt and saving it in "a"
see:

and then i want the text stored in "a" and some text like "blah blah blah" printed in a single line with typewriter effect of css.

html {
  min-height: 100%;
  overflow: hidden;
}

body {
  display: flex;
  background-repeat: no-repeat;
  /* background-attachment: fixed;*/
  background-image: radial-gradient(black, white);
}

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation:
  typing 3.5s steps(40, end),
  blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange; }
}

      blah blah

When i run it i onle see blah blah blah ani mation not the text stored in "a"

Body:
There is a typo in your code please check developer console for errors.

{
  "message": "Uncaught ReferenceError: docment is not defined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 60,
  "colno": 17
}

html {
      min-height: 100%;
      overflow: hidden;
}
body
    {
        display: flex;
        background-repeat: no-repeat;
       /* background-attachment: fixed;*/
        background-image: radial-gradient(black,white);
    }

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  color: #fff;
  font-family: monospace;
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
     animation:
    typing 3.5s steps(40, end),
    blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange; }
}
}

<html>
<head>
<!--Google Analytics code Here -->
<title>HAPPY INDEPENDANCE DAY</title>
<link rel="stylesheet" href="full.css">

</head>
<body>
    <script type="text/javascript" language="Javascript">
                 var a=prompt("Please Enter Your Name ");
                </script>
<div class="typewriter">
    <h1><script>document.write(a) </script> blah blah</h1>
</div>
</body>
</html>


问:
How can I reverse the Excel time function to hour, minute and second?
In Excel I use the following function

Time( hour, minute, second )

And it appears in the following format

11:07:27 AM

However when I treat excel as an ODBC data source and use getString to retrieve the value, it comes out something like

0.45856481481

How can I reverse this back to hours, minutes and seconds?

答:
For starters, see the SO question/answer for Excel parsing (xls) date error for an explanation of date time formats in Excel; this will explain where that number you are seeing is coming from.  Your problem is just a variation; numbers to the right of a decimal are an indicator of time measured as a fraction of a day.

I am going to assume you are using Java (based on the clues in your post), though your post isn't tagged with a programming language.

You should not use getString() to return a date value because this method simply returns the string representation of the underlying data (in this case, the number); you should use getDate() instead, which will translate the number into a date.

ContentLicense: CC BY-SA 3.0


问:
In a Neural Network if the input is > 1 or < -1 then should an activation function be applied before propagation?
I am creating my first ANN and am using the 'stock standard' Iris flower data sheet. Some of the input are as follows: 1.3, 4.0, 2.8, etc.

Should these values be placed through an activation function so they are <1 and will propagating without this cause any problems?

Cheers in advance

答:
Normalization removes geometrical biases towards some of the dimensions of the data vectors. In this way every bit of data gets treated in a "fair" manner. Another way of posing this is to realize that all learning algorithms depend on numerical properties so one should try to avoid small numbers, large numbers, and large differences.

If you do not normalize your inputs between (0,1) or (-1,1) you could not equally distribute importance of each input,  thus naturally  large values become dominant according to less values during ANN training.

The important thing is comparability  of inputs.  For example there are two inputs to your ann, x1 and x2. x1 varies from to 0 to 0.5 and x2 varies from 0 to 1000. A change of x1 of 0.5  is 100 percent change where as a change of x2 by 0.5 is only a change of 0.05%. Hence normalization helps.


问:
How to compute a HMAC SHA256 in c#
Edit: I've fixed the ascii encoding as pointed out by @DavidG

I'm creating an integration towards a vendor and the integration requires me to sign the message with a HMAC-SHA256 algorithm.

The simple test I've got from the vendor is that we're going to use this data:

```<code>key: "1234567890ABCDEF1234567890ABCDEF" (hex)
data: "00000000" (ascii)
expected output (only first 32 chars): FF365893D899291C3BF505FB3175E880 (hex)
</code>```

I've checked a number of online hmac generators and found them to return different results for me, some correct and some incorrect.

```<code>Correct reply: https://www.liavaag.org/English/SHA-Generator/HMAC/
Correct reply: https://cryptii.com/pipes/hmac
Incorrect reply: https://codebeautify.org/hmac-generator
Incorrect reply: http://billatnapier.com/security01.aspx
</code>```

Can anyone help me or point me in the right direction here? This is causing me to become bald very soon...

```<code>    [TestClass()]
    public class AutogiroConcentFileWriterTests
    {
        [TestMethod()]
        public void ManualKVVTest()
        {
            String key = "1234567890ABCDEF1234567890ABCDEF";
            String message = "00000000";
            String expected = "FF365893D899291C3BF505FB3175E880";

            Encoding ascii = Encoding.ASCII;
            Byte[] key_bytes = this.KeyData(key);

            Byte[] message_bytes = ascii.GetBytes(message);

            System.Security.Cryptography.HMACSHA256 hmacSHA256 = new System.Security.Cryptography.HMACSHA256(key_bytes);
            Byte[] hash = hmacSHA256.ComputeHash(message_bytes);
            String data = this.ByteToString(hash);

            // only compare first 32 chars of the hash
            Assert.AreEqual(expected, data.Substring(0, 32));

            //Assert.AreEqual failed.
            //Expected:<FF365893D899291C3BF505FB3175E880>.
            //Actual:<997BBD8C79F0D98FCA6470723CDB65D3>.
        }

        private Byte[] KeyData(String key)
        {
            if (key.Length % 2 == 1)
                throw new Exception("The binary key cannot have an odd number of digits");

            byte[] arr = new byte[key.Length >> 1];

            Int32 pos = 0;
            for (int i = 0; i < key.Length; i += 2)
            {
                Int32 b1 = key[i] - (key[i] < 58 ? 48 : 55);
                Int32 b2 = key[i + 1] - (key[i + 1] < 58 ? 48 : 55);
                arr[pos++] = (byte)((b1 << 4) + b2);
            }

            return arr;
        }

        private String ByteToString(Byte[] buff)
        {
            Char[] retval = new char[buff.Length * 2];
            for (int i = 0; i < buff.Length; i++)
            {
                String t = buff[i].ToString("X2");
                retval[i * 2] = t[0];
                retval[i * 2 + 1] = t[1];
            }
            return new String(retval);
        }
    }
</code>```

答:
You are converting your key directly to bytes rather than interpreting it as a hex string. Using a string-to-bytes function from here:

```<code>public static byte[] StringToByteArray(string hex)
{
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}
</code>```

Change your code to this:

```<code>Byte[] key_bytes = StringToByteArray(key);
</code>```

Title: How to compute a HMAC SHA256 in c#

Body:
Edit: I've fixed the ascii encoding as pointed out by @DavidG

I'm creating an integration towards a vendor and the integration requires me to sign the message with a HMAC-SHA256 algorithm.

The simple test I've got from the vendor is that we're going to use this data:

key: "1234567890ABCDEF1234567890ABCDEF" (hex)
data: "00000000" (ascii)
expected output (only first 32 chars): FF365893D899291C3BF505FB3175E880 (hex)

I've checked a number of online hmac generators and found them to return different results for me, some correct and some incorrect.

Correct reply: https://www.liavaag.org/English/SHA-Generator/HMAC/
Correct reply: https://cryptii.com/pipes/hmac
Incorrect reply: https://codebeautify.org/hmac-generator
Incorrect reply: http://billatnapier.com/security01.aspx

Can anyone help me or point me in the right direction here? This is causing me to become bald very soon...

    [TestClass()]
    public class AutogiroConcentFileWriterTests
    {
        [TestMethod()]
        public void ManualKVVTest()
        {
            String key = "1234567890ABCDEF1234567890ABCDEF";
            String message = "00000000";
            String expected = "FF365893D899291C3BF505FB3175E880";

            Encoding ascii = Encoding.ASCII;
            Byte[] key_bytes = this.KeyData(key);

            Byte[] message_bytes = ascii.GetBytes(message);

            System.Security.Cryptography.HMACSHA256 hmacSHA256 = new System.Security.Cryptography.HMACSHA256(key_bytes);
            Byte[] hash = hmacSHA256.ComputeHash(message_bytes);
            String data = this.ByteToString(hash);

            // only compare first 32 chars of the hash
            Assert.AreEqual(expected, data.Substring(0, 32));

            //Assert.AreEqual failed.
            //Expected:<FF365893D899291C3BF505FB3175E880>.
            //Actual:<997BBD8C79F0D98FCA6470723CDB65D3>.
        }

        private Byte[] KeyData(String key)
        {
            if (key.Length % 2 == 1)
                throw new Exception("The binary key cannot have an odd number of digits");

            byte[] arr = new byte[key.Length >> 1];

            Int32 pos = 0;
            for (int i = 0; i < key.Length; i += 2)
            {
                Int32 b1 = key[i] - (key[i] < 58 ? 48 : 55);
                Int32 b2 = key[i + 1] - (key[i + 1] < 58 ? 48 : 55);
                arr[pos++] = (byte)((b1 << 4) + b2);
            }

            return arr;
        }

        private String ByteToString(Byte[] buff)
        {
            Char[] retval = new char[buff.Length * 2];
            for (int i = 0; i < buff.Length; i++)
            {
                String t = buff[i].ToString("X2");
                retval[i * 2] = t[0];
                retval[i * 2 + 1] = t[1];
            }
            return new String(retval);
        }
    }

Body:
You are converting your key directly to bytes rather than interpreting it as a hex string. Using a string-to-bytes function from here:

public static byte[] StringToByteArray(string hex)
{
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

Change your code to this:

Byte[] key_bytes = StringToByteArray(key);


问:
How to find cpu and ram usage in Kubernetes deployment
My Kubernetes cluster is failing to deploy new applications with insufficient CPU on the cluster

After digging around rancher and kubectl I have found that I am using 5% of CPU, but Reserved 96% CPU.

This is due to wrongly configured values in my micro-services values.yaml

If there a way to find out how much the micro-services are using when idle and when at load

```<code>resources:
  requests:
    memory: {{ .Values.resources.requests.memory | quote}}
    cpu: {{ .Values.resources.requests.cpu | quote}}

  limits:
    memory: {{ .Values.resources.limits.memory | quote}}
    cpu: {{ .Values.resources.requests.cpu | quote}}
</code>```

I have tried using kubectl to describe the node
I am monitoring netdata, but that is real time and hard to gauge limits from that.

If anyone had suggestions, that would be great

答: The built in tool is kubectl top but this requires you have metrics-server running, which you probably do if you are using a hosted kube option but might not if running it yourself. Beyond that, Prometheus and tools like node-exporter and cadvisor can get you the data

Body:
My Kubernetes cluster is failing to deploy new applications with insufficient CPU on the cluster

After digging around rancher and kubectl I have found that I am using 5% of CPU, but Reserved 96% CPU.

This is due to wrongly configured values in my micro-services values.yaml

If there a way to find out how much the micro-services are using when idle and when at load

resources:
  requests:
    memory: {{ .Values.resources.requests.memory | quote}}
    cpu: {{ .Values.resources.requests.cpu | quote}}

  limits:
    memory: {{ .Values.resources.limits.memory | quote}}
    cpu: {{ .Values.resources.requests.cpu | quote}}

I have tried using kubectl to describe the node
I am monitoring netdata, but that is real time and hard to gauge limits from that.

If anyone had suggestions, that would be great


问:
What is the best way to do french text analysis in Python?
I want to do text analysis on a french texts to visualise similarities between those texts, the possible class depending on the words that are used.
I ask for your help because I just started working with Python and I would like to know the best way to do text analysis in Python taking into account that my texts are in French ?

Are there libraries specially designed for french texts ? The uses would be to clean the data, and further to analyse the data.

I can already :

Clean: Removed all special  characters, put every word in lowercase and suppressed STOPWORDS

Tag : It's not optimal on french words (Libraries tested : StanfordPostagger, Tag.pos de NLTK).

Lemmatize : Not optimal (--) with french words(FrenchLefffLemmatizer,  WordNetLemmatizer)

Stemming: FrenchStemmer snowball

What I can't do with French words : pass to singular, pass verbs to the infinitive form...

答:
Spacy library and Treetagger tool (that you can use through treetaggerwrapper library) have good french support.

Example using spacy :

```<code>import spacy
nlp_fr = spacy.load('fr_core_news_sm')
text = "J'ai mangé des pommes hier"
tokens = nlp_fr(text)
for token in tokens:
    print(token.lemma_)
</code>```

Prints :

```<code>je
avoir
manger
un
pomme
hier
</code>```

Treetagger is more difficult to install but this can help you and here is the documentation of the python wrapper.

Body:
Spacy library and Treetagger tool (that you can use through treetaggerwrapper library) have good french support.

Example using spacy :

import spacy
nlp_fr = spacy.load('fr_core_news_sm')
text = "J'ai mangé des pommes hier"
tokens = nlp_fr(text)
for token in tokens:
    print(token.lemma_)

Prints :

je
avoir
manger
un
pomme
hier

Treetagger is more difficult to install but this can help you and here is the documentation of the python wrapper.


问:
MySQL SELECT statement only returning one row
I know for certain that there are two rows of data in my table that meet the condition of the where clause, yet my coding is only outputting (echoing) one row. What am I doing wrong?   </p>

```<code><?php

$connect= mysqli_connect("localhost", "root", "", "friends_list")
or die('error connecting with the database');

$query= "SELECT * FROM people WHERE age=19";

$result= mysqli_query($connect, $query)
or die('error querying the database');

$row= mysqli_fetch_array($result);

while ($row = mysqli_fetch_array($result))
{
echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "<br/>"
}
mysqli_close($connect);

?>
</code>```

答:
```<code><?php
    $connect= mysqli_connect("localhost", "root", "", "friends_list")
    or die('error connecting with the database');

    $query= "SELECT * FROM people WHERE age=19";

    $result= mysqli_query($connect, $query)
    or die('error querying the database');

    while ($row = $result->fetch_assoc()){
        echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "<br/>"
    }
    mysqli_close($connect);
?>
</code>```

$result->fetch_assoc() will fetch everything that match the sql condition, and you can prevent further error like you did in the above.
You can learn more here fetch_assoc() function

Body:
I know for certain that there are two rows of data in my table that meet the condition of the where clause, yet my coding is only outputting (echoing) one row. What am I doing wrong?

<?php

$connect= mysqli_connect("localhost", "root", "", "friends_list")
or die('error connecting with the database');

$query= "SELECT * FROM people WHERE age=19";

$result= mysqli_query($connect, $query)
or die('error querying the database');

$row= mysqli_fetch_array($result);

while ($row = mysqli_fetch_array($result))
{
echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "
"
}
mysqli_close($connect);

?>

Body:
<?php
    $connect= mysqli_connect("localhost", "root", "", "friends_list")
    or die('error connecting with the database');

    $query= "SELECT * FROM people WHERE age=19";

    $result= mysqli_query($connect, $query)
    or die('error querying the database');

    while ($row = $result->fetch_assoc()){
        echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "<br/>"
    }
    mysqli_close($connect);
?>

$result->fetch_assoc() will fetch everything that match the sql condition, and you can prevent further error like you did in the above.
You can learn more here fetch_assoc() function


问:
App crashes when i get all value from all edittext from listview
Hello I have implemented listview where i used one edittext in listview,and i am getting all the values from all edittext but i am getting following error and aoo crashes

my code to get values is like below.

```<code> for (int k = 0; k < imagelist.getCount(); k++) {
                        EditText et;
                        Log.v("aaaaaa"," sss "+k);
                        vv = imagelist.getChildAt(k);

                             et = (EditText) vv.findViewById(R.id.pimgqty);//getting error at this line

                    }
</code>```

答: Just Create one model class and in that create one varible to save ediitext Value.and then traverse that list you will get all ediitext values</p>

Body:
Hello I have implemented listview where i used one edittext in listview,and i am getting all the values from all edittext but i am getting following error and aoo crashes

my code to get values is like below.

 for (int k = 0; k < imagelist.getCount(); k++) {
                        EditText et;
                        Log.v("aaaaaa"," sss "+k);
                        vv = imagelist.getChildAt(k);

                             et = (EditText) vv.findViewById(R.id.pimgqty);//getting error at this line

                    }


问:
XSLT output two documents based on array variable
I have xml file with structure like this:

```<code><?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.6.xsd">

    <changeSet author="system" id="65D7AFA9-17F1-4406-997E-D2B42A0E9008" dbms="oracle">
        <sql>GRANT SELECT,INSERT,UPDATE,DELETE ON ${dbSchema}.CATALOG TO ${appUser}</sql>
        <rollback>REVOKE SELECT,INSERT,UPDATE,DELETE ON ${dbSchema}.CATALOG FROM ${appUser}</rollback>
    </changeSet>
    <changeSet author="system" id="E2731435-DCEE-4B7E-BA60-20A87E75227A" dbms="oracle">
        <sql>GRANT SELECT,INSERT,UPDATE,DELETE ON ${dbSchema}.CATALOGATTRIBUTE TO ${appUser}</sql>
        <rollback>REVOKE SELECT,INSERT,UPDATE,DELETE ON ${dbSchema}.CATALOGATTRIBUTE FROM ${appUser}</rollback>
    </changeSet>
    <changeSet author="system" id="65D7AFA9-17F1-4406-997E-D2B42A0E9008" dbms="oracle">
        <createTable ...>
    </changeSet>

</databaseChangeLog>
</code>```

I'd like to output all changeSets where sql contains one of tables to one document and all others (which doesn't contain the table name) to other document. I was thinking about appending stuff to variable and at the end print two variables, but that doesn't work (or I don't know how to process further).

```<code><xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
               xpath-default-namespace="http://www.liquibase.org/xml/ns/dbchangelog"
               xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
               xmlns:uuid="http://uuid.util.java"
               exclude-result-prefixes="uuid">

    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <xsl:variable name="tables"
                  select="('CATALOG','CATALOGATTRIBUTE','EVENTTYPES')"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="changeSet[sql]">
        <xsl:variable name="changeSet" select="."/>
        <xsl:variable name="sql" select="sql"/>
        <xsl:for-each select="$tables">
            <!--<xsl:variable name="selected" select="sql[contains(text(),concat('${dbSchema}.', ., ' '))]"/>-->
            <xsl:variable name="tableName">
                <xsl:value-of select="."/>
                <xsl:value-of select="' '"/>
            </xsl:variable>
            <xsl:choose>
                <xsl:when test="contains($sql, $tableName)">
                    <xsl:copy-of select="$changeSet"/>
                </xsl:when>
                <xsl:otherwise>

                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
    </xsl:template>
</xsl:transform>
</code>```

can I somehow gather all changeSet which match tables and then all changeSets which doe not?

ps: I'm using Saxon-HE-9.8.0-14 for processing.

Thanks

答:
Consider the following simplified example:

XML

```<code><databaseChangeLog>
    <changeSet>
        <sql>ALPHA,BRAVO,CHARLIE</sql>
    </changeSet>
    <changeSet>
        <sql>BRAVO,CHARLIE,DELTA</sql>
    </changeSet>
    <changeSet>
        <sql>DELTA,ECHO,FOXTROT</sql>
    </changeSet>
    <changeSet>
        <sql>FOXTROT,GOLF,HOTEL</sql>
    </changeSet>
</databaseChangeLog>
</code>```

XSLT 2.0

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:param name="tables" select="('BRAVO', 'GOLF')"/>

<xsl:template match="/databaseChangeLog">
    <xsl:variable name="group1" select="changeSet[some $t in $tables satisfies contains(sql, $t)]" />
    <xsl:copy>
        <group1>
            <xsl:copy-of select="$group1"/>
        </group1>
        <group2>
            <xsl:copy-of select="changeSet except $group1"/>
        </group2>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Result

```<code><?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog>
   <group1>
      <changeSet>
        <sql>ALPHA,BRAVO,CHARLIE</sql>
      </changeSet>
      <changeSet>
        <sql>BRAVO,CHARLIE,DELTA</sql>
      </changeSet>
      <changeSet>
        <sql>FOXTROT,GOLF,HOTEL</sql>
      </changeSet>
   </group1>
   <group2>
      <changeSet>
        <sql>DELTA,ECHO,FOXTROT</sql>
      </changeSet>
   </group2>
</databaseChangeLog>
</code>```

Demo: https://xsltfiddle.liberty-development.net/jyRYYiP

A better solution would be to use tokenize():

XSLT 2.0

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:param name="tables" select="('BRAVO', 'GOLF')"/>

<xsl:template match="/databaseChangeLog">
    <xsl:variable name="group1" select="changeSet[tokenize(sql, ',') = $tables]" />
    <xsl:copy>
        <group1>
            <xsl:copy-of select="$group1"/>
        </group1>
        <group2>
            <xsl:copy-of select="changeSet except $group1"/>
        </group2>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Demo: https://xsltfiddle.liberty-development.net/jyRYYiP/1

Body:
I have xml file with structure like this:

<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.6.xsd">

    <changeSet author="system" id="65D7AFA9-17F1-4406-997E-D2B42A0E9008" dbms="oracle">
        <sql>GRANT SELECT,INSERT,UPDATE,DELETE ON ${dbSchema}.CATALOG TO ${appUser}</sql>
        <rollback>REVOKE SELECT,INSERT,UPDATE,DELETE ON ${dbSchema}.CATALOG FROM ${appUser}</rollback>
    </changeSet>
    <changeSet author="system" id="E2731435-DCEE-4B7E-BA60-20A87E75227A" dbms="oracle">
        <sql>GRANT SELECT,INSERT,UPDATE,DELETE ON ${dbSchema}.CATALOGATTRIBUTE TO ${appUser}</sql>
        <rollback>REVOKE SELECT,INSERT,UPDATE,DELETE ON ${dbSchema}.CATALOGATTRIBUTE FROM ${appUser}</rollback>
    </changeSet>
    <changeSet author="system" id="65D7AFA9-17F1-4406-997E-D2B42A0E9008" dbms="oracle">
        <createTable ...>
    </changeSet>

</databaseChangeLog>

I'd like to output all changeSets where sql contains one of tables to one document and all others (which doesn't contain the table name) to other document. I was thinking about appending stuff to variable and at the end print two variables, but that doesn't work (or I don't know how to process further).

<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
               xpath-default-namespace="http://www.liquibase.org/xml/ns/dbchangelog"
               xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
               xmlns:uuid="http://uuid.util.java"
               exclude-result-prefixes="uuid">

    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <xsl:variable name="tables"
                  select="('CATALOG','CATALOGATTRIBUTE','EVENTTYPES')"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="changeSet[sql]">
        <xsl:variable name="changeSet" select="."/>
        <xsl:variable name="sql" select="sql"/>
        <xsl:for-each select="$tables">

            <xsl:variable name="tableName">
                <xsl:value-of select="."/>
                <xsl:value-of select="' '"/>
            </xsl:variable>
            <xsl:choose>
                <xsl:when test="contains($sql, $tableName)">
                    <xsl:copy-of select="$changeSet"/>
                </xsl:when>
                <xsl:otherwise>

                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
    </xsl:template>
</xsl:transform>

can I somehow gather all changeSet which match tables and then all changeSets which doe not?

ps: I'm using Saxon-HE-9.8.0-14 for processing.

Thanks

Body:
Consider the following simplified example:

XML

<databaseChangeLog>
    <changeSet>
        <sql>ALPHA,BRAVO,CHARLIE</sql>
    </changeSet>
    <changeSet>
        <sql>BRAVO,CHARLIE,DELTA</sql>
    </changeSet>
    <changeSet>
        <sql>DELTA,ECHO,FOXTROT</sql>
    </changeSet>
    <changeSet>
        <sql>FOXTROT,GOLF,HOTEL</sql>
    </changeSet>
</databaseChangeLog>

XSLT 2.0

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:param name="tables" select="('BRAVO', 'GOLF')"/>

<xsl:template match="/databaseChangeLog">
    <xsl:variable name="group1" select="changeSet[some $t in $tables satisfies contains(sql, $t)]" />
    <xsl:copy>
        <group1>
            <xsl:copy-of select="$group1"/>
        </group1>
        <group2>
            <xsl:copy-of select="changeSet except $group1"/>
        </group2>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog>
   <group1>
      <changeSet>
        <sql>ALPHA,BRAVO,CHARLIE</sql>
      </changeSet>
      <changeSet>
        <sql>BRAVO,CHARLIE,DELTA</sql>
      </changeSet>
      <changeSet>
        <sql>FOXTROT,GOLF,HOTEL</sql>
      </changeSet>
   </group1>
   <group2>
      <changeSet>
        <sql>DELTA,ECHO,FOXTROT</sql>
      </changeSet>
   </group2>
</databaseChangeLog>

Demo: https://xsltfiddle.liberty-development.net/jyRYYiP

A better solution would be to use tokenize():

XSLT 2.0

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:param name="tables" select="('BRAVO', 'GOLF')"/>

<xsl:template match="/databaseChangeLog">
    <xsl:variable name="group1" select="changeSet[tokenize(sql, ',') = $tables]" />
    <xsl:copy>
        <group1>
            <xsl:copy-of select="$group1"/>
        </group1>
        <group2>
            <xsl:copy-of select="changeSet except $group1"/>
        </group2>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Demo: https://xsltfiddle.liberty-development.net/jyRYYiP/1


问:
on Scrolling Custom layout hide or show
I am working on an app and getting stuck on some code. Actually I am using search layout inside a fragment and on scrolling RecyclerView I have to hide or show that layout. And I used on scrolling listener for that but on translation it is showing blank space. You can see my code and after that I used scaling but I did not get any expected result.

```<code>public void onScrolled(@NonNull RecyclerView view, int dx, int dy) {

    if (dy > 0) {
        if (!up)
            scaleView(searchLayout, searchLayout.getScaleY(), .0f);
        up=true;
        down=false;
    }
    else if (dy < 0) {
        if(!down)
        scaleView1(searchLayout, .0f, searchLayout.getScaleY());
        up=false;
        down=true;
    }

}

public void scaleView(View v, float startScale, float endScale) {

    Animation anim = new ScaleAnimation(
            1f, 1f, // Start and end values for the X axis scaling
            startScale, endScale, // Start and end values for the Y axis scaling
            Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
            Animation.RELATIVE_TO_SELF, endScale); // Pivot point of Y scaling
    anim.setFillAfter(true); // Needed to keep the result of the animation
    anim.setDuration(1000);
    anim.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            searchLayout.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationEnd(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    v.startAnimation(anim);

}
public void scaleView1(View v, float startScale, float endScale) {
    Animation anim = new ScaleAnimation(
            1f, 1f, // Start and end values for the X axis scaling
            startScale, endScale, // Start and end values for the Y axis scaling
            Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
            Animation.RELATIVE_TO_SELF, 0f); // Pivot point of Y scaling
    anim.setFillAfter(true); // Needed to keep the result of the animation
    anim.setDuration(1000);
    anim.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            searchLayout.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    v.startAnimation(anim);
}
</code>```

I'm getting blank space on scrolling.

答:
Add this code into your scrollview and control the view according to the dependant view in your view

Use Nestedscroll view around your Recyclerview

 scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {

                Rect scrollBounds = new Rect();
                scrollView.getHitRect(scrollBounds);
                if (yourView.getLocalVisibleRect(scrollBounds)) {
                                                                     // is your dependant view is in visible bounds
                    searchBar.setVisibility("Visibility.GONE");

                                                                      //your animation

                } else {
                    searchBar.setVisibility("Visibility.VISISBLE");

                                                                       //your animation

                }

            }
        });```

Title: on Scrolling Custom layout hide or show

Body:
I am working on an app and getting stuck on some code. Actually I am using search layout inside a fragment and on scrolling RecyclerView I have to hide or show that layout. And I used on scrolling listener for that but on translation it is showing blank space. You can see my code and after that I used scaling but I did not get any expected result.

public void onScrolled(@NonNull RecyclerView view, int dx, int dy) {

    if (dy > 0) {
        if (!up)
            scaleView(searchLayout, searchLayout.getScaleY(), .0f);
        up=true;
        down=false;
    }
    else if (dy < 0) {
        if(!down)
        scaleView1(searchLayout, .0f, searchLayout.getScaleY());
        up=false;
        down=true;
    }

}

public void scaleView(View v, float startScale, float endScale) {

    Animation anim = new ScaleAnimation(
            1f, 1f, // Start and end values for the X axis scaling
            startScale, endScale, // Start and end values for the Y axis scaling
            Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
            Animation.RELATIVE_TO_SELF, endScale); // Pivot point of Y scaling
    anim.setFillAfter(true); // Needed to keep the result of the animation
    anim.setDuration(1000);
    anim.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            searchLayout.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationEnd(Animation animation) {
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    v.startAnimation(anim);

}
public void scaleView1(View v, float startScale, float endScale) {
    Animation anim = new ScaleAnimation(
            1f, 1f, // Start and end values for the X axis scaling
            startScale, endScale, // Start and end values for the Y axis scaling
            Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
            Animation.RELATIVE_TO_SELF, 0f); // Pivot point of Y scaling
    anim.setFillAfter(true); // Needed to keep the result of the animation
    anim.setDuration(1000);
    anim.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            searchLayout.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    v.startAnimation(anim);
}

I'm getting blank space on scrolling.


问:
How to call a command from window pop in wpf
How call a delegate command from window pop up.
I'm showing a pop up window over a window..
The pop up window have button which need to call DelegateCommand from ViewModel.

Below is the code for Window > MyPopUp.xaml.cs

```<code>public partial class MyPopUp : Window
{
  public MyPopUp(){
     InitializeComponent();
    }
}
</code>```

Below is the code for ViewModel> > MyPopUpViewModel.cs

```<code>public class MyPopUpViewModel: BindableBase
{
    public MyPopUpViewModel()
    {
        AddCommand = new DelegateCommand(AddCommandCall);

    }

    private void AddCommandCall()
    {
        /// Command call Code here
    }

    public DelegateCommand AddCommand { get; private set; }

}
</code>```

MyPopUp.xaml code here

```<code><Window x:Class="Project"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

      xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:local="clr-namespace:Project.PopUpControls"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
     xmlns:prism="http://prismlibrary.com/"

    mc:Ignorable="d"
    Title="Create Levels" Height="700" Width="900"
    prism:ViewModelLocator.AutoWireViewModel="True">

<Grid>
    <Button
        Command="{Binding DataContext.AddCommand}"
        Content="test"
        Margin="0,5,0,0"
        FontSize="16"
        FontWeight="Normal"
        Width="100"
        HorizontalAlignment="Center"
        HorizontalContentAlignment="Center"
        VerticalAlignment="Top"
        VerticalContentAlignment="Center"
        Foreground="#ffffff"
        Background="#4e4e4e"/>
</Grid>
</code>```

Though when InitializeComponent(); is called in MyPopUp.xaml.cs  the window DataContext get all the commands in it from MyPopUpViewModel.cs

Then when clicked on button on pop up... It should call the command AddCommand, but it is not getting called.

Let me know what I'm missing or sommnething need to be added/change.

Thanks in advance.

答:
Digging for so much time on wpf and trying some alternative.. i got the answer Command="{Binding Path=DataContext.AddCommand,RelativeSource={RelativeSource AncestorType=Window}}"

```<code><Grid>
<Button
    Command="{Binding Path=DataContext.AddCommand,RelativeSource={RelativeSource AncestorType=Window}}"
    Content="test"
    Margin="0,5,0,0"
    FontSize="16"
    FontWeight="Normal"
    Width="100"
    HorizontalAlignment="Center"
    HorizontalContentAlignment="Center"
    VerticalAlignment="Top"
    VerticalContentAlignment="Center"
    Foreground="#ffffff"
    Background="#4e4e4e"/>
</code>```

Body:
How call a delegate command from window pop up.
I'm showing a pop up window over a window..
The pop up window have button which need to call DelegateCommand from ViewModel.

Below is the code for Window > MyPopUp.xaml.cs

public partial class MyPopUp : Window
{
  public MyPopUp(){
     InitializeComponent();
    }
}

Below is the code for ViewModel> > MyPopUpViewModel.cs

public class MyPopUpViewModel: BindableBase
{
    public MyPopUpViewModel()
    {
        AddCommand = new DelegateCommand(AddCommandCall);

    }

    private void AddCommandCall()
    {
        /// Command call Code here
    }

    public DelegateCommand AddCommand { get; private set; }

}

MyPopUp.xaml code here

<Window x:Class="Project"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

      xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:local="clr-namespace:Project.PopUpControls"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
     xmlns:prism="http://prismlibrary.com/"

    mc:Ignorable="d"
    Title="Create Levels" Height="700" Width="900"
    prism:ViewModelLocator.AutoWireViewModel="True">

<Grid>
    <Button
        Command="{Binding DataContext.AddCommand}"
        Content="test"
        Margin="0,5,0,0"
        FontSize="16"
        FontWeight="Normal"
        Width="100"
        HorizontalAlignment="Center"
        HorizontalContentAlignment="Center"
        VerticalAlignment="Top"
        VerticalContentAlignment="Center"
        Foreground="#ffffff"
        Background="#4e4e4e"/>
</Grid>

Though when InitializeComponent(); is called in MyPopUp.xaml.cs  the window DataContext get all the commands in it from MyPopUpViewModel.cs

Then when clicked on button on pop up... It should call the command AddCommand, but it is not getting called.

Let me know what I'm missing or sommnething need to be added/change.

Thanks in advance.

Body:
Digging for so much time on wpf and trying some alternative.. i got the answer Command="{Binding Path=DataContext.AddCommand,RelativeSource={RelativeSource AncestorType=Window}}"

<Grid>
<Button
    Command="{Binding Path=DataContext.AddCommand,RelativeSource={RelativeSource AncestorType=Window}}"
    Content="test"
    Margin="0,5,0,0"
    FontSize="16"
    FontWeight="Normal"
    Width="100"
    HorizontalAlignment="Center"
    HorizontalContentAlignment="Center"
    VerticalAlignment="Top"
    VerticalContentAlignment="Center"
    Foreground="#ffffff"
    Background="#4e4e4e"/>


问:
How to understand this rx-swift map function
I have some textfileds in my viewcontroller. And use rx-swift to observer the .editingDidBegin event.

I want to judge which textfield sends event.

```<code>let tags = txtFieldArray.map{($0.rx.controlEvent(.editingDidBegin), $0.tag)}
            .map{obs, tag in obs.map{tag}}
let value = Observable.merge(tags)
        value.bind {[weak self] (tags) in
            guard let strongSelf = self else { return }
            if let view = strongSelf.ipEnteryView.viewWithTag(tags) as? UITextField {
                strongSelf.viewMode.changeTextFiledBottomColor(view, true)
            }
            }.disposed(by: disposedBag)
</code>```

The txtFieldArray's first map return a array, element is tuples(as my understand),first is controlEvent, second is a int value. What i don't understand is the second map function. Obs is contrlEvent type. Why obs.map{tag} return a observable. And how to understand map{obs, tag in obs.map{tag}}?
Thank you very much!

答:
The output is:

```<code>obs.map{ tag }
</code>```

which represents

```<code>$0.rx.controlEvent(.editingDidBegin).map { $0.tag }
</code>```

It's replacing a the .editingDidBegin control sequence with whatever that field's tag value is.

Body:
I have some textfileds in my viewcontroller. And use rx-swift to observer the .editingDidBegin event.

I want to judge which textfield sends event.

let tags = txtFieldArray.map{($0.rx.controlEvent(.editingDidBegin), $0.tag)}
            .map{obs, tag in obs.map{tag}}
let value = Observable.merge(tags)
        value.bind {[weak self] (tags) in
            guard let strongSelf = self else { return }
            if let view = strongSelf.ipEnteryView.viewWithTag(tags) as? UITextField {
                strongSelf.viewMode.changeTextFiledBottomColor(view, true)
            }
            }.disposed(by: disposedBag)

The txtFieldArray's first map return a array, element is tuples(as my understand),first is controlEvent, second is a int value. What i don't understand is the second map function. Obs is contrlEvent type. Why obs.map{tag} return a observable. And how to understand map{obs, tag in obs.map{tag}}?
Thank you very much!

Body:
The output is:

obs.map{ tag }

which represents

$0.rx.controlEvent(.editingDidBegin).map { $0.tag }

It's replacing a the .editingDidBegin control sequence with whatever that field's tag value is.


问:
Adding a batch of items to a product list (in-app products)
I'm trying to import a csv-sheet products, but keep getting an error related to incorrect indication of the country or currency. I tried to export csv with in-apps first, and then tried to import (upload) this document. But still the same errors. How can I avoid it?

UDP: Sorry, cant attach an image, beacause Im a new user...

答:
After a lot of digging, I finally found some documentation with examples about this:
https://support.google.com/googleplay/android-developer/answer/1153481?hl=en

CSV syntax example

```<code>Product ID,Published State,Purchase Type,Auto Translate,Locale; Title; Description,Auto Fill Prices,Price,Pricing Template ID
</code>```

Managed product examples

Example 1:

```<code>basic_sleeping_potion,published,managed_by_android,false,en_US; Basic Sleeping Potion; Puts small creatures to sleep.; es_ES; Poción básica de dormir; Causa las criaturas pequeñas ir a dormir.,false,,4637138456024710495
</code>```

Example 2:

```<code>standard_sleeping_potion, published,managed_by_android,false,en_US; Standard Sleeping Potion; Puts all creatures to sleep for 2 minutes.,true, 1990000,
</code>```

Example 3:

```<code>invisibility_potion,published, managed_by_android,false,en_US; Invisibility Potion; Invisible to all enemies for 5 minutes.,false, US; 1990000; BR; 6990000; RU; 129000000; IN; 130000000; ID; 27000000000; MX; 37000000;
</code>```

And even more detailed documentation is here:
http://www.androiddocs.com/google/play/billing/billing_admin.html

Body:
After a lot of digging, I finally found some documentation with examples about this:
https://support.google.com/googleplay/android-developer/answer/1153481?hl=en

CSV syntax example

Product ID,Published State,Purchase Type,Auto Translate,Locale; Title; Description,Auto Fill Prices,Price,Pricing Template ID

Managed product examples

Example 1:

basic_sleeping_potion,published,managed_by_android,false,en_US; Basic Sleeping Potion; Puts small creatures to sleep.; es_ES; Poción básica de dormir; Causa las criaturas pequeñas ir a dormir.,false,,4637138456024710495

Example 2:

standard_sleeping_potion, published,managed_by_android,false,en_US; Standard Sleeping Potion; Puts all creatures to sleep for 2 minutes.,true, 1990000,

Example 3:

invisibility_potion,published, managed_by_android,false,en_US; Invisibility Potion; Invisible to all enemies for 5 minutes.,false, US; 1990000; BR; 6990000; RU; 129000000; IN; 130000000; ID; 27000000000; MX; 37000000;

And even more detailed documentation is here:
http://www.androiddocs.com/google/play/billing/billing_admin.html


问:
What does XmlReader.Parse() do?
edit: The project is an old project and the below code is one class in there that handles the xml.

There is a question to get the xsd from an old legacy application, but all it seems to be doing is: xmlReader.ParseXml(fileName,outputFile); in the ProcessXml() method.

```<code>using System;
using System.IO;
using System.Configuration;
using Utilities;
namespace JobProcessor
{

public class XmlJob : Job
{
    #region variables
    private string      ftpServer;
    private string      ftpUserName;
    private string      ftpPassWord;
    private string      ftpDestination;
    ///<summary>The xml reader used to get validation information from the xmp parsing</summary>
    protected XmlReader xmlReader   = new XmlReader();

    private string      outputFile;

    public XmlJob(string fileName, string type) : base(fileName, type){
        ftpServer       = ConfigurationManager.AppSettings[type + "-ftp"];
        ftpUserName     = ConfigurationManager.AppSettings[type + "-ftpUser"];
        ftpPassWord     = ConfigurationManager.AppSettings[type + "-ftpPass"];
        ftpDestination  = ConfigurationManager.AppSettings[type + "-ftpDest"];
    }

    protected bool ConfigureXmlReader(){
        int    recType    = 0;

        try{
            //set up the record types (i.e. the elements that trigger a new record in the output
            while(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")] != null){
                xmlReader.AddRecordType(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")],recType.ToString("00"));
                recType++;
            }
            //store the number of types
            xmlReader.SetNoRecordTypes(recType);
        }catch(Exception e){
            HandleError("Error loading record types\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }

        try{
            //set up the fields which make up each record type
            for(int i=0;i<recType;i++){
                xmlReader.AddFieldsList(i,ConfigurationManager.AppSettings[type + "-" + i.ToString("00") + "Fields"]);
            }
        }catch(Exception e){
            HandleError("Error loading field list\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    public override void RunJob(){
        outputFile = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(fileName) + ".flat");

        if(!ConfigureXmlReader()){
            return;
        }

        if(!CheckInputFile()){
            return;
        }

        if(!ProcessXml()){
            return;
        }

        if(!Validate()){
            return;
        }

        if(ftpServer!=null && ftpUserName!=null && ftpPassWord!=null && ftpDestination!=null){
            if(!FtpFile()){
                return;
            }
        }

        MoveOriginalFile();
    }

    protected virtual bool Validate(){
        return(true);
    }

    protected bool ProcessXml(){
        /*
         * Process the xml file into a delimited format
         */

        try{
            xmlReader.ParseXml(fileName,outputFile);
        }catch(Exception e){
            HandleError("Error parsing XML file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }
    protected bool FtpFile(){
        try{
            FtpMethods.UploadFile(ftpServer,ftpUserName,ftpPassWord,outputFile,ftpDestination);
        }catch(Exception e){
            HandleError("Error FTPing file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    #endregion
}
</code>```

}

What exactly does this command do? F1 doesn't find anything and searching google gets me to a lot of xmlTextReaders.

答:
The XmlReader class doesn't have a Parse method.
Checkout what is the runtime-type of the xmlReader variable declared in your code, and then recheck the msdn.

Or else you meant the XDocument.Parse.

Update after OP's edit

I didn't manage to find any ParseXml in the entire BCL.

Update2 after OP's edit

The XmlReader class is abstract and thus cannot be used as declared in your code.

We must conclude (Also because the System.Xml namespace was not imported to your file...) that the type of the xmlReader variable in your code is probably declared somewhere in the Utilities namespace, no one can guess how you (or anybody else) coded it.

As a side note, when using XmlReader or any other type that implements the IDisposable interface, you have to take care of its disposal (view link).

Title: What does XmlReader.Parse() do?

Body:
edit: The project is an old project and the below code is one class in there that handles the xml.

There is a question to get the xsd from an old legacy application, but all it seems to be doing is: xmlReader.ParseXml(fileName,outputFile); in the ProcessXml() method.

using System;
using System.IO;
using System.Configuration;
using Utilities;
namespace JobProcessor
{

public class XmlJob : Job
{
    #region variables
    private string      ftpServer;
    private string      ftpUserName;
    private string      ftpPassWord;
    private string      ftpDestination;
    ///The xml reader used to get validation information from the xmp parsing
    protected XmlReader xmlReader   = new XmlReader();

    private string      outputFile;

    public XmlJob(string fileName, string type) : base(fileName, type){
        ftpServer       = ConfigurationManager.AppSettings[type + "-ftp"];
        ftpUserName     = ConfigurationManager.AppSettings[type + "-ftpUser"];
        ftpPassWord     = ConfigurationManager.AppSettings[type + "-ftpPass"];
        ftpDestination  = ConfigurationManager.AppSettings[type + "-ftpDest"];
    }

    protected bool ConfigureXmlReader(){
        int    recType    = 0;

        try{
            //set up the record types (i.e. the elements that trigger a new record in the output
            while(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")] != null){
                xmlReader.AddRecordType(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")],recType.ToString("00"));
                recType++;
            }
            //store the number of types
            xmlReader.SetNoRecordTypes(recType);
        }catch(Exception e){
            HandleError("Error loading record types\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }

        try{
            //set up the fields which make up each record type
            for(int i=0;i<recType;i++){
                xmlReader.AddFieldsList(i,ConfigurationManager.AppSettings[type + "-" + i.ToString("00") + "Fields"]);
            }
        }catch(Exception e){
            HandleError("Error loading field list\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    public override void RunJob(){
        outputFile = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(fileName) + ".flat");

        if(!ConfigureXmlReader()){
            return;
        }

        if(!CheckInputFile()){
            return;
        }

        if(!ProcessXml()){
            return;
        }

        if(!Validate()){
            return;
        }

        if(ftpServer!=null && ftpUserName!=null && ftpPassWord!=null && ftpDestination!=null){
            if(!FtpFile()){
                return;
            }
        }

        MoveOriginalFile();
    }

    protected virtual bool Validate(){
        return(true);
    }

    protected bool ProcessXml(){
        /*
         * Process the xml file into a delimited format
         */

        try{
            xmlReader.ParseXml(fileName,outputFile);
        }catch(Exception e){
            HandleError("Error parsing XML file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }
    protected bool FtpFile(){
        try{
            FtpMethods.UploadFile(ftpServer,ftpUserName,ftpPassWord,outputFile,ftpDestination);
        }catch(Exception e){
            HandleError("Error FTPing file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    #endregion
}

}

What exactly does this command do? F1 doesn't find anything and searching google gets me to a lot of xmlTextReaders.


问:
IoC container and dll memory management
I'm working on a server project and the server has a few different, independent layers and a few singleton classes. And I use the SimpleInjector, an IoC container, all across the layers. The full, executable example source code is available at  https://github.com/DamonJung/TestAdvanture001.. ( It's unnecessarily lengthy because I was trying to reproduce a different problem there. )

I access the Singleton from Main method directly and indirectly from the IoC container.

```<code>// Use case in Main
.
.
using Impl;

static void Main(string args[])
{
    .
    .
    // Singleton.Instance address = 0x0301f001 for example.
    var context = Singleton.Instance.GetContext();

    // SimpleInjector
    // Singleton.Instance address inside of the dependency = 0x0408f023 for example.
    var di = Container.GetInstance<ISomeInterface>();
    var contextFromIoC = di.GetContext();
    .
    .
}
</code>```

I expected the Singleton should be instantiated only once and the static instance should have the exact same memory address in the application, no matter where it's being invoked from and no matter how it's constructed ( by Main or the IoC container )

However, as the console output is saying, it didn't work that way. The Singleton's Instance shouldn't have been instantiated more than once. But they ended up having a different address on their own.

If my shallow understanding serves me right, the executable loads the dll into its own memory, and once the static member is created, the variable can be accessed throughout the AppDomain region.

Isn't this confirming the fact about static variables, isn't it?

Static Members

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

I was in search for the relevant read in SimpleInjector's documentation and found none. Reading about dynamic linking library and its memory management doesn't come right at me ( I shall be reading it further and over and over again anyway ! )

How a program treats dlls in terms of memory management

If IoC container is the scene behind, how SimpleInjector treats the dependencies when they are registered via Container.Register();

Above items would be my ultimate questions.

答:
Two instances are created because your code creates two instances.

The first one is created by the following code

```<code>public class Singleton
{
    public static readonly Singleton Instance = new Singleton();
    // ....
}
</code>```

and the second one is created when you register your type to SimpleInjector

If you want an instance to be created only once you could use a private constructor

```<code>public class Singleton
{
    static Singleton()
    {
        Singleton.Instance = new Singleton();
    }
    public static Singleton Instance { get; }

    private Singleton(){
    }
}
</code>```

This way only the Singleton class create itself.

To register your singleton in SimpleInjector you can use the RegisterInstance method :

```<code>container.RegisterInstance<Singleton>(Singleton.Instance);
</code>```

By the way it is more common to let the container manage instances by itself and not rely on static property which could indicate that you are using a service locator which is a common anti pattern.

If you want to let SimpleInjector manage the instance you should use

```<code>container.RegisterSingleton<Singleton>();
</code>```

This way SimpleInjector will create only one Singleton instance for the container.

See Singleton lifestyle in the SimpleInjector documentation

Title: IoC container and dll memory management

Body:
I'm working on a server project and the server has a few different, independent layers and a few singleton classes. And I use the SimpleInjector, an IoC container, all across the layers. The full, executable example source code is available at  https://github.com/DamonJung/TestAdvanture001.. ( It's unnecessarily lengthy because I was trying to reproduce a different problem there. )

I access the Singleton from Main method directly and indirectly from the IoC container.

// Use case in Main
.
.
using Impl;

static void Main(string args[])
{
    .
    .
    // Singleton.Instance address = 0x0301f001 for example.
    var context = Singleton.Instance.GetContext();

    // SimpleInjector
    // Singleton.Instance address inside of the dependency = 0x0408f023 for example.
    var di = Container.GetInstance<ISomeInterface>();
    var contextFromIoC = di.GetContext();
    .
    .
}

I expected the Singleton should be instantiated only once and the static instance should have the exact same memory address in the application, no matter where it's being invoked from and no matter how it's constructed ( by Main or the IoC container )

However, as the console output is saying, it didn't work that way. The Singleton's Instance shouldn't have been instantiated more than once. But they ended up having a different address on their own.

If my shallow understanding serves me right, the executable loads the dll into its own memory, and once the static member is created, the variable can be accessed throughout the AppDomain region.

Isn't this confirming the fact about static variables, isn't it?

Static Members

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

I was in search for the relevant read in SimpleInjector's documentation and found none. Reading about dynamic linking library and its memory management doesn't come right at me ( I shall be reading it further and over and over again anyway ! )

How a program treats dlls in terms of memory management

If IoC container is the scene behind, how SimpleInjector treats the dependencies when they are registered via Container.Register();

Above items would be my ultimate questions.

Body:
Two instances are created because your code creates two instances.

The first one is created by the following code

public class Singleton
{
    public static readonly Singleton Instance = new Singleton();
    // ....
}

and the second one is created when you register your type to SimpleInjector

If you want an instance to be created only once you could use a private constructor

public class Singleton
{
    static Singleton()
    {
        Singleton.Instance = new Singleton();
    }
    public static Singleton Instance { get; }

    private Singleton(){
    }
}

This way only the Singleton class create itself.

To register your singleton in SimpleInjector you can use the RegisterInstance method :

container.RegisterInstance<Singleton>(Singleton.Instance);

By the way it is more common to let the container manage instances by itself and not rely on static property which could indicate that you are using a service locator which is a common anti pattern.

If you want to let SimpleInjector manage the instance you should use

container.RegisterSingleton<Singleton>();

This way SimpleInjector will create only one Singleton instance for the container.

See Singleton lifestyle in the SimpleInjector documentation


问:
Passing argument in LEFT JOIN
I am currently trying to get data from 2 tables with a LEFT JOIN having an unknow value.

I tried using LEFT JOIN but it didn't work.

Here is my code example :

```<code>SELECT
    cc.shid,
    cc.user,
    ts.type,
    sum(cc.qty1) + sum(cc.qty2) as qty_tot,
    COUNT(cc.id) as nb
FROM
    content_c cc
LEFT JOIN
    (SELECT
        s.shid,
        s.type
    FROM
        tab_s s
    LIMIT 1
    ) as ts ON ts.shid = cc.shid
WHERE
    cc.time_i like '2019-01%'
GROUP BY
    cc.user,
    ts.type
</code>```

With that query it will never work : ts will contain the first occurence of tab_s regardless of cc.shid. I wonder if there is a way to make this :

```<code>LEFT JOIN
    (SELECT
        s.shid,
        s.type
    FROM
        tab_s s
    WHERE
        s.shid = cc.shid
    LIMIT 1
    ) as ts ON ts.shid = cc.shid
</code>```

Any idea ? Is there a pointer notion in SQL or something like ? Like I can use &cc.shid, or @cc.shid ?

Note that doing the following :

```<code>LEFT JOIN tab_s ts ON ts.shid = cc.shid
</code>```

Will make my request to take more than 1 minute to display results. And I cannot set an index in tab_s.shid aswell as cc.shid as its have multiple occurences.

Please keep in mind that content_c can have multiple occurence of cc.shid, that why I need to take only the first result (LIMIT 1). It's important.

答:
As discussed in the question comments, Can you please try this  script and see if it meets your requirements? This will return a row per ID in "content_c" table with the GROUP BY impact.</p>

```<code>SELECT
    cc.shid,
    cc.user,
    ts.type,
    sum(cc.qty1) + sum(cc.qty2) as qty_tot,
    COUNT(cc.id) as nb
FROM content_c cc
LEFT JOIN
(
    SELECT DISTINCT s.shid, s.type FROM tab_s s
) AS ts ON ts.shid = cc.shid
WHERE cc.time_i like '2019-01%'
GROUP BY cc.shid,cc.user,ts.type
</code>```

Title: Passing argument in LEFT JOIN

Body:
I am currently trying to get data from 2 tables with a LEFT JOIN having an unknow value.

I tried using LEFT JOIN but it didn't work.

Here is my code example :

SELECT
    cc.shid,
    cc.user,
    ts.type,
    sum(cc.qty1) + sum(cc.qty2) as qty_tot,
    COUNT(cc.id) as nb
FROM
    content_c cc
LEFT JOIN
    (SELECT
        s.shid,
        s.type
    FROM
        tab_s s
    LIMIT 1
    ) as ts ON ts.shid = cc.shid
WHERE
    cc.time_i like '2019-01%'
GROUP BY
    cc.user,
    ts.type

With that query it will never work : ts will contain the first occurence of tab_s regardless of cc.shid. I wonder if there is a way to make this :

LEFT JOIN
    (SELECT
        s.shid,
        s.type
    FROM
        tab_s s
    WHERE
        s.shid = cc.shid
    LIMIT 1
    ) as ts ON ts.shid = cc.shid

Any idea ? Is there a pointer notion in SQL or something like ? Like I can use &cc.shid, or @cc.shid ?

Note that doing the following :

LEFT JOIN tab_s ts ON ts.shid = cc.shid

Will make my request to take more than 1 minute to display results. And I cannot set an index in tab_s.shid aswell as cc.shid as its have multiple occurences.

Please keep in mind that content_c can have multiple occurence of cc.shid, that why I need to take only the first result (LIMIT 1). It's important.

Body:
As discussed in the question comments, Can you please try this  script and see if it meets your requirements? This will return a row per ID in "content_c" table with the GROUP BY impact.

SELECT
    cc.shid,
    cc.user,
    ts.type,
    sum(cc.qty1) + sum(cc.qty2) as qty_tot,
    COUNT(cc.id) as nb
FROM content_c cc
LEFT JOIN
(
    SELECT DISTINCT s.shid, s.type FROM tab_s s
) AS ts ON ts.shid = cc.shid
WHERE cc.time_i like '2019-01%'
GROUP BY cc.shid,cc.user,ts.type


问:
AttributeError: 'Ui_Dialog' object has no attribute 'setWindowFlags'
I can't use setWindowFlags with my QDialog widget. am trying to hide the close button or remove the whole frame so the user can't close it using the default method.

I've tried adding one of those two lines inside the setupUi function for my class :

self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

and

self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False) but both gave me the same error.

Here is my code for a better inspection:

import os
import sys

import psycopg2
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMessageBox

import backoffice

class Ui_Dialog(object):

    def setupUi(self, Dialog):
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 274)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(self.resource_path("./images/pos_logo_small.png")), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        Dialog.setWindowIcon(icon)
        Dialog.setLayoutDirection(QtCore.Qt.RightToLeft)
        Dialog.setStyleSheet("background:#a1d0f4;")
        self.gridLayout = QtWidgets.QGridLayout(Dialog)
        self.gridLayout.setObjectName("gridLayout")
        self.formLayout = QtWidgets.QFormLayout()
        self.formLayout.setHorizontalSpacing(4)
        self.formLayout.setObjectName("formLayout")
        self.label_2 = QtWidgets.QLabel(Dialog)
        font = QtGui.QFont()
        font.setFamily("Shorooq_N1")
        font.setPointSize(18)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2)
        self.label_3 = QtWidgets.QLabel(Dialog)
        font = QtGui.QFont()
        font.setFamily("Shorooq_N1")
        font.setPointSize(18)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_3)
        self.lineEdit = QtWidgets.QLineEdit(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit.setStyleSheet("background:white;")
        self.lineEdit.setObjectName("lineEdit")

        self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.lineEdit)
        self.lineEdit_2 = QtWidgets.QLineEdit(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
        self.lineEdit_2.setSizePolicy(sizePolicy)
        self.lineEdit_2.setStyleSheet("background:white;")
        self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.lineEdit_2)
        self.closeToolButton = QtWidgets.QToolButton(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.closeToolButton.sizePolicy().hasHeightForWidth())
        self.closeToolButton.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Shorooq_N1")
        font.setPointSize(18)
        font.setBold(False)
        font.setWeight(50)
        self.closeToolButton.setFont(font)
        self.closeToolButton.setStyleSheet("background:red;color:white;")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(self.resource_path("./images/close-window-256.ico")), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.closeToolButton.setIcon(icon1)
        self.closeToolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.closeToolButton.setObjectName("closeToolButton")
        self.closeToolButton.clicked.connect(self.exit_app)
        self.formLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.closeToolButton)
        self.logInToolButton = QtWidgets.QToolButton(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.logInToolButton.sizePolicy().hasHeightForWidth())
        self.logInToolButton.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Shorooq_N1")
        font.setPointSize(16)
        self.logInToolButton.setFont(font)
        self.logInToolButton.setStyleSheet("background:#0a74c4;color:white;")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(self.resource_path("./images/check-mark-11-256.ico")), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.logInToolButton.setIcon(icon2)
        self.logInToolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.logInToolButton.setObjectName("logInToolButton")
        self.dialog = Dialog
        self.logInToolButton.clicked.connect(self.log_in)
        self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.logInToolButton)
        self.gridLayout.addLayout(self.formLayout, 1, 1, 1, 1)
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 1, 1, 1)
        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def exit_app(self):
        QtCore.QCoreApplication.instance().quit()

    def log_in(self):
        print('activated')
        try:
            connection = psycopg2.connect(user="*******",
                                          password="********",
                                          host="127.0.0.1",
                                          port="5432",
                                          database="********")
            cursor = connection.cursor()
            postgreSQL_select_Query = "select * from users"
            cursor.execute(postgreSQL_select_Query)
            print("Selecting rows from users table using cursor.fetchall")
            user_records = cursor.fetchall()
            print("Print each row and it's columns values")
            input_username = self.lineEdit.text()
            input_password = self.lineEdit_2.text()
            for row in user_records:
                if row[1] == input_username:
                    if row[2] == input_password:
                        backoffice.isAuthenticated = True
                        print('logged in ')
                        self.dialog.close()
                else:
                    pass
                print(input)
        except (Exception, psycopg2.Error) as error:
            print("Error while fetching data from PostgreSQL", error)
        finally:
            # closing database connection.
            connection = psycopg2.connect(user="*********",
                                          password="*******",
                                          host="127.0.0.1",
                                          port="5432",
                                          database="*******")
            cursor = connection.cursor()
            if (connection):
                cursor.close()
                connection.close()
                print("PostgreSQL connection is closed")

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Vision Store Manager"))
        self.label_2.setText(_translate("Dialog", "إسم المستخدم"))
        self.label_3.setText(_translate("Dialog", "كلمة المرور"))
        self.closeToolButton.setText(_translate("Dialog", "خروج"))
        self.logInToolButton.setText(_translate("Dialog", "تسجيل الدخول"))
        self.label.setText(_translate("Dialog",
                                      "

"))

    @staticmethod
    def resource_path(relative_path):
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

import login_rcs_rc

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()

    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())
```

<p>Getting the error <code>AttributeError: 'Ui_Dialog' object has no attribute 'setWindowFlags'</code> when executing the line : <code>self.setWindowFlags(QtCore.Qt.FramelessWindowHint)</code></p>

<p><strong><em>UPDATE</em></strong></p>

<p>I changed :
<code>self.setWindowFlags(QtCore.Qt.FramelessWindowHint)</code>
To </p>

```the_login = QtWidgets.QDialog
the_login.setWindowFlags(QtCore.Qt.FramelessWindowHint)
```

and the error now is:TypeError: setWindowFlags(self, Union[Qt.WindowFlags, Qt.WindowType]): first argument of unbound method must have type 'QWidget'

答:
You do your inheritance wrong.

How it should be in declarations?
class Ui_Dialog should inherit all properties from QtWidgets.QDialog. Your Dialog variable should be self. You shouldn't call your functions with Dialog variable.

Your main mistakes:

```<code>class Ui_Dialog => class Ui_Dialog(QtWidgets.QDialog)
self.gridLayout = QtWidgets.QGridLayout(Dialog) => self.gridLayout = QtWidgets.QGridLayout(self)
#all should be changed like this
ui.setupUi(Dialog)=>ui.setupUi()
</code>```

Code:

```<code>class Ui_Dialog(QtWidgets.QDialog):

    def setupUi(self):
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setObjectName("Dialog")
        self.resize(400, 274)

        self.gridLayout = QtWidgets.QGridLayout(self)
        ... #your stuff

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    #Dialog = QtWidgets.QDialog()

    ui = Ui_Dialog()
    ui.setupUi()
    ui.show()
    sys.exit(app.exec_())
</code>```

Body:
I can't use setWindowFlags with my QDialog widget. am trying to hide the close button or remove the whole frame so the user can't close it using the default method.

I've tried adding one of those two lines inside the setupUi function for my class :

self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

and

self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False) but both gave me the same error.

Here is my code for a better inspection:

import os
import sys

import psycopg2
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMessageBox

import backoffice

class Ui_Dialog(object):

    def setupUi(self, Dialog):
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 274)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(self.resource_path("./images/pos_logo_small.png")), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        Dialog.setWindowIcon(icon)
        Dialog.setLayoutDirection(QtCore.Qt.RightToLeft)
        Dialog.setStyleSheet("background:#a1d0f4;")
        self.gridLayout = QtWidgets.QGridLayout(Dialog)
        self.gridLayout.setObjectName("gridLayout")
        self.formLayout = QtWidgets.QFormLayout()
        self.formLayout.setHorizontalSpacing(4)
        self.formLayout.setObjectName("formLayout")
        self.label_2 = QtWidgets.QLabel(Dialog)
        font = QtGui.QFont()
        font.setFamily("Shorooq_N1")
        font.setPointSize(18)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2)
        self.label_3 = QtWidgets.QLabel(Dialog)
        font = QtGui.QFont()
        font.setFamily("Shorooq_N1")
        font.setPointSize(18)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_3)
        self.lineEdit = QtWidgets.QLineEdit(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit.setStyleSheet("background:white;")
        self.lineEdit.setObjectName("lineEdit")

        self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.lineEdit)
        self.lineEdit_2 = QtWidgets.QLineEdit(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
        self.lineEdit_2.setSizePolicy(sizePolicy)
        self.lineEdit_2.setStyleSheet("background:white;")
        self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.lineEdit_2)
        self.closeToolButton = QtWidgets.QToolButton(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.closeToolButton.sizePolicy().hasHeightForWidth())
        self.closeToolButton.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Shorooq_N1")
        font.setPointSize(18)
        font.setBold(False)
        font.setWeight(50)
        self.closeToolButton.setFont(font)
        self.closeToolButton.setStyleSheet("background:red;color:white;")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(self.resource_path("./images/close-window-256.ico")), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.closeToolButton.setIcon(icon1)
        self.closeToolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.closeToolButton.setObjectName("closeToolButton")
        self.closeToolButton.clicked.connect(self.exit_app)
        self.formLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.closeToolButton)
        self.logInToolButton = QtWidgets.QToolButton(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.logInToolButton.sizePolicy().hasHeightForWidth())
        self.logInToolButton.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Shorooq_N1")
        font.setPointSize(16)
        self.logInToolButton.setFont(font)
        self.logInToolButton.setStyleSheet("background:#0a74c4;color:white;")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(self.resource_path("./images/check-mark-11-256.ico")), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.logInToolButton.setIcon(icon2)
        self.logInToolButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.logInToolButton.setObjectName("logInToolButton")
        self.dialog = Dialog
        self.logInToolButton.clicked.connect(self.log_in)
        self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.logInToolButton)
        self.gridLayout.addLayout(self.formLayout, 1, 1, 1, 1)
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 1, 1, 1)
        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def exit_app(self):
        QtCore.QCoreApplication.instance().quit()

    def log_in(self):
        print('activated')
        try:
            connection = psycopg2.connect(user="*******",
                                          password="********",
                                          host="127.0.0.1",
                                          port="5432",
                                          database="********")
            cursor = connection.cursor()
            postgreSQL_select_Query = "select * from users"
            cursor.execute(postgreSQL_select_Query)
            print("Selecting rows from users table using cursor.fetchall")
            user_records = cursor.fetchall()
            print("Print each row and it's columns values")
            input_username = self.lineEdit.text()
            input_password = self.lineEdit_2.text()
            for row in user_records:
                if row[1] == input_username:
                    if row[2] == input_password:
                        backoffice.isAuthenticated = True
                        print('logged in ')
                        self.dialog.close()
                else:
                    pass
                print(input)
        except (Exception, psycopg2.Error) as error:
            print("Error while fetching data from PostgreSQL", error)
        finally:
            # closing database connection.
            connection = psycopg2.connect(user="*********",
                                          password="*******",
                                          host="127.0.0.1",
                                          port="5432",
                                          database="*******")
            cursor = connection.cursor()
            if (connection):
                cursor.close()
                connection.close()
                print("PostgreSQL connection is closed")

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Vision Store Manager"))
        self.label_2.setText(_translate("Dialog", "إسم المستخدم"))
        self.label_3.setText(_translate("Dialog", "كلمة المرور"))
        self.closeToolButton.setText(_translate("Dialog", "خروج"))
        self.logInToolButton.setText(_translate("Dialog", "تسجيل الدخول"))
        self.label.setText(_translate("Dialog",
                                      "

"))

    @staticmethod
    def resource_path(relative_path):
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

import login_rcs_rc

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()

    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

Getting the error AttributeError: 'Ui_Dialog' object has no attribute 'setWindowFlags' when executing the line : self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

UPDATE

I changed :
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
To

the_login = QtWidgets.QDialog
the_login.setWindowFlags(QtCore.Qt.FramelessWindowHint)

and the error now is:TypeError: setWindowFlags(self, Union[Qt.WindowFlags, Qt.WindowType]): first argument of unbound method must have type 'QWidget'

Body:
You do your inheritance wrong.

How it should be in declarations?
class Ui_Dialog should inherit all properties from QtWidgets.QDialog. Your Dialog variable should be self. You shouldn't call your functions with Dialog variable.

Your main mistakes:

class Ui_Dialog => class Ui_Dialog(QtWidgets.QDialog)
self.gridLayout = QtWidgets.QGridLayout(Dialog) => self.gridLayout = QtWidgets.QGridLayout(self)
#all should be changed like this
ui.setupUi(Dialog)=>ui.setupUi()

Code:

class Ui_Dialog(QtWidgets.QDialog):

    def setupUi(self):
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setObjectName("Dialog")
        self.resize(400, 274)

        self.gridLayout = QtWidgets.QGridLayout(self)
        ... #your stuff

if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    #Dialog = QtWidgets.QDialog()

    ui = Ui_Dialog()
    ui.setupUi()
    ui.show()
    sys.exit(app.exec_())


问:
Error while building Android Apk using terminal Command
While building android application using command line I am getting this issue as shown below .How to get rid of this using command line.

```<code>Note: Recompile with -Xlint:deprecation for details.
</code>```

How to remove this  -Xlint using command I am getting solution as gradle change

```<code>allprojects {
tasks.withType(JavaCompile) {
    options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}}
</code>```

I am not able to get the command line . Please help me to find a solution thanks in advance.

答:
Try this:

```<code>allprojects {
    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
        }
    }
}
</code>```

You should be able to build again via command line.

This will give more information about which classes/methods are deprecated. This way, you can check and fix those warnings properly

Body:
While building android application using command line I am getting this issue as shown below .How to get rid of this using command line.

Note: Recompile with -Xlint:deprecation for details.

How to remove this  -Xlint using command I am getting solution as gradle change

allprojects {
tasks.withType(JavaCompile) {
    options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}}

I am not able to get the command line . Please help me to find a solution thanks in advance.

Body:
Try this:

allprojects {
    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
        }
    }
}

You should be able to build again via command line.

This will give more information about which classes/methods are deprecated. This way, you can check and fix those warnings properly