问:
Function not returning result in c (in a project file)
When I run this code in a .c file, it works, but when I make a project for it, the function I call will only return 0.00. Why? Why does it not work in a project file?

I'm using DevC++.

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

float mean(int total, int max);

int main(){
    int i,max, total=0;
    int array[max];
    printf("Enter max: ");
    scanf("%d",&max);

    for(i=0; i<max; i++){
        scanf("%d",&array[i]);
        total+=array[i];
    }
    printf("Total: %d\n",total);
    printf("Mean: %.2f",mean(total,max));
    return 0;
}

float mean(int total, int max){
    float ave;
    ave=(float)total/max;

    return ave;
}
</code>```

答:
The problem is with these two lines of code - you're declaring the size of array to be max before you actually work out what value max has which will cause unexplained behaviour. It's most likely pure chance that your code ever worked as expected.

```<code>int array[max];
...
scanf("%d",&max);
</code>```

The way to do what you're trying to do is to allocate memory big enough to hold your array like this. You'd probably want to check that max is more than 0 too and also that scanf found a number. But the rough gist of it is like this:

```<code>int max;
int *array;
printf("Enter max: ");
scanf("%d",&max);
array=malloc(sizeof(int)*max);

/* your code goes here */

free(array);
</code>```

Body:
When I run this code in a .c file, it works, but when I make a project for it, the function I call will only return 0.00. Why? Why does it not work in a project file?

I'm using DevC++.

#include<stdio.h>

float mean(int total, int max);

int main(){
    int i,max, total=0;
    int array[max];
    printf("Enter max: ");
    scanf("%d",&max);

    for(i=0; i<max; i++){
        scanf("%d",&array[i]);
        total+=array[i];
    }
    printf("Total: %d\n",total);
    printf("Mean: %.2f",mean(total,max));
    return 0;
}

float mean(int total, int max){
    float ave;
    ave=(float)total/max;

    return ave;
}

Body:
The problem is with these two lines of code - you're declaring the size of array to be max before you actually work out what value max has which will cause unexplained behaviour. It's most likely pure chance that your code ever worked as expected.

int array[max];
...
scanf("%d",&max);

The way to do what you're trying to do is to allocate memory big enough to hold your array like this. You'd probably want to check that max is more than 0 too and also that scanf found a number. But the rough gist of it is like this:

int max;
int *array;
printf("Enter max: ");
scanf("%d",&max);
array=malloc(sizeof(int)*max);

/* your code goes here */

free(array);


来源: stackexchange

问:
my js works in another browser but not in chrome
when i click on button ajax must load more contents and to throw the user in top of the new load contents.Function worked perfectly in mozilla and IE but not in Chrome i don't know where is the problem. Thanks in advance.</p>

```<code>if ($showMoreOffersButton) { ?>
        <div class="text-center box" id="show-more-tourism-offers-btn-holder">
            <a class="site-button blue" onclick="showMoreTourismOffers(<?php echo $offset; ?>)"
               onclick="ga('send', 'event', '<?= isset($parent_component) ? $parent_component : 'Unknown' ?>', 'Show More Offers' );">
                <span class="glyphicon glyphicon-refresh spinning" id="travel-arrow-spinner"
                      style="display: none"></span>
                ОЩЕ ОФЕРТИ
            </a>
        </div>
    <? }

function showMoreTourismOffers(begin_offset) {
if (!btn_lock) {
    //check if user already visited this page and saw more than 16 boxes
    if (offset < begin_offset) {
        offset = begin_offset;
    }
    var mobileFlag;
    if(isMobile == 1){
        mobileFlag = true;
    }else{
        mobileFlag = false;
    }
    $.ajax({
        url: base_url + 'pochivki/show_more_offers/',
        type: 'POST',
        data: {
            filter: ajaxDealFilter(true, mobileFlag),
            country_index: countryIndex,
            region_index: regionIndex,
            city_index: cityIndex,
            offset: offset,
            current_url: window.location.href
        },
        success: function (data) {
            $('#tourism-deals-holder').append(data.deals);
            if (data.hideButton) {
                $('#show-more-tourism-offers-btn-holder').remove();
            }
             offset += 48;
            $('#travel-arrow-spinner').hide();
        },
        error: function () {
        },
        beforeSend: function () {
            btn_lock = !btn_lock; // becomes true
            $('#travel-arrow-spinner').show();
        },
        complete: function () {
            btn_lock = !btn_lock; // becomes false again
            $('.images-rotation').imagesRotation()
        },
        dataType: "json"
    });
}   }
</code>```

答:
solving this problem  i hope this help of anyone who have the same problem

```<code>function showMoreTourismOffers(begin_offset) {
if (!btn_lock) {
    //check if user already visited this page and saw more than 16 boxes
    if (offset < begin_offset) {
        offset = begin_offset;
    }
    var mobileFlag;
    if(isMobile == 1){
        mobileFlag = true;
    }else{
        mobileFlag = false;
    }

    var buttonPosition = $('#show-more-tourism-offers-btn-holder').position();
    var buttonPositionTop = buttonPosition.top;

    $.ajax({
        url: base_url + 'pochivki/show_more_offers/',
        type: 'POST',
        data: {
            filter: ajaxDealFilter(true, mobileFlag),
            country_index: countryIndex,
            region_index: regionIndex,
            city_index: cityIndex,
            offset: offset,
            current_url: window.location.href
        },
        success: function (data) {
            $('#tourism-deals-holder').append(data.deals);
            $('body').scrollTop(buttonPositionTop);
            if (data.hideButton) {
                $('#show-more-tourism-offers-btn-holder').remove();
            }
             offset += 48;
            $('#travel-arrow-spinner').hide();
        },
        error: function () {

        },
        beforeSend: function () {
            btn_lock = !btn_lock; // becomes true
            $('#travel-arrow-spinner').show();
        },
        complete: function () {
            btn_lock = !btn_lock; // becomes false again
            $('.images-rotation').imagesRotation()
        },
        dataType: "json"
    });
}
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
when i click on button ajax must load more contents and to throw the user in top of the new load contents.Function worked perfectly in mozilla and IE but not in Chrome i don't know where is the problem. Thanks in advance.

if ($showMoreOffersButton) { ?>

            <a class="site-button blue" onclick="showMoreTourismOffers(<?php echo $offset; ?>)"
               onclick="ga('send', 'event', '<?= isset($parent_component) ? $parent_component : 'Unknown' ?>', 'Show More Offers' );">

                ОЩЕ ОФЕРТИ

    <? }

function showMoreTourismOffers(begin_offset) {
if (!btn_lock) {
    //check if user already visited this page and saw more than 16 boxes
    if (offset < begin_offset) {
        offset = begin_offset;
    }
    var mobileFlag;
    if(isMobile == 1){
        mobileFlag = true;
    }else{
        mobileFlag = false;
    }
    $.ajax({
        url: base_url + 'pochivki/show_more_offers/',
        type: 'POST',
        data: {
            filter: ajaxDealFilter(true, mobileFlag),
            country_index: countryIndex,
            region_index: regionIndex,
            city_index: cityIndex,
            offset: offset,
            current_url: window.location.href
        },
        success: function (data) {
            $('#tourism-deals-holder').append(data.deals);
            if (data.hideButton) {
                $('#show-more-tourism-offers-btn-holder').remove();
            }
             offset += 48;
            $('#travel-arrow-spinner').hide();
        },
        error: function () {
        },
        beforeSend: function () {
            btn_lock = !btn_lock; // becomes true
            $('#travel-arrow-spinner').show();
        },
        complete: function () {
            btn_lock = !btn_lock; // becomes false again
            $('.images-rotation').imagesRotation()
        },
        dataType: "json"
    });
}   }

Body:
solving this problem  i hope this help of anyone who have the same problem

function showMoreTourismOffers(begin_offset) {
if (!btn_lock) {
    //check if user already visited this page and saw more than 16 boxes
    if (offset < begin_offset) {
        offset = begin_offset;
    }
    var mobileFlag;
    if(isMobile == 1){
        mobileFlag = true;
    }else{
        mobileFlag = false;
    }

    var buttonPosition = $('#show-more-tourism-offers-btn-holder').position();
    var buttonPositionTop = buttonPosition.top;

    $.ajax({
        url: base_url + 'pochivki/show_more_offers/',
        type: 'POST',
        data: {
            filter: ajaxDealFilter(true, mobileFlag),
            country_index: countryIndex,
            region_index: regionIndex,
            city_index: cityIndex,
            offset: offset,
            current_url: window.location.href
        },
        success: function (data) {
            $('#tourism-deals-holder').append(data.deals);
            $('body').scrollTop(buttonPositionTop);
            if (data.hideButton) {
                $('#show-more-tourism-offers-btn-holder').remove();
            }
             offset += 48;
            $('#travel-arrow-spinner').hide();
        },
        error: function () {

        },
        beforeSend: function () {
            btn_lock = !btn_lock; // becomes true
            $('#travel-arrow-spinner').show();
        },
        complete: function () {
            btn_lock = !btn_lock; // becomes false again
            $('.images-rotation').imagesRotation()
        },
        dataType: "json"
    });
}

}


问:
Arduino Loop Confusion
I'm creating an auto watering system for some plants. I am using a motor to control them, and soil sensors to tell when they need water. But I'm having trouble both understanding how I should be approaching this and secondly why my code isn't working. My problem is that the while loop is never initialized, and so the motor never stops I can tell this by my serial monitor.</p>

```<code>      if(sensorVal1 <= thresholdDown1){
Serial.println("Plant Group 1 is Dry!");
Serial.println(sensorVal1);
Serial.println("Watering");
digitalWrite(in1, LOW); //LEFT
digitalWrite(in2, HIGH);
analogWrite(enA, 255);

delay(6250);

startTime = millis();
while(sensorVal1 <= thresholdDown1){
  Serial.println("Stopping");
    digitalWrite(in1, LOW);
digitalWrite(in2, LOW);

      if(sensorVal1 >= thresholdUp1){
     break;
   }
}

      totalTime = millis() - startTime;
      digitalWrite(in1, HIGH); //RIGHT
      digitalWrite(in2, LOW);
      delay(500);
      digitalWrite(in1, LOW); //OFF
      digitalWrite(in2, LOW);
      delay(totalTime);
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      delay(500);
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      delay(totalTime);
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      delay(3000);
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);

      }
</code>```

答:
Here is a very simple logic you can try :

```<code>if( sensorVal <= treshold ) {
  Serial.println("Watering");
  waterOn();
} else {
  Serial.println("NOT watering");
  waterOff();
}
</code>```

Title: Arduino Loop Confusion

Body:
I'm creating an auto watering system for some plants. I am using a motor to control them, and soil sensors to tell when they need water. But I'm having trouble both understanding how I should be approaching this and secondly why my code isn't working. My problem is that the while loop is never initialized, and so the motor never stops I can tell this by my serial monitor.

      if(sensorVal1 <= thresholdDown1){
Serial.println("Plant Group 1 is Dry!");
Serial.println(sensorVal1);
Serial.println("Watering");
digitalWrite(in1, LOW); //LEFT
digitalWrite(in2, HIGH);
analogWrite(enA, 255);

delay(6250);

startTime = millis();
while(sensorVal1 <= thresholdDown1){
  Serial.println("Stopping");
    digitalWrite(in1, LOW);
digitalWrite(in2, LOW);

      if(sensorVal1 >= thresholdUp1){
     break;
   }
}

      totalTime = millis() - startTime;
      digitalWrite(in1, HIGH); //RIGHT
      digitalWrite(in2, LOW);
      delay(500);
      digitalWrite(in1, LOW); //OFF
      digitalWrite(in2, LOW);
      delay(totalTime);
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      delay(500);
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      delay(totalTime);
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      delay(3000);
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);

      }

