问:
C# About the Ref<T> class i've found
Link to the class :

https://stackoverflow.com/a/4543089/6591306

My question is simple, the usage of the class is as so :

The getter is getting () => variable, and the setter is getting z => { variable = z; }

In order to call the function i call it like this :

```<code>ref<int> tempx;
int tempy = 5;
tempx=new Ref<int>(() => tempy, z => { tempy = z; });
tempy = 6;//tempx.Value becomes 6
tempx.Value = 7;//tempy becomes 7
</code>```

I want to achieve that in order to call the class i'll do it :

```<code>tempx=new Ref<int>(tempy);
</code>```

without writing the actions, so that it won't take alot of lines of code, and the actions will be saved in the class, and whenever i call it they'll be performed automatically.

I dont know how to achieve it, therefore i'm asking here.

答: You can't.  There's no way to pass in an int and end up with the ability to get or set it at some arbitrary point in time in the future; you need to create lambdas in order to be able to do that.

Title: C# About the Ref<T> class i've found

Body:
Link to the class :

https://stackoverflow.com/a/4543089/6591306

My question is simple, the usage of the class is as so :

The getter is getting () => variable, and the setter is getting z => { variable = z; }

In order to call the function i call it like this :

ref<int> tempx;
int tempy = 5;
tempx=new Ref<int>(() => tempy, z => { tempy = z; });
tempy = 6;//tempx.Value becomes 6
tempx.Value = 7;//tempy becomes 7

I want to achieve that in order to call the class i'll do it :

tempx=new Ref<int>(tempy);

without writing the actions, so that it won't take alot of lines of code, and the actions will be saved in the class, and whenever i call it they'll be performed automatically.

I dont know how to achieve it, therefore i'm asking here.


来源: stackexchange

问:
How to check if a float is infinity/zero/denormal?
```<code>int is_infinity/is_zero/is_denormal(float f){
    //do something, return 0 or 1
}
</code>```

This is what I did for checking if a float is negative.  I want to do something similar for the other functions, but I'm not sure how.

```<code>int is_negative(float val){
    union sp_object copy;
    copy.frep = val;
    if((copy.irep & 0x80000000) != 0)
        return 1;
    else
        return 0;
}
</code>```

答:
I want to do something similar for the other functions

Avoid bit fields, @David, as it depends  on implementation specifics.  <math.h> contains macros to classify a float.  These macros work for double and long double too.

```<code>#include <math.h>

// Adjust returns values as desired.
int is_infinity_is_zero_is_denormal(float f) {
  if (isinf(f)) return 'i';
  if (f == 0.0f) return 'z';
  if (isnan(f)) return 'n';
  if (isnormal(f)) return 0;  // neither zero, subnormal, infinite, nor NaN

  // All that is left is de-normal/sub-normal.
  return 'd';
}
</code>```

Or maybe simply

```<code>bool is_infinity_is_zero_is_denormal(float f) {
  return !(isnormal(f) || isnan(f));
}
</code>```

Also see int fpclassify(real-floating x); to classify the number in one step.

classifies its argument value as NaN, infinite, normal, subnormal, zero, or into another implementation-defined category.  C11 §7.12.3.1 2

The number classification macros FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL FP_ZERO represent the mutually exclusive kinds of floating-point values. They expand to integer constant expressions with distinct values. §7.12 6

```<code>bool is_infinity_is_zero_is_denormal(float f) {
  // return fpclassify(f) & (FP_INFINITE | FP_ZERO | FP_SUBNORMAL);  // not good
  switch (fpclassify(f)) {
    case FP_INFINITE:
    case FP_ZERO:
    case FP_SUBNORMAL:
      return true;
  }
  return false;
}
</code>```

Let the compiler handle the optimization.

ContentLicense: CC BY-SA 4.0

Body:
int is_infinity/is_zero/is_denormal(float f){
    //do something, return 0 or 1
}

This is what I did for checking if a float is negative.  I want to do something similar for the other functions, but I'm not sure how.

int is_negative(float val){
    union sp_object copy;
    copy.frep = val;
    if((copy.irep & 0x80000000) != 0)
        return 1;
    else
        return 0;
}

Body:
I want to do something similar for the other functions

Avoid bit fields, @David, as it depends  on implementation specifics.  <math.h> contains macros to classify a float.  These macros work for double and long double too.

#include <math.h>

// Adjust returns values as desired.
int is_infinity_is_zero_is_denormal(float f) {
  if (isinf(f)) return 'i';
  if (f == 0.0f) return 'z';
  if (isnan(f)) return 'n';
  if (isnormal(f)) return 0;  // neither zero, subnormal, infinite, nor NaN

  // All that is left is de-normal/sub-normal.
  return 'd';
}

Or maybe simply

bool is_infinity_is_zero_is_denormal(float f) {
  return !(isnormal(f) || isnan(f));
}

Also see int fpclassify(real-floating x); to classify the number in one step.

classifies its argument value as NaN, infinite, normal, subnormal, zero, or into another implementation-defined category.  C11 §7.12.3.1 2

The number classification macros FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL FP_ZERO represent the mutually exclusive kinds of floating-point values. They expand to integer constant expressions with distinct values. §7.12 6

bool is_infinity_is_zero_is_denormal(float f) {
  // return fpclassify(f) & (FP_INFINITE | FP_ZERO | FP_SUBNORMAL);  // not good
  switch (fpclassify(f)) {
    case FP_INFINITE:
    case FP_ZERO:
    case FP_SUBNORMAL:
      return true;
  }
  return false;
}

Let the compiler handle the optimization.


问:
Return all values from a PHP array for a given key
I want to return all the values in an array for a given key. For example, if the key I select is "a" I want 'redpinkmaroon' to be returned. Currently I just get 'maroon' which is the final element.

```<code>$newarray = array("a"=>"red","b"=>"green","c"=>"blue","a"=>"pink","a"=>"maroon");

foreach($newarray as $key => $value) {
    if ($key === "a") { echo $value; }
}
</code>```

Any thoughts much appreciated.

答:
That's because there is only one a key.  Keys are unique so the following one overwrites the previous one. From PHP: Arrays:

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

Try print_r($newarray); to see.

You can define a multi-dimensional array with a sub-array under the key a:

```<code>$newarray = array("a"=>array("red","pink","maroon"),"b"=>"green","c"=>"blue");
</code>```

Then just loop the a key:

```<code>foreach($newarray['a'] as $value) {
    echo $value;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to return all the values in an array for a given key. For example, if the key I select is "a" I want 'redpinkmaroon' to be returned. Currently I just get 'maroon' which is the final element.

$newarray = array("a"=>"red","b"=>"green","c"=>"blue","a"=>"pink","a"=>"maroon");

foreach($newarray as $key => $value) {
    if ($key === "a") { echo $value; }
}

Any thoughts much appreciated.

Body:
That's because there is only one a key.  Keys are unique so the following one overwrites the previous one. From PHP: Arrays:

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

Try print_r($newarray); to see.

You can define a multi-dimensional array with a sub-array under the key a:

$newarray = array("a"=>array("red","pink","maroon"),"b"=>"green","c"=>"blue");

Then just loop the a key:

foreach($newarray['a'] as $value) {
    echo $value;
}


问:
Please Review these Requirements im abit lost
Hi im insure about functional and non functional requirements, are these correct ?

FUNCTIONAL:

Player Creates account.

Player Chooses Region.

Player Chooses Player type.

Player TypeA/Player Typeb Views Game statistics.

Player TypeA Views opponent List.

Player TypeA/Player Typeb Selects Target/Assassin From Job List.

Player TypeA/Player Typeb Views opponent Map.

Player TypeA views weapons.

Player TypeA equips weapon .

Player TypeA Shoots weapon; compute hit probability.

Combat opponents player is hit; opponent eliminated Player TypeA receives points.

Player TypeA/Player Typeb sends message.

Player Typeb views target history.

This program requires a gps connection is this a functional requirement ?

Non-Functional: ?????
what would they be based on my functional ones ?

I will seriously give everyone cookies if they can answer my Questions !

答:
Functional Requirements describe the features, behavior, business rules and general functionality that the proposed system must support.

Non-functional requirements describe everything else.  The scalability, availability, security, communication between various components, performance.

That sort of thing.

As I read your list it's purely functional.

ContentLicense: CC BY-SA 2.5


问:
UnusedPrivateMethod - false positive on nested-class builders
I've written a nested-class builder for a complex class and I'm now getting a false positive (Unused "private" methods should be removed) on the private method "setEmail", but it's used in the inner class.

```<code>public class Email extends AbstractDatabaseEntity<Long> {

    private String email;

    protected Email() {
    }

    public String getEmail() {
        return email;
    }

    private void setEmail(final String email) {
        this.email = email;
    }

    public static final class Builder extends AbstractEntityBuilder<Email> {

        private Builder(Email entity, EntityState state) {
            super(entity, state);
        }

        public static Builder create() {
            return new Builder(new Email(), EntityState.NEW);
        }

        public static Builder from(Email entity) {
            return new Builder(entity, EntityState.BUILT);
        }

        public Builder email(String email) {
            entity.setEmail(email);
            return this;
        }
    }
}

public abstract class AbstractEntityBuilder<T extends Object> {

    protected final EntityState state;
    protected T entity;
    ...

}
</code>```

SonarQube version: 5.6.3

SonarJava 4.4.0.8066

Thanks!

答: The problem looks to be already fixed at SonarJava 4.10.0.10260 in SonarQube 5.6.3. After some investigation I realized the fix most likely came from the issue SONARJAVA-2204. You should update the plugin version, restart your Sonar instance and analyse your project again to see that the issues are gone now. Just the really problematic code should remain highlighted from now on.

Body:
I've written a nested-class builder for a complex class and I'm now getting a false positive (Unused "private" methods should be removed) on the private method "setEmail", but it's used in the inner class.

public class Email extends AbstractDatabaseEntity<Long> {

    private String email;

    protected Email() {
    }

    public String getEmail() {
        return email;
    }

    private void setEmail(final String email) {
        this.email = email;
    }

    public static final class Builder extends AbstractEntityBuilder<Email> {

        private Builder(Email entity, EntityState state) {
            super(entity, state);
        }

        public static Builder create() {
            return new Builder(new Email(), EntityState.NEW);
        }

        public static Builder from(Email entity) {
            return new Builder(entity, EntityState.BUILT);
        }

        public Builder email(String email) {
            entity.setEmail(email);
            return this;
        }
    }
}

public abstract class AbstractEntityBuilder<T extends Object> {

    protected final EntityState state;
    protected T entity;
    ...

}

SonarQube version: 5.6.3

SonarJava 4.4.0.8066

Thanks!


问:
How to start apache2 automatically in a ubuntu docker container?
I am trying to create a Dockerfile that will start apache automatically. Nothing has worked. But If I log into the container and run service apache2 start it works. Why can I not run that command from my Dockerfile?

```<code>FROM ubuntu

