问:
Why does the number of constructor calls not match with the number of destructor calls?

I am very confused about the following piece of code.

```<code>#include <iostream>

class mobject
{
public:
    mobject(){ std::cout << "mobject ctor\n"; }
    ~mobject(){ std::cout << "mobject dtor\n"; }
};

mobject giveme() { return mobject(); }
void func2(const mobject& p) { mobject g = p; }
void func1(const mobject& p) { func2(p); }
int main()
{
    func1(giveme());
    return 0;
}
</code>```

It gives me the following output:

```
mobject ctor
mobject dtor
mobject dtor
```

I compiled the code with gcc 5.4.0 with `"g++ -g temp.cpp". My main concern is the second call tor mobjects's destructor. That looks to be quite wrong since we call dtor a second time. valgrind tells me there is no problem with this one but still I am confused.

答:
Two lines of output of mobject dtor is due to following:

First object is created when you calls giveme() function in main in line func1(giveme());. This gives the 3rd line of output mobject dtor, when program ends.

2nd object is created using default-copy-constructor in line mobject g = p; of function func2. 2nd line of output mobject dtor is when this object is getting deleted in return from this function.

Following modified code and respective output will demonstrate it:

```<code>class mobject
{
public:
    mobject(const mobject& ob){ cout << "mobject overridden-copy-constructor\n"; }
    mobject(){ cout << "mobject ctor\n"; }
    ~mobject(){ cout << "mobject dtor\n"; }
};

mobject giveme()
{
    cout << "1. In Function: "<<__func__<<endl;
    return mobject();
}
void func2(const mobject& p)
{
    cout << "2. In Function: "<<__func__<<endl;
    mobject g = p;
    cout << "3. In Function: "<<__func__<<endl;
}
void func1(const mobject& p)
{
    cout << "4. In Function: "<<__func__<<endl;
    func2(p);
    cout << "5. In Function: "<<__func__<<endl;
}
int main()
{
    cout << "6. In Function: "<<__func__<<endl;
    func1(giveme());
    cout << "7. In Function: "<<__func__<<endl;
    return 0;
}
</code>```

OUTPUT

```<code>6. In Function: main
1. In Function: giveme
mobject ctor
4. In Function: func1
2. In Function: func2
mobject overridden-copy-constructor
3. In Function: func2
mobject dtor
5. In Function: func1
mobject dtor
7. In Function: main
</code>```

See here working code it.

Body:
I am very confused about the following piece of code.

#include <iostream>

class mobject
{
public:
    mobject(){ std::cout << "mobject ctor\n"; }
    ~mobject(){ std::cout << "mobject dtor\n"; }
};

mobject giveme() { return mobject(); }
void func2(const mobject& p) { mobject g = p; }
void func1(const mobject& p) { func2(p); }
int main()
{
    func1(giveme());
    return 0;
}

It gives me the following output:

mobject ctor
mobject dtor
mobject dtor

I compiled the code with gcc 5.4.0 with `"g++ -g temp.cpp". My main concern is the second call tor mobjects's destructor. That looks to be quite wrong since we call dtor a second time. valgrind tells me there is no problem with this one but still I am confused.

Body:
Two lines of output of mobject dtor is due to following:

First object is created when you calls giveme() function in main in line func1(giveme());. This gives the 3rd line of output mobject dtor, when program ends.

2nd object is created using default-copy-constructor in line mobject g = p; of function func2. 2nd line of output mobject dtor is when this object is getting deleted in return from this function.

Following modified code and respective output will demonstrate it:

class mobject
{
public:
    mobject(const mobject& ob){ cout << "mobject overridden-copy-constructor\n"; }
    mobject(){ cout << "mobject ctor\n"; }
    ~mobject(){ cout << "mobject dtor\n"; }
};

mobject giveme()
{
    cout << "1. In Function: "<<__func__<<endl;
    return mobject();
}
void func2(const mobject& p)
{
    cout << "2. In Function: "<<__func__<<endl;
    mobject g = p;
    cout << "3. In Function: "<<__func__<<endl;
}
void func1(const mobject& p)
{
    cout << "4. In Function: "<<__func__<<endl;
    func2(p);
    cout << "5. In Function: "<<__func__<<endl;
}
int main()
{
    cout << "6. In Function: "<<__func__<<endl;
    func1(giveme());
    cout << "7. In Function: "<<__func__<<endl;
    return 0;
}

OUTPUT

6. In Function: main
1. In Function: giveme
mobject ctor
4. In Function: func1
2. In Function: func2
mobject overridden-copy-constructor
3. In Function: func2
mobject dtor
5. In Function: func1
mobject dtor
7. In Function: main

See here working code it.


来源: stackexchange

问:
zlib.error: Error -3 while decompressing: incorrect header check
I have a gzip file and I am trying to read it via Python as below:

```<code>import zlib

do = zlib.decompressobj(16+zlib.MAX_WBITS)
fh = open('abc.gz', 'rb')
cdata = fh.read()
fh.close()
data = do.decompress(cdata)
</code>```

it throws this error:

```<code>zlib.error: Error -3 while decompressing: incorrect header check
</code>```

How can I overcome it?

答:
Just add headers 'Accept-Encoding': 'identity'

```<code>import requests

requests.get('http://gett.bike/', headers={'Accept-Encoding': 'identity'})
</code>```

https://github.com/requests/requests/issues/3849

ContentLicense: CC BY-SA 2.5

Body:
I have a gzip file and I am trying to read it via Python as below:

import zlib

do = zlib.decompressobj(16+zlib.MAX_WBITS)
fh = open('abc.gz', 'rb')
cdata = fh.read()
fh.close()
data = do.decompress(cdata)

it throws this error:

zlib.error: Error -3 while decompressing: incorrect header check

How can I overcome it?

Body:
Just add headers 'Accept-Encoding': 'identity'

import requests

requests.get('http://gett.bike/', headers={'Accept-Encoding': 'identity'})

https://github.com/requests/requests/issues/3849

ContentLicense: CC BY-SA 3.0


问:
Why is pip install mysql-connector fail?
I'm just trying to simply install python-myconnector using the very simple instructions provided here.

But it is failing. Here is the error I get:

```<code>(my_virtual_env) [my.username@my_machine ~]$ pip install mysql-connector
...
Command "/home/my.username/my_virtual_env/bin/python2.7 -u -c
  "import setuptools, tokenize;
  __file__='/tmp/pip-build-rLJbLN/mysql-connector/setup.py';
  f=getattr(tokenize, 'open', open)(__file__);
  code=f.read().replace('\r\n', '\n');f.close();
  exec(compile(code, __file__, 'exec'))" install
  --record /tmp/pip-mFh5Pg-record/install-record.txt
  --single-version-externally-managed
  --compile
  --install-headers
  /home/me/my_virtual_env/include/site/python2.7/mysql-connector"
  failed with error code 1 in /tmp/pip-build-rLJbLN/mysql-connector/```
```

The full error log can be found here if you need to see it (but I doubt you will)

Why is this happening and how can I fix it?? Also, FYI, I don't have sudo access on this machine. So that's why I am installing it into a virtual environment..

FYI, it seems like it was supposed write something into /tmp/pip-build-rLJbLN/ but didn't and then it blows up later on when it tries to read from what it was supposed to have written there earlier. So how do I fix this bug??

I have read other solutions to other similar problem here. But I couldn't get any of them to work for me.

答:
The mysql-connector clearly states that it requires protobuf

mysql-connector (version >= 2.2.3) requires Protobuf C++ (version >= 2.6.0)

Just as I commented, your error log insists the same:

Line 81, 165: Unable to find Protobuf include directory.

Based on your platform, follow this protobuf C++ installaion instruction, and export the protobuf path so that pip can refer that path

Body:
I'm just trying to simply install python-myconnector using the very simple instructions provided here.

But it is failing. Here is the error I get:

(my_virtual_env) [my.username@my_machine ~]$ pip install mysql-connector
...
Command "/home/my.username/my_virtual_env/bin/python2.7 -u -c
  "import setuptools, tokenize;
  __file__='/tmp/pip-build-rLJbLN/mysql-connector/setup.py';
  f=getattr(tokenize, 'open', open)(__file__);
  code=f.read().replace('\r\n', '\n');f.close();
  exec(compile(code, __file__, 'exec'))" install
  --record /tmp/pip-mFh5Pg-record/install-record.txt
  --single-version-externally-managed
  --compile
  --install-headers
  /home/me/my_virtual_env/include/site/python2.7/mysql-connector"
  failed with error code 1 in /tmp/pip-build-rLJbLN/mysql-connector/```

The full error log can be found here if you need to see it (but I doubt you will)

Why is this happening and how can I fix it?? Also, FYI, I don't have sudo access on this machine. So that's why I am installing it into a virtual environment..

FYI, it seems like it was supposed write something into /tmp/pip-build-rLJbLN/ but didn't and then it blows up later on when it tries to read from what it was supposed to have written there earlier. So how do I fix this bug??

I have read other solutions to other similar problem here. But I couldn't get any of them to work for me.


问:
Firebase phone auth sends unreadable verification SMS for chinese and japanese language
We are using the library FirebaseUI/Phone. And our ios app is supporting for multiple languages.

The auth UIs are correctly localized but sms message are sometimes unreadable when the app language is Chinese or Japanese. English works fine.

Does someone has a solution for it. (It seems like a bug of some particular sms sending server. )

sms is readable from the number in the first picture and unreadable from the second

We tried to set the languageCode as the document says like
Auth.auth().languageCode = "fr" and auth().useAppLanguage and so on.
No change for japanese and chinese.
As a result we have to set languageCode to en for all languages.

答: I just tested phone sign in with the web SDK. I set the language code to "zh-CN" and I got the SMS in Chinese. Make sure you are passing the correct language code for Chinese (simplified: zh-CN, traditional: zh-TW)</p>


答:
Your code constructs two mobjects, one default constructed and the other copy constructed, but you have only put a print message in the default constructor and ignored the copy constructor. Note also that your function calls are irrelevant to the problem at hand:

```<code>#include <iostream>

struct mobject
{
    mobject(const mobject& /* other */){ std::cout << "mobject copy-ctor\n"; }
    mobject(){ std::cout << "mobject ctor\n"; }
    ~mobject(){ std::cout << "mobject dtor\n"; }
};

int main()
{
  const mobject& p = mobject();
  mobject g = p;
}
</code>```

which gives:

```
mobject ctor
mobject copy-ctor
mobject dtor
mobject dtor
```

Title: Why does the number of constructor calls not match with the number of destructor calls?

Body:
Your code constructs two mobjects, one default constructed and the other copy constructed, but you have only put a print message in the default constructor and ignored the copy constructor. Note also that your function calls are irrelevant to the problem at hand:

#include <iostream>

struct mobject
{
    mobject(const mobject& /* other */){ std::cout << "mobject copy-ctor\n"; }
    mobject(){ std::cout << "mobject ctor\n"; }
    ~mobject(){ std::cout << "mobject dtor\n"; }
};

int main()
{
  const mobject& p = mobject();
  mobject g = p;
}

which gives:

mobject ctor
mobject copy-ctor
mobject dtor
mobject dtor


问:
grunt compass give single scss file
I am using grunt compass and I want only to compile a single scss file src/scss/image_slider.scss instead of all the files under scss folder.

Below written code works fine for full scss foler.

```<code>compass: {
        dist: {
            options: {
                sassDir: 'src/scss',
                cssDir: 'src/css',
            }
        }
    },
</code>```

答:
It worked in below format:</p>

