问:
Datadog Grok Parsing - extracting fields from nested JSON
Is it possible to extract json fields that are nested inside a log?

Sample I've been work on:

```<code>thread-191555 app.main - [cid: 2cacd6f9-546d-41ew-a7ce-d5d41b39eb8f, uid: e6ffc3b0-2f39-44f7-85b6-1abf5f9ad970] Request: protocol=[HTTP/1.0] method=[POST] path=[/metrics] headers=[Timeout-Access: <function1>, Remote-Address: 192.168.0.1:37936, Host: app:5000, Connection: close, X-Real-Ip: 192.168.1.1, X-Forwarded-For: 192.168.1.1, Authorization: ***, Accept: application/json, text/plain, */*, Referer: https://google.com, Accept-Language: cs-CZ, Accept-Encoding: gzip, deflate, User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko, Cache-Control: no-cache] entity=[HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }
</code>```

what I wanted to achieve was:

```<code>{
"extract": "text",
"duration": "451"
}
</code>```

I tried to combine a sample regex ("(extract)"\s*:\s*"([^"]+)",?) with example_parser %{data::json} (using the JSON as a log sample data, for starters) but I haven't managed to get anything working.

Thanks in advance!

答:
Is that sample text formatted properly? The final entity object is missing a ] from the end.

entity=[HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }

should be

entity=[HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }]

I'm going to continue these instructions assuming that was a typo and the entity field actually ends with ]. If it doesn't, I think you need to fix the underlying log to be formatted properly and close out the bracket.

Instead of just skipping the entire log and only parsing out that json bit, I decided to parse the entire thing and show what would look good as a final result. So the first thing we need to do is pull out that set of key/value pairs after the request object:

Example Input: thread-191555 app.main - [cid: 2cacd6f9-546d-41ew-a7ce-d5d41b39eb8f, uid: e6ffc3b0-2f39-44f7-85b6-1abf5f9ad970] Request: protocol=[HTTP/1.0] method=[POST] path=[/metrics] headers=[Timeout-Access: <function1>, Remote-Address: 192.168.0.1:37936, Host: app:5000, Connection: close, X-Real-Ip: 192.168.1.1, X-Forwarded-For: 192.168.1.1, Authorization: ***, Accept: application/json, text/plain, */*, Referer: https://google.com, Accept-Language: cs-CZ, Accept-Encoding: gzip, deflate, User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko, Cache-Control: no-cache] entity=[HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }]

Grok parser rule: app_log thread-%{integer:thread} %{notSpace:file} - \[%{data::keyvalue(": ")}\] Request: %{data:request:keyvalue("=","","[]")}

Result:

```<code>{
  "thread": 191555,
  "file": "app.main",
  "cid": "2cacd6f9-546d-41ew-a7ce-d5d41b39eb8f",
  "uid": "e6ffc3b0-2f39-44f7-85b6-1abf5f9ad970",
  "request": {
    "protocol": "HTTP/1.0",
    "method": "POST",
    "path": "/metrics",
    "headers": "Timeout-Access: <function1>, Remote-Address: 192.168.0.1:37936, Host: app:5000, Connection: close, X-Real-Ip: 192.168.1.1, X-Forwarded-For: 192.168.1.1, Authorization: ***, Accept: application/json, text/plain, */*, Referer: https://google.com, Accept-Language: cs-CZ, Accept-Encoding: gzip, deflate, User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko, Cache-Control: no-cache",
    "entity": "HttpEntity.Strict application/json {\"type\":\"text\",\"extract\": \"text\", \"field2\":\"text2\",\"duration\": 451 }"
  }
}
</code>```

Notice how we use the keyvalue parser with a quoting string of [], that allows us to easily pull out everything from the request object.

Now the goal is to pull out the details from that entity field inside of the request object. With Grok parsers you can specify a specific attribute to parse further.

So in that same pipeline we'll add another grok parser processor, right after our first

And then configure the advanced options section to run on request.entity, since that is what we called the attribute

Example Input: HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }

Grok Parser Rule: entity_rule %{notSpace:request.entity.class} %{notSpace:request.entity.media_type} %{data:request.entity.json:json}

Result:

```<code>{
  "request": {
    "entity": {
      "class": "HttpEntity.Strict",
      "media_type": "application/json",
      "json": {
        "duration": 451,
        "extract": "text",
        "type": "text",
        "field2": "text2"
      }
    }
  }
}
</code>```

Now when we look at the final parsed log it has everything we need broken out:

Also just because it was really simple, I threw in a third grok processor for the headers chunk as well (the advanced settings are set to parse from request.headers):

Example Input: Timeout-Access: <function1>, Remote-Address: 192.168.0.1:37936, Host: app:5000, Connection: close, X-Real-Ip: 192.168.1.1, X-Forwarded-For: 192.168.1.1, Authorization: ***, Accept: application/json, text/plain, */*, Referer: https://google.com, Accept-Language: cs-CZ, Accept-Encoding: gzip, deflate, User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko, Cache-Control: no-cache

Grok Parser Rule: headers_rule %{data:request.headers:keyvalue(": ", "/)(; :")}

Result:

```<code>{
  "request": {
    "headers": {
      "Timeout-Access": "function1",
      "Remote-Address": "192.168.0.1:37936",
      "Host": "app:5000",
      "Connection": "close",
      "X-Real-Ip": "192.168.1.1",
      "X-Forwarded-For": "192.168.1.1",
      "Accept": "application/json",
      "Referer": "https://google.com",
      "Accept-Language": "cs-CZ",
      "Accept-Encoding": "gzip",
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
      "Cache-Control": "no-cache"
    }
  }
}
</code>```

The only tricky bit here is that I had to define a characterWhiteList of /)(; :. Mostly to handle all those special characters are in the User-Agent field.

References:

Just the documentation and some guess & checking in my personal Datadog account.

https://docs.datadoghq.com/logs/processing/parsing/?tab=matcher#key-value-or-logfmt

Body:
Is it possible to extract json fields that are nested inside a log?

Sample I've been work on:

thread-191555 app.main - [cid: 2cacd6f9-546d-41ew-a7ce-d5d41b39eb8f, uid: e6ffc3b0-2f39-44f7-85b6-1abf5f9ad970] Request: protocol=[HTTP/1.0] method=[POST] path=[/metrics] headers=[Timeout-Access: <function1>, Remote-Address: 192.168.0.1:37936, Host: app:5000, Connection: close, X-Real-Ip: 192.168.1.1, X-Forwarded-For: 192.168.1.1, Authorization: ***, Accept: application/json, text/plain, */*, Referer: https://google.com, Accept-Language: cs-CZ, Accept-Encoding: gzip, deflate, User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko, Cache-Control: no-cache] entity=[HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }

what I wanted to achieve was:

{
"extract": "text",
"duration": "451"
}

I tried to combine a sample regex ("(extract)"\s*:\s*"([^"]+)",?) with example_parser %{data::json} (using the JSON as a log sample data, for starters) but I haven't managed to get anything working.

Thanks in advance!

Body:
Is that sample text formatted properly? The final entity object is missing a ] from the end.

entity=[HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }

should be

entity=[HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }]

I'm going to continue these instructions assuming that was a typo and the entity field actually ends with ]. If it doesn't, I think you need to fix the underlying log to be formatted properly and close out the bracket.

Instead of just skipping the entire log and only parsing out that json bit, I decided to parse the entire thing and show what would look good as a final result. So the first thing we need to do is pull out that set of key/value pairs after the request object:

Example Input: thread-191555 app.main - [cid: 2cacd6f9-546d-41ew-a7ce-d5d41b39eb8f, uid: e6ffc3b0-2f39-44f7-85b6-1abf5f9ad970] Request: protocol=[HTTP/1.0] method=[POST] path=[/metrics] headers=[Timeout-Access: <function1>, Remote-Address: 192.168.0.1:37936, Host: app:5000, Connection: close, X-Real-Ip: 192.168.1.1, X-Forwarded-For: 192.168.1.1, Authorization: ***, Accept: application/json, text/plain, */*, Referer: https://google.com, Accept-Language: cs-CZ, Accept-Encoding: gzip, deflate, User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko, Cache-Control: no-cache] entity=[HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }]

Grok parser rule: app_log thread-%{integer:thread} %{notSpace:file} - \[%{data::keyvalue(": ")}\] Request: %{data:request:keyvalue("=","","[]")}

Result:

{
  "thread": 191555,
  "file": "app.main",
  "cid": "2cacd6f9-546d-41ew-a7ce-d5d41b39eb8f",
  "uid": "e6ffc3b0-2f39-44f7-85b6-1abf5f9ad970",
  "request": {
    "protocol": "HTTP/1.0",
    "method": "POST",
    "path": "/metrics",
    "headers": "Timeout-Access: <function1>, Remote-Address: 192.168.0.1:37936, Host: app:5000, Connection: close, X-Real-Ip: 192.168.1.1, X-Forwarded-For: 192.168.1.1, Authorization: ***, Accept: application/json, text/plain, */*, Referer: https://google.com, Accept-Language: cs-CZ, Accept-Encoding: gzip, deflate, User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko, Cache-Control: no-cache",
    "entity": "HttpEntity.Strict application/json {\"type\":\"text\",\"extract\": \"text\", \"field2\":\"text2\",\"duration\": 451 }"
  }
}

Notice how we use the keyvalue parser with a quoting string of [], that allows us to easily pull out everything from the request object.

Now the goal is to pull out the details from that entity field inside of the request object. With Grok parsers you can specify a specific attribute to parse further.

So in that same pipeline we'll add another grok parser processor, right after our first

And then configure the advanced options section to run on request.entity, since that is what we called the attribute

Example Input: HttpEntity.Strict application/json {"type":"text","extract": "text", "field2":"text2","duration": 451 }

Grok Parser Rule: entity_rule %{notSpace:request.entity.class} %{notSpace:request.entity.media_type} %{data:request.entity.json:json}

Result:

{
  "request": {
    "entity": {
      "class": "HttpEntity.Strict",
      "media_type": "application/json",
      "json": {
        "duration": 451,
        "extract": "text",
        "type": "text",
        "field2": "text2"
      }
    }
  }
}

Now when we look at the final parsed log it has everything we need broken out:

Also just because it was really simple, I threw in a third grok processor for the headers chunk as well (the advanced settings are set to parse from request.headers):

Example Input: Timeout-Access: <function1>, Remote-Address: 192.168.0.1:37936, Host: app:5000, Connection: close, X-Real-Ip: 192.168.1.1, X-Forwarded-For: 192.168.1.1, Authorization: ***, Accept: application/json, text/plain, */*, Referer: https://google.com, Accept-Language: cs-CZ, Accept-Encoding: gzip, deflate, User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko, Cache-Control: no-cache

Grok Parser Rule: headers_rule %{data:request.headers:keyvalue(": ", "/)(; :")}

Result:

{
  "request": {
    "headers": {
      "Timeout-Access": "function1",
      "Remote-Address": "192.168.0.1:37936",
      "Host": "app:5000",
      "Connection": "close",
      "X-Real-Ip": "192.168.1.1",
      "X-Forwarded-For": "192.168.1.1",
      "Accept": "application/json",
      "Referer": "https://google.com",
      "Accept-Language": "cs-CZ",
      "Accept-Encoding": "gzip",
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
      "Cache-Control": "no-cache"
    }
  }
}

The only tricky bit here is that I had to define a characterWhiteList of /)(; :. Mostly to handle all those special characters are in the User-Agent field.

References:

Just the documentation and some guess & checking in my personal Datadog account.

https://docs.datadoghq.com/logs/processing/parsing/?tab=matcher#key-value-or-logfmt


来源: stackexchange

问:
Get file size from Google Drive Api (python)
I'm trying to figure out how to retrieve the file size of a file uploaded to Google Drive.  According to the docs this should be in the file metadata... but when I request it, file size is not in the metadata at all.

```<code>file = self.drive_service.files().get(fileId=file_id).execute()
print(file)

