问:
Why nginx is not caching?
I am using following nginx config to cache s3 responses, i am able to access s3, but not able to cache anything. Not sure why!

```<code>proxy_cache_path /var/cache/nginx
                   levels=1:2 keys_zone=s3_cache:1024m max_size=250g
                   loader_files=150000 loader_threshold=1s loader_sleep=50ms
                   inactive=365d use_temp_path=off;

    location / {
        # Calling aws_auth, to set HTTP Headers
        set $s3_host s3.amazonaws.com;
        set $s3_uri "/$arg_bucket$uri";
        access_by_lua "local aws = require 'resty.aws_auth'; aws.s3_set_headers(ngx.var.s3_host, ngx.var.s3_uri)";

        resolver               ...;

        # Cache related settings
        proxy_cache            s3_cache;
        proxy_cache_valid      200 30d; # 1 month
        proxy_cache_use_stale  error timeout http_500 http_502 http_503 http_504;
        proxy_cache_lock       on;
        proxy_cache_bypass     $http_cache_purge;
        # disable convert get to head, otherwise, HEAD request will be denied
        proxy_cache_convert_head off;
        # disable cache convert requires setting cache key, $request_method is not part of proxy_cache_key by default
        proxy_cache_methods GET HEAD;
        proxy_cache_key $scheme$request_method$proxy_host$s3_uri;
        # This max-age is different from "inactive" in proxy_cache_path.
        # It tells the browser or intermediary cache how long the response can be used from the time it was requested.
        add_header             Cache-Control max-age=2592000;
        add_header             X-Cache-Status $upstream_cache_status;
        # http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_valid
        # make sure the response will be cached.
        proxy_ignore_headers   Set-Cookie Vary;

        proxy_pass             https://$s3_host$s3_uri;
    }
}
</code>```

error/access.log didn't say anything wrong with the system. Not sure if I am missing something.

答:
at http level there was proxy_buffering off, after removing that line it started caching.

Unfortunately there is no error in errors.log or documentation about this.

Title: Why nginx is not caching?

Body:
I am using following nginx config to cache s3 responses, i am able to access s3, but not able to cache anything. Not sure why!

proxy_cache_path /var/cache/nginx
                   levels=1:2 keys_zone=s3_cache:1024m max_size=250g
                   loader_files=150000 loader_threshold=1s loader_sleep=50ms
                   inactive=365d use_temp_path=off;

    location / {
        # Calling aws_auth, to set HTTP Headers
        set $s3_host s3.amazonaws.com;
        set $s3_uri "/$arg_bucket$uri";
        access_by_lua "local aws = require 'resty.aws_auth'; aws.s3_set_headers(ngx.var.s3_host, ngx.var.s3_uri)";

        resolver               ...;

        # Cache related settings
        proxy_cache            s3_cache;
        proxy_cache_valid      200 30d; # 1 month
        proxy_cache_use_stale  error timeout http_500 http_502 http_503 http_504;
        proxy_cache_lock       on;
        proxy_cache_bypass     $http_cache_purge;
        # disable convert get to head, otherwise, HEAD request will be denied
        proxy_cache_convert_head off;
        # disable cache convert requires setting cache key, $request_method is not part of proxy_cache_key by default
        proxy_cache_methods GET HEAD;
        proxy_cache_key $scheme$request_method$proxy_host$s3_uri;
        # This max-age is different from "inactive" in proxy_cache_path.
        # It tells the browser or intermediary cache how long the response can be used from the time it was requested.
        add_header             Cache-Control max-age=2592000;
        add_header             X-Cache-Status $upstream_cache_status;
        # http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_valid
        # make sure the response will be cached.
        proxy_ignore_headers   Set-Cookie Vary;

        proxy_pass             https://$s3_host$s3_uri;
    }
}

error/access.log didn't say anything wrong with the system. Not sure if I am missing something.


来源: stackexchange

问:
Force progress bar component to re-render after progress prop has changed
How can I force a component to re-render after a passed-in prop has changed?

Premise: On my base page, I have a progress bar. From that base page, the user can access a number of modal pages. The progress bar should visualise how many modals the user has viewed.

In principle, most of it works. The only problem is that my progress bar component does not re-render my visual progress bar when the passed-in progress prop changes.

```<code><ProgressBar
    progress={ this.props.progress }
/>
</code>```

The progress bar component itself is aware of the change and will happily re-render a text field that prints the value of progress to reflect the updated value. However, it will not re-render the visual progress bar (a series of view components with styling) in a way that reflects the changed prop. The text field changes, the views do not.

Here's my code. Could it be that I need to repeat the calculations I do in ComponentDidMount() in some kind of update function as well?

```<code>// Progress Bar component
export default class ProgressBar extends React.Component {

    state = {
        // define some variables
    }

    componentDidMount() {
        // do some math using this.props.progress and state
        // to calculate the percentage etc that the views use to
        // display the length of the progress bar
    }

    componentWillUpdate( prevProps, prevState ) {
        // I tried repeating the above calculations in here as well
        // but anything I place in here will result in error message:
        // Invariant Violation: Maximum update depth exceeded...
    }

    render() {
        // a number of views that create a visual progress bar
        // entirely dependent on calculated values, i.e. not directly
        // referencing this.props.progress
    }
</code>```

}

Any guidance would be much appreciated!

答:
A re-render can only be triggered if state has changed. The state can change from a props change, or from a direct setState change. The component gets the updated state and React decides if it should re-render the component.

so component you will pass a state if state you will change any where its make effects on render
class Progress extends React.Component {

```<code>componentDidMount() {
    setInterval(() => {
        this.setState(() => {

            progress:true
        });
    }, 1000);
}

render() {

    return (<div>{this.state.progress ? <div> true </div>: <div>false</div>}</div>);
}
</code>```

}

ContentLicense: CC BY-SA 4.0

Body:
How can I force a component to re-render after a passed-in prop has changed?

Premise: On my base page, I have a progress bar. From that base page, the user can access a number of modal pages. The progress bar should visualise how many modals the user has viewed.

In principle, most of it works. The only problem is that my progress bar component does not re-render my visual progress bar when the passed-in progress prop changes.

<ProgressBar
    progress={ this.props.progress }
/>

The progress bar component itself is aware of the change and will happily re-render a text field that prints the value of progress to reflect the updated value. However, it will not re-render the visual progress bar (a series of view components with styling) in a way that reflects the changed prop. The text field changes, the views do not.

Here's my code. Could it be that I need to repeat the calculations I do in ComponentDidMount() in some kind of update function as well?

// Progress Bar component
export default class ProgressBar extends React.Component {

    state = {
        // define some variables
    }

    componentDidMount() {
        // do some math using this.props.progress and state
        // to calculate the percentage etc that the views use to
        // display the length of the progress bar
    }

    componentWillUpdate( prevProps, prevState ) {
        // I tried repeating the above calculations in here as well
        // but anything I place in here will result in error message:
        // Invariant Violation: Maximum update depth exceeded...
    }

    render() {
        // a number of views that create a visual progress bar
        // entirely dependent on calculated values, i.e. not directly
        // referencing this.props.progress
    }

}

Any guidance would be much appreciated!

Body:
A re-render can only be triggered if state has changed. The state can change from a props change, or from a direct setState change. The component gets the updated state and React decides if it should re-render the component.

so component you will pass a state if state you will change any where its make effects on render
class Progress extends React.Component {

componentDidMount() {
    setInterval(() => {
        this.setState(() => {

            progress:true
        });
    }, 1000);
}

render() {

    return (<div>{this.state.progress ? <div> true </div>: <div>false</div>}</div>);
}

}


问:
How to populate a List of strings from a DataTable?
I'm trying to populate a List with a column of a DataTable in order to later convert it to a AutoCompleteStringCollection later. Is there a neater way to do it than the "good old" For Each?

Is there a way to use myDataTable.Rows.CopyTo for this task?

Cheers! = )

答: See this :- Best practice when converting DataColumn values to an array of strings?</p>

ContentLicense: CC BY-SA 3.0


问:
Magento paypal express review page and agreements
at the moment i'm trying to commit a little change to Magento's Paypal Express Extension. I'm trying to get rid of the review page because it's unnecessary.

How it's done is alreasy described here:
Magento: easy way to remove "paypal/express/review" step

But it won't work when you enable agreements.
And here's the problem:

```<code>app/code/core/Mage/Paypal/Controller/Express/Abstract.php
</code>```

line 314 to 316 must be uncommented

```<code>if (array_diff($requiredAgreements, $postedAgreements)) {
   Mage::throwException(Mage::helper('paypal')->__('Please agree to all the terms and conditions before placing the order.'));
}
</code>```

```<code>app/code/community/Sandfox/RemovePaypalExpressReviewStep/etc/config.xml
</code>```

```<code><?xml version="1.0"?>
<config>
    <modules>
        <Sandfox_RemovePaypalExpressReviewStep>
            <version>0.1.0</version>
        </Sandfox_RemovePaypalExpressReviewStep>
    </modules>
    <global>
        <models>
            <sandfox_removepaypalexpressreviewstep>
                <class>Sandfox_RemovePaypalExpressReviewStep_Model</class>
            </sandfox_removepaypalexpressreviewstep>
            <paypal>
                <rewrite>
                    <config>Sandfox_RemovePaypalExpressReviewStep_Model_Config</config>
                </rewrite>
            </paypal>
        </models>
        <events>
            <controller_action_predispatch_paypal_express_review>
                <observers>
                    <sandfox_removepaypalexpressreviewstep>
                        <type>singleton</type>
                        <class>sandfox_removepaypalexpressreviewstep/observer</class>
                        <method>controllerActionPredispatchPaypalExpressReview</method>
                    </sandfox_removepaypalexpressreviewstep>
                </observers>
            </controller_action_predispatch_paypal_express_review>
        </events>
    </global>
    <frontend>
        <routers>
            <paypal>
                <args>
                    <modules>
                         <Sandfox_RemovePaypalExpressReviewStep before="Mage_Paypal">Sandfox_RemovePaypalExpressReviewStep</Sandfox_RemovePaypalExpressReviewStep>
                    </modules>
                </args>
            </paypal>
        </routers>
    </frontend>
</config>
</code>```