```<code>compass: {
        dist: {
            options: {
                sassDir: 'src/scss',
                specify: 'src/scss/my_file.scss',
                cssDir: 'src/css',
            }
        }
    },
</code>```

Title: grunt compass give single scss file

Body:
I am using grunt compass and I want only to compile a single scss file src/scss/image_slider.scss instead of all the files under scss folder.

Below written code works fine for full scss foler.

compass: {
        dist: {
            options: {
                sassDir: 'src/scss',
                cssDir: 'src/css',
            }
        }
    },

Body:
It worked in below format:

compass: {
        dist: {
            options: {
                sassDir: 'src/scss',
                specify: 'src/scss/my_file.scss',
                cssDir: 'src/css',
            }
        }
    },


问:
Converting C++ object file from linux .o to Windows .obj
I'm sorry if this sounds crazy. Is there anyway I can convert .o file that I get from g++ compiler to *obj that is compatible with Visual Studio.

This is the reason I am considering doing this conversion.

答:
Hmm, technically the objcopy command which is part of gnu bintuils might be able to do it.
However, and this is a huge however, converting the format isn't enough. You'd need a version of the g++ compiler that has the exact calling conventions and name mangling as vc++ for starters, and the same idea of compiling structures and so on.

Physically converting the file into a valid .obj file may well be possible, but it's likely not very helpful to you.


问:
Thymeleaf ignore fragment not found
I have an Spring Boot (2M6) application which is using Thymeleaf to render some HTML documents.

My templates include some fragments which are ultimately selected based on user input. On some occasions the user input results in selection of a fragment that does not exist.

This is an error, and currently this results in an exception and the template does not render. I would like to either render a different, default "invalid selection" fragment, or perhaps even an empty fragment.

The top end of the stack trace looks like this

```<code>org.thymeleaf.exceptions.TemplateInputException: Error resolving fragment: ":: ${entity.fields[code]}": template or fragment could not be resolved (template: "common/fragments" - line 5, col 14)
at org.thymeleaf.standard.processor.AbstractStandardFragmentInsertionTagProcessor.doProcess(AbstractStandardFragmentInsertionTagProcessor.java:117) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.engine.StandaloneElementTag.beHandled(StandaloneElementTag.java:228) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.engine.Model.process(Model.java:282) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
</code>```

If entity.fields[code] contains a value for which there is a matching th:fragment, all is well.

Working back from AbstractStandardFragmentInsertionTagProcessor.doProcess

AbstractStandardFragmentInsertionTagProcessor#computeFragment seems to, by choice, always fail if the fragment does not exist.

This seems to be contrary to another answer. FWIW I've tried using th:include, th:insert and th:replace

Is it possible to detect if a fragment is defined (so that I can then select a different fragment)? Or alternatively, what tools are available to handle missing fragments and where are the levers to adjust them?

I'm pretty new to Thymeleaf, so I've probably missed something fairly basic.

答:
As is always the way, I spot something after submitting the question.

The documentation for advanced conditional insertion of fragments includes an example of what I'm trying to achieve

My fragment insertion now looks like

```<code><div th:replace="~{:: __${entity.fields[code]}__} ?: _">
    Invalid code
</div>
</code>```

Title: Thymeleaf ignore fragment not found

Body:
I have an Spring Boot (2M6) application which is using Thymeleaf to render some HTML documents.

My templates include some fragments which are ultimately selected based on user input. On some occasions the user input results in selection of a fragment that does not exist.

This is an error, and currently this results in an exception and the template does not render. I would like to either render a different, default "invalid selection" fragment, or perhaps even an empty fragment.

The top end of the stack trace looks like this

org.thymeleaf.exceptions.TemplateInputException: Error resolving fragment: ":: ${entity.fields[code]}": template or fragment could not be resolved (template: "common/fragments" - line 5, col 14)
at org.thymeleaf.standard.processor.AbstractStandardFragmentInsertionTagProcessor.doProcess(AbstractStandardFragmentInsertionTagProcessor.java:117) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.engine.StandaloneElementTag.beHandled(StandaloneElementTag.java:228) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.engine.Model.process(Model.java:282) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]

If entity.fields[code] contains a value for which there is a matching th:fragment, all is well.

Working back from AbstractStandardFragmentInsertionTagProcessor.doProcess

AbstractStandardFragmentInsertionTagProcessor#computeFragment seems to, by choice, always fail if the fragment does not exist.

This seems to be contrary to another answer. FWIW I've tried using th:include, th:insert and th:replace

Is it possible to detect if a fragment is defined (so that I can then select a different fragment)? Or alternatively, what tools are available to handle missing fragments and where are the levers to adjust them?

I'm pretty new to Thymeleaf, so I've probably missed something fairly basic.

Body:
As is always the way, I spot something after submitting the question.

The documentation for advanced conditional insertion of fragments includes an example of what I'm trying to achieve

My fragment insertion now looks like

<div th:replace="~{:: __${entity.fields[code]}__} ?: _">
    Invalid code
</div>


问:
PostgreSQL ADD COLUMN DEFAULT NULL locks and performance
I have a table in my PostgreSQL 9.6 database with 3 million rows. This table already has a null bitmap (it has 2 other DEFAULT NULL fields). I want to add a new boolean nullable column to this table. I stuck with the difference between these two statements:

```<code>ALTER TABLE my_table ADD COLUMN my_column BOOLEAN;
ALTER TABLE my_table ADD COLUMN my_column BOOLEAN DEFAULT NULL;
</code>```

I think that these statements have no difference, but:

I can't find any proof of it in documentation. Documentation tells that providing DEFAULT value for the new column makes PostgreSQL to rewrite all the tuples, but I don't think that it's true for this case, cause default value is NULL.

I ran some tests on copy of this table, and the first statement (without DEFAULT NULL) took a little bit more time than the second. I can't understand why.

My questions are:

Will PostgreSQL use the same lock type (ACCESS EXCLUSIVE) for those two statements?

Will PostgreSQL rewrite all tuples to add NULL value to every of them in case that I use DEFAULT NULL?

Are there any difference between those two statements?

答:
https://www.postgresql.org/docs/current/static/sql-altertable.html

Yes - same ACCESS EXCLUSIVE, no exceptions for DEFAULT NULL or no DEFAULT mentionned (statistics, "options", constraints, cluster would require less strict I think, but not add column)

Note that the lock level required may differ for each subform. An
  ACCESS EXCLUSIVE lock is held unless explicitly noted. When multiple
  subcommands are listed, the lock held will be the strictest one
  required from any subcommand.

No - it will rather append NULL to result on select

When a column is added with ADD COLUMN, all existing rows in the table
  are initialized with the column's default value (NULL if no DEFAULT
  clause is specified). If there is no DEFAULT clause, this is merely a
  metadata change and does not require any immediate update of the
  table's data; the added NULL values are supplied on readout, instead.

No - no difference AFAIK. Just metadata change in both cases (as I believe it is one case expressed with different semantics)

Edit - Demo:

```<code>db=# create table so(i int);
CREATE TABLE
Time: 9.498 ms
db=# insert into so select generate_series(1,10*1000*1000);
INSERT 0 10000000
Time: 13899.190 ms
db=# alter table so add column nd BOOLEAN;
ALTER TABLE
Time: 1025.178 ms
db=# alter table so add column dn BOOLEAN default null;
ALTER TABLE
Time: 13.849 ms
db=# alter table so add column dnn BOOLEAN default true;
ALTER TABLE
Time: 14988.450 ms
db=# select version();
                                                    version
----------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.6.1 on x86_64-apple-darwin15.6.0, compiled by Apple LLVM version 8.0.0 (clang-800.0.42.1), 64-bit
(1 row)
</code>```

lastly to avoid speculations it is data type specific:

```<code>db=# alter table so add column t text;
ALTER TABLE
Time: 25.831 ms
db=# alter table so add column tn text default null;
ALTER TABLE
Time: 13.798 ms
db=# alter table so add column tnn text default 'null';
ALTER TABLE
Time: 15440.318 ms
</code>```

Body:
I have a table in my PostgreSQL 9.6 database with 3 million rows. This table already has a null bitmap (it has 2 other DEFAULT NULL fields). I want to add a new boolean nullable column to this table. I stuck with the difference between these two statements:

ALTER TABLE my_table ADD COLUMN my_column BOOLEAN;
ALTER TABLE my_table ADD COLUMN my_column BOOLEAN DEFAULT NULL;

I think that these statements have no difference, but:

I can't find any proof of it in documentation. Documentation tells that providing DEFAULT value for the new column makes PostgreSQL to rewrite all the tuples, but I don't think that it's true for this case, cause default value is NULL.

I ran some tests on copy of this table, and the first statement (without DEFAULT NULL) took a little bit more time than the second. I can't understand why.

My questions are:

Will PostgreSQL use the same lock type (ACCESS EXCLUSIVE) for those two statements?

Will PostgreSQL rewrite all tuples to add NULL value to every of them in case that I use DEFAULT NULL?

Are there any difference between those two statements?

Body:
https://www.postgresql.org/docs/current/static/sql-altertable.html

Yes - same ACCESS EXCLUSIVE, no exceptions for DEFAULT NULL or no DEFAULT mentionned (statistics, "options", constraints, cluster would require less strict I think, but not add column)

Note that the lock level required may differ for each subform. An
  ACCESS EXCLUSIVE lock is held unless explicitly noted. When multiple
  subcommands are listed, the lock held will be the strictest one
  required from any subcommand.

No - it will rather append NULL to result on select

When a column is added with ADD COLUMN, all existing rows in the table
  are initialized with the column's default value (NULL if no DEFAULT
  clause is specified). If there is no DEFAULT clause, this is merely a
  metadata change and does not require any immediate update of the
  table's data; the added NULL values are supplied on readout, instead.

No - no difference AFAIK. Just metadata change in both cases (as I believe it is one case expressed with different semantics)

Edit - Demo:

db=# create table so(i int);
CREATE TABLE
Time: 9.498 ms
db=# insert into so select generate_series(1,10*1000*1000);
INSERT 0 10000000
Time: 13899.190 ms
db=# alter table so add column nd BOOLEAN;
ALTER TABLE
Time: 1025.178 ms
db=# alter table so add column dn BOOLEAN default null;
ALTER TABLE
Time: 13.849 ms
db=# alter table so add column dnn BOOLEAN default true;
ALTER TABLE
Time: 14988.450 ms
db=# select version();
                                                    version
----------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.6.1 on x86_64-apple-darwin15.6.0, compiled by Apple LLVM version 8.0.0 (clang-800.0.42.1), 64-bit
(1 row)

lastly to avoid speculations it is data type specific:

db=# alter table so add column t text;
ALTER TABLE
Time: 25.831 ms
db=# alter table so add column tn text default null;
ALTER TABLE
Time: 13.798 ms
db=# alter table so add column tnn text default 'null';
ALTER TABLE
Time: 15440.318 ms

ContentLicense: CC BY-SA 4.0


问:
Format numbers with million (M) and billion (B) suffixes
I have large numbers, e.g. currency or dollar:

```<code>1 6,000,000
2 75,000,400
3 743,450,000
4 340,000
5 4,300,000
</code>```

I want to format them using suffixes, like M (million) and B (billion):

```<code>1 6.0 M
2 75.0 M
3 743.5 M
4 0.3 M
5 4.3 M
</code>```

答:
Borrowing from other answers and adding to them with the main intent of producing pretty labels for ggplot2 axes. And yes, only positive values (negative will be left as is) since usually I want those suffixes only for positive quantities. Easy to extend to negative numbers.