# File Author / Maintainer
MAINTAINER rmuktader

# Update the repository sources list
RUN apt-get update

# Install and run apache
RUN apt-get install -y apache2 && apt-get clean

#ENTRYPOINT ["/usr/sbin/apache2", "-k", "start"]

#ENV APACHE_RUN_USER www-data
#ENV APACHE_RUN_GROUP www-data
#ENV APACHE_LOG_DIR /var/log/apache2

EXPOSE 80
CMD service apache2 start
</code>```

答:
The issue is here: CMD service apache2 start When you execute this command process apache2 will be detached from the shell. But Docker works only while main process is alive.

The solution is to run Apache in the foreground. Dockerfile must look like this: (only last line changed).

```<code>FROM ubuntu

# File Author / Maintainer
MAINTAINER rmuktader

# Update the repository sources list
RUN apt-get update

# Install and run apache
RUN apt-get install -y apache2 && apt-get clean

#ENTRYPOINT ["/usr/sbin/apache2", "-k", "start"]

#ENV APACHE_RUN_USER www-data
#ENV APACHE_RUN_GROUP www-data
#ENV APACHE_LOG_DIR /var/log/apache2

EXPOSE 80
CMD apachectl -D FOREGROUND
</code>```

Body:
I am trying to create a Dockerfile that will start apache automatically. Nothing has worked. But If I log into the container and run service apache2 start it works. Why can I not run that command from my Dockerfile?

FROM ubuntu

# File Author / Maintainer
MAINTAINER rmuktader

# Update the repository sources list
RUN apt-get update

# Install and run apache
RUN apt-get install -y apache2 && apt-get clean

#ENTRYPOINT ["/usr/sbin/apache2", "-k", "start"]

#ENV APACHE_RUN_USER www-data
#ENV APACHE_RUN_GROUP www-data
#ENV APACHE_LOG_DIR /var/log/apache2

EXPOSE 80
CMD service apache2 start

Body:
The issue is here: CMD service apache2 start When you execute this command process apache2 will be detached from the shell. But Docker works only while main process is alive.

The solution is to run Apache in the foreground. Dockerfile must look like this: (only last line changed).

FROM ubuntu

# File Author / Maintainer
MAINTAINER rmuktader

# Update the repository sources list
RUN apt-get update

# Install and run apache
RUN apt-get install -y apache2 && apt-get clean

#ENTRYPOINT ["/usr/sbin/apache2", "-k", "start"]

#ENV APACHE_RUN_USER www-data
#ENV APACHE_RUN_GROUP www-data
#ENV APACHE_LOG_DIR /var/log/apache2

EXPOSE 80
CMD apachectl -D FOREGROUND


问:
Appending extra elements to existing string of html in Node.js
I need to dynamically append a header and footer to specific elements of an HTML web page in Node.js but I'm not sure how to do it. I have a function that takes html as a string and options that may or may not contain extra strings for header and footer content.

The idea is that if either a header or footer is passed into the function it will be appended to the existing HTML appropriately.

Here is what the function looks like. I am using lodash to test if there is header/footer content. I'd like to perform the append inside the if block. I've had a look at cheerio but not sure if it can be used on html if it's in a string.Thanks for any help in advance!

```<code>function generator(html, options) {

    var header = _.get(options, 'partials.header');
    var footer = _.get(options, 'partials.footer');

  // Check if either header of footer options.partials
    if(header || footer) {
      console.log('YEAH! ::: ', header);
      // Append header and/or footer to the HTML here

    }
}
</code>```

答:
How about concatenating the strings?</p>

```<code>function generator(html, options) {

    var header = _.get(options, 'partials.header') || '';
    var footer = _.get(options, 'partials.footer') || '';

    // Check if either header of footer options.partials
    if (header || footer) {
      html = (header + html + footer);
    }

    return html;
}
</code>```

Body:
I need to dynamically append a header and footer to specific elements of an HTML web page in Node.js but I'm not sure how to do it. I have a function that takes html as a string and options that may or may not contain extra strings for header and footer content.

The idea is that if either a header or footer is passed into the function it will be appended to the existing HTML appropriately.

Here is what the function looks like. I am using lodash to test if there is header/footer content. I'd like to perform the append inside the if block. I've had a look at cheerio but not sure if it can be used on html if it's in a string.Thanks for any help in advance!

function generator(html, options) {

    var header = _.get(options, 'partials.header');
    var footer = _.get(options, 'partials.footer');

  // Check if either header of footer options.partials
    if(header || footer) {
      console.log('YEAH! ::: ', header);
      // Append header and/or footer to the HTML here

    }
}

Body:
How about concatenating the strings?

function generator(html, options) {

    var header = _.get(options, 'partials.header') || '';
    var footer = _.get(options, 'partials.footer') || '';

    // Check if either header of footer options.partials
    if (header || footer) {
      html = (header + html + footer);
    }

    return html;
}


问:
How to get a blend mode effect without use the CSS property mix-blend-mode: multiply
I want to do a thing that should look like this code output, but without using the property mix-blend-mode: multiply of css, in order to get support for some old versions of moderns browsers.

This feature of CSS is still low supporting, look this link caniuse.com[mix-blend-mode]

.active{
  font-size: 80px;
  font-family: "DejaVu Sans";
  text-align: center;
  color: #646e7a;
}
.active::after {
  background: #00d7a7 none repeat scroll 0 0;
  content: "";
  height: 45px;
  left: 10%;
  margin-top: 0;
  mix-blend-mode: multiply;
  position: absolute;
  right: 10%;
  top: 13.8%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="active">
    WEB
</div></code>```

答:
This is a nice solution that I have found:

.active{
    background: #00d7a7 none repeat scroll 0 0;
    color: rgba(30, 40, 52, 0.73);
    font-family: "DejaVu Sans";
    font-size: 80px;
    height: 45px;
    line-height: 0.6;
    position: relative;
    text-align: center;
    top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="active">
    WEB
</div></code>```

Body:
I want to do a thing that should look like this code output, but without using the property mix-blend-mode: multiply of css, in order to get support for some old versions of moderns browsers.

This feature of CSS is still low supporting, look this link caniuse.com[mix-blend-mode]

.active{
  font-size: 80px;
  font-family: "DejaVu Sans";
  text-align: center;
  color: #646e7a;
}
.active::after {
  background: #00d7a7 none repeat scroll 0 0;
  content: "";
  height: 45px;
  left: 10%;
  margin-top: 0;
  mix-blend-mode: multiply;
  position: absolute;
  right: 10%;
  top: 13.8%;
}

    WEB

Body:
This is a nice solution that I have found:

.active{
    background: #00d7a7 none repeat scroll 0 0;
    color: rgba(30, 40, 52, 0.73);
    font-family: "DejaVu Sans";
    font-size: 80px;
    height: 45px;
    line-height: 0.6;
    position: relative;
    text-align: center;
    top: 20px;
}

<div class="active">
    WEB
</div>


问:
get_the_author_meta() not working on wp
I have some problems with the standard wp function get_the_author_meta(). I use it in my project to display the social link of an author but I always get an empty variable.

Here is my code in article page:

```<code>    $author_name = get_the_author();//not empty
    $author_info = get_the_author_meta('description');//not empty
    $author_website = get_the_author_meta('url');//empty

    $author_facebook = get_the_author_meta('facebook');//empty
    $author_twitter = get_the_author_meta('twitter');//empty
    $author_google = get_the_author_meta('google');//empty
    $author_linkedin = get_the_author_meta('linkedin','7');//also empty whit this desperate attempt
    $author_instagram = get_the_author_meta('instagram',7);//also empty whit this desperate attempt
</code>```

I tested on an article of an author with all social link.
I have no php an no js error.
I installed cimy user extra fields.

答:
First you have an extra comma here $author_facebook = get_the_author_meta( 'facebook', ); //empty

I'm guessing this was an error in the copy paste, otherwise you get a very specific 'unexpected token' error. With that exception your code should work. You might be getting this error for two reasons:

The plugin you are using to add the user meta is not working correctly.

The actual author of the page / post does not have the meta data set correctly.

This code worked for me, try this just to test:

```<code>$user_id = get_the_author_meta( 'ID' );
add_user_meta( $user_id, 'facebook', 'https://facebook.com' );

var_dump( $user_id );
var_dump( get_the_author_meta( 'facebook' ) );

// Output: string(20) "https://facebook.com"
</code>```

You mentioned before that you can see the social media links on the DB under usermeta, so my guess is that the current author of the post / page does not have the social media links set. On the var_dumps of the code you will see the user ID. Find on the DB all the entries of the table usermeta with that user ID and you will notice there is no custom meta for that specific user.

Title: get_the_author_meta() not working on wp

Body:
I have some problems with the standard wp function get_the_author_meta(). I use it in my project to display the social link of an author but I always get an empty variable.

Here is my code in article page:

    $author_name = get_the_author();//not empty
    $author_info = get_the_author_meta('description');//not empty
    $author_website = get_the_author_meta('url');//empty

    $author_facebook = get_the_author_meta('facebook');//empty
    $author_twitter = get_the_author_meta('twitter');//empty
    $author_google = get_the_author_meta('google');//empty
    $author_linkedin = get_the_author_meta('linkedin','7');//also empty whit this desperate attempt
    $author_instagram = get_the_author_meta('instagram',7);//also empty whit this desperate attempt

I tested on an article of an author with all social link.
I have no php an no js error.
I installed cimy user extra fields.

Body:
First you have an extra comma here $author_facebook = get_the_author_meta( 'facebook', ); //empty

I'm guessing this was an error in the copy paste, otherwise you get a very specific 'unexpected token' error. With that exception your code should work. You might be getting this error for two reasons:

The plugin you are using to add the user meta is not working correctly.

The actual author of the page / post does not have the meta data set correctly.

This code worked for me, try this just to test:

$user_id = get_the_author_meta( 'ID' );
add_user_meta( $user_id, 'facebook', 'https://facebook.com' );

var_dump( $user_id );
var_dump( get_the_author_meta( 'facebook' ) );

// Output: string(20) "https://facebook.com"

You mentioned before that you can see the social media links on the DB under usermeta, so my guess is that the current author of the post / page does not have the social media links set. On the var_dumps of the code you will see the user ID. Find on the DB all the entries of the table usermeta with that user ID and you will notice there is no custom meta for that specific user.


问:
Django SQLite testing oddity: Different path of execution?
This is merely a theory that I would like to figure out based on others feedback and perhaps similar experiences.

Been using mySQL for running tests, but of course an in-memory SQLite database is much faster. However, it seems to have run into some problems.

When DATABASE_ENGINE is set to use django.db.backends.sqlite3 and I run manage.py test, the output is not as hoped:

(Removed most lines, but pointing out interesting points of failure)

```
$ python manage.py test
Traceback (most recent call last):
  File "manage.py", line 12, in
    execute_manager(settings)
  File "/Users/bartekc/.virtualenvs/xx/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/Users/bartekc/domains/xx/xx/associates/yy/models.py", line 51, in
    class AcvTripIncentive(models.Model):

  # First interesting failure
  File "/Users/bartekc/domains/xx/xx/associates/yy/models.py", line 55, in AcvTripIncentive
    trip = models.OneToOneField(Trip, limit_choices_to={'sites' : Site.objects.get(name='ZZ'), 'is_active' : True,})

  # Next interesting failure
   File "/Users/bartekc/domains/xx/xx/associates/yyz/models.py", line 252, in
    current_site = Site.objects.get_current()
```

There are multiple failures like this but just pointing out a couple. The problem is obvious. The Site model has no actual data, but the files contain code that try to fetch the current, or specific instances under the Site model.

Now, I can think of an easy solution: That OneToOneField should be switched to use a function with limit_choices_to, and the second one the same. The functions are then called when required, not on initial scanning of the file by Django.

However, my actual question is: Why does this happen with SQLite and not mySQL?. Is there a different way the two database engines process through tests? I wouldn't think so, since Python is doing all the compiling of the models.

What exactly is happening here?

Cheers.

答:
Are you loading your Site objects from a fixture?

If so, perhaps you are stumbling upon a known issue with MySQL and transactions. Do a text search for "MySQL and Fixtures" on this page: http://docs.djangoproject.com/en/dev/ref/django-admin/?from=olddocs

Body:
This is merely a theory that I would like to figure out based on others feedback and perhaps similar experiences.

Been using mySQL for running tests, but of course an in-memory SQLite database is much faster. However, it seems to have run into some problems.

When DATABASE_ENGINE is set to use django.db.backends.sqlite3 and I run manage.py test, the output is not as hoped:

(Removed most lines, but pointing out interesting points of failure)

$ python manage.py test
Traceback (most recent call last):
  File "manage.py", line 12, in
    execute_manager(settings)
  File "/Users/bartekc/.virtualenvs/xx/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/Users/bartekc/domains/xx/xx/associates/yy/models.py", line 51, in
    class AcvTripIncentive(models.Model):

  # First interesting failure
  File "/Users/bartekc/domains/xx/xx/associates/yy/models.py", line 55, in AcvTripIncentive
    trip = models.OneToOneField(Trip, limit_choices_to={'sites' : Site.objects.get(name='ZZ'), 'is_active' : True,})

  # Next interesting failure
   File "/Users/bartekc/domains/xx/xx/associates/yyz/models.py", line 252, in
    current_site = Site.objects.get_current()

There are multiple failures like this but just pointing out a couple. The problem is obvious. The Site model has no actual data, but the files contain code that try to fetch the current, or specific instances under the Site model.

Now, I can think of an easy solution: That OneToOneField should be switched to use a function with limit_choices_to, and the second one the same. The functions are then called when required, not on initial scanning of the file by Django.

However, my actual question is: Why does this happen with SQLite and not mySQL?. Is there a different way the two database engines process through tests? I wouldn't think so, since Python is doing all the compiling of the models.

What exactly is happening here?

Cheers.


问:
Get all subsets of a Python dictionary with restrictions
I have the following dictionary:

```<code>intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}
</code>```

How would I create all possible subsets of this dictionary where I must have exactly one of each number x for 'paramx'? Meaning that I can only have one entry for param1 (_lo or _hi), one entry for param2 (_lo or _hi), and so on, and that each subset must include every paramx that does not have a _lo or _hi.

Here are two possible subsets:

```<code>subset_one = {'param1': [0, 1],
              'param2_hi': [4, 5, 6, 7, 8, 9],
              'param3_hi': [9, 10, 11, 12, 13, 14, 15],
              'param4': [0, 1],
              'param5_hi': [4, 5, 6, 7, 8, 9]}