Now i tried to rewrite the controller (is it really a controller? Why it's not in controllers  but has it's own Controller directory?)

```<code>app/code/community/Sandfox/RemovePaypalExpressReviewStep/Controller/Express/Abstract.php
</code>```

```<code>    <?php
    include_once("Mage/Paypal/Controller/Express/Abstract.php");

    class Sandfox_RemovePaypalExpressReviewStep_Controller_Express_Abstract extends Mage_Paypal_Controller_Express_Abstract
    {

        public function placeOrderAction()
        {
            try {
            .
            .
            .
                //    if (array_diff($requiredAgreements, $postedAgreements)) {
                 //       Mage::throwException(Mage::helper('paypal')->__('Please agree to all the terms and conditions before placing the order.'));
                  //  }
                }
            .
            .
            .

}
</code>```

At the moment the rewrite doesn't work. Can someone give me a hint?

tec:

Magento 1.9.2

PHP 5.5

MYSQL 5.6.19

答: You can't extends an Abstract class. U need to copy into local/Mage...</p>

Body:
at the moment i'm trying to commit a little change to Magento's Paypal Express Extension. I'm trying to get rid of the review page because it's unnecessary.

How it's done is alreasy described here:
Magento: easy way to remove "paypal/express/review" step

But it won't work when you enable agreements.
And here's the problem:

app/code/core/Mage/Paypal/Controller/Express/Abstract.php

line 314 to 316 must be uncommented

if (array_diff($requiredAgreements, $postedAgreements)) {
   Mage::throwException(Mage::helper('paypal')->__('Please agree to all the terms and conditions before placing the order.'));
}

app/code/community/Sandfox/RemovePaypalExpressReviewStep/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Sandfox_RemovePaypalExpressReviewStep>
            <version>0.1.0</version>
        </Sandfox_RemovePaypalExpressReviewStep>
    </modules>
    <global>
        <models>
            <sandfox_removepaypalexpressreviewstep>
                <class>Sandfox_RemovePaypalExpressReviewStep_Model</class>
            </sandfox_removepaypalexpressreviewstep>
            <paypal>
                <rewrite>
                    <config>Sandfox_RemovePaypalExpressReviewStep_Model_Config</config>
                </rewrite>
            </paypal>
        </models>
        <events>
            <controller_action_predispatch_paypal_express_review>
                <observers>
                    <sandfox_removepaypalexpressreviewstep>
                        <type>singleton</type>
                        <class>sandfox_removepaypalexpressreviewstep/observer</class>
                        <method>controllerActionPredispatchPaypalExpressReview</method>
                    </sandfox_removepaypalexpressreviewstep>
                </observers>
            </controller_action_predispatch_paypal_express_review>
        </events>
    </global>
    <frontend>
        <routers>
            <paypal>
                <args>
                    <modules>
                         <Sandfox_RemovePaypalExpressReviewStep before="Mage_Paypal">Sandfox_RemovePaypalExpressReviewStep</Sandfox_RemovePaypalExpressReviewStep>
                    </modules>
                </args>
            </paypal>
        </routers>
    </frontend>
</config>

Now i tried to rewrite the controller (is it really a controller? Why it's not in controllers  but has it's own Controller directory?)

