问:
HTML table to proper excel table Python
I am pretty new at Python and struggling with printing the web scraping data to beautiful excel table.
Here is a table I am trying to scrape and replicate in Python:
HTML Table.

Here is how HTML page looks like:

```<code></div>
    <section id="first" style="display:none" aria-label="Power situation graph section">
        <div class="gridModule-2up">
            <div class="prognos_controls hidden" data-proggraph="1">
                Show data for:
                <button value="1" onclick="this.blur();" type="button" class="btn  btn--secondary prognosdaybutton"><span class="fa fa-clock-o" aria-hidden="true"></span> Yesterday</button>
                <button value="2" onclick="this.blur();" type="button" class="btn  btn--tertiary prognosdaybutton"><span class="fa fa-clock-o" aria-hidden="true"></span> Today</button>
                <button value="3" onclick="this.blur();" type="button" class="btn  btn--secondary prognosdaybutton"><span class="fa fa-clock-o" aria-hidden="true"></span> Tomorrow</button>
            </div>
            <table summary="Consumption" id="prognos_datatable_total" class="prognos_datatable scrollable">
                <thead>
                    <tr>
                                <th data-sheets-numberformat="[null,1]"></th>
                                <th data-sheets-value="[null,2,'17/02/2020']" data-sheets-numberformat="[null,1]" scope="col">2020-02-17</th>
                                <th data-sheets-numberformat="[null,1]"></th>
                                <th data-sheets-value="[null,2,'18/02/2020']" data-sheets-numberformat="[null,1]" scope="col">2020-02-18</th>
                                <th data-sheets-numberformat="[null,1]"></th>
                                <th data-sheets-value="[null,2,'19/02/2020']" data-sheets-numberformat="[null,1]" scope="col">2020-02-19</th>

                    </tr>
                    <tr>
                        <th caldata-sheets-value="[null,2,'Timme']" data-sheets-numberformat="[null,1]" scope="col">Hour</th>
                                <th data-sheets-value="[null,2,'F\u00f6rbrukning']" data-sheets-numberformat="[null,1]" scope="col">Consumption</th>
                                <th data-sheets-value="[null,2,'Prognos']" data-sheets-numberformat="[null,1]" scope="col">Forecast</th>
                                <th data-sheets-value="[null,2,'F\u00f6rbrukning']" data-sheets-numberformat="[null,1]" scope="col">Consumption</th>
                                <th data-sheets-value="[null,2,'Prognos']" data-sheets-numberformat="[null,1]" scope="col">Forecast</th>
                                <th data-sheets-value="[null,2,'F\u00f6rbrukning']" data-sheets-numberformat="[null,1]" scope="col">Consumption</th>
                                <th data-sheets-value="[null,2,'Prognos']" data-sheets-numberformat="[null,1]" scope="col">Forecast</th>

                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th data-sheets-value="[null,2,'00-01']" data-sheets-numberformat="[null,1]" scope="col">
                            00-01
                        </th>

                            <td data-sheets-value="[null,2,'15544']" data-sheets-numberformat="[null,1]">15 544</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15143']" data-sheets-numberformat="[null,1]">15 143</td>
                            <td data-sheets-value="[null,2,'15669']" data-sheets-numberformat="[null,1]">15 669</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15869']" data-sheets-numberformat="[null,1]">15 869</td>
                            <td data-sheets-value="[null,2,'-']" data-sheets-numberformat="[null,1]">-</td>
                            <td class="alert_1" data-sheets-value="[null,2,'16422']" data-sheets-numberformat="[null,1]">16 422</td>
                    </tr>
                    <tr>
                        <th data-sheets-value="[null,2,'01-02']" data-sheets-numberformat="[null,1]" scope="col">
                            01-02
                        </th>

                            <td data-sheets-value="[null,2,'15238']" data-sheets-numberformat="[null,1]">15 238</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15052']" data-sheets-numberformat="[null,1]">15 052</td>
                            <td data-sheets-value="[null,2,'15509']" data-sheets-numberformat="[null,1]">15 509</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15366']" data-sheets-numberformat="[null,1]">15 366</td>
                            <td data-sheets-value="[null,2,'-']" data-sheets-numberformat="[null,1]">-</td>
                            <td class="alert_1" data-sheets-value="[null,2,'16176']" data-sheets-numberformat="[null,1]">16 176</td>
                    </tr>
                    <tr>
                        <th data-sheets-value="[null,2,'02-03']" data-sheets-numberformat="[null,1]" scope="col">
                            02-03
                        </th>

                            <td data-sheets-value="[null,2,'15250']" data-sheets-numberformat="[null,1]">15 250</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15135']" data-sheets-numberformat="[null,1]">15 135</td>
                            <td data-sheets-value="[null,2,'15576']" data-sheets-numberformat="[null,1]">15 576</td>
                            <td class="alert_1" data-sheets-value="[null,2,'15501']" data-sheets-numberformat="[null,1]">15 501</td>
                            <td data-sheets-value="[null,2,'-']" data-sheets-numberformat="[null,1]">-</td>
                            <td class="alert_1" data-sheets-value="[null,2,'16124']" data-sheets-numberformat="[null,1]">16 124</td>
                    </tr>
                    <tr>
                        <th data-sheets-value="[null,2,'03-04']" data-sheets-numberformat="[null,1]" scope="col">
                            03-04
                        </th>.............
</code>```

Here is the code I used:

```<code>import requests
import lxml.html as lh
import pandas as pd
from bs4 import BeautifulSoup
import csv

url = 'myURLlink'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'lxml')

extract = soup.select("table")[1]

table = [[item.text for item in row_data.select("th,td")]
                for row_data in extract.select("tr")]

for item in table:
    print(' '.join(item))
</code>```

This is how my output looks with this code: Output.

How can I create a normal data frame from this that I can then export to Excel?

I would appreciate any help.

答:
The issue is because of escape characters.

```<code>from bs4 import BeautifulSoup

with open("sample.html", "r") as f:

    contents = f.read()
    soup = BeautifulSoup(contents, 'lxml')
    extract = soup.find("table")

    # added strip() to remove leading and trailing characters
    table = [[item.text.strip() for item in row_data.select("th,td")]
                    for row_data in extract.select("tr")]

    for item in table:
        print(' '.join(item))
</code>```

Check output here

Title: HTML table to proper excel table Python

Body:
I am pretty new at Python and struggling with printing the web scraping data to beautiful excel table.
Here is a table I am trying to scrape and replicate in Python:
HTML Table.

Here is how HTML page looks like:

                Show data for:
                <button value="1" onclick="this.blur();" type="button" class="btn  btn--secondary prognosdaybutton"> Yesterday</button>
                <button value="2" onclick="this.blur();" type="button" class="btn  btn--tertiary prognosdaybutton"> Today</button>
                <button value="3" onclick="this.blur();" type="button" class="btn  btn--secondary prognosdaybutton"> Tomorrow</button>

                                2020-02-17

                                2020-02-18

                                2020-02-19

                        Hour
                                Consumption
                                Forecast
                                Consumption
                                Forecast
                                Consumption
                                Forecast

                            00-01

                            15 544
                            15 143
                            15 669
                            15 869
                            -
                            16 422

                            01-02

                            15 238
                            15 052
                            15 509
                            15 366
                            -
                            16 176

                            02-03

                            15 250
                            15 135
                            15 576
                            15 501
                            -
                            16 124

                            03-04
                        	.............

Here is the code I used:

import requests
import lxml.html as lh
import pandas as pd
from bs4 import BeautifulSoup
import csv

url = 'myURLlink'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'lxml')

extract = soup.select("table")[1]

table = [[item.text for item in row_data.select("th,td")]
                for row_data in extract.select("tr")]

for item in table:
    print(' '.join(item))

This is how my output looks with this code: Output.

How can I create a normal data frame from this that I can then export to Excel?

I would appreciate any help.

Body:
The issue is because of escape characters.

from bs4 import BeautifulSoup

with open("sample.html", "r") as f:

    contents = f.read()
    soup = BeautifulSoup(contents, 'lxml')
    extract = soup.find("table")

    # added strip() to remove leading and trailing characters
    table = [[item.text.strip() for item in row_data.select("th,td")]
                    for row_data in extract.select("tr")]

    for item in table:
        print(' '.join(item))

Check output here


来源: stackexchange

问:
DialogFlow: Regexp not accept occurrence of case
Regexp entity

```<code>Hall ?([0-9]{1,2})?
</code>```

Case wants to accept :

Hall  //Not Accept

Hall1 //Accept

Hall 1 //Accept

but case 1 not satisfy by Regexp

And I Want to satisfy all 3 cases.

答:
If you want to accept the last 2 only, you should not make the group optional

```<code>Hall ?[0-9]{1,2}
</code>```

Regex demo

ContentLicense: CC BY-SA 4.0

Body:
Regexp entity

Hall ?([0-9]{1,2})?

Case wants to accept :

Hall  //Not Accept

Hall1 //Accept

Hall 1 //Accept

but case 1 not satisfy by Regexp

And I Want to satisfy all 3 cases.

Body:
If you want to accept the last 2 only, you should not make the group optional

Hall ?[0-9]{1,2}

Regex demo


问:
human activity recognition dataset problem
if we have a gyroscope and an accelerometer sensor data and merge them we will have id, activity, time, accx, accy, accz, id, activity_gur, time, gurx, gury, gurz. So we will end up with a data frame that contains an activity column and also with an activity-gyroscope column. does it make sense to drop the activity-gyroscope column and work with the remain columns?

答: Drop it if it is duplicated and has the same value as activity. Also, check the time column and see if it is also duplicated. Then you can drop also one of the time columns. Normally, it just does make sense, if your data belongs to the same dataset, publicly available.</p>


问:
NodeJS -> Error Cannot read property 'length' of undefined
I wanted to made a query to the mysql database if the username already exists he should throw me a message and if not, show me the new id. I wanted to check if the query result.lenght is higher than 0.
however it throws the error "Cannot read property 'length' of undefined"

Service file

