问:
MySQL - Auto_increment by 10
How do I set the auto_increment column in such a way that it increments by 10 for each record insert.

For eg: Instead of the default auto_increment by 1,

```<code>insert into temptable (name) values('abc'),('def');

select * from temptable;
  id|name
  1|abc
  2|def

auto_increment by 10,
  id|name
  10|abc
  20|def
</code>```

答:
If you already have your ids and want to enlarge them by '10 by 10', follow Nazariy's idea and use the current ids and multiply them by 10 with

update xyourtablex set id=id*10000

or a bigger number than your ids (if not, you will create duplicates)
and finally:

update xyourtablex set id=id/1000

or simply remove unique or index, multiply by 10 and add index or unique again :)

Title: MySQL - Auto_increment by 10

Body:
How do I set the auto_increment column in such a way that it increments by 10 for each record insert.

For eg: Instead of the default auto_increment by 1,

insert into temptable (name) values('abc'),('def');

select * from temptable;
  id|name
  1|abc
  2|def

auto_increment by 10,
  id|name
  10|abc
  20|def


来源: stackexchange

问:
Why don't my href image files appear when i try to test my HTML code
The href tags that I have put in my code lead to images saved on my computer but when I test my code they appear as little broken images.

Moodle, c'est cool.

```<code><img src="d6j542d-6fbbd2d6-8801-4016-94aa-63dae5560124.png" alt="wat" width="40px" height="20px">
</code>```

I would like the image to appear, doesn't matter what format, I would just like to see it.

答:
This is only an image name. In that case the browser will try to find the file in the same folder as the html file. Apparently it is not there. It would make sense to check that first. If it's in a different folder you would have to either move it in the same folder as your html or add the folder(s) where the image is located before the file name (e.g. src="folder-a/folder-b/image-name.png")

A folder called "images" in your project folder would make sense. Then the new link would be:

```<code><img src="images/d6j542d-6fbbd2d6-8801-4016-94aa-63dae5560124.png" alt="wat" width="40px" height="20px">
</code>```

(you might also want to consider a more descriptive file name for the image... e.g. logo.png)

ContentLicense: CC BY-SA 4.0

Body:
The href tags that I have put in my code lead to images saved on my computer but when I test my code they appear as little broken images.

Moodle, c'est cool.

I would like the image to appear, doesn't matter what format, I would just like to see it.

Body:
This is only an image name. In that case the browser will try to find the file in the same folder as the html file. Apparently it is not there. It would make sense to check that first. If it's in a different folder you would have to either move it in the same folder as your html or add the folder(s) where the image is located before the file name (e.g. src="folder-a/folder-b/image-name.png")

A folder called "images" in your project folder would make sense. Then the new link would be:

<img src="images/d6j542d-6fbbd2d6-8801-4016-94aa-63dae5560124.png" alt="wat" width="40px" height="20px">

(you might also want to consider a more descriptive file name for the image... e.g. logo.png)


问:
How does callback functions work in NodeJS?
Considering the following code:

rectangle.js:

```<code>module.exports = (x,y,callback) => {
    if (x <= 0 || y <= 0)
        setTimeout(() =>
            callback(new Error("Rectangle dimensions should be greater than zero: l = "
                + x + ", and b = " + y),
            null),
            2000);
    else
        setTimeout(() =>
            callback(null, {
                perimeter: () => (2*(x+y)),
                area:() => (x*y)
            }),
            2000);
}
</code>```

index.js:

```<code>var rect = require('./rectangle');

function solveRect(l,b) {
    console.log("Solving for rectangle with l = "
                + l + " and b = " + b);
    rect(l,b, (err,rectangle) => {
        if (err) {
            console.log("ERROR: ", err.message);
        }
        else {
            console.log("The area of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.area());
            console.log("The perimeter of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.perimeter());
        }
    });
    console.log("This statement after the call to rect()");
};

solveRect(2,4);
solveRect(3,5);
solveRect(0,5);
solveRect(-3,5);
</code>```