```<code># Format numbers with suffixes K, M, B, T and optional rounding. Vectorized
# Main purpose: pretty formatting axes for plots produced by ggplot2
#
# Usage in ggplot2: scale_x_continuous(labels = suffix_formatter)

suffix_formatter <- function(x, digits = NULL)
{
    intl <- c(1e3, 1e6, 1e9, 1e12);
    suffixes <- c('K', 'M', 'B', 'T');

    i <- findInterval(x, intl);

    result <- character(length(x));

    # Note: for ggplot2 the last label element of x is NA, so we need to handle it
    ind_format <- !is.na(x) & i > 0;

    # Format only the elements that need to be formatted
    # with suffixes and possible rounding
    result[ind_format] <- paste0(
        formatC(x[ind_format]/intl[i[ind_format]], format = "f", digits = digits)
        ,suffixes[i[ind_format]]
    );
    # And leave the rest with no changes
    result[!ind_format] <- as.character(x[!ind_format]);

    return(invisible(result));
}
</code>```

And example of usage.

```<code>x <- seq(1:10);
d <- data.frame(x = x, y = 10^x);
ggplot(aes(x=x, y=y), data = d) + geom_line() + scale_y_log10()
</code>```

without suffix formatter

```<code>ggplot(aes(x=x, y=y), data = d) + geom_line() + scale_y_log10(labels = suffix_formatter)
</code>```

with suffix formatter

Body:
I have large numbers, e.g. currency or dollar:

1 6,000,000
2 75,000,400
3 743,450,000
4 340,000
5 4,300,000

I want to format them using suffixes, like M (million) and B (billion):

1 6.0 M
2 75.0 M
3 743.5 M
4 0.3 M
5 4.3 M

Body:
Borrowing from other answers and adding to them with the main intent of producing pretty labels for ggplot2 axes. And yes, only positive values (negative will be left as is) since usually I want those suffixes only for positive quantities. Easy to extend to negative numbers.

# Format numbers with suffixes K, M, B, T and optional rounding. Vectorized
# Main purpose: pretty formatting axes for plots produced by ggplot2
#
# Usage in ggplot2: scale_x_continuous(labels = suffix_formatter)

suffix_formatter <- function(x, digits = NULL)
{
    intl <- c(1e3, 1e6, 1e9, 1e12);
    suffixes <- c('K', 'M', 'B', 'T');

    i <- findInterval(x, intl);

    result <- character(length(x));

    # Note: for ggplot2 the last label element of x is NA, so we need to handle it
    ind_format <- !is.na(x) & i > 0;

    # Format only the elements that need to be formatted
    # with suffixes and possible rounding
    result[ind_format] <- paste0(
        formatC(x[ind_format]/intl[i[ind_format]], format = "f", digits = digits)
        ,suffixes[i[ind_format]]
    );
    # And leave the rest with no changes
    result[!ind_format] <- as.character(x[!ind_format]);

    return(invisible(result));
}

And example of usage.

x <- seq(1:10);
d <- data.frame(x = x, y = 10^x);
ggplot(aes(x=x, y=y), data = d) + geom_line() + scale_y_log10()

without suffix formatter

ggplot(aes(x=x, y=y), data = d) + geom_line() + scale_y_log10(labels = suffix_formatter)

with suffix formatter


问:
How to use same method but to call different methods in response every time?
I have method InfoDetails(); I need to call that method in different methods but in response for that different methods to call other methods. So want i want is something like this:

```<code>InfoDetails(methodName){
  this.methodName(params);
}
</code>```

Any suggestion how can i do that?

答:
if i understand you currctly and im not sure i am.
you can do somthing like this

InfoDetails = function(methodName){
  return window[methodName](arguments)
}

mymethod1 = function(params){
     return 'mymethod1'
}
mymethod2 = function(params){
      return 'mymethod2'
}
console.log(InfoDetails('mymethod1'))
console.log(InfoDetails('mymethod2'))

//or its the function own method
InfoDetails = function(methodName){
  return this[methodName](arguments)
}

InfoDetails.prototype.mymethod1 = function(params){
     return 'mymethod1'
}
InfoDetails.prototype.mymethod2 = function(params){
      return 'mymethod2'
}
var a =  InfoDetails('mymethod1')
console.log(a)```

Body:
I have method InfoDetails(); I need to call that method in different methods but in response for that different methods to call other methods. So want i want is something like this:

InfoDetails(methodName){
  this.methodName(params);
}

Any suggestion how can i do that?


问:
How to make a string interpreted as a condition with Python?
I need to use the following syntax to filter the list operations:

```<code>a = [ope for ope in operations if ope[0] == 1]
</code>```

The if statement condition is variable and may contain multiple conditions:

```<code>a = [ope for ope in operations if ope[0] == 1 and ope[1] == "test"]
</code>```

I use a function to build the condition and return it as a string:

```<code>>>>> c = makeCondition(**{"id": 1, "title": 'test'})
>>>> c
"ope[0] == 1 and ope[1] == 'test'"
</code>```

Is there a way to integrate the c variable into the list filtering? Something like this (of course, the c variable is evaluated as a string in the below example):

```<code> a = [ope for ope in operations if c]
</code>```

Thanks for help!

答:
eval is considered unsafe and is generally avoided.

You can use [filter][1] with functions. For this you should put your test conditions in a function.

Here's an example to create a list of numbers between 1 and 100 that are multiples of 3 and 7

```<code>def mult3(n):
    return n % 3 == 0

def mult7(n):
    return n % 7 == 0

def mult3_and_7(n):
    return mult3(n) and mult7(n)

list(filter(mult3_and_7, range(1, 101)))
</code>```

A more consice way is to use lambdas:

```<code>list(filter(lambda n: (n % 3 == 0) and (n % 7 == 0), range(1, 101))
</code>```

The cool thing is you can chain filters like so:

```<code>list(filter(lambda n: n % 3 == 0, filter(lambda n: n % 7 == 0, range(1, 101))))
</code>```

They all give [21, 42, 63, 84]

This approach should help you chain multiple conditions clearly.

Body:
I need to use the following syntax to filter the list operations:

a = [ope for ope in operations if ope[0] == 1]

The if statement condition is variable and may contain multiple conditions:

a = [ope for ope in operations if ope[0] == 1 and ope[1] == "test"]

I use a function to build the condition and return it as a string:

>>>> c = makeCondition(**{"id": 1, "title": 'test'})
>>>> c
"ope[0] == 1 and ope[1] == 'test'"

Is there a way to integrate the c variable into the list filtering? Something like this (of course, the c variable is evaluated as a string in the below example):

 a = [ope for ope in operations if c]

Thanks for help!

Body:
eval is considered unsafe and is generally avoided.

You can use [filter][1] with functions. For this you should put your test conditions in a function.

Here's an example to create a list of numbers between 1 and 100 that are multiples of 3 and 7

def mult3(n):
    return n % 3 == 0

def mult7(n):
    return n % 7 == 0

def mult3_and_7(n):
    return mult3(n) and mult7(n)

list(filter(mult3_and_7, range(1, 101)))

A more consice way is to use lambdas:

list(filter(lambda n: (n % 3 == 0) and (n % 7 == 0), range(1, 101))

The cool thing is you can chain filters like so:

list(filter(lambda n: n % 3 == 0, filter(lambda n: n % 7 == 0, range(1, 101))))

They all give [21, 42, 63, 84]

This approach should help you chain multiple conditions clearly.


问:
rJava 'class not found' error with makeCluster
I'm having this issue for a while now and can't find answers online. I try to execute makeCluster and somehow get this

Error in .jfindClass(as.character(driverClass)[1]) : class not found

```<code>library(doParallel)
library(foreach)
cores = makeCluster(2)
# Loading required package: methods
# Loading required package: DBI
# Loading required package: rJava
# Error in .jfindClass(as.character(driverClass)[1]) : class not found
# Calls: JDBC -> is.jnull -> .jfindClass
# Execution halted
</code>```

Would anyone be able to help? Thanks.

答:
In your console first File-->changedir into your jar file location

then you try this one

drv <- JDBC(driverClass="com.mysql.jdbc.Driver",
   classPath="mysql-connector-java-5.1.23-bin.jar",
   identifier.quote="`")

Body:
I'm having this issue for a while now and can't find answers online. I try to execute makeCluster and somehow get this

Error in .jfindClass(as.character(driverClass)[1]) : class not found

library(doParallel)
library(foreach)
cores = makeCluster(2)
# Loading required package: methods
# Loading required package: DBI
# Loading required package: rJava
# Error in .jfindClass(as.character(driverClass)[1]) : class not found
# Calls: JDBC -> is.jnull -> .jfindClass
# Execution halted

Would anyone be able to help? Thanks.


问:
Python import coding style
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

```<code>import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)
</code>```

I move all my imports into the function where they're actually used., like this:

```<code>def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)
</code>```

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

答:
A few problems with this approach:

It's not immediately obvious when opening the file which modules it depends on.

It will confuse programs that have to analyze dependencies, such as py2exe, py2app etc.

What about modules that you use in many functions? You will either end up with a lot of redundant imports or you'll have to have some at the top of the file and some inside functions.

So... the preferred way is to put all imports at the top of the file. I've found that if my imports get hard to keep track of, it usually means I have too much code that I'd be better off splitting it into two or more files.

Some situations where I have found imports inside functions to be useful:

To deal with circular dependencies (if you really really can't avoid them)

Platform specific code

Also: putting imports inside each function is actually not appreciably slower than at the top of the file. The first time each module is loaded it is put into sys.modules, and each subsequent import costs only the time to look up the module, which is fairly fast (it is not reloaded).

OwnerDisplayName: TokenMacGuy

Title: Python import coding style

Body:
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)

I move all my imports into the function where they're actually used., like this:

def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

OwnerDisplayName: dF

LastEditorDisplayName: dF


问:
iBatis Silent Failure to Map Columns
When I am mapping a POJO with iBatis such as below:

```<code>Person {
    String firstName
    String lastName;
}
</code>```

To the query:

```<code>select firstName, last_name from Person
</code>```

I am finding that Person.firstName is populated correctly whereas Person.lastName is null - this happens silently. I can introduce a ResultMap to fix the null issue (by translating last_name -> lastName), but I would like iBatis to throw an error when attempting to map rather than doing the best it can silently...

Does anyone know how I can do this?

Thanks!

答:
I see several issues.

I'm Blind!

The class Person {     String firstName     String lastName; }
provides exactly 0 visible elements to iBatis because iBatis neither extends Person nor shares the package of Person.  Consider the following:

```<code>public class Person
{
    private String firstName;
    private String lastName;

    public String getFirstName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public void setFirstName(final String newValue)
    {
        firstName = newValue;
    }

    public void setLastName(final String newValue)
    {
        lastName = newValue;
    }
}</code>```

Seperate and Not Equal

last_name is in no way the same as lastName.

Consider using a result map like the following:

```<code><resultMap id="theIdOfThisMap"
           class="Person">
    <result property="firstName" column="firstName"/>
    <result property="lastName" column="last_name"/>
</resultMap>

<select id="searchForEntities"
        resultMap="theIdOfThisMap">
    select
        firstName,
        last_name
    from
        PERSON
</select></code>```

Title: iBatis Silent Failure to Map Columns

Body:
When I am mapping a POJO with iBatis such as below:

Person {
    String firstName
    String lastName;
}

To the query:

select firstName, last_name from Person

I am finding that Person.firstName is populated correctly whereas Person.lastName is null - this happens silently. I can introduce a ResultMap to fix the null issue (by translating last_name -> lastName), but I would like iBatis to throw an error when attempting to map rather than doing the best it can silently...

Does anyone know how I can do this?

Thanks!

Body:
I see several issues.

I'm Blind!

The class Person {     String firstName     String lastName; }
provides exactly 0 visible elements to iBatis because iBatis neither extends Person nor shares the package of Person.  Consider the following:

public class Person
{
    private String firstName;
    private String lastName;

    public String getFirstName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public void setFirstName(final String newValue)
    {
        firstName = newValue;
    }

    public void setLastName(final String newValue)
    {
        lastName = newValue;
    }
}

Seperate and Not Equal

last_name is in no way the same as lastName.

Consider using a result map like the following:

<resultMap id="theIdOfThisMap"
           class="Person">
    <result property="firstName" column="firstName"/>
    <result property="lastName" column="last_name"/>
</resultMap>

<select id="searchForEntities"
        resultMap="theIdOfThisMap">
    select
        firstName,
        last_name
    from
        PERSON
</select>


问:
Best Practice to store link in string
I have two options how use the link for the application when I need to open the link in just simple browser.

Rather I save it in the strings.xml file as

```<code><string name="link_openBrowser_calendar" translatable="false">/schedule/</string>
</code>```

that looks quite ugly lets say or just to save it in the Constants.java file as

```<code>final static final String linkSchedule = "/schedule/";
</code>```

In some cases I have a lot of such links, that require additional parameter

```<code><string name="link_openBrowser_account_byId" translatable="false">
    /accounts/account/?id=%1$s
</string>
</code>```

or even more parameters

```<code><string name="view_meeting_time_inOneDay_period">%1$s at \n%2$s – %3$s</string>
</code>```

that is useful when part of the string need to be translated, but in the code it looks quite massive and hardly to read.

```<code>String time = mEvent.isAllDay() ? getString(R.string.view_meeting_time_inOneDay_allDay, isTodayStr)
                : getString(R.string.view_meeting_time_inOneDay_period, isTodayStr, startStr, finishStr);
</code>```

Which one of these methods is more productive in the ways of scalability, performance or just clearness? I believe at some point it matters where to store this links, while they are not used all the time and only need "on the go", rather I spend memory on storing them as static.

答: If you need text strings for your application with optional text styling and formatting, strings.xml is convenient. For instance, you can use it to translate your strings into other languages. Android takes a look at user preferences and selects the strings.xml file from the correct localization folder (values is the base one, values-xx stands for other languages). On the other hand, you should use a separate class (e.g., Constants.java) for other strings which you need to use in the global scope. Defining that kind of constant strings in Constants.java is the best practice.

Title: Best Practice to store link in string

Body:
I have two options how use the link for the application when I need to open the link in just simple browser.

Rather I save it in the strings.xml file as

<string name="link_openBrowser_calendar" translatable="false">/schedule/</string>

that looks quite ugly lets say or just to save it in the Constants.java file as

final static final String linkSchedule = "/schedule/";

In some cases I have a lot of such links, that require additional parameter

<string name="link_openBrowser_account_byId" translatable="false">
    /accounts/account/?id=%1$s
</string>

or even more parameters

<string name="view_meeting_time_inOneDay_period">%1$s at \n%2$s – %3$s</string>

that is useful when part of the string need to be translated, but in the code it looks quite massive and hardly to read.

String time = mEvent.isAllDay() ? getString(R.string.view_meeting_time_inOneDay_allDay, isTodayStr)
                : getString(R.string.view_meeting_time_inOneDay_period, isTodayStr, startStr, finishStr);

Which one of these methods is more productive in the ways of scalability, performance or just clearness? I believe at some point it matters where to store this links, while they are not used all the time and only need "on the go", rather I spend memory on storing them as static.


问:
AcousticEchoCanceler on Samsung devices not working
I have AcousticEchoCanceler working for VoIP calls for every other device type I've tried, but not on any Samsung device. The device reports AcousticEchoCanceler being available but it simply does nothing.

What I've got:

acousticEchoCanceler.setEnabled(true);

audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);