app/code/community/Sandfox/RemovePaypalExpressReviewStep/Controller/Express/Abstract.php

    <?php
    include_once("Mage/Paypal/Controller/Express/Abstract.php");

    class Sandfox_RemovePaypalExpressReviewStep_Controller_Express_Abstract extends Mage_Paypal_Controller_Express_Abstract
    {

        public function placeOrderAction()
        {
            try {
            .
            .
            .
                //    if (array_diff($requiredAgreements, $postedAgreements)) {
                 //       Mage::throwException(Mage::helper('paypal')->__('Please agree to all the terms and conditions before placing the order.'));
                  //  }
                }
            .
            .
            .

}

At the moment the rewrite doesn't work. Can someone give me a hint?

tec:

Magento 1.9.2

PHP 5.5

MYSQL 5.6.19


问:
no rule to make target while compiling elastix binaries
I am trying to compile source code from Elastic binaries. I am using ITK and CMAKE. I am able to compile the code, however when I navigate to the build directory and run make install I get the following error

```<code>make[2]: *** No rule to make target '/Users/tony/ITK_DIR/lib/libitkdouble-conversion-4.13.a', needed by 'bin/elastix'.  Stop.
make[1]: *** [CMakeFiles/Makefile2:5668: Core/CMakeFiles/elastix.dir/all] Error 2
make: *** [Makefile:141: all] Error 2
</code>```

Here is some of my makefile code. I'm new to this so if any more information is needed please request it and I will provide it

```<code>
.PHONY : default_target

# The main recursive all target
all:

.PHONY : all

# The main recursive preinstall target
preinstall:

.PHONY : preinstall

# The main recursive clean target
clean:

.PHONY : clean

#=============================================================================
# Special targets provided by cmake.

# Disable implicit rules so canonical targets will work.
.SUFFIXES:

# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =

.SUFFIXES: .hpux_make_needs_suffix_list

# Suppress display of executed commands.
$(VERBOSE).SILENT:

# A target that is always out of date.
cmake_force:

.PHONY : cmake_force

#=============================================================================
# Set environment variables for the build.

# The shell in which to execute make rules.
SHELL = /bin/sh

# The CMake executable.
CMAKE_COMMAND = /private/var/folders/h7/c6g9qc8j25l92b58yr_jbc2h0000gn/T/AppTranslocation/BE140EBD-E4FD-4FE0-8DAA-7526DF6251A7/d/CMake.app/Contents/bin/cmake

# The command to remove a file.
RM = /private/var/folders/h7/c6g9qc8j25l92b58yr_jbc2h0000gn/T/AppTranslocation/BE140EBD-E4FD-4FE0-8DAA-7526DF6251A7/d/CMake.app/Contents/bin/cmake -E remove -f

# Escaping for special characters.
EQUALS = =

# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /Users/tony/Downloads/InsightToolkit-4.13.2

# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /Users/tony/ITK_DIR
</code>```

答: Did you configure ITK to use system double conversion? If so, you might be interested in the patch in this PR. If not, you could ask about your problem on Elastix forum.</p>

Body:
I am trying to compile source code from Elastic binaries. I am using ITK and CMAKE. I am able to compile the code, however when I navigate to the build directory and run make install I get the following error

make[2]: *** No rule to make target '/Users/tony/ITK_DIR/lib/libitkdouble-conversion-4.13.a', needed by 'bin/elastix'.  Stop.
make[1]: *** [CMakeFiles/Makefile2:5668: Core/CMakeFiles/elastix.dir/all] Error 2
make: *** [Makefile:141: all] Error 2

Here is some of my makefile code. I'm new to this so if any more information is needed please request it and I will provide it

.PHONY : default_target

# The main recursive all target
all:

.PHONY : all

# The main recursive preinstall target
preinstall:

.PHONY : preinstall

# The main recursive clean target
clean:

.PHONY : clean

#=============================================================================
# Special targets provided by cmake.

# Disable implicit rules so canonical targets will work.
.SUFFIXES:

# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =

.SUFFIXES: .hpux_make_needs_suffix_list

# Suppress display of executed commands.
$(VERBOSE).SILENT:

# A target that is always out of date.
cmake_force:

.PHONY : cmake_force

#=============================================================================
# Set environment variables for the build.

# The shell in which to execute make rules.
SHELL = /bin/sh

# The CMake executable.
CMAKE_COMMAND = /private/var/folders/h7/c6g9qc8j25l92b58yr_jbc2h0000gn/T/AppTranslocation/BE140EBD-E4FD-4FE0-8DAA-7526DF6251A7/d/CMake.app/Contents/bin/cmake

# The command to remove a file.
RM = /private/var/folders/h7/c6g9qc8j25l92b58yr_jbc2h0000gn/T/AppTranslocation/BE140EBD-E4FD-4FE0-8DAA-7526DF6251A7/d/CMake.app/Contents/bin/cmake -E remove -f

# Escaping for special characters.
EQUALS = =

# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /Users/tony/Downloads/InsightToolkit-4.13.2

# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /Users/tony/ITK_DIR


问:
Producing a linear distribution for a "donut" shape
I am trying to produce a distribution for points within a circle where there are more towards the center, but for a donut shape

I can produce a uniformly distributed donut shape (1), or a circle where there are more points towards the center (2) but not a donut shape that has so many points towards its inside boundary.

(1)

```<code>r = sqrt(runif(250, min = 0.25, max =1))
p = runif(250)
theta = p *2*pi
a = r * cos(theta) #coordinates for circle
b = r * sin(theta)
plot(a,b)
</code>```

(2)

```<code>r = runif(250)
p = runif(250)
theta = p *2*pi
a = r * cos(theta)
b = r * sin(theta)
plot(a,b)

</code>```

My closest attempt is modifying program (2) where r is bound between 0.5 and 1 but this removes most of the points closest to the center and does not have as many around its inside.

答:
As @RobertDodier said, try to use some advanced distribution for radius. What I would like to propose is Beta distribution.

First, it is naturally in the [0...1] range, no need to truncate, accept/reject etc.
Second, it has two parameters (a,b) which could be used to get single peak, zero at 0, and slope to 1. Look at graphs in the wiki page. And last, it is implemented in R. a being smaller than b means peak is on the lef of 0.5, a being larger than b means peak is on the right of 0.5.

Along the lines

```<code>N = 10000
r = rbeta(N, 7.0, 5.0)
theta = 2.0*pi*runif(N)
a = r * cos(theta)
b = r * sin(theta)
plot(a,b)
</code>```

will produce plot like that

Does it look like at donut?

UPDATE

This one is with clear hole at the center and shape proposed by  @RobertDodier

```<code>N = 10000
hole = 0.25
r = hole + (1.0-hole)*rbeta(N, 1.0, 3.0)
theta = 2.0*pi*runif(N)
a = r * cos(theta)
b = r * sin(theta)
plot(a,b)
</code>```

Another one with clear hole in the center and symmetric shape, like a true donut

```<code>r = hole + (1.0-hole)*rbeta(N, 2.0, 2.0)
</code>```

Body:
I am trying to produce a distribution for points within a circle where there are more towards the center, but for a donut shape

I can produce a uniformly distributed donut shape (1), or a circle where there are more points towards the center (2) but not a donut shape that has so many points towards its inside boundary.

(1)

r = sqrt(runif(250, min = 0.25, max =1))
p = runif(250)
theta = p *2*pi
a = r * cos(theta) #coordinates for circle
b = r * sin(theta)
plot(a,b)

(2)

r = runif(250)
p = runif(250)
theta = p *2*pi
a = r * cos(theta)
b = r * sin(theta)
plot(a,b)

My closest attempt is modifying program (2) where r is bound between 0.5 and 1 but this removes most of the points closest to the center and does not have as many around its inside.

Body:
As @RobertDodier said, try to use some advanced distribution for radius. What I would like to propose is Beta distribution.

First, it is naturally in the [0...1] range, no need to truncate, accept/reject etc.
Second, it has two parameters (a,b) which could be used to get single peak, zero at 0, and slope to 1. Look at graphs in the wiki page. And last, it is implemented in R. a being smaller than b means peak is on the lef of 0.5, a being larger than b means peak is on the right of 0.5.

Along the lines

N = 10000
r = rbeta(N, 7.0, 5.0)
theta = 2.0*pi*runif(N)
a = r * cos(theta)
b = r * sin(theta)
plot(a,b)

will produce plot like that

Does it look like at donut?

UPDATE

This one is with clear hole at the center and shape proposed by  @RobertDodier

N = 10000
hole = 0.25
r = hole + (1.0-hole)*rbeta(N, 1.0, 3.0)
theta = 2.0*pi*runif(N)
a = r * cos(theta)
b = r * sin(theta)
plot(a,b)

Another one with clear hole in the center and symmetric shape, like a true donut

r = hole + (1.0-hole)*rbeta(N, 2.0, 2.0)


问:
package .apk in Microsoft Visual Studio 2010 using Mono for Android
I'm using Mono for Android and Microsoft Visual Studio Professional 2010 and created HelloMonodroid App. App is running fine in Emulator, when Project is configured to DEBUG.
What i want to do now is build/package an .apk file in RELEASE mode. I followed the steps described on: Preparing Package

But i'm getting following error:

monodroid : error 1: This version of mandroid.exe does not support static compilation.

I'm using the evaluation/trial version of Mono for Android. Anybody knows what is wrong here? Thanks for help!

答:
I'd guess that your version of monodroid doesn't support static compilation.

Or more usefully, since you're using a eval/trial version, it's probably crippled to prevent releases - to evaluate/trial it, you don't need to create a release version.


问:
What's the difference between %s and %d in string formatting?
I don't understand what %s and %d do and how they work.

答:
These are all informative answers, but none are quite getting at the core of what the difference is between %s and %d.

%s tells the formatter to call the str() function on the argument and since we are coercing to a string by definition, %s is essentially just performing str(arg).

%d on the other hand, is calling int() on the argument before calling str(), like str(int(arg)), This will cause int coercion as well as str coercion.

For example, I can convert a hex value to decimal,

```<code>>>> '%d' % 0x15
'21'
</code>```

or truncate a float.

```<code>>>> '%d' % 34.5
'34'
</code>```

But the operation will raise an exception if the argument isn't a number.

```<code>>>> '%d' % 'thirteen'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
</code>```

So if the intent is just to call str(arg), then %s is sufficient, but if you need extra formatting (like formatting float decimal places) or other coercion, then the other format symbols are needed.

With the f-string notation, when you leave the formatter out, the default is str.

```<code>>>> a = 1
>>> f'{a}'
'1'
>>> f'{a:d}'
'1'
>>> a = '1'
>>> f'{a:d}'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'
</code>```

The same is true with string.format; the default is str.

```<code>>>> a = 1
>>> '{}'.format(a)
'1'
>>> '{!s}'.format(a)
'1'
>>> '{:d}'.format(a)
'1'
</code>```

Body:
These are all informative answers, but none are quite getting at the core of what the difference is between %s and %d.

%s tells the formatter to call the str() function on the argument and since we are coercing to a string by definition, %s is essentially just performing str(arg).

%d on the other hand, is calling int() on the argument before calling str(), like str(int(arg)), This will cause int coercion as well as str coercion.

For example, I can convert a hex value to decimal,

>>> '%d' % 0x15
'21'

or truncate a float.

>>> '%d' % 34.5
'34'

But the operation will raise an exception if the argument isn't a number.

>>> '%d' % 'thirteen'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

So if the intent is just to call str(arg), then %s is sufficient, but if you need extra formatting (like formatting float decimal places) or other coercion, then the other format symbols are needed.

With the f-string notation, when you leave the formatter out, the default is str.

>>> a = 1
>>> f'{a}'
'1'
>>> f'{a:d}'
'1'
>>> a = '1'
>>> f'{a:d}'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'

The same is true with string.format; the default is str.

>>> a = 1
>>> '{}'.format(a)
'1'
>>> '{!s}'.format(a)
'1'
>>> '{:d}'.format(a)
'1'


问:
How do I wait for the input from the GUI back to main?
I want to be able to pass user input from my GUI to one of my classes. However, the input is not passed over and immediately checks the if statement.
How do I get program to wait for the input and only checks after the button is clicked?

Main class

```<code>public class MainTest {
    public static void main(String[] args) {
        String weaponCategory;
        //Create Java GUI
        GUITest window = new GUITest();

        if(window.getCategory() != "")
        {
            System.out.println("test");
        }
    }

}
</code>```

GUITest class

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GUITest implements ActionListener{

    private JFrame frmInventorysystem;
    private JPanel frameBottom;
    private JComboBox equipList;
    private String category = "";
    private JButton confirmBtn, cancelBtn;

    /**
     * Create the application.
     */
    public GUITest()
    {
        frmInventorysystem = new JFrame();
        frmInventorysystem.setTitle("InventorySystem");
        frmInventorysystem.setBounds(100, 100, 450, 300);
        frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));

        frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /*JFrame inside another JFrame is not recommended. JPanels are used instead.
        * Creating a flow layout for the bottom frame
        */
        frameBottom = new JPanel();
        frameBottom.setLayout(new FlowLayout());

        //creates comboBox to find out which of the three items player is looking to insert
        String[] weaponCategories = {"Weapon", "Armor", "Mod"};
        equipList = new JComboBox(weaponCategories);
        frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);

        //Converting BorderLayout.south into a flow layout
        frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);

        confirmBtn = new JButton("Confirm");
        confirmBtn.addActionListener(this);

        frameBottom.add(confirmBtn);

        cancelBtn = new JButton("Cancel");
        cancelBtn.addActionListener(this);
        frameBottom.add(cancelBtn);

        frmInventorysystem.setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
        //creates new windows to sort equipment when confirmBtn is clicked
        if(e.getSource() == confirmBtn)
        {
            if(equipList.getSelectedItem().equals("Weapon"))
            {
                //GUIWeaponCategory weapon = new GUIWeaponCategory();
                category = equipList.getSelectedItem().toString();
            }
        }
        //Exits when cancelBtn is clicked
        if(e.getSource() == cancelBtn)
        {
            System.exit(0);
        }
    }

    public String getCategory()
    {
        return category;
    }

    public void setCategory(String a)
    {
        category = a;
    }
}
</code>```

GUITest launches as expected.
However, the first println is missing.
How would I go about doing this?
What concepts or pieces of code am I missing?

EDIT1: Added a couple more details to make the program reproducible and complete.

EDIT2: Making the code more readable for easy understanding.

答:
There are some changes to make on your program

Remove extends JFrame as stated in my comments above, see Extends JFrame vs. creating it inside the program

Place your program on the EDT, see point #3 on this answer and the main method for an example on how to do that.

You're confused about how the ActionListeners work, they wait until you perform certain action in your program (i.e. you press Confirm button) and then do something. "Something" in your program means: Print the selected item and check if it's a weapon then, do something else.

So, in this case, you don't need to return back to main to continue with your program, main only serves to initialize your application and nothing else. You need to think in the events and not in a sequential way. That's the tricky and most important part.

You need to change your programming paradigm from console applications and do-while that everything happens in a sequential manner rather than events that are triggered when the user does something with your application.

For example:

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GUITest implements ActionListener {
    private JFrame frmInventorysystem;
    private JPanel frameBottom;
    private JComboBox equipList;
    private JButton confirmBtn, cancelBtn;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new GUITest()); //Java 8+ if using an earlier version check the point #2 in this answer and modify the code accordingly.
    }

    /**
     * Create the application.
     */
    public GUITest() {
        frmInventorysystem = new JFrame();
        frmInventorysystem.setTitle("InventorySystem");
        frmInventorysystem.setBounds(100, 100, 450, 300);
        frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));

        /*
         * JFrame inside another JFrame is not recommended. JPanels are used instead
         * Creating a flow layout for the bottom frame
         */
        frameBottom = new JPanel();
        frameBottom.setLayout(new FlowLayout());

        // creates comboBox to find out which of the three items player is looking to
        // insert
        String[] weaponCategories = { "Weapon", "Armor", "Mod" };
        equipList = new JComboBox(weaponCategories);
        frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);

        // Converting BorderLayout.south into a flow layout
        frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);

        confirmBtn = new JButton("Confirm");
        confirmBtn.addActionListener(this);

        frameBottom.add(confirmBtn);

        cancelBtn = new JButton("Cancel");
        cancelBtn.addActionListener(this);
        frameBottom.add(cancelBtn);

        frmInventorysystem.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        // creates new windows to sort equipment when confirmBtn is clicked
        if (e.getSource() == confirmBtn) {
            String category = equipList.getSelectedItem().toString(); //Get the selected category
            doSomething(category); //Pass it as a parameter
        }
        // Exits when cancelBtn is clicked
        if (e.getSource() == cancelBtn) {
            frmInventorysystem.dispose();
        }
    }

    // Do something with the category
    private void doSomething(String selectedEquipment) {
        System.out.println(selectedEquipment);
        if (selectedEquipment.equals("Weapon")) {
            System.out.println("It's a weapon!"); //You can open dialogs or do whatever you need here, not necessarily a print.
        } else {
            System.out.println("Not a weapon");
        }
    }
}
</code>```