```<code>const connect = () =>
    mysql.createConnection({
        host: process.env.MYSQL_HOST,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        database: process.env.MYSQL_DATABASE
    });
const insert = (conn, user) => {
    return conn.query(`insert into user(username, firstName, lastName, password)
    values(?,?,?,?)`,
        [
            user.username,
            user.firstName,
            user.lastName,
            user.password
        ]
    )
}
const getByUsername = username => {
    return connect()
        .then(conn => {
            conn.query(
                `select id, username, firstName, lastName
                from user
                where username = ?`,
                [username]
            );
        })
}

const create = user => {

    return getByUsername(user.username)
        .then(result => {
            if (result.length > 0) {
                throw new Error(`User "${user.username}" already exists`);
            }
        })
        .then(() => connect())
        .then(conn => insert(conn, user))
        .then(result =>
            ({
                id: result.insertId
            }));
};
</code>```

Controller file

```<code>const create = (req, res) => {

    userService.create(req.body)
        .then(result => {
            res.status(200);
            res.json(result);
        })
        .catch(err => {
            res.status(500);
            res.send('Error ' + err.message);
        })
}
</code>```

I tried to define lenght but I think this isnt the issue. I make the query with postman and i use mysql as database. I also tried to replace the result.length with username.length but it thorws "Error username is not defined"...

答:
The result might be undefined there. Because we don't return proper query results. That why we getting error.

Solution:

```<code>const getByUsername = username => {
    return new Promise((resolve, reject) => {
        connect()
            .then(conn => {
                conn.query(
                    `select id, username, firstName, lastName
                    from user
                    where username = ?`,
                    [username],
                    function(err, results) {
                        if (err) {
                            return reject(err);
                        }
                        return resolve(results)
                    }
                );
            })
    });
}
</code>```

Explanation:

As per mysql2 documentation, the conn.query will not return the results. The conn.query method has a third argument which is a callback method. Here we can get the SQL query error and query results.

By the use of javascript Promise API, we can decide to reject or resolve based upon the SQL query result.

Body:
I wanted to made a query to the mysql database if the username already exists he should throw me a message and if not, show me the new id. I wanted to check if the query result.lenght is higher than 0.
however it throws the error "Cannot read property 'length' of undefined"

Service file

const connect = () =>
    mysql.createConnection({
        host: process.env.MYSQL_HOST,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD,
        database: process.env.MYSQL_DATABASE
    });
const insert = (conn, user) => {
    return conn.query(`insert into user(username, firstName, lastName, password)
    values(?,?,?,?)`,
        [
            user.username,
            user.firstName,
            user.lastName,
            user.password
        ]
    )
}
const getByUsername = username => {
    return connect()
        .then(conn => {
            conn.query(
                `select id, username, firstName, lastName
                from user
                where username = ?`,
                [username]
            );
        })
}

const create = user => {

    return getByUsername(user.username)
        .then(result => {
            if (result.length > 0) {
                throw new Error(`User "${user.username}" already exists`);
            }
        })
        .then(() => connect())
        .then(conn => insert(conn, user))
        .then(result =>
            ({
                id: result.insertId
            }));
};

Controller file

const create = (req, res) => {

    userService.create(req.body)
        .then(result => {
            res.status(200);
            res.json(result);
        })
        .catch(err => {
            res.status(500);
            res.send('Error ' + err.message);
        })
}

I tried to define lenght but I think this isnt the issue. I make the query with postman and i use mysql as database. I also tried to replace the result.length with username.length but it thorws "Error username is not defined"...

Body:
The result might be undefined there. Because we don't return proper query results. That why we getting error.

Solution:

const getByUsername = username => {
    return new Promise((resolve, reject) => {
        connect()
            .then(conn => {
                conn.query(
                    `select id, username, firstName, lastName
                    from user
                    where username = ?`,
                    [username],
                    function(err, results) {
                        if (err) {
                            return reject(err);
                        }
                        return resolve(results)
                    }
                );
            })
    });
}

Explanation:

As per mysql2 documentation, the conn.query will not return the results. The conn.query method has a third argument which is a callback method. Here we can get the SQL query error and query results.

By the use of javascript Promise API, we can decide to reject or resolve based upon the SQL query result.


问:
Json to pandas dataframe with slight modification
I have a json data as below:

```<code>{
"X": "abc",
"Y": 1,
"Z": 4174,

"t_0":
  {
     "M": "bm",
     "T": "sp",
     "CUD": 4,
"t_1": '
   {
     "CUD": "1",
     "BBC": "09",
     "CPR": -127
  },

  "EVV": "10.7000",
  "BBC": -127,
  "CMIX": "25088"
 },
 "EYR": "sp"
}
</code>```

The problem is converting to python data-frame creates two columns of same name CUD. One is under t_0 and another is under t_1. But both are different events. How can I append json tag name to column names so that I can differentiate two columns of same name. Something like t_0_CUD , t_1_CUD.

My code is below:

```<code>df = pd.io.json.json_normalize(json_data)
df.columns = df.columns.map(lambda x: x.split(".")[-1])
</code>```

答:
If use only first part of solution it return what you need, only instead _ are used .:

```<code>df = pd.io.json.json_normalize(json_data)
print (df)
     X  Y     Z EYR t_0.M t_0.T  t_0.CUD t_0.t_1.CUD t_0.t_1.BBC  t_0.t_1.CPR  \
0  abc  1  4174  sp    bm    sp        4           1          09         -127

   t_0.EVV  t_0.BBC t_0.CMIX
0  10.7000     -127    25088
</code>```

If need _:

```<code>df.columns = df.columns.str.replace('\.','_')
print (df)
     X  Y     Z EYR t_0_M t_0_T  t_0_CUD t_0_t_1_CUD t_0_t_1_BBC  t_0_t_1_CPR  \
0  abc  1  4174  sp    bm    sp        4           1          09         -127

   t_0_EVV  t_0_BBC t_0_CMIX
0  10.7000     -127    25088
</code>```

Body:
I have a json data as below:

{
"X": "abc",
"Y": 1,
"Z": 4174,

"t_0":
  {
     "M": "bm",
     "T": "sp",
     "CUD": 4,
"t_1": '
   {
     "CUD": "1",
     "BBC": "09",
     "CPR": -127
  },

  "EVV": "10.7000",
  "BBC": -127,
  "CMIX": "25088"
 },
 "EYR": "sp"
}

The problem is converting to python data-frame creates two columns of same name CUD. One is under t_0 and another is under t_1. But both are different events. How can I append json tag name to column names so that I can differentiate two columns of same name. Something like t_0_CUD , t_1_CUD.

My code is below:

df = pd.io.json.json_normalize(json_data)
df.columns = df.columns.map(lambda x: x.split(".")[-1])

Body:
If use only first part of solution it return what you need, only instead _ are used .:

df = pd.io.json.json_normalize(json_data)
print (df)
     X  Y     Z EYR t_0.M t_0.T  t_0.CUD t_0.t_1.CUD t_0.t_1.BBC  t_0.t_1.CPR  \
0  abc  1  4174  sp    bm    sp        4           1          09         -127

   t_0.EVV  t_0.BBC t_0.CMIX
0  10.7000     -127    25088

If need _:

df.columns = df.columns.str.replace('\.','_')
print (df)
     X  Y     Z EYR t_0_M t_0_T  t_0_CUD t_0_t_1_CUD t_0_t_1_BBC  t_0_t_1_CPR  \
0  abc  1  4174  sp    bm    sp        4           1          09         -127

   t_0_EVV  t_0_BBC t_0_CMIX
0  10.7000     -127    25088


问:
jqgrid via Perl
I'm trying to send JSON information to jqgrid via Perl, however I'm struggling on how to get the appropriate JSON structure:

Per JQgrid docs, the JSON needs to be in the following format:

```<code>{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
{"id" :"2", "cell":["cell21", "cell22", "cell23"]},
...
]
}
</code>```

```<code>#!/usr/bin/perl
use CGI (-debug);
use DBI;
use JSON;
use POSIX qw(ceil);
use strict;
use warnings;
...
my $i=0;
my $response = {};
$response->{total} = $total_pages;
$response->{page} = $page;
$response->{records} = $count;
while ( my $row = $sth->fetchrow_hashref ){
        $response->{rows}->[$i]->{id} = $i;
        $response->{rows}->[$i]->{cell} = ($row);
        $i++;
}
print $cgi->header(-type => "application/json", -charset => "utf-8");
print JSON::to_json($response);
</code>```

I'm pretty sure I need a hash of arrays, but I can't seem to figure out how to go about it.

答:
This is one problem:

```<code>$response->{rows}->[id]
</code>```

In that phrase you're taking a hashref ($response), accessing its hash key "rows", and then accessing an anonymous array referred to by $response->{rows}.  So far so good, but the anonymous array cannot have an element named 'id', unless 'id' is defined somewhere as a constant, which I don't see anywhere in the code you posted.  It's more likely that you mean "$response->{rows}{id}".  In other words, a hash of hashes.  Note, the -> operator is redundant when sandwiched between indices, so I removed it.

However, you mentioned in your post that you need a hash of arrays.  But that would have to look more like $response->{rows}[0].

One thing I find useful sometimes is to just use Data::Dumper to dump the return value of fetchrow_hashref to see what it looks like.  You may already have a picture of it in your mind, but sometimes seeing it dumped out as a datastructure will help you to better visualize how your datastructure should be rearranged to fit the design requirements.

ContentLicense: CC BY-SA 3.0

Title: jqgrid via Perl

Body:
I'm trying to send JSON information to jqgrid via Perl, however I'm struggling on how to get the appropriate JSON structure:

Per JQgrid docs, the JSON needs to be in the following format:

{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
{"id" :"2", "cell":["cell21", "cell22", "cell23"]},
...
]
}

#!/usr/bin/perl
use CGI (-debug);
use DBI;
use JSON;
use POSIX qw(ceil);
use strict;
use warnings;
...
my $i=0;
my $response = {};
$response->{total} = $total_pages;
$response->{page} = $page;
$response->{records} = $count;
while ( my $row = $sth->fetchrow_hashref ){
        $response->{rows}->[$i]->{id} = $i;
        $response->{rows}->[$i]->{cell} = ($row);
        $i++;
}
print $cgi->header(-type => "application/json", -charset => "utf-8");
print JSON::to_json($response);

I'm pretty sure I need a hash of arrays, but I can't seem to figure out how to go about it.