subset_two = {'param1': [0, 1],
              'param2_lo': [0, 1, 2, 3, 4, 5],
              'param3_lo': [5, 6, 7, 8, 9, 10],
              'param4': [0, 1],
              'param5_lo': [0, 1, 2, 3, 4, 5]}

# Example of mixed '_hi' and '_lo' intervals
subset_three = {'param1': [0, 1],
                'param2_lo': [0, 1, 2, 3, 4, 5],
                'param3_hi': [9, 10, 11, 12, 13, 14, 15],
                'param4': [0, 1],
                'param5_lo': [0, 1, 2, 3, 4, 5]}

...
</code>```

Note: I want to preserve key, value pairs.

Edit: Added subset_three to show the possibility of having mixed '_lo' and '_hi' intervals.

答:
I believe that you want itertools.product applied to the five choice sets in your parameters:

```<code>choices = [
    ['param1'],
    ['param2_lo', 'param2_hi'],
    ['param3_lo', 'param3_hi'],
    ['param4'],
    ['param5_lo', 'param5_hi']
]

for permute in itertools.product(*choices):
    ....
</code>```

Is that enough to get you going?

Body:
I have the following dictionary:

intervals = {'param1': [0, 1],
             'param2_hi': [4, 5, 6, 7, 8, 9],
             'param2_lo': [0, 1, 2, 3, 4, 5],
             'param3_hi': [9, 10, 11, 12, 13, 14, 15],
             'param3_lo': [5, 6, 7, 8, 9, 10],
             'param4': [0, 1],
             'param5_hi': [4, 5, 6, 7, 8, 9],
             'param5_lo': [0, 1, 2, 3, 4, 5]}

How would I create all possible subsets of this dictionary where I must have exactly one of each number x for 'paramx'? Meaning that I can only have one entry for param1 (_lo or _hi), one entry for param2 (_lo or _hi), and so on, and that each subset must include every paramx that does not have a _lo or _hi.

Here are two possible subsets:

subset_one = {'param1': [0, 1],
              'param2_hi': [4, 5, 6, 7, 8, 9],
              'param3_hi': [9, 10, 11, 12, 13, 14, 15],
              'param4': [0, 1],
              'param5_hi': [4, 5, 6, 7, 8, 9]}

subset_two = {'param1': [0, 1],
              'param2_lo': [0, 1, 2, 3, 4, 5],
              'param3_lo': [5, 6, 7, 8, 9, 10],
              'param4': [0, 1],
              'param5_lo': [0, 1, 2, 3, 4, 5]}

# Example of mixed '_hi' and '_lo' intervals
subset_three = {'param1': [0, 1],
                'param2_lo': [0, 1, 2, 3, 4, 5],
                'param3_hi': [9, 10, 11, 12, 13, 14, 15],
                'param4': [0, 1],
                'param5_lo': [0, 1, 2, 3, 4, 5]}

...

Note: I want to preserve key, value pairs.

Edit: Added subset_three to show the possibility of having mixed '_lo' and '_hi' intervals.

Body:
I believe that you want itertools.product applied to the five choice sets in your parameters:

choices = [
    ['param1'],
    ['param2_lo', 'param2_hi'],
    ['param3_lo', 'param3_hi'],
    ['param4'],
    ['param5_lo', 'param5_hi']
]

for permute in itertools.product(*choices):
    ....

Is that enough to get you going?


答:
try this,    </p>

```<code>$newarray = array("a"=>array("red","pink","maroon"),"b"=>"green","c"=>"blue");

    foreach($newarray as $key => $value) {
        if ($key === "a") {
            foreach ($value as $color) {
                echo $color;
             }
        }
    }