Notice that I removed inheritance, I'm not returning back to main and still printing the selected item and checking if it's a weapon or not.

I also exit the application in a safer way.

This is a sample output:

```<code>Weapon
It's a weapon!
Armor
Not a weapon
</code>```

Body:
I want to be able to pass user input from my GUI to one of my classes. However, the input is not passed over and immediately checks the if statement.
How do I get program to wait for the input and only checks after the button is clicked?

Main class

public class MainTest {
    public static void main(String[] args) {
        String weaponCategory;
        //Create Java GUI
        GUITest window = new GUITest();

        if(window.getCategory() != "")
        {
            System.out.println("test");
        }
    }

}

GUITest class

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GUITest implements ActionListener{

    private JFrame frmInventorysystem;
    private JPanel frameBottom;
    private JComboBox equipList;
    private String category = "";
    private JButton confirmBtn, cancelBtn;

    /**
     * Create the application.
     */
    public GUITest()
    {
        frmInventorysystem = new JFrame();
        frmInventorysystem.setTitle("InventorySystem");
        frmInventorysystem.setBounds(100, 100, 450, 300);
        frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));

        frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /*JFrame inside another JFrame is not recommended. JPanels are used instead.
        * Creating a flow layout for the bottom frame
        */
        frameBottom = new JPanel();
        frameBottom.setLayout(new FlowLayout());

        //creates comboBox to find out which of the three items player is looking to insert
        String[] weaponCategories = {"Weapon", "Armor", "Mod"};
        equipList = new JComboBox(weaponCategories);
        frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);

        //Converting BorderLayout.south into a flow layout
        frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);

        confirmBtn = new JButton("Confirm");
        confirmBtn.addActionListener(this);

        frameBottom.add(confirmBtn);

        cancelBtn = new JButton("Cancel");
        cancelBtn.addActionListener(this);
        frameBottom.add(cancelBtn);

        frmInventorysystem.setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
        //creates new windows to sort equipment when confirmBtn is clicked
        if(e.getSource() == confirmBtn)
        {
            if(equipList.getSelectedItem().equals("Weapon"))
            {
                //GUIWeaponCategory weapon = new GUIWeaponCategory();
                category = equipList.getSelectedItem().toString();
            }
        }
        //Exits when cancelBtn is clicked
        if(e.getSource() == cancelBtn)
        {
            System.exit(0);
        }
    }

    public String getCategory()
    {
        return category;
    }

    public void setCategory(String a)
    {
        category = a;
    }
}

GUITest launches as expected.
However, the first println is missing.
How would I go about doing this?
What concepts or pieces of code am I missing?

EDIT1: Added a couple more details to make the program reproducible and complete.

EDIT2: Making the code more readable for easy understanding.

Body:
There are some changes to make on your program

Remove extends JFrame as stated in my comments above, see Extends JFrame vs. creating it inside the program

Place your program on the EDT, see point #3 on this answer and the main method for an example on how to do that.

You're confused about how the ActionListeners work, they wait until you perform certain action in your program (i.e. you press Confirm button) and then do something. "Something" in your program means: Print the selected item and check if it's a weapon then, do something else.

So, in this case, you don't need to return back to main to continue with your program, main only serves to initialize your application and nothing else. You need to think in the events and not in a sequential way. That's the tricky and most important part.

You need to change your programming paradigm from console applications and do-while that everything happens in a sequential manner rather than events that are triggered when the user does something with your application.

For example:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GUITest implements ActionListener {
    private JFrame frmInventorysystem;
    private JPanel frameBottom;
    private JComboBox equipList;
    private JButton confirmBtn, cancelBtn;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new GUITest()); //Java 8+ if using an earlier version check the point #2 in this answer and modify the code accordingly.
    }

    /**
     * Create the application.
     */
    public GUITest() {
        frmInventorysystem = new JFrame();
        frmInventorysystem.setTitle("InventorySystem");
        frmInventorysystem.setBounds(100, 100, 450, 300);
        frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));

        /*
         * JFrame inside another JFrame is not recommended. JPanels are used instead
         * Creating a flow layout for the bottom frame
         */
        frameBottom = new JPanel();
        frameBottom.setLayout(new FlowLayout());

        // creates comboBox to find out which of the three items player is looking to
        // insert
        String[] weaponCategories = { "Weapon", "Armor", "Mod" };
        equipList = new JComboBox(weaponCategories);
        frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);

        // Converting BorderLayout.south into a flow layout
        frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);

        confirmBtn = new JButton("Confirm");
        confirmBtn.addActionListener(this);

        frameBottom.add(confirmBtn);

        cancelBtn = new JButton("Cancel");
        cancelBtn.addActionListener(this);
        frameBottom.add(cancelBtn);

        frmInventorysystem.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        // creates new windows to sort equipment when confirmBtn is clicked
        if (e.getSource() == confirmBtn) {
            String category = equipList.getSelectedItem().toString(); //Get the selected category
            doSomething(category); //Pass it as a parameter
        }
        // Exits when cancelBtn is clicked
        if (e.getSource() == cancelBtn) {
            frmInventorysystem.dispose();
        }
    }

    // Do something with the category
    private void doSomething(String selectedEquipment) {
        System.out.println(selectedEquipment);
        if (selectedEquipment.equals("Weapon")) {
            System.out.println("It's a weapon!"); //You can open dialogs or do whatever you need here, not necessarily a print.
        } else {
            System.out.println("Not a weapon");
        }
    }
}

Notice that I removed inheritance, I'm not returning back to main and still printing the selected item and checking if it's a weapon or not.

I also exit the application in a safer way.

This is a sample output:

Weapon
It's a weapon!
Armor
Not a weapon


问:
Verilog: How to deal with if conditions of wires?
Question follows over from here: Why is wire variable causing illegal left-hand side in continuous assignment?

Below is my adjusted code, but I'm still having the problem of reconciling b (which is a reg) and Y (which is a wire) under the same if conditions. I get that a wire has to be viewed as a result of the combinations its attached to, and can't just be assigned a value, and certainly not as a function of itself. And all the stuff about not being allowed to use assign to regs or that wires can't be used in if blocks.

But the problem is once b is calculated, and if b!=0, how do I correct the bth bit error (Y[b]) and getting it to flip from 1 to 0 or vice versa?

```<code>// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  integer b;       // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  always @(I,e)
  begin
    b=0; // initialize b to zero
  if(S[1]!=P[1])
    b=b+1;
  if(S[2]!=P[2]) // b is cumulative if each of the conditions is true
    b=b+2;
  if(S[3]!=P[3])
    b=b+4;
  if(b!=0)
    begin
    Y[b]=!(Y[b]); // HOW TO CORRECT THIS?
    end
  end

  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule
</code>```

答:
As I said in the comments: your code is very ... sub-optimal. So here I'll answer only:

Y[b]=!(Y[b]); // HOW TO CORRECT THIS?

If you write Y[b]=!(Y[b]) (and there is no clock involved) you have made a combinatorial loop: Y[b] becomes not Y[b], which immediately becomes not-not Y[b], which immediately becomes not-not-not Y[b] etc.

You have to use forward working logic: make a new variable e.g. Z which is equal to Y but bit b (b!=0) is inverted.

```<code>always @( * )
   case (b)
   1 : Z = Y ^ 4'b0010;
   2 : Z = Y ^ 4'b0100;
   3 : Z = Y ^ 4'b1000;
   default : Z = Y;
   endcase
</code>```

(Of course it also helps if you are familiar with how the various logic operations work.)

Not tested, typos are possible

Body:
Question follows over from here: Why is wire variable causing illegal left-hand side in continuous assignment?

Below is my adjusted code, but I'm still having the problem of reconciling b (which is a reg) and Y (which is a wire) under the same if conditions. I get that a wire has to be viewed as a result of the combinations its attached to, and can't just be assigned a value, and certainly not as a function of itself. And all the stuff about not being allowed to use assign to regs or that wires can't be used in if blocks.

But the problem is once b is calculated, and if b!=0, how do I correct the bth bit error (Y[b]) and getting it to flip from 1 to 0 or vice versa?

// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  integer b;       // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  always @(I,e)
  begin
    b=0; // initialize b to zero
  if(S[1]!=P[1])
    b=b+1;
  if(S[2]!=P[2]) // b is cumulative if each of the conditions is true
    b=b+2;
  if(S[3]!=P[3])
    b=b+4;
  if(b!=0)
    begin
    Y[b]=!(Y[b]); // HOW TO CORRECT THIS?
    end
  end

  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule

Body:
As I said in the comments: your code is very ... sub-optimal. So here I'll answer only:

Y[b]=!(Y[b]); // HOW TO CORRECT THIS?

If you write Y[b]=!(Y[b]) (and there is no clock involved) you have made a combinatorial loop: Y[b] becomes not Y[b], which immediately becomes not-not Y[b], which immediately becomes not-not-not Y[b] etc.

You have to use forward working logic: make a new variable e.g. Z which is equal to Y but bit b (b!=0) is inverted.

always @( * )
   case (b)
   1 : Z = Y ^ 4'b0010;
   2 : Z = Y ^ 4'b0100;
   3 : Z = Y ^ 4'b1000;
   default : Z = Y;
   endcase

(Of course it also helps if you are familiar with how the various logic operations work.)

Not tested, typos are possible


问:
How to Add changable text on splash screen?
Hi i want to add text on the splash image on splash screen. i have added single text on image but i want to change the text every time the app opens.how to do that please tell me .

i have added single textview in splash.xml it is displaying . But i want to display all the item in the list.xml one-by-one every time app opens.

```<code><TextView
    android:id="@+id/quote"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your limitation—it's only your imagination."
    android:textColor="#ffffff"
    android:textSize="36sp"
   android:layout_centerInParent="true"/>
</code>```

in list.xml

```<code><string-array name="quote_array">
    <item>Your limitation—it's only your imagination.</item>
    <item>Great things never come from comfort zones.</item>
    <item>The harder you work for something, the greater you’ll feel when you achieve it.</item>
</string-array>
</code>```