>>> {u'mimeType': u'application/x-zip', u'kind': u'drive#file', u'id': u'0B3JGbAfem1CrWnhtWq5qYlkzSXf', u'name': u'myfile.ipa'}
</code>```

What am I missing here?  How can I check the file size?

答:
Passing 'size' within fields should work.

Example: fields='size'

Although if the file is native to Google Drive such as a file made within Google Docs or Sheets those files do not take up space against your quota and thus don't have a size.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to figure out how to retrieve the file size of a file uploaded to Google Drive.  According to the docs this should be in the file metadata... but when I request it, file size is not in the metadata at all.

file = self.drive_service.files().get(fileId=file_id).execute()
print(file)

>>> {u'mimeType': u'application/x-zip', u'kind': u'drive#file', u'id': u'0B3JGbAfem1CrWnhtWq5qYlkzSXf', u'name': u'myfile.ipa'}

What am I missing here?  How can I check the file size?

ContentLicense: CC BY-SA 4.0


问:
jQuery problem selecting text only from table cell when there is an image
I'm using jQuery (well, cheerio) to scrape data from an html table. I'm trying to display data from one column that has text as well as an image in the cell, but I only want it to display the text.

for example the table looks like:

```<code>col 1          | col 2     | col 3
---------------------------------------
data 1-1 [img] | data 1-2  | data 1-3
data 2-1 [img] | data 2-2  | data 2-3
data 3-1 [img] | data 3-2  | data 3-3
data 4-1 [img] | data 4-2  | data 4-3
</code>```

When I select like this: $(this).children().next().text() it outputs everything in that row, like this: data 1-1 data 1-2 data 1-3

It works when I do $(this).children().next().html() but then the output is this: data 1-1 , obviously because it's including the html of the image in that column.

How do I get it to only select data 1-1 without including the img or the rest of that row?

I'm very new to jQuery so I've been having a hard time with this. Apologies if this question was already asked, I couldn't find anything about it...I've left out some code for simplicity but let me know if you'd like to see the entire function

UPDATE: ANSWER

Thank you to Roko for the help, here is the solution implemented with my full code (i used .eq(0) instead of tr:eq(0) because I'm using cheerio)

router.get("/scrape", function(req, res){
    request("http://link-goes-here", function(error, response, html){
        var $ = cheerio.load(html);
        var storeInfo = [];
        $("body > table > tbody > tr > td:nth-child(1) > table").addClass("row");
        //loop through selected table only where tr = "QA1"
        $('.row > tbody > tr:contains("QA1")').each(function(i, element){
            var result = {
                "environment" : $(this).children().next().eq(0).text(),
                "store" : $(this).children().next().next().html(),
                "version" : $(this).children().next().next().next().html()
            };
            storeInfo.push(result);
        });
    });
    res.redirect("/stores");
});
```

答:
You could use :eq() selector  or the .eq() method to get a specific Row index and than a specific cell index.

Example getting the .text() of the TBODY's first TR :eq(0) and its first TD :eq(0)

const val = $("#someTable").find("tbody tr:eq(0) td:eq(0)").text();
console.log(val);   // "data 1-1" ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="someTable">
<thead>
  <tr><th>Col 1</th><th>Col 2</th><th>Col 3</th></tr>
</thead>
<tbody>
  <tr><td>data 1-1 <img src="//placehold.it/50x50"></td><td>data 1-2</td><td>data 1-3</td></tr>
  <tr><td>data 2-1 <img src="//placehold.it/50x50"></td><td>data 2-2</td><td>data 2-3</td></tr>
  <tr><td>data 3-1 <img src="//placehold.it/50x50"></td><td>data 3-2</td><td>data 3-3</td></tr>
  <tr><td>data 4-1 <img src="//placehold.it/50x50"></td><td>data 4-2</td><td>data 4-3</td></tr>
</tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

To get the second row's first cell simply use tr:eq(1) and td:eq(0). And so on

Body:
I'm using jQuery (well, cheerio) to scrape data from an html table. I'm trying to display data from one column that has text as well as an image in the cell, but I only want it to display the text.

for example the table looks like:

col 1          | col 2     | col 3
---------------------------------------
data 1-1 [img] | data 1-2  | data 1-3
data 2-1 [img] | data 2-2  | data 2-3
data 3-1 [img] | data 3-2  | data 3-3
data 4-1 [img] | data 4-2  | data 4-3

When I select like this: $(this).children().next().text() it outputs everything in that row, like this: data 1-1 data 1-2 data 1-3

It works when I do $(this).children().next().html() but then the output is this: data 1-1 , obviously because it's including the html of the image in that column.

How do I get it to only select data 1-1 without including the img or the rest of that row?

I'm very new to jQuery so I've been having a hard time with this. Apologies if this question was already asked, I couldn't find anything about it...I've left out some code for simplicity but let me know if you'd like to see the entire function

UPDATE: ANSWER