Audio session ID passed to AudioTrack

Sample rate: 16k

Tried both mono and stereo recording

<uses-permission android:name="android.permission.RECORD_AUDIO"/>

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>

Has anyone got AcousticEchoCanceler to work on a Samsung device?

答:
I had the same issue recently. The most important part for me was to use audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION) before creating the AudioRecord.

Next the AudioRecord was created with :

```<code>mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, mSamplingRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, audioRecordBufferSize);
</code>```

And finally create and enable the NS and AEC :

```<code>mNoiseSuppressor = NoiseSuppressor.create(mAudioRecord.getAudioSessionId());
if (mNoiseSuppressor != null) {
    int res = mNoiseSuppressor.setEnabled(true);
}

mAcousticEchoCanceler = AcousticEchoCanceler.create(mAudioRecord.getAudioSessionId());
if (mAcousticEchoCanceler != null) {
    int res = mAcousticEchoCanceler.setEnabled(true);
}
</code>```

The AudioTrack doesn't need to be associated to same Audio session ID than AudioTrack (I suppose it should be done automatically).

Body:
I had the same issue recently. The most important part for me was to use audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION) before creating the AudioRecord.

Next the AudioRecord was created with :

mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, mSamplingRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, audioRecordBufferSize);

And finally create and enable the NS and AEC :

mNoiseSuppressor = NoiseSuppressor.create(mAudioRecord.getAudioSessionId());
if (mNoiseSuppressor != null) {
    int res = mNoiseSuppressor.setEnabled(true);
}

mAcousticEchoCanceler = AcousticEchoCanceler.create(mAudioRecord.getAudioSessionId());
if (mAcousticEchoCanceler != null) {
    int res = mAcousticEchoCanceler.setEnabled(true);
}

The AudioTrack doesn't need to be associated to same Audio session ID than AudioTrack (I suppose it should be done automatically).


问:
Generating PEM private key file knowing n and d
For academic reasons I have succeeded to factor a small size RSA public key and extract n,p,q,e and then computed d. My question is, is there a way using python to generate a .pem private key file for the private key (d,n), in order to make it easy to verify the encryption/decryption goes well? </p>

答:
Late answer, but this script should help you achieve your goal. Here's what the author says about it:

Introduction

This is a Python script that fetches JWKS results, and for each jwk,
  uses the modulus and exponent to generate a PEM encoded public
  key, suitable for use in tools like jwt.io

Here is an example of using this tool to get the PEM encoded public
  keys for the "example.okta.com" Okta org:

```<code>./jwks_to_pem.py --org example.okta.com

Fetching JWKS from example.okta.com
PEM for KID 're7eOFV6SiygSbCyYHGGdERFCJ_EoNpi9Duv0FIxllo'
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgVdVgO4RogxtWt4XN2vO
9SG3Ekt6Qh+k6Io28dTNjEWuNxCYCtQI2dFtFs2y7OyLxQ2e3491XTDVRxtUx/Kl
RhQCcGDtLM5vTRWtGo39heg9dLWv7mqlk+jVkJrK2vAO+0bfl0x2Ouov4VS4Ixwx
lJfaec8v0cw+xjcJc29Y28WNFYhW/wpf1uEHYAf/pQ9q7S25rhK5yPv23101P7pA
bCNDyFB6PYLuXxqkE7dq7rIZXfw5xgNQBRugBrSmUEjoCFs3XowAXCk2gWhM/1Lg
mSqaaAh/Cu5vvzM0wYoaEi598LWYmtgurQ3C2Nenu8HVjI+zCSg8v7VrcTa1MHua
owIDAQAB
-----END PUBLIC KEY-----

PEM for KID 'kTP2cLZY0qA2qfnedNEgx6rs6yqIEdf4DQYYV2m4KPQ'
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjKb91FLaoZe9/5NEMZrO
1eDn4hdrhtjrvsy+qO1QIbbdhRXJIJoE+qpHmgmq1gK28OZCV51xUAwk8ugw5p7/
m2wIarykHtXuBmhcFPkWez6N/yX30qvdOPPKUGqd05AoGcrzAW6fV07CRROU+5g1
RnTdNasLEMYaq0xPlmCMDjb3usyiafGyyrwg4+tndOTry4uMtF7LeTVLZo9Tnn2x
dJiytWWh+Rq5/KAn1mJ2GgwG8tp8o7SRf65c0LYQenN1d6vXX/Iimq/mg//B5CHP
zIaUrZfoL+2sbRIyQ5AePlDyn8Neg6sIsV9nTkPAcYvvQsS+/8xnfNq6np0zKbua
dQIDAQAB
-----END PUBLIC KEY-----
</code>```

Body:
Late answer, but this script should help you achieve your goal. Here's what the author says about it:

Introduction

This is a Python script that fetches JWKS results, and for each jwk,
  uses the modulus and exponent to generate a PEM encoded public
  key, suitable for use in tools like jwt.io

Here is an example of using this tool to get the PEM encoded public
  keys for the "example.okta.com" Okta org:

./jwks_to_pem.py --org example.okta.com

Fetching JWKS from example.okta.com
PEM for KID 're7eOFV6SiygSbCyYHGGdERFCJ_EoNpi9Duv0FIxllo'
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgVdVgO4RogxtWt4XN2vO
9SG3Ekt6Qh+k6Io28dTNjEWuNxCYCtQI2dFtFs2y7OyLxQ2e3491XTDVRxtUx/Kl
RhQCcGDtLM5vTRWtGo39heg9dLWv7mqlk+jVkJrK2vAO+0bfl0x2Ouov4VS4Ixwx
lJfaec8v0cw+xjcJc29Y28WNFYhW/wpf1uEHYAf/pQ9q7S25rhK5yPv23101P7pA
bCNDyFB6PYLuXxqkE7dq7rIZXfw5xgNQBRugBrSmUEjoCFs3XowAXCk2gWhM/1Lg
mSqaaAh/Cu5vvzM0wYoaEi598LWYmtgurQ3C2Nenu8HVjI+zCSg8v7VrcTa1MHua
owIDAQAB
-----END PUBLIC KEY-----

PEM for KID 'kTP2cLZY0qA2qfnedNEgx6rs6yqIEdf4DQYYV2m4KPQ'
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjKb91FLaoZe9/5NEMZrO
1eDn4hdrhtjrvsy+qO1QIbbdhRXJIJoE+qpHmgmq1gK28OZCV51xUAwk8ugw5p7/
m2wIarykHtXuBmhcFPkWez6N/yX30qvdOPPKUGqd05AoGcrzAW6fV07CRROU+5g1
RnTdNasLEMYaq0xPlmCMDjb3usyiafGyyrwg4+tndOTry4uMtF7LeTVLZo9Tnn2x
dJiytWWh+Rq5/KAn1mJ2GgwG8tp8o7SRf65c0LYQenN1d6vXX/Iimq/mg//B5CHP
zIaUrZfoL+2sbRIyQ5AePlDyn8Neg6sIsV9nTkPAcYvvQsS+/8xnfNq6np0zKbua
dQIDAQAB
-----END PUBLIC KEY-----


问:
Cannot send command IR with HotPI
I bought a HotPi a while ago, and decided to use it. So I followed the procedure to configure the IR and after a few hours I was able to IR signals on my Raspberry 1.
But my purpose here is to send IR signals, which I tried, without any luck.

So this is the command I try to do (just for test):

```<code>irsend SEND_START devinput KEY_POWER ; sleep 3
</code>```

And this is what lircd tells me:

```<code>lircd-0.9.4c[907]: Notice: accepted new client on /var/run/lirc/lircd
lircd-0.9.4c[907]: Info: Cannot configure the rc device for /dev/lirc0
lircd-0.9.4c[907]: Error: invalid send buffer
lircd-0.9.4c[907]: Error: this remote configuration cannot be used to transmit
lircd-0.9.4c[907]: Error: error processing command: SEND_START devinput KEY_POWER
lircd-0.9.4c[907]: Error: transmission failed
lircd-0.9.4c[907]: Info: removed client
</code>```