</code>```

Title: Return all values from a PHP array for a given key

Body:
try this,

$newarray = array("a"=>array("red","pink","maroon"),"b"=>"green","c"=>"blue");

    foreach($newarray as $key => $value) {
        if ($key === "a") {
            foreach ($value as $color) {
                echo $color;
             }
        }
    }


问:
display data to listbox C#
Listbox does not show data. Verified data is in database and I am not getting an
error.  Not sure where/what is wrong.  Thanks in advance.  My code is attached.</p>

```<code> private void UpDateList()
        {
            //  add data connection and fill data set.

            SqlConnection conn = new SqlConnection(dataSource);
            DataTable dt = new DataTable();
            string sqlString = "select * from Suppliers";
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            try
            {
                cmd.Connection = conn;
                conn.Open();
                cmd.CommandText = sqlString;
                da.Fill(ds);
                conn.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
            foreach(DataRow dRow in ds.Tables[0].Rows)
            {
                ArrayList values = new ArrayList();
                foreach(object value in dRow.ItemArray)
                {
                    values.Add(value);
                    _Suppliers.Add(values);
                }
            }
            lstSuppliers.DataSource = _Suppliers;
            lstSuppliers.Update();
        }
</code>```

答:
It's kinda pointless to enumerate one bindable data collection and transfer data into another bindable collection so it can be bound. Just have your list use the default view of the datatable that already holds the data (allows sorting, filtering etc)

E.g.

```<code>LstSuppliers.DataSource = ds.Tables[0].DefaultView;
LstSuppliers.DisplayMember = "column name goes here of what to show eg SupplierName";
LstSuppliers.ValueMember = "column whose value to use for lstSuppliers.SelectedValue e.g. supplierId";
</code>```

And then for example, not required but an example possibility:

```<code>ds.Tables[0].DefaultView.Sort = "[SupplierName] ASC";
</code>```

Title: display data to listbox C#

Body:
Listbox does not show data. Verified data is in database and I am not getting an
error.  Not sure where/what is wrong.  Thanks in advance.  My code is attached.

 private void UpDateList()
        {
            //  add data connection and fill data set.

            SqlConnection conn = new SqlConnection(dataSource);
            DataTable dt = new DataTable();
            string sqlString = "select * from Suppliers";
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            try
            {
                cmd.Connection = conn;
                conn.Open();
                cmd.CommandText = sqlString;
                da.Fill(ds);
                conn.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
            foreach(DataRow dRow in ds.Tables[0].Rows)
            {
                ArrayList values = new ArrayList();
                foreach(object value in dRow.ItemArray)
                {
                    values.Add(value);
                    _Suppliers.Add(values);
                }
            }
            lstSuppliers.DataSource = _Suppliers;
            lstSuppliers.Update();
        }

Body:
It's kinda pointless to enumerate one bindable data collection and transfer data into another bindable collection so it can be bound. Just have your list use the default view of the datatable that already holds the data (allows sorting, filtering etc)

E.g.

LstSuppliers.DataSource = ds.Tables[0].DefaultView;
LstSuppliers.DisplayMember = "column name goes here of what to show eg SupplierName";
LstSuppliers.ValueMember = "column whose value to use for lstSuppliers.SelectedValue e.g. supplierId";

And then for example, not required but an example possibility:

ds.Tables[0].DefaultView.Sort = "[SupplierName] ASC";


答:
You can try making a 2d array so something like

```<code>$newarray = [
   "a" => ['red','pink','maroon'],
   "b" => ['green'],
   "c" => ['blue']
];
</code>```

Then you can access the values like this:

```<code>$newarray['a']
</code>```

Which will return an array containing red pink and maroon

Body:
I want to return all the values in an array for a given key. For example, if the key I select is "a" I want 'redpinkmaroon' to be returned. Currently I just get 'maroon' which is the final element.

$newarray = array("a"=>"red","b"=>"green","c"=>"blue","a"=>"pink","a"=>"maroon");

foreach($newarray as $key => $value) {
    if ($key === "a") { echo $value; }
}

Any thoughts much appreciated.

Body:
You can try making a 2d array so something like

$newarray = [
   "a" => ['red','pink','maroon'],
   "b" => ['green'],
   "c" => ['blue']
];

Then you can access the values like this:

$newarray['a']

Which will return an array containing red pink and maroon


问:
jQuery height won't use transition when set to 100% or auto
JS FIDDLE: https://jsfiddle.net/t2eynytg/1/

Essentially, I want a readmore button that reveals an entire long paragraph (which is normally cut to 3-4 lines). It "grows" with a transition when the desired height is set in pixels, but it just "appears" when set to auto or 100%. Obviously I want this to work for all cases, so it can't be in pixels or ems.

How do I fix?

jQuery

```<code>$('.first-link').click(function(){
    $('.first-pg').css({'height' : '100%'})
});
</code>```

HTML

```<code><p class="first-pg">
 This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test.
</p>
<a class="first-link" href="#">Read More</a>
</code>```

CSS

```<code>p {
  height:3em;
  border:1px solid green;
  overflow:hidden;
  -webkit-transition: height .8s;
    -moz-transition: height .8s;
    transition: height .8s;
}
</code>```

答:
Transition only works with hard values because it needs them to calculate start/finish values for the timing. So things like transitioning between display: none; and display: block; don't work (there is no quantitative value to scale from/to).

Height: auto; is not a hard value so you can't animate to/from it. What you can do is check what the value of height: auto would be using scrollHeight and then use that in your animation.

So for example:

'height' : $('.first-pg')[0].scrollHeight

Below is a working example:

https://jsfiddle.net/oxn357az/

And further reading:

https://css-tricks.com/using-css-transitions-auto-dimensions/

/* Desired Effect */
var $firstPara = $('.first-pg');
$firstPara.prop({
 'original-height' :  $firstPara.height(),
  'open' : false
});

var $secondPara = $('.second-pg');
$secondPara.prop({
 'original-height' :  $secondPara.height(),
  'open' : false
});

$('.first-link').click(function(){
 if(!$firstPara.prop('open')){
    $firstPara.animate({
    'height' : $firstPara[0].scrollHeight
    })
    $firstPara.prop('open', true);
  }
  else{
    $firstPara.animate({
    'height' : $firstPara.prop('original-height')
    })
    $firstPara.prop('open', false);
  }
});

$('.second-link').click(function(){
 if(!$secondPara.prop('open')){
    $secondPara.animate({
    'height' : $secondPara[0].scrollHeight
    })
    $secondPara.prop('open', true);
  }
  else{
    $secondPara.animate({
    'height' : $firstPara.prop('original-height')
    })
    $secondPara.prop('open', false);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  height:3em;
  border:1px solid green;
  overflow:hidden;
  -webkit-transition: height 5.8s;
 -moz-transition: height 5.8s;
 transition: height .8s;
}</code>```

Desired Effect

 This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test.

Read More

Issue

 This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test.

Read More```

Body:
JS FIDDLE: https://jsfiddle.net/t2eynytg/1/

Essentially, I want a readmore button that reveals an entire long paragraph (which is normally cut to 3-4 lines). It "grows" with a transition when the desired height is set in pixels, but it just "appears" when set to auto or 100%. Obviously I want this to work for all cases, so it can't be in pixels or ems.

How do I fix?

jQuery

$('.first-link').click(function(){
    $('.first-pg').css({'height' : '100%'})
});

HTML

 This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test.

Read More

CSS

p {
  height:3em;
  border:1px solid green;
  overflow:hidden;
  -webkit-transition: height .8s;
    -moz-transition: height .8s;
    transition: height .8s;
}

Body:
Transition only works with hard values because it needs them to calculate start/finish values for the timing. So things like transitioning between display: none; and display: block; don't work (there is no quantitative value to scale from/to).

Height: auto; is not a hard value so you can't animate to/from it. What you can do is check what the value of height: auto would be using scrollHeight and then use that in your animation.

So for example:

'height' : $('.first-pg')[0].scrollHeight

Below is a working example:

https://jsfiddle.net/oxn357az/

And further reading:

https://css-tricks.com/using-css-transitions-auto-dimensions/

/* Desired Effect */
var $firstPara = $('.first-pg');
$firstPara.prop({
 'original-height' :  $firstPara.height(),
  'open' : false
});

var $secondPara = $('.second-pg');
$secondPara.prop({
 'original-height' :  $secondPara.height(),
  'open' : false
});

$('.first-link').click(function(){
 if(!$firstPara.prop('open')){
    $firstPara.animate({
    'height' : $firstPara[0].scrollHeight
    })
    $firstPara.prop('open', true);
  }
  else{
    $firstPara.animate({
    'height' : $firstPara.prop('original-height')
    })
    $firstPara.prop('open', false);
  }
});

$('.second-link').click(function(){
 if(!$secondPara.prop('open')){
    $secondPara.animate({
    'height' : $secondPara[0].scrollHeight
    })
    $secondPara.prop('open', true);
  }
  else{
    $secondPara.animate({
    'height' : $firstPara.prop('original-height')
    })
    $secondPara.prop('open', false);
  }
});

p {
  height:3em;
  border:1px solid green;
  overflow:hidden;
  -webkit-transition: height 5.8s;
 -moz-transition: height 5.8s;
 transition: height .8s;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Desired Effect</h1>
<p class="first-pg">
 This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test.
</p>
<a class="first-link" href="#">Read More</a>

<h1>Issue</h1>
<p class="second-pg">
 This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test. This is a long type test.
</p>
<a class="second-link" href="#">Read More</a>


问:
Laravel HTTP vs HTTPS requests
My Laravel website is deployed on Heroku. For example, when I type http://example.herokuapp.com -> the UI stays intact. However, when I use https, the UI jumbles up and breaks.

How can I fix this?

答:
As everyone says, it's because You have some assets loaded under http protocol and your domain is in https.

My recommendation is that You use asset():

```<code><img src="{{ asset('images/my-image.png') }}">

<link href="{{ asset('css/my-styles.css') }}" rel="stylesheet">

<script src="{{ asset('js/my-script.js') }}"></script>
</code>```

Title: Laravel HTTP vs HTTPS requests

Body:
As everyone says, it's because You have some assets loaded under http protocol and your domain is in https.

My recommendation is that You use asset():

<img src="{{ asset('images/my-image.png') }}">

<link href="{{ asset('css/my-styles.css') }}" rel="stylesheet">

<script src="{{ asset('js/my-script.js') }}"></script>


问:
C++ , function pointer exception error
I get "error: exception specifications are not allowed beyond a single level of indirection" with the following code. Please point me to the part of standard that says that it is not allowed. I want to be sure that it is really required by the language or just compiler specific error. If it is from language specification, what motivates this rule? I am using clang 3.8.0.</p>

```<code>  int main()
    {
        void (**fp)() throw() ;
    }
</code>```

答:
You said:

Please point me to a reference book /spec that says that it is not allowed. I want to be sure that it is really required by the language or just compiler specific error.

With

```<code>void (**fp)() throw() ;
</code>```

you are trying to specify an exception-specification in the declaration of a pointer to a function pointer. That is not allowed by the standard. Exception-specification is allowed only for a limited set of declarations.

From https://timsong-cpp.github.io/cppwp/n3337/except.spec#2 (emphasis mine):

An exception-specification shall appear only on a function declarator for a function type, pointer to function type, reference to function type, or pointer to member function type that is the top-level type of a declaration or definition, or on such a type appearing as a parameter or return type in a function declarator. An exception-specification shall not appear in a typedef declaration or alias-declaration. [ Example:

```<code> void f() throw(int);                    // OK
 void (*fp)() throw (int);               // OK
 void g(void pfa() throw(int));          // OK
 typedef int (*pf)() throw(int);         // ill-formed
</code>```

— end example ] A type denoted in an exception-specification shall not denote an incomplete type. A type denoted in an exception-specification shall not denote a pointer or reference to an incomplete type, other than void*, const void*, volatile void*, or const volatile void*. A type cv T, “array of T”, or “function returning T” denoted in an exception-specification is adjusted to type T, “pointer to T”, or “pointer to function returning T”, respectively.

You asked:

If it is from language specification, what motivates this rule?

I don't have an answer to that.

Title: C++ , function pointer exception error

Body:
I get "error: exception specifications are not allowed beyond a single level of indirection" with the following code. Please point me to the part of standard that says that it is not allowed. I want to be sure that it is really required by the language or just compiler specific error. If it is from language specification, what motivates this rule? I am using clang 3.8.0.

  int main()
    {
        void (**fp)() throw() ;
    }

Body:
You said:

Please point me to a reference book /spec that says that it is not allowed. I want to be sure that it is really required by the language or just compiler specific error.

With

void (**fp)() throw() ;

you are trying to specify an exception-specification in the declaration of a pointer to a function pointer. That is not allowed by the standard. Exception-specification is allowed only for a limited set of declarations.

From https://timsong-cpp.github.io/cppwp/n3337/except.spec#2 (emphasis mine):

An exception-specification shall appear only on a function declarator for a function type, pointer to function type, reference to function type, or pointer to member function type that is the top-level type of a declaration or definition, or on such a type appearing as a parameter or return type in a function declarator. An exception-specification shall not appear in a typedef declaration or alias-declaration. [ Example:

 void f() throw(int);                    // OK
 void (*fp)() throw (int);               // OK
 void g(void pfa() throw(int));          // OK
 typedef int (*pf)() throw(int);         // ill-formed

— end example ] A type denoted in an exception-specification shall not denote an incomplete type. A type denoted in an exception-specification shall not denote a pointer or reference to an incomplete type, other than void*, const void*, volatile void*, or const volatile void*. A type cv T, “array of T”, or “function returning T” denoted in an exception-specification is adjusted to type T, “pointer to T”, or “pointer to function returning T”, respectively.

You asked:

If it is from language specification, what motivates this rule?

I don't have an answer to that.


问:
Join plan node with condition=true encounter an error
```<code>final RelBuilder builder = RelBuilder.create(config().build());
    RelNode root =
        builder.scan("EMP")
            .as("e")
            .scan("EMP")
            .as("m")
            .scan("DEPT")
            .join(JoinRelType.INNER)
            .join(JoinRelType.INNER)
            .filter(
                builder.equals(builder.field("e", "DEPTNO"),
                    builder.field("DEPT", "DEPTNO")),
                builder.equals(builder.field("m", "EMPNO"),
                    builder.field("e", "MGR")))
            .build();
    final String expected = ""
        + "LogicalFilter(condition=[AND(=($7, $16), =($8, $3))])\n"
        + "  LogicalJoin(condition=[true], joinType=[inner])\n"
        + "    LogicalTableScan(table=[[scott, EMP]])\n"
        + "    LogicalJoin(condition=[true], joinType=[inner])\n"
        + "      LogicalTableScan(table=[[scott, EMP]])\n"
        + "      LogicalTableScan(table=[[scott, DEPT]])\n";
    assertThat(str(root), is(expected));
</code>```

The code above is from RelBuilderTest.java 。why does calcite generate the LogicalJoin(condition=[true], joinType=[inner]) Node? when I use RelToSqlConverter to convert the RelNode to SQL,it encounter an error about the filter 'condition=[true]'

```<code>ava.lang.AssertionError: Internal error: While invoking method 'public org.apache.calcite.rel.rel2sql.SqlImplementor$Result org.apache.calcite.rel.rel2sql.RelToSqlConverter.visit(org.apache.calcite.rel.core.Filter)
at org.apache.calcite.util.Util.newInternal(Util.java:792)
at org.apache.calcite.util.ReflectUtil$2.invoke(ReflectUtil.java:535)
at org.apache.calcite.rel.rel2sql.RelToSqlConverter.dispatch(RelToSqlConverter.java:80
</code>```

why does this happen?

答:
RelBuilder is doing what is told: building a join with no condition. This is analogous to how you might write

```<code>SELECT ...
FROM Emp, Dept
</code>```

and later specify the join condition in the WHERE clause:

```<code>WHERE Emp.deptno = Dept.deptno
</code>```

RelBuilder doesn't try to make optimizations (aside from a few micro-optimizations like removing trivial Projects). Folding the Filter onto the Join is the job of FilterIntoJoinRule, and will duly happen during the query optimization phase.

The error in RelToSqlConverter is a known issue and will be fixed in the next release (1.13.0).

Body:
final RelBuilder builder = RelBuilder.create(config().build());
    RelNode root =
        builder.scan("EMP")
            .as("e")
            .scan("EMP")
            .as("m")
            .scan("DEPT")
            .join(JoinRelType.INNER)
            .join(JoinRelType.INNER)
            .filter(
                builder.equals(builder.field("e", "DEPTNO"),
                    builder.field("DEPT", "DEPTNO")),
                builder.equals(builder.field("m", "EMPNO"),
                    builder.field("e", "MGR")))
            .build();
    final String expected = ""
        + "LogicalFilter(condition=[AND(=($7, $16), =($8, $3))])\n"
        + "  LogicalJoin(condition=[true], joinType=[inner])\n"
        + "    LogicalTableScan(table=[[scott, EMP]])\n"
        + "    LogicalJoin(condition=[true], joinType=[inner])\n"
        + "      LogicalTableScan(table=[[scott, EMP]])\n"
        + "      LogicalTableScan(table=[[scott, DEPT]])\n";
    assertThat(str(root), is(expected));

The code above is from RelBuilderTest.java 。why does calcite generate the LogicalJoin(condition=[true], joinType=[inner]) Node? when I use RelToSqlConverter to convert the RelNode to SQL,it encounter an error about the filter 'condition=[true]'

ava.lang.AssertionError: Internal error: While invoking method 'public org.apache.calcite.rel.rel2sql.SqlImplementor$Result org.apache.calcite.rel.rel2sql.RelToSqlConverter.visit(org.apache.calcite.rel.core.Filter)
at org.apache.calcite.util.Util.newInternal(Util.java:792)
at org.apache.calcite.util.ReflectUtil$2.invoke(ReflectUtil.java:535)
at org.apache.calcite.rel.rel2sql.RelToSqlConverter.dispatch(RelToSqlConverter.java:80

why does this happen?

Body:
RelBuilder is doing what is told: building a join with no condition. This is analogous to how you might write

SELECT ...
FROM Emp, Dept

and later specify the join condition in the WHERE clause:

WHERE Emp.deptno = Dept.deptno

RelBuilder doesn't try to make optimizations (aside from a few micro-optimizations like removing trivial Projects). Folding the Filter onto the Join is the job of FilterIntoJoinRule, and will duly happen during the query optimization phase.

The error in RelToSqlConverter is a known issue and will be fixed in the next release (1.13.0).


问:
SQL : Error converting data type nvarchar to float
I want to convert nvarchar data to float type.

In my case I have SalesValue column and I used this command

```<code>UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )
</code>```

My table has values like

```<code>201.01
40.50
215.12
550
304.201
</code>```

But I get an error

SQL : Error converting data type nvarchar to float.

How can I solve this problem ?

答:
You should find the values that do not match.  In SQL Server 2012+, you can use try_convert().  That is not available.  So, how about this?

```<code>SELECT SalesValue
FROM Overseas
WHERE SalesValue LIKE '%[^0-9,.]%' OR
      SalesValue LIKE '%[.,]%[.,]%';
</code>```

I think that covers the obvious irregularities:  a character that is not numeric or two (or more) decimal points.

Body:
I want to convert nvarchar data to float type.

In my case I have SalesValue column and I used this command

UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )

My table has values like

201.01
40.50
215.12
550
304.201

But I get an error

SQL : Error converting data type nvarchar to float.

How can I solve this problem ?

Body:
You should find the values that do not match.  In SQL Server 2012+, you can use try_convert().  That is not available.  So, how about this?

SELECT SalesValue
FROM Overseas
WHERE SalesValue LIKE '%[^0-9,.]%' OR
      SalesValue LIKE '%[.,]%[.,]%';

I think that covers the obvious irregularities:  a character that is not numeric or two (or more) decimal points.


问:
django: avoid firefox back button restore the user session
Let me put you in context: Say that I'm logged in and I close my session. After loggout if I click on back button in firefox my private page is showed, my session is restored! That does not happen in chrome. If I try to do it in chrome I'm redirected to login page with next get param set to url I'm trying to go. So how can avoid this firefox behavior, or it's matter of django?</p>

答:
This is browser default behavior when you click back button, it load previous page from browser cache

you have to write a js function which will fire on when user click on back button, you can reload page using that function.
Then you will see session expire and redirect to login page


问:
Google maps; add place card to marker
As you can see on the following image, the div (top left) shows the current marker address/directions/ save..

This was done using the embedded iframe code from google maps. But how can you do the same with custom "coded" map?

```<code>geocoder = new google.maps.Geocoder();

geocoder.geocode({
    "address": nw.google_pointer
}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {

        var myOptions = {
            zoom: parseInt(nw.google_zoom),
            center: results[0].geometry.location,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
            title: nw.google_pointer
        });
    } else {
        console.log('Geocode was not successful for the following reason: ' + status);
    }
});
</code>```

答:
I added second map in @jcsmesquita answer but there are same place cards on two maps : http://jsbin.com/vixehodaka/edit?html,css,js,output

so I changed javascript code a bit : jsbin.com/dezorezohe/edit?html,css,js,output

Title: Google maps; add place card to marker

Body:
As you can see on the following image, the div (top left) shows the current marker address/directions/ save..

This was done using the embedded iframe code from google maps. But how can you do the same with custom "coded" map?

geocoder = new google.maps.Geocoder();

geocoder.geocode({
    "address": nw.google_pointer
}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {

        var myOptions = {
            zoom: parseInt(nw.google_zoom),
            center: results[0].geometry.location,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
            title: nw.google_pointer
        });
    } else {
        console.log('Geocode was not successful for the following reason: ' + status);
    }
});


问:
stacked bar chart in ggplot when converted to plotly doesnt render right
update: adding a minimum reproducible code for the data.

im trying to convert a ggplot to plotly chart in shiny. The problem is that in ggplot, the stacked bar chart (with stat =identity) stacks up nicely without any spaces in between, whereas when i convert to plotly, there are these spaces in between each item.

I am not producing the entire code for shiny, as it is difficult to follow. However here are the images and a much simplified code (not the shiny version)

```<code>t<- 1:50
GIB_Rating = rep(c('2','3','4+','5','5-','7','8','6','6+','5'),5)
t1<-data.frame(t,GIB_Rating)
CapitalChargeType = c('Credit_risk_Capital','NameConcentration','SectorConcentration')
t2<- expand.grid(t=t, CapitalChargeType=CapitalChargeType)
t3<-left_join(t2,t1)
New = rnorm(150, mean=100,sd=250)
t3<- data.frame(t3,New)