Thank you to Roko for the help, here is the solution implemented with my full code (i used .eq(0) instead of tr:eq(0) because I'm using cheerio)

router.get("/scrape", function(req, res){
    request("http://link-goes-here", function(error, response, html){
        var $ = cheerio.load(html);
        var storeInfo = [];
        $("body > table > tbody > tr > td:nth-child(1) > table").addClass("row");
        //loop through selected table only where tr = "QA1"
        $('.row > tbody > tr:contains("QA1")').each(function(i, element){
            var result = {
                "environment" : $(this).children().next().eq(0).text(),
                "store" : $(this).children().next().next().html(),
                "version" : $(this).children().next().next().next().html()
            };
            storeInfo.push(result);
        });
    });
    res.redirect("/stores");
});

Body:
You could use :eq() selector  or the .eq() method to get a specific Row index and than a specific cell index.

Example getting the .text() of the TBODY's first TR :eq(0) and its first TD :eq(0)

const val = $("#someTable").find("tbody tr:eq(0) td:eq(0)").text();
console.log(val);   // "data 1-1"

<table id="someTable">
<thead>
  <tr><th>Col 1</th><th>Col 2</th><th>Col 3</th></tr>
</thead>
<tbody>
  <tr><td>data 1-1 <img src="//placehold.it/50x50"></td><td>data 1-2</td><td>data 1-3</td></tr>
  <tr><td>data 2-1 <img src="//placehold.it/50x50"></td><td>data 2-2</td><td>data 2-3</td></tr>
  <tr><td>data 3-1 <img src="//placehold.it/50x50"></td><td>data 3-2</td><td>data 3-3</td></tr>
  <tr><td>data 4-1 <img src="//placehold.it/50x50"></td><td>data 4-2</td><td>data 4-3</td></tr>
</tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

To get the second row's first cell simply use tr:eq(1) and td:eq(0). And so on


问:
Doing computation on folders
I have a main directory and 9 subfolders within. I have to first read the path and in each folder excluding specific files and plotting the result with the legend of the name of the folder. The problem is that I can see the files which I need to do computations but then it does not work anything. The code that I wrote is below:

```<code>from __future__ import division
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import glob
import seaborn as sns
from scipy import stats
from scipy.stats.kde import gaussian_kde

mean_curv = []
FILES=[]
for r, d, f in os.walk(r'C:\Users\Hasan\Desktop\output\new our scenario\beta 15\test'):
    for dirs in d:
        CASES = [f for f in sorted(files) if f.startswith('config')]
        maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in CASES])

        CASES = ['configuration_%d.out' % i for i in range(maxnum)]
        FILES.append(CASES)
        for i, d in enumerate(FILES):
            a = np.loadtxt(d).T
            num = os.path.splitext(d)[0]
            local_curv = np.abs(a[4])
        mean_curv.append(np.mean(local_curv))
Time = np.arange(0,len(mean_curv))
plt.plot(Time,mean_curv)
</code>```

The error that I have gotten is below:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-62-4e1e3e29813a> in <module>
      1 for i, d in enumerate(RIVERS):
----> 2     a = np.loadtxt(d).T
      3     num = os.path.splitext(d)[0]
      4     local_curv = np.abs(a[4])
      5     mean_curv.append(np.mean(local_curv))

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin, encoding, max_rows)
   1157         # converting the data
   1158         X = None
-> 1159         for x in read_data(_loadtxt_chunksize):
   1160             if X is None:
   1161                 X = np.array(x, dtype)

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in read_data(chunk_size)
   1085
   1086             # Convert each value according to its column and store
-> 1087             items = [conv(val) for (conv, val) in zip(converters, vals)]
   1088
   1089             # Then pack it according to the dtype's nesting

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in <listcomp>(.0)
   1085
   1086             # Convert each value according to its column and store
-> 1087             items = [conv(val) for (conv, val) in zip(converters, vals)]
   1088
   1089             # Then pack it according to the dtype's nesting

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in floatconv(x)
    792         if '0x' in x:
    793             return float.fromhex(x)
--> 794         return float(x)
    795
    796     typ = dtype.type

ValueError: could not convert string to float: 'configuration_0.out'
</code>```

答:
You're ignoring the path to the files, instead of:

```<code>a = np.loadtxt(d).T
</code>```

you should use:

```<code>a = np.loadtxt(os.path.join(r, d)).T
</code>```

Title: Doing computation on folders

Body:
I have a main directory and 9 subfolders within. I have to first read the path and in each folder excluding specific files and plotting the result with the legend of the name of the folder. The problem is that I can see the files which I need to do computations but then it does not work anything. The code that I wrote is below:

from __future__ import division
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import glob
import seaborn as sns
from scipy import stats
from scipy.stats.kde import gaussian_kde

mean_curv = []
FILES=[]
for r, d, f in os.walk(r'C:\Users\Hasan\Desktop\output\new our scenario\beta 15\test'):
    for dirs in d:
        CASES = [f for f in sorted(files) if f.startswith('config')]
        maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in CASES])

        CASES = ['configuration_%d.out' % i for i in range(maxnum)]
        FILES.append(CASES)
        for i, d in enumerate(FILES):
            a = np.loadtxt(d).T
            num = os.path.splitext(d)[0]
            local_curv = np.abs(a[4])
        mean_curv.append(np.mean(local_curv))
Time = np.arange(0,len(mean_curv))
plt.plot(Time,mean_curv)

The error that I have gotten is below:

ValueError                                Traceback (most recent call last)
<ipython-input-62-4e1e3e29813a> in <module>
      1 for i, d in enumerate(RIVERS):
----> 2     a = np.loadtxt(d).T
      3     num = os.path.splitext(d)[0]
      4     local_curv = np.abs(a[4])
      5     mean_curv.append(np.mean(local_curv))

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin, encoding, max_rows)
   1157         # converting the data
   1158         X = None
-> 1159         for x in read_data(_loadtxt_chunksize):
   1160             if X is None:
   1161                 X = np.array(x, dtype)

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in read_data(chunk_size)
   1085
   1086             # Convert each value according to its column and store
-> 1087             items = [conv(val) for (conv, val) in zip(converters, vals)]
   1088
   1089             # Then pack it according to the dtype's nesting

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in <listcomp>(.0)
   1085
   1086             # Convert each value according to its column and store
-> 1087             items = [conv(val) for (conv, val) in zip(converters, vals)]
   1088
   1089             # Then pack it according to the dtype's nesting

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in floatconv(x)
    792         if '0x' in x:
    793             return float.fromhex(x)
--> 794         return float(x)
    795
    796     typ = dtype.type

ValueError: could not convert string to float: 'configuration_0.out'

Body:
You're ignoring the path to the files, instead of:

a = np.loadtxt(d).T

you should use:

a = np.loadtxt(os.path.join(r, d)).T


问:
Spring4 MVC keep session alive forever
I have a scenario where session is getting expired after some time of inactivity, But i need to keep Spring 4 MVC keep session alive forever.
Below is my Spring Initializer class,

'''public class SpringWebAppInitializer implements WebApplicationInitializer {

```<code>@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
    appContext.register(ApplicationContextConfig.class);

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
            "SpringDispatcher", new DispatcherServlet(appContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

}
</code>```

}'''

答:
Use -1 in  tag because -1 is for session never expires.

Web.xml:

```<code><session-config>
    <session-timeout>-1</session-timeout>