Edit:
It seems I'm not using the good drivers. According to the HotPi documentation, I'm suppose to use lirc-rpi, which I'm suppos to install with

```<code>sudo modprobe lirc-rpi
</code>```

Which, at least, doesn't return an error. But trying to configure the interface tells me that the driver doesn't exist:

```<code>pi@raspberrypi:~ $ mode2 --driver lirc-rpi --device /dev/lirc0
Driver `lirc-rpi' not found. (Missing -U/--plugins option?)
Available drivers:
accent
alsa_usb
asusdh
atilibusb
atwf83
audio
audio_alsa
awlibusb
bte
bw6130
commandir
creative
creative_infracd
default
devinput
dfclibusb
dsp
dvico
ea65
file
ftdi
ftdi-exp
ftdix
girs
i2cuser
irlink
irtoy
livedrive_midi
livedrive_seq
logitech
macmini
mouseremote
mouseremote_ps2
mp3anywhere
mplay
mplay2
pcmak
pinsys
pixelview
samsung
sb0540
silitek
slinke
sonyir
srm7500libusb
tira
tira_raw
udp
uirt2
uirt2_raw
usb_uirt_raw
usbx
zotac
</code>```

答:
Here is no info what lirc version you are using. There are vast differences between the legacy 0.9.0 still used in some distros and modern lirc.

That said, the logs seems pretty clear. You are using the devinput driver, right? This driver does not support sending data, reflecting the fact that also the kernel doesn't.

You then need to use another driver - first stop might be the default one. If/when using this other driver, you need another lircd.conf.

Please refer to  http://lirc.org/html/configuration-guide.html

EDIT: Ah, lirc-0.9.4c says the log. Sorry, my bad. The reply should still be valid, though.

Title: Cannot send command IR with HotPI

Body:
I bought a HotPi a while ago, and decided to use it. So I followed the procedure to configure the IR and after a few hours I was able to IR signals on my Raspberry 1.
But my purpose here is to send IR signals, which I tried, without any luck.

So this is the command I try to do (just for test):

irsend SEND_START devinput KEY_POWER ; sleep 3

And this is what lircd tells me:

lircd-0.9.4c[907]: Notice: accepted new client on /var/run/lirc/lircd
lircd-0.9.4c[907]: Info: Cannot configure the rc device for /dev/lirc0
lircd-0.9.4c[907]: Error: invalid send buffer
lircd-0.9.4c[907]: Error: this remote configuration cannot be used to transmit
lircd-0.9.4c[907]: Error: error processing command: SEND_START devinput KEY_POWER
lircd-0.9.4c[907]: Error: transmission failed
lircd-0.9.4c[907]: Info: removed client

Edit:
It seems I'm not using the good drivers. According to the HotPi documentation, I'm suppose to use lirc-rpi, which I'm suppos to install with

sudo modprobe lirc-rpi

Which, at least, doesn't return an error. But trying to configure the interface tells me that the driver doesn't exist:

pi@raspberrypi:~ $ mode2 --driver lirc-rpi --device /dev/lirc0
Driver `lirc-rpi' not found. (Missing -U/--plugins option?)
Available drivers:
accent
alsa_usb
asusdh
atilibusb
atwf83
audio
audio_alsa
awlibusb
bte
bw6130
commandir
creative
creative_infracd
default
devinput
dfclibusb
dsp
dvico
ea65
file
ftdi
ftdi-exp
ftdix
girs
i2cuser
irlink
irtoy
livedrive_midi
livedrive_seq
logitech
macmini
mouseremote
mouseremote_ps2
mp3anywhere
mplay
mplay2
pcmak
pinsys
pixelview
samsung
sb0540
silitek
slinke
sonyir
srm7500libusb
tira
tira_raw
udp
uirt2
uirt2_raw
usb_uirt_raw
usbx
zotac


问:
Misalignment of Facebook & Twitter buttons
The page contains two buttons, from twitter and from facebook.

What I'm observing in Firefox 3.5.15 is:

While the page is loading, the buttons are more or less aligned (I mean their bottom sides)

When the page is loaded, the facebook button moves a few pixels down, so that it's bottom side is lower than the bottom side of the twitter button.

If I reload the page, the buttons are again aligned, and remain in this state even after the page is loaded.

Can someone please explain what's going on and how to fix it?

答:
I can't tell you what's going on in there and I don't even want to think about what < fb:headache > does there, but you should be able to resolve this issue by floating the iframe for the twitter button left and adding some margin-right to get the original look back.

```<code>iframe.twitter-share-button { float: left; margin-right: 4px; }
</code>```

It's a little hackish, but should do.

UPDATE

```<code>.fb_iframe_widget { display: block !important; }
// leave important away if possible!

// change main.css / line 41:
div.text {
    clear: left;
    margin: 0 auto;
    padding: 35pt 5pt 15pt;
    width: 40em;
}
</code>```

Body:
I can't tell you what's going on in there and I don't even want to think about what < fb:headache > does there, but you should be able to resolve this issue by floating the iframe for the twitter button left and adding some margin-right to get the original look back.

iframe.twitter-share-button { float: left; margin-right: 4px; }

It's a little hackish, but should do.

UPDATE

.fb_iframe_widget { display: block !important; }
// leave important away if possible!

// change main.css / line 41:
div.text {
    clear: left;
    margin: 0 auto;
    padding: 35pt 5pt 15pt;
    width: 40em;
}


问:
Uri is not supported when saving pdf in server folder with nreco pdf generator
I have the following code:

```<code>var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "~/files/";
htmlToPdf.GeneratePdf(template);
</code>```

Which throws the following error:

Uri is not supported when saving pdf in server folder with nreco pdf generator.

答:
You will need to set a regular path to your file system like e.g. "C:\temp\myfolder\". Or use a . instead of ~ and backslashes:

```<code>htmlToPdf.PdfToolPath = ".\\files\\";
</code>```

If NReco is able to deliver you an byte-array or a stream you should prefer this instead of a file and return it directly.

UPDATE:

After takeing a look into the documentation of NReco all you need to do is following:

```<code>var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "<CORRECT_PATH_FOR_TOOL>";
var output = htmlToPdf.GeneratePdf(template);
System.IO.File.WriteAllBytes("<OUTPUT_PATH>", output);
</code>```

This should create your pdf in the OUTPUT_PATH.

Body:
I have the following code:

var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "~/files/";
htmlToPdf.GeneratePdf(template);

Which throws the following error:

Uri is not supported when saving pdf in server folder with nreco pdf generator.

Body:
You will need to set a regular path to your file system like e.g. "C:\temp\myfolder\". Or use a . instead of ~ and backslashes:

htmlToPdf.PdfToolPath = ".\\files\\";

If NReco is able to deliver you an byte-array or a stream you should prefer this instead of a file and return it directly.

UPDATE:

After takeing a look into the documentation of NReco all you need to do is following:

var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "<CORRECT_PATH_FOR_TOOL>";
var output = htmlToPdf.GeneratePdf(template);
System.IO.File.WriteAllBytes("<OUTPUT_PATH>", output);

This should create your pdf in the OUTPUT_PATH.


问:
ADO.net connector: Delete command return Invalid value for column: Expected INT64
Hey guys anyone run into this issue where the ADO.net connector returns "Invalid value for column: Expected INT64" when the column parameters are ordered in some other ways:

Error details:
  "Operation was rejected because the system is not in a state required for the operation's execution.
  Status(StatusCode=FailedPrecondition, Detail="Invalid value for column GeographyKey in table Table1: Expected INT64.")"

```<code>var qry = "DELETE Table1";
var col = new SpannerParameterCollection();
col.Add("CustomerKey", SpannerDbType.Int64, 0);
col.Add("EmailAddress", SpannerDbType.String, "some@email.com");
col.Add("GeographyKey", SpannerDbType.Int64, 37);
</code>```

This one throws error on CustomerKey:

```<code>var qry = "DELETE Table1";
var col = new SpannerParameterCollection();
col.Add("EmailAddress", SpannerDbType.String, "some@email.com");
col.Add("GeographyKey", SpannerDbType.Int64, 37);
col.Add("CustomerKey", SpannerDbType.Int64, 0);
</code>```

But when the columns are arrange this way, moving the GeographyKey and CustomerKey in the first list, it doesn't throw an error

```<code>var qry = "DELETE Table1";
var col = new SpannerParameterCollection();
col.Add("GeographyKey", SpannerDbType.Int64, 37);
col.Add("CustomerKey", SpannerDbType.Int64, 0);
col.Add("EmailAddress", SpannerDbType.String, "some@email.com");
</code>```

答:
A delete mutation takes a KeySet as its only argument. A KeySet does not include the column names, only the values of the key. It is therefore required that you specify the key values in the order of the key columns of the table. Have a look here for a specification of the method that is being called under the hood: https://cloud.google.com/spanner/docs/reference/rest/v1/projects.instances.databases.sessions/commit#Delete

I am not familiar with the ADO.NET connector, but even if you are able to specify key values using a combination of column name and value in the ADO.NET API, in the end only the key values will be sent to Cloud Spanner.

Body:
Hey guys anyone run into this issue where the ADO.net connector returns "Invalid value for column: Expected INT64" when the column parameters are ordered in some other ways:

Error details:
  "Operation was rejected because the system is not in a state required for the operation's execution.
  Status(StatusCode=FailedPrecondition, Detail="Invalid value for column GeographyKey in table Table1: Expected INT64.")"

var qry = "DELETE Table1";
var col = new SpannerParameterCollection();
col.Add("CustomerKey", SpannerDbType.Int64, 0);
col.Add("EmailAddress", SpannerDbType.String, "some@email.com");
col.Add("GeographyKey", SpannerDbType.Int64, 37);

This one throws error on CustomerKey:

var qry = "DELETE Table1";
var col = new SpannerParameterCollection();
col.Add("EmailAddress", SpannerDbType.String, "some@email.com");
col.Add("GeographyKey", SpannerDbType.Int64, 37);
col.Add("CustomerKey", SpannerDbType.Int64, 0);

But when the columns are arrange this way, moving the GeographyKey and CustomerKey in the first list, it doesn't throw an error

var qry = "DELETE Table1";
var col = new SpannerParameterCollection();
col.Add("GeographyKey", SpannerDbType.Int64, 37);
col.Add("CustomerKey", SpannerDbType.Int64, 0);
col.Add("EmailAddress", SpannerDbType.String, "some@email.com");


问:
npm request moudule not giving the output
Why when I run the npm request module the output I get is undefined?

```<code>const request = require('request');
request({
  url: 'https://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia',
  json: true
  }, (error, response, body) => {
     console.log(body);
});
</code>```

答:
Seems like your code should work properly if request is installed. The possible reason why you get undefined is a problem with your internet connection.

Start with checking if you can access Internet at all. You can try this code:

```<code> require('dns').resolve('www.google.com', function(err) {
   if (err) {
     console.log("No connection");
   } else {
     console.log("Connected");
     }
 });
</code>```

Body:
Why when I run the npm request module the output I get is undefined?

const request = require('request');
request({
  url: 'https://maps.googleapis.com/maps/api/geocode/json?address=1301%20lombard%20street%20philadelphia',
  json: true
  }, (error, response, body) => {
     console.log(body);
});

Body:
Seems like your code should work properly if request is installed. The possible reason why you get undefined is a problem with your internet connection.