In this line rect(l,b, (err,rectangle) we call the rect function and pass l,b, err,rectangle to it. I can see what are l,b but can't see and understand what are err, rectangle ?

Also can't understand where is the definition of callback function? Is it an inner function?

答:
Callback is nothing but the concept of passing a function as a parameter in function call like solveRect(2,4, fn). Here fn is going to be a function.

You can define it inline:

```<code>solveRect(2,4, function(err,rectangle){
   // your code to handle response or delayed result
});
</code>```

Or as named function:

```<code>let fn = function(err,rectangle){
   // your code to handle response or delayed result
}
solveRect(2,4,fn)
</code>```

Body:
Considering the following code:

rectangle.js:

module.exports = (x,y,callback) => {
    if (x <= 0 || y <= 0)
        setTimeout(() =>
            callback(new Error("Rectangle dimensions should be greater than zero: l = "
                + x + ", and b = " + y),
            null),
            2000);
    else
        setTimeout(() =>
            callback(null, {
                perimeter: () => (2*(x+y)),
                area:() => (x*y)
            }),
            2000);
}

index.js:

var rect = require('./rectangle');

function solveRect(l,b) {
    console.log("Solving for rectangle with l = "
                + l + " and b = " + b);
    rect(l,b, (err,rectangle) => {
        if (err) {
            console.log("ERROR: ", err.message);
        }
        else {
            console.log("The area of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.area());
            console.log("The perimeter of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.perimeter());
        }
    });
    console.log("This statement after the call to rect()");
};

solveRect(2,4);
solveRect(3,5);
solveRect(0,5);
solveRect(-3,5);

In this line rect(l,b, (err,rectangle) we call the rect function and pass l,b, err,rectangle to it. I can see what are l,b but can't see and understand what are err, rectangle ?

Also can't understand where is the definition of callback function? Is it an inner function?

Body:
Callback is nothing but the concept of passing a function as a parameter in function call like solveRect(2,4, fn). Here fn is going to be a function.

You can define it inline:

solveRect(2,4, function(err,rectangle){
   // your code to handle response or delayed result
});

Or as named function:

let fn = function(err,rectangle){
   // your code to handle response or delayed result
}
solveRect(2,4,fn)


问:
pandas: Apply operation to all columns without applymap?
I’m trying to figure out if it’s possible to achieve the following without using apply and without using a for loop.

```<code>df= [df[x].map(lambda x: len(x) > 5) for x in df.columns]
</code>```

I’m specifically trying to avoid apply and applymap, and look for a vectorised solution. All values in DF are strings. I’m using the above as a mask later on.

The fastest I've found is:

```<code>df1 = [df[x].map(lambda x: len(x) > 5) for x in df.columns]
df2 = df[pd.concat(df1, axis=1, keys=[s.name for s in df1]).any(1)]
</code>```

It's faster than:

```<code>df[(df.applymap(len) > 5).any(axis=1)]
</code>```

答:
How about vectorize, at least it should be slightly faster than apply , about the comparision of for loop , it all depends on your data size and shape . Link, Link

```<code>np.vectorize(len)(df.values)>5
</code>```

Body:
I’m trying to figure out if it’s possible to achieve the following without using apply and without using a for loop.

df= [df[x].map(lambda x: len(x) > 5) for x in df.columns]

I’m specifically trying to avoid apply and applymap, and look for a vectorised solution. All values in DF are strings. I’m using the above as a mask later on.

The fastest I've found is:

df1 = [df[x].map(lambda x: len(x) > 5) for x in df.columns]
df2 = df[pd.concat(df1, axis=1, keys=[s.name for s in df1]).any(1)]

It's faster than:

df[(df.applymap(len) > 5).any(axis=1)]

Body:
How about vectorize, at least it should be slightly faster than apply , about the comparision of for loop , it all depends on your data size and shape . Link, Link

np.vectorize(len)(df.values)>5


问:
how to write function to get value through 2 data frames using iteration in python
I got two data frames, A of length 2173 and B of length 6135.
A is called 'file_name', B is called 'crsp_name'

A.head()
                    file_name
0                       3M CO
1         ABBOTT LABORATORIES
2                     ABC INC
3            ALTRIA GROUP INC
4  AMERICAN ELECTRIC POWER CO
B.head()
0      A & E PLASTIK PAK INC
1    A & M FOOD SERVICES INC
2                 A A I CORP
3          A A IMPORTING INC
4                 A A R CORP
Name: comnam, dtype: object
```

<p>I was trying to compute the fuzz.token_set_ratio of every element in A with B and combine them as one data frame.For example, compute the ratio of "3M CO" with every element in B, and combine "3M" and the largest ratio as one row in a data frame. in this way, I was expected to get a data frame of shape(2173,2)</p>

<p>Here is my function, I try to use 'apply' and my 'fuzzratio' function to compute the desired ratio. But there was an error, hope someone can provide me a right solution.</p>

<pre class="lang-py prettyprint-override"><code>def fuzzratio(x):
    global crsp_name
    ratio_list = list()
    name_list = list()
    for i in crsp_name:
        ratio = fuzz.token_set_ratio(x,i)
        if ratio > 80:
            name_list.append(x)
            ratio_list.append(ratio)
    name_list = pd.DataFrame(name_list)
    result = pd.merge(name_list,ratio_list).rename(columns = {'comnam','ratio'})
    return result

file_name.apply(fuzzratio)
</code>```

error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 6004, in apply
    return op.get_result()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/apply.py", line 318, in get_result
    return super(FrameRowApply, self).get_result()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/apply.py", line 142, in get_result
    return self.apply_standard()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/apply.py", line 248, in apply_standard
    self.apply_series_generator()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/apply.py", line 277, in apply_series_generator
    results[i] = self.f(v)
  File "<stdin>", line 11, in fuzzratio
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 60, in merge
    validate=validate)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 526, in __init__
    'type {right}'.format(right=type(right)))
ValueError: ("can not merge DataFrame with instance of type <class 'list'>", 'occurred at index file_name')
```

答:
I created test data the following way:

```<code>dat_A="""file_name
3M CO
ABBOTT LABORATORIES
ABC INC
ALTRIA GROUP INC
AMERICAN ELECTRIC POWER CO"""

dat_B="""crsp_name
A & E PLASTIK PAK INC
A & M FOOD SERVICES INC
A A I CORP
A A IMPORTING INC
A A R CORP
ABBOTT
ABBOTT LABS
ALTRIA
ALTRIA GROUP"""

df_A = pd.read_csv(pd.compat.StringIO(dat_A))
df_B = pd.read_csv(pd.compat.StringIO(dat_B))
</code>```

Because from df_B there is used only crsp_name column, for efficiency
reason I extracted it into crsp variable:

```<code>crsp = df_B.crsp_name
</code>```

For easier manipulation with the ratio threshold, I saved it as another variable:

```<code>ratio_threshold = 50
</code>```

For test purpose I took a lower value in order to get any "non-empty"
results, but for your data set it back at 80 (the value which you defined).

Then we define the function to be applied soon:

```<code>def fn(t1):
    ratios = crsp.apply(lambda t2: fuzz.token_set_ratio(t1, t2))
    iMax = ratios.idxmax()
    rMax = ratios[iMax]
    return crsp.loc[iMax] if rMax > ratio_threshold else f'{iMax}_{rMax}'
</code>```

This function will be applied to each string from df_A.file_name,
so t1 is the current value (file_name).

The function starts from computing token set ratios between the current
file_name and each crsp_name (saved in ratios).

Then iMax is computed as the index of max ratio and rMax - the
max ratio itself.

If the max ratio is above our threshold, the function returns
the respective crsp_name.

Otherwise the function returns a "diagnostic message" - x_y (2 numbers)
where x is the index where the max ratio has been found and
y - the ratio itself. In the final version of the program change
it to either np.nan or an empty string.

And the only thing to do is to apply this function and add the result
as a new column to df_A:

```<code>df_A['crsp_name'] = df_A.file_name.apply(fn)
</code>```

For the above test data (and the threshold == 50) I got:

```<code>                    file_name              crsp_name
0                       3M CO                   2_46
1         ABBOTT LABORATORIES                 ABBOTT
2                     ABC INC  A & E PLASTIK PAK INC
3            ALTRIA GROUP INC                 ALTRIA
4  AMERICAN ELECTRIC POWER CO                   1_43
</code>```

As you can see, there are still 2 cases where no position
in crsp_name gave ratio over 50, but the reason is that
source data is very limited.

Second solution

When the task is to find a match against a list of candidates,
a better (quicker) solution is to use process.extractOne.

As it takes a list as the second argument, I extracted values
from crsp into another variable:

```<code>crspVals = crsp.values
</code>```

The function to match (returning only the best match) is:

```<code>def fn3(t1):
    res = process.extractOne(t1, crspVals, scorer=fuzz.token_set_ratio,
        score_cutoff=ratio_threshold)
    return res[0] if res else ''
</code>```

process.extractOne returns a tuple (best match, ratio), but if
no match above the threshold has been found, the result is None,
so I decided to give up the best ratio below the threshold, and return
only the best match or an empty string.

To apply this function, run:

```<code>df_A['crsp_name'] = df_A.file_name.apply(fn3)
</code>```

Compared to the first solution (modified to return only crsp_name)
it runs almost 2 times quicker.

Body:
I got two data frames, A of length 2173 and B of length 6135.
A is called 'file_name', B is called 'crsp_name'

A.head()
                    file_name
0                       3M CO
1         ABBOTT LABORATORIES
2                     ABC INC
3            ALTRIA GROUP INC
4  AMERICAN ELECTRIC POWER CO
B.head()
0      A & E PLASTIK PAK INC
1    A & M FOOD SERVICES INC
2                 A A I CORP
3          A A IMPORTING INC
4                 A A R CORP
Name: comnam, dtype: object

I was trying to compute the fuzz.token_set_ratio of every element in A with B and combine them as one data frame.For example, compute the ratio of "3M CO" with every element in B, and combine "3M" and the largest ratio as one row in a data frame. in this way, I was expected to get a data frame of shape(2173,2)

Here is my function, I try to use 'apply' and my 'fuzzratio' function to compute the desired ratio. But there was an error, hope someone can provide me a right solution.

def fuzzratio(x):
    global crsp_name
    ratio_list = list()
    name_list = list()
    for i in crsp_name:
        ratio = fuzz.token_set_ratio(x,i)
        if ratio > 80:
            name_list.append(x)
            ratio_list.append(ratio)
    name_list = pd.DataFrame(name_list)
    result = pd.merge(name_list,ratio_list).rename(columns = {'comnam','ratio'})
    return result

file_name.apply(fuzzratio)

error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/frame.py", line 6004, in apply
    return op.get_result()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/apply.py", line 318, in get_result
    return super(FrameRowApply, self).get_result()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/apply.py", line 142, in get_result
    return self.apply_standard()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/apply.py", line 248, in apply_standard
    self.apply_series_generator()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/apply.py", line 277, in apply_series_generator
    results[i] = self.f(v)
  File "<stdin>", line 11, in fuzzratio
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 60, in merge
    validate=validate)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 526, in __init__
    'type {right}'.format(right=type(right)))
ValueError: ("can not merge DataFrame with instance of type <class 'list'>", 'occurred at index file_name')

Body:
I created test data the following way:

dat_A="""file_name
3M CO
ABBOTT LABORATORIES
ABC INC
ALTRIA GROUP INC
AMERICAN ELECTRIC POWER CO"""

dat_B="""crsp_name
A & E PLASTIK PAK INC
A & M FOOD SERVICES INC
A A I CORP
A A IMPORTING INC
A A R CORP
ABBOTT
ABBOTT LABS
ALTRIA
ALTRIA GROUP"""

df_A = pd.read_csv(pd.compat.StringIO(dat_A))
df_B = pd.read_csv(pd.compat.StringIO(dat_B))

Because from df_B there is used only crsp_name column, for efficiency
reason I extracted it into crsp variable:

crsp = df_B.crsp_name

For easier manipulation with the ratio threshold, I saved it as another variable:

ratio_threshold = 50

For test purpose I took a lower value in order to get any "non-empty"
results, but for your data set it back at 80 (the value which you defined).

Then we define the function to be applied soon:

def fn(t1):
    ratios = crsp.apply(lambda t2: fuzz.token_set_ratio(t1, t2))
    iMax = ratios.idxmax()
    rMax = ratios[iMax]
    return crsp.loc[iMax] if rMax > ratio_threshold else f'{iMax}_{rMax}'

This function will be applied to each string from df_A.file_name,
so t1 is the current value (file_name).

The function starts from computing token set ratios between the current
file_name and each crsp_name (saved in ratios).

Then iMax is computed as the index of max ratio and rMax - the
max ratio itself.

If the max ratio is above our threshold, the function returns
the respective crsp_name.

Otherwise the function returns a "diagnostic message" - x_y (2 numbers)
where x is the index where the max ratio has been found and
y - the ratio itself. In the final version of the program change
it to either np.nan or an empty string.

And the only thing to do is to apply this function and add the result
as a new column to df_A:

df_A['crsp_name'] = df_A.file_name.apply(fn)

For the above test data (and the threshold == 50) I got:

                    file_name              crsp_name
0                       3M CO                   2_46
1         ABBOTT LABORATORIES                 ABBOTT
2                     ABC INC  A & E PLASTIK PAK INC
3            ALTRIA GROUP INC                 ALTRIA
4  AMERICAN ELECTRIC POWER CO                   1_43

As you can see, there are still 2 cases where no position
in crsp_name gave ratio over 50, but the reason is that
source data is very limited.

Second solution

When the task is to find a match against a list of candidates,
a better (quicker) solution is to use process.extractOne.

As it takes a list as the second argument, I extracted values
from crsp into another variable:

crspVals = crsp.values

The function to match (returning only the best match) is:

def fn3(t1):
    res = process.extractOne(t1, crspVals, scorer=fuzz.token_set_ratio,
        score_cutoff=ratio_threshold)
    return res[0] if res else ''

process.extractOne returns a tuple (best match, ratio), but if
no match above the threshold has been found, the result is None,
so I decided to give up the best ratio below the threshold, and return
only the best match or an empty string.

To apply this function, run:

df_A['crsp_name'] = df_A.file_name.apply(fn3)

Compared to the first solution (modified to return only crsp_name)
it runs almost 2 times quicker.


问:
Last Executed Query through Application in HANA
I am looking for the last executed query and time taken in SAP HANA from an application. I know that we have something like SYS.M_SQL_PLAN_CACHE which will give the queries executed directly in HANA, but I am looking for those executed through some Java application. Is it possible?

答:
You should enable user-specific trace for the user with which you connect your Java-app to HANA.

Starting with SAP HANA 2.0 SPS 03 it is possible to restrict traced statements by user and/or by connection ID along with statements hash.

Here are the examples how to enable trace by different criteria:

```<code>-- to enable traces
ALTER SYSTEM ALTER CONFIGURATION ('global.ini','SYSTEM')
SET
('traceprofile_<context>','application_user') = '<application user>',
('traceprofile_<context>','sql_user') = '<database user>',
('traceprofile_<context>','connection_id') = '<connection id>',
('traceprofile_<context>','statement_hash') = '<statement_hash of DB>',
('traceprofile_<context>', '<component1>') = '<trace level>',
('traceprofile_<context>', '<component2>') = '<trace level>'
with reconfigure;

-- to disable traces
ALTER SYSTEM ALTER CONFIGURATION ('global.ini','SYSTEM')
UNSET ('traceprofile_<context>') with reconfigure;
</code>```

Traces are stored in /usr/sap/{SID}/{HDB_instance}/{host}/trace, read more in this blog

Body:
You should enable user-specific trace for the user with which you connect your Java-app to HANA.

Starting with SAP HANA 2.0 SPS 03 it is possible to restrict traced statements by user and/or by connection ID along with statements hash.

Here are the examples how to enable trace by different criteria:

-- to enable traces
ALTER SYSTEM ALTER CONFIGURATION ('global.ini','SYSTEM')
SET
('traceprofile_<context>','application_user') = '<application user>',
('traceprofile_<context>','sql_user') = '<database user>',
('traceprofile_<context>','connection_id') = '<connection id>',
('traceprofile_<context>','statement_hash') = '<statement_hash of DB>',
('traceprofile_<context>', '<component1>') = '<trace level>',
('traceprofile_<context>', '<component2>') = '<trace level>'
with reconfigure;

-- to disable traces
ALTER SYSTEM ALTER CONFIGURATION ('global.ini','SYSTEM')
UNSET ('traceprofile_<context>') with reconfigure;

Traces are stored in /usr/sap/{SID}/{HDB_instance}/{host}/trace, read more in this blog


问:
Gridlines for a table not showing in mail when using Kable for CSS
I am trying to send a mail via mailR and it is working fine. I have a Data Frame and I wanted to colour code specific cells. I used Kable() to format and I got the desired output and it is showing the way it should in Rstudio viewer. But while sending that HTML in the mail, the gridlines are not visible.

I've tried adding 'bordered' in kable_styling()

```<code>#color coding for a data frame
library(knitr)
library(kableExtra)

library(dplyr)

a<-mtcars[1:10, 1:2] %>%
        mutate(
                car = row.names(.),
                mpg = cell_spec(mpg, "html", color = ifelse(mpg > 20,                     "red", "blue")),
                cyl = cell_spec(cyl, "html", color = "white", align = "c", angle = 45,
                                background = factor(cyl, c(4, 6, 8),
                                                    c("#666666",     "#999999", "#BBBBBB")))
        ) %>%
        select(car, mpg, cyl) %>%
        kable(format = "html", escape = F) %>%
        kable_styling(c("striped","bordered"), full_width = F)

#=================Send Email
library(mailR)
body_B <- paste("<p>
                ",a,"
                <br> Note: report

                <p>",sep="")

Subject <- paste(Sys.Date(), 'xyz',sep= ":")

send.mail(from = "asdf@gmail.com",
          to = c("asdf@gmail.com"),
          subject = Subject,
          body = body_B,
          html = TRUE,
          smtp = list(host.name = "smtp.gmail.com", port = 587,
                      user.name = "#####",
                      passwd = "#####", ssl = T),
          authenticate = T,
          #attach.files = raw_data,
          send = TRUE)
</code>```

答:
When you print a, you're using the print.kableExtra method, but body_B doesn't have the kableExtra class, so you'll just use the default methods producing the body for your message.  If you read the source to kableExtra:::print.kableExtra, you'll see it really does quite a bit of manipulation before sending the object to the browser, so you'll need to duplicate that.

Here's an attempt at that.  This might not be the simplest way to do it, but this produces a file that displays properly:

```<code># Generate an HTML header
html_header <- htmltools::tags$head(rmarkdown::html_dependency_jquery(),
                                    rmarkdown::html_dependency_bootstrap(theme = "simplex"),
                                    html_dependency_kePrint())
# Declare body_B to be HTML
html_table <- htmltools::HTML(body_B)

# Glue the two parts together
html_result <- htmltools::tagList(html_header, html_table)

# Create a temp file and write the result there
html_file <- tempfile(fileext = ".html")
htmltools::save_html(html_result, file = html_file, background = "white")

# That will require several different files.  You probably want to
# merge them all into one to display.  Pandoc can do that...
system(paste(rmarkdown::pandoc_exec(), "--self-contained --template", html_file, "-o", html_file, "</dev/null"))

# The result is now in the file named in html_file.  If you want it as
# a character variable, you can read it.
html_lines <- readLines(html_file)
</code>```

I haven't tried putting this in an email, but I don't see why it wouldn't work.

Body:
I am trying to send a mail via mailR and it is working fine. I have a Data Frame and I wanted to colour code specific cells. I used Kable() to format and I got the desired output and it is showing the way it should in Rstudio viewer. But while sending that HTML in the mail, the gridlines are not visible.

I've tried adding 'bordered' in kable_styling()

#color coding for a data frame
library(knitr)
library(kableExtra)

library(dplyr)

a<-mtcars[1:10, 1:2] %>%
        mutate(
                car = row.names(.),
                mpg = cell_spec(mpg, "html", color = ifelse(mpg > 20,                     "red", "blue")),
                cyl = cell_spec(cyl, "html", color = "white", align = "c", angle = 45,
                                background = factor(cyl, c(4, 6, 8),
                                                    c("#666666",     "#999999", "#BBBBBB")))
        ) %>%
        select(car, mpg, cyl) %>%
        kable(format = "html", escape = F) %>%
        kable_styling(c("striped","bordered"), full_width = F)

#=================Send Email
library(mailR)
body_B <- paste("

                ",a,"

 Note: report

",sep="")

Subject <- paste(Sys.Date(), 'xyz',sep= ":")

send.mail(from = "asdf@gmail.com",
          to = c("asdf@gmail.com"),
          subject = Subject,
          body = body_B,
          html = TRUE,
          smtp = list(host.name = "smtp.gmail.com", port = 587,
                      user.name = "#####",
                      passwd = "#####", ssl = T),
          authenticate = T,
          #attach.files = raw_data,
          send = TRUE)

Body:
When you print a, you're using the print.kableExtra method, but body_B doesn't have the kableExtra class, so you'll just use the default methods producing the body for your message.  If you read the source to kableExtra:::print.kableExtra, you'll see it really does quite a bit of manipulation before sending the object to the browser, so you'll need to duplicate that.

Here's an attempt at that.  This might not be the simplest way to do it, but this produces a file that displays properly:

# Generate an HTML header
html_header <- htmltools::tags$head(rmarkdown::html_dependency_jquery(),
                                    rmarkdown::html_dependency_bootstrap(theme = "simplex"),
                                    html_dependency_kePrint())
# Declare body_B to be HTML
html_table <- htmltools::HTML(body_B)

# Glue the two parts together
html_result <- htmltools::tagList(html_header, html_table)

# Create a temp file and write the result there
html_file <- tempfile(fileext = ".html")
htmltools::save_html(html_result, file = html_file, background = "white")

# That will require several different files.  You probably want to
# merge them all into one to display.  Pandoc can do that...
system(paste(rmarkdown::pandoc_exec(), "--self-contained --template", html_file, "-o", html_file, "</dev/null"))

# The result is now in the file named in html_file.  If you want it as
# a character variable, you can read it.
html_lines <- readLines(html_file)

I haven't tried putting this in an email, but I don't see why it wouldn't work.


问:
Implementation of Shortest Path Graph in Python Class

Hi! I am new to Python and I am struggling for many hours so far with some problem regarding Shortest Path Algorithm implementation in Python.

I am expected to solve some task about finding shortest paths (graph problem) among given persons, and at the end find a common person who connects all of them.

I've made something like this so far:

```<code>import itertools

class centralperson():

def initialization(self,N,data,a,b,c):
    self.data = data
    self.N = N
    self.a = a
    self.b = b
    self.c = c
    self.list_of_values = [self.a,self.b,self.c]
    self.list_of_paths = []
    self.common_person = []

def makeGraph(self):

    # Create dict with empty list for each key
    graph = {key: [] for key in range(self.N)}
    self.graph = graph

    for key in self.graph:
        for x in self.data:
            if key in x:

                x = x.copy()
                x.remove(key)
                self.graph[key].extend(x)

def find_path(self,start, end):
    path = []
    path = path + [start]
    if start == end:
        return path
    if start not in self.graph.keys():
        raise ValueError('No such key in graph!')
    for node in self.graph[start]:
        if node not in path:
            newpath = self.find_path(self.graph, node, end, path)
            if newpath: return newpath
    return self.list_of_paths.append(path)

def findPaths(self):

    for pair in itertools.combinations(self.list_of_values, r=5):
        self.find_path(*pair)

def commonperson(self):

    list_of_lens = {}
    commonalities = set(self.list_of_paths[0]) & set(self.list_of_paths[1]) & set(self.list_of_paths[2])
    for i in self.list_of_values:
        list_of_lens[i] = (len(self.graph[i]))

    if len(commonalities)>1 or len(commonalities)<1:
        for k,v in list_of_lens.items():
            if v==1 and self.graph[k][0] in commonalities:
                output = self.graph[k]
                self.common_person.append(output)
    else:
        output = list(commonalities)
        self.common_person.append(output)
    return

def printo(self):

    #return(self.common_person[0])
    return(self.list_of_paths,self.list_of_values)
</code>```

Description of each function and inputs:

N -> number of unique nodes

a,b,c -> some arbitrarily chosen nodes to find common one among them

initialization -> just initialize our global variables used in other methods, and store the list of outputs

makeGraph -> makes an Adjacency List out of an input.

find_path -> find path between two given nodes (backtracking recursion)

findPaths -> it was expected to call find_path here for every combination of A,B,C i.e A->B, A->C, B->C

commonperson -> expected to find common person from the output of list_of_paths list

printo -> print this common person

Generally It works (I'think) when I'am running each function separately. But, when I try to make a huge class of it, it doesn't work :(

I think the problem is with this recursive function find_path. It is supposed to find a path between two person given, and append the result path to the list with all paths. Yet, as I have 3 different persons, and find_path is a recursive function with only 2 parameters.

Hence, I need to find all paths that connects them (3 paths) and append it to a bigger list list_of_paths. I've created a def findPaths to make use of itertools.combinations and in for loop cal function find_path for every combination of start and end argument of this function, but it seems not to work...

Can you help me with this? Also I don't know how to run all the def functions at once, because honestly I wouldn't like to run all instances of the class separately... My desired version is to:

Provide Input to a class i.e : N,data,a,b,c where N is number of unique nodes, data is just list of list with networks assigned, and A,B,C are my persons.

Get Output: which is a common person for all this 3 persons, (I planned to store it in common_person list.

答:
itertools.combinations(self.list_of_values, r=5)
```

<p>returns an empty list, since <code>self.list_of_values</code> only has 3 elements, from which you cannot pick 5. </p>

<p>Perhaps you meant:</p>

<pre class="lang-py prettyprint-override"><code>itertools.combinations(self.list_of_values, r=2)
</code>```

Body:
Hi! I am new to Python and I am struggling for many hours so far with some problem regarding Shortest Path Algorithm implementation in Python.

I am expected to solve some task about finding shortest paths (graph problem) among given persons, and at the end find a common person who connects all of them.

I've made something like this so far:

import itertools

class centralperson():

def initialization(self,N,data,a,b,c):
    self.data = data
    self.N = N
    self.a = a
    self.b = b
    self.c = c
    self.list_of_values = [self.a,self.b,self.c]
    self.list_of_paths = []
    self.common_person = []

def makeGraph(self):

    # Create dict with empty list for each key
    graph = {key: [] for key in range(self.N)}
    self.graph = graph

    for key in self.graph:
        for x in self.data:
            if key in x:

                x = x.copy()
                x.remove(key)
                self.graph[key].extend(x)

def find_path(self,start, end):
    path = []
    path = path + [start]
    if start == end:
        return path
    if start not in self.graph.keys():
        raise ValueError('No such key in graph!')
    for node in self.graph[start]:
        if node not in path:
            newpath = self.find_path(self.graph, node, end, path)
            if newpath: return newpath
    return self.list_of_paths.append(path)

def findPaths(self):

    for pair in itertools.combinations(self.list_of_values, r=5):
        self.find_path(*pair)

def commonperson(self):

    list_of_lens = {}
    commonalities = set(self.list_of_paths[0]) & set(self.list_of_paths[1]) & set(self.list_of_paths[2])
    for i in self.list_of_values:
        list_of_lens[i] = (len(self.graph[i]))

    if len(commonalities)>1 or len(commonalities)<1:
        for k,v in list_of_lens.items():
            if v==1 and self.graph[k][0] in commonalities:
                output = self.graph[k]
                self.common_person.append(output)
    else:
        output = list(commonalities)
        self.common_person.append(output)
    return

def printo(self):

    #return(self.common_person[0])
    return(self.list_of_paths,self.list_of_values)

Description of each function and inputs:

N -> number of unique nodes

a,b,c -> some arbitrarily chosen nodes to find common one among them

initialization -> just initialize our global variables used in other methods, and store the list of outputs

makeGraph -> makes an Adjacency List out of an input.

find_path -> find path between two given nodes (backtracking recursion)

findPaths -> it was expected to call find_path here for every combination of A,B,C i.e A->B, A->C, B->C

commonperson -> expected to find common person from the output of list_of_paths list

printo -> print this common person

Generally It works (I'think) when I'am running each function separately. But, when I try to make a huge class of it, it doesn't work :(

I think the problem is with this recursive function find_path. It is supposed to find a path between two person given, and append the result path to the list with all paths. Yet, as I have 3 different persons, and find_path is a recursive function with only 2 parameters.

Hence, I need to find all paths that connects them (3 paths) and append it to a bigger list list_of_paths. I've created a def findPaths to make use of itertools.combinations and in for loop cal function find_path for every combination of start and end argument of this function, but it seems not to work...

Can you help me with this? Also I don't know how to run all the def functions at once, because honestly I wouldn't like to run all instances of the class separately... My desired version is to:

Provide Input to a class i.e : N,data,a,b,c where N is number of unique nodes, data is just list of list with networks assigned, and A,B,C are my persons.

Get Output: which is a common person for all this 3 persons, (I planned to store it in common_person list.

Body:
itertools.combinations(self.list_of_values, r=5)

returns an empty list, since self.list_of_values only has 3 elements, from which you cannot pick 5.

Perhaps you meant:

itertools.combinations(self.list_of_values, r=2)


问:
Separation of Runtime and History
I whould like to use separate databases for runtime and history data without implementing a custom HistoryEventHandler. Does someone know how this is possible?

I read the camunda user guides but this did not help much because it only hints the custom implementation way.

Currently, everytime I query history data (about 2mil activity entries) the performance of the system drops as it kind of blocks the runtime, too. I'd like to avoid this without loosing the ability to query historic data.

答: That would be a really cool feature, but it is currently not supported. You will have to disable the default history and implement a custom handler.</p>

Title: Separation of Runtime and History


问:
Circle CI + Firebase "tslint: not found"
I'm trying to deploy to Firebase through CircleCI, but I keep getting the following error from Circle:

```<code>tslint: not found
</code>```

The Circle CI config file is here.

The firebase config file is here.

答:
are u trying to deploy your functions?

If so, notice you are installing everything into the root folder, not the functions folder.

I spent like 6 hours on the same issue once... ^^

Take a look at this scroll down to Create the cloud build configuration file notice the dir is functions instead of the root.

Changing your dir configuration on the circle file should do the trick

Body:
I'm trying to deploy to Firebase through CircleCI, but I keep getting the following error from Circle:

tslint: not found

The Circle CI config file is here.

The firebase config file is here.


问:
How Do I display current date and time in Toad for Oracle?
I have a sql statement that counts the units(cable boxes) that were refurbished (had damaged parts replaced) and total units(cable boxes that just went through refurb and had nothing replaced) and it's supposed to do this count regularly (every time a unit is processed the count). Can someone please help me? Thank you.

Justin

Heres my sql code so far:

SELECT COUNT(*)
FROM  cxadminn.repair_part

WHERE repair_type = 'REFURB' and created_date >?

答:
```<code>SELECT COUNT(*) FROM cxadminn.repair_part
WHERE repair_type = 'REFURB' and created_date > sysdate
</code>```

or

```<code>created_date > to_date('01.01.11 01:01:01', 'dd.mm.yyyy hh:mi:ss')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
SELECT COUNT(*) FROM cxadminn.repair_part
WHERE repair_type = 'REFURB' and created_date > sysdate

or

created_date > to_date('01.01.11 01:01:01', 'dd.mm.yyyy hh:mi:ss')


问:
De-selecting single Autofilter item using VBA is actually de-selecting ALL items
Fairly good with VBA but this code is failing. Trying to de-select a single item in an Autofilter field. Instead, it's deselecting all the items in that field. Can someone please tell me what I'm doing wrong? In the below snippet, I want the following:

Show all the #N/A values in Field 24

Show all the field values in Field 22 EXCEPT "Revenue"

Show all the field values in Field 8 EXCEPT blanks

But instead, fields 24 and 8 are deselecting all values and not filtering. I've tried adding a forced calculate but that's not doing anything either. Any advice?

Sub Macro1()

    With Sheets("Expense Data")
        .Activate
        On Error Resume Next
        .ShowAllData
        Range("A1").AutoFilter Field:=24, Criteria1:="#N/A"
        Range("A1").AutoFilter Field:=22, Criteria1:="<>Revenue"
        Range("A1").AutoFilter Field:=8, Criteria1:="<>(blanks)"
        .Calculate
    End With

End Sub
```

答:
Nevermind, I got it...

It's treated as a TEXT filter - so the "<>(blanks)" should just be "<>".

All fixed.


问:
Changed the version of python, but not reflected in pythonw
I am trying to change the version of python that I'm running.
When i do python -V, it says 3.6 but if i do pythonw -V it is still running 3.7.

For this application, I need to run pythonw.
Is there a way to roll this back to use 3.6 (using OSX)?

答:
You don't need to rollback anything.

Please take a look here.

There are several ways to define the version you want to run, from py launcher options to environment vars, ini settings, shebang lines, or even file type associations.


问:
Echo newline in Bash prints literal \n
How do I print a newline? This merely prints \n:

```<code>$ echo -e "Hello,\nWorld!"
Hello,\nWorld!
</code>```

答:
Simply type

```<code>echo
</code>```

to get a new line

Title: Echo newline in Bash prints literal \n

Body:
How do I print a newline? This merely prints \n:

$ echo -e "Hello,\nWorld!"
Hello,\nWorld!

Body:
Simply type

echo

to get a new line


问:
SparkUI not showing Tab (Jobs, Stages, Storage, Environment,...) when run in standalone mode
I'm running spark master through the following command:

./sbin/start-master.sh

After that I went to http://localhost:8080, and I saw the following page.

I was expecting to see the tab with Jobs, Environments, ... like the following

Could someone help me to understand where the problem is?

Do I need extra configuration?

Thanks

Giuseppe

答:
To monitor and inspect Spark job executions in a web browser access the port 4040 instead of 8080.

For example : http://ipAddress:4040

Replace 8080 in the URL.

Refer to : https://spark.apache.org/docs/latest/monitoring.html

In the above link, spark documentation states that it launches the web interface in port 4040

One more useful note is this information is only available for the duration of the application by default. To view the web UI after the fact, set spark.eventLog.enabled to true before starting the application. This configures Spark to log Spark events that encode the information displayed in the UI to persisted storage.

Hope that helps.


问:
Programmatically Create Aggregate Audio Devices In Swift Using CoreAudio
I am researching creating multi-output devices on either OS X or iOS, and I found out that CoreAudio would allow you to create aggregate devices.  My first question is, does iOS allow you to do this. I know that this is certainly possible on OS X, but I've heard that iOS will not allow it. I would really appreciate an example of how you would go about detecting multiple audio output devices and creating an aggregate device, all using swift.  I have checked here, but it doesn't fully answer my question, and the answer it does have is based on Objective-C.  I'd appreciate any help, and thanks in advance!</p>

答:
The aggregate audio device API is not publicly available on iOS, so you cannot create those devices yourself.

However iOS will create aggregate devices* for you depending on the most recently attached audio hardware and some other rules if you activate an AVAudioSession that uses the .multiRoute category.

When you get a route change notification due to an audio interface being added or removed, you can create a remote IO audio unit with the right number of channels. I haven’t tried using multi route audio with AVAudioEngine nor have I tried using only a subset of the available channels.

* They’re probably aggregate devices, although you never see them or interact with them directly.


问:
Recording audio on WatchOS over AVAudioRecorder
Is there any sample code or tutorials about that? I've found that AVAudioRecorder supported since WatchOS 4.0 https://developer.apple.com/documentation/avfoundation/avaudiorecorder. But when I am trying to use it - it records 1 second and no actual sound (just noise).

Here is my code:

```<code>let audioURL = self.getRecordedFileURL()
print(audioURL.absoluteString)

let settings = [
  AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
  AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]

do {
  recorder = try AVAudioRecorder(url: audioURL, settings: settings)
  recorder?.delegate = self
  recorder?.record()
} catch {
  finishRecording(success: false)
}
</code>```

Also, should I use AudioSession here? If yes, is it required requestRecordPermission and how do deal with it? Thank you for your help!

答:
This one works:

```<code>    let recordingName = "audio.m4a"
    let dirPath = getDirectory()
    let pathArray = [dirPath, recordingName]
    guard let filePath = URL(string: pathArray.joined(separator: "/")) else { return }

    let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                    AVSampleRateKey:12000,
                    AVNumberOfChannelsKey:1,
                    AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    //start recording
    do {
        audioRecorder = try AVAudioRecorder(url: filePath, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record()
    } catch {
        print("Recording Failed")
    }
func getDirectory()-> String {
    let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    return dirPath
}
</code>```

Don't forget to add NSMicrophoneUsageDescription into your phone companion app Info.plist.

Body:
Is there any sample code or tutorials about that? I've found that AVAudioRecorder supported since WatchOS 4.0 https://developer.apple.com/documentation/avfoundation/avaudiorecorder. But when I am trying to use it - it records 1 second and no actual sound (just noise).

Here is my code:

let audioURL = self.getRecordedFileURL()
print(audioURL.absoluteString)

let settings = [
  AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
  AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]

do {
  recorder = try AVAudioRecorder(url: audioURL, settings: settings)
  recorder?.delegate = self
  recorder?.record()
} catch {
  finishRecording(success: false)
}

Also, should I use AudioSession here? If yes, is it required requestRecordPermission and how do deal with it? Thank you for your help!

Body:
This one works:

    let recordingName = "audio.m4a"
    let dirPath = getDirectory()
    let pathArray = [dirPath, recordingName]
    guard let filePath = URL(string: pathArray.joined(separator: "/")) else { return }

    let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                    AVSampleRateKey:12000,
                    AVNumberOfChannelsKey:1,
                    AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    //start recording
    do {
        audioRecorder = try AVAudioRecorder(url: filePath, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record()
    } catch {
        print("Recording Failed")
    }
func getDirectory()-> String {
    let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    return dirPath
}

Don't forget to add NSMicrophoneUsageDescription into your phone companion app Info.plist.


问:
parseInt() - String to Integer and back in PHP
Im trying to reverse engineering some Javascript code and recode it in PHP.
There is a String which is "converted" with parseInt(String, 36) to an Integer.
I need a posibility to convert the integer back to the secret String in PHP, without knowing the secret string.

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510```
</div>
</div>
</p>

<p>How i can do that in PHP?
<code>115802171408044510</code> back to <code>0vo8fz4kvy03</code></p>

<p>This interger contains some informations:</p>

```decode="115802171408044510";
storeID = decode.substr(0, 4); // 1158
posID = decode.substr(12, 2); // 04
orderID = decode.substr(14, 2); // 45
day = decode.substr(6, 2); // 17
month = decode.substr(4, 2); // 02
hour = decode.substr(8, 2); // 14
minutes = decode.substr(10, 2); // 08
```

I would like to edit this values above and convert this back to a "secretCode" String.
They are doing exactly this somehow server-side.

答:
You could take BigInt and convert large values to decimal or back to string.

function convertFrom(value, radix) {
    return [...value.toString()]
        .reduce((r, v) => r * BigInt(radix) + BigInt(parseInt(v, radix)), 0n);
}

function convertTo(value, radix) {
    var result = '',
        r = BigInt(radix);

    do {
        result = (value % r).toString(36) + result;
        value = value / r;
    } while (value);
    return result;
}

var secretCode = "0vo8fz4kvy03",
    value = convertFrom(secretCode, 36),
    encode = convertTo(value, 36);

console.log(value.toString());
console.log(encode.toString());```

Body:
Im trying to reverse engineering some Javascript code and recode it in PHP.
There is a String which is "converted" with parseInt(String, 36) to an Integer.
I need a posibility to convert the integer back to the secret String in PHP, without knowing the secret string.

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510

How i can do that in PHP?
115802171408044510 back to 0vo8fz4kvy03

This interger contains some informations:

decode="115802171408044510";
storeID = decode.substr(0, 4); // 1158
posID = decode.substr(12, 2); // 04
orderID = decode.substr(14, 2); // 45
day = decode.substr(6, 2); // 17
month = decode.substr(4, 2); // 02
hour = decode.substr(8, 2); // 14
minutes = decode.substr(10, 2); // 08

I would like to edit this values above and convert this back to a "secretCode" String.
They are doing exactly this somehow server-side.


问:
Unable to add a source with url for private repo
When I want to install pods from private repo and run pod install, I'm getting a following error:

```<code>[!] Unable to add a source with url `https://bitbucket.org/mycompany/pods.git` named `bitbucket-some-pods`.
You can try adding it manually in `/Users/myusername/.cocoapods/repos` or via `pod repo add`.
</code>```

I've tried to pod setup, add it manually, renew SSH keys, tried to install having source urls inside of Podfile both as ssh and htmls. Nothing helped.

答:
The problem was that I had a few Git credentials stored on the system and they got mixed up somehow. I've found a credentials manager this way:

```<code>$ git config --system --list
</code>```

It's shown this: credential.helper=osxkeychain

So, I followed steps below:

Opened Keychain Access

Searched keys for github.com

Removed all found keys

Restarted the laptop

Done

Body:
When I want to install pods from private repo and run pod install, I'm getting a following error:

[!] Unable to add a source with url `https://bitbucket.org/mycompany/pods.git` named `bitbucket-some-pods`.
You can try adding it manually in `/Users/myusername/.cocoapods/repos` or via `pod repo add`.

I've tried to pod setup, add it manually, renew SSH keys, tried to install having source urls inside of Podfile both as ssh and htmls. Nothing helped.

Body:
The problem was that I had a few Git credentials stored on the system and they got mixed up somehow. I've found a credentials manager this way:

$ git config --system --list

It's shown this: credential.helper=osxkeychain

So, I followed steps below:

Opened Keychain Access

Searched keys for github.com

Removed all found keys

Restarted the laptop

Done


问:
Why can't I use var in this instance?
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

```<code>var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;
</code>```

Thanks to anyone who can tell me the correct method of making this work.

答:
Not sure if it will fix it but try this:</p>

```<code>var brandslist = (from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select new { brand_family.brand_family_name, priority, roll_image } );
</code>```

Title: Why can't I use var in this instance?

Body:
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;

Thanks to anyone who can tell me the correct method of making this work.

Body:
Not sure if it will fix it but try this:

var brandslist = (from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select new { brand_family.brand_family_name, priority, roll_image } );


问:
Flutter CircleAvatar backgroundImage not filling up the circle
I am using a CircleAvatar with a backgroundImage property to load an image took from a camera but the image shown does not fill the entire circle avatar. It looks like a rectangular image in a circle.

How do I make the image expand to cover the circle avatar? Thanks.

答:
This is my working example:</p>

```<code>Stack(
                fit: StackFit.expand,
                children: <Widget>[
                  CircleAvatar(
                    radius: 30.0,
                    backgroundImage:
                        NetworkImage("https://via.placeholder.com/150/92c952"),
                    backgroundColor: Colors.transparent,
                  ),
                  Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: Image.asset(
                      'assets/photo-camera.png',
                      width: 20.9,
                      height: 19.9,
                    ),
                  ),
                ],
              ))
</code>```

Body:
This is my working example:

Stack(
                fit: StackFit.expand,
                children: <Widget>[
                  CircleAvatar(
                    radius: 30.0,
                    backgroundImage:
                        NetworkImage("https://via.placeholder.com/150/92c952"),
                    backgroundColor: Colors.transparent,
                  ),
                  Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: Image.asset(
                      'assets/photo-camera.png',
                      width: 20.9,
                      height: 19.9,
                    ),
                  ),
                ],
              ))


问:
Why does JavaScript seem to return modulus inconsistently?
I'm learning JavaScript and I have a page that displays the result of dividing two user-inputted numbers.

I didn't like that (1 / 3) would fill the whole result box with 3.333333333333..., so I set the result with .toFixed(4). But this has the result of making (4 / 2) return 2.0000 instead of just 2.

So, in order to fix that I check if (answer % 1 == 0), in which case it displays the answer normally, then checks (answer % 0.1 == 0), which displays answer.toFixed(1), and so on, with the final else being .toFixed(4).

This works as intended for some numbers but not for others, and I don't see why or what's going wrong in the cases it doesn't work.

Examples:

(2 / 5) returns 0.4. This satisfies the second condition, (answer % 0.1 == 0), and returns answer.toFixed(1), displaying 0.4. Great.

(2 / 10) also works and displays 0.2, and something like (2 / 7) correctly gets pushed to the else and displays 0.2857.

(2 / 8) returns 0.25, then incorrectly displays 0.2500

(2 / 20) correctly returns and displays 0.1

(9 / 6) returns 1.5, then incorrectly displays 1.5000

(2 / 4) returns 0.5, but displays 0.5000. It failed all the conditions and jumps to the else sentence, so answer.toFixed(4) is used.

Why does JavaScript consider (0.4 % 0.1 == 0) to be true, but (0.5 % 0.1 == 0) to be false?

This is my current code:

```<code>let num1 = parseFloat($("calcInput1").value);
let num2 = parseFloat($("calcInput2").value);
answer = num1 / num2;

if (answer % 1 == 0) {
    document.getElementById("calcResult").value = answer;
    alert("answer % 1 == 0");
} else if (answer % 0.1 == 0) {
    document.getElementById("calcResult").value = answer.toFixed(1);
    alert("answer % 0.1 == 0");
} else if (answer % 0.01 == 0) {
    document.getElementById("calcResult").value = answer.toFixed(2);
    alert("answer % 0.01 == 0");
} else if (answer % 0.001 == 0) {
    document.getElementById("calcResult").value = answer.toFixed(3);
    alert("else");
} else {
    document.getElementById("calcResult").value = answer.toFixed(4);
}
</code>```

答:
I believe, that what you need to output can be achieved using:

```<code>var answer = +(num1 / num2).toFixed(4);
</code>```

Casting the string generated with toFixed() back to a number can help to avoid the redundant zeros at the end. Also, you don't need to use the modulus operator at all and do not need to face the problems related to arithmetics precision with floating point.

Note I have use the unary plus to cast the string back to number, as on the MDN says:

Unary plus is the fastest and preferred way of converting something into a number.

Example:

var button = document.getElementById("calc");
var in1 = document.getElementById("calcInput1");
var in2 = document.getElementById("calcInput2");
var out = document.getElementById("answer");

button.addEventListener("click", function()
{
    var num1 = in1.value, num2 = in2.value;
    var answer = +(num1 / num2).toFixed(4);
    out.value = answer;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="calcInput1">
<input type="text" id="calcInput2">
<button type="button" id="calc">Calc</button>
<input type="text" id="answer"></code>```

Body:
I'm learning JavaScript and I have a page that displays the result of dividing two user-inputted numbers.

I didn't like that (1 / 3) would fill the whole result box with 3.333333333333..., so I set the result with .toFixed(4). But this has the result of making (4 / 2) return 2.0000 instead of just 2.

So, in order to fix that I check if (answer % 1 == 0), in which case it displays the answer normally, then checks (answer % 0.1 == 0), which displays answer.toFixed(1), and so on, with the final else being .toFixed(4).

This works as intended for some numbers but not for others, and I don't see why or what's going wrong in the cases it doesn't work.

Examples:

(2 / 5) returns 0.4. This satisfies the second condition, (answer % 0.1 == 0), and returns answer.toFixed(1), displaying 0.4. Great.

(2 / 10) also works and displays 0.2, and something like (2 / 7) correctly gets pushed to the else and displays 0.2857.

(2 / 8) returns 0.25, then incorrectly displays 0.2500

(2 / 20) correctly returns and displays 0.1

(9 / 6) returns 1.5, then incorrectly displays 1.5000

(2 / 4) returns 0.5, but displays 0.5000. It failed all the conditions and jumps to the else sentence, so answer.toFixed(4) is used.

Why does JavaScript consider (0.4 % 0.1 == 0) to be true, but (0.5 % 0.1 == 0) to be false?

This is my current code:

let num1 = parseFloat($("calcInput1").value);
let num2 = parseFloat($("calcInput2").value);
answer = num1 / num2;

if (answer % 1 == 0) {
    document.getElementById("calcResult").value = answer;
    alert("answer % 1 == 0");
} else if (answer % 0.1 == 0) {
    document.getElementById("calcResult").value = answer.toFixed(1);
    alert("answer % 0.1 == 0");
} else if (answer % 0.01 == 0) {
    document.getElementById("calcResult").value = answer.toFixed(2);
    alert("answer % 0.01 == 0");
} else if (answer % 0.001 == 0) {
    document.getElementById("calcResult").value = answer.toFixed(3);
    alert("else");
} else {
    document.getElementById("calcResult").value = answer.toFixed(4);
}

Body:
I believe, that what you need to output can be achieved using:

var answer = +(num1 / num2).toFixed(4);

Casting the string generated with toFixed() back to a number can help to avoid the redundant zeros at the end. Also, you don't need to use the modulus operator at all and do not need to face the problems related to arithmetics precision with floating point.

Note I have use the unary plus to cast the string back to number, as on the MDN says:

Unary plus is the fastest and preferred way of converting something into a number.

Example:

var button = document.getElementById("calc");
var in1 = document.getElementById("calcInput1");
var in2 = document.getElementById("calcInput2");
var out = document.getElementById("answer");

button.addEventListener("click", function()
{
    var num1 = in1.value, num2 = in2.value;
    var answer = +(num1 / num2).toFixed(4);
    out.value = answer;
});

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

<input type="text" id="calcInput1">
<input type="text" id="calcInput2">
<button type="button" id="calc">Calc</button>
<input type="text" id="answer">


问:
I need to take off
 from data using react
I receive data from database like this :

```<code>description:<p>my name is ....</p>
</code>```

I put this in a table, all I need is to put the text only, how can I remove the

?

答:
You can explicitly replace the
 and
 tags only using the String.prototype.replace() JS string method, available as .replace(string, replacement) on any string in JavaScript. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

const description = '
my name is ....
';
const newDescription = description.replace('
', '').replace('
','');
console.log(newDescription);```

Title: I need to take off <p> from data using react

Body:
I receive data from database like this :

description:
my name is ....

I put this in a table, all I need is to put the text only, how can I remove the

?

Body:
You can explicitly replace the <p> and </p> tags only using the String.prototype.replace() JS string method, available as .replace(string, replacement) on any string in JavaScript. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

const description = '<p>my name is ....</p>';
const newDescription = description.replace('<p>', '').replace('</p>','');
console.log(newDescription);


问:
Creating a command with sprintf. Is this possible?
I want to plot some data. The data is in several files and the line it is in is not always the same. Therefore I used grep and some other commandline tools to extract the line I want. I read online, that it should be possible with gnuplot to print from a string or from the result of a commandline.

I work in linux.

```<code>set terminal pdfcairo enhanced font "Garamond,10" fontscale 1.0 size 9in,9in

set nogrid
set samples 1001
set border 31 linewidth .3
set output "access/accessTimeAcrossFreq.pdf"
set xlabel "freq"
set ylabel "Time [s]"
set key right top
set size square
set autoscale y
set termoption lw 2.5

volts = "0.8"
fins = "111 122 222"
freq = "0.5G 1G 1.5G 2G 2.5G 3G"

metrics = "read1bldeltav read0bldeltav read1senseChange read0senseChange read1latchChange read0latchChange sense1speed sense0speed write1CellFlip write0CellFLip write1CellSwing write0CellSwing write1BLSwing write0BLSwing powerpertime"

runTitle = "abetraryString"
filename(fin, f, volt) = sprintf("../%s_temp27_fin%s_freq%s_vdd%s/accessTimeVolLSA/result.txt", runTitle, fin, f, volt)

data(met, file) = system(sprintf("grep -n '%s' %s | cut -d: -f 2 | awk '{$1=$1};1'", met, file))
com(met, file) = sprintf("< grep -n '%s' %s | cut -d: -f 2 | awk '{$1=$1};1'", met, file)

do for [fin in fins] {
    do for [v in volts] {
        do for [met in metrics] {
            set title sprintf("%s VLSA across Freq, fins %s, %sV, w/o she", met, fin, v)
            plot for[i=1:words(freq)] com(met, filename(fin, word(freq, i), v)) using (i):2:xtic(word(freq, i))  notitle with points lc i
        }
    }
}
</code>```

So I was wondering if a) I can have a function that returns a string that is a command that is then run by gnuplot
b) Where the error might come from:

```<code>line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: x range is invalid
</code>```

I thought, maybe I need a linebreak at the end of my one-liner of data. Or because gnuplot always thinks the first line is not data... I don't know.

答:
Today I figured it out. I used prints in the for loop to see what the command returns. Before I posted the question I tried the command in a separate terminal with success. The problem was I just tested it with the first element of metrics. The prints revealed that I forgot the metrics need to be all lower case.

To conclude. Yes, you can put a string via a function together and gnuplot will then run it as I was expecting it. See the use of com(..) in the plot line.

Second. I think the xrange error usually points out that in a plot there are no data points and gnuplot does not like a xrange of 0. To figure this out I used prints. I did a quick search if there is a verbose mode but was not successful, so prints it is.

Maybe someone can take away something like I did.

Body:
I want to plot some data. The data is in several files and the line it is in is not always the same. Therefore I used grep and some other commandline tools to extract the line I want. I read online, that it should be possible with gnuplot to print from a string or from the result of a commandline.

I work in linux.

set terminal pdfcairo enhanced font "Garamond,10" fontscale 1.0 size 9in,9in

set nogrid
set samples 1001
set border 31 linewidth .3
set output "access/accessTimeAcrossFreq.pdf"
set xlabel "freq"
set ylabel "Time [s]"
set key right top
set size square
set autoscale y
set termoption lw 2.5

volts = "0.8"
fins = "111 122 222"
freq = "0.5G 1G 1.5G 2G 2.5G 3G"

metrics = "read1bldeltav read0bldeltav read1senseChange read0senseChange read1latchChange read0latchChange sense1speed sense0speed write1CellFlip write0CellFLip write1CellSwing write0CellSwing write1BLSwing write0BLSwing powerpertime"

runTitle = "abetraryString"
filename(fin, f, volt) = sprintf("../%s_temp27_fin%s_freq%s_vdd%s/accessTimeVolLSA/result.txt", runTitle, fin, f, volt)

data(met, file) = system(sprintf("grep -n '%s' %s | cut -d: -f 2 | awk '{$1=$1};1'", met, file))
com(met, file) = sprintf("< grep -n '%s' %s | cut -d: -f 2 | awk '{$1=$1};1'", met, file)

do for [fin in fins] {
    do for [v in volts] {
        do for [met in metrics] {
            set title sprintf("%s VLSA across Freq, fins %s, %sV, w/o she", met, fin, v)
            plot for[i=1:words(freq)] com(met, filename(fin, word(freq, i), v)) using (i):2:xtic(word(freq, i))  notitle with points lc i
        }
    }
}

So I was wondering if a) I can have a function that returns a string that is a command that is then run by gnuplot
b) Where the error might come from:

line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: warning: Skipping data file with no valid points
line 32: x range is invalid

I thought, maybe I need a linebreak at the end of my one-liner of data. Or because gnuplot always thinks the first line is not data... I don't know.


问:
XPath wildcards and contains() function usage
I have a problem using XPath and contains function. Imagine the XML example below:

```<code>   <doc>
     <Test>
       <Name>1 Pre Histoy</Name>
       <Type>Known</Type>
       <Data>
          <Name>Dinasor</Name>
          <Name>Fish</Name>
      </Data>
      </Test>

      <Test>
        <Name>1 Post Histoy</Name>
        <Type>Known</Type>
        <Data>
          <Name>Human</Name>
          <Name>Dog</Name>
        </Data>
     </Test>

      <Test>
        <Name>1 Post Histoy</Name>
        <Type>UNKNOWN</Type>
        <Data>
          <Name>Human</Name>
          <Name>Dog</Name>
        </Data>
     </Test>

  </doc>
</code>```

So what I want to do is returning all <Name> texts within <Data> node, with following criteria:

doc//Test/Name should contain "Pre" text

doc//Test/Type should be "Known"

What I need is a query like this but so far I couldn't manage it

```<code>/doc//Test[Name contains(.,'Pre') and Type='Known']/data//Name
</code>```