答:
It depends on what you want to achieve. If order does not matter you can use random Integer by new Random.nextInt(stringArray.length() - 1); each time you start your application. But if you want to show your strings in order from 0 to the last, you need to persist previous index in any storage. I think SharedPreferences is better solution for it.

Good luck!

Body:
Hi i want to add text on the splash image on splash screen. i have added single text on image but i want to change the text every time the app opens.how to do that please tell me .

i have added single textview in splash.xml it is displaying . But i want to display all the item in the list.xml one-by-one every time app opens.

<TextView
    android:id="@+id/quote"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your limitation—it's only your imagination."
    android:textColor="#ffffff"
    android:textSize="36sp"
   android:layout_centerInParent="true"/>

in list.xml

<string-array name="quote_array">
    <item>Your limitation—it's only your imagination.</item>
    <item>Great things never come from comfort zones.</item>
    <item>The harder you work for something, the greater you’ll feel when you achieve it.</item>
</string-array>


问:
Check if date crash with another
I have two variables: start_time, end_time, which I need to compare with two other identical variables to see if they collide. Is there a function I can use?</p>

答:
I assume you mean the 2 time ranges overlap each other. In that case, here is the one liner</p>

```<code>is_overlap = not (end_time1 < start_time2 or end_time2 < start_time1)
</code>```

Title: Check if date crash with another

Body:
I assume you mean the 2 time ranges overlap each other. In that case, here is the one liner

is_overlap = not (end_time1 < start_time2 or end_time2 < start_time1)


问:
Is there a way to determine the type of edit used with onEdit in a Google Sheets Script?
I need to know if a user is deleting a row, editing a cell, or pasting a bunch of cells. I keep looking through documentation and I cannot find a way to determine what the user's action is. Is there a way in to know what kind of action is used in onEdit?</p>

答:
What's in an Event Trigger?

If you want to know what an event object has in it then you can do something like this:

```<code>function onEdit(e) {
  Logger.log(JSON.stringify(e));
}
</code>```

In the case of a simple onEdit() trigger this is what it contains:

```<code>[19-05-30 10:19:36:809 MDT] {"authMode":{},"range":{"columnStart":4,"rowStart":4,"rowEnd":4,"columnEnd":4},"source":{},"user":{"nickname":"Your Nickname","email":"Your Email"},"value":"NewValue"}
</code>```

Body:
What's in an Event Trigger?

If you want to know what an event object has in it then you can do something like this:

function onEdit(e) {
  Logger.log(JSON.stringify(e));
}

In the case of a simple onEdit() trigger this is what it contains:

[19-05-30 10:19:36:809 MDT] {"authMode":{},"range":{"columnStart":4,"rowStart":4,"rowEnd":4,"columnEnd":4},"source":{},"user":{"nickname":"Your Nickname","email":"Your Email"},"value":"NewValue"}


问:
Search robots can't index because of assets present rails heroku
On these websites https://staging.blockbutler.io and https://blockbutler.io (RoR on heroku both)
Google and Yandex search bots can't index with reason: 'robots.txt blocks'
but robots.txt is fine. And if you will remove
javascript_include_tag and stylesheet_link_tag it perfectly indexed the page. I spent 3 days of trying different tests - nothing helps:

if there are only javascript_include_tag with empty
application.js or only stylesheet_link_tag with empty
application.scss - no indexing

add gem 'rails_12factor' - no
indexing

rake assets:precompile RAILS_ENV=production and push static files from public/assets to server - no indexing

put assets in footer - no indexing

wrap assets in <noindex> and rel: "nofollow" - no indexing

I really don't know what da magic is going on and be really happy for any ideas

Logs when run google search console live test:

production.rb:

```<code>config.assets.js_compressor = :uglifier
config.assets.enabled = true
config.assets.version = '1.0'
config.assets.compile = true
</code>```

robots.txt:

```<code>User-agent: *
Allow: /

User-agent: Yandex
Allow: /

User-agent: Google
Allow: /

Sitemap: https://blockbutler.io/sitemap.xml
</code>```