Body:
This is one problem:

$response->{rows}->[id]

In that phrase you're taking a hashref ($response), accessing its hash key "rows", and then accessing an anonymous array referred to by $response->{rows}.  So far so good, but the anonymous array cannot have an element named 'id', unless 'id' is defined somewhere as a constant, which I don't see anywhere in the code you posted.  It's more likely that you mean "$response->{rows}{id}".  In other words, a hash of hashes.  Note, the -> operator is redundant when sandwiched between indices, so I removed it.

However, you mentioned in your post that you need a hash of arrays.  But that would have to look more like $response->{rows}[0].

One thing I find useful sometimes is to just use Data::Dumper to dump the return value of fetchrow_hashref to see what it looks like.  You may already have a picture of it in your mind, but sometimes seeing it dumped out as a datastructure will help you to better visualize how your datastructure should be rearranged to fit the design requirements.


问:
Accessing data of one DBCS to another DBCS
I have two DBCS instance. DB1 and DB2. I want to access data of DB2 instance in DB1.
I dont want to copy the data , I just want to access for reporting purpose.

Can you please help me on the same.

答:
Within DB1, create a db link to DB2:

```<code>CREATE PUBLIC DATABASE LINK "DB2"
   CONNECT TO "db2user" IDENTIFIED BY "db2userpwd"
   USING 'DB2';
</code>```

Create a tnsnames.ora entry (in the tnsnames.ora of the DB1 machine) for DB2

Then when you want to select the data,

```<code>select * from my_db2_table@DB2;
</code>```

Read more on DB Links in the SQL Reference.create database link

BTW, in the CREATE statement above, the two strings 'DB2' do not have to be the same, but probably should be for consistency.  The first (CREATE DATABASE LINK DB2) is the name of the link and is what is referenced in the sample SELECT statement. The second (using 'DB2') is the reference to the tnsnames.ora entry.

Body:
Within DB1, create a db link to DB2:

CREATE PUBLIC DATABASE LINK "DB2"
   CONNECT TO "db2user" IDENTIFIED BY "db2userpwd"
   USING 'DB2';

Create a tnsnames.ora entry (in the tnsnames.ora of the DB1 machine) for DB2

Then when you want to select the data,

select * from my_db2_table@DB2;

Read more on DB Links in the SQL Reference.create database link

BTW, in the CREATE statement above, the two strings 'DB2' do not have to be the same, but probably should be for consistency.  The first (CREATE DATABASE LINK DB2) is the name of the link and is what is referenced in the sample SELECT statement. The second (using 'DB2') is the reference to the tnsnames.ora entry.


问:
How to connect via WebSocket on Android using Scarlet?
Code from README.md

```<code> val scarletInstance = Scarlet.Builder()
    .webSocketFactory(okHttpClient.newWebSocketFactory(GDAX_URL))
    .addMessageAdapterFactory(MoshiMessageAdapter.Factory())
    .addStreamAdapterFactory(RxJava2StreamAdapterFactory())
    .build()
</code>```

Version and dependencies:

```<code>implementation 'com.tinder.scarlet:scarlet:0.1.8'
implementation "com.github.tinder.scarlet:scarlet-websocket-okhttp:0.1.7"
implementation "com.github.tinder.scarlet:scarlet-stream-adapter-rxjava2:0.2.4"
implementation "com.github.tinder.scarlet:scarlet-message-adapter-moshi:0.2.4"
implementation "com.github.tinder.scarlet:scarlet-lifecycle-android:0.2.4"
</code>```

答:
Your code is FAILING due to class duplication. It occurs because of different lib versions. The correct implementation is:</p>

```<code>//web sockets
implementation 'com.tinder.scarlet:scarlet:0.1.10'
implementation "com.tinder.scarlet:websocket-okhttp:0.1.10"
implementation "com.tinder.scarlet:stream-adapter-rxjava2:0.1.10"
implementation "com.tinder.scarlet:message-adapter-moshi:0.1.10"
implementation "com.tinder.scarlet:lifecycle-android:0.1.10"
</code>```

Body:
Code from README.md

 val scarletInstance = Scarlet.Builder()
    .webSocketFactory(okHttpClient.newWebSocketFactory(GDAX_URL))
    .addMessageAdapterFactory(MoshiMessageAdapter.Factory())
    .addStreamAdapterFactory(RxJava2StreamAdapterFactory())
    .build()

Version and dependencies:

implementation 'com.tinder.scarlet:scarlet:0.1.8'
implementation "com.github.tinder.scarlet:scarlet-websocket-okhttp:0.1.7"
implementation "com.github.tinder.scarlet:scarlet-stream-adapter-rxjava2:0.2.4"
implementation "com.github.tinder.scarlet:scarlet-message-adapter-moshi:0.2.4"
implementation "com.github.tinder.scarlet:scarlet-lifecycle-android:0.2.4"

Body:
Your code is FAILING due to class duplication. It occurs because of different lib versions. The correct implementation is:

//web sockets
implementation 'com.tinder.scarlet:scarlet:0.1.10'
implementation "com.tinder.scarlet:websocket-okhttp:0.1.10"
implementation "com.tinder.scarlet:stream-adapter-rxjava2:0.1.10"
implementation "com.tinder.scarlet:message-adapter-moshi:0.1.10"
implementation "com.tinder.scarlet:lifecycle-android:0.1.10"


问:
Laravel ajax callback request response

      <button  id="finish" class="btn btn-primary">finish</button>

```

<p>//script </p>

<pre class="lang-js prettyprint-override"><code> $('#addNew').click(function(cb){

    $.ajax({
        type:GET;
        url:'Get/local/'
        dataType:'json',
        data:form_data,
        success:function(res){
            cb(res);
        }
    });
</code>```

//and now I want to pass res I get to other function, and I try this, but not working
"data" get from the first function// the first function res

$('#finish').click(function(data){
    console.log(data);
});
```

any help, please. res..give me data of an object. my problem is I am new to ajax and I don't know how to a callback res to other function

答:
One way would be to store the data in a global variable

```<code>var data_global = {};