Any help and tips will be appreciated.

答:
Try this:

```<code>/doc/Test[contains(Name, "Pre") and Type="Known"]/Data/Name
</code>```

Here is a working example implemented in Javascript to take advantage of StackOverflow's Runnable Code Snippets

function fu(path){
  var output = "";
  var results =  document.evaluate(path, document, null, XPathResult.ANY_TYPE  , null);
  while(nextResult = results.iterateNext()){ output += nextResult.outerHTML + "\n"; }
  return output;
}

document.body.innerText = fu('//doc/Test[contains(Name, "Pre") and Type="Known"]/Data/Name');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><doc>
 <Test>
   <Name>1 Pre Histoy</Name>
   <Type>Known</Type>
   <Data>
      <Name>Dinasor</Name>
      <Name>Fish</Name>
  </Data>
  </Test>

  <Test>
    <Name>1 Post Histoy</Name>
    <Type>Known</Type>
    <Data>
      <Name>Human</Name>
      <Name>Dog</Name>
    </Data>
 </Test>

  <Test>
    <Name>1 Post Histoy</Name>
    <Type>UNKNOWN</Type>
    <Data>
      <Name>Human</Name>
      <Name>Dog</Name>
    </Data>
 </Test>

  </doc></code>```

Body:
I have a problem using XPath and contains function. Imagine the XML example below:

   <doc>
     <Test>
       <Name>1 Pre Histoy</Name>
       <Type>Known</Type>
       <Data>
          <Name>Dinasor</Name>
          <Name>Fish</Name>
      </Data>
      </Test>

      <Test>
        <Name>1 Post Histoy</Name>
        <Type>Known</Type>
        <Data>
          <Name>Human</Name>
          <Name>Dog</Name>
        </Data>
     </Test>

      <Test>
        <Name>1 Post Histoy</Name>
        <Type>UNKNOWN</Type>
        <Data>
          <Name>Human</Name>
          <Name>Dog</Name>
        </Data>
     </Test>

  </doc>

So what I want to do is returning all <Name> texts within <Data> node, with following criteria:

doc//Test/Name should contain "Pre" text

doc//Test/Type should be "Known"

What I need is a query like this but so far I couldn't manage it

/doc//Test[Name contains(.,'Pre') and Type='Known']/data//Name

Any help and tips will be appreciated.

Body:
Try this:

/doc/Test[contains(Name, "Pre") and Type="Known"]/Data/Name

Here is a working example implemented in Javascript to take advantage of StackOverflow's Runnable Code Snippets

function fu(path){
  var output = "";
  var results =  document.evaluate(path, document, null, XPathResult.ANY_TYPE  , null);
  while(nextResult = results.iterateNext()){ output += nextResult.outerHTML + "\n"; }
  return output;
}

document.body.innerText = fu('//doc/Test[contains(Name, "Pre") and Type="Known"]/Data/Name');

<doc>
 <Test>
   <Name>1 Pre Histoy</Name>
   <Type>Known</Type>
   <Data>
      <Name>Dinasor</Name>
      <Name>Fish</Name>
  </Data>
  </Test>

  <Test>
    <Name>1 Post Histoy</Name>
    <Type>Known</Type>
    <Data>
      <Name>Human</Name>
      <Name>Dog</Name>
    </Data>
 </Test>

  <Test>
    <Name>1 Post Histoy</Name>
    <Type>UNKNOWN</Type>
    <Data>
      <Name>Human</Name>
      <Name>Dog</Name>
    </Data>
 </Test>

  </doc>


问:
Access S3 from Amazon ML
I am evaluating Amazon ML and I am unable to use any S3 file. Even the sample "aml-sample-data/banking.csv" gives me the same error: We are unable to read your S3 file. Make sure this is a CSV formatted file and UTF-8 encoded.

Should I have any configuration to use the product? I thought the sample would be already configured.

答: You need to setup the specific access level for Amazon ml to the specific S3 file. The security settings has to be matching at both end and can be easily done using ui.</p>

Title: Access S3 from Amazon ML


问:
How to SQL PIVOT this data by day?
With the following schema and table, showing example output of the table, I'm trying to "PIVOT" this data to have rows consisting of the SERIAL and AREA, with each column being the COMPLIANCE for each "NIGHTOF" record. Ideal output shown below as well. I can not wrap my head around the PIVOT syntax no matter how many times I read examples...

Schema and table:

```<code>SELECT [CONTID], [AREA], [NIGHTOF], [COMPLIANCE] FROM ComplianceScores
</code>```

Regular Output:

```<code>CONTID  NIGHTOF     AREA    COMPLIANCE
001     2014-01-01  Room 2  28
001     2014-01-01  Room 2  18
001     2014-01-01  Room 2  20
003     2014-01-02  Room 1  18
003     2014-01-02  Room 1  70
003     2014-01-02  Room 1  80
008     2014-01-03  Room 1  0
009     2014-01-04  Room 1  35
</code>```

Ideal output:

```<code>CONTID  AREA    2014-01-01   2014-01-02    2014-01-03
001     Room 2  28           18            20
003     Room 1  18           70            80
</code>```

答:
I agree with @Sparky that your data and output don't match.

I think your data was meant to be like:

```<code>create table ComplianceScores (
  CONTID char(3),
  NIGHTOF date,
  AREA varchar(10),
  COMPLIANCE int
  )