t3<- ggplot(t3, aes(x=GIB_Rating, y=New, fill=CapitalChargeType)) + geom_bar(stat='identity')
t3
</code>```

this produces this image some what like this, which is exactly what I want.

However as it is not interactive, I want a plotly image, which shows the total of capital charge type when cursor hovers over. so, I use the code below

```<code>t4<-ggplotly(t3)
t4
</code>```

the plotly plot now produced has white lines (for each individual item) in between each color class (Capitalchargetype), which i want to avoid, also the tooltip also produces individual items rather than the sum of each CapitalChargeType

答:
The issue is in the way plotly handles stacked bars of factors. Each factor gets wrapped in a border which is white by default. There's a very easy workaround: Just add color = CapitalChargeType to the ggplot object.

```<code>library(tidyverse)
df <- data_frame(
  t = 1:50,
  GIB_Rating = rep(c('2','3','4+','5','5-','7','8','6','6+','5'),5)
)

df <- df %>%
  expand(t, CapitalChargeType =
c('Credit_risk_Capital','NameConcentration','SectorConcentration')) %>%
  left_join(df) %>%
  mutate(New = rnorm(150, mean=100,sd=250))

g <- ggplot(df, aes(x = GIB_Rating, y = New, fill = CapitalChargeType, color = CapitalChargeType)) +
  geom_bar(stat='identity')