$('#addNew').click(function(){

  $.ajax({
   type:GET;
   url:'Get/local/'
   dataType:'json',
   data:form_data,
   success:function(res){
     data_global = res;
   }
 });
</code>```

Then you can pick up the data stored in the global variable with a function or an event on another button

```<code> $('#finish').click(function(){
    console.log(data_global);
 });
</code>```

Depending on your logic, usually you would call a function inside the success callback

```<code>$('#addNew').click(function(cb){

  $.ajax({
   type:GET;
   url:'Get/local/'
   dataType:'json',
   data:form_data,
   success:function(res){
     myFantasticFunction(res);
   }
 });

 myFantasticFunction(data){
   console.log(data);
 }
</code>```

Title: Laravel ajax callback request response

Body:
      <button  id="finish" class="btn btn-primary">finish</button>

//script

 $('#addNew').click(function(cb){

    $.ajax({
        type:GET;
        url:'Get/local/'
        dataType:'json',
        data:form_data,
        success:function(res){
            cb(res);
        }
    });

//and now I want to pass res I get to other function, and I try this, but not working
"data" get from the first function// the first function res

$('#finish').click(function(data){
    console.log(data);
});

any help, please. res..give me data of an object. my problem is I am new to ajax and I don't know how to a callback res to other function

Body:
One way would be to store the data in a global variable

var data_global = {};

$('#addNew').click(function(){

  $.ajax({
   type:GET;
   url:'Get/local/'
   dataType:'json',
   data:form_data,
   success:function(res){
     data_global = res;
   }
 });

Then you can pick up the data stored in the global variable with a function or an event on another button

 $('#finish').click(function(){
    console.log(data_global);
 });

Depending on your logic, usually you would call a function inside the success callback

$('#addNew').click(function(cb){

  $.ajax({
   type:GET;
   url:'Get/local/'
   dataType:'json',
   data:form_data,
   success:function(res){
     myFantasticFunction(res);
   }
 });

 myFantasticFunction(data){
   console.log(data);
 }


问:
Notifications job date format
I need a hint: how to change date format on jobs notification?
I can't figure it out. As far as I understand, is related to messages.properties file, which I
can't find.
I created i18n directory with messages.properties file, but I'm not sure what is the format of messages file content. (found on albundy83 comment)

```<code>Date dateS = Date.parse( "yyyy-MM-dd HH:mm:ss.SSS", execution.dateStarted.toString() )
String dateStartedIso8601 = dateS.format( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" )

Date dateE = Date.parse( "yyyy-MM-dd HH:mm:ss.SSS", execution.dateEnded.toString() )
String dateEndedIso8601 = dateE.format( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" )
</code>```

I have installed Rundeck 3.2.2 using RPM on CentOS 8.

Regards,
Adi

答:
To use that custom format you need to create a groovy plugin, follow this. Basically you need to create a .groovy file and put it on $RDECK_BASE/libext (as any plugin).

I did an basic example modifying this plugin and this. Take a look:

import java.text.SimpleDateFormat
import java.util.Date
import com.dtolabs.rundeck.plugins.notification.NotificationPlugin;

rundeckPlugin(NotificationPlugin){
    onstart {
        println("job start: data ${execution}")
        true
    }

    onfailure {
        println("failure: data ${execution}")
        true
    }

    onsuccess {
        Date dateS = Date.parse( "yyyy-MM-dd HH:mm:ss.SSS", execution.dateStarted.toString() )
        String customdate = dateS.format( "dd-MM-YYYY" )

        println("success: data ${customdate}")
        true
    }
}
```

<p>Output (success job execution):</p>

<pre class="lang-bash prettyprint-override"><code>success: data 18-02-2020

</code>```

Title: Notifications job date format

Body:
I need a hint: how to change date format on jobs notification?
I can't figure it out. As far as I understand, is related to messages.properties file, which I
can't find.
I created i18n directory with messages.properties file, but I'm not sure what is the format of messages file content. (found on albundy83 comment)

Date dateS = Date.parse( "yyyy-MM-dd HH:mm:ss.SSS", execution.dateStarted.toString() )
String dateStartedIso8601 = dateS.format( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" )

Date dateE = Date.parse( "yyyy-MM-dd HH:mm:ss.SSS", execution.dateEnded.toString() )
String dateEndedIso8601 = dateE.format( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" )

I have installed Rundeck 3.2.2 using RPM on CentOS 8.

Regards,
Adi

Body:
To use that custom format you need to create a groovy plugin, follow this. Basically you need to create a .groovy file and put it on $RDECK_BASE/libext (as any plugin).

I did an basic example modifying this plugin and this. Take a look:

import java.text.SimpleDateFormat
import java.util.Date
import com.dtolabs.rundeck.plugins.notification.NotificationPlugin;

rundeckPlugin(NotificationPlugin){
    onstart {
        println("job start: data ${execution}")
        true
    }

    onfailure {
        println("failure: data ${execution}")
        true
    }

    onsuccess {
        Date dateS = Date.parse( "yyyy-MM-dd HH:mm:ss.SSS", execution.dateStarted.toString() )
        String customdate = dateS.format( "dd-MM-YYYY" )

        println("success: data ${customdate}")
        true
    }
}

Output (success job execution):

success: data 18-02-2020


问:
How to know on which physical processor and on which physical core my code is running
How can I know in a C program, on which physical processor and core my code is running?
I'm using Linux and gcc 4.4.3.</p>

答:
See http://en.wikipedia.org/wiki/CPUID#Accessing_the_id_from_other_languages

What you want is the APIC ID... basically:

```<code>    cpuid
    shr     ebx, 24
</code>```

Body:
See http://en.wikipedia.org/wiki/CPUID#Accessing_the_id_from_other_languages

What you want is the APIC ID... basically:

    cpuid
    shr     ebx, 24


问:
Can a user delete data stored in shared preferences?
Suppose i made an app which uses shared preferences,
will the data stored with shared preferences be deleted when user clears app storage?

if yes then what is alternative to store/retrieve important data faster which will not get erased by user?

i tried firebase-database, but it is lagging the speed/performance i require.

答:
will the data stored with shared preferences be deleted when user clears app storage?

Yes.

what is alternative to store/retrieve important data faster which will not get erased by user?

Store it on a server.

i tried firebase-database, but it is lagging the speed/performance i require.

Then store it on a faster server, I guess. Or, use a local file as a cache, with the server acting as a backup location, should you need to restore the data at a later point.


问:
node_modules/ngx-toastr/toastr/toast-noanimation.component.d.ts(19,9)
shared.module.ts

```<code>import { animate, state, style, transition, trigger } from '@angular/animations';
import { ToastrModule } from 'ngx-toastr';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
    declarations: [HeaderComponent, SidebarComponent],
    imports: [
        CommonModule,
        RouterModule,
        FormsModule,
        NgxDatatableModule,
        ToastrModule.forRoot() // ToastrModule added
    ],
    exports: [
        HeaderComponent,
        SidebarComponent,
        FormsModule,
        NgxDatatableModule,
        ToastrModule,
    ],
    providers: []
})
</code>```

this is my shared module
i have installed
npm install ngx-toastr --save

npm install @angular/animations --save

But it gives me an error

ERROR in node_modules/@angular/animations/browser/browser.d.ts(135,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/@angular/animations/browser/browser.d.ts(301,9): error TS1086: An accessor cannot be declared in an ambient context.

    node_modules/ngx-toastr/portal/portal.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/ngx-toastr/toastr/toast-noanimation.component.d.ts(19,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/ngx-toastr/toastr/toast.component.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.

Please suggest for this

package.json file

```<code>{
  "name": "mop",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^9.0.1",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "~8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/router": "~8.2.14",
    "@fortawesome/fontawesome-free": "^5.12.1",
    "@ng-bootstrap/ng-bootstrap": "^5.2.1",
    "@swimlane/ngx-datatable": "^16.0.3",
    "angular-font-awesome": "^3.1.2",
    "bootstrap": "^4.4.1",
    "font-awesome": "^4.7.0",
    "line-awesome": "^1.3.0",
    "ng2-bootstrap": "^1.6.3",
    "ngx-cookie-service": "^2.3.0",
    "ngx-toastr": "^12.0.0",
    "rxjs": "~6.4.0",
    "save": "^2.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.23",
    "@angular/cli": "~8.3.23",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  }
}
</code>```

答:
Please check your package.json, you may be using wrong version of

@angular... packages, some of them are ~9 and some of them are ~8

upgrade Angular by running:

```<code>ng update @angular/core @angular/cli
</code>```

upgrade material

```<code>ng update @angular/material
</code>```

You can also update manually the version in package.json and run npm install or yarn

Body:
shared.module.ts

import { animate, state, style, transition, trigger } from '@angular/animations';
import { ToastrModule } from 'ngx-toastr';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
    declarations: [HeaderComponent, SidebarComponent],
    imports: [
        CommonModule,
        RouterModule,
        FormsModule,
        NgxDatatableModule,
        ToastrModule.forRoot() // ToastrModule added
    ],
    exports: [
        HeaderComponent,
        SidebarComponent,
        FormsModule,
        NgxDatatableModule,
        ToastrModule,
    ],
    providers: []
})

this is my shared module
i have installed
npm install ngx-toastr --save

npm install @angular/animations --save

But it gives me an error

ERROR in node_modules/@angular/animations/browser/browser.d.ts(135,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/@angular/animations/browser/browser.d.ts(301,9): error TS1086: An accessor cannot be declared in an ambient context.

    node_modules/ngx-toastr/portal/portal.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/ngx-toastr/toastr/toast-noanimation.component.d.ts(19,9): error TS1086: An accessor cannot be declared in an ambient context.
    node_modules/ngx-toastr/toastr/toast.component.d.ts(26,9): error TS1086: An accessor cannot be declared in an ambient context.

Please suggest for this

package.json file

{
  "name": "mop",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^9.0.1",
    "@angular/common": "~8.2.14",
    "@angular/compiler": "~8.2.14",
    "@angular/core": "~8.2.14",
    "@angular/forms": "~8.2.14",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "~8.2.14",
    "@angular/platform-browser-dynamic": "~8.2.14",
    "@angular/router": "~8.2.14",
    "@fortawesome/fontawesome-free": "^5.12.1",
    "@ng-bootstrap/ng-bootstrap": "^5.2.1",
    "@swimlane/ngx-datatable": "^16.0.3",
    "angular-font-awesome": "^3.1.2",
    "bootstrap": "^4.4.1",
    "font-awesome": "^4.7.0",
    "line-awesome": "^1.3.0",
    "ng2-bootstrap": "^1.6.3",
    "ngx-cookie-service": "^2.3.0",
    "ngx-toastr": "^12.0.0",
    "rxjs": "~6.4.0",
    "save": "^2.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.23",
    "@angular/cli": "~8.3.23",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  }
}

Body:
Please check your package.json, you may be using wrong version of

@angular... packages, some of them are ~9 and some of them are ~8

upgrade Angular by running:

ng update @angular/core @angular/cli

upgrade material

ng update @angular/material

You can also update manually the version in package.json and run npm install or yarn


问:
Trademark considerations when naming .NET assemblies
We have an application and some of its assemblies, that are generated by us, are named Microsoft.*.dll

Is that OK from a legal point of view?

If not, is there a specific reference on Microsoft's website clearly stating this is prohibited?
I searched and couldn't find one.

答:
Stackoverflow is not the right place to ask legal questions but the official design guidelines says you should consider naming DLLs according to <Company>.<Component>.dll where <Company> is the name of the manufacturer.

Microsoft is not the manufacturer of your assemblies and it is a registered trademark with all that it entails.

In short, don't use their name. If not illegal, it's a least confusing for any consumer of your assemblies.


问:
Load jar dynamically at runtime?
My current java project is using methods and variables from another project (same package). Right now the other project's jar has to be in the classpath to work correctly. My problem here is that the name of the jar can and will change because of increasing versions, and because you cannot use wildcards in the manifest classpath, it's impossible to add it to the classpath. So currently the only option of starting my application is using the -cp argument from the command line, manually adding the other jar my project depends on.

To improve this, I wanted to load the jar dynamically and read about using the ClassLoader. I read a lot of examples for it, however I still don't understand how to use it in my case.

What I want is it to load a jar file, lets say, myDependency-2.4.1-SNAPSHOT.jar, but it should be able to just search for a jar file starting with myDependency- because as I already said the version number can change at anytime. Then I should just be able to use it's methods and variables in my Code just like I do now (like ClassInMyDependency.exampleMethod()).

Can anyone help me with this, as I've been searching the web for a few hours now and still don't get how to use the ClassLoader to do what I just explained.

Many thanks in advance

答:
I needed to load a jar file at runtime for both java 8 and java 9+. Here is the method to do it (using Spring Boot 1.5.2 if it may relate).</p>

```<code>public static synchronized void loadLibrary(java.io.File jar) {
    try {
        java.net.URL url = jar.toURI().toURL();
        java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
        method.setAccessible(true); /*promote the method to public access*/
        method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});
    } catch (Exception ex) {
        throw new RuntimeException("Cannot load library from jar file '" + jar.getAbsolutePath() + "'. Reason: " + ex.getMessage());
    }
}
</code>```

Title: Load jar dynamically at runtime?

Body:
I needed to load a jar file at runtime for both java 8 and java 9+. Here is the method to do it (using Spring Boot 1.5.2 if it may relate).

public static synchronized void loadLibrary(java.io.File jar) {
    try {
        java.net.URL url = jar.toURI().toURL();
        java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
        method.setAccessible(true); /*promote the method to public access*/
        method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});
    } catch (Exception ex) {
        throw new RuntimeException("Cannot load library from jar file '" + jar.getAbsolutePath() + "'. Reason: " + ex.getMessage());
    }
}


问:
loading a shapefile with properties in non-UTF8 formats
I can successfully load and display a shapefile in Leaflet. However, when I try to access the features properties, the characters are all mangled. To investigate, I defined the following function:

```<code>function unpack(str) {
    var codePoints = [];
    for(var i = 0; i < str.length; i++)
        codePoints.push( str.charCodeAt(i) );
    return codePoints;
};
</code>```

Then, I do the following:

```<code>const options = {
    onEachFeature: (feature, layer) => {
         console.log(unpack(feature.properties.NAME));
    }
};
L.shapefile(url, options);
</code>```

When I load the application I see on the console arrays like the following:

[65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533]

... which corresponds to the Unicode replacement character.

For what it's worth, I've examined the *.dbf file using a binary editor and I've established that the feature.properties.NAME is given in ISO 8859-7 (ISO Latin/Greek alphabet).

答:
Let's have a trip down the rabbit hole of how Leaflet.shapefile handles strings from features' properties.

First off, if you know a bit about the shapefile format, you'll be familiar with the fact that the .shp file holds the geometries and that the .dbf file holds the properties. The data for each feature is split between those files.

So Leaflet.shapefile depends on shapefilejs to do the parsing, and in turn shapefilejs depends on parseDBF to read the contents of the .dbf file. Reading a bit of the code from parseDBF shows that there's support for multiple character encodings via iconv-lite:

```<code>module.exports = function(buffer, encoding) {
  var decoder = createDecoder(encoding);
  // ...etc...
</code>```

So one can call the parseDBF module with a buffer for the contents of the DBF file, and pass a string with an iconv-compatible encoding.

Now, does shapefilejs use this functionality? Once again let's look at the code:

```<code>  if (zip[name + '.dbf']) {
    dbf = parseDbf(zip[name + '.dbf'], zip[name + '.cpg']);
  }
</code>```

This means "if there's a .dbf file, call parseDBF with the contents of the .dbf file and the contents of the .cpg file". Wait, why is it reading a .cpg file? What does that mean? The answer is in any list of shapefile sidecar files, such as the one in wikipedia:

.cpg — used to specify the code page (only for .dbf) for identifying the character encoding to be used

This should show that leaflet-shapefile is handling character encoding as expected - it reads encoding information from the right sidecar file, and decodes strings from the .dbf file via iconv-lite. You should check if that sidecar file exists, and that the contents of that file are the desired character encoding.

Note that the list of supported encodings for iconv-lite (and also the supported encodings for iconv) is far for complete (compared to the list of known text encodings). Maybe your .cpg file is OK but support for that text encoding is just not there.

Body:
I can successfully load and display a shapefile in Leaflet. However, when I try to access the features properties, the characters are all mangled. To investigate, I defined the following function:

function unpack(str) {
    var codePoints = [];
    for(var i = 0; i < str.length; i++)
        codePoints.push( str.charCodeAt(i) );
    return codePoints;
};

Then, I do the following:

const options = {
    onEachFeature: (feature, layer) => {
         console.log(unpack(feature.properties.NAME));
    }
};
L.shapefile(url, options);

When I load the application I see on the console arrays like the following:

[65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533, 65533]

... which corresponds to the Unicode replacement character.

For what it's worth, I've examined the *.dbf file using a binary editor and I've established that the feature.properties.NAME is given in ISO 8859-7 (ISO Latin/Greek alphabet).

Body:
Let's have a trip down the rabbit hole of how Leaflet.shapefile handles strings from features' properties.

First off, if you know a bit about the shapefile format, you'll be familiar with the fact that the .shp file holds the geometries and that the .dbf file holds the properties. The data for each feature is split between those files.

So Leaflet.shapefile depends on shapefilejs to do the parsing, and in turn shapefilejs depends on parseDBF to read the contents of the .dbf file. Reading a bit of the code from parseDBF shows that there's support for multiple character encodings via iconv-lite:

module.exports = function(buffer, encoding) {
  var decoder = createDecoder(encoding);
  // ...etc...

So one can call the parseDBF module with a buffer for the contents of the DBF file, and pass a string with an iconv-compatible encoding.

Now, does shapefilejs use this functionality? Once again let's look at the code:

  if (zip[name + '.dbf']) {
    dbf = parseDbf(zip[name + '.dbf'], zip[name + '.cpg']);
  }

This means "if there's a .dbf file, call parseDBF with the contents of the .dbf file and the contents of the .cpg file". Wait, why is it reading a .cpg file? What does that mean? The answer is in any list of shapefile sidecar files, such as the one in wikipedia:

.cpg — used to specify the code page (only for .dbf) for identifying the character encoding to be used

This should show that leaflet-shapefile is handling character encoding as expected - it reads encoding information from the right sidecar file, and decodes strings from the .dbf file via iconv-lite. You should check if that sidecar file exists, and that the contents of that file are the desired character encoding.

Note that the list of supported encodings for iconv-lite (and also the supported encodings for iconv) is far for complete (compared to the list of known text encodings). Maybe your .cpg file is OK but support for that text encoding is just not there.


问:
.NET units class, inches to millimeters
Does .NET has Units conversion class? I need to convert inches to millimeters and vise versa. </p>

答: Csunits is a nice Units of Measurement library for C#, see https://github.com/cureos/csunits. It's currently geared towards radiotherapy but you can easily add your own units and quantities.</p>

Title: .NET units class, inches to millimeters


问:
Unable to connect to Kafka from outside application
I have two docker machines  and I want to create a kafka cluster inside docker swarm. My docker-compose.yml looks like this:

```<code>version: '3.2'
services:
  zookeeper:
    image: wurstmeister/zookeeper
    ports:
      - "2181:2181"
  kafka:
    image: wurstmeister/kafka:latest
    ports:
      - "9092:9092"
      - "29092:29092"
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_LISTENERS: PLAINTEXT://:9092,PLAINTEXT_HOST://:29092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
</code>```

I followed this question: Unable to connect to Kafka run in container from Spring Boot app run outside container and I am trying to access kafka from outside using localhost:29092.

I have already create the topic mytesttopic inside kafka. The below python code:

```<code>from kafka import KafkaConsumer, SimpleProducer, TopicPartition, KafkaClient

def consume_from_topic():
    try:
        consumer = KafkaConsumer('mytesttopic',
                                 group_id= None,
                                 bootstrap_servers=['localhost:29092'],
                                 auto_offset_reset='earliest')

        for message in consumer:
            #consumer.commit()
            print ("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition,
                                                  message.offset, message.key,
                                                  message.value))
    except Exception as e:
        print(e)
        pass

if __name__ == '__main__':
    consume_from_topic()
</code>```

returns:

NoBrokersAvailable

Does anyone know what I am missing here?

答:
Given you are running docker swarm on 2 other machines you won't be able to connect on localhost:29092 due to the fact that kafka will be exposed on port 29092 on your nodes of the docker swarm. Try connecting to kafka by using the hostname of one of your nodes + port 29092. You should be able to connect to kafka this way.

Please note that this will only work if you are running docker swarm with routing mesh, the routing mesh makes sure that each node accepts incoming requests on a published port for any service, no matter if it is running on the same hosts and makes sure the traffic reaches the actual host where your container is running.

If you have not yet setup routing mesh try connceting to the actual hostname where a kafka container is running (not recommended, but for testing purposes it works)

I hope this helps you!

Body:
I have two docker machines  and I want to create a kafka cluster inside docker swarm. My docker-compose.yml looks like this:

version: '3.2'
services:
  zookeeper:
    image: wurstmeister/zookeeper
    ports:
      - "2181:2181"
  kafka:
    image: wurstmeister/kafka:latest
    ports:
      - "9092:9092"
      - "29092:29092"
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_LISTENERS: PLAINTEXT://:9092,PLAINTEXT_HOST://:29092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092

I followed this question: Unable to connect to Kafka run in container from Spring Boot app run outside container and I am trying to access kafka from outside using localhost:29092.

I have already create the topic mytesttopic inside kafka. The below python code:

from kafka import KafkaConsumer, SimpleProducer, TopicPartition, KafkaClient

def consume_from_topic():
    try:
        consumer = KafkaConsumer('mytesttopic',
                                 group_id= None,
                                 bootstrap_servers=['localhost:29092'],
                                 auto_offset_reset='earliest')

        for message in consumer:
            #consumer.commit()
            print ("%s:%d:%d: key=%s value=%s" % (message.topic, message.partition,
                                                  message.offset, message.key,
                                                  message.value))
    except Exception as e:
        print(e)
        pass

if __name__ == '__main__':
    consume_from_topic()

returns:

NoBrokersAvailable

Does anyone know what I am missing here?


问:
One line console command to set first root password in GitLab
I need to setup GitLab and runner, create user and projects, register runner - automatically via user data in terraform. It could be possible via API with bash or python scripts.

To use API we need ACCESS_TOKEN - with this script  https://gist.github.com/vitalyisaev2/215f890e75252cd36794221c2debf365 it is possible to create ACCESS_TOKEN for root user.

But first I need to have a valid root user password. This is a big problem for me I can not solve and ask You guys to help me.

On first login GitLab asks to set/change password.
First login to GitLab UI

I want to set this password via script, non interactively.
It is possible set password this way:

```<code>gitlab-rails console
irb(main):001:0> user = User.where(id: 1).first
irb(main):001:0> user.password = user.password_confirmation ='IrF8WCsZJlMP'
irb(main):001:0> user.save!
irb(main):001:0> exit
</code>```

But, it is not suitable for me, because I can not input commands interactively. I need one line command to set password, or set it while installing gitlab-ce.

This way doesn't work too, it doesn't set password, only EXTERNAL_URL :

```<code>sudo GITLAB_ROOT_EMAIL="some@email.com" GITLAB_ROOT_PASSWORD="nTjYfcKxcW" EXTERNAL_URL="http://example.com" yum install gitlab-ce
</code>```

Please help to set first gitlab root password non interactively, without visiting browser, via console with one line command or while gitlab-ce installation.

Thanks!

答:
In file /etc/gitlab/gitlab.rb i found "gitlab_rails['initial_root_password"

So, I solved my problem this way

```<code>sed -i"" "s#\# gitlab_rails\['initial_root_password.*#gitlab_rails\['initial_root_password'\] = \""${GITLAB_INITIAL_ROOT_PASSWD}"\"#g" /etc/gitlab/gitlab.rb

</code>```

Need to set "root_initial_password" before first "gitlab-ctl reconfigure" command

Body:
I need to setup GitLab and runner, create user and projects, register runner - automatically via user data in terraform. It could be possible via API with bash or python scripts.

To use API we need ACCESS_TOKEN - with this script  https://gist.github.com/vitalyisaev2/215f890e75252cd36794221c2debf365 it is possible to create ACCESS_TOKEN for root user.

But first I need to have a valid root user password. This is a big problem for me I can not solve and ask You guys to help me.

On first login GitLab asks to set/change password.
First login to GitLab UI

I want to set this password via script, non interactively.
It is possible set password this way:

gitlab-rails console
irb(main):001:0> user = User.where(id: 1).first
irb(main):001:0> user.password = user.password_confirmation ='IrF8WCsZJlMP'
irb(main):001:0> user.save!
irb(main):001:0> exit

But, it is not suitable for me, because I can not input commands interactively. I need one line command to set password, or set it while installing gitlab-ce.

This way doesn't work too, it doesn't set password, only EXTERNAL_URL :

sudo GITLAB_ROOT_EMAIL="some@email.com" GITLAB_ROOT_PASSWORD="nTjYfcKxcW" EXTERNAL_URL="http://example.com" yum install gitlab-ce

Please help to set first gitlab root password non interactively, without visiting browser, via console with one line command or while gitlab-ce installation.

Thanks!

Body:
In file /etc/gitlab/gitlab.rb i found "gitlab_rails['initial_root_password"

So, I solved my problem this way

sed -i"" "s#\# gitlab_rails\['initial_root_password.*#gitlab_rails\['initial_root_password'\] = \""${GITLAB_INITIAL_ROOT_PASSWD}"\"#g" /etc/gitlab/gitlab.rb

Need to set "root_initial_password" before first "gitlab-ctl reconfigure" command


问:
Delayed scroll to Div ID when select option is chosen
I'd like to be able to scroll to a particular ID when a select option has been chosen from a drop down list. It seems like it should be extremely simple, however I can't find an example on here that performs how I want it to.

Basically, I have a div near the top of the page

CONTENT

Then lower down the page, a select box:

```<code><select id="variant">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</code>```

What I would like to do, is - once a selection has been made - for the page to scroll back up to the id "mainimage".

If possible, ideally this would happen after a delay of around half a second, and scroll smoothly.

It seems like it should be fairly straightforward, as the page just needs to scroll to the same ID regardless of the selection.

Is this possible with javascript?

Thanks in advance.

答:
Try this</p>

```<code>$('#variant').on('change',function(){
 setTimeout(function(){
    $('html, body').animate({
    scrollTop: $("#mainimage").offset().top
  }, 2000);
 },500);
})
</code>```

Body:
I'd like to be able to scroll to a particular ID when a select option has been chosen from a drop down list. It seems like it should be extremely simple, however I can't find an example on here that performs how I want it to.

Basically, I have a div near the top of the page

CONTENT

Then lower down the page, a select box:

<select id="variant">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

What I would like to do, is - once a selection has been made - for the page to scroll back up to the id "mainimage".

If possible, ideally this would happen after a delay of around half a second, and scroll smoothly.

It seems like it should be fairly straightforward, as the page just needs to scroll to the same ID regardless of the selection.

Is this possible with javascript?

Thanks in advance.

Body:
Try this

$('#variant').on('change',function(){
 setTimeout(function(){
    $('html, body').animate({
    scrollTop: $("#mainimage").offset().top
  }, 2000);
 },500);
})


问:
Display stored Array Objects to List in Javascript to HTML
I'm Trying to make a list display in HTML of the stored details i put in my object using Javascript.
which should look like this

```<code>name: Tester1 , age: 1
name: Tester2 , age: 2
name: Tester3 , age: 3
</code>```

I used for in loop to display all the inputted objects, but it this happened

```<code>Actual:
name: Tester1 , age: 1name: Tester1 , age: 1name: Tester2 , age: 2name: Tester1 , age: 1name: Tester2 , age: 2name: Tester3 , age: 3
</code>```

Here is the code for the Jascript

```<code>var person = [];
function profile(e) {
    //to stop form from resubmitting
    e.preventDefault();

    var pProfile = {
        name: document.getElementById('name').value,
        age: document.getElementById('age').value
    }
    person.push(pProfile);
    //used to convert result to string
    var myJSON = JSON.stringify(person);

    document.forms[0].reset();

    //display in Final Obejct div
    document.getElementById("fObject").innerHTML = myJSON;

    //display converted objects to
    for (let x in person){
         document.getElementById("rFormat").append("name: " + person[x].name + " , " + "age : " + person[x].age + "<br>");
         console.log(person[x]);
    }
}

</code>```

And this is for the HTML

```<code>    <div id="part1">
        <h3>Part 1</h2>
        <form id="profile" onsubmit="profile(event)" action="#">
            Name: <input type="text" id ="name">
            Age: <input type="text" id ="age">
            <input type="Submit" value="Add">
        </form>

        <h4>Final Object</h4>
        <div id="fObject"></div>

        <h4>Readable Format</h4>
        <div id="rFormat"></div>
    </div>
</code>```

Pretty sure that I did something wrong with the for in loop, but i don't know exactly where.
Please help. I'm new in javascript. Thanks so much.

答:
The correct way is by using the innerHTML method instead:

```<code>for (let x in person) {
    document.getElementById("rFormat").innerHTML += person[0] + "<br>";
}
</code>```

I am not sure as to why yours does not work though.

Body:
I'm Trying to make a list display in HTML of the stored details i put in my object using Javascript.
which should look like this

name: Tester1 , age: 1
name: Tester2 , age: 2
name: Tester3 , age: 3

I used for in loop to display all the inputted objects, but it this happened

Actual:
name: Tester1 , age: 1name: Tester1 , age: 1name: Tester2 , age: 2name: Tester1 , age: 1name: Tester2 , age: 2name: Tester3 , age: 3

Here is the code for the Jascript

var person = [];
function profile(e) {
    //to stop form from resubmitting
    e.preventDefault();

    var pProfile = {
        name: document.getElementById('name').value,
        age: document.getElementById('age').value
    }
    person.push(pProfile);
    //used to convert result to string
    var myJSON = JSON.stringify(person);

    document.forms[0].reset();

    //display in Final Obejct div
    document.getElementById("fObject").innerHTML = myJSON;

    //display converted objects to
    for (let x in person){
         document.getElementById("rFormat").append("name: " + person[x].name + " , " + "age : " + person[x].age + "
");
         console.log(person[x]);
    }
}

And this is for the HTML

Part 1

        <form id="profile" onsubmit="profile(event)" action="#">
            Name: <input type="text" id ="name">
            Age: <input type="text" id ="age">
            <input type="Submit" value="Add">
        </form>

Final Object

Readable Format

Pretty sure that I did something wrong with the for in loop, but i don't know exactly where.
Please help. I'm new in javascript. Thanks so much.

Body:
The correct way is by using the innerHTML method instead:

for (let x in person) {
    document.getElementById("rFormat").innerHTML += person[0] + "<br>";
}

I am not sure as to why yours does not work though.


问:
Can't create svg in d3.js
I wrote a function that returns svg but faced an error (screenshot):

Error in created hook: "TypeError: Cannot read property 'prefix' of undefined"

This is how I add the library :

```<code>import * as d3 from 'd3'

markerSvgIcon (options) {
      const svg = document.createElementNS(d3.ns.prefix.svg, 'svg')
      // eslint-disable-next-line no-unused-vars
      const triangle = d3.svg.symbol().type('triangle').size(195)
      // eslint-disable-next-line no-unused-vars
      const svgTri = d3.select(svg)
        .append('path')
        .attr('d', triangle)
        .attr('transform', function (d) { return 'translate(' + 14 + ',' + 31 + ')' })
        .style('fill', '#35c377')
      console.log(svg)
      return svg
    }
</code>```

答:
As the changelog says, d3.ns has been renamed to d3.namespaces.

It should be:

```<code>const svg = document.createElementNS(d3.namespaces.svg, 'svg')
</code>```

Title: Can't create svg in d3.js

Body:
I wrote a function that returns svg but faced an error (screenshot):

Error in created hook: "TypeError: Cannot read property 'prefix' of undefined"

This is how I add the library :

import * as d3 from 'd3'

markerSvgIcon (options) {
      const svg = document.createElementNS(d3.ns.prefix.svg, 'svg')
      // eslint-disable-next-line no-unused-vars
      const triangle = d3.svg.symbol().type('triangle').size(195)
      // eslint-disable-next-line no-unused-vars
      const svgTri = d3.select(svg)
        .append('path')
        .attr('d', triangle)
        .attr('transform', function (d) { return 'translate(' + 14 + ',' + 31 + ')' })
        .style('fill', '#35c377')
      console.log(svg)
      return svg
    }

Body:
As the changelog says, d3.ns has been renamed to d3.namespaces.

It should be:

const svg = document.createElementNS(d3.namespaces.svg, 'svg')


问:
need help to take phpMyAdmin database's backup
i want to  backup my database from php file...

i am using phpMyAdmin as back end. i want to create excel file from that data base is it possible? yes then how? give me some suggestion on it thanks in advance...

my one more querty is:

if i am running this php code then when it store that file..? i've checked into the phpMyAdmin bt that was not inside that the code is as below

```<code><?php
include 'config.php';
include 'opendb.php';
$tableName  = 'mypet';
$backupFile = 'backup/mypet.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $login_master";
$result = mysql_query($query);

include 'closedb.php';
?>
</code>```

答:
It's pretty easy.

On the phpmyadmin graphic interface, select the database you want to save.

Click on the export tab at the top.

Select "excel" from the box you'll find on the right.

Click go at the bottom.

Done.

Body:
i want to  backup my database from php file...

i am using phpMyAdmin as back end. i want to create excel file from that data base is it possible? yes then how? give me some suggestion on it thanks in advance...

my one more querty is:

if i am running this php code then when it store that file..? i've checked into the phpMyAdmin bt that was not inside that the code is as below

<?php
include 'config.php';
include 'opendb.php';
$tableName  = 'mypet';
$backupFile = 'backup/mypet.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $login_master";
$result = mysql_query($query);

include 'closedb.php';
?>


问:
Difference between Fabric Canvas and StaticCanvas
Can anyone explain the difference and purpose of Canvas and Static Canvas in Fabric JS. I'm really confused with the both topic!</p>

答:
StaticCanvas has no interactive layer and no event handling. You can't drag objects around, draw, register clicks, etc.

StaticCanvas is used when you only need to render a scene or when handling user interaction is impossible, e.g. rendering canvas on the server side.


问:
How to load JAR files dynamically at Runtime?
Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own ClassLoader, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument.

Any suggestions for simple code that does this?

答:
I needed to load a jar file at runtime for both java 8 and java 9+ (above comments don't work for both of these versions). Here is the method to do it (using Spring Boot 1.5.2 if it may relate).</p>

```<code>public static synchronized void loadLibrary(java.io.File jar) {
    try {
        java.net.URL url = jar.toURI().toURL();
        java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
        method.setAccessible(true); /*promote the method to public access*/
        method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});
    } catch (Exception ex) {
        throw new RuntimeException("Cannot load library from jar file '" + jar.getAbsolutePath() + "'. Reason: " + ex.getMessage());
    }
}
</code>```

OwnerDisplayName: allain

Body:
I needed to load a jar file at runtime for both java 8 and java 9+ (above comments don't work for both of these versions). Here is the method to do it (using Spring Boot 1.5.2 if it may relate).

public static synchronized void loadLibrary(java.io.File jar) {
    try {
        java.net.URL url = jar.toURI().toURL();
        java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class});
        method.setAccessible(true); /*promote the method to public access*/
        method.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{url});
    } catch (Exception ex) {
        throw new RuntimeException("Cannot load library from jar file '" + jar.getAbsolutePath() + "'. Reason: " + ex.getMessage());
    }
}


问:
Find blank cells, insert formula that includes cell range above
I am trying to find a vba code that will find blank cells in a certain column, and replace these cells with a formula that includes the range of cells above (up until the next blank cell)

for instance, cells A2:A15 are filled in,
A16 is blank,
I want a code that can find the blank C16, and insert the following code:

```<code>=COUNTIF(A2:A13,A2)=COUNTA(A2:A13)
</code>```

I have about 72,000 rows, and there is not a uniform spacing between the blank cell ranges.

Thank you so much in advance!

This the what the code in have found

```<code>Sub Testing()
Dim Rng As Range, r As Range