</session-config>
</code>```

Title: Spring4 MVC keep session alive forever

Body:
I have a scenario where session is getting expired after some time of inactivity, But i need to keep Spring 4 MVC keep session alive forever.
Below is my Spring Initializer class,

'''public class SpringWebAppInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
    appContext.register(ApplicationContextConfig.class);

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
            "SpringDispatcher", new DispatcherServlet(appContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

}

}'''

Body:
Use -1 in  tag because -1 is for session never expires.

Web.xml:

<session-config>
    <session-timeout>-1</session-timeout>
</session-config>


问:
Boolean defaultValue MapStruct
I'm trying to set a defaultValue for a boolean field using MapStruct, but the generated code simply ignores it.

My code:

```<code>public class CreateEventRequest {

    @NotNull
    @JsonProperty
    private Boolean isPrivate;

    @JsonProperty
    private Boolean friendCanInviteFriends;

    @JsonProperty
    private boolean showGuestList;

    public boolean isPrivate() {
      return isPrivate;
     }

     public String getDescription() {
       return description;
     }

      public boolean isFriendCanInviteFriends() {
        return friendCanInviteFriends;
     }

      public boolean isShowGuestList() {
        return showGuestList;
     }
}
</code>```

My mapper:

```<code>@Mapper(componentModel = "spring")
public interface CreateEventRequestMapper {
    @Mapping(target = "showGuestList", source = "showGuestList", defaultExpression = "java(true)")
    @Mapping(target = "friendCanInviteFriends", source = "friendCanInviteFriends", defaultValue = "true")
    Event map(CreateEventRequest request);
}
</code>```

The generated code:

```<code>public class CreateEventRequestMapperImpl implements CreateEventRequestMapper {

    @Override
    public Event map(CreateEventRequest request) {
        if ( request == null ) {
            return null;
        }

        Event event = new Event();

        event.setShowGuestList( request.isShowGuestList() );
        event.setFriendCanInviteFriends( request.isFriendCanInviteFriends() );
        event.setPrivate( request.isPrivate() );

        return event;
    }
}
</code>```

As you can see, I've tried using primitive/non-primitive type but it simply ignores the defaultValue.

Am I missing something here?

Thanks!

答:
The problem is that the return type of your getter methods in the source object is always primitive which can't be null, you need to return Boolean.

MapStruct doesn't support direct private field access which requires reflection.

Title: Boolean defaultValue MapStruct

Body:
I'm trying to set a defaultValue for a boolean field using MapStruct, but the generated code simply ignores it.

My code:

public class CreateEventRequest {

    @NotNull
    @JsonProperty
    private Boolean isPrivate;

    @JsonProperty
    private Boolean friendCanInviteFriends;

    @JsonProperty
    private boolean showGuestList;

    public boolean isPrivate() {
      return isPrivate;
     }

     public String getDescription() {
       return description;
     }

      public boolean isFriendCanInviteFriends() {
        return friendCanInviteFriends;
     }

      public boolean isShowGuestList() {
        return showGuestList;
     }
}

My mapper:

@Mapper(componentModel = "spring")
public interface CreateEventRequestMapper {
    @Mapping(target = "showGuestList", source = "showGuestList", defaultExpression = "java(true)")
    @Mapping(target = "friendCanInviteFriends", source = "friendCanInviteFriends", defaultValue = "true")
    Event map(CreateEventRequest request);
}

The generated code:

public class CreateEventRequestMapperImpl implements CreateEventRequestMapper {

    @Override
    public Event map(CreateEventRequest request) {
        if ( request == null ) {
            return null;
        }

        Event event = new Event();

        event.setShowGuestList( request.isShowGuestList() );
        event.setFriendCanInviteFriends( request.isFriendCanInviteFriends() );
        event.setPrivate( request.isPrivate() );

        return event;
    }
}

As you can see, I've tried using primitive/non-primitive type but it simply ignores the defaultValue.

Am I missing something here?

Thanks!


问:
Flutter: How to parse mutli array JSON
I have a JSON array - https://jsonplaceholder.typicode.com/users
and my code

```<code>  final String apiURL = 'https://jsonplaceholder.typicode.com/users';

  Future<List<GetUsers>> fetchJSONData() async {

    var jsonResponse = await http.get(apiURL);

    if (jsonResponse.statusCode == 200) {

      final jsonItems = json.decode(jsonResponse.body).cast<Map<String, dynamic>>();
      print(jsonItems);

      List<GetUsers> usersList = jsonItems.map<GetUsers>((json) {
        return GetUsers.fromJson(json);
      }).toList();

      return usersList;

    } else {
      throw Exception('Failed to load data from internet');
    }
  }
</code>```

How do I parse

"address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },

Street and city

And output it to ListTile
I just know how to output the first level of the array, but I don't understand how to parse the second one

答:
Suppose you want to get the street name of the first user then you can do that by

```<code>usersList[0]["address"]["street"]

</code>```

Here is the complete example:

```<code>
import "package:flutter/material.dart";
import "dart:convert";
import "package:http/http.dart" as http;

class JsonMultyParse extends StatefulWidget {
  @override
  _JsonMultyParseState createState() => _JsonMultyParseState();
}

class _JsonMultyParseState extends State<JsonMultyParse> {
  final String apiURL = 'https://jsonplaceholder.typicode.com/users';
  List<dynamic> users = [];
  void fetchJSONData() async {
    var jsonResponse = await http.get(apiURL);

    if (jsonResponse.statusCode == 200) {
      final jsonItems =
          json.decode(jsonResponse.body).cast<Map<String, dynamic>>();
      print(jsonItems[0]["address"]["street"]);
      setState(() {
        users = jsonItems;
      });

      for (dynamic user in users) {
        print(user["address"]["street"]);
      }
    } else {
      throw Exception('Failed to load data from internet');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          body: Container(
            child: Column(
              children: <Widget>[
                SizedBox(height: 20),
                RaisedButton(
                  onPressed: fetchJSONData,
                  child: Text("Fetch Data"),
                ),
                Expanded(
                  child: ListView.builder(
                      itemCount: users.length,
                      itemBuilder: (context, index) {
                        return Card(
                          child: Container(
                            height: 50,
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              users[index]["address"]["street"],
                            ),
                          ),
                        );
                      }),
                )
              ],
            ),
          ),
        ));
  }
}

</code>```

Output:

Title: Flutter: How to parse mutli array JSON

Body:
I have a JSON array - https://jsonplaceholder.typicode.com/users
and my code

  final String apiURL = 'https://jsonplaceholder.typicode.com/users';

  Future<List<GetUsers>> fetchJSONData() async {

    var jsonResponse = await http.get(apiURL);

    if (jsonResponse.statusCode == 200) {

      final jsonItems = json.decode(jsonResponse.body).cast<Map<String, dynamic>>();
      print(jsonItems);

      List<GetUsers> usersList = jsonItems.map<GetUsers>((json) {
        return GetUsers.fromJson(json);
      }).toList();

      return usersList;

    } else {
      throw Exception('Failed to load data from internet');
    }
  }

How do I parse

"address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },

Street and city

And output it to ListTile
I just know how to output the first level of the array, but I don't understand how to parse the second one

Body:
Suppose you want to get the street name of the first user then you can do that by

usersList[0]["address"]["street"]

Here is the complete example:

import "package:flutter/material.dart";
import "dart:convert";
import "package:http/http.dart" as http;

class JsonMultyParse extends StatefulWidget {
  @override
  _JsonMultyParseState createState() => _JsonMultyParseState();
}

class _JsonMultyParseState extends State<JsonMultyParse> {
  final String apiURL = 'https://jsonplaceholder.typicode.com/users';
  List<dynamic> users = [];
  void fetchJSONData() async {
    var jsonResponse = await http.get(apiURL);

    if (jsonResponse.statusCode == 200) {
      final jsonItems =
          json.decode(jsonResponse.body).cast<Map<String, dynamic>>();
      print(jsonItems[0]["address"]["street"]);
      setState(() {
        users = jsonItems;
      });

      for (dynamic user in users) {
        print(user["address"]["street"]);
      }
    } else {
      throw Exception('Failed to load data from internet');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          body: Container(
            child: Column(
              children: <Widget>[
                SizedBox(height: 20),
                RaisedButton(
                  onPressed: fetchJSONData,
                  child: Text("Fetch Data"),
                ),
                Expanded(
                  child: ListView.builder(
                      itemCount: users.length,
                      itemBuilder: (context, index) {
                        return Card(
                          child: Container(
                            height: 50,
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              users[index]["address"]["street"],
                            ),
                          ),
                        );
                      }),
                )
              ],
            ),
          ),
        ));
  }
}

Output:


问:
Duplicate symbols for architecture x86_64 under Xcode
I now have the same question with above title but have not found the right answer yet. I got the error:

```<code>    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
duplicate symbol _OBJC_METACLASS_$_MoboSDK in:
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
ld: 75 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Any help is appreciated.

Finally I find out the reason of this error cause I added -ObjC to the Other Linker Flags. After remove this value then I can build my project successfully, but I don't know why. Can anyone explain this?

答:
Update answer for 2021, Xcode 12.X:

```<code>pod deintegrate
pod install
</code>```

Hope this helps!

Body:
I now have the same question with above title but have not found the right answer yet. I got the error:

    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
duplicate symbol _OBJC_METACLASS_$_MoboSDK in:
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
    /Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
ld: 75 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any help is appreciated.

Finally I find out the reason of this error cause I added -ObjC to the Other Linker Flags. After remove this value then I can build my project successfully, but I don't know why. Can anyone explain this?

Body:
Update answer for 2021, Xcode 12.X:

pod deintegrate
pod install