plotly::ggplotly(g)
</code>```

Body:
update: adding a minimum reproducible code for the data.

im trying to convert a ggplot to plotly chart in shiny. The problem is that in ggplot, the stacked bar chart (with stat =identity) stacks up nicely without any spaces in between, whereas when i convert to plotly, there are these spaces in between each item.

I am not producing the entire code for shiny, as it is difficult to follow. However here are the images and a much simplified code (not the shiny version)

t<- 1:50
GIB_Rating = rep(c('2','3','4+','5','5-','7','8','6','6+','5'),5)
t1<-data.frame(t,GIB_Rating)
CapitalChargeType = c('Credit_risk_Capital','NameConcentration','SectorConcentration')
t2<- expand.grid(t=t, CapitalChargeType=CapitalChargeType)
t3<-left_join(t2,t1)
New = rnorm(150, mean=100,sd=250)
t3<- data.frame(t3,New)

t3<- ggplot(t3, aes(x=GIB_Rating, y=New, fill=CapitalChargeType)) + geom_bar(stat='identity')
t3

this produces this image some what like this, which is exactly what I want.

However as it is not interactive, I want a plotly image, which shows the total of capital charge type when cursor hovers over. so, I use the code below

t4<-ggplotly(t3)
t4

the plotly plot now produced has white lines (for each individual item) in between each color class (Capitalchargetype), which i want to avoid, also the tooltip also produces individual items rather than the sum of each CapitalChargeType

Body:
The issue is in the way plotly handles stacked bars of factors. Each factor gets wrapped in a border which is white by default. There's a very easy workaround: Just add color = CapitalChargeType to the ggplot object.

library(tidyverse)
df <- data_frame(
  t = 1:50,
  GIB_Rating = rep(c('2','3','4+','5','5-','7','8','6','6+','5'),5)
)

df <- df %>%
  expand(t, CapitalChargeType =
c('Credit_risk_Capital','NameConcentration','SectorConcentration')) %>%
  left_join(df) %>%
  mutate(New = rnorm(150, mean=100,sd=250))

g <- ggplot(df, aes(x = GIB_Rating, y = New, fill = CapitalChargeType, color = CapitalChargeType)) +
  geom_bar(stat='identity')

plotly::ggplotly(g)


问:
SQL Query with multiple JOINS on multiple tables
I have created this query to match data against multiple tables but i feel that it has got a little complicated.

I need to select from the following tables:

leads

instructors_options

instructor_calendar

using the following relationships:

```<code>leads.sequence = instructors_options.instructor_seq
leads.sequence = instructor_calendar.instructor_seq
</code>```

and the following filters MUST match:

lead.lead_type = 'Instructor'

instructors_options.option_name = 'pupil_cap' AND instructors_options.value > 0

instructors_options.option_name = 'car_type' AND instructors_options.value = 'variable'

instructors_options.option_name = 'areas_covered' AND instructors_options.value = 'variable'

instructor_calendar.pupil_name = 'AVAILABLE' AND instructor_calendar.date >= 'variable' AND instructor_calendar.date <= 'variable'

instructors_options.option_name = 'diary_updates' AND instructors_options.value = '1'

```<code>  SELECT    i.sequence as instructor_seq,
                ic.date AS date,
                ic.start_time AS start_time,
                ic.end_time AS end_time
        FROM
            leads i

        LEFT JOIN
            instructors_options io
        ON
            i.sequence = io.instructor_seq AND
            (io.option_name = 'pupil_cap' AND io.value > '0')

        RIGHT JOIN
            instructors_options io2
        ON
            i.sequence = io2.instructor_seq AND
            io2.option_name = 'car_type' AND io2.value = '".$bookingData["car_type"]."'

        RIGHT JOIN
            instructors_options io3
        ON
            i.sequence = io3.instructor_seq AND
            io3.option_name = 'areas_covered' AND (io3.value LIKE '".substr($postcode, 0, 1)."' OR io3.value LIKE '".substr($postcode, 0, 2)."' OR io3.value LIKE '".substr($postcode, 0, 3)."' OR io3.value LIKE '".substr($postcode, 0, 4)."')

        RIGHT JOIN
            instructors_options io4
        ON
            i.sequence = io4.instructor_seq AND
            io4.option_name = 'diary_updates' AND io4.value = '1'

        RIGHT JOIN
            instructor_calendar ic
        ON
            i.sequence = ic.instructor_seq AND
            ic.pupil_name = 'AVAILABLE' AND
            ic.date >= '".ChangeDateFormat($date, 'Y-m-d')."' AND
            ic.date <= '".date('Y-m-d', strtotime($date. ' + 7 days'))."'
        WHERE
            i.lead_type = 'Instructor'
        GROUP BY date
        ORDER BY date ASC, start_time ASC
</code>```

Can someone please help me update my query to ensure I have done it correctly

Thank you!

答:
You are looking for certain calendar entries. So select from that table.

One of the conditions is that the related instructor sequence has all of four certain options. So aggregate the options per instructor sequence and keep those who match all criteria. Use an IN clause to get the calendar entries for these instructor sequences.

```<code>select
  instructor_seq,
  date,
  start_time,
  end_time
from instructor_calendar
where pupil_name = 'AVAILABLE'
and date >= '2017-01-01'
and date <= '2017-05-31'
and instructor_seq in
(
  select instructor_seq
  from instructors_options
  group by instructor_seq
  having sum(option_name = 'pupil_cap'     and value > 0)   > 0
     and sum(option_name = 'car_type'      and value = 123) > 0
     and sum(option_name = 'areas_covered' and value = 456) > 0
     and sum(option_name = 'diary_updates' and value = 1)   > 0
);
</code>```

The HAVING clause makes use of MySQL's true = 1, false = 0 by the way.

Body:
I have created this query to match data against multiple tables but i feel that it has got a little complicated.

I need to select from the following tables:

leads

instructors_options

instructor_calendar

using the following relationships:

leads.sequence = instructors_options.instructor_seq
leads.sequence = instructor_calendar.instructor_seq

and the following filters MUST match:

lead.lead_type = 'Instructor'

instructors_options.option_name = 'pupil_cap' AND instructors_options.value > 0

instructors_options.option_name = 'car_type' AND instructors_options.value = 'variable'

instructors_options.option_name = 'areas_covered' AND instructors_options.value = 'variable'

instructor_calendar.pupil_name = 'AVAILABLE' AND instructor_calendar.date >= 'variable' AND instructor_calendar.date <= 'variable'

instructors_options.option_name = 'diary_updates' AND instructors_options.value = '1'

  SELECT    i.sequence as instructor_seq,
                ic.date AS date,
                ic.start_time AS start_time,
                ic.end_time AS end_time
        FROM
            leads i

        LEFT JOIN
            instructors_options io
        ON
            i.sequence = io.instructor_seq AND
            (io.option_name = 'pupil_cap' AND io.value > '0')

        RIGHT JOIN
            instructors_options io2
        ON
            i.sequence = io2.instructor_seq AND
            io2.option_name = 'car_type' AND io2.value = '".$bookingData["car_type"]."'

        RIGHT JOIN
            instructors_options io3
        ON
            i.sequence = io3.instructor_seq AND
            io3.option_name = 'areas_covered' AND (io3.value LIKE '".substr($postcode, 0, 1)."' OR io3.value LIKE '".substr($postcode, 0, 2)."' OR io3.value LIKE '".substr($postcode, 0, 3)."' OR io3.value LIKE '".substr($postcode, 0, 4)."')

        RIGHT JOIN
            instructors_options io4
        ON
            i.sequence = io4.instructor_seq AND
            io4.option_name = 'diary_updates' AND io4.value = '1'

        RIGHT JOIN
            instructor_calendar ic
        ON
            i.sequence = ic.instructor_seq AND
            ic.pupil_name = 'AVAILABLE' AND
            ic.date >= '".ChangeDateFormat($date, 'Y-m-d')."' AND
            ic.date <= '".date('Y-m-d', strtotime($date. ' + 7 days'))."'
        WHERE
            i.lead_type = 'Instructor'
        GROUP BY date
        ORDER BY date ASC, start_time ASC

Can someone please help me update my query to ensure I have done it correctly

Thank you!

Body:
You are looking for certain calendar entries. So select from that table.

One of the conditions is that the related instructor sequence has all of four certain options. So aggregate the options per instructor sequence and keep those who match all criteria. Use an IN clause to get the calendar entries for these instructor sequences.

select
  instructor_seq,
  date,
  start_time,
  end_time
from instructor_calendar
where pupil_name = 'AVAILABLE'
and date >= '2017-01-01'
and date <= '2017-05-31'
and instructor_seq in
(
  select instructor_seq
  from instructors_options
  group by instructor_seq
  having sum(option_name = 'pupil_cap'     and value > 0)   > 0
     and sum(option_name = 'car_type'      and value = 123) > 0
     and sum(option_name = 'areas_covered' and value = 456) > 0
     and sum(option_name = 'diary_updates' and value = 1)   > 0
);

The HAVING clause makes use of MySQL's true = 1, false = 0 by the way.


问:
HTML - Icons in buttons trouble
The icons inside my buttons are half outside of them for some reason even though there's definitely enough room inside for them. Why is this and how can I fix it? Also, with my css I have the buttons set to be blue but whenever they're disabled, the buttons are white. How can I have them not change their color when they're disabled? Thanks!

tfoot,
thead {
  background-color: blue;
  color: white;
}

i {
  color: white;
  vertical-align: middle;
}

button {
  background-color: blue;
}

.footertext {
  float: right;
  padding-left: 10px;
  padding-right: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td colspan="6">
  Requests:
  <button [disabled]="!isNextValid()" class="form-control" style="width: 50px; height: 25px; float: right;" (click)="nextEmployee()"><i class="fa fa-caret-right fa-2x" aria-hidden="true"></i></button>
  <label style="float: right;">{{selectedEmployee+1}} of {{empInfo.length}}</label>
  <button [disabled]="!isPreviousValid()" class="form-control" style="width: 50px; height: 25px; float: right;" (click)="previousEmployee()"><i class="fa fa-caret-left fa-2x" aria-hidden="true"></i></button>
</td></code>```

答:
It is because you are using a fixed width on your button element. Instead of a fixed with, adjust the size using padding. This will allow your button to scale properly for its content. This will also keep the label and icon centered properly in the button.

Something like this:

```<code><button [disabled]="!isNextValid()" class="form-control" style="padding: 15px 30px; float: right;" (click)="nextEmployee()"><i class="fa fa-caret-right fa-2x" aria-hidden="true"></i></button>
</code>```

Title: HTML - Icons in buttons trouble

Body:
The icons inside my buttons are half outside of them for some reason even though there's definitely enough room inside for them. Why is this and how can I fix it? Also, with my css I have the buttons set to be blue but whenever they're disabled, the buttons are white. How can I have them not change their color when they're disabled? Thanks!