Set Rng = Range("a2:a" & Range("a" & Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeConstants)
Top = Selection.End(xlUp).Value

For Each r In Rng.Areas
    With r
         .Cells(1, 1).Offset(.Rows.Count).Formula = "=countif(" & .Address & ", " & .Top & ") = CountA(" & .Address & ")" 'i got stucked with the code here. where i want to pick the first cell for every range.
    End With
Next
End Sub

</code>```

答:
Try the following (without VBA at first):

Select your column.

Goto blanks (ctrl+G).

In the formula bar, type your formula.

Press ctrl ENTER.

This should copy the formula into all blank cells you have selected.

Once this works, record it into a VBA macro.

Body:
I am trying to find a vba code that will find blank cells in a certain column, and replace these cells with a formula that includes the range of cells above (up until the next blank cell)

for instance, cells A2:A15 are filled in,
A16 is blank,
I want a code that can find the blank C16, and insert the following code:

=COUNTIF(A2:A13,A2)=COUNTA(A2:A13)

I have about 72,000 rows, and there is not a uniform spacing between the blank cell ranges.

Thank you so much in advance!

This the what the code in have found

Sub Testing()
Dim Rng As Range, r As Range

Set Rng = Range("a2:a" & Range("a" & Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeConstants)
Top = Selection.End(xlUp).Value

For Each r In Rng.Areas
    With r
         .Cells(1, 1).Offset(.Rows.Count).Formula = "=countif(" & .Address & ", " & .Top & ") = CountA(" & .Address & ")" 'i got stucked with the code here. where i want to pick the first cell for every range.
    End With
Next
End Sub


问:
Ionic Native HTTP does not work for Anroid 9 (Pie) and up?
I've created an app that connects successfully to our server using Ionic Native HTTP, testing it with Samsung Galaxy J7 Prime OS version Marshmallow and several others that were not yet under Android Pie. For some reason, when I tested it with a device under Android Pie, it won't work anymore and I'm receiving CORS policy issues. Has anybody encountered a similar issue? Is there a workaround for this? Unfortunately, modifications within the server config is not an option. I've also read some solutions about proxy but am not sure how to implement them.

Versions:
cordova-plugin-advanced-http: 2.1.1
ionic-native/http: 5.8.0

答:
To solve that problem, you should make changes to the config.xml file.

First thing you need to change is 'widget' tag, it should look similar to this one:

```<code><widget id="com.dynamicsoft.app" version="2.2.2" xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cdv="http://cordova.apache.org/ns/1.0">
</code>```

After that, inside of platform where name='android', you should add this code:

```<code><edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
    <application android:usesCleartextTraffic="true" />
</edit-config>
</code>```

After that you can run rebuild the application.

Body:
To solve that problem, you should make changes to the config.xml file.

First thing you need to change is 'widget' tag, it should look similar to this one:

<widget id="com.dynamicsoft.app" version="2.2.2" xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cdv="http://cordova.apache.org/ns/1.0">

After that, inside of platform where name='android', you should add this code:

<edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
    <application android:usesCleartextTraffic="true" />
</edit-config>

After that you can run rebuild the application.


问:
Deploying Django on Heroku?
I am trying to host a Python\Django app on Heroku. I followed the guide on heroku website but when I execute the line "heroku ps:scale web:1" it comes back the following message:

No process types on ⬢ salty-brushlands-45215.

   ▸    Upload a Procfile to add process types.

   ▸    https://devcenter.heroku.com/articles/procfile

I already tryed to commit a Procfile into my project (searching for a solution) but I don't know if requires any configuration inside it. Help please!

答:
Your Procfile should contain this,

```<code>web: gunicorn your_project.wsgi
</code>```

web defines the type of your application

gunicorn is a wsgi server

Title: Deploying Django on Heroku?

Body:
Your Procfile should contain this,

web: gunicorn your_project.wsgi

web defines the type of your application

gunicorn is a wsgi server


问:
How change focus in reused table view cell with nested collection view in tvOS?
I have table view with nested collection view(horizontal scrolling) into table view cell. Something like that:

```<code>-table view:
  - section
   - cell:
    - collection view
</code>```

On starting screen I have 3 sections with 1 cell in each section. When I try to reuse 1 section with cell, indexPath for focused item don't change.

For example, if I select 1 section 1 cell and focused 12th item in collection view, then I scroll down table view in this manner I change focused item and switch to another section of table view. So I reuse cell and see the same focused indexPath (12 row). So collection view scrolles to this item.

I tried to reset preferredFocusEnvironments in

override func prepareForReuse()

but it had no result. And when I set to false collectionView.remembersLastFocusedIndexPath = false it didn't help me to solve the  problem. How can I fix this problem?

答:
I found out that problem was in contentOffset in collectionView. When I reused tableViewCell I didn't reset offset in collectionView. So I saved all offset for each collectionView in tableViewCell and set this value by key to collectionView. Something like this(in func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)):

```<code>return tableView.dequeueReusableCell(cellClass: HomeTableViewCell.self, for: indexPath).adjust {

    if let id = $0.feedID {
      contentOffsets[id] = $0.collectionView.contentOffset
    }
    $0.preprareForDisplay(feed: feeds[indexPath.section)
    $0.collectionView.contentOffset = contentOffsets[feeds[indexPath.section].origin.id] ?? .zero
  }
</code>```

So after that focus work correct.

Body:
I have table view with nested collection view(horizontal scrolling) into table view cell. Something like that:

-table view:
  - section
   - cell:
    - collection view

On starting screen I have 3 sections with 1 cell in each section. When I try to reuse 1 section with cell, indexPath for focused item don't change.

For example, if I select 1 section 1 cell and focused 12th item in collection view, then I scroll down table view in this manner I change focused item and switch to another section of table view. So I reuse cell and see the same focused indexPath (12 row). So collection view scrolles to this item.

I tried to reset preferredFocusEnvironments in

override func prepareForReuse()

but it had no result. And when I set to false collectionView.remembersLastFocusedIndexPath = false it didn't help me to solve the  problem. How can I fix this problem?

Body:
I found out that problem was in contentOffset in collectionView. When I reused tableViewCell I didn't reset offset in collectionView. So I saved all offset for each collectionView in tableViewCell and set this value by key to collectionView. Something like this(in func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)):

return tableView.dequeueReusableCell(cellClass: HomeTableViewCell.self, for: indexPath).adjust {

    if let id = $0.feedID {
      contentOffsets[id] = $0.collectionView.contentOffset
    }
    $0.preprareForDisplay(feed: feeds[indexPath.section)
    $0.collectionView.contentOffset = contentOffsets[feeds[indexPath.section].origin.id] ?? .zero
  }

So after that focus work correct.


问:
Which are the best alternatives to Lucene?
It may run on Unix and it will be used for email searching (Dovecot, Postfix and maildir).

Lucene is not a problem, I'm just analyzing some alternatives.

答:
For simple things native full-text search of your RDBMS.

Full text search in PostgreSQL

FTS2 in SQLite

Full text search in MySQL

Oracle Text in Oracle DB

Full text search in Microsoft SQL Server

OwnerDisplayName: Rui Carneiro

LastEditorDisplayName: Rui Carneiro


问:
WCF RIA Services simple question
I'm new to all this stuff, so a question is dumb. If I'll use WCF RIA Services in my app, does a user well need to install something special to launch my app?

Thank you in advance!

答: Just the Silverlight Plugin and nothing more.</p>

Title: WCF RIA Services simple question


问:
Is it possible to extend Celery, so results would be store to several MongoDB collections?
I've started a new project and I want to make Celery save results to several MongoDB collections instead of one. Is there a way to do that through configs or do I need to extend Celery and Kombu to achieve that? </p>

答:
Celery is licensed under The BSD License. The source code is on https://github.com/celery/celery

it is possible to extend Celery ?

Yes, of course. This is parts of the freedom granted by open source licenses.

I was wondering weather I can make Celery and save results to several MongoDB collections instead of one?

So you download the source code and take the necessary time and efforts to study it and modify it.

Read about forking a software development. Consider proposing your code improvements upstream (on github, with a pull request).


问:
How to change status bar color in Flutter?
I am trying to change the status bar color to white. I found this pub on flutter. I tried to use the example code on my dart files.</p>

答:
This one will also work</p>

```<code>SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
</code>```

Body:
This one will also work

SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);


问:
illegal argument exception while performing a query on elastic search 6.6?
Hi I am having an instance of elastic search running on my machine . it has an index named mep-reports. when i do a query using curl command it is giving an error . the following is the curl command.

```<code> curl -X GET "10.10.9.1:9200/mep-reports*/_search?pretty&size=0" -H 'Content-Type: application/json' -d'{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "@timestamp": {
              "from": "2019-01-31T23:59:59Z",
              "to": "2020-02-17T23:59:59Z",
              "include_lower": true,
              "include_upper": false,
              "format": "yyyy-MM-dd'T'HH:mm:ssZ",
              "boost": 1.0
            }
          }
        },
        {
          "term": {
            "account_id": {
              "value": "270d13e6-2f4f-4d51-99d5-92ffba5f0cb6",
              "boost": 1.0
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1.0
    }
  },
  "aggregations": {
    "performance_over_time": {
      "date_histogram": {
        "field": "@timestamp",
        "format": "yyyy-MM-dd'T'HH:mm:ssZ",
        "interval": "1M",
        "offset": 0,
        "order": {
          "_key": "asc"
        },
        "keyed": false,
        "min_doc_count": 0
      }
    }
  }
}'