Start with checking if you can access Internet at all. You can try this code:

 require('dns').resolve('www.google.com', function(err) {
   if (err) {
     console.log("No connection");
   } else {
     console.log("Connected");
     }
 });


问:
How can I get an IBeam cursor in an XNA Game?
I've managed to get the cursor to change to an IBeam in a trivial XNA 'Game' with Update as:

```<code>protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here

        if (Keyboard.GetState().IsKeyDown(Keys.A))
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Arrow;
        }
        if (Keyboard.GetState().IsKeyDown(Keys.I))
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.IBeam;
        }

        base.Update(gameTime);
    }
</code>```

The mouse changes to the IBeam cursor when 'I' is pressed, but immediately changes back to an arrow when you move the mouse. Is there a way to get it to stay as the default Windows IBeam, or will I need to create and track a custom cursor?

[EDIT] I should also point out that setting the cursor every single frame causes it to flicker when the mouse is moved. It seems the XNA (or Windows) is internally resetting the cursor to an arrow every frame?

答:
Before resorting to drawing it manually, I'd try to set the Cursor property of the underlying System.Windows.Forms.Form:

```<code>Form f = (Form)Control.FromHandle(Game.Window.Handle);
f.Cursor = System.Windows.Forms.Cursors.IBeam;
</code>```

As I don't have XNA installed right now, I don't know if this will work, or if it will be permenant, but I don't see why it wouldn't.

Body:
I've managed to get the cursor to change to an IBeam in a trivial XNA 'Game' with Update as:

protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here

        if (Keyboard.GetState().IsKeyDown(Keys.A))
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Arrow;
        }
        if (Keyboard.GetState().IsKeyDown(Keys.I))
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.IBeam;
        }

        base.Update(gameTime);
    }

The mouse changes to the IBeam cursor when 'I' is pressed, but immediately changes back to an arrow when you move the mouse. Is there a way to get it to stay as the default Windows IBeam, or will I need to create and track a custom cursor?

[EDIT] I should also point out that setting the cursor every single frame causes it to flicker when the mouse is moved. It seems the XNA (or Windows) is internally resetting the cursor to an arrow every frame?

Body:
Before resorting to drawing it manually, I'd try to set the Cursor property of the underlying System.Windows.Forms.Form:

Form f = (Form)Control.FromHandle(Game.Window.Handle);
f.Cursor = System.Windows.Forms.Cursors.IBeam;

As I don't have XNA installed right now, I don't know if this will work, or if it will be permenant, but I don't see why it wouldn't.


问:
Python OpenCV - Trying to identify a completely visible tile (all four edges are visible) and draw a green contour edges
I am working on a project to click images of the tiles and using OpenCV to to find out that the tile is visit-able or not.

Accessible tile should be shown as below -

In the image below tile is not visit-able.

Code i have written is identifying multiple contours.

```<code>import numpy as np
import cv2

image1  = cv2.imread('floor3.jpg')#, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
orig = image1.copy()
cv2.imshow("Game Boy Screen", orig)
cv2.waitKey(0)

gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
edged = cv2.Canny(gray, 30, 200)
flag, thresh = cv2.threshold(edged, 120, 255, cv2.THRESH_BINARY)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy = []

height, width, _ = image1.shape
min_x, min_y = width, height
max_x = max_y = 0

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
    (x,y,w,h) = cv2.boundingRect(contour)
    min_x, max_x = min(x, min_x), max(x+w, max_x)
    min_y, max_y = min(y, min_y), max(y+h, max_y)
    if w > 80 and h > 80:
        cv2.rectangle(orig, (x,y), (x+w,y+h), (255, 0, 0), 2)

if max_x - min_x > 0 and max_y - min_y > 0:
    cv2.rectangle(orig, (min_x, min_y), (max_x, max_y), (255, 0, 0), 3)

cv2.imshow("Game Boy Screen", orig)
cv2.waitKey(0)
</code>```

Below is the output i am getting -

Original image:

答:
Original:

First, you should also put your original image.

Second, using minAreaRect other than boundingRect to find the rotated rectangles.

Update:

I don't think do findContours on Canny edges is a good idea. I just do it on threshed binary image, then remove the contours with small area. So we can get the boundary of regions.Then how to judge whether the region is complete or not, it's upto your math knowledge.

```<code>#!/usr/bin/python3
# 2017.12.09 00:25:47 CST
# 2017.12.09 14:26:01 CST
import cv2
import numpy as np

img = cv2.imread("test.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
th, threshed = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
cnts = cv2.findContours(threshed,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas = np.zeros_like(img, np.uint8)
H,W = img.shape[:2]
AREA = H*W
for cnt in cnts:
    area = cv2.contourArea(cnt)
    if(area<AREA/100):
        continue
    _ = cv2.drawContours(canvas, [cnt], -1, (0,255,0), 1, cv2.LINE_AA)

cv2.imwrite("result.png", canvas)
</code>```

Update 2:
After get the contours of regions, then how to judge whether it's complete or not?

You should define what is complete? In this situation, the complete tile means it is a quadrilateral, four corner points, almost equal lengths of side. Then you program the condition to tell the computer how to judge. It's your job, you should try to solve it by yourself first.

Total code and the result:

```<code>#!/usr/bin/python3
# 2017.12.09 00:25:47 CST
# 2017.12.09 14:26:01 CST
# 2017.12.09 17:52:17 CST
import cv2
import numpy as np

## lambda: calc distance
dist = lambda pt1, pt2: ((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)**0.5

img = cv2.imread("img04.jpg")

## (1) filter, threshed
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
th, threshed = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)

## (2) findContours
cnts = cv2.findContours(threshed,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]

## (3) some variables
H,W = img.shape[:2]
AREA = H*W
xcnts = []
R = 0.8

## (4) judge wether the contour is belongs to a complete tile
for cnt in cnts:
    ## （4.1） filter by area
    area = cv2.contourArea(cnt)
    if(area<AREA/100):
        continue
    ## （4.2） calc arpprox contour
    arclen = cv2.arcLength(cnt, closed=True)
    approx = cv2.approxPolyDP(cnt, arclen*0.02, closed=True)
    ## （4.3） filter by "complete ruler"
    ## "the complete tile means it is a quadrilateral, four corner points, almost equal lengths of side"
    pts = np.array(approx).reshape(-1,2)
    if len(pts) == 4:
        lens = np.array(list(dist(pts[i], pts[(i+1)%4]) for i in range(4)))
        flag = True
        for x in lens:
            if not (R< x/lens[0] < 1.0/R):
                flag = False
                continue
        if flag:
            xcnts.append(cnt)

## (5) draw and save
res = img.copy()
for cnt in xcnts:
    cv2.drawContours(res, [cnt], -1, (0,255,0), -1, cv2.LINE_AA)
cv2.imwrite("00result.png", res)
</code>```

Update 3 (The last update):

I use the fixed threshed value in the my code just because your image contains a large dark origin. As for this image

,

there is no large dark, so change the threshold flag to cv2.THRESH_OTSU， and modify the area thresh to AREA/20 or larger, modify the R smaller such as R=0.7.

Then I get the result:

Similar questions:

(1) How to find the object on the noisy background?

(2) Python OpenCV - Trying to identify a completely visible tile (all four edges are visible) and draw a green contour edges

Body:
I am working on a project to click images of the tiles and using OpenCV to to find out that the tile is visit-able or not.

Accessible tile should be shown as below -

In the image below tile is not visit-able.

Code i have written is identifying multiple contours.

import numpy as np
import cv2

image1  = cv2.imread('floor3.jpg')#, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
orig = image1.copy()
cv2.imshow("Game Boy Screen", orig)
cv2.waitKey(0)

gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
edged = cv2.Canny(gray, 30, 200)
flag, thresh = cv2.threshold(edged, 120, 255, cv2.THRESH_BINARY)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

try: hierarchy = hierarchy[0]
except: hierarchy = []

height, width, _ = image1.shape
min_x, min_y = width, height
max_x = max_y = 0

# computes the bounding box for the contour, and draws it on the frame,
for contour, hier in zip(contours, hierarchy):
    (x,y,w,h) = cv2.boundingRect(contour)
    min_x, max_x = min(x, min_x), max(x+w, max_x)
    min_y, max_y = min(y, min_y), max(y+h, max_y)
    if w > 80 and h > 80:
        cv2.rectangle(orig, (x,y), (x+w,y+h), (255, 0, 0), 2)

if max_x - min_x > 0 and max_y - min_y > 0:
    cv2.rectangle(orig, (min_x, min_y), (max_x, max_y), (255, 0, 0), 3)

cv2.imshow("Game Boy Screen", orig)
cv2.waitKey(0)

Below is the output i am getting -

Original image:

Body:
Original:

First, you should also put your original image.

Second, using minAreaRect other than boundingRect to find the rotated rectangles.

Update:

I don't think do findContours on Canny edges is a good idea. I just do it on threshed binary image, then remove the contours with small area. So we can get the boundary of regions.Then how to judge whether the region is complete or not, it's upto your math knowledge.

#!/usr/bin/python3
# 2017.12.09 00:25:47 CST
# 2017.12.09 14:26:01 CST
import cv2
import numpy as np