tfoot,
thead {
  background-color: blue;
  color: white;
}

i {
  color: white;
  vertical-align: middle;
}

button {
  background-color: blue;
}

.footertext {
  float: right;
  padding-left: 10px;
  padding-right: 10px;
}

  Requests:
  <button [disabled]="!isNextValid()" class="form-control" style="width: 50px; height: 25px; float: right;" (click)="nextEmployee()"></button>
  {{selectedEmployee+1}} of {{empInfo.length}}
  <button [disabled]="!isPreviousValid()" class="form-control" style="width: 50px; height: 25px; float: right;" (click)="previousEmployee()"></button>

Body:
It is because you are using a fixed width on your button element. Instead of a fixed with, adjust the size using padding. This will allow your button to scale properly for its content. This will also keep the label and icon centered properly in the button.

Something like this:

<button [disabled]="!isNextValid()" class="form-control" style="padding: 15px 30px; float: right;" (click)="nextEmployee()"><i class="fa fa-caret-right fa-2x" aria-hidden="true"></i></button>


问:
SQL Server 2008: Table size is increased due to ghost records related to LOB data
A have the following table on Production environment. It is heavily updated (lots of inserts and deletes). This table contains LOB data types - ntext and nvarchar(max).
Data is constantly removed and inserted in this table. But total row count is quite stable and is about 150,000.

But for unknown reason table size is only increased. It means that space of deleted data is not release.

For example, at this moment there are 150,000 rows in the table and it occupies about 60GB. If I copy this data to new table (simple insert into) then my data will occupy only 10GB.

What I tried to do:

Shrink file or database is not helping me

Index rebuild is not helping me

DBCC CLEANTABLE is not helping me

Here's the table structure:

```<code>CREATE TABLE dbo.T_Test(
KeyHash nvarchar(50) NOT NULL,
SiteDomainId int NOT NULL,
srcFullUrl nvarchar(max) NOT NULL,
srcResponse ntext NOT NULL,
srcExpirationDate datetime NOT NULL,
srcKey nvarchar(max) NOT NULL,
srcCachePeriodInMinutes int NOT NULL,
srcNumOfHits int NOT NULL,
srcVital bit NOT NULL,
CONSTRAINT PK_T_Test_1 PRIMARY KEY NONCLUSTERED
(
KeyHash ASC,
SiteDomainId ASC
))
GO
CREATE CLUSTERED INDEX [IX_T_Test_srcExpirationDate_ppa] ON dbo.T_Test
(
srcExpirationDate ASC
)
GO
</code>```

What I know exactly that the issue is in the ghost records related to LOB data.
select * from sys.dm_db_index_physical_stats(db_id(), object_id('MyTable'), null, null, N'DETAILED') returned the following:

```<code>index_type_desc alloc_unit_type_desc record_count ghost_record_count
CLUSTERED INDEX LOB_DATA 394996 2869376
</code>```

But ghost process is working normally, i.e. ghost records are removed for IN_ROW_DATA of clustered index.

At this moment I don't have idea how to delete ghost records and reclaim space.
The only way is to truncate table and upload data again.

Any suggestion how to avoid this issue are valuable. Thank you.

Configuration of my environment is Microsoft SQL Server Web Edition (64-bit) 10.0.2531.0

答: I have restarted sql server process and the issue has been resolved.</p>

Body:
A have the following table on Production environment. It is heavily updated (lots of inserts and deletes). This table contains LOB data types - ntext and nvarchar(max).
Data is constantly removed and inserted in this table. But total row count is quite stable and is about 150,000.

But for unknown reason table size is only increased. It means that space of deleted data is not release.

For example, at this moment there are 150,000 rows in the table and it occupies about 60GB. If I copy this data to new table (simple insert into) then my data will occupy only 10GB.

What I tried to do:

Shrink file or database is not helping me

Index rebuild is not helping me

DBCC CLEANTABLE is not helping me

Here's the table structure:

CREATE TABLE dbo.T_Test(
KeyHash nvarchar(50) NOT NULL,
SiteDomainId int NOT NULL,
srcFullUrl nvarchar(max) NOT NULL,
srcResponse ntext NOT NULL,
srcExpirationDate datetime NOT NULL,
srcKey nvarchar(max) NOT NULL,
srcCachePeriodInMinutes int NOT NULL,
srcNumOfHits int NOT NULL,
srcVital bit NOT NULL,
CONSTRAINT PK_T_Test_1 PRIMARY KEY NONCLUSTERED
(
KeyHash ASC,
SiteDomainId ASC
))
GO
CREATE CLUSTERED INDEX [IX_T_Test_srcExpirationDate_ppa] ON dbo.T_Test
(
srcExpirationDate ASC
)
GO

What I know exactly that the issue is in the ghost records related to LOB data.
select * from sys.dm_db_index_physical_stats(db_id(), object_id('MyTable'), null, null, N'DETAILED') returned the following:

index_type_desc alloc_unit_type_desc record_count ghost_record_count
CLUSTERED INDEX LOB_DATA 394996 2869376

But ghost process is working normally, i.e. ghost records are removed for IN_ROW_DATA of clustered index.

At this moment I don't have idea how to delete ghost records and reclaim space.
The only way is to truncate table and upload data again.

Any suggestion how to avoid this issue are valuable. Thank you.

Configuration of my environment is Microsoft SQL Server Web Edition (64-bit) 10.0.2531.0


问:
Installing 2 year old application
I started a project 2 years ago that I now can't seem to install into other directories.

I used to follow these steps to install my angular frontend

npm install gulp

npm install typings

npm install

typings install

gulp build

I never had to do them again and it correctly installed a typings folder from which the gulp file found all it packages, it worked and I didn't mind how.

I am now trying to install it again and it does not fill the typings folder correctly, there only appears a index.d.ts file.

I found here https://github.com/typings/typings/tree/abea10b5787e1a18634d5f37bb2fa56550c32fd1
that it should've been around version 1.0.4.

So I try to install with:

```<code>npm install typings@1.0.4
</code>```

But this still does not install any typing directory.

Any direction I should look into further would be apreciated.

答: If you look have a package.json file for the 2 year old project (which you should) then you should find the version numbers of each dependency in there.</p>

Title: Installing 2 year old application

Body:
I started a project 2 years ago that I now can't seem to install into other directories.

I used to follow these steps to install my angular frontend

npm install gulp

npm install typings

npm install

typings install

gulp build

I never had to do them again and it correctly installed a typings folder from which the gulp file found all it packages, it worked and I didn't mind how.

I am now trying to install it again and it does not fill the typings folder correctly, there only appears a index.d.ts file.

I found here https://github.com/typings/typings/tree/abea10b5787e1a18634d5f37bb2fa56550c32fd1
that it should've been around version 1.0.4.

So I try to install with:

npm install typings@1.0.4

But this still does not install any typing directory.

Any direction I should look into further would be apreciated.


问:
Saving to multiple locations within Excel via Macro
This is my first post.

I've recorded a macro to save a file to multiple locations in Microsoft Excel and created a button in my personal ribbon to quickly activate it.

However when I activate the macro I get the prompt to confirm overwrite and I don't need that.

I've read other solutions in these forums but I'm not sure exactly where to insert the code as I'm not much of a coder myself. Could someone please help?

```<code>Sub SaveToNetworkDrive()
'
' SaveToNetworkDrive Macro
'

'
ChDir "V:\#E902MS"
ActiveWorkbook.SaveAs Filename:="V:\#E902MS\Greyson's Excel Log.xls", _
    FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
    ReadOnlyRecommended:=False, CreateBackup:=False
ChDir "C:\Users\E902MS\Desktop"
ActiveWorkbook.SaveAs Filename:= _
    "C:\Users\E902MS\Desktop\Greyson's Excel Log.xls", FileFormat:=xlExcel8, _
    Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
    CreateBackup:=False
End Sub
</code>```

答:
You could use FileCopy instead of save as.  FileCopy will automatically overwrite the destination file.  The On Error Resume next will stop the program from crashing if the worksheet in the copy-to location is currently in use, however this will prevent it from getting overwritten as well.

EDIT:  Added save before copy.

```<code>Thisworkbook.Save
On Error Resume Next
    FileCopy Application.ThisWorkbook.fullname, "C:\folder\" & Application.ThisWorkbook.Name
On Error GoTo 0
</code>```

Body:
This is my first post.

I've recorded a macro to save a file to multiple locations in Microsoft Excel and created a button in my personal ribbon to quickly activate it.

However when I activate the macro I get the prompt to confirm overwrite and I don't need that.

I've read other solutions in these forums but I'm not sure exactly where to insert the code as I'm not much of a coder myself. Could someone please help?

Sub SaveToNetworkDrive()
'
' SaveToNetworkDrive Macro
'

'
ChDir "V:\#E902MS"
ActiveWorkbook.SaveAs Filename:="V:\#E902MS\Greyson's Excel Log.xls", _
    FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
    ReadOnlyRecommended:=False, CreateBackup:=False
ChDir "C:\Users\E902MS\Desktop"
ActiveWorkbook.SaveAs Filename:= _
    "C:\Users\E902MS\Desktop\Greyson's Excel Log.xls", FileFormat:=xlExcel8, _
    Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
    CreateBackup:=False
End Sub

Body:
You could use FileCopy instead of save as.  FileCopy will automatically overwrite the destination file.  The On Error Resume next will stop the program from crashing if the worksheet in the copy-to location is currently in use, however this will prevent it from getting overwritten as well.

EDIT:  Added save before copy.

Thisworkbook.Save
On Error Resume Next
    FileCopy Application.ThisWorkbook.fullname, "C:\folder\" & Application.ThisWorkbook.Name
On Error GoTo 0


问:
Any point in refactoring RoleInterface use to Role at this point?
Just noticed a deprecation warning when upgrading to Symfony 3.3, that RoleInterface is now deprecated, and I should extend a Role class instead.

Reading some of the comments about this on GitHub, however, it seems both options will be deprecated once 3.4 rolls around, and removed in 4.0. (In favor of using simple strings as roles.)

So, I have to wonder, why should anybody bother making this change, when both options basically do the same thing, and both will likely exist until both are removed? What's the point?

答:
If you look at Role vs. RoleInterface you will see that Role is not deprecated, neither in branch 3.3, 3.4 nor master. This means as of now this class is not scheduled to be removed in Symfony 4. This indicates to me that the discussion ended in an agreement that Role will stay.

Long story short: Role, unlike RoleInterface, is not deprecated and will not be removed any time soon. It is absolutely safe to use.

edit: I just noticed PR #22048. So it seems I was wrong and Role might be deprecated in 3.4. Nevertheless it's probably still a good idea to extend Role for now until it's clear how to migrate from there.