Body:
Here is a very simple logic you can try :

if( sensorVal <= treshold ) {
  Serial.println("Watering");
  waterOn();
} else {
  Serial.println("NOT watering");
  waterOff();
}


问:
Tokenize by using regular expressions (parenthesis)
I have the following text:

I don't like to eat Cici's food (it is true)

I need to tokenize it to

['i', 'don't', 'like', 'to', 'eat', 'Cici's', 'food', '(', 'it', 'is', 'true', ')']

I have found out that the following regex expression (['()\w]+|\.) splits like this:

['i', 'don't', 'like', 'to', 'eat', 'Cici's', 'food', '(it', 'is', 'true)']

How do I take the parenthesis out of the token and make it to an own token?

Thanks for ideas.

答:
When you want to tokenize a string with regex with special restrictions on context, you may use a matching approach that usually yields cleaner output (especially when it comes to empty elements in the resulting list).

Any word character is matched with \w and any non-word char is matched with \W. If you wanted to tokenize the string into word and non-word chars, you could use \w+|\W+ regex. However, in your case, you want to match word character chunks that are optionally followed with ' that is followed with 1+ word characters, and any other single characters that are not whitespace.

Use

```<code>re.findall(r"\w+(?:'\w+)?|[^\w\s]", s)
</code>```

Here, \w+(?:'\w+)? matches the words like people or people's, and [^\w\s] matches a single character other than word and whitespace character.

See the regex demo

Python demo:

```<code>import re
rx = r"\w+(?:'\w+)?|[^\w\s]"
s = "I don't like to eat Cici's food (it is true)"
print(re.findall(rx, s))
</code>```

Another example that will tokenize using ( and ):

```<code>[^()\s]+|[()]
</code>```

See the regex demo

Here, [^()\s]+ matches 1 or more symbols other than (, ) and whitespace, and [()] matches either ( or ).

ContentLicense: CC BY-SA 4.0

Body:
When you want to tokenize a string with regex with special restrictions on context, you may use a matching approach that usually yields cleaner output (especially when it comes to empty elements in the resulting list).

Any word character is matched with \w and any non-word char is matched with \W. If you wanted to tokenize the string into word and non-word chars, you could use \w+|\W+ regex. However, in your case, you want to match word character chunks that are optionally followed with ' that is followed with 1+ word characters, and any other single characters that are not whitespace.

Use

re.findall(r"\w+(?:'\w+)?|[^\w\s]", s)

Here, \w+(?:'\w+)? matches the words like people or people's, and [^\w\s] matches a single character other than word and whitespace character.

See the regex demo

Python demo:

import re
rx = r"\w+(?:'\w+)?|[^\w\s]"
s = "I don't like to eat Cici's food (it is true)"
print(re.findall(rx, s))

Another example that will tokenize using ( and ):

[^()\s]+|[()]

See the regex demo

Here, [^()\s]+ matches 1 or more symbols other than (, ) and whitespace, and [()] matches either ( or ).


问:
Add custom atrribute to json response
I have model something like that with custom attribute

```<code>class MyModel extends Model
{
    public function getExtraAttribute(){
        return 'some string'; //etc.
    }
}
</code>```

And for controller method i have this

```<code>return MyModel::where('user_id', Auth::user()->id)->get();
</code>```

But i don't see 'extra' attribute on json response

P.s. extra isn't column from database.

答:
As per the docs here: https://laravel.com/docs/5.4/eloquent-serialization#appending-values-to-json</p>
```<code>class User extends Model
{
     protected $appends = ['extra'];

     public function getExtraAttribute()
     {
        return $this->attributes['extra'] = 'some string...';
     }
}
</code>```

Title: Add custom atrribute to json response

Body:
I have model something like that with custom attribute

class MyModel extends Model
{
    public function getExtraAttribute(){
        return 'some string'; //etc.
    }
}

And for controller method i have this

return MyModel::where('user_id', Auth::user()->id)->get();

But i don't see 'extra' attribute on json response

P.s. extra isn't column from database.

Body:
As per the docs here: https://laravel.com/docs/5.4/eloquent-serialization#appending-values-to-json

class User extends Model
{
     protected $appends = ['extra'];

     public function getExtraAttribute()
     {
        return $this->attributes['extra'] = 'some string...';
     }
}


问:
Link button full height of container Bootstrap
I'm having issues forcing a link to take full height of its parent container.

Here is a Fiddle of my code: http://jsfiddle.net/z2ua5g4j/

```<code>a > span.button-single {
    font-size: 30px;
    color: #fff;
    display: block;
    margin-bottom: 8px;
    margin-left: 0px;
}

.box {
    background-color: #f5f5f5;
    border: 1px solid #dcdcdc;
    height: 100%;
}

.box h1 {
    color: #667477;
    font-size: 24px;
    margin-left: 20px;
}

.box p {
    color: #b1b1b1;
    font-size: 13px;
    margin-left: 20px;
    margin-bottom: 20px;
}

.box a.button {
    width: 95px;
    background-color: #b4b4b4;
    margin-right:-1px;
    color: #fff;
    padding-top: 13px;
    padding-bottom: 13px;
    font-size: 15px;
    line-height: 16px;
    text-align: center;
    float: right;
    height: 100%;
    display: block;
}

.box a.button:hover {
    text-decoration: none;
    background-color: #a7a7a7;
}
</code>```

Basically, I want to make the gray button (on the right) take full height of the box container. As of writing, I've tried setting the link to display block and set its height to 100%, but with no avail.

Any ideas?

答:
Just use the btn-block class instead of messing around with div heights, like this:

```<code><div class="col-md-3"><button class="btn btn-block" >Show Details</button></div>
</code>```

Body:
I'm having issues forcing a link to take full height of its parent container.

Here is a Fiddle of my code: http://jsfiddle.net/z2ua5g4j/

a > span.button-single {
    font-size: 30px;
    color: #fff;
    display: block;
    margin-bottom: 8px;
    margin-left: 0px;
}

.box {
    background-color: #f5f5f5;
    border: 1px solid #dcdcdc;
    height: 100%;
}

.box h1 {
    color: #667477;
    font-size: 24px;
    margin-left: 20px;
}

.box p {
    color: #b1b1b1;
    font-size: 13px;
    margin-left: 20px;
    margin-bottom: 20px;
}

.box a.button {
    width: 95px;
    background-color: #b4b4b4;
    margin-right:-1px;
    color: #fff;
    padding-top: 13px;
    padding-bottom: 13px;
    font-size: 15px;
    line-height: 16px;
    text-align: center;
    float: right;
    height: 100%;
    display: block;
}

.box a.button:hover {
    text-decoration: none;
    background-color: #a7a7a7;
}

Basically, I want to make the gray button (on the right) take full height of the box container. As of writing, I've tried setting the link to display block and set its height to 100%, but with no avail.

Any ideas?

Body:
Just use the btn-block class instead of messing around with div heights, like this:

<div class="col-md-3"><button class="btn btn-block" >Show Details</button></div>


问:
Can't install curb gem in Linux Mint
I have a problem with installing curb. When I type in my console:

```<code> sudo gem install curb
</code>```

It returns me following error:

```<code>Fetching: curb-0.8.6.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing curb:
    ERROR: Failed to build gem native extension.

        /usr/bin/ruby1.9.1 extconf.rb
checking for curl-config... no
checking for main() in -lcurl... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/bin/ruby1.9.1
    --with-curl-dir
    --without-curl-dir
    --with-curl-include
    --without-curl-include=${curl-dir}/include
    --with-curl-lib
    --without-curl-lib=${curl-dir}/lib
    --with-curllib
    --without-curllib
extconf.rb:23:in `<main>':   Can't find libcurl or curl/curl.h (RuntimeError)

  Try passing --with-curl-dir or --with-curl-lib and --with-curl-include
  options to extconf.

Gem files will remain installed in /var/lib/gems/1.9.1/gems/curb-0.8.6 for inspection.
Results logged to /var/lib/gems/1.9.1/gems/curb-0.8.6/ext/gem_make.out
</code>```

I don't have any idea how to solve this problem. I was looking for some solution in Google but not find anything that will help me to solve this problem. Please help...

EDIT:

Here is mkmf.log file. Maybe it will be helpfull in debuging:

```<code>find_executable: checking for curl-config... -------------------- no

--------------------

have_library: checking for main() in -lcurl... -------------------- no

"gcc -o conftest -I/usr/include/ruby-1.9.1/x86_64-linux -I/usr/include/ruby-1.9.1/ruby/backward -I/usr/include/ruby-1.9.1 -I. -D_FORTIFY_SOURCE=2  -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wall -fno-strict-aliasing -fPIC conftest.c  -L. -L/usr/lib -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -L/build/buildd/ruby1.9.1-1.9.3.484/debian/lib -rdynamic -Wl,-export-dynamic     -lruby-1.9.1  -lpthread -lrt -ldl -lcrypt -lm   -lc"
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */

"gcc -o conftest -I/usr/include/ruby-1.9.1/x86_64-linux -I/usr/include/ruby-1.9.1/ruby/backward -I/usr/include/ruby-1.9.1 -I. -D_FORTIFY_SOURCE=2  -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wall -fno-strict-aliasing -fPIC conftest.c  -L. -L/usr/lib -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -L/build/buildd/ruby1.9.1-1.9.3.484/debian/lib -rdynamic -Wl,-export-dynamic     -lruby-1.9.1 -lcurl  -lpthread -lrt -ldl -lcrypt -lm   -lc"
conftest.c: In function ‘t’:
conftest.c:4:53: error: ‘main’ undeclared (first use in this function)
 int t() { void ((*volatile p)()); p = (void ((*)()))main; return 0; }
                                                     ^
conftest.c:4:53: note: each undeclared identifier is reported only once for each function it appears in
conftest.c:4:28: warning: variable ‘p’ set but not used [-Wunused-but-set-variable]
 int t() { void ((*volatile p)()); p = (void ((*)()))main; return 0; }
                            ^
checked program was:
/* begin */
 1: #include "ruby.h"
 2:
 3: /*top*/
 4: int t() { void ((*volatile p)()); p = (void ((*)()))main; return 0; }
 5: int main(int argc, char **argv)
 6: {
 7:   if (argc > 1000000) {
 8:     printf("%p", &t);
 9:   }
10:
11:   return 0;
12: }
/* end */

"gcc -o conftest -I/usr/include/ruby-1.9.1/x86_64-linux -I/usr/include/ruby-1.9.1/ruby/backward -I/usr/include/ruby-1.9.1 -I. -D_FORTIFY_SOURCE=2  -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wall -fno-strict-aliasing -fPIC conftest.c  -L. -L/usr/lib -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -L/build/buildd/ruby1.9.1-1.9.3.484/debian/lib -rdynamic -Wl,-export-dynamic     -lruby-1.9.1 -lcurl  -lpthread -lrt -ldl -lcrypt -lm   -lc"
conftest.c: In function ‘t’:
conftest.c:4:1: warning: implicit declaration of function ‘main’ [-Wimplicit-function-declaration]
 int t() { main(); return 0; }
 ^
/usr/bin/ld: cannot find -lcurl
collect2: error: ld returned 1 exit status
checked program was:
/* begin */
 1: #include "ruby.h"
 2:
 3: /*top*/
 4: int t() { main(); return 0; }
 5: int main(int argc, char **argv)
 6: {
 7:   if (argc > 1000000) {
 8:     printf("%p", &t);
 9:   }
10:
11:   return 0;
12: }
/* end */

--------------------
</code>```

答:
Use command from previous answer

sudo apt-get install libcurl3 libcurl3-gnutls libcurl4-openssl-dev

Sometimes Mint can't install libcurl4-openssl-dev because of next error.

```<code>The following packages have unmet dependencies:
 libldap2-dev : Depends: libldap-2.4-2 (= 2.4.31-1+nmu2ubuntu8.2) but 2.4.31-1+nmu2ubuntu8.3 is to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

In my case I've resolved it with next command:

sudo aptitude install libldap2-dev

At first it suggested to do nothing, I've selected No, then it suggested to downgrade my current install to proper version. I've selected Yes. Then I was able to install libcurl4-openssl-dev as usual

Title: Can't install curb gem in Linux Mint

Body:
I have a problem with installing curb. When I type in my console:

 sudo gem install curb

It returns me following error:

Fetching: curb-0.8.6.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing curb:
    ERROR: Failed to build gem native extension.

        /usr/bin/ruby1.9.1 extconf.rb
checking for curl-config... no
checking for main() in -lcurl... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/bin/ruby1.9.1
    --with-curl-dir
    --without-curl-dir
    --with-curl-include
    --without-curl-include=${curl-dir}/include
    --with-curl-lib
    --without-curl-lib=${curl-dir}/lib
    --with-curllib
    --without-curllib
extconf.rb:23:in `':   Can't find libcurl or curl/curl.h (RuntimeError)

  Try passing --with-curl-dir or --with-curl-lib and --with-curl-include
  options to extconf.

Gem files will remain installed in /var/lib/gems/1.9.1/gems/curb-0.8.6 for inspection.
Results logged to /var/lib/gems/1.9.1/gems/curb-0.8.6/ext/gem_make.out

I don't have any idea how to solve this problem. I was looking for some solution in Google but not find anything that will help me to solve this problem. Please help...

EDIT:

Here is mkmf.log file. Maybe it will be helpfull in debuging:

find_executable: checking for curl-config... -------------------- no

--------------------

have_library: checking for main() in -lcurl... -------------------- no

"gcc -o conftest -I/usr/include/ruby-1.9.1/x86_64-linux -I/usr/include/ruby-1.9.1/ruby/backward -I/usr/include/ruby-1.9.1 -I. -D_FORTIFY_SOURCE=2  -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wall -fno-strict-aliasing -fPIC conftest.c  -L. -L/usr/lib -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -L/build/buildd/ruby1.9.1-1.9.3.484/debian/lib -rdynamic -Wl,-export-dynamic     -lruby-1.9.1  -lpthread -lrt -ldl -lcrypt -lm   -lc"
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main(int argc, char **argv)
4: {
5:   return 0;
6: }
/* end */

"gcc -o conftest -I/usr/include/ruby-1.9.1/x86_64-linux -I/usr/include/ruby-1.9.1/ruby/backward -I/usr/include/ruby-1.9.1 -I. -D_FORTIFY_SOURCE=2  -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wall -fno-strict-aliasing -fPIC conftest.c  -L. -L/usr/lib -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -L/build/buildd/ruby1.9.1-1.9.3.484/debian/lib -rdynamic -Wl,-export-dynamic     -lruby-1.9.1 -lcurl  -lpthread -lrt -ldl -lcrypt -lm   -lc"
conftest.c: In function ‘t’:
conftest.c:4:53: error: ‘main’ undeclared (first use in this function)
 int t() { void ((*volatile p)()); p = (void ((*)()))main; return 0; }
                                                     ^
conftest.c:4:53: note: each undeclared identifier is reported only once for each function it appears in
conftest.c:4:28: warning: variable ‘p’ set but not used [-Wunused-but-set-variable]
 int t() { void ((*volatile p)()); p = (void ((*)()))main; return 0; }
                            ^
checked program was:
/* begin */
 1: #include "ruby.h"
 2:
 3: /*top*/
 4: int t() { void ((*volatile p)()); p = (void ((*)()))main; return 0; }
 5: int main(int argc, char **argv)
 6: {
 7:   if (argc > 1000000) {
 8:     printf("%p", &t);
 9:   }
10:
11:   return 0;
12: }
/* end */

"gcc -o conftest -I/usr/include/ruby-1.9.1/x86_64-linux -I/usr/include/ruby-1.9.1/ruby/backward -I/usr/include/ruby-1.9.1 -I. -D_FORTIFY_SOURCE=2  -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -Wall -fno-strict-aliasing -fPIC conftest.c  -L. -L/usr/lib -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -L/build/buildd/ruby1.9.1-1.9.3.484/debian/lib -rdynamic -Wl,-export-dynamic     -lruby-1.9.1 -lcurl  -lpthread -lrt -ldl -lcrypt -lm   -lc"
conftest.c: In function ‘t’:
conftest.c:4:1: warning: implicit declaration of function ‘main’ [-Wimplicit-function-declaration]
 int t() { main(); return 0; }
 ^
/usr/bin/ld: cannot find -lcurl
collect2: error: ld returned 1 exit status
checked program was:
/* begin */
 1: #include "ruby.h"
 2:
 3: /*top*/
 4: int t() { main(); return 0; }
 5: int main(int argc, char **argv)
 6: {
 7:   if (argc > 1000000) {
 8:     printf("%p", &t);
 9:   }
10:
11:   return 0;
12: }
/* end */

--------------------

Body:
Use command from previous answer

sudo apt-get install libcurl3 libcurl3-gnutls libcurl4-openssl-dev

Sometimes Mint can't install libcurl4-openssl-dev because of next error.

The following packages have unmet dependencies:
 libldap2-dev : Depends: libldap-2.4-2 (= 2.4.31-1+nmu2ubuntu8.2) but 2.4.31-1+nmu2ubuntu8.3 is to be installed
E: Unable to correct problems, you have held broken packages.

In my case I've resolved it with next command:

sudo aptitude install libldap2-dev

At first it suggested to do nothing, I've selected No, then it suggested to downgrade my current install to proper version. I've selected Yes. Then I was able to install libcurl4-openssl-dev as usual


问:
React Native: building a layout from data in an array
So I have a layout on screen which duplicates itself multiple times. I really want to clean it up.  Currently it's like this:

```<code>import { content } from '../content.js';

class Display extends Component {
  render() {
    return (
      <View style={styles.displayContainer}>
        <ScrollView>
          <View style={styles.row}>

            <View style={styles.displayItemBlock}>
              <TouchableOpacity style={styles.displayItem} onPress={this.item1}>
                <Image
                  style={styles.displayItemImage}
                  source={require('../images/display-item1.jpg')}
                />
                <View style={styles.displayItemText}>
                  <Text style={styles.displayItemTitle}>{content.display_title_item1}</Text>
                  <Text style={styles.recipeItemTime}>
                    <IconMCI name="clock" color="#4F8EF7" /> 2h 30m
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
            <View style={styles.displayItemBlock}>
              <TouchableOpacity style={styles.displayItem} onPress={this.item2}>
                <Image
                  style={styles.displayItemImage}
                  source={require('../images/display-item2.jpg')}
                />
                <View style={styles.displayItemText}>
                  <Text style={styles.displayItemTitle}>{content.display_title_item2}</Text>
                  <Text style={styles.recipeItemTime}>
                    <IconMCI name="clock" color="#4F8EF7" /> 45m
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
           {/* AND REPEAT... */}

          </View>
        </ScrollView>
      </View>
    );
  }
}
</code>```

So I thought I could easily replace most of this with a map which will take the information which changes and put that into an array.  So now I have this:

```<code>import { content } from '../content.js';

const dataArray = [
  { img: '../images/display-item1.jpg',
    title: 'content.display_title_item1',
    func: 'item1',
    time: '2h 30m' },
  { img: '../images/display-item2.jpg',
    title: 'content.display_title_item2',
    func: 'item2',
    time: '45m' },
];

class Display extends Component {

  ShowEverything() {
    return dataArray.map(function (data, i) {
      return (
        <View key={i} style={styles.displayItemBlock}>
          <TouchableOpacity style={styles.displayItem} onPress={this.{data.func}}>
            <Image
              style={styles.displayItemImage}
              source={require({data.img)}
            />
            <View style={styles.displayItemText}>
              <Text style={styles.displaytemTitle}>{data.title}</Text>
              <Text style={styles.displayItemTime}>
                <IconMCI name="clock" color="#4F8EF7" /> {data.time}
              </Text>
            </View>
          </TouchableOpacity>
        </View>
      );
    });
  }

  render() {
    return (
      <View style={styles.displayContainer}>
        <ScrollView>
          <View style={styles.row}>

            {this.ShowEverything()}

          </View>
        </Scroll>
      </View>
    );
  }
}
</code>```

What could be easier, right? :)

This, of course, doesn't work.  The time (data.time) is output correctly, but the title doesn't pull the correct text from content.js (it just outputs the string content.display_title_item from the array).  The img and func items also don't work as I would have expected.

Am I way off here?  It seems like this is the most obvious way of keeping this DRY; any help would be appreciated.

答:
Try this</p>

```<code>import { content } from '../content.js';

const dataArray = [
  { img: require('../images/display-item1.jpg'), //this is a known issue in react, dynamic paths needs to assigned like this
    title: 'display_title_item1',
    func: 'item1',
    time: '2h 30m' },
  { img: require('../images/display-item2.jpg'),
    title: 'display_title_item2',
    func: 'item2',
    time: '45m' },
];

class Display extends Component {

  ShowEverything() {
    return dataArray.map((data, i) => { // changed to fat arrow func to be in scope of this
      return (
        <View key={i} style={styles.displayItemBlock}>
          <TouchableOpacity style={styles.displayItem} onPress={this[data.func]}> // syntax error
            <Image
              style={styles.displayItemImage}
              source={data.img}
            />
            <View style={styles.displayItemText}>
              <Text style={styles.displaytemTitle}>content[data.title]</Text> // syntax error
              <Text style={styles.displayItemTime}>
                <IconMCI name="clock" color="#4F8EF7" /> {data.time}
              </Text>
            </View>
          </TouchableOpacity>
        </View>
      );
    });
  }
</code>```

Body:
So I have a layout on screen which duplicates itself multiple times. I really want to clean it up.  Currently it's like this:

import { content } from '../content.js';

class Display extends Component {
  render() {
    return (
      <View style={styles.displayContainer}>
        <ScrollView>
          <View style={styles.row}>

            <View style={styles.displayItemBlock}>
              <TouchableOpacity style={styles.displayItem} onPress={this.item1}>
                <Image
                  style={styles.displayItemImage}
                  source={require('../images/display-item1.jpg')}
                />
                <View style={styles.displayItemText}>
                  <Text style={styles.displayItemTitle}>{content.display_title_item1}</Text>
                  <Text style={styles.recipeItemTime}>
                    <IconMCI name="clock" color="#4F8EF7" /> 2h 30m
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
            <View style={styles.displayItemBlock}>
              <TouchableOpacity style={styles.displayItem} onPress={this.item2}>
                <Image
                  style={styles.displayItemImage}
                  source={require('../images/display-item2.jpg')}
                />
                <View style={styles.displayItemText}>
                  <Text style={styles.displayItemTitle}>{content.display_title_item2}</Text>
                  <Text style={styles.recipeItemTime}>
                    <IconMCI name="clock" color="#4F8EF7" /> 45m
                  </Text>
                </View>
              </TouchableOpacity>
            </View>
           {/* AND REPEAT... */}

          </View>
        </ScrollView>
      </View>
    );
  }
}

So I thought I could easily replace most of this with a map which will take the information which changes and put that into an array.  So now I have this:

import { content } from '../content.js';

const dataArray = [
  { img: '../images/display-item1.jpg',
    title: 'content.display_title_item1',
    func: 'item1',
    time: '2h 30m' },
  { img: '../images/display-item2.jpg',
    title: 'content.display_title_item2',
    func: 'item2',
    time: '45m' },
];

class Display extends Component {

  ShowEverything() {
    return dataArray.map(function (data, i) {
      return (
        <View key={i} style={styles.displayItemBlock}>
          <TouchableOpacity style={styles.displayItem} onPress={this.{data.func}}>
            <Image
              style={styles.displayItemImage}
              source={require({data.img)}
            />
            <View style={styles.displayItemText}>
              <Text style={styles.displaytemTitle}>{data.title}</Text>
              <Text style={styles.displayItemTime}>
                <IconMCI name="clock" color="#4F8EF7" /> {data.time}
              </Text>
            </View>
          </TouchableOpacity>
        </View>
      );
    });
  }

  render() {
    return (
      <View style={styles.displayContainer}>
        <ScrollView>
          <View style={styles.row}>

            {this.ShowEverything()}

          </View>
        </Scroll>
      </View>
    );
  }
}

What could be easier, right? :)

This, of course, doesn't work.  The time (data.time) is output correctly, but the title doesn't pull the correct text from content.js (it just outputs the string content.display_title_item from the array).  The img and func items also don't work as I would have expected.

Am I way off here?  It seems like this is the most obvious way of keeping this DRY; any help would be appreciated.

Body:
Try this

import { content } from '../content.js';

const dataArray = [
  { img: require('../images/display-item1.jpg'), //this is a known issue in react, dynamic paths needs to assigned like this
    title: 'display_title_item1',
    func: 'item1',
    time: '2h 30m' },
  { img: require('../images/display-item2.jpg'),
    title: 'display_title_item2',
    func: 'item2',
    time: '45m' },
];

class Display extends Component {

  ShowEverything() {
    return dataArray.map((data, i) => { // changed to fat arrow func to be in scope of this
      return (
        <View key={i} style={styles.displayItemBlock}>
          <TouchableOpacity style={styles.displayItem} onPress={this[data.func]}> // syntax error
            <Image
              style={styles.displayItemImage}
              source={data.img}
            />
            <View style={styles.displayItemText}>
              <Text style={styles.displaytemTitle}>content[data.title]</Text> // syntax error
              <Text style={styles.displayItemTime}>
                <IconMCI name="clock" color="#4F8EF7" /> {data.time}
              </Text>
            </View>
          </TouchableOpacity>
        </View>
      );
    });
  }


问:
Python MySQL: error inserting data
Here is my code

```<code>qry = " INSERT INTO transactions(transaction_id,listing_id) VALUES ('%s','%s')"
cursor.execute(qry, ('123', '456',))
db_con.commit()
</code>```

I am getting error:

```<code>(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '123'',''456'')' at line 1")
</code>```

答:
Remove the  double-quoted quotes from the query:

```<code>qry = " INSERT INTO transactions(transaction_id,listing_id) VALUES (%s,%s)"
</code>```

Title: Python MySQL: error inserting data

Body:
Here is my code

qry = " INSERT INTO transactions(transaction_id,listing_id) VALUES ('%s','%s')"
cursor.execute(qry, ('123', '456',))
db_con.commit()

I am getting error:

(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '123'',''456'')' at line 1")

Body:
Remove the  double-quoted quotes from the query:

qry = " INSERT INTO transactions(transaction_id,listing_id) VALUES (%s,%s)"


问:
getopt_long()/getopt() with duplicated option input
I just got to know both functions. Have been searching internet to learn their usage. Found one thing which is very important to parse the command line option input, but not discussed.

Is such a case, if duplicated options are typed in, both functions can not do anything to handle it. I was wondering if there is any lib function to use for this.

If I have to handle it myself. The way in my mind is to collection short option into an array and find identical ones in the array.

Any better way to do it?

答:
If you want to do something special with duplicate options, you can manage state in the option handling code.

Something like -v|--verbose can be repeated for additional verboseness, and the vebosity handling code is

```<code>// initialize
int verbose_level=0

// in the getopt case for -v
  verbose_level++;
</code>```

(for options that can be repeated with arguments which should all be used, load up a list or some such).

If you don't want repeats to do anything special just set the value every time

```<code>  // in the case
  verbose_level = 1;
</code>```

and if you want to detect repeats

```<code>  // in the case
  if (verbose_level) {
   // handle this case as an error...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you want to do something special with duplicate options, you can manage state in the option handling code.

Something like -v|--verbose can be repeated for additional verboseness, and the vebosity handling code is

// initialize
int verbose_level=0

// in the getopt case for -v
  verbose_level++;

(for options that can be repeated with arguments which should all be used, load up a list or some such).

If you don't want repeats to do anything special just set the value every time

  // in the case
  verbose_level = 1;

and if you want to detect repeats

  // in the case
  if (verbose_level) {
   // handle this case as an error...
}


问:
SQL-Statement provides unexpected result
I've the following table (mTable)

```<code>id  | sent                  | number
---------------------------------------
23  | 2017-03-02 00:00:00   | 0
23  | 2017-03-04 00:00:00   | 0
45  | 2017-03-15 00:00:00   | 1.8
45  | 2017-03-17 00:00:00   | 1.9

id: integer, not unique, no primary key
sent: timestamp
number: float
</code>```

The SQL-Statement:

```<code>SELECT DISTINCT `id`, number as mynum, MAX(`sent`) AS sentOn FROM `mTable` GROUP BY `id`
</code>```

The result is:

```<code>id  | mynum  |  sentOn
------------------------------------
23  | 0      | 2017-03-04 00:00:00
45  | 1.8    | 2017-03-17 00:00:00
</code>```

The expected result would be:

```<code>id  | mynum  |  sentOn
------------------------------------
23  | 0      | 2017-03-04 00:00:00
45  | 1.9    | 2017-03-17 00:00:00
</code>```

In the second row I would expect to be the mynum(1.9) with the latest sent date(2017-03-17 00:00:00).
Instead the SQL-Query provides the mynum(1.8) from the second latest send date(2017-03-15 00:00:00).

Any hints, to solve the problem?
Thank's

答:
You are using Group By Clause Which is wrong . Use Aggregation function in your select  then use Group By.. Such as Below :

```<code>SELECT id, MAX(number) as mynum, MAX(sent) AS sentOn
FROM mTable
GROUP BY id
</code>```

This link help to about Group By Clause.

Helping Link For Group By

Body:
I've the following table (mTable)

id  | sent                  | number
---------------------------------------
23  | 2017-03-02 00:00:00   | 0
23  | 2017-03-04 00:00:00   | 0
45  | 2017-03-15 00:00:00   | 1.8
45  | 2017-03-17 00:00:00   | 1.9

id: integer, not unique, no primary key
sent: timestamp
number: float

The SQL-Statement:

SELECT DISTINCT `id`, number as mynum, MAX(`sent`) AS sentOn FROM `mTable` GROUP BY `id`

The result is:

id  | mynum  |  sentOn
------------------------------------
23  | 0      | 2017-03-04 00:00:00
45  | 1.8    | 2017-03-17 00:00:00

The expected result would be:

id  | mynum  |  sentOn
------------------------------------
23  | 0      | 2017-03-04 00:00:00
45  | 1.9    | 2017-03-17 00:00:00

In the second row I would expect to be the mynum(1.9) with the latest sent date(2017-03-17 00:00:00).
Instead the SQL-Query provides the mynum(1.8) from the second latest send date(2017-03-15 00:00:00).

Any hints, to solve the problem?
Thank's

Body:
You are using Group By Clause Which is wrong . Use Aggregation function in your select  then use Group By.. Such as Below :

SELECT id, MAX(number) as mynum, MAX(sent) AS sentOn
FROM mTable
GROUP BY id

This link help to about Group By Clause.

Helping Link For Group By


问:
ASP.Net MVC 5 Html.BeginForm onsubmit and model with required attribute
I have required attribute on my model properties but I added a "spinner" to show processing request in form onsubmit. Now, even though that it didn't submit the form, it shows the "spinner" i created, and stuck on the overlay but the textbox with required attribute is in focus.

```<code>using (Html.BeginForm("Add", "UserAccount", FormMethod.Post, new { onsubmit="spinner()"}))
{
//Html.TextBoxes for model properties with required
}
<div id="spinner" hidden="">
    <div>
        <i class="fa fa-spinner fa-spin fa-pulse" style="color: white; font-    size: 50px;"></i>
        <label style="color: white; font-size: 50px;">Processing</label>
    </div>
</div>

<script>
function spinner() {
    $("#spinner").show();
}
</script>
</code>```

Is their a way to check first if the "required" attribute is satisfied before accessing the onsubmit function?

答:
I think you need client side validation before form has been submitted you have added required attribute on properties that is fine now make a client side validation work you need to add some js which is handle all validations client side

```<code>bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate*"));
</code>```

Below is list of js you need

```<code><script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
</code>```

You need jquery.validate.unobstrusive.js to make client validation work

Second you need to change in web config as well

```<code> <appSettings>
        ...
  <add key="ClientValidationEnabled" value="true"/>
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

        ...
 </appSettings>
</code>```

Fore more infomration find what is unobtrusive-validation on this blog.

Using this your form is not submitted before all fields are validated properly like Required,Range etc which you have mentioned on properties

After adding this bunch of code you can validate form in on button click as well as below

```<code>$("#btn1").click(function (e) {

   e.preventDefault();

   // now trigger the form validation, result is 1 or 0
   var result = $('form').valid();
   if(!result)
   {
     // Do some stuff if form is not valid
   }
});
</code>```

Body:
I have required attribute on my model properties but I added a "spinner" to show processing request in form onsubmit. Now, even though that it didn't submit the form, it shows the "spinner" i created, and stuck on the overlay but the textbox with required attribute is in focus.

using (Html.BeginForm("Add", "UserAccount", FormMethod.Post, new { onsubmit="spinner()"}))
{
//Html.TextBoxes for model properties with required
}

        Processing

Is their a way to check first if the "required" attribute is satisfied before accessing the onsubmit function?

Body:
I think you need client side validation before form has been submitted you have added required attribute on properties that is fine now make a client side validation work you need to add some js which is handle all validations client side

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate*"));

Below is list of js you need

<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

You need jquery.validate.unobstrusive.js to make client validation work

Second you need to change in web config as well

 <appSettings>
        ...
  <add key="ClientValidationEnabled" value="true"/>
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

        ...
 </appSettings>

Fore more infomration find what is unobtrusive-validation on this blog.

Using this your form is not submitted before all fields are validated properly like Required,Range etc which you have mentioned on properties

After adding this bunch of code you can validate form in on button click as well as below

$("#btn1").click(function (e) {

   e.preventDefault();

   // now trigger the form validation, result is 1 or 0
   var result = $('form').valid();
   if(!result)
   {
     // Do some stuff if form is not valid
   }
});


问:
Connection string issue in VB.NET?
I have the following connection string class

```<code>Imports System.Data.SqlClient

Public Class DBConnection
    Sub GetConnection()
        Dim CrmsConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("crmsConnectionString").ConnectionString)

    End Sub

End Class
</code>```

And I have tried to call the connection string from the above class as follows:

```<code> Dim dbcon As DBConnection
Dim con As New SqlConnection(dbcon.GetConnection())
</code>```

But it has an error near dbcon.GetConnection().
What is the solution?

答:
GetConnection is a sub. This means that it doesn't return anything and you cannot try to use an inexistant return value. (This is a compile time error, you can't produce any executable code until you fix it)

Make it a function and public

```<code>Public Function GetConnection() as SqlConnection
    return New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("crmsConnectionString").ConnectionString)
End Function
</code>```

and then use it as (but create the class instance first otherwise a null reference exception occurs at runtime)

```<code>' Create the instance of the DBConnection class and ...
Dim dbcon As DBConnection = new DBConnection()

' ... get the connection
Dim con as SqlConnection = dbcon.GetConnection()
</code>```

Finally remember to use the Using statement around disposable objects like this

```<code>Using con = dbCon.GetConnection()
    ....
End Using
</code>```

Title: Connection string issue in VB.NET?

Body:
I have the following connection string class

Imports System.Data.SqlClient

Public Class DBConnection
    Sub GetConnection()
        Dim CrmsConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("crmsConnectionString").ConnectionString)

    End Sub

End Class

And I have tried to call the connection string from the above class as follows:

 Dim dbcon As DBConnection
Dim con As New SqlConnection(dbcon.GetConnection())

But it has an error near dbcon.GetConnection().
What is the solution?

Body:
GetConnection is a sub. This means that it doesn't return anything and you cannot try to use an inexistant return value. (This is a compile time error, you can't produce any executable code until you fix it)

Make it a function and public

Public Function GetConnection() as SqlConnection
    return New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("crmsConnectionString").ConnectionString)
End Function

and then use it as (but create the class instance first otherwise a null reference exception occurs at runtime)

' Create the instance of the DBConnection class and ...
Dim dbcon As DBConnection = new DBConnection()

' ... get the connection
Dim con as SqlConnection = dbcon.GetConnection()

Finally remember to use the Using statement around disposable objects like this

Using con = dbCon.GetConnection()
    ....
End Using


问:
IF Statement multiple conditions, same statement
Hey all, looking to reduce the code on my c# if statements as there are several repeating factors and was wondering if a trimmer solution is possible.

I currently have 2 if statements that need to carry out an identical statement, however the only variable is an extra condition on an if statement when a checkbox is not checked. Im just wondering if there is a way to make it one statement or make the condition string variable, heres the compressed version of the code:

```<code>if (checkbox.checked)
  {
    if (columnname != a && columnname != b && columnname != c)
    {
      "statement 1"
    }
  }
else
  {
    if (columnname != a && columnname != b && columnname != c
        && columnname != A2)
    {
      "statement 1"
    }
  }
</code>```

Its like I need to run an if statement within the conditions of an if statement if that makes sense, like this psuedo form:

```<code>if (columnname != a
    && columnname != b
    && columnname != c
    && if(checkbox.checked{columnname != A2})
</code>```

答:
Check this for a more clustered way of checking conditions:

```<code>private bool IsColumn(string col, params string[] names) => names.Any(n => n == col);
</code>```

usage:

```<code>private void CheckColumn()
{
     if(!IsColumn(ColName, "Column A", "Column B", "Column C"))
    {
     //not A B C column
    }

}
</code>```

Body:
Hey all, looking to reduce the code on my c# if statements as there are several repeating factors and was wondering if a trimmer solution is possible.

I currently have 2 if statements that need to carry out an identical statement, however the only variable is an extra condition on an if statement when a checkbox is not checked. Im just wondering if there is a way to make it one statement or make the condition string variable, heres the compressed version of the code:

if (checkbox.checked)
  {
    if (columnname != a && columnname != b && columnname != c)
    {
      "statement 1"
    }
  }
else
  {
    if (columnname != a && columnname != b && columnname != c
        && columnname != A2)
    {
      "statement 1"
    }
  }

Its like I need to run an if statement within the conditions of an if statement if that makes sense, like this psuedo form:

if (columnname != a
    && columnname != b
    && columnname != c
    && if(checkbox.checked{columnname != A2})

Body:
Check this for a more clustered way of checking conditions:

private bool IsColumn(string col, params string[] names) => names.Any(n => n == col);

usage:

private void CheckColumn()
{
     if(!IsColumn(ColName, "Column A", "Column B", "Column C"))
    {
     //not A B C column
    }

}


问:
What is the typical speed that PHP connects to MySQL?
Say I have very standard mysql connection code:

```<code>$dbhost = '192.168.1.99';
$dbuser = 'dbuser';
$dbpass = 'dbuserpass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'mydb';
mysql_select_db($dbname);
</code>```

This would connect from the web server to the database server (say the web server is at 192.168.1.98 or something). Typically, how long would the above code run? Currently, I'm seeing about 2 seconds. Is that slow?

答: That is very slow. On avarage websites, the entire page renders within two seconds. That is, connecting to the database, running the queries, retrieving results and rendering the page.

Body:
Say I have very standard mysql connection code:

$dbhost = '192.168.1.99';
$dbuser = 'dbuser';
$dbpass = 'dbuserpass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'mydb';
mysql_select_db($dbname);

This would connect from the web server to the database server (say the web server is at 192.168.1.98 or something). Typically, how long would the above code run? Currently, I'm seeing about 2 seconds. Is that slow?


问:
Mockito Android Unit testing
I have MVP in my application. Presenter has interface

```<code>public interface ILoginPresenter<V> extends Presenter<V> {
    void logUserIn(String email, String password, String deviceToken, String deviceType);
}
</code>```

Realization has RX Single

```<code> mLoginSubscription = mModel.logUserIn(email, password, deviceToken, deviceType)
            .compose(RxUtil.setupNetworkSingle())
            .subscribe(new Subscriber<User>() {
                @Override
                public void onCompleted() {
                    Timber.i("Log in complete");
                }

                @Override
                public void onError(Throwable e) {
                    Timber.e(e, "Retrofit could not get User.");

                    getView().dismissProgressDialog();
                }

                @Override
                public void onNext(UserResponseRetrofit response) {
                    Timber.i("Retrofit is attempting to get User");
                    mSaveModel.saveUser(user);
                    getView().dismissProgressDialog();
                    getView().goToMenuActivity();
                }
            });
</code>```

Also i have module for Dagger

```<code>@Module
public class ModelModule {
    @Provides
    @ScreenScope
    public ILoginModel provideLoginModel(LoginModel p) {
        return p;
    }
}
</code>```

My unit test look like next:

```<code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml")
public class LoginPresenterTest {

    public static final String SOME_OTHER_TOKEN = "someOtherToken";
    private AppComponent mAppComponent;
    private LoginComponent mLoginComponent;
    private ILoginView mockView;
    private ModelModule mockModel;
    private ILoginPresenter mLoginPresenter;

    @Before
    public void setup() {
        // Creating the mocks
        mockView = Mockito.mock(ILoginView.class);
        mockModel = Mockito.mock(ModelModule.class);

        ILoginModel mock = Mockito.mock(ILoginModel.class);
        User urr = Mockito.mock(User.class);
        Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
        Mockito.when(mock.logUserIn("", "", "", "")).thenReturn(ScalarSynchronousSingle.just(urr));

        mAppComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(RuntimeEnvironment.application))
                .build();

        mLoginComponent = DaggerLoginComponent.builder()
                .appComponent(mAppComponent)
                .modelModule(mockModel)
                .presenterModule(new PresenterModule())
                .build();

        mLoginPresenter = mLoginComponent.provideLoginPresenter();
        mLoginPresenter.setView(mockView);
    }

    @Test
    public void testLogin() {
        mLoginPresenter.logUserIn("", "", "", "");
        try {
            java.lang.Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Mockito.verify(mockView).dismissProgressDialog();
    }
</code>```

So using Dagger I need to build Presenter correctly. For this purposes, I am trying to use Mockito.when. Firstly look like this line doesn't work

```<code>Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
</code>```

The target purpose is to use my own Model realization which return Single.

don't really understand why my mock of ModelModule doesn't work?

答:
What about creating a test module out of your production Module?

See how they suggest to do testing via Dagger in official site.

```<code>@Module
public class ModelModuleTest extends ModelModule {

    @Override
    public ILoginModel provideLoginModel(LoginModel p) {
        ...
    }
}
</code>```

You can pass mocked dependency to your Module.

Title: Mockito Android Unit testing

Body:
I have MVP in my application. Presenter has interface

public interface ILoginPresenter<V> extends Presenter<V> {
    void logUserIn(String email, String password, String deviceToken, String deviceType);
}

Realization has RX Single

 mLoginSubscription = mModel.logUserIn(email, password, deviceToken, deviceType)
            .compose(RxUtil.setupNetworkSingle())
            .subscribe(new Subscriber<User>() {
                @Override
                public void onCompleted() {
                    Timber.i("Log in complete");
                }

                @Override
                public void onError(Throwable e) {
                    Timber.e(e, "Retrofit could not get User.");

                    getView().dismissProgressDialog();
                }

                @Override
                public void onNext(UserResponseRetrofit response) {
                    Timber.i("Retrofit is attempting to get User");
                    mSaveModel.saveUser(user);
                    getView().dismissProgressDialog();
                    getView().goToMenuActivity();
                }
            });

Also i have module for Dagger

@Module
public class ModelModule {
    @Provides
    @ScreenScope
    public ILoginModel provideLoginModel(LoginModel p) {
        return p;
    }
}

My unit test look like next:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml")
public class LoginPresenterTest {

    public static final String SOME_OTHER_TOKEN = "someOtherToken";
    private AppComponent mAppComponent;
    private LoginComponent mLoginComponent;
    private ILoginView mockView;
    private ModelModule mockModel;
    private ILoginPresenter mLoginPresenter;

    @Before
    public void setup() {
        // Creating the mocks
        mockView = Mockito.mock(ILoginView.class);
        mockModel = Mockito.mock(ModelModule.class);

        ILoginModel mock = Mockito.mock(ILoginModel.class);
        User urr = Mockito.mock(User.class);
        Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
        Mockito.when(mock.logUserIn("", "", "", "")).thenReturn(ScalarSynchronousSingle.just(urr));

        mAppComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(RuntimeEnvironment.application))
                .build();

        mLoginComponent = DaggerLoginComponent.builder()
                .appComponent(mAppComponent)
                .modelModule(mockModel)
                .presenterModule(new PresenterModule())
                .build();

        mLoginPresenter = mLoginComponent.provideLoginPresenter();
        mLoginPresenter.setView(mockView);
    }

    @Test
    public void testLogin() {
        mLoginPresenter.logUserIn("", "", "", "");
        try {
            java.lang.Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Mockito.verify(mockView).dismissProgressDialog();
    }

So using Dagger I need to build Presenter correctly. For this purposes, I am trying to use Mockito.when. Firstly look like this line doesn't work

Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);

The target purpose is to use my own Model realization which return Single.

don't really understand why my mock of ModelModule doesn't work?

Body:
What about creating a test module out of your production Module?

See how they suggest to do testing via Dagger in official site.

@Module
public class ModelModuleTest extends ModelModule {

    @Override
    public ILoginModel provideLoginModel(LoginModel p) {
        ...
    }
}

You can pass mocked dependency to your Module.


问:
Why occur Internal server error in my ajax query?
I want to pass some value to server and it has to return one string.

Jquery version

```<code> <script src="js/jquery-3.1.1.js"></script>
</code>```

Here is my code:

```<code> $('#btnSaveFile').click(function () {
    var fileName = $('#txtFileName').val();
    alert(fileName);
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'GET',      //method or type ?
        contentType: 'application/json',
        data: '{fileName:' + fileName +'}',  //UPDATED Line
        dataType: 'json',
        success: function (data) {
            alert('success');
            alert(data.d.exist);
        },
        error: function (error) {
            alert('fail');
            alert(error);
        }
    });
});
</code>```

Aspx code

```<code>    [WebMethod]
    public static string getFileExistOrNot(string fileName)
    {
        string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=@UserFileName  and ReportName=@ReportName";
            cmd.Parameters.AddWithValue("@UserFileName", fileName);
            cmd.Parameters.AddWithValue("@ReportName", "TotalSales");
            con.Open();
            var data = cmd.ExecuteScalar();
            if (data != null)
            {
                string exist = "dataExist";
                return exist;
            }
            else
            {
                string exist = "notExist";
                return exist;
            }
        }
    }
</code>```

Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)

ExceptionType:"System.InvalidOperationException"

Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."

StackTrace:"   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".

I think this error it occurs in server side. But I don't know what is that

Updated

Error Message:"Invalid web service call, missing value for parameter:'fileName'."

答:
Send your data like below:

In object format

```<code>data: { fileName:fileName },
</code>```

OR

As a String

```<code>data = "fileName="+filename;
</code>```

Body:
I want to pass some value to server and it has to return one string.

Jquery version

Here is my code:

 $('#btnSaveFile').click(function () {
    var fileName = $('#txtFileName').val();
    alert(fileName);
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'GET',      //method or type ?
        contentType: 'application/json',
        data: '{fileName:' + fileName +'}',  //UPDATED Line
        dataType: 'json',
        success: function (data) {
            alert('success');
            alert(data.d.exist);
        },
        error: function (error) {
            alert('fail');
            alert(error);
        }
    });
});

Aspx code

    [WebMethod]
    public static string getFileExistOrNot(string fileName)
    {
        string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=@UserFileName  and ReportName=@ReportName";
            cmd.Parameters.AddWithValue("@UserFileName", fileName);
            cmd.Parameters.AddWithValue("@ReportName", "TotalSales");
            con.Open();
            var data = cmd.ExecuteScalar();
            if (data != null)
            {
                string exist = "dataExist";
                return exist;
            }
            else
            {
                string exist = "notExist";
                return exist;
            }
        }
    }

Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)