img = cv2.imread("test.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
th, threshed = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
cnts = cv2.findContours(threshed,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas = np.zeros_like(img, np.uint8)
H,W = img.shape[:2]
AREA = H*W
for cnt in cnts:
    area = cv2.contourArea(cnt)
    if(area<AREA/100):
        continue
    _ = cv2.drawContours(canvas, [cnt], -1, (0,255,0), 1, cv2.LINE_AA)

cv2.imwrite("result.png", canvas)

Update 2:
After get the contours of regions, then how to judge whether it's complete or not?

You should define what is complete? In this situation, the complete tile means it is a quadrilateral, four corner points, almost equal lengths of side. Then you program the condition to tell the computer how to judge. It's your job, you should try to solve it by yourself first.

Total code and the result:

#!/usr/bin/python3
# 2017.12.09 00:25:47 CST
# 2017.12.09 14:26:01 CST
# 2017.12.09 17:52:17 CST
import cv2
import numpy as np

## lambda: calc distance
dist = lambda pt1, pt2: ((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)**0.5

img = cv2.imread("img04.jpg")

## (1) filter, threshed
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
th, threshed = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)

## (2) findContours
cnts = cv2.findContours(threshed,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]

## (3) some variables
H,W = img.shape[:2]
AREA = H*W
xcnts = []
R = 0.8

## (4) judge wether the contour is belongs to a complete tile
for cnt in cnts:
    ## （4.1） filter by area
    area = cv2.contourArea(cnt)
    if(area<AREA/100):
        continue
    ## （4.2） calc arpprox contour
    arclen = cv2.arcLength(cnt, closed=True)
    approx = cv2.approxPolyDP(cnt, arclen*0.02, closed=True)
    ## （4.3） filter by "complete ruler"
    ## "the complete tile means it is a quadrilateral, four corner points, almost equal lengths of side"
    pts = np.array(approx).reshape(-1,2)
    if len(pts) == 4:
        lens = np.array(list(dist(pts[i], pts[(i+1)%4]) for i in range(4)))
        flag = True
        for x in lens:
            if not (R< x/lens[0] < 1.0/R):
                flag = False
                continue
        if flag:
            xcnts.append(cnt)

## (5) draw and save
res = img.copy()
for cnt in xcnts:
    cv2.drawContours(res, [cnt], -1, (0,255,0), -1, cv2.LINE_AA)
cv2.imwrite("00result.png", res)

Update 3 (The last update):

I use the fixed threshed value in the my code just because your image contains a large dark origin. As for this image

,

there is no large dark, so change the threshold flag to cv2.THRESH_OTSU， and modify the area thresh to AREA/20 or larger, modify the R smaller such as R=0.7.

Then I get the result:

Similar questions:

(1) How to find the object on the noisy background?

(2) Python OpenCV - Trying to identify a completely visible tile (all four edges are visible) and draw a green contour edges


问:
How i can style SVG <use> elements on hover?
I'm beginner in SVG. I'm trying to change style of multiple <use> elements on hover at a specific <use> element with css, but I can't, because <use> elements using Shadow DOM.

I have the following <defs>:

<defs>
    <filter id="Sjax0b81q1" filterUnits="userSpaceOnUse">...</filter>
    <circle cx="0" cy="0" r="40" id="action-circle" style="cursor: move; fill: #fff;" filter="url('#Sjax0b81q1')" class="el action-el"></circle>
    <g id="condition-rhombus" style="cursor: move; fill: #fff;" class="el condition-el" transform="matrix(1,0,0,1,0,0)">
        <circle cx="0" cy="0" r="40" fill="none"></circle>
        <path d="M -35 0, L 0 -35, L 35 0, L 0 35 L -35 0" style="stroke-linecap: round; stroke: white;" filter="url('#Sjax0b81q1')" class="condition-rhombus"></path>
    </g>
    <g id="svg-plus-button">
        <circle cx="0" cy="40" r="10" id="svg-plus-circle" fill="none" style="fill-opacity: 1;" class="svg-plus-circle"></circle>
        <path d="M956.8,408.....408.5z" id="svg-plus-sign" fill="none" transform="matrix(0.008,0,0,0.008,-4,36)" style="pointer-events: none;" class="svg-plus-sign"></path>
    </g>
    <rect x="-20" y="-20" width="40" height="40" id="rect-active-layer" fill="none" style="pointer-events: visible;" class="rect-active-layer"></rect>
    <path d="M252.967.....2v1Z" id="api-svg" class="cls-1"></path>
</defs>
```
<p>And I have a group of elements that contains several <code><use></code> elements:</p>
<pre class="lang-xml prettyprint-override"><code><g id="action-group-2" class="external action-group" transform="matrix(1,0,0,1,420,180)">
    <g class="internal action-group">
        <rect x="-40" y="-40" width="80" height="80" fill="none"></rect>
    </g>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#action-circle"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#svg-plus-button" id="useSjax0b81q1k"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#rect-active-layer"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#api-svg"></use>
</g>
</code>```

For example, I need to change the <path> fill in element with id #api-svg, when I hover on the #action-circle.

How can I do this? Maybe there is another way to render and styling reusable elements on hover.

答:
There's nothing overly complex here. Just change the 'use' element, rather than anything in the defs area (unless you want it to affect everything that references it).

You can either style the use element via normal css, via a css selector, e.g it's id is possibly simplest.

Or you can set the fill svg attribute on the svg 'use' element you are handling.

You shouldn't need fill inherit or anything unless I'm missing something.

Body:
I'm beginner in SVG. I'm trying to change style of multiple <use> elements on hover at a specific <use> element with css, but I can't, because <use> elements using Shadow DOM.

I have the following <defs>:

<defs>
    <filter id="Sjax0b81q1" filterUnits="userSpaceOnUse">...</filter>
    <circle cx="0" cy="0" r="40" id="action-circle" style="cursor: move; fill: #fff;" filter="url('#Sjax0b81q1')" class="el action-el"></circle>
    <g id="condition-rhombus" style="cursor: move; fill: #fff;" class="el condition-el" transform="matrix(1,0,0,1,0,0)">
        <circle cx="0" cy="0" r="40" fill="none"></circle>
        <path d="M -35 0, L 0 -35, L 35 0, L 0 35 L -35 0" style="stroke-linecap: round; stroke: white;" filter="url('#Sjax0b81q1')" class="condition-rhombus"></path>
    </g>
    <g id="svg-plus-button">
        <circle cx="0" cy="40" r="10" id="svg-plus-circle" fill="none" style="fill-opacity: 1;" class="svg-plus-circle"></circle>
        <path d="M956.8,408.....408.5z" id="svg-plus-sign" fill="none" transform="matrix(0.008,0,0,0.008,-4,36)" style="pointer-events: none;" class="svg-plus-sign"></path>
    </g>
    <rect x="-20" y="-20" width="40" height="40" id="rect-active-layer" fill="none" style="pointer-events: visible;" class="rect-active-layer"></rect>
    <path d="M252.967.....2v1Z" id="api-svg" class="cls-1"></path>
</defs>

And I have a group of elements that contains several <use> elements:

<g id="action-group-2" class="external action-group" transform="matrix(1,0,0,1,420,180)">
    <g class="internal action-group">
        <rect x="-40" y="-40" width="80" height="80" fill="none"></rect>
    </g>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#action-circle"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#svg-plus-button" id="useSjax0b81q1k"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#rect-active-layer"></use>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#api-svg"></use>
</g>

For example, I need to change the <path> fill in element with id #api-svg, when I hover on the #action-circle.

How can I do this? Maybe there is another way to render and styling reusable elements on hover.


问:
How to attach new policies in AWS?
I want to add 3 new policies to my IAM user

I have problems here

No results,can not detect User Name.

答:
You could try creating a role with all the policies you want attached, and attaching that role to the user.
Attaching policies directly to a user is not really a best practice

An IAM role is similar to a user, in that it is an AWS identity with
  permission policies that determine what the identity can and cannot do
  in AWS. However, instead of being uniquely associated with one person,
  a role is intended to be assumable by anyone who needs it. Also, a
  role does not have standard long-term credentials (password or access
  keys) associated with it. Instead, if a user assumes a role, temporary
  security credentials are created dynamically and provided to the user.

More can be found Here

Title: How to attach new policies in AWS?


问:
Angular: How to extract parameters from child routes?
Let's say I've this table

```<code>+--------------------+-------+----------+---------+
| Label | Date       | Items | Location |         |
+-------+------------+-------+----------+---------+
| REF 1 | 12/12/2017 | 3     | Floor 1  | Details |
+-------+------------+-------+----------+---------+
| TXD 7 | 12/31/2017 | 1     | Floor 3  | Details |
+-------+------------+-------+----------+---------+
</code>```

Details is a button. When user clicks the the Details button, div with tabs should display on the bottom.

```<code>+------------------------+
| TAB 1  | TAB 2 | TAB 3 |
+--------+-------+-------+------------------------+
|                                                 |
| Content of the TAB 1                            |
|                                                 |
|                                                 |
+-------------------------------------------------+
</code>```

Here's the routing

```<code>RouterModule.forChild([
  {
    path: 'gift', component: GiftComponent,
  },
  {
    path: 'gift/:id', component: GiftComponent,
    children: [
      { path: '', redirectTo: 'giftItemList', pathMatch: 'full'},
      { path: 'giftItemList', component: GiftItemListComponent },
      { path: 'giftItemDetails', component: GiftItemDetailsComponent }
    ]
  }
])
</code>```

When user the Gift link from the menu
Gift
, the gift component is displayed. Only the upper portion is displayed.

If the user clicks the Details button,

```<code> <td>
     <button (click)="displayGiftItems(gift.id)" class="btn btn-link">
        Details
     </button>
</td>
</code>```

Then displayGiftItems function from the component is called. It makes the the surrounding DIV visible where the child component will be displayed. Then it navigate to the child component.

```<code> displayGiftItems(id: number, e) {
if (id) {
  this.giftItemsPanelIsVisible = true;
  this.router.navigate(['giftItemList'], { relativeTo: this.route});
}
</code>```

}

When I click the Details button, the url doesn't have this form: gift/1/giftItemList.

How to get such url and how to extract parameters from this url?

Thanks for helping

答:
You could try something like this:

```<code>displayGiftItems(id: number, e) {
if (id) {
  this.giftItemsPanelIsVisible = true;
  this.router.navigate(['gift', id, 'giftItemList']);
}
</code>```

You then read it something like this:

```<code>const id = route.paramMap.get('id');
</code>```

For more information, see this post:
Sending data with route.navigate in Angular 2

Body:
Let's say I've this table

+--------------------+-------+----------+---------+
| Label | Date       | Items | Location |         |
+-------+------------+-------+----------+---------+
| REF 1 | 12/12/2017 | 3     | Floor 1  | Details |
+-------+------------+-------+----------+---------+
| TXD 7 | 12/31/2017 | 1     | Floor 3  | Details |
+-------+------------+-------+----------+---------+

Details is a button. When user clicks the the Details button, div with tabs should display on the bottom.

+------------------------+
| TAB 1  | TAB 2 | TAB 3 |
+--------+-------+-------+------------------------+
|                                                 |
| Content of the TAB 1                            |
|                                                 |
|                                                 |
+-------------------------------------------------+

Here's the routing

RouterModule.forChild([
  {
    path: 'gift', component: GiftComponent,
  },
  {
    path: 'gift/:id', component: GiftComponent,
    children: [
      { path: '', redirectTo: 'giftItemList', pathMatch: 'full'},
      { path: 'giftItemList', component: GiftItemListComponent },
      { path: 'giftItemDetails', component: GiftItemDetailsComponent }
    ]
  }
])

When user the Gift link from the menu
Gift
, the gift component is displayed. Only the upper portion is displayed.

If the user clicks the Details button,

     <button (click)="displayGiftItems(gift.id)" class="btn btn-link">
        Details
     </button>

Then displayGiftItems function from the component is called. It makes the the surrounding DIV visible where the child component will be displayed. Then it navigate to the child component.

 displayGiftItems(id: number, e) {
if (id) {
  this.giftItemsPanelIsVisible = true;
  this.router.navigate(['giftItemList'], { relativeTo: this.route});
}

}

When I click the Details button, the url doesn't have this form: gift/1/giftItemList.

How to get such url and how to extract parameters from this url?

Thanks for helping

Body:
You could try something like this:

displayGiftItems(id: number, e) {
if (id) {
  this.giftItemsPanelIsVisible = true;
  this.router.navigate(['gift', id, 'giftItemList']);
}

You then read it something like this:

const id = route.paramMap.get('id');

For more information, see this post:
Sending data with route.navigate in Angular 2


问:
python-dev installation without package management?
I must install python-dev on my embedded linux machine, which runs python-2.7.2. The linux flavor is custom-built by TimeSys; uname -a gives:
Linux hotspot-smc 2.6.32-ts-armv7l-LRI-6.0.0 #1 Mon Jun 25 18:12:45 UTC 2012 armv7l GNU/Linux

The platform does not have package management such as 'yum' or 'apt-get', and for various reasons I prefer not to install one. It does have gcc.

Does python-dev source contain C/C++ code? Can I download python-dev source code as a .tar.gz file, for direct compilation on this machine? I have looked for the source but haven't been able to find it.

Thanks,
Tom

答:
You have to use </p>

```<code>./configure --enable-shared
</code>```

Body:
You have to use

./configure --enable-shared


问:
Create Next/Previous node links in a node-panel in Drupal?
So I am on a seemingly simple mission of creating previous/next buttons for a type of nodes, like for pages in a book. Sounds easy enough, considering that there is the Custom Pager module. But, the module does not work for nodes which are built using panels, as described in this bug: http://drupal.org/node/591782

There is another module which creates an API for this operation, but it does not seem to have custom sorting based on a view.

Any ideas would be highly appreciated and thank you in advance.

答: What about using the views module (and its built-in pager functionality) to display a single node at a time?</p>


问:
FluentFTP - Getting error while connecting "Timed out trying to read data from the socket stream!"
Getting

Timed out trying to read data from the socket stream!

when connecting to FTP using FluentFTP.

Below is the source code which I am using to connect:

```<code>Console.WriteLine("Configuring FTP to Connect to {0}", hostname);
ftp = new FtpClient(hostname,port,new NetworkCredential(username,password));
ftp.ConnectTimeout = 600000;
ftp.ReadTimeout = 60000;
ftp.EncryptionMode = FtpEncryptionMode.Explicit;
ftp.SslProtocols = System.Security.Authentication.SslProtocols.Tls;
ftp.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
ftp.Connect();
Console.WriteLine("Connected to {0}", hostname);

ftp.SetWorkingDirectory(foldername);
Console.WriteLine("Changed directory to {0}", foldername);
</code>```

```<code>void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e)
{
    // add logic to test if certificate is valid here
    e.Accept = true;
}
</code>```

FileZilla log file for successful connectivity. I am able to connect the location via FileZilla. Snippet of log is below:

2017-12-08 13:34:33 17672 1 Status: Connecting to xx.xx.xx.xx:990...
2017-12-08 13:34:33 17672 1 Status: Connection established, initializing TLS...
2017-12-08 13:34:33 17672 1 Status: Verifying certificate...
2017-12-08 13:35:06 17672 1 Status: TLS connection established, waiting for welcome message...
2017-12-08 13:35:06 17672 1 Response: 220-Microsoft FTP Service
2017-12-08 13:35:06 17672 1 Status: Invalid character sequence received, disabling UTF-8. Select UTF-8 option in site manager to force UTF-8.
2017-12-08 13:35:06 17672 1 Response:     Warning: This IT system is restricted to company authorised users only, including authorised third parties. Unauthorised access or use is a violation of Company’s policies and potentially the law.
2017-12-08 13:35:06 17672 1 Response:
2017-12-08 13:35:06 17672 1 Response: 220 Our IT systems may be monitored for administrative and security reasons. By proceeding, you acknowledge that you have read and understood this notice and that you consent to the monitoring. [ftps0]
2017-12-08 13:35:06 17672 1 Command: USER ftp_usr_comp_ext
2017-12-08 13:35:06 17672 1 Response: 331 Password required
2017-12-08 13:35:06 17672 1 Command: PASS ****************
2017-12-08 13:35:06 17672 1 Response: 230 User logged in.
2017-12-08 13:35:06 17672 1 Command: SYST
2017-12-08 13:35:06 17672 1 Response: 215 Windows_NT
2017-12-08 13:35:06 17672 1 Command: FEAT
2017-12-08 13:35:06 17672 1 Response: 211-Extended features supported:
2017-12-08 13:35:06 17672 1 Response:  LANG EN*
2017-12-08 13:35:06 17672 1 Response:  UTF8
2017-12-08 13:35:06 17672 1 Response:  AUTH TLS;TLS-C;SSL;TLS-P;
2017-12-08 13:35:06 17672 1 Response:  PBSZ
2017-12-08 13:35:06 17672 1 Response:  PROT C;P;
2017-12-08 13:35:06 17672 1 Response:  CCC
2017-12-08 13:35:06 17672 1 Response:  HOST
2017-12-08 13:35:06 17672 1 Response:  SIZE
2017-12-08 13:35:06 17672 1 Response:  MDTM
2017-12-08 13:35:06 17672 1 Response:  REST STREAM
2017-12-08 13:35:06 17672 1 Response: 211 END
2017-12-08 13:35:06 17672 1 Command: PBSZ 0
2017-12-08 13:35:07 17672 1 Response: 200 PBSZ command successful.
2017-12-08 13:35:07 17672 1 Command: PROT P
2017-12-08 13:35:07 17672 1 Response: 200 PROT command successful.
2017-12-08 13:35:07 17672 1 Status: Logged in
2017-12-08 13:35:07 17672 1 Status: Retrieving directory listing of "/Prod/Outbound"...
2017-12-08 13:35:07 17672 1 Command: CWD /Prod/Outbound
2017-12-08 13:35:07 17672 1 Response: 250 CWD command successful.
```

<p>Stack Trace:</p>

<pre class="lang-none prettyprint-override"><code>   at FluentFTP.FtpSocketStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at FluentFTP.FtpSocketStream.ReadLine(Encoding encoding)
   at FluentFTP.FtpClient.GetReply()
   at FluentFTP.FtpClient.Handshake()
   at FluentFTP.FtpClient.Connect()
   at ASOSSFTP.DownloadFile.DownloadFileFromFTP()
</code>```

答:
In FileZilla, you are connecting to implicit FTPS port 990.

If you also use this port in C#, you cannot use FtpEncryptionMode.Explicit.

Use FtpEncryptionMode.Implicit.

Though you better connect to port 21 and keep using FtpEncryptionMode.Explicit, if that port is available.

Body:
Getting

Timed out trying to read data from the socket stream!

when connecting to FTP using FluentFTP.

Below is the source code which I am using to connect:

Console.WriteLine("Configuring FTP to Connect to {0}", hostname);
ftp = new FtpClient(hostname,port,new NetworkCredential(username,password));
ftp.ConnectTimeout = 600000;
ftp.ReadTimeout = 60000;
ftp.EncryptionMode = FtpEncryptionMode.Explicit;
ftp.SslProtocols = System.Security.Authentication.SslProtocols.Tls;
ftp.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
ftp.Connect();
Console.WriteLine("Connected to {0}", hostname);

ftp.SetWorkingDirectory(foldername);
Console.WriteLine("Changed directory to {0}", foldername);

void OnValidateCertificate(FtpClient control, FtpSslValidationEventArgs e)
{
    // add logic to test if certificate is valid here
    e.Accept = true;
}

FileZilla log file for successful connectivity. I am able to connect the location via FileZilla. Snippet of log is below:

2017-12-08 13:34:33 17672 1 Status: Connecting to xx.xx.xx.xx:990...
2017-12-08 13:34:33 17672 1 Status: Connection established, initializing TLS...
2017-12-08 13:34:33 17672 1 Status: Verifying certificate...
2017-12-08 13:35:06 17672 1 Status: TLS connection established, waiting for welcome message...
2017-12-08 13:35:06 17672 1 Response: 220-Microsoft FTP Service
2017-12-08 13:35:06 17672 1 Status: Invalid character sequence received, disabling UTF-8. Select UTF-8 option in site manager to force UTF-8.
2017-12-08 13:35:06 17672 1 Response:     Warning: This IT system is restricted to company authorised users only, including authorised third parties. Unauthorised access or use is a violation of Company’s policies and potentially the law.
2017-12-08 13:35:06 17672 1 Response:
2017-12-08 13:35:06 17672 1 Response: 220 Our IT systems may be monitored for administrative and security reasons. By proceeding, you acknowledge that you have read and understood this notice and that you consent to the monitoring. [ftps0]
2017-12-08 13:35:06 17672 1 Command: USER ftp_usr_comp_ext
2017-12-08 13:35:06 17672 1 Response: 331 Password required
2017-12-08 13:35:06 17672 1 Command: PASS ****************
2017-12-08 13:35:06 17672 1 Response: 230 User logged in.
2017-12-08 13:35:06 17672 1 Command: SYST
2017-12-08 13:35:06 17672 1 Response: 215 Windows_NT
2017-12-08 13:35:06 17672 1 Command: FEAT
2017-12-08 13:35:06 17672 1 Response: 211-Extended features supported:
2017-12-08 13:35:06 17672 1 Response:  LANG EN*
2017-12-08 13:35:06 17672 1 Response:  UTF8
2017-12-08 13:35:06 17672 1 Response:  AUTH TLS;TLS-C;SSL;TLS-P;
2017-12-08 13:35:06 17672 1 Response:  PBSZ
2017-12-08 13:35:06 17672 1 Response:  PROT C;P;
2017-12-08 13:35:06 17672 1 Response:  CCC
2017-12-08 13:35:06 17672 1 Response:  HOST
2017-12-08 13:35:06 17672 1 Response:  SIZE
2017-12-08 13:35:06 17672 1 Response:  MDTM
2017-12-08 13:35:06 17672 1 Response:  REST STREAM
2017-12-08 13:35:06 17672 1 Response: 211 END
2017-12-08 13:35:06 17672 1 Command: PBSZ 0
2017-12-08 13:35:07 17672 1 Response: 200 PBSZ command successful.
2017-12-08 13:35:07 17672 1 Command: PROT P
2017-12-08 13:35:07 17672 1 Response: 200 PROT command successful.
2017-12-08 13:35:07 17672 1 Status: Logged in
2017-12-08 13:35:07 17672 1 Status: Retrieving directory listing of "/Prod/Outbound"...
2017-12-08 13:35:07 17672 1 Command: CWD /Prod/Outbound
2017-12-08 13:35:07 17672 1 Response: 250 CWD command successful.

Stack Trace:

   at FluentFTP.FtpSocketStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at FluentFTP.FtpSocketStream.ReadLine(Encoding encoding)
   at FluentFTP.FtpClient.GetReply()
   at FluentFTP.FtpClient.Handshake()
   at FluentFTP.FtpClient.Connect()
   at ASOSSFTP.DownloadFile.DownloadFileFromFTP()


问:
Runtime Controller in Jmeter
Can you help me to explain relationship between time in Runtime Controller and Ramp_up period value of Thread group?
I tested

Number of Thread: 1

Ramp_Up Period: 1

Loop count: 1

Runtime Controller: 5s

->Elapsed time of current running test: 5s

But with case

Number of Thread: 5

Ramp_Up Period: 5

Loop count: 1

Runtime Controller: 5s

->Elapsed time of current running test: 10s

I don't understand why it become 10s.

Could you help me to explain more?

答:
Ramp up is the time to execute all threads, runtime is controlling each thread execution.

In your case, ramp up 5 seconds means last thread will be executed after 5 seconds. Last thread will enter runtime controller which will run 5 seconds of execution. Thus 10 seconds is the maximum of your execution.

Title: Runtime Controller in Jmeter


问:
SlickGrid - Fill grid with values in specific positions
I'm with a problem with SlickGrid Scripts. I want to build a grid based on an array with data. This data basically has a value and an address (row and column) where it should be inserted. I can fill the grid with data, but I can't put the values in the specific column and row. For instance, I have value = 3, cellRow = 2 and cellColumn = A. When I'm building the grid I want to put the value 3 in the row 2 and column A.

Any help? I already searched a lot in slickgrid documentation :(

Thanks in advance.

答:
The basic structure of Slickgrid data in object form is an array of objects:

```<code>var data = [
    { A: 1, B: 4, C: 6 },
    { A: 5, B: 9, C: 34 },
    { A: 2, B: 10, C: 2 }
];
</code>```

this appears to be what you have. The basic example uses this kind of data.
So, what is the problem?

If you have an array of arrays, eg

```<code>var data = [
    [ 1, 4, 6 ],
    [ 5, 9, 34 ],
    [ 2, 10, 2 ]
];
</code>```

then you do need to write some javascript to put the data into the first form.

Body:
The basic structure of Slickgrid data in object form is an array of objects:

var data = [
    { A: 1, B: 4, C: 6 },
    { A: 5, B: 9, C: 34 },
    { A: 2, B: 10, C: 2 }
];

this appears to be what you have. The basic example uses this kind of data.
So, what is the problem?

If you have an array of arrays, eg

var data = [
    [ 1, 4, 6 ],
    [ 5, 9, 34 ],
    [ 2, 10, 2 ]
];

then you do need to write some javascript to put the data into the first form.