问:
MySQL: Select comments and the number of replies they have
I have a 'Comments' MySQL table that has the following fields:

id

text

parent_id (NULL by default)

Basically I want to select all the comments that have a NULL parent_id, and the total number of their replies. This comment system has only one level of replies. The result would look something like:

```<code>-------------------------------------------------
| id | Text                     | total_replies |
-------------------------------------------------
| 1  | This is a comment        | 0             |
-------------------------------------------------
| 5  | another comment          | 3             |
-------------------------------------------------
| 7  | a different comment      | 1             |
-------------------------------------------------
</code>```

Appreciate your help :)

答:
Assuming replies are in the same table:</p>

```<code>SELECT c1.id, c1.text, COUNT(c2.id) total_replies
FROM comments c1
LEFT JOIN comments c2 ON c2.parent_id = c1.id
WHERE c1.parent_id IS NULL
GROUP BY c1.id, c1.text
ORDER BY c1.id
</code>```

Body:
I have a 'Comments' MySQL table that has the following fields:

id

text

parent_id (NULL by default)

Basically I want to select all the comments that have a NULL parent_id, and the total number of their replies. This comment system has only one level of replies. The result would look something like:

-------------------------------------------------
| id | Text                     | total_replies |
-------------------------------------------------
| 1  | This is a comment        | 0             |
-------------------------------------------------
| 5  | another comment          | 3             |
-------------------------------------------------
| 7  | a different comment      | 1             |
-------------------------------------------------

Appreciate your help :)

Body:
Assuming replies are in the same table:

SELECT c1.id, c1.text, COUNT(c2.id) total_replies
FROM comments c1
LEFT JOIN comments c2 ON c2.parent_id = c1.id
WHERE c1.parent_id IS NULL
GROUP BY c1.id, c1.text
ORDER BY c1.id


问:
Simplest CSS equivalent for two-column one-row table?
What is the simplest CSS equivalent for this HTML code:

```<code><table><tr><td>
One<br>
Two
</td><td>
Three<br>
Four
</td></tr></table>
</code>```

Background:

I've been asked to modify an existing website that uses CSS extensively.  My knowledge of CSS is rudimentary at best, but the changes being requested were fairly straightforward, mainly just text edits.  However, one edit involved adding a bullet list that was too long to fit in its assigned area.  I decided to use a table to break it into two lists, but when I input a rudimentary HTML table, it was offset downwards by several lines and displayed in a different font than the rest of the paragraph.  So, is there a way I can make a "table" with CSS that will inherit all the properties of the area (or is DIV the correct term) that it is in?

答:
You could do something like I've posted below. You can then just adjust the widths to be how you would need them to be.

#table {
  width: 600px;
}

#table ul {
  width: 50%;
}

#table ul li {
  float: left;
  width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="table">
  <ul>
    <li>One</li>
    <li>Two</li>
  </ul>
  <ul>
    <li>One</li>
    <li>Two</li>
  </ul>
</div></code>```

Body:
What is the simplest CSS equivalent for this HTML code:

One

Two

Three

Four

Background:

I've been asked to modify an existing website that uses CSS extensively.  My knowledge of CSS is rudimentary at best, but the changes being requested were fairly straightforward, mainly just text edits.  However, one edit involved adding a bullet list that was too long to fit in its assigned area.  I decided to use a table to break it into two lists, but when I input a rudimentary HTML table, it was offset downwards by several lines and displayed in a different font than the rest of the paragraph.  So, is there a way I can make a "table" with CSS that will inherit all the properties of the area (or is DIV the correct term) that it is in?

Body:
You could do something like I've posted below. You can then just adjust the widths to be how you would need them to be.

#table {
  width: 600px;
}

#table ul {
  width: 50%;
}

#table ul li {
  float: left;
  width: 50%;
}

<div id="table">
  <ul>
    <li>One</li>
    <li>Two</li>
  </ul>
  <ul>
    <li>One</li>
    <li>Two</li>
  </ul>
</div>


问:
why passing in a temp variable into const ref in ctor work?
```<code>// Example program
#include <iostream>
#include <string>

struct foo
{
    int d_member;

    foo(const int & in):
    d_member(in){};
};

int main()
{
    foo *p;

    {
        int temp = 5;
        p = new foo(temp);
    }

    std::cout << p->d_member << std::endl;

    return 0;
}
</code>```

Foo takes a const ref in it's ctor to a int, and I passed a temporary int to it.
temp is destroyed after new. Why I am still able to print out d_member?

答:
As others already mentioned with a non reference member variable your constructor call simply copies the value from the const reference parameter (and it even doesn't matter if you pass it by reference or value).

You would have a different situation, if your member variable is a reference like

```<code>struct foo
{
    const int& d_member; // <<<< reference member variable

    foo(const int & in): d_member(in){};
};
</code>```

In that case, accessing d_member after your scope block would raise undefined behavior:

```<code>{
    int temp = 5;
    p = new foo(temp);
}

std::cout << p->d_member << std::endl; // <<<<  Undefined behavior
</code>```

Body:
// Example program
#include <iostream>
#include <string>

struct foo
{
    int d_member;

    foo(const int & in):
    d_member(in){};
};

int main()
{
    foo *p;

    {
        int temp = 5;
        p = new foo(temp);
    }

    std::cout <
d_member << std::endl;

    return 0;
}

Foo takes a const ref in it's ctor to a int, and I passed a temporary int to it.
temp is destroyed after new. Why I am still able to print out d_member?

Body:
As others already mentioned with a non reference member variable your constructor call simply copies the value from the const reference parameter (and it even doesn't matter if you pass it by reference or value).

You would have a different situation, if your member variable is a reference like

struct foo
{
    const int& d_member; // <<<< reference member variable

    foo(const int & in): d_member(in){};
};

In that case, accessing d_member after your scope block would raise undefined behavior:

{
    int temp = 5;
    p = new foo(temp);
}

std::cout << p->d_member << std::endl; // <<<<  Undefined behavior


问:
Authentication errors in HTTP requisitions with AngularJs and Keycloak
I'm trying to create an app for study purposes with AngularJS and Keycloak.

And I'm experiencing some errors in my HTML requisitions:

Failed to load resource: the server responded with a status of 401 ()

XMLHttpRequest cannot load http://127.0.0.1:8081/customers. Response for preflight has invalid HTTP status code 401

My problem is in the requests made by the app. The requests made by Postman works fine.

My HTTP Requisition:

```<code>$http({
  method: 'GET',
  url: 'http://127.0.0.1:8081/customers'
}).then(function success(response) {
  console.log('success');
}, function error() {
  console.log('error');
});
</code>```

My angular configs:

```<code>app.config(['$httpProvider', function ($httpProvider) {
   $httpProvider.interceptors.push('BearerAuthInterceptor');
}]);

app.factory('BearerAuthInterceptor', function () {
  var token = window._keycloak.token;

  return {
    request: function (config) {
      config.headers = config.headers || {};
      if (token) {
        config.headers.Authorization = 'Bearer ' + token;
      }
      return config;
    }
  };
});
</code>```

From what I saw, the token is being sent in the header correctly.

I would be grateful if anyone could help me.

答:
Make sure you have CORS enabled on your server to allow the client to make cross domain/cross port requests.  The error

XMLHttpRequest cannot load http://127.0.0.1:8081/customers. Response
  for preflight has invalid HTTP status code 401

401 is unauthorized, preflight is the OPTIONS request the browser sends ahead of another HTTP request automatically when the request is using AJAX and is going to another domain/port from the client code that is making the call.  The server just needs to respond with the appropriate headers to allow the client to get the response (it has to respond with the appropriate headers to the OPTION request)

https://enable-cors.org/

Body:
I'm trying to create an app for study purposes with AngularJS and Keycloak.

And I'm experiencing some errors in my HTML requisitions:

Failed to load resource: the server responded with a status of 401 ()

XMLHttpRequest cannot load http://127.0.0.1:8081/customers. Response for preflight has invalid HTTP status code 401

My problem is in the requests made by the app. The requests made by Postman works fine.

My HTTP Requisition:

$http({
  method: 'GET',
  url: 'http://127.0.0.1:8081/customers'
}).then(function success(response) {
  console.log('success');
}, function error() {
  console.log('error');
});

My angular configs:

app.config(['$httpProvider', function ($httpProvider) {
   $httpProvider.interceptors.push('BearerAuthInterceptor');
}]);

app.factory('BearerAuthInterceptor', function () {
  var token = window._keycloak.token;

  return {
    request: function (config) {
      config.headers = config.headers || {};
      if (token) {
        config.headers.Authorization = 'Bearer ' + token;
      }
      return config;
    }
  };
});

From what I saw, the token is being sent in the header correctly.

I would be grateful if anyone could help me.


问:
Is it safe to send credit card details securely over http POST using swift?
The API that I'm using requires me to send Credit Card Details to complete payment through a HTTP POST request (through swift). Is this safe by any means? And moreover, how do I securely store credit card information for repeated payments?

The credit card holder's name, credit card number, cvc, and date of expiry are all sent over a POST request. Then, the API returns whether the payment was successful, and the last four digits of the credit card number.

Simply put, I'm not entirely familiar with payment security, and would like to know if this is safe, and moreover how to save payment information securely using swift, even if that's possible. I don't think I can use stripe for this process, but I would love to know if that's possible as well.

EDIT:
I have confirmed that the API I'm using does in fact employ an HTTPS connection, and not simply a HTTP server. At this point, I know not to save credit card information locally and that I should retrieve it from a third party service before handling it. Thanks All!

答: Sending any sensitive information over HTTP is not secure and not recommended. Most of the payment gate ways doesn't allow you to establish a session on HTTP. Even if you are using HTTPS usually sensitive information is encrypted and sometimes encoded on client end and server decrypts, decodes and processes it which inturn gives double security to the requests you make.</p>


问:
How to authorize webapp with ebay?
I am making a django app that can hold info about items i have on ebay.
So, each user would have multiple ebay accounts.
For example:
user1 would have access to ebay1, ebay2, ebay3 account.
How can I get appid, certid, devid and token for each account?
The best would be to click 'add ebay account' and in new window with ebay sign in page and authorize by inserting username/password.

I had a look to:

https://github.com/timotheus/ebaysdk-python

https://developer.ebay.com/devzone/xml/docs/reference/ebay/FetchToken.html

but it is not clear to me.
Can anyone provide me some step-by-step or any guidelines?

Thanks in advance

答:
You simply login to the developer account and then Click User Tokens.

next click Get a User Token Here.

login to each account you need a token for

your APPID, CertId, and DevID always stay the same..

Title: How to authorize webapp with ebay?