Hope this helps!


问:
what is the scope of this variable in c++?
If i define a function like this

```<code>std::string& returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}
</code>```

and if i use this temp which is passed by reference to another function like this

```<code>void displaystring(std::string &temp)
{
    std::cout<<temp;
}
</code>```

would the string temp still be in scope when i pass it by reference to displaystring function?

答:
No. The scope of temp is limited to the block where it is declared. Because you declared it on stack (you didn't use the keyword new), the variable temp will be destroyed the moment you exit the function.
The only way to keep the variable would be to have the value of temp be copied to a variable outside the function. For example, this would work:

```<code>std::string returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}
</code>```

Because the return value is a copy rather than a reference, you could then do
    std::string returned_string = returnstring(ist);
And have the value of temp be copied into a newly declared variable that could be used for your displaystring function.

In general, I would avoid declaring variables inside a function that you will need outside the scope of the function. Instead, return by value whenever you are returning variables built inside of the function (not recommended for large arrays and objects, however).

Body:
If i define a function like this

std::string& returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}

and if i use this temp which is passed by reference to another function like this

void displaystring(std::string &temp)
{
    std::cout<<temp;
}

would the string temp still be in scope when i pass it by reference to displaystring function?

Body:
No. The scope of temp is limited to the block where it is declared. Because you declared it on stack (you didn't use the keyword new), the variable temp will be destroyed the moment you exit the function.
The only way to keep the variable would be to have the value of temp be copied to a variable outside the function. For example, this would work:

std::string returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}

Because the return value is a copy rather than a reference, you could then do
    std::string returned_string = returnstring(ist);
And have the value of temp be copied into a newly declared variable that could be used for your displaystring function.

In general, I would avoid declaring variables inside a function that you will need outside the scope of the function. Instead, return by value whenever you are returning variables built inside of the function (not recommended for large arrays and objects, however).


问:
django how to load url but stay on same page
I have a sign up button on my home page and when user clicks it, it opens sign-up modal form. The problem is I need to have a URL and view for sign-up form and when I click the button server redirects to signup URL and quits from my home page. How can I prevent this?

--Views.py

```<code>def register(request):
if request.method == 'POST':
    user_form = UserRegistrationForm(request.POST)
    if user_form.is_valid():
        #Create a new user object but avoid saving it yet
        new_user = user_form.save(commit=False)
        #Set the chosen password
        new_user.set_password(user_form.cleaned_data['password'])
        #Save the user object
        new_user.save()
        return redirect('home')
else:
    user_form = UserRegistrationForm()
return render(request,'account/signup.html',{'user_form':user_form})
</code>```

--urls.py

```<code>urlpatterns = [
  path('login/', auth_views.LoginView.as_view(authentication_form=LoginForm), name='login'),
  path('logout/', auth_views.LogoutView.as_view(), name='logout'),
  path('signup/', user_views.register, name='signup'),
</code>```

]

--signup.js

```<code>var signup_form = document.querySelector(".signup-form");

var trigger = document.querySelector(".signup-btn");

var closeBtn = document.querySelector(".close-btn");

function toggleModal(){
  signup_form.classList.toggle("show-signup-form");
 }

function windowOnClick(event) {
  if (event.target == signup_form){
    toggleModal();
  }
}

trigger.addEventListener("click", toggleModal);
closeBtn.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
</code>```

答: If want to prevent redirection. Try event.preventDefault() in your click function,</p>

Body:
I have a sign up button on my home page and when user clicks it, it opens sign-up modal form. The problem is I need to have a URL and view for sign-up form and when I click the button server redirects to signup URL and quits from my home page. How can I prevent this?

--Views.py

def register(request):
if request.method == 'POST':
    user_form = UserRegistrationForm(request.POST)
    if user_form.is_valid():
        #Create a new user object but avoid saving it yet
        new_user = user_form.save(commit=False)
        #Set the chosen password
        new_user.set_password(user_form.cleaned_data['password'])
        #Save the user object
        new_user.save()
        return redirect('home')
else:
    user_form = UserRegistrationForm()
return render(request,'account/signup.html',{'user_form':user_form})

--urls.py

urlpatterns = [
  path('login/', auth_views.LoginView.as_view(authentication_form=LoginForm), name='login'),
  path('logout/', auth_views.LogoutView.as_view(), name='logout'),
  path('signup/', user_views.register, name='signup'),

]

--signup.js

var signup_form = document.querySelector(".signup-form");

var trigger = document.querySelector(".signup-btn");

var closeBtn = document.querySelector(".close-btn");

function toggleModal(){
  signup_form.classList.toggle("show-signup-form");
 }

function windowOnClick(event) {
  if (event.target == signup_form){
    toggleModal();
  }
}

trigger.addEventListener("click", toggleModal);
closeBtn.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);


问:
python yaml load_all fetching wrong Keys
yaml.load all requires space after ":" to recognize the right key. If it does not find the space it will use the whole key value pair as key and then give None as value.

See below: OP print has 'B2_key:B2_VAL': None

```<code>test_item = "A1: {B1_key: b1_val, B2_key:B2_VAL}"
yaml_iterator = yaml.load_all(test_item, Loader=yaml.Loader)
op = {}
for item in yaml_iterator:
    op.update(item)
print(op)

Output print: {'A1': {'B1_key': 'b1_val', 'B2_key:B2_VAL': None}}
</code>```

I understand we can just have IP file in the right format. But is there a way we can handle it? i want users to not be care about spaces.

One way can be to inspect the the OP dict and handle it there.

Please advice best way to handle this. Thanks in advance.

答:
If you really don't want your users to care about the syntax and you have the yaml in a string, you could add spaces after the semicolons:

```<code>test_item = test_item.replace(':', ': ')
</code>```

Output:

```<code>{'A1': {'B1_key': 'b1_val', 'B2_key': 'B2_VAL'}}
</code>```

But this would only work if semicolons are not allowed in the keys and values.

Body:
yaml.load all requires space after ":" to recognize the right key. If it does not find the space it will use the whole key value pair as key and then give None as value.

See below: OP print has 'B2_key:B2_VAL': None

test_item = "A1: {B1_key: b1_val, B2_key:B2_VAL}"
yaml_iterator = yaml.load_all(test_item, Loader=yaml.Loader)
op = {}
for item in yaml_iterator:
    op.update(item)
print(op)

Output print: {'A1': {'B1_key': 'b1_val', 'B2_key:B2_VAL': None}}

I understand we can just have IP file in the right format. But is there a way we can handle it? i want users to not be care about spaces.

One way can be to inspect the the OP dict and handle it there.

Please advice best way to handle this. Thanks in advance.

Body:
If you really don't want your users to care about the syntax and you have the yaml in a string, you could add spaces after the semicolons:

test_item = test_item.replace(':', ': ')

Output:

{'A1': {'B1_key': 'b1_val', 'B2_key': 'B2_VAL'}}

But this would only work if semicolons are not allowed in the keys and values.


问:
SQL Statement with "dynamic" where clause

Possible Duplicate:

  Howto build a SQL statement with using IDs that might not be available in the table?

Hello together, I try to build a SQL statement with some unknown variables.
I would like to select the province, district, commune and village out of table dbo.pmd.
As there are only the IDs stored, I need to read the name out of the value table.
This is no problem for province and district as they will always be filled in table dbo.pmd. Anyhow the commune and village is not mandatory and might therefor be not filled.
This is where it comes to a problem if I compare the IDs between dbo.pmd and dbo.vhcs (communes) and dbo.pmd and dbo.vhv (villages) if there is no value stored in the dbo.pmd table.

The tables look like this:

table: dbo.pmd

fields: province, district, commune, village (stored value is the ID number)

table: dbo.vhp

fields: country_id, province_id, province_en (name of province)

table: dbo.vhd

fields: province_id, district_id, district_en (name of district)

table: dbo.vhc2

fields: district_id, commune_id, commune_en (name of commune)

table: dbo.vhv

fields: commune_id, village_id, village_en (name of commune)

My current statement looks like this:

```<code>SELECT pmd.patient_code, pmd.last_name, pmd.first_name, pmd.age, pmd.sex, pmd.province, pmd.district, pmd.commune, pmd.village
FROM dbo.pmd AS pmd
INNER JOIN dbo.vhp AS vhp
ON pmd.province = vhp.province_id
INNER JOIN dbo.vhd AS vhd
ON pmd.district = vhd.district_id
INNER JOIN dbo.vhc2 AS vhc2
ON (pmd.commune is NULL OR (pmd.commune = vhc2.commune_id))
INNER JOIN dbo.vhv AS vhv
ON (pmd.village is NULL OR (pmd.village = vhv.village_id))
ORDER BY pmd.last_name
</code>```