insert ComplianceScores (CONTID, NIGHTOF, AREA, COMPLIANCE)
values ('001', '2014-01-01', 'Room 2', 28)
, ('001', '2014-01-02', 'Room 2', 18)
, ('001', '2014-01-03', 'Room 2', 20)
, ('003', '2014-01-01', 'Room 1', 18)
, ('003', '2014-01-02', 'Room 1', 70)
, ('003', '2014-01-03', 'Room 1', 80)

</code>```

And I think you're looking for this SQL:

```<code>select ContId, Area, [2014-01-01], [2014-01-02], [2014-01-03]
  from (select Area, ContId, NightOf, Compliance
          from ComplianceScores) SourceTable
pivot
(
  sum(Compliance)
  for NightOf in ([2014-01-01], [2014-01-02], [2014-01-03])
) pt;
</code>```

Title: How to SQL PIVOT this data by day?

Body:
With the following schema and table, showing example output of the table, I'm trying to "PIVOT" this data to have rows consisting of the SERIAL and AREA, with each column being the COMPLIANCE for each "NIGHTOF" record. Ideal output shown below as well. I can not wrap my head around the PIVOT syntax no matter how many times I read examples...

Schema and table:

SELECT [CONTID], [AREA], [NIGHTOF], [COMPLIANCE] FROM ComplianceScores

Regular Output:

CONTID  NIGHTOF     AREA    COMPLIANCE
001     2014-01-01  Room 2  28
001     2014-01-01  Room 2  18
001     2014-01-01  Room 2  20
003     2014-01-02  Room 1  18
003     2014-01-02  Room 1  70
003     2014-01-02  Room 1  80
008     2014-01-03  Room 1  0
009     2014-01-04  Room 1  35

Ideal output:

CONTID  AREA    2014-01-01   2014-01-02    2014-01-03
001     Room 2  28           18            20
003     Room 1  18           70            80

Body:
I agree with @Sparky that your data and output don't match.

I think your data was meant to be like:

create table ComplianceScores (
  CONTID char(3),
  NIGHTOF date,
  AREA varchar(10),
  COMPLIANCE int
  )

insert ComplianceScores (CONTID, NIGHTOF, AREA, COMPLIANCE)
values ('001', '2014-01-01', 'Room 2', 28)
, ('001', '2014-01-02', 'Room 2', 18)
, ('001', '2014-01-03', 'Room 2', 20)
, ('003', '2014-01-01', 'Room 1', 18)
, ('003', '2014-01-02', 'Room 1', 70)
, ('003', '2014-01-03', 'Room 1', 80)

And I think you're looking for this SQL:

select ContId, Area, [2014-01-01], [2014-01-02], [2014-01-03]
  from (select Area, ContId, NightOf, Compliance
          from ComplianceScores) SourceTable
pivot
(
  sum(Compliance)
  for NightOf in ([2014-01-01], [2014-01-02], [2014-01-03])
) pt;


问:
How to solve this TypeError Exception in Pylibmodbus?
I am trying to create this ModbusRtu object however when I try to insert some parameters, it seems to raise an error. Even when I just try to run it with its original parameters as dictated by the author, the same error rises. I currently have all of the required packages installed.

libffi-dev - 3.2.1-4
libmodbus - 3.1.4-2
libmodbus-dev - 3.1.4-2
python-dev - 2.7.15~rc1-1
cffi - 2.19

I really confused why it should not work since even the author-defined parameters seem to create the same error as well.

I already tried following its message by converting the parameters into bytes, or list, or tuple, but it only raises another exception

```<code>``` Python Code 1 (before my solution)
self.master = ModbusRtu(device='/dev/ttyACM0',
                        baud=9600, data_bit=8,
                        parity='N', stop_bit=1)

``` Python Code 2 (after my solution)
self.master = ModbusRtu(device=bytes('/dev/ttyACM0', 'ascii),
                        baud=9600, data_bit=8,
                        parity=bytes('N', 'ascii), stop_bit=1)

``` Simpler Python Code 1
from pylibmodbus import ModbusRtu

def main():
    client = ModbusRtu()
    # i can't instantiate the ModbusRtu class
    print(client)
    # i should have at least the id of the instantiated class
if __name__ == '__main__':
    main()
```

It is supposedly create the object, however I only got this message:

File "/usr/local/lib/python3.6/dist-packages/pylibmodbus/modbus_rtu.py", line 11, in init
    self.ctx = C.modbus_new_rtu(device, baud, parity, data_bit,
                                stop_bit)
TypeError: initializer for ctype 'char *' must be a bytes or list or tuple, not str

When I try converting the string parameters into bytes I got this message:

File "/usr/local/lib/python3.6/dist-packages/pylibmodbus/modbus_core.py", line 60, in _run
    raise Exception(ffi.string(C.modbus_strerror(ffi.errno)))
Exception: b'No such file or directory'

答:
This is what works for me with Python 2.x:

```<code>from pylibmodbus import ModbusRtu

client=ModbusRtu(device="/dev/ttyACM0", baud=19200, parity="N", data_bit=8, stop_bit=1)

client.connect()
SERVER_ID=0

client.set_slave(SERVER_ID)

client.write_registers(0, [0]*10)

result=(client.read_registers(0, 10))
print result

client.close()
</code>```

For Python 3.x you have to encode the text, I think that was your problem:

from pylibmodbus import ModbusRtu

```<code>client=ModbusRtu(device="/dev/ttyACM0".encode("ascii"), baud=19200, parity="N".encode("ascii"), data_bit=8, stop_bit=1)

client.connect()
SERVER_ID=0

client.set_slave(SERVER_ID)

client.write_registers(0, [0]*10)

result=(client.read_registers(0, 10))
print(result)

client.close()
</code>```

Body:
I am trying to create this ModbusRtu object however when I try to insert some parameters, it seems to raise an error. Even when I just try to run it with its original parameters as dictated by the author, the same error rises. I currently have all of the required packages installed.

libffi-dev - 3.2.1-4
libmodbus - 3.1.4-2
libmodbus-dev - 3.1.4-2
python-dev - 2.7.15~rc1-1
cffi - 2.19

I really confused why it should not work since even the author-defined parameters seem to create the same error as well.

I already tried following its message by converting the parameters into bytes, or list, or tuple, but it only raises another exception

``` Python Code 1 (before my solution)
self.master = ModbusRtu(device='/dev/ttyACM0',
                        baud=9600, data_bit=8,
                        parity='N', stop_bit=1)

``` Python Code 2 (after my solution)
self.master = ModbusRtu(device=bytes('/dev/ttyACM0', 'ascii),
                        baud=9600, data_bit=8,
                        parity=bytes('N', 'ascii), stop_bit=1)

``` Simpler Python Code 1
from pylibmodbus import ModbusRtu

def main():
    client = ModbusRtu()
    # i can't instantiate the ModbusRtu class
    print(client)
    # i should have at least the id of the instantiated class
if __name__ == '__main__':
    main()

It is supposedly create the object, however I only got this message:

File "/usr/local/lib/python3.6/dist-packages/pylibmodbus/modbus_rtu.py", line 11, in init
    self.ctx = C.modbus_new_rtu(device, baud, parity, data_bit,
                                stop_bit)
TypeError: initializer for ctype 'char *' must be a bytes or list or tuple, not str

When I try converting the string parameters into bytes I got this message:

File "/usr/local/lib/python3.6/dist-packages/pylibmodbus/modbus_core.py", line 60, in _run
    raise Exception(ffi.string(C.modbus_strerror(ffi.errno)))
Exception: b'No such file or directory'

Body:
This is what works for me with Python 2.x:

from pylibmodbus import ModbusRtu

client=ModbusRtu(device="/dev/ttyACM0", baud=19200, parity="N", data_bit=8, stop_bit=1)

client.connect()
SERVER_ID=0

client.set_slave(SERVER_ID)

client.write_registers(0, [0]*10)

result=(client.read_registers(0, 10))
print result

client.close()

For Python 3.x you have to encode the text, I think that was your problem:

from pylibmodbus import ModbusRtu

client=ModbusRtu(device="/dev/ttyACM0".encode("ascii"), baud=19200, parity="N".encode("ascii"), data_bit=8, stop_bit=1)

client.connect()
SERVER_ID=0

client.set_slave(SERVER_ID)

client.write_registers(0, [0]*10)

result=(client.read_registers(0, 10))
print(result)

client.close()


问:
How to update map markers based on an AsyncTask result
I have an asyncTask CommunicationThread which creates some Latitudes and Longitudes. I also have a map activity where I want to take the results of CommunicationThread update the marker based on these results. Here is the code of my map Activity.

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private Thread2ThreadInfo connectionInfo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    connectionInfo = SubscriberActivity.getConnInfo();
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        Value currentPosition;
        @Override
        public void run() {
            while(true) {
                Log.e("start", "new thread");
                CommunicationThread communicationThread = new CommunicationThread();
                try {
                    currentPosition = communicationThread.execute(connectionInfo).get();
                    Log.e("start", currentPosition.toString());

                    LatLng templt = null;
                    double lat = currentPosition.getLatitude();
                    double lon = currentPosition.getLongtitude();
                    LatLng lt = new LatLng(lat, lon);

                    templt = lt;

                    MarkerOptions a = new MarkerOptions().position(lt).title(currentPosition.getBus().getBusLineId());
                    Marker m = mMap.addMarker(a);
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(lt));
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(templt, 13.0f));
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}
}
</code>```

CommunicationThread works properly and the data (positions) are send to the map activity. I use an infinite loop to execute CommunicationThread tasks and when new positions are avaiable, fetch them. I alse use a handler in order to avoid issues with infinite loop inside the main thread. When I run it, the data are sent succesfuly (according to the logs produced inside the loop), but the map appears as follows:

When I run it without the infinite loop (just for one position) it runs properly.
Any other ideas?

答:
Did you get a key for the Google maps api ?
if you didn't you have to get a key to use the google map in your application

please follow this link
Get an API Key

Body:
I have an asyncTask CommunicationThread which creates some Latitudes and Longitudes. I also have a map activity where I want to take the results of CommunicationThread update the marker based on these results. Here is the code of my map Activity.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private Thread2ThreadInfo connectionInfo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    connectionInfo = SubscriberActivity.getConnInfo();
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        Value currentPosition;
        @Override
        public void run() {
            while(true) {
                Log.e("start", "new thread");
                CommunicationThread communicationThread = new CommunicationThread();
                try {
                    currentPosition = communicationThread.execute(connectionInfo).get();
                    Log.e("start", currentPosition.toString());

                    LatLng templt = null;
                    double lat = currentPosition.getLatitude();
                    double lon = currentPosition.getLongtitude();
                    LatLng lt = new LatLng(lat, lon);

                    templt = lt;

                    MarkerOptions a = new MarkerOptions().position(lt).title(currentPosition.getBus().getBusLineId());
                    Marker m = mMap.addMarker(a);
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(lt));
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(templt, 13.0f));
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}
}

CommunicationThread works properly and the data (positions) are send to the map activity. I use an infinite loop to execute CommunicationThread tasks and when new positions are avaiable, fetch them. I alse use a handler in order to avoid issues with infinite loop inside the main thread. When I run it, the data are sent succesfuly (according to the logs produced inside the loop), but the map appears as follows:

When I run it without the infinite loop (just for one position) it runs properly.
Any other ideas?


问:
Multiply every matrix of a numpy array with the transpose of every other efficiently
Given a numpy array M I want to calculate the matrix product M[i] @ M[j].T of every 2-combination of matrices of this array. After having applied some operations to that matrix (the product), I want to store the results in another matrix at position [i,j]. Is there a way to compute this fast without iterating over two nested loops?

I.e. what I want to avoid (because it takes literally hours) is:

```<code>import numpy as np

M = np.random.rand(7000,3,3)
r = np.zeros((len(M), len(M)))

for i in range(len(r)):
    for j in range(len(r[0])):
        n = M[i] @ M[j].T
        r[i,j] = np.linalg.norm(n)
</code>```

答:
Assuming You wanted r's shape to be (M.shape[0],M.shape[0]).

```<code>M = np.random.rand(700,3,3)
t = M.shape[0]
r = np.zeros((t, t))
</code>```

This is equivalent to the first statement of your inner loop

```<code>q = M[:,None,...] @ M.swapaxes(1,2)
</code>```

And this completes the inner/outer loop

```<code>p = np.linalg.norm(q, axis=(2,3))
</code>```

```<code>for i in range(len(r)):
    for j in range(len(r[0])):
        n = M[i] @ M[j].T
        r[i,j] = np.linalg.norm(n)

>>> np.all(np.isclose(p,r))
True
</code>```

With M.shape -> (70,3,3) it is about 42 times faster than the for loop.

With M.shape -> (700,3,3) it is about 36 times faster than the for loop.

My poor computer cannot handle M.shape --> (7000,3,3) ... MemoryError.

Body:
Given a numpy array M I want to calculate the matrix product M[i] @ M[j].T of every 2-combination of matrices of this array. After having applied some operations to that matrix (the product), I want to store the results in another matrix at position [i,j]. Is there a way to compute this fast without iterating over two nested loops?

I.e. what I want to avoid (because it takes literally hours) is:

import numpy as np

M = np.random.rand(7000,3,3)
r = np.zeros((len(M), len(M)))

for i in range(len(r)):
    for j in range(len(r[0])):
        n = M[i] @ M[j].T
        r[i,j] = np.linalg.norm(n)

Body:
Assuming You wanted r's shape to be (M.shape[0],M.shape[0]).

M = np.random.rand(700,3,3)
t = M.shape[0]
r = np.zeros((t, t))

This is equivalent to the first statement of your inner loop

q = M[:,None,...] @ M.swapaxes(1,2)

And this completes the inner/outer loop

p = np.linalg.norm(q, axis=(2,3))

for i in range(len(r)):
    for j in range(len(r[0])):
        n = M[i] @ M[j].T
        r[i,j] = np.linalg.norm(n)

>>> np.all(np.isclose(p,r))
True

With M.shape -> (70,3,3) it is about 42 times faster than the for loop.

With M.shape -> (700,3,3) it is about 36 times faster than the for loop.

My poor computer cannot handle M.shape --> (7000,3,3) ... MemoryError.