p.s. sorry for bad english - will appreciate editing my language (:

答:
Some freaking magic over here.
Change <%= javascript_include_tag 'application', rel: "nofollow" %> to

And now google indexer works just fine. GooGLe InDExER DoesN'T LiKE BIg fiLe NamES. Will think about how to prevent cache assets file.

p.s. ok. Now every time Im updating assets - Im changing assets name, like applicationv0.js and etc. Still have no idea, why google wasn't ok with default application-hash.js filename

Body:
On these websites https://staging.blockbutler.io and https://blockbutler.io (RoR on heroku both)
Google and Yandex search bots can't index with reason: 'robots.txt blocks'
but robots.txt is fine. And if you will remove
javascript_include_tag and stylesheet_link_tag it perfectly indexed the page. I spent 3 days of trying different tests - nothing helps:

if there are only javascript_include_tag with empty
application.js or only stylesheet_link_tag with empty
application.scss - no indexing

add gem 'rails_12factor' - no
indexing

rake assets:precompile RAILS_ENV=production and push static files from public/assets to server - no indexing

put assets in footer - no indexing

wrap assets in <noindex> and rel: "nofollow" - no indexing

I really don't know what da magic is going on and be really happy for any ideas

Logs when run google search console live test:

production.rb:

config.assets.js_compressor = :uglifier
config.assets.enabled = true
config.assets.version = '1.0'
config.assets.compile = true

robots.txt:

User-agent: *
Allow: /

User-agent: Yandex
Allow: /

User-agent: Google
Allow: /

Sitemap: https://blockbutler.io/sitemap.xml

p.s. sorry for bad english - will appreciate editing my language (:

Body:
Some freaking magic over here.
Change <%= javascript_include_tag 'application', rel: "nofollow" %> to <script src="/assets/application.js" rel="nofollow"></script>

And now google indexer works just fine. GooGLe InDExER DoesN'T LiKE BIg fiLe NamES. Will think about how to prevent cache assets file.

p.s. ok. Now every time Im updating assets - Im changing assets name, like applicationv0.js and etc. Still have no idea, why google wasn't ok with default application-hash.js filename


问:
Get a big List<T> from WCF in chunks?
I'm trying to get a list of entities from a WCF service, the problem I'm experiencing is that we have some bad latency on the network and so the data takes a considerable amount of time to get to my client. The idea I have is to find a way to get the first 1000 and just push those to the UI while I'm waiting for the next ones to arrive.

I guess it would be like paging but I just want to page the full set in the WCF layer rather that get one page at a time from the db

Cheers

答:
In the end as I'm using tcpTransport for my communication, I ended using duplex channels to do what I needed.

What I did is just change my current SearchMethod that was returning a big list to void. Inside this method I get my data from the DB, chunk it and send it to the client via a callback operation

Title: Get a big List<T> from WCF in chunks?


问:
Custom exception from Messenger handler
I try Symfony 4.3.0-dev version to get some new features from Messenger component. My command bus works in sync mode.

Before upgrading I could easily throw my custom exception ConflictException from handler. But for 4.3.0-dev I get a Symfony\Component\Messenger\Exception\HandlerFailedException.

How can I catch my custom exception again?

答:
As you can see on CHANGELOG, a BC break was introduced in version 4.3.
In my application I was catching exceptions, and I solved by adding following code:</p>

```<code>if ($exception instanceof HandlerFailedException) {
    $exception = $exception->getPrevious();
}
</code>```

Title: Custom exception from Messenger handler

Body:
As you can see on CHANGELOG, a BC break was introduced in version 4.3.
In my application I was catching exceptions, and I solved by adding following code:

if ($exception instanceof HandlerFailedException) {
    $exception = $exception->getPrevious();
}


问:
Laravel/Eloquent escape quote character
I'm using Laravel for the first time and I'm encountering a SQL syntax error when saving an Eloquent model to the DB.

SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 's'. (SQL: update [plan_part] set [plan_id] = 48, [is_astm_testing_complete] = 0, [supplier_part_weight] = .0308, [hazard_class_type_id] = 42, [supplier_additional_details] = test's, [modified_by] = 1003 where [plan_part_id] = 55826)

It has to do with supplier_additional_details = test's where I have an apostrophe in the value.

I'm confused as to why this is happening because I thought the Eloquent save method was using PHP's PDO and bound parameters, as evidenced by the stack trace in the error response:

 Connection->runQueryCallback('update [plan_part] set [plan_id] = ?, [is_astm_testing_complete] = ?, [supplier_part_weight] = ?, [hazard_class_type_id] = ?, [supplier_additional_details] = ?, [modified_by] = ? where [plan_part_id] = ?', array('48', 0, '.0308', '42', 'test\'s', 1003, '55826'), object(Closure))

I can see that the apostrophe appears to have been automatically escaped (I didn't do anything to add the slash), but don't bound parameters automatically do this for me?

Why is Laravel erroring out on this when it appears to have been escaped properly anyway? Am I expected to manually escape every single input in my controller logic?

That seems wrong and unnecessary, but again, I'm not super familiar with Eloquent/Laravel.

The save logic is pretty straightforward:

$plan_part = PlanPart::find(...);
...
$plan_part->supplier_additional_details = $request->supplier_additional_details;
$plan_part->save();

What am I doing wrong?

FWIW, I'm using a SQL Server not MySQL, so I'm not sure if there a nuances there that I don't understand.

UPDATE
Looks like SQL Server uses double single-quotes instead of slashed single-quotes for escaping. Anyone know what I'm supposed to do to get Laravel to work with SQL Server better?

答:
The issue was that our PHP web server was not configured with the appropriate SQLSRV PDO drivers.  We had a goofy setup where we were running PHP on a FreeBSD box but pointing to a SQL Server database.  The FreeBSD box did not have the PDO drivers for SQL Server and Microsoft doesn't provide any for that particular OS without requiring manual compilation, etc.

We ended up migrating our web servers to IIS and were able to rectify the problem by installing the Microsoft-provided SQLSRV PDO drivers for IIS/Windows.

Title: Laravel/Eloquent escape quote character


问:
Remove character from dynamic string
I have a file with some junk values and i need to get rid of them while loading that file into a table.
Giving here some example. File is semicolon separated, and last column has those junk values.

```<code>2019-02-20;05377378;ABC+xY+++Rohit Anita Chicago
2019-02-20;05201343;ABC+xY++Gustav Russia
2019-02-20;07348738;ABC+xy+++Jain Ram Ambarnath
</code>```

Now the last column I have to load without ABC+xY+++  value.
but some row i have ABC+xY+++ and some ABC+xY++. any suggestion to get rid of this. which means 2 times or 3 times + is available

I am using informatica powercenter for loading this file.
in expression i need to create some substr/instr function. which i can put test here in oracle sql as well to understand quickly if the value coming is properly.

and my expected output is

Any suggestion please.

Thanks,
Bithun

答:
This is the solution.

```<code>substr
    (
        Address,
        0,
        instr(Address ,';',-1)
    )
    ||
substr
    (
        Address,
        instr(Address ,'+',-1)
    )
</code>```

you may want to add +1 in substr start / end position depending on the needs.

Title: Remove character from dynamic string

Body:
I have a file with some junk values and i need to get rid of them while loading that file into a table.
Giving here some example. File is semicolon separated, and last column has those junk values.

2019-02-20;05377378;ABC+xY+++Rohit Anita Chicago
2019-02-20;05201343;ABC+xY++Gustav Russia
2019-02-20;07348738;ABC+xy+++Jain Ram Ambarnath

Now the last column I have to load without ABC+xY+++  value.
but some row i have ABC+xY+++ and some ABC+xY++. any suggestion to get rid of this. which means 2 times or 3 times + is available

I am using informatica powercenter for loading this file.
in expression i need to create some substr/instr function. which i can put test here in oracle sql as well to understand quickly if the value coming is properly.

and my expected output is

Any suggestion please.

Thanks,
Bithun

Body:
This is the solution.

substr
    (
        Address,
        0,
        instr(Address ,';',-1)
    )
    ||
substr
    (
        Address,
        instr(Address ,'+',-1)
    )

you may want to add +1 in substr start / end position depending on the needs.


问:
Http_user_agent not detected in Nginx
I want to block some user agents but NGinx seems not to see it.

I did use the map
calling the map from the http section and having the test in the server section (like show on many tutorials)

```<code>map $http_user_agent $badagent {
    default         0;
  ~*archive.org_bot 1;
  ~*Anemone         1;
  ~*Ant.com         1;
  ~*Baidu           1;
  ~*Bot/1.0         1;
  ~*Companybook     1;
  ~*Go-http-client  1;
  ~*Pcore-HTTP      1;
}
</code>```

then in the server section

```<code>if ($badagent) {
  return 444;
}
</code>```

i've tried that too

```<code>if ($badagent = 1) {
  return 444;
}
</code>```

to make it easier i even tried that :

```<code>if ($http_user_agent="Mozilla") {return 404;}
</code>```

and

```<code>if ($http_user_agent = "Mozilla") {return 404;}
</code>```

there is no error, but even after restart, my browser is not blocked. What did i did wrong ?

答:
I found the issue.

I have a nginx.conf file AND a mydomain.conf file.

Whenever the instruction was in my main nginx.conf file (that is parsed and part of the config), the instruction/test was not taken into consideration.
But as soon as i moved the intruction in mydomain.conf file, then everything was working fine.

Title: Http_user_agent not detected in Nginx

Body:
I want to block some user agents but NGinx seems not to see it.

I did use the map
calling the map from the http section and having the test in the server section (like show on many tutorials)

map $http_user_agent $badagent {
    default         0;
  ~*archive.org_bot 1;
  ~*Anemone         1;
  ~*Ant.com         1;
  ~*Baidu           1;
  ~*Bot/1.0         1;
  ~*Companybook     1;
  ~*Go-http-client  1;
  ~*Pcore-HTTP      1;
}

then in the server section

if ($badagent) {
  return 444;
}

i've tried that too

if ($badagent = 1) {
  return 444;
}

to make it easier i even tried that :

if ($http_user_agent="Mozilla") {return 404;}

and

if ($http_user_agent = "Mozilla") {return 404;}

there is no error, but even after restart, my browser is not blocked. What did i did wrong ?


问:
Connecting SQL Server with ASP.NET using Windows Authentication
I am getting below exception while connecting ASP.NET with SQLSERVER using below connection strings.i tried two methods.

Exception

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL

Connection String

```<code>    protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con;
            con = new SqlConnection("Server=ADMIN/SQLEXPRESS,Database=test,integrated security=true");
            con.Open();

        }

              (or)

    protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con;
            con = new SqlConnection("Server=localhost;Database=test;integrated security=sspi");
            con.Open();

        }
</code>```

i am connecting SQLSERVER directly by using below server name in windows authentication.It is connecting well but it is not connected from asp.net

Server Name:ADMIN\SQLEXPRESS

答:
A connection string for  SQL server should be like this: "Server=localhost; Database=Testdb; Integrated Security=True;"
and If you have Named Instance e.g localhost\SQLEXPRESS

```<code>Integrated Security=?
</code>```

When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.
Recognized values are true, false, yes, no, and SSPI (strongly recommended), which is equivalent to true.check connectionstrings

Body:
I am getting below exception while connecting ASP.NET with SQLSERVER using below connection strings.i tried two methods.

Exception

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL

Connection String

    protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con;
            con = new SqlConnection("Server=ADMIN/SQLEXPRESS,Database=test,integrated security=true");
            con.Open();

        }

              (or)

    protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con;
            con = new SqlConnection("Server=localhost;Database=test;integrated security=sspi");
            con.Open();

        }

i am connecting SQLSERVER directly by using below server name in windows authentication.It is connecting well but it is not connected from asp.net

Server Name:ADMIN\SQLEXPRESS

Body:
A connection string for  SQL server should be like this: "Server=localhost; Database=Testdb; Integrated Security=True;"
and If you have Named Instance e.g localhost\SQLEXPRESS

Integrated Security=?

When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.
Recognized values are true, false, yes, no, and SSPI (strongly recommended), which is equivalent to true.check connectionstrings


问:
React-to-print: how to change state in onAfterPrint when closing print window
I am using react-to-print library, and using that, I want to change a state when closing print window.

When I click cancel button, it works fine. However, if I click X (exit) button, it will crash.

I have the following code.

```<code><ReactToPrint
  trigger={() => (
    ...
  )}
  content={() => ...}
  onBeforePrint={() => { this.setState({ printState: true}) }}
  onAfterPrint={() => { this.setState({ printState: false }) }}
  closeAfterPrint
/>
</code>```

Here's the error message

Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

答: It might not be it, but try using onAfterPrint={() => this.handlePrintAfter()}

Body:
I am using react-to-print library, and using that, I want to change a state when closing print window.

When I click cancel button, it works fine. However, if I click X (exit) button, it will crash.

I have the following code.

<ReactToPrint
  trigger={() => (
    ...
  )}
  content={() => ...}
  onBeforePrint={() => { this.setState({ printState: true}) }}
  onAfterPrint={() => { this.setState({ printState: false }) }}
  closeAfterPrint
/>

Here's the error message

Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.


问:
Avoiding copying large objects in R - does get() function make copy?
I have an inherited some R code that uses an idiom to avoid copying of large data frames. When a function that builds the data frame finishes, it does not return the data frame, but instead stores it in the global environment context:

```<code>assign(df_name, df, envir = globalenv())
</code>```

After the function finishes, the calling code retrieves the data frame with this:

```<code>df <- get(df_name, envir = globalenv())
</code>```

My question is this: does the get() function itself actually make a copy when it returns a value, thus creating the very copy that this idiom was meant to avoid? If so, is there a better way of doing this?

答:
In a word, this is nonsense. What makes copies here are the two assignments (both via assign and <-). Just returning the object from the function would have saved one of the copies.

Incidentally, the copying itself is cheap, since R implements a concept called “copy on write” semantics: The commands above logically do make copies, but physically that only increases a reference counter inside the copied reference. The actual data behind the reference is copied only when you modify the data via one of the references.

Body:
I have an inherited some R code that uses an idiom to avoid copying of large data frames. When a function that builds the data frame finishes, it does not return the data frame, but instead stores it in the global environment context:

assign(df_name, df, envir = globalenv())

After the function finishes, the calling code retrieves the data frame with this:

df <- get(df_name, envir = globalenv())

My question is this: does the get() function itself actually make a copy when it returns a value, thus creating the very copy that this idiom was meant to avoid? If so, is there a better way of doing this?


问:
How to know how often an external link is clicked?
This page: http://funds.ft.com/CityofLondon/investmentmanagement/HCEWUR contains a number of links under the section "Annual Reports & Factsheets". The content these links point at is hosted at fundslibrary.co.uk, a 3rd party supplier.

Is there any way for us to track how often these links are clicked? We don't have access to the 3rd party web server logs.

One way I'm thinking is to POST an instruction to increment a count with jQuery every time the link is clicked, but that would mean us having to maintain the count.

Is there any functionality in Google Analytics that could give us this info?

答:
Google analytics will tell you how many exits for a page in a given time period.  It cannot tell you where they went to though unless it was to another page in your site.  If you want to log where they went when that then you probably would need to do some javascript to send the information back to the server on the click.

You could feed all your outside links though a page on your site, put the url in the query string, then you process the request add to your tracking tables, and then redirect them to where they wanted to go, but then you would have to change every link you want to track.


问:
Google Sheets Custom functions - simplifying calling, with convenience functions
I would like to have a custom function handle most of the complexity of
this type of formula, not have to type it in each cell.

```<code>=sparkline({B3-$B$2,C3-B3},{"charttype","bar"; "color1", "white";"color2","blue";"max",$D$2})
</code>```

From reading the docs, it appears that you cannot invoke a built-in function
from within a custom function. sigh!

My next thought would be: can I have a custom function that returns the parameters
required by "SPARKLINE", so the formula I enter in the call would look like

```<code>=sparkline({B3-$B$2,C3-B3}, MYGETPARAMS())

//  * @customfunction
function MYGETPARAMS() {
  return {"charttype":"bar", "max":20, "color1": "white", "color2": "green"};
}
</code>```

However the params don't appear to be in js dict format. Any ideas?

答:
You don't have to type it in each cell. You can set up these settings elsewhere in your sheet(say,Y2:Z4). Then, You can use it like,

```<code>=sparkline({B3-$B$2,C3-B3},Y2:Z4)
</code>```

Where Y1:Z4 looks like:

```<code>    CHART SETTINGS
    charttype    bar
    color1    white
    color2    blue
    max    =$D$2
</code>```

Body:
I would like to have a custom function handle most of the complexity of
this type of formula, not have to type it in each cell.

=sparkline({B3-$B$2,C3-B3},{"charttype","bar"; "color1", "white";"color2","blue";"max",$D$2})

From reading the docs, it appears that you cannot invoke a built-in function
from within a custom function. sigh!

My next thought would be: can I have a custom function that returns the parameters
required by "SPARKLINE", so the formula I enter in the call would look like

=sparkline({B3-$B$2,C3-B3}, MYGETPARAMS())

//  * @customfunction
function MYGETPARAMS() {
  return {"charttype":"bar", "max":20, "color1": "white", "color2": "green"};
}

However the params don't appear to be in js dict format. Any ideas?

Body:
You don't have to type it in each cell. You can set up these settings elsewhere in your sheet(say,Y2:Z4). Then, You can use it like,

=sparkline({B3-$B$2,C3-B3},Y2:Z4)

Where Y1:Z4 looks like:

    CHART SETTINGS
    charttype    bar
    color1    white
    color2    blue
    max    =$D$2


问:
It is possible to rename defaults java packages without breaking Jhipster generator capabilities?
I'm starting a new project with JHipster-6.0.1 and I would like to know whether is possible to rename defaults java packages without breaking JHipster generator capabilities. For example:

from myapp.aop.logging to myapp.infrastructure.logging

from myapp.config to myapp.infrastructure.config

from myapp.security to myapp.infrastructure.security

from myapp.service to myapp.infrastructure.service

from myapp.domain  to myapp.infrastructure.jpa

答:
The first 4 changes are possible by changing packageName in .yo-rc.json or JDL file and then re-generating the app.

The 5th change from myapp.domain to myapp.infrastructure.jpa is not possible with the generator as it is, it can be done by writing a blueprint.


问:
Numpy empty array changes value after creating normal array
I read on the official numpy page that there was an alternative to creating an initialised array without using just zeros:

empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster.

I created two functions below that demonstrate an unusual issue with using this function:

```<code>import numpy as np

def getInitialisedArray():
    return np.empty((), dtype=np.float).tolist()

def createFloatArray(x):
    return np.array(float(x))
</code>```

If I just call getInitialisedArray() on its own, here is what it outputs:

```<code>>>> getInitialisedArray()
0.007812501848093234
</code>```

And if I just call the createFloatArray() function:

```<code>>>> createFloatArray(3.1415)
3.1415
</code>```

This all seems fine, but if I repeat the test and call the getInitialisedArray() after creating the float array, there is an issue:

```<code>print(getInitialisedArray())
print(createFloatArray(3.1415))
print(getInitialisedArray())
</code>```

Output:

```<code>>>>
0.007812501848093234
3.1415
3.1415
</code>```

It seems the second call to get an initialised array gets the same value as what was put in the normal np.array(). I don't get why this occurs. Shouldn't they be separate arrays that have no link between each other?

--- Update ---

I repeated this and changed the size of the empty array:

```<code>import numpy as np

def getInitialisedArray():
    # Changed size to 2 x 2
    return np.empty((2, 2), dtype=np.float).tolist()

def createFloatArray(x):
    return np.array(float(x))

print(getInitialisedArray())
print(createFloatArray(3.1415))
print(getInitialisedArray())
</code>```

Output:

```<code>[[1.6717403e-316, 6.9051865033801e-310], [9.97338022253e-313, 2.482735075993e-312]]
3.1415
[[1.6717403e-316, 6.9051865033801e-310], [9.97338022253e-313, 2.482735075993e-312]]
</code>```

This is the sort of output I was expecting, but here it works because I changed the size. Does size now affect if an empty array takes on the same value of a normal np.array()?

答:
Check id() for each array after initializing it. np.empty() creates space that later can be used after initializing array of the same shape.

for more understanding:
print(np.array(float(1))
print(np.empty((),dtype=np.float).tolist())

same thing but assigning to variables:
x = np.array(float(1))
y = np.empty((),dtype=np.float).tolist()
print(x)
print(y)

Body:
I read on the official numpy page that there was an alternative to creating an initialised array without using just zeros:

empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster.

I created two functions below that demonstrate an unusual issue with using this function:

import numpy as np

def getInitialisedArray():
    return np.empty((), dtype=np.float).tolist()

def createFloatArray(x):
    return np.array(float(x))

If I just call getInitialisedArray() on its own, here is what it outputs:

>>> getInitialisedArray()
0.007812501848093234

And if I just call the createFloatArray() function:

>>> createFloatArray(3.1415)
3.1415

This all seems fine, but if I repeat the test and call the getInitialisedArray() after creating the float array, there is an issue:

print(getInitialisedArray())
print(createFloatArray(3.1415))
print(getInitialisedArray())

Output:

>>>
0.007812501848093234
3.1415
3.1415

It seems the second call to get an initialised array gets the same value as what was put in the normal np.array(). I don't get why this occurs. Shouldn't they be separate arrays that have no link between each other?

--- Update ---

I repeated this and changed the size of the empty array:

import numpy as np

def getInitialisedArray():
    # Changed size to 2 x 2
    return np.empty((2, 2), dtype=np.float).tolist()

def createFloatArray(x):
    return np.array(float(x))

print(getInitialisedArray())
print(createFloatArray(3.1415))
print(getInitialisedArray())

Output:

[[1.6717403e-316, 6.9051865033801e-310], [9.97338022253e-313, 2.482735075993e-312]]
3.1415
[[1.6717403e-316, 6.9051865033801e-310], [9.97338022253e-313, 2.482735075993e-312]]

This is the sort of output I was expecting, but here it works because I changed the size. Does size now affect if an empty array takes on the same value of a normal np.array()?


问:
Why does MS SQL allow you to create an illegal column?
I recently saw a tweet stating that you could prevent other developers from reading from a table using the SELECT * FROM TableName by building your table in the following way:

```<code>CREATE TABLE [TableName]
(
   [ID] INT IDENTITY NOT NULL,
   [Name] VARCHAR(50) NOT NULL,
   [DontUseStar] AS (1 / 0)
);
</code>```

It's easy to see that using the SELECT * here would try to read the blank column name as 1 divided by 0 (thus causing a divide by zero error), but without a datatype assigned to the column.

Why does SQL allow you to create a column with no assigned data type, with a name it knows will be illegal?

答:
What you have created is a computed column and it is quite powerful and useful!

The expression can be anything.  For instance, you could define:

```<code>CREATE TABLE [TableName] (
   [ID] INT IDENTITY NOT NULL,
   [Name] VARCHAR(50) NOT NULL,
   NameLength as (LEN(Name))
);
</code>```

This would create a column called NameLength and it would always have the length of Name when you refer to it -- no updates, no triggers, no views.  It just works.

You don't need a type because SQL Server can figure that out.

The error that you have can even be beneficial -- if you really want to enforce that users never use select *.

Body:
I recently saw a tweet stating that you could prevent other developers from reading from a table using the SELECT * FROM TableName by building your table in the following way:

CREATE TABLE [TableName]
(
   [ID] INT IDENTITY NOT NULL,
   [Name] VARCHAR(50) NOT NULL,
   [DontUseStar] AS (1 / 0)
);

It's easy to see that using the SELECT * here would try to read the blank column name as 1 divided by 0 (thus causing a divide by zero error), but without a datatype assigned to the column.

Why does SQL allow you to create a column with no assigned data type, with a name it knows will be illegal?

Body:
What you have created is a computed column and it is quite powerful and useful!

The expression can be anything.  For instance, you could define:

CREATE TABLE [TableName] (
   [ID] INT IDENTITY NOT NULL,
   [Name] VARCHAR(50) NOT NULL,
   NameLength as (LEN(Name))
);

This would create a column called NameLength and it would always have the length of Name when you refer to it -- no updates, no triggers, no views.  It just works.

You don't need a type because SQL Server can figure that out.

The error that you have can even be beneficial -- if you really want to enforce that users never use select *.


问:
Migrating Oracle query to PostgreSQL
Can you please help me with this? How can I convert below query to PostgreSQL.

The query below gives different output when executed in PostgreSQL than when executed in Oracle.

```<code>SELECT
  to_char(to_date('01011970','ddmmyyyy') + 1/24/60/60 * 4304052,'dd-mon-yyyy hh24:mi:ss')
from dual;
</code>```

答:
Let's assume you want to use the same expression as in Oracle to compute the  resulting value.

The reason it is not working when you simply remove from dual is because this expression is being evaluated to 0 as integer division truncates results towards 0.

```<code>select 1/24/60/60 * 4304052;
 ?column?
----------
        0
(1 row)
</code>```

If I make one of them a decimal, it will give you the required result

```<code>select 1.0/24/60/60 * 4304052;
          ?column?
-----------------------------
 49.815416666666666347848000
</code>```

Now, after changing this, your expression will return the same result you got in Oracle.

```<code>SELECT  to_char( to_date('01011970','ddmmyyyy')
 +  INTERVAL '1 DAY' *  (1.0/24/60/60 * 4304052) ,'dd-mon-yyyy hh24:mi:ss') ;
       to_char
----------------------
 19-feb-1970 19:34:12
(1 row)
</code>```

Note that I had to add an interval expression, because unlike Oracle, a Postgres DATE does not store time component and simply adding a number to date will result in an error. Using an interval will ensure that it will be evaluated as timestamp.

```<code>knayak=# select pg_typeof( current_date);
 pg_typeof
-----------
 date
(1 row)

knayak=# select pg_typeof( current_date + INTERVAl '1 DAY');
          pg_typeof
-----------------------------
 timestamp without time zone
(1 row)
</code>```

Title: Migrating Oracle query to PostgreSQL

Body:
Can you please help me with this? How can I convert below query to PostgreSQL.

The query below gives different output when executed in PostgreSQL than when executed in Oracle.

SELECT
  to_char(to_date('01011970','ddmmyyyy') + 1/24/60/60 * 4304052,'dd-mon-yyyy hh24:mi:ss')
from dual;

Body:
Let's assume you want to use the same expression as in Oracle to compute the  resulting value.

The reason it is not working when you simply remove from dual is because this expression is being evaluated to 0 as integer division truncates results towards 0.

select 1/24/60/60 * 4304052;
 ?column?
----------
        0
(1 row)

If I make one of them a decimal, it will give you the required result

select 1.0/24/60/60 * 4304052;
          ?column?
-----------------------------
 49.815416666666666347848000

Now, after changing this, your expression will return the same result you got in Oracle.

SELECT  to_char( to_date('01011970','ddmmyyyy')
 +  INTERVAL '1 DAY' *  (1.0/24/60/60 * 4304052) ,'dd-mon-yyyy hh24:mi:ss') ;
       to_char
----------------------
 19-feb-1970 19:34:12
(1 row)

Note that I had to add an interval expression, because unlike Oracle, a Postgres DATE does not store time component and simply adding a number to date will result in an error. Using an interval will ensure that it will be evaluated as timestamp.

knayak=# select pg_typeof( current_date);
 pg_typeof
-----------
 date
(1 row)

knayak=# select pg_typeof( current_date + INTERVAl '1 DAY');
          pg_typeof
-----------------------------
 timestamp without time zone
(1 row)


答:
It a perfectly valid syntax for a computed column. Computed columns can be used to calculate some value on select without actually storing them, although the value can be persisted.

The reason why 1/0 is allowed, is because the actual computed column value not evaluated until runtime. For example the computed column can be defined as columna/columnb, the same error will occur if any row in columnb has a 0 and is , but only if that row/column was selected.

```<code>if object_id('tempdb..#t') IS NOT NULL
    drop table #t;

CREATE TABLE #t
(a int
,b int
,div as (a/b)
);

INSERT INTO #t
values
(1,1)
,(2,0);

SELECT * FROM #t WHERE a = 1;
SELECT a from #t; -- NO ERRORS

SELECT * FROM #t WHERE a=2; --WILL RESULT IN AN ERROR
SELECT * FROM #t; --WILL RESULT IN AN ERROR
</code>```

https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-2017

Title: Why does MS SQL allow you to create an illegal column?

Body:
It a perfectly valid syntax for a computed column. Computed columns can be used to calculate some value on select without actually storing them, although the value can be persisted.

The reason why 1/0 is allowed, is because the actual computed column value not evaluated until runtime. For example the computed column can be defined as columna/columnb, the same error will occur if any row in columnb has a 0 and is , but only if that row/column was selected.

if object_id('tempdb..#t') IS NOT NULL
    drop table #t;

CREATE TABLE #t
(a int
,b int
,div as (a/b)
);

INSERT INTO #t
values
(1,1)
,(2,0);

SELECT * FROM #t WHERE a = 1;
SELECT a from #t; -- NO ERRORS

SELECT * FROM #t WHERE a=2; --WILL RESULT IN AN ERROR
SELECT * FROM #t; --WILL RESULT IN AN ERROR

https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-2017


问:
Short argument in boost::program_options without long
Is it possible to specify an argument with boost::program_options with short option only?
The answer given here is to use allow_long_disguise, which will result in long options being acceptable with a single dash. Is there any way to make some options short-only (single dash and single character), without using allow_long_disguise?

答: No, the library does not support this.</p>

Body: No, the library does not support this.


问:
Force progress bar component to re-render after progress prop has changed
How can I force a component to re-render after a passed-in prop has changed?

Premise: On my base page, I have a progress bar. From that base page, the user can access a number of modal pages. The progress bar should visualise how many modals the user has viewed.

In principle, most of it works. The only problem is that my progress bar component does not re-render my visual progress bar when the passed-in progress prop changes.

```<code><ProgressBar
    progress={ this.props.progress }
/>
</code>```

The progress bar component itself is aware of the change and will happily re-render a text field that prints the value of progress to reflect the updated value. However, it will not re-render the visual progress bar (a series of view components with styling) in a way that reflects the changed prop. The text field changes, the views do not.

Here's my code. Could it be that I need to repeat the calculations I do in ComponentDidMount() in some kind of update function as well?

```<code>// Progress Bar component
export default class ProgressBar extends React.Component {

    state = {
        // define some variables
    }

    componentDidMount() {
        // do some math using this.props.progress and state
        // to calculate the percentage etc that the views use to
        // display the length of the progress bar
    }

    componentWillUpdate( prevProps, prevState ) {
        // I tried repeating the above calculations in here as well
        // but anything I place in here will result in error message:
        // Invariant Violation: Maximum update depth exceeded...
    }

    render() {
        // a number of views that create a visual progress bar
        // entirely dependent on calculated values, i.e. not directly
        // referencing this.props.progress
    }
</code>```

}

Any guidance would be much appreciated!

答:
When the passed props change getDerivedStateFromProps() is called before render method. In here you can compare the current state with the new data and return an object or null to update nothing.

```<code>static getDerivedStateFromProps(props, state)
</code>```

Body:
How can I force a component to re-render after a passed-in prop has changed?

Premise: On my base page, I have a progress bar. From that base page, the user can access a number of modal pages. The progress bar should visualise how many modals the user has viewed.

In principle, most of it works. The only problem is that my progress bar component does not re-render my visual progress bar when the passed-in progress prop changes.

<ProgressBar
    progress={ this.props.progress }
/>

The progress bar component itself is aware of the change and will happily re-render a text field that prints the value of progress to reflect the updated value. However, it will not re-render the visual progress bar (a series of view components with styling) in a way that reflects the changed prop. The text field changes, the views do not.

Here's my code. Could it be that I need to repeat the calculations I do in ComponentDidMount() in some kind of update function as well?

// Progress Bar component
export default class ProgressBar extends React.Component {

    state = {
        // define some variables
    }

    componentDidMount() {
        // do some math using this.props.progress and state
        // to calculate the percentage etc that the views use to
        // display the length of the progress bar
    }

    componentWillUpdate( prevProps, prevState ) {
        // I tried repeating the above calculations in here as well
        // but anything I place in here will result in error message:
        // Invariant Violation: Maximum update depth exceeded...
    }

    render() {
        // a number of views that create a visual progress bar
        // entirely dependent on calculated values, i.e. not directly
        // referencing this.props.progress
    }

}

Any guidance would be much appreciated!

Body:
When the passed props change getDerivedStateFromProps() is called before render method. In here you can compare the current state with the new data and return an object or null to update nothing.

static getDerivedStateFromProps(props, state)


问:
Freeling Python API working on sample, get Import error on other code
I'm trying out Freeling's API for python. The installation and test were ok, they provide a sample.py file that works perfectly (I've played around a little bit with it and it works).

So I was trying to use it on some other python code I have, in a different folder (I'm kind of guessing this is a path issue), but whenever I import freeling (like it shows on the sample.py):

```<code>import freeling

FREELINGDIR = "/usr/local";
DATA = FREELINGDIR+"/share/freeling/";
LANG="es";
freeling.util_init_locale("default");
</code>```

I get this error:

```<code>ModuleNotFoundError: No module named 'freeling'.
</code>```

The sample.py is located on the ~/Freeling-4.0/APIs/Python/ folder, while my other file is located in ~/project/, I dont know if that can be an issue.
Thank you!

答:
A simple solution is to have a copy of freeling.py in the same directory as your code, since python will look there.

A better solution is to either paste it in one of the locations where it usually checks (like the lib folder in its install directory), or to tell it that the path where your file is should be scanned for a module.

You can check out this question to see how it can be done on Windows. You are basically just setting the PYTHONPATH environment variable, and there will only be minor differences in how to do so for other OSes. This page gives instructions that should work on Linux systems.

I like this answer since it adds the path at runtime in the script itself, doesn't make persistent changes, and is largely independent of the underlying OS (apart from the fact that you need to use the appropriate module path of course).

Body:
I'm trying out Freeling's API for python. The installation and test were ok, they provide a sample.py file that works perfectly (I've played around a little bit with it and it works).

So I was trying to use it on some other python code I have, in a different folder (I'm kind of guessing this is a path issue), but whenever I import freeling (like it shows on the sample.py):

import freeling

FREELINGDIR = "/usr/local";
DATA = FREELINGDIR+"/share/freeling/";
LANG="es";
freeling.util_init_locale("default");

I get this error:

ModuleNotFoundError: No module named 'freeling'.

The sample.py is located on the ~/Freeling-4.0/APIs/Python/ folder, while my other file is located in ~/project/, I dont know if that can be an issue.
Thank you!


问:
How to make a slack dialog with more than 5 inputs ? Node Slack API
I'm currently handling with a problem. I need to make like a form to create something like this:

So, I'm trying to make a form with a Slack's Dialog but my problem is that only supports 5 inputs, this is my current process:

Is there another way to input text or dropdowns and return that kind of format ? or how can I add more inputs (5+) to a dialog ?

答:
Currently the limit is 10 for each dialog. In case you need to retain the state of the previous dialog, or want to get the previous dialog input values in the next dialog submit processors, you can use state field in the dialog attachment. The state field take values as text and you can possibly put a delimiter like below:

"state": "input1|input2|inout3...|input10"

and get the values in the next dialog processor.


问:
Get orientation of scroll given AccessibilityNodeInfo
I am creating a script that explore different android applications. If the script finds a scrollable component during the exploration this one must be scrolled. The problem is that sometimes the scroll direction can be horizontal or vertical and I would like to know it before perform the scrolling action.

Given an AccessibilityNodeInfo of a scrollable component (e. g. RecyclerView), is it possible to know in which directions the RecyclerView is scrollable (vertical or horizontal)?

答: The presence of ACTION_SCROLL_UP/DOWN/LEFT/RIGHT is the API that gives you this information. Unfortunately, the original API of ACTION_SCROLL_FORWARD/BACKWARD is very common and doesn't tell you which direction. So, like pretty much everything in the accessibility API, it depends on the app and widget sharing the information with you.</p>