I have two entries in my database. One entry with commune_id and village_id = NULL and one with commune_id and village_id = some ID number.

I have stopped the execution of this statement after ~2minutes and there are: 8273612 rows all with the same values, showing only the entry with commund_id and village_id equals NULL.

I am using Microsoft SQL Server 2008.

答:
```<code>    INNER JOIN dbo.vhc2 AS vhc2
ON (pmd.commune is NULL OR (pmd.commune = vhc2.commune_id))
</code>```

You are inadvertently doing something like a cartesian join here. On a row where pmd.commune is NULL, pmd.commune IS NULL evaluates as true for every row in vhc2, causing every single row in vhc2 to be joined to that pmd row.

Your scenario this time around is a little bit different from what you described in your previous question, which is why the solution offered there is not helping you in your current situation.

Some variation on an outer join is what you want for vhc2 & vhv, e.g.:

```<code>LEFT OUTER JOIN dbo.vhc2 AS vhc2
ON  pmd.commune = vhc2.commune_id
</code>```

Body:
Possible Duplicate:

  Howto build a SQL statement with using IDs that might not be available in the table?

Hello together, I try to build a SQL statement with some unknown variables.
I would like to select the province, district, commune and village out of table dbo.pmd.
As there are only the IDs stored, I need to read the name out of the value table.
This is no problem for province and district as they will always be filled in table dbo.pmd. Anyhow the commune and village is not mandatory and might therefor be not filled.
This is where it comes to a problem if I compare the IDs between dbo.pmd and dbo.vhcs (communes) and dbo.pmd and dbo.vhv (villages) if there is no value stored in the dbo.pmd table.

The tables look like this:

table: dbo.pmd

fields: province, district, commune, village (stored value is the ID number)

table: dbo.vhp

fields: country_id, province_id, province_en (name of province)

table: dbo.vhd

fields: province_id, district_id, district_en (name of district)

table: dbo.vhc2

fields: district_id, commune_id, commune_en (name of commune)

table: dbo.vhv

fields: commune_id, village_id, village_en (name of commune)

My current statement looks like this:

SELECT pmd.patient_code, pmd.last_name, pmd.first_name, pmd.age, pmd.sex, pmd.province, pmd.district, pmd.commune, pmd.village
FROM dbo.pmd AS pmd
INNER JOIN dbo.vhp AS vhp
ON pmd.province = vhp.province_id
INNER JOIN dbo.vhd AS vhd
ON pmd.district = vhd.district_id
INNER JOIN dbo.vhc2 AS vhc2
ON (pmd.commune is NULL OR (pmd.commune = vhc2.commune_id))
INNER JOIN dbo.vhv AS vhv
ON (pmd.village is NULL OR (pmd.village = vhv.village_id))
ORDER BY pmd.last_name

I have two entries in my database. One entry with commune_id and village_id = NULL and one with commune_id and village_id = some ID number.

I have stopped the execution of this statement after ~2minutes and there are: 8273612 rows all with the same values, showing only the entry with commund_id and village_id equals NULL.

I am using Microsoft SQL Server 2008.

Body:
    INNER JOIN dbo.vhc2 AS vhc2
ON (pmd.commune is NULL OR (pmd.commune = vhc2.commune_id))

You are inadvertently doing something like a cartesian join here. On a row where pmd.commune is NULL, pmd.commune IS NULL evaluates as true for every row in vhc2, causing every single row in vhc2 to be joined to that pmd row.

Your scenario this time around is a little bit different from what you described in your previous question, which is why the solution offered there is not helping you in your current situation.

Some variation on an outer join is what you want for vhc2 & vhv, e.g.:

LEFT OUTER JOIN dbo.vhc2 AS vhc2
ON  pmd.commune = vhc2.commune_id


问:
Replacing NAs in a time variable in R
I am having issues when dealing with the NAs in my dataframe.

The variable that has all the NAs is a time variable in the format HMS. I want to replace the NAs with 00:00:00.

Here is an example of what I am looking at.

```<code>< time> 00:00:07, 00:00:02, NA, 00:00:00, NA, 00:00:00, 00:00:00, NA, 00:00:00
</code>```

Or a better view might be

```<code>glimpse(k$hold_time)
'hms' num [1:965201] 00:00:07 00:00:02 NA 00:00:00 ...
   - attr(*, "units")= chr "secs"
</code>```

I have tried to run the following code but it returns the same data with no changes.

```<code>K$hold_time[is.na(k$hold_time)] <- 0
</code>```

Also when I run this line it gives me the correct amount of NAs so I know that R is picking them up correctly.

```<code>sum(is.na(k$hold_time))
</code>```

Title: Replacing NAs in a time variable in R

Body:
I am having issues when dealing with the NAs in my dataframe.

The variable that has all the NAs is a time variable in the format HMS. I want to replace the NAs with 00:00:00.

Here is an example of what I am looking at.

< time> 00:00:07, 00:00:02, NA, 00:00:00, NA, 00:00:00, 00:00:00, NA, 00:00:00

Or a better view might be

glimpse(k$hold_time)
'hms' num [1:965201] 00:00:07 00:00:02 NA 00:00:00 ...
   - attr(*, "units")= chr "secs"

I have tried to run the following code but it returns the same data with no changes.

K$hold_time[is.na(k$hold_time)] <- 0

Also when I run this line it gives me the correct amount of NAs so I know that R is picking them up correctly.

sum(is.na(k$hold_time))

Body:
It looks like hold_time is of class hms. Try using :

k$hold_time[is.na(k$hold_time)] <- hms::hms(0)

Reproducible example :

set.seed(123)
k <- data.frame(hold_time = hms::hms(sample(100, 10)))
k$hold_time[c(5, 8)] <- NA
k

#   hold_time
#1   00:00:31
#2   00:01:19
#3   00:00:51
#4   00:00:14
#5         NA
#6   00:00:42
#7   00:00:50
#8         NA
#9   00:01:37
#10  00:00:25

k$hold_time[is.na(k$hold_time)] <- hms::hms(0)
k
#   hold_time
#1   00:00:31
#2   00:01:19
#3   00:00:51
#4   00:00:14
#5   00:00:00
#6   00:00:42
#7   00:00:50
#8   00:00:00
#9   00:01:37
#10  00:00:25


问:
Loading SDK Paypal Haw to do it?
I require the access token to make payment tests in Paypal

I can't move on this happened I don't know what to do. Sorry I am not a developer. I downloaded the Visual Studio code. in case it's of any use. Any help would be greatly appreciated.

答:
It looks like you have a REST App called "Prueba Pagos".  First, determine whether you want a Live or Sandbox Client ID, and toggle the appropriate mode.

Then click on the App's name to load it.  There will be a Client ID there.

If you don't know what to do with the Client ID, then you need a developer's help.

Title: Loading SDK Paypal Haw to do it?


问:
Node.js auto migrations
I have been doing Django for several years and was spoiled by their automigrations that they have supported for a very long time. Recently I started using SailsJS (which I am very new to) and noticed that it only supports alter for db migrations in development, NOT production. Is there any third party for node that does something to that effect? I looked at knex but that doesn't autodetect the changes made to my models. I'm looking for something similar to what Django has.

I read the below thoroughly:

https://sailsjs.com/documentation/concepts/models-and-orm/model-settings#?migrate

答: The only framework that has such functionality is the nestjs. The only downside it that it is not a pure js solution. It is typescript. But the functionality is heavily inspired in ORM frameworks like Django ORM.</p>

Title: Node.js auto migrations


问:
How to programmatically print without prompting for filename in MFC and CView using Print-To-PDF printer?
I have a large graphics program using C++, MFC, and C++6.0.
I need it to print to PDFs without prompting the user for printer settings and file name.

I use CView::OnPrint() to print using Microsoft Print-to-PDF and it works fine except for the user prompts.

I've seen how to bypass those prompts with a PrintDocument object in C# but how can I do that when using CView::OnPrint() in MFC? Surely there must be a way?

My project is much too big to consider re-writing in C#, and I've tried moving forward to Visual studio 2005/2010/2019 etc. without success as changes in default data structure packing and converting existing data files is fraught with problems so solution has to be an addition to existing MFC C++6.0 if at all possible.

Can anybody help?