ExceptionType:"System.InvalidOperationException"

Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."

StackTrace:"   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".

I think this error it occurs in server side. But I don't know what is that

Updated

Error Message:"Invalid web service call, missing value for parameter:'fileName'."

Body:
Send your data like below:

In object format

data: { fileName:fileName },

OR

As a String

data = "fileName="+filename;


问:
Matlab : If 'A' is an indexed variable, performance can be improved using logical indexing instead of FIND
In the title there is the recommendation by MATLAB to optimize my code, but I don't understand how can I optimize this </p>

```<code>X2 = X(~points_in_Cluster,:); %points non vue
A = (1:length(points_in_Cluster))'.*~points_in_Cluster;
Neighbors2 = find(pdist2(X(j,:),X2) <= epsilon);
A = A(A~=0);
Neighbors2 = A(Neighbors2)';
Neighbors = ([Neighbors Neighbors2]);
</code>```

答:
find is unnecessary in your case because you can use an array of logical values directly to index into an array. There is an extensive article on this in MATLAB's own online documentation

As a brief example:

```<code>data = [1, 2, 3];
mask = [true, false, true];

% Using find (slow because it's an extra step)
data(find(mask))
%   1   3

% Using the logical array directly
data(mask)
%   1   3
</code>```

So for your code, it would look something like:

```<code>Neighbors2 = pdist2(X(j,:),X2) <= epsilon;
A = A(A~=0);
Neighbors2 = A(Neighbors2).';
Neighbors = ([Neighbors Neighbors2]);
</code>```

As a side-note, you'll want to use .' if you want the transpose rather than '

Body:
In the title there is the recommendation by MATLAB to optimize my code, but I don't understand how can I optimize this

X2 = X(~points_in_Cluster,:); %points non vue
A = (1:length(points_in_Cluster))'.*~points_in_Cluster;
Neighbors2 = find(pdist2(X(j,:),X2) <= epsilon);
A = A(A~=0);
Neighbors2 = A(Neighbors2)';
Neighbors = ([Neighbors Neighbors2]);

Body:
find is unnecessary in your case because you can use an array of logical values directly to index into an array. There is an extensive article on this in MATLAB's own online documentation

As a brief example:

data = [1, 2, 3];
mask = [true, false, true];

% Using find (slow because it's an extra step)
data(find(mask))
%   1   3

% Using the logical array directly
data(mask)
%   1   3

So for your code, it would look something like:

Neighbors2 = pdist2(X(j,:),X2) <= epsilon;
A = A(A~=0);
Neighbors2 = A(Neighbors2).';
Neighbors = ([Neighbors Neighbors2]);

As a side-note, you'll want to use .' if you want the transpose rather than '


问:
C++ A constructor triggers a destructor
I'm trying to make a Monster generator using vectors and classes to allow the user to create and delete Monster objects as they wish. However, when I call the constructor of Monster in my code it also immediately triggers a destructor, thereby removing Monster from the the vector container.

This is the fragment of my code, which creates and destroys the Monster object:

```<code>while (p == 't')
{
    cout << "Generate (g) or remove (u) a monster?" << endl;
    cin >> p;
    while (p == 'u' && Monster::n == 0)
    {
        cout << "No monsters to remove." << endl;
        cout << "Generate (g) or remove (u) a monster?" << endl;
        cin >> p;
    }
    while (p != 'g' && p != 'u')
    {
        cout << "Error. Follow the instructions." << endl;
        cout << "Generate (g) or remove (u) a monster?" << endl;
        cin >> p;
    }
    if (p == 'g')
    {
        {
            vec.push_back(Monster());
            vec[Monster::n].print();
        }
    }
    if (p == 'u')
    {
        vec.~Monster();
    }
    cout << "Continue (t) or finish (n)?" << endl;
    cin >> p;
    while (p != 't' && p != 'n')
    {
        cout << "Error. Follow the instructions?" << endl;
        cout << "Continue (t) or finish (n)?" << endl;
        cin >> p;
    }
</code>```

This is the constructor for Monster:

```<code>Monster::Monster()
{
    ostringstream buffer;
    buffer << Monster::n;
    string name = buffer.str();
    Monster::setname(name);
    Monster::settype(MonsterType(rand() % 7 + 1));
    Monster::setattack(rand() % 25);
    Monster::sethealth(rand() % 15);
    cout << endl << "Monster generated." << endl << endl;
    Monster::n++;
}
</code>```

This is the destructor:

```<code>Monster::~Monster()
{
    cout << "Monster removed." << endl << endl;
    Monster::n--;
}
</code>```

When I input the character 'g', it creates a Monster object as expected but then immediately destroys it, even before its stats are printed with the print() method. This means my code is not acting as expected, as it will never allow the proper creation or destruction of Monster objects.

Can someone please help me understand what's going on here?

EDIT:

Alright, I was able to somewhat solve the issue by making another constructor.

This is it:

```<code>Monster::Monster(const Monster & mon)
{
    Monster::name = mon.name;
    Monster::type = mon.type;
    Monster::attack = mon.attack;
    Monster::health = mon.health;
    cout << endl << "Monster created (cpy)." << endl << endl;
    Monster::n++;
}
</code>```

I edited the point where the user decides to generate a Monster to the following:

```<code>    {
        vec.push_back(Monster());
        vector<Monster> veccpy = {};
        veccpy.push_back(Monster(vec[Monster::n-1]));
        vec.back().print();
    }
</code>```

When I lauch the program, it spits out something like this:

Monster created

Monster created (cpy)

Monster removed

Monster created (cpy)

Monster created (cpy)

Monster removed

Monster's stats

Now, the odd thing is even though it uses those constructors so oddly, the program works as I intended it to. n iterates as it should, I can remove or add Monster as I intended and the Monster stats are displayed as they should.

Could someone point to what I'm doing wrong here?

答:
What you are seeing is expected and it's happening because you have defied the vec as std::vector<Monster>. What does it means that you are declaring the vector that would contains the objects of Monster class.

Now the way vector works is that they need to keep all those Monster class objects alive unless you remove them from the vector. Which means, the scope of those Monstors object should be equivalent till the Object remains the vector.

Having said that, now if you look at this line of code vec.push_back(Monster());, the new Monster object hat you are declaring will have the scope till the scope of braces with in the if, and as soon it it will be out of scope, it will not be accessible. Which is why, when the push_back gets executed, it copies the given Monster object (by executing its default copy constructor, or custom one if any), and create a new object for the vector.

If you don't want to the object to be copied, what you do is as follow:

Declare vector as std::vector<std::unique_ptr<Monster>> and
call push_back as .push_back(make_unique<Monster>()).

Here instead of declaring the Monster on the local stack, you are declaring it on the Heap and using the smart pointer to manage the life of the object on the heap.

Title: C++ A constructor triggers a destructor

Body:
I'm trying to make a Monster generator using vectors and classes to allow the user to create and delete Monster objects as they wish. However, when I call the constructor of Monster in my code it also immediately triggers a destructor, thereby removing Monster from the the vector container.

This is the fragment of my code, which creates and destroys the Monster object:

while (p == 't')
{
    cout << "Generate (g) or remove (u) a monster?" << endl;
    cin >> p;
    while (p == 'u' && Monster::n == 0)
    {
        cout << "No monsters to remove." << endl;
        cout << "Generate (g) or remove (u) a monster?" << endl;
        cin >> p;
    }
    while (p != 'g' && p != 'u')
    {
        cout << "Error. Follow the instructions." << endl;
        cout << "Generate (g) or remove (u) a monster?" << endl;
        cin >> p;
    }
    if (p == 'g')
    {
        {
            vec.push_back(Monster());
            vec[Monster::n].print();
        }
    }
    if (p == 'u')
    {
        vec.~Monster();
    }
    cout << "Continue (t) or finish (n)?" << endl;
    cin >> p;
    while (p != 't' && p != 'n')
    {
        cout << "Error. Follow the instructions?" << endl;
        cout << "Continue (t) or finish (n)?" << endl;
        cin >> p;
    }

This is the constructor for Monster:

Monster::Monster()
{
    ostringstream buffer;
    buffer << Monster::n;
    string name = buffer.str();
    Monster::setname(name);
    Monster::settype(MonsterType(rand() % 7 + 1));
    Monster::setattack(rand() % 25);
    Monster::sethealth(rand() % 15);
    cout << endl << "Monster generated." << endl << endl;
    Monster::n++;
}

This is the destructor:

Monster::~Monster()
{
    cout << "Monster removed." << endl << endl;
    Monster::n--;
}

When I input the character 'g', it creates a Monster object as expected but then immediately destroys it, even before its stats are printed with the print() method. This means my code is not acting as expected, as it will never allow the proper creation or destruction of Monster objects.

Can someone please help me understand what's going on here?

EDIT:

Alright, I was able to somewhat solve the issue by making another constructor.

This is it:

Monster::Monster(const Monster & mon)
{
    Monster::name = mon.name;
    Monster::type = mon.type;
    Monster::attack = mon.attack;
    Monster::health = mon.health;
    cout << endl << "Monster created (cpy)." << endl << endl;
    Monster::n++;
}

I edited the point where the user decides to generate a Monster to the following:

    {
        vec.push_back(Monster());
        vector<Monster> veccpy = {};
        veccpy.push_back(Monster(vec[Monster::n-1]));
        vec.back().print();
    }

When I lauch the program, it spits out something like this:

Monster created

Monster created (cpy)

Monster removed

Monster created (cpy)

Monster created (cpy)

Monster removed

Monster's stats

Now, the odd thing is even though it uses those constructors so oddly, the program works as I intended it to. n iterates as it should, I can remove or add Monster as I intended and the Monster stats are displayed as they should.

Could someone point to what I'm doing wrong here?


问:
VB.NET / VB - Passing a variable into Startinfo.Arguments
I'm trying to use a string variable in StartInfo.Arguments of a process, but can't figure out the correct syntax.</p>

```<code> Dim pquery As New Process
    Dim User As String = "test"
    pquery.StartInfo.UseShellExecute = False
    pquery.StartInfo.CreateNoWindow = True
    pquery.StartInfo.FileName = "cmd"
    pquery.StartInfo.Arguments = "/c dsquery.exe * -filter ""(&(objectClass=user)(!(objectClass=computer)(mail=***string variable should go here***)))"" | dsget user -samid"
    pquery.StartInfo.RedirectStandardOutput = True
    pquery.StartInfo.RedirectStandardError = True
    pquery.Start()
</code>```

答:
You can use String.Format():

Change your assignment to pquery.StartInfo.Arguments like so:

```<code>pquery.StartInfo.Arguments = String.Format("/c dsquery.exe * -filter ""(&(objectClass=user)(!(objectClass=computer)(mail={0})))"" | dsget user -samid", User)
</code>```

Body:
I'm trying to use a string variable in StartInfo.Arguments of a process, but can't figure out the correct syntax.

 Dim pquery As New Process
    Dim User As String = "test"
    pquery.StartInfo.UseShellExecute = False
    pquery.StartInfo.CreateNoWindow = True
    pquery.StartInfo.FileName = "cmd"
    pquery.StartInfo.Arguments = "/c dsquery.exe * -filter ""(&(objectClass=user)(!(objectClass=computer)(mail=***string variable should go here***)))"" | dsget user -samid"
    pquery.StartInfo.RedirectStandardOutput = True
    pquery.StartInfo.RedirectStandardError = True
    pquery.Start()

Body:
You can use String.Format():

Change your assignment to pquery.StartInfo.Arguments like so:

pquery.StartInfo.Arguments = String.Format("/c dsquery.exe * -filter ""(&(objectClass=user)(!(objectClass=computer)(mail={0})))"" | dsget user -samid", User)


问:
Most efficient way to check if object value exists in PHP 7
I have the following object in PHP 7:

```<code>(int) 0 => object() {
   'master' => null
},
(int) 1 => object() {
   'master' => true
},
(int) 2 => object() {
   'master' => null
},
</code>```

What is the most efficient way to check whether master is true in any key of that object?

I could loop through the object and then set a variable, e.g.

```<code>$master = 0;
foreach ($obj as $key => $value) {
    if ($value->master) {
       $master++;
    }
}
if ($master !== 0) {

}
</code>```

But this seems inefficient.

The object itself has other data in each node, this is a simplified example.

What I'm trying to write, in as few lines as possible is, does any part of this object have master == true? Or, looking at it the other way round, are all my master nodes set to null on this object? A return of true or false would probably suffice as the output, although a count would also be ok.

答:
```<code>if ($value->master && $value->master !== null) {
       $master++;
}
</code>```

Have a look to this table :
http://php.net/manual/en/types.comparisons.php

Body:
I have the following object in PHP 7:

(int) 0 => object() {
   'master' => null
},
(int) 1 => object() {
   'master' => true
},
(int) 2 => object() {
   'master' => null
},

What is the most efficient way to check whether master is true in any key of that object?

I could loop through the object and then set a variable, e.g.

$master = 0;
foreach ($obj as $key => $value) {
    if ($value->master) {
       $master++;
    }
}
if ($master !== 0) {

}

But this seems inefficient.

The object itself has other data in each node, this is a simplified example.

What I'm trying to write, in as few lines as possible is, does any part of this object have master == true? Or, looking at it the other way round, are all my master nodes set to null on this object? A return of true or false would probably suffice as the output, although a count would also be ok.

Body:
if ($value->master && $value->master !== null) {
       $master++;
}

Have a look to this table :
http://php.net/manual/en/types.comparisons.php


问:
find the text and return its value, return 0 if the text is not found
I need your help. Cannot figure out why the piece of code below doesn't work. I have a PivotTable where I look for a specific value with a function FIND and VLOOKUP and add it to a specific cell:

After the data update - there is no information about States duration of 10 - 19 days anymore. In this case when some category values are absent - I want to assign the 0 value to a specific cells.
I tried to achive it writing the following:

```<code>Dim x As Long
Dim Lookup_Range, RangeA As range

With Worksheets("Duration")

Set Lookup_Range = Worksheets("Duration").range("A1:B56")

On Error Resume Next
x = Lookup_Range.Find("1 - 9 days", range("A1"), xlValues, xlWhole, xlByColumns, xlNext).Row

Set RangeA = .range(.Cells(x, 1), .Cells(x + 4, 2))

If Not x <> "" Then

   .Cells(30, 7) = Application.VLookup("State1", RangeA, 2, False)
   .Cells(31, 7) = Application.VLookup("State2", RangeA, 2, False)
   .Cells(32, 7) = Application.VLookup("State3", RangeA, 2, False)
   .Cells(33, 7) = Application.VLookup("State4", RangeA, 2, False)

Else

   .Cells(30, 7) = 0
   .Cells(31, 7) = 0
   .Cells(32, 7) = 0
   .Cells(33, 7) = 0

End If

On Error Resume Next
x = Lookup_Range.Find("10 - 19 days", range("A1"), xlValues, xlWhole, xlByColumns, xlNext).Row

Set RangeA = .range(.Cells(x, 1), .Cells(x + 4, 2))

If Not x <> "" Then

   .Cells(34, 7) = Application.VLookup("State1", RangeA, 2, False)
   .Cells(35, 7) = Application.VLookup("State2", RangeA, 2, False)
   .Cells(36, 7) = Application.VLookup("State3", RangeA, 2, False)
   .Cells(37, 7) = Application.VLookup("State4", RangeA, 2, False)

Else

.Cells(34, 7) = 0
.Cells(35, 7) = 0
.Cells(36, 7) = 0
.Cells(37, 7) = 0

End If

End With
</code>```

It only returns the right values when the first condition of IF is fulfilled.

Any help would be appreciated.

答:
This adds some checks that the values are found which should avoid the errors.</p>

```<code>Sub xy()

Dim x As Long, r As Range

Dim Lookup_Range, RangeA As Range

With Worksheets("Duration")
    Set Lookup_Range = .Range("A1:B56")
    Set r = Lookup_Range.Find("1 - 9 days", .Range("A1"), xlValues, xlWhole, xlByColumns, xlNext)
    If Not r Is Nothing Then
        x = r.Row
        Set RangeA = .Range(.Cells(x, 1), .Cells(x + 4, 2))
        .Cells(30, 7) = Application.VLookup("State1", RangeA, 2, False)
        .Cells(31, 7) = Application.VLookup("State2", RangeA, 2, False)
        .Cells(32, 7) = Application.VLookup("State3", RangeA, 2, False)
        .Cells(33, 7) = Application.VLookup("State4", RangeA, 2, False)
    Else
        .Cells(30, 7) = 0
        .Cells(31, 7) = 0
        .Cells(32, 7) = 0
        .Cells(33, 7) = 0
    End If
    Set r = Lookup_Range.Find("10 - 19 days")
    If Not r Is Nothing Then
        x = r.Row
        Set RangeA = .Range(.Cells(x, 1), .Cells(x + 4, 2))
        .Cells(34, 7) = Application.VLookup("State1", RangeA, 2, False)
        .Cells(35, 7) = Application.VLookup("State2", RangeA, 2, False)
        .Cells(36, 7) = Application.VLookup("State3", RangeA, 2, False)
        .Cells(37, 7) = Application.VLookup("State4", RangeA, 2, False)
    Else
        .Cells(34, 7) = 0
        .Cells(35, 7) = 0
        .Cells(36, 7) = 0
        .Cells(37, 7) = 0
    End If
End With

End Sub
</code>```

Body:
I need your help. Cannot figure out why the piece of code below doesn't work. I have a PivotTable where I look for a specific value with a function FIND and VLOOKUP and add it to a specific cell:

After the data update - there is no information about States duration of 10 - 19 days anymore. In this case when some category values are absent - I want to assign the 0 value to a specific cells.
I tried to achive it writing the following:

Dim x As Long
Dim Lookup_Range, RangeA As range

With Worksheets("Duration")

Set Lookup_Range = Worksheets("Duration").range("A1:B56")

On Error Resume Next
x = Lookup_Range.Find("1 - 9 days", range("A1"), xlValues, xlWhole, xlByColumns, xlNext).Row

Set RangeA = .range(.Cells(x, 1), .Cells(x + 4, 2))

If Not x <> "" Then

   .Cells(30, 7) = Application.VLookup("State1", RangeA, 2, False)
   .Cells(31, 7) = Application.VLookup("State2", RangeA, 2, False)
   .Cells(32, 7) = Application.VLookup("State3", RangeA, 2, False)
   .Cells(33, 7) = Application.VLookup("State4", RangeA, 2, False)

Else

   .Cells(30, 7) = 0
   .Cells(31, 7) = 0
   .Cells(32, 7) = 0
   .Cells(33, 7) = 0

End If

On Error Resume Next
x = Lookup_Range.Find("10 - 19 days", range("A1"), xlValues, xlWhole, xlByColumns, xlNext).Row

Set RangeA = .range(.Cells(x, 1), .Cells(x + 4, 2))

If Not x <> "" Then

   .Cells(34, 7) = Application.VLookup("State1", RangeA, 2, False)
   .Cells(35, 7) = Application.VLookup("State2", RangeA, 2, False)
   .Cells(36, 7) = Application.VLookup("State3", RangeA, 2, False)
   .Cells(37, 7) = Application.VLookup("State4", RangeA, 2, False)

Else

.Cells(34, 7) = 0
.Cells(35, 7) = 0
.Cells(36, 7) = 0
.Cells(37, 7) = 0

End If

End With

It only returns the right values when the first condition of IF is fulfilled.

Any help would be appreciated.

Body:
This adds some checks that the values are found which should avoid the errors.

Sub xy()

Dim x As Long, r As Range

Dim Lookup_Range, RangeA As Range

With Worksheets("Duration")
    Set Lookup_Range = .Range("A1:B56")
    Set r = Lookup_Range.Find("1 - 9 days", .Range("A1"), xlValues, xlWhole, xlByColumns, xlNext)
    If Not r Is Nothing Then
        x = r.Row
        Set RangeA = .Range(.Cells(x, 1), .Cells(x + 4, 2))
        .Cells(30, 7) = Application.VLookup("State1", RangeA, 2, False)
        .Cells(31, 7) = Application.VLookup("State2", RangeA, 2, False)
        .Cells(32, 7) = Application.VLookup("State3", RangeA, 2, False)
        .Cells(33, 7) = Application.VLookup("State4", RangeA, 2, False)
    Else
        .Cells(30, 7) = 0
        .Cells(31, 7) = 0
        .Cells(32, 7) = 0
        .Cells(33, 7) = 0
    End If
    Set r = Lookup_Range.Find("10 - 19 days")
    If Not r Is Nothing Then
        x = r.Row
        Set RangeA = .Range(.Cells(x, 1), .Cells(x + 4, 2))
        .Cells(34, 7) = Application.VLookup("State1", RangeA, 2, False)
        .Cells(35, 7) = Application.VLookup("State2", RangeA, 2, False)
        .Cells(36, 7) = Application.VLookup("State3", RangeA, 2, False)
        .Cells(37, 7) = Application.VLookup("State4", RangeA, 2, False)
    Else
        .Cells(34, 7) = 0
        .Cells(35, 7) = 0
        .Cells(36, 7) = 0
        .Cells(37, 7) = 0
    End If
End With

End Sub


答:
Inspired by Eelco Hoogendoorn's library, but without his library, and using the fact that the first column of your array is always increasing (if not, sort first with a = a[a[:, 0].argsort()])

```<code>>>> np.split(a[:,1], np.unique(a[:, 0], return_index=True)[1][1:])
[array([275, 441, 494, 593]),
 array([679, 533, 686]),
 array([559, 219, 455]),
 array([605, 468, 692, 613])]
</code>```

I didn't "timeit" ([EDIT] see below) but this is probably the faster way to achieve the question :

No python native loop

Result lists are numpy arrays, in case you need to make other numpy operations on them, no new conversion will be needed

Complexity looks O(n) (with sort it goes O(n log(n))

[EDIT sept 2021] I ran timeit on my Macbook M1, for a table of 10k random integers. The duration is for 1000 calls.

```<code>>>> a = np.random.randint(5, size=(10000, 2))  # 5 different "groups"

# Only the sort
>>> a = a[a[:, 0].argsort()]
⏱ 116.9 ms

# Group by on the already sorted table
>>> np.split(a[:, 1], np.unique(a[:, 0], return_index=True)[1][1:])
⏱ 35.5 ms

# Total sort + groupby
>>> a = a[a[:, 0].argsort()]
>>> np.split(a[:, 1], np.unique(a[:, 0], return_index=True)[1][1:])
⏱ 153.0 ms

# With numpy-indexed package (cf Eelco answer)
>>> npi.group_by(a[:, 0]).split(a[:, 1])
⏱ 353.3 ms

# With pandas (cf Piotr answer)
>>> df = pd.DataFrame(a, columns=["key", "val"]) # no timer for this line
>>> df.groupby("key").val.apply(pd.Series.tolist)
⏱ 362.3 ms

# With defaultdict, the python native way (cf Piotr answer)
>>> d = defaultdict(list)
for key, val in a:
    d[key].append(val)
⏱ 3543.2 ms

# With numpy_groupies (cf Michael answer)
>>> aggregate(a[:,0], a[:,1], "array", fill_value=[])
⏱ 376.4 ms
</code>```

Second timeit scenario, with 500 different groups instead of 5.
I'm surprised about pandas, I ran several times, but it just behave badly in this scenario.

```<code>>>> a = np.random.randint(500, size=(10000, 2))

just the sort  141.1 ms
already_sorted 392.0 ms
sort+groupby   542.4 ms
pandas        2695.8 ms
numpy-indexed  800.6 ms
defaultdict   3707.3 ms
numpy_groupies 836.7 ms
</code>```

[EDIT] I improved the answer thanks to
ns63sr's answer and Behzad Shayegh (cf comment)
Thanks also TMBailey for noticing complexity of argsort is n log(n).

Title: Is there any numpy group by function?

Body:
Is there any function in numpy to group this array down below by the first column?

I couldn't find any good answer over the internet..

>>> a
array([[  1, 275],
       [  1, 441],
       [  1, 494],
       [  1, 593],
       [  2, 679],
       [  2, 533],
       [  2, 686],
       [  3, 559],
       [  3, 219],
       [  3, 455],
       [  4, 605],
       [  4, 468],
       [  4, 692],
       [  4, 613]])

Wanted output:

array([[[275, 441, 494, 593]],
       [[679, 533, 686]],
       [[559, 219, 455]],
       [[605, 468, 692, 613]]], dtype=object)

Body:
Inspired by Eelco Hoogendoorn's library, but without his library, and using the fact that the first column of your array is always increasing (if not, sort first with a = a[a[:, 0].argsort()])

>>> np.split(a[:,1], np.unique(a[:, 0], return_index=True)[1][1:])
[array([275, 441, 494, 593]),
 array([679, 533, 686]),
 array([559, 219, 455]),
 array([605, 468, 692, 613])]

I didn't "timeit" ([EDIT] see below) but this is probably the faster way to achieve the question :

No python native loop

Result lists are numpy arrays, in case you need to make other numpy operations on them, no new conversion will be needed

Complexity looks O(n) (with sort it goes O(n log(n))

[EDIT sept 2021] I ran timeit on my Macbook M1, for a table of 10k random integers. The duration is for 1000 calls.

>>> a = np.random.randint(5, size=(10000, 2))  # 5 different "groups"

# Only the sort
>>> a = a[a[:, 0].argsort()]
⏱ 116.9 ms

# Group by on the already sorted table
>>> np.split(a[:, 1], np.unique(a[:, 0], return_index=True)[1][1:])
⏱ 35.5 ms

# Total sort + groupby
>>> a = a[a[:, 0].argsort()]
>>> np.split(a[:, 1], np.unique(a[:, 0], return_index=True)[1][1:])
⏱ 153.0 ms

# With numpy-indexed package (cf Eelco answer)
>>> npi.group_by(a[:, 0]).split(a[:, 1])
⏱ 353.3 ms

# With pandas (cf Piotr answer)
>>> df = pd.DataFrame(a, columns=["key", "val"]) # no timer for this line
>>> df.groupby("key").val.apply(pd.Series.tolist)
⏱ 362.3 ms

# With defaultdict, the python native way (cf Piotr answer)
>>> d = defaultdict(list)
for key, val in a:
    d[key].append(val)
⏱ 3543.2 ms

# With numpy_groupies (cf Michael answer)
>>> aggregate(a[:,0], a[:,1], "array", fill_value=[])
⏱ 376.4 ms

Second timeit scenario, with 500 different groups instead of 5.
I'm surprised about pandas, I ran several times, but it just behave badly in this scenario.

>>> a = np.random.randint(500, size=(10000, 2))

just the sort  141.1 ms
already_sorted 392.0 ms
sort+groupby   542.4 ms
pandas        2695.8 ms
numpy-indexed  800.6 ms
defaultdict   3707.3 ms
numpy_groupies 836.7 ms

[EDIT] I improved the answer thanks to
ns63sr's answer and Behzad Shayegh (cf comment)
Thanks also TMBailey for noticing complexity of argsort is n log(n).


问:
byte[] to file in Java
With Java:

I have a byte[] that represents a file.

How do I write this to a file (ie. C:\myfile.pdf)

I know it's done with InputStream, but I can't seem to work it out.

答:
```<code>File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();

Path path = Paths.get(f.getAbsolutePath());
try {
    Files.write(path, fileContent);
} catch (IOException ex) {
    Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
</code>```

Title: byte[] to file in Java