Response
{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "Invalid format: [yyyy-MM-ddTHH:mm:ssZ]: Illegal pattern component: T"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "Invalid format: [yyyy-MM-ddTHH:mm:ssZ]: Illegal pattern component: T",
    "caused_by" : {
      "type" : "illegal_argument_exception",
      "reason" : "Illegal pattern component: T"
    }
  },
  "status" : 400
}
</code>```

The following a sample from my elastic search index

```<code>{
  "took" : 14,
  "timed_out" : false,
  "_shards" : {
    "total" : 12,
    "successful" : 12,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 1073013,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "mep-reports-2019.09.11",
        "_type" : "doc",
        "_id" : "68e8e03f-baf8-4bfc-a920-58e26edf835c-353899837500",
        "_score" : 1.0,
        "_source" : {
          "account_id" : "270d13e6-2f4f-4d51-99d5-92ffba5f0cb6",
          "inventory" : "SMS",
          "flight_name" : "test flight 001",
          "status" : "ENROUTE",
          "msg_text" : "Test !!!!!!!!!!!!!!1 elastic searchY",
          "flight_id" : "68e8e03f-baf8-4bfc-a920-58e26edf835c",
          "submission_ts" : "1568197286",
          "recipient" : "353899837500",
          "o_error" : null,
          "nof_segments" : "-1",
          "campaign_id" : "0fae8662-bee9-46ac-9b3e-062f4ba55966",
          "campaign_name" : "Index search petri11",
          "@version" : "1",
          "sender" : "800111",
          "delivery_ts" : "0",
          "@timestamp" : "2019-09-11T10:21:26.000Z"
        }
      }
    ]
  }
}
</code>```

it something related to date format as i am trying to do a search on @timestamp field
really appreciate if you can help

thank you

答:
The problem is because the JSON query is enclosed into single quotes, i.e. the same characters around the T in your date format.

What I suggest you to do is to store the query inside a file named query.json and then send it in binary-mode like this:

```<code>curl -X GET "10.10.9.1:9200/mep-reports*/_search?pretty&size=0" -H 'Content-Type: application/json' --data-binary @query.json
</code>```

That should solve your issue

Body:
Hi I am having an instance of elastic search running on my machine . it has an index named mep-reports. when i do a query using curl command it is giving an error . the following is the curl command.

 curl -X GET "10.10.9.1:9200/mep-reports*/_search?pretty&size=0" -H 'Content-Type: application/json' -d'{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "@timestamp": {
              "from": "2019-01-31T23:59:59Z",
              "to": "2020-02-17T23:59:59Z",
              "include_lower": true,
              "include_upper": false,
              "format": "yyyy-MM-dd'T'HH:mm:ssZ",
              "boost": 1.0
            }
          }
        },
        {
          "term": {
            "account_id": {
              "value": "270d13e6-2f4f-4d51-99d5-92ffba5f0cb6",
              "boost": 1.0
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1.0
    }
  },
  "aggregations": {
    "performance_over_time": {
      "date_histogram": {
        "field": "@timestamp",
        "format": "yyyy-MM-dd'T'HH:mm:ssZ",
        "interval": "1M",
        "offset": 0,
        "order": {
          "_key": "asc"
        },
        "keyed": false,
        "min_doc_count": 0
      }
    }
  }
}'

Response
{
  "error" : {
    "root_cause" : [
      {
        "type" : "illegal_argument_exception",
        "reason" : "Invalid format: [yyyy-MM-ddTHH:mm:ssZ]: Illegal pattern component: T"
      }
    ],
    "type" : "illegal_argument_exception",
    "reason" : "Invalid format: [yyyy-MM-ddTHH:mm:ssZ]: Illegal pattern component: T",
    "caused_by" : {
      "type" : "illegal_argument_exception",
      "reason" : "Illegal pattern component: T"
    }
  },
  "status" : 400
}

The following a sample from my elastic search index

{
  "took" : 14,
  "timed_out" : false,
  "_shards" : {
    "total" : 12,
    "successful" : 12,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 1073013,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "mep-reports-2019.09.11",
        "_type" : "doc",
        "_id" : "68e8e03f-baf8-4bfc-a920-58e26edf835c-353899837500",
        "_score" : 1.0,
        "_source" : {
          "account_id" : "270d13e6-2f4f-4d51-99d5-92ffba5f0cb6",
          "inventory" : "SMS",
          "flight_name" : "test flight 001",
          "status" : "ENROUTE",
          "msg_text" : "Test !!!!!!!!!!!!!!1 elastic searchY",
          "flight_id" : "68e8e03f-baf8-4bfc-a920-58e26edf835c",
          "submission_ts" : "1568197286",
          "recipient" : "353899837500",
          "o_error" : null,
          "nof_segments" : "-1",
          "campaign_id" : "0fae8662-bee9-46ac-9b3e-062f4ba55966",
          "campaign_name" : "Index search petri11",
          "@version" : "1",
          "sender" : "800111",
          "delivery_ts" : "0",
          "@timestamp" : "2019-09-11T10:21:26.000Z"
        }
      }
    ]
  }
}

it something related to date format as i am trying to do a search on @timestamp field
really appreciate if you can help

thank you

Body:
The problem is because the JSON query is enclosed into single quotes, i.e. the same characters around the T in your date format.

What I suggest you to do is to store the query inside a file named query.json and then send it in binary-mode like this:

curl -X GET "10.10.9.1:9200/mep-reports*/_search?pretty&size=0" -H 'Content-Type: application/json' --data-binary @query.json

That should solve your issue


问:
How to parallelize function call in Python
I have this code:

```<code>fog_coeff = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
start = time.time()
for f in fog_coeff:

    foggy_images= am.add_fog(images[0:278],fog_coeff=f)

    for img in foggy_images:
        im = Image.fromarray(img)
        im.save('./result/'+str(counter)+'-'+str(fog_coeff)+'.jpg')
        counter += 1