答:
I haven't used VC++ 6 in quite a while now, so I'm going from rather distant memories, but the general idea is fairly simple.

Full Approach

Your view has a DoPreparePrinting member function. By default, this creates a CPrintDialog object, then invokes the CPrintDialog's DoModal to show the print settings dialog. Eventually (but not in DoPreparePrinting, if memory serves) that CPrinterDialog's CreatePrinterDC will be called to (obviously enough) create a DC for the printer using the settings the user entered in the dialog.

To bypass the dialog, you can override DoPreparePrinting. That receives a pointer to a CPrintDialog. Since you don't want to show a print dialog, you obviously won't invoke its DoModal member. Instead, you'll fill in its DEVMODE and DEVNAMES structures for the printer and any settings you want. Then when CreatePrinterDC gets called, it'll use what you filled in without displaying the dialog.

My personal advice would be to do a run using the dialog under the debugger, then after the CPrintDialog's DoModal has returned, look through the DEVNAMES structure it returned. You may not need it, but I found the DEVNAMES structure a little confusing the first time I had to set it up on my own. The DEVMODE is bigger and arguably more complex, but I've usually just modified a few bits and pieces, and left most of it with default values.

Simplified Approach

If you just want to use the system's default print settings, there's a simpler approach: you can override OnPreparePrinting. This receives a pInfo parameter, which is a pointer to a CPrintInfo. That has an m_bDirect member, which you can set to true to do "direct" printing, which just uses the default settings without using a printer dialog. I don't remember for sure when m_bDirect was added though. If it's missing, there's a "trick" to get the same effect: the default implementation of DoPreparePrinting doesn't display a print dialog for a print preview, so you override OnPreparePrinting to set m_bPreview to true, invoke DoPreparePrinting, then set m_bPreview back to false.


问:
Trouble understanding this sudoku solver recursion function (python)
So basically I decided to make a sudoku solver in python and recursive functions is most efficient, but I've been trying to understand this code from a youtuber and don't understand why each space (bo[row][col]) doesn't immediately reset to 0.  The resetting of one space to 0 only occurs if solve(bo) is True, but if I look through the code, the board will only return True if the board is completely solved, so why doesn't this function just lead nowhere since solve(bo) will never be True?

def solve(bo):
    find = find_empty(bo)

    if not find:
        return True  # This is the only time that solve(bo) == True
    else:
        row, col = find

    for i in range(1, 10):
        if valid(bo, i, (row, col)):
            bo[row][col] = i

            if solve(bo):
                return True

            bo[row][col] = 0   # Yet here it resets the space to 0 if solve(bo) is False

    return False

def valid(bo, num, pos):
    for i in range(9):
        if bo[pos[0]][i] == num and pos[1] != i:
            return False

    for i in range(9):
        if bo[i][pos[1]] == num and pos[0] != i:
            return False

    box_x = (pos[1] // 3) * 3
    box_y = (pos[0] // 3) * 3

    for i in range(box_y, box_y + 3):
        for j in range(box_x, box_x + 3):
            if bo[i][j] == num and (i, j) != pos:
                return False

    return True

def find_empty(bo):
    for y in range(9):
        for x in range(9):
            if bo[y][x] == 0:
                return (y, x)
    return False
```

答:
There is some discrepancy  between your explanation and comments in the code, but I'll do my best to explain the code anyway.

First solve() will try to find the first empty spot (i.e. one that is 0). If it can't find any, then the board is solved so it returns true.

If it does find a spot, then it will try to place numbers 1-9 there and check if it works with the previously entered numbers. Say 7 works (we don't know if 8 or 9 work as well because we haven't checked that yet). So we set the empty space to 7 and then pass this updated board in a recursive call. Essentially, this is like saying "if I force this spot to have the number 7, can you find a solution?"

If the recursive call returns true, it means there is a solution with 7 in that spot and hence the board has a solution, so we return true. If the recursive call to solve() returns false, then we know that there is no solution to the board with 7 in this spot, so we reset this spot to 0 and then try 8 (and then 9 if needed).

The thing to remember is that there is only one board (bo) in all the recursive calls - in other words, all the function calls are operating on the same variable bo. It doesn't create a copy of the board every time you make a recursive call. Lookup 'Pass by reference' and shallow vs. deep copies if you want to learn more about why.


问:
How do you convert XAML 3d object postitions, normals texture coordinates into C#
So I have a 3d object that I created and imported into XAML format and into Viewport3d. We have another C# object that is used from a book. The issue is that it is a parent object and trying to put the code behind file under the new object in C# creates a parent vs. parent conflict. I decided to make a c# class out of it as I need multiple instances of the object. I've been translating all the XAML code to C# but I'm stuck at the positions, normals, & texture coordinates of the XAML object. If there was an easier workaround instead of translating it, it would make my day. Can anyone help please? It would be much appreciated. </p>

答: If you don't want to convert it you can parse the XAML to an object using the XamlReader class which provides parsing methods.


问:
How can I fade an image and replace it with another one?
I'm having trouble with my image gallery. For some reason the image fades out but the rest of the code doesn't execute, it just stops mid way. I've tried removing the fade out function and the code works fine, the images are swapped how they should be etc. What is it about the fade that I'm doing wrong?

```<code> $('.frame').click(function() {
    $("#lightbox").toggleClass("fadeout", function (){
    var copy = $(this).children().clone();
    $('#lightbox').children().replaceWith(copy);
    $("#lightbox").toggleClass("fadeout");
    });
});
</code>```

I'm a complete self-taught newbie so I might ask some daft questions.

```<code>    #lightbox {
    opacity: 1;
    padding: 0 0 0 1%;
    width: 89%;
    height: 100%;
    float: right;
    text-align: center;
    transition: opacity 1s ease;
}

#lightbox.fadeout {
    opacity: 0;
}

.frame {
    width: 100%;
    text-align: left;
}

<div id="gallery_container">
<div id="lightbox">
    <img src="images/IMG_6412.jpg" alt="">
    </div>
<div id="gallery_nav">
    <ul>
        <div class="frame"><img src="images/XA2.jpg" alt=""></div>
        <div class="frame"><img src="images/Mega002.jpg" alt=""></div>
        <div class="frame"><img src="images/IMG_6412.jpg" alt=""</div>
    </ul>
</div>
    </div>
</code>```

答:
You're not using the toggleClass function properly.   The second parameter is a function, but according to the documentation, the second parameter must be a state indication which is a boolean value (True = show, False = hide)

Based on your comments, here's something that should work:

```<code>$('.frame').click(function() {
    var copy = $(this).children().clone();
    $("#lightbox").fadeOut(2000, function (){
      $('#lightbox').children().replaceWith(copy);
      $("#lightbox").fadeIn(2000);
    });
});
</code>```

Body:
I'm having trouble with my image gallery. For some reason the image fades out but the rest of the code doesn't execute, it just stops mid way. I've tried removing the fade out function and the code works fine, the images are swapped how they should be etc. What is it about the fade that I'm doing wrong?

 $('.frame').click(function() {
    $("#lightbox").toggleClass("fadeout", function (){
    var copy = $(this).children().clone();
    $('#lightbox').children().replaceWith(copy);
    $("#lightbox").toggleClass("fadeout");
    });
});

I'm a complete self-taught newbie so I might ask some daft questions.

    #lightbox {
    opacity: 1;
    padding: 0 0 0 1%;
    width: 89%;
    height: 100%;
    float: right;
    text-align: center;
    transition: opacity 1s ease;
}

#lightbox.fadeout {
    opacity: 0;
}

.frame {
    width: 100%;
    text-align: left;
}

<img src="images/IMG_6412.jpg" alt=""

Body:
You're not using the toggleClass function properly.   The second parameter is a function, but according to the documentation, the second parameter must be a state indication which is a boolean value (True = show, False = hide)

Based on your comments, here's something that should work:

$('.frame').click(function() {
    var copy = $(this).children().clone();
    $("#lightbox").fadeOut(2000, function (){
      $('#lightbox').children().replaceWith(copy);
      $("#lightbox").fadeIn(2000);
    });
});


问:
Building a DSL in JavaScript similar to a Ruby DSL
I am wanting to venture more into JavaScript wanted to see if I could create a Domain Specific Language that was similar to that of something I could make in Ruby using instance_eval and block_given?. I mostly don't know what terms to search and when I search DSL I usually get some hugely meta stuff I'm not familiar with. I originally got real lucky with my Ruby search and found a good blog that helped me out. My examples in Ruby are:

# frozen_string_literal: true

require 'phil_dsl/version'

module PhilDsl
  class Error < StandardError; end

  # The DSL Class.
  class Pipeline
    def initialize(&block)
      if block_given? # rubocop:disable Style/GuardClause
        if block.arity == 1
          yield self
        else
          instance_eval(&block)
        end
      end
    end

    def pipeline(&block)
      if block_given? # rubocop:disable Style/GuardClause
        if block.arity == 1
          yield self
        else
          instance_eval(&block)
        end
      end
    end

    def print_stuff(name = 'bob', &block)
      puts name.to_s

      if block_given? # rubocop:disable Style/GuardClause
        if block.arity == 1
          yield self
        else
          instance_eval(&block)
        end
      end
    end
  end
end
```

<p>and then the actual usage of the DSL, once installed</p>

<pre class="lang-rb prettyprint-override"><code>#!/usr/bin/env ruby
# frozen_string_literal: true

require 'phil_dsl'

PhilDsl::Pipeline.new.pipeline do
  print_stuff('hello') do
    print_stuff
  end
end
</code>```

Looking at MochaJS is what I want to emulate, but I'm not sure where to start or go for figuring out how to do DSL creation similar to what I can do in Ruby.

My Ruby DSL full example: https://github.com/FilBot3/phil_dsl

答:
It's not as pretty in JS because you always need the this keyword, but the core part of a DSL is that instance_exec functionality, which is very easy to do in JS using bind, apply, or arrow functions.

Rather than use a class (which doesn't support arrow functions) I'll build a new scope using an IIFE:

```<code>MyDsl = (function(){
  return this;
}).apply({});
</code>```

Then I'll add a single-function DSL:

```<code>MyDsl = (function(){
  this.print_stuff = (arg, callback) => {
    console.log(arg);
    callback && callback.apply(this);
  };
  return this;
}).apply({});
</code>```

Since I define print_stuff as an arrow function I guarantee that inside of it, this will always refer to MyDsl.

I can then use the DSL like so:

```<code>MyDsl.print_stuff("foo", function() {
  this.print_stuff("bar");
});
</code>```

Note that we cannot use an error function here, because then the .apply(this) would be ignored.

Body:
I am wanting to venture more into JavaScript wanted to see if I could create a Domain Specific Language that was similar to that of something I could make in Ruby using instance_eval and block_given?. I mostly don't know what terms to search and when I search DSL I usually get some hugely meta stuff I'm not familiar with. I originally got real lucky with my Ruby search and found a good blog that helped me out. My examples in Ruby are:

# frozen_string_literal: true

require 'phil_dsl/version'

module PhilDsl
  class Error < StandardError; end

  # The DSL Class.
  class Pipeline
    def initialize(&block)
      if block_given? # rubocop:disable Style/GuardClause
        if block.arity == 1
          yield self
        else
          instance_eval(&block)
        end
      end
    end

    def pipeline(&block)
      if block_given? # rubocop:disable Style/GuardClause
        if block.arity == 1
          yield self
        else
          instance_eval(&block)
        end
      end
    end

    def print_stuff(name = 'bob', &block)
      puts name.to_s

      if block_given? # rubocop:disable Style/GuardClause
        if block.arity == 1
          yield self
        else
          instance_eval(&block)
        end
      end
    end
  end
end

and then the actual usage of the DSL, once installed

#!/usr/bin/env ruby
# frozen_string_literal: true

require 'phil_dsl'

PhilDsl::Pipeline.new.pipeline do
  print_stuff('hello') do
    print_stuff
  end
end

Looking at MochaJS is what I want to emulate, but I'm not sure where to start or go for figuring out how to do DSL creation similar to what I can do in Ruby.

My Ruby DSL full example: https://github.com/FilBot3/phil_dsl

Body:
It's not as pretty in JS because you always need the this keyword, but the core part of a DSL is that instance_exec functionality, which is very easy to do in JS using bind, apply, or arrow functions.

Rather than use a class (which doesn't support arrow functions) I'll build a new scope using an IIFE:

MyDsl = (function(){
  return this;
}).apply({});

Then I'll add a single-function DSL:

MyDsl = (function(){
  this.print_stuff = (arg, callback) => {
    console.log(arg);
    callback && callback.apply(this);
  };
  return this;
}).apply({});

Since I define print_stuff as an arrow function I guarantee that inside of it, this will always refer to MyDsl.

I can then use the DSL like so:

MyDsl.print_stuff("foo", function() {
  this.print_stuff("bar");
});

Note that we cannot use an error function here, because then the .apply(this) would be ignored.


问:
How to add @keyframes rule through inspect element?
I constantly like to customize web pages that I use frequently through inspect element to be more pleasing for me, however, I've been constantly failing at adding a @keyframes rule to css. Everytime I click "New Style Rule" and type my code, it simply disappears.

```<code>  0%{
    text-shadow: 0 0px 15px #f0f;
  }
  33%{
    text-shadow:0 0px 15px #0ff;
  }
  66%{
    text-shadow: 0 0px 10px #0f0;
  }
  100%{
    text-shadow: 0 0px 10px #ff0;
  }
}
</code>```

I have noticed in other websites that use keyframes that they are separated from regular classes, and I cannot interact in any way with it through inspect element.
     @keyframe in inspect element

Is it impossible to add keyframes through inspect element alone?

答:
there are some chrome extensions that helps with page css editing, like amino.

alternatively, you may handle the css file directly at Sources tab.

At Sources tab you have all content files served including css files. the css files will be in purple. most likely it's compressed, but you can pretty print with {} button in the bottom left. once there, you can edit it anyway you like it, do your tests, and see translated to the page layout.

Body:
I constantly like to customize web pages that I use frequently through inspect element to be more pleasing for me, however, I've been constantly failing at adding a @keyframes rule to css. Everytime I click "New Style Rule" and type my code, it simply disappears.

  0%{
    text-shadow: 0 0px 15px #f0f;
  }
  33%{
    text-shadow:0 0px 15px #0ff;
  }
  66%{
    text-shadow: 0 0px 10px #0f0;
  }
  100%{
    text-shadow: 0 0px 10px #ff0;
  }
}

I have noticed in other websites that use keyframes that they are separated from regular classes, and I cannot interact in any way with it through inspect element.
     @keyframe in inspect element

Is it impossible to add keyframes through inspect element alone?


问:
Turn off debug or log messages in log4j.xml
I want to turn off debug or log message in log4j.xml.

My log4j.xml is :

```<code><appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n" />
        </layout>
    </appender>

    <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false" />
        <param name="file" value="./logs/learning.log" />
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="consoleAppender" />
        <appender-ref ref="fileAppender" />
    </root>
</code>```

My Java code :

```<code> public static void main(String[] args) {
        log.info("info");
        log.debug("dddffff");
    }
</code>```

If I run this program still INFO messages are also getting logged, Below is log file

```<code>07 Aug 2014 12:54:49  INFO MainClass - info
07 Aug 2014 12:54:49 DEBUG MainClass - dddffff
</code>```

Now I want to turn off INFO messages.

答:
You can set the logging level for a package like this:

log4j2.xml snippet:

```<code>    <Loggers>
        <Root level="debug">
            <appender-ref ref="Console" />
        </Root>
        <Logger name="org.eclipse.jetty" level="info" additivity="true">
            <appender-ref ref="Console" />
        </Logger>
    </Loggers>
</code>```

In this example, classes in the org.eclipse.jetty package output INFO level logging. All other classes output DEBUG level logging.

Body:
I want to turn off debug or log message in log4j.xml.

My log4j.xml is :

<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n" />
        </layout>
    </appender>

    <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false" />
        <param name="file" value="./logs/learning.log" />
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="consoleAppender" />
        <appender-ref ref="fileAppender" />
    </root>

My Java code :

 public static void main(String[] args) {
        log.info("info");
        log.debug("dddffff");
    }

If I run this program still INFO messages are also getting logged, Below is log file

07 Aug 2014 12:54:49  INFO MainClass - info
07 Aug 2014 12:54:49 DEBUG MainClass - dddffff

Now I want to turn off INFO messages.

Body:
You can set the logging level for a package like this:

log4j2.xml snippet:

    <Loggers>
        <Root level="debug">
            <appender-ref ref="Console" />
        </Root>
        <Logger name="org.eclipse.jetty" level="info" additivity="true">
            <appender-ref ref="Console" />
        </Logger>
    </Loggers>

In this example, classes in the org.eclipse.jetty package output INFO level logging. All other classes output DEBUG level logging.