print("time taken"+ str(time.time()-start))
</code>```

I want to parallize this. How can I do this? My main idea was to take each value from fog_coeff list and give it to each core. Each core will then process 278 images. Is this the right direction? If so, how can I proceed?

答:
You have two options for this, Threads or Processes. The first are allowed to share memory but they are limited in what they can do concurrently, so you can use variables to share the results for example, but you will have to use locks to avoid fdata races.

On the other side processes do not allow to share memory, gaining full concurrency at the OS level. You will have to use some sort of external communication like sockets to send the output back to the main process, or write their results to files.

The answer would depend on which of these two mechanisms you choose.

Edit: elaborating multi processing.

This is done with the multiprocessing library. You will basically define the function that you want your other process to run and then run it in a different process. Processes are handled by the OS, not by Python, so your OS scheduler will be in charge of where each process can be executed. There are advanced tools like process pools that would allow you to have always 4 processes running (in case you are on a quadra-core) but you won't be able to tell your OS how should he handle those processes. He may want to execute its own background processes.

Body:
I have this code:

fog_coeff = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
start = time.time()
for f in fog_coeff:

    foggy_images= am.add_fog(images[0:278],fog_coeff=f)

    for img in foggy_images:
        im = Image.fromarray(img)
        im.save('./result/'+str(counter)+'-'+str(fog_coeff)+'.jpg')
        counter += 1
print("time taken"+ str(time.time()-start))

I want to parallize this. How can I do this? My main idea was to take each value from fog_coeff list and give it to each core. Each core will then process 278 images. Is this the right direction? If so, how can I proceed?


问:
Is there a way to use a custom Angular Directive to apply a ngIf "effect"?
I have an application which has a Role based access. I'm using *ngIf's to allow/block users from access some components.

Is there a way to use a custom directive that will process the "existence" of the component based on the user role; instead of a complete *ngIf condition like this:

```<code><admin-menu *ngIf="user.role =='admin'"></admin-menu>

<admin-menu my-custom-directive ></admin-menu>

    my-custom-directive {

    //make the component where this directive is attached render or vanish based on the user.role
    ngAfterViewInit() {
        if(user.role == 'admin'){
            //render the component
        } else {
            //vanish the component
        }
    }
}
</code>```

答:
Yes, it is. You can use structural directive for this purpose. It is super easy and it can be used in this way *appIfRole="". Exactly same as *ngIf.

Just refer this URL - https://angular.io/guide/structural-directives

And https://angular.io/guide/structural-directives#write-a-structural-directive

Body:
I have an application which has a Role based access. I'm using *ngIf's to allow/block users from access some components.

Is there a way to use a custom directive that will process the "existence" of the component based on the user role; instead of a complete *ngIf condition like this:

<admin-menu *ngIf="user.role =='admin'"></admin-menu>

<admin-menu my-custom-directive ></admin-menu>

    my-custom-directive {

    //make the component where this directive is attached render or vanish based on the user.role
    ngAfterViewInit() {
        if(user.role == 'admin'){
            //render the component
        } else {
            //vanish the component
        }
    }
}