问:
Error getting ADC input
I am using a Cortex-M3 based board. It is the first time I am programming this kind of board, so I don't know how to read the libraries and make it "happen".

This board comes with a temperature sensor, and I am trying to use the adc lib for reading.

My code:

```<code>#include <adc.h>
#include <gpio.h>

using namespace EPOS;
//const NIC::Protocol NIC_PROTOCOL = 42;

ADC * temperature;

int main()
{
   temperature = new ADC( 0xE, 0x2, 0x3);
   //    printf("&temperature");

   return 0;
}
</code>```

The library

```<code>// EPOS ARM Cortex-M Analog to Digital Converter (ADC) Mediator Declarations

#include <system/config.h>
#if !defined(__cortex_adc_h_) && defined(__ADC_H)
#define __cortex_adc_h_

#include <adc.h>
#include <machine.h>

__BEGIN_SYS

class ADC: private ADC_Common, private Machine_Model
{
public:
    enum Channel {
        SINGLE_ENDED_ADC0 = 0,
        SINGLE_ENDED_ADC1 = 1,
        SINGLE_ENDED_ADC2 = 2,
        SINGLE_ENDED_ADC3 = 3,
        SINGLE_ENDED_ADC4 = 4,
        SINGLE_ENDED_ADC5 = 5,
        SINGLE_ENDED_ADC6 = 6,
        SINGLE_ENDED_ADC7 = 7,
        DIFF8             = 8,
        DIFF9             = 9,
        DIFF10            = 10,
        DIFF11            = 11,
        GND               = 12,
        TEMPERATURE       = 14,
        AVDD5_3           = 15,
    };

    enum Reference {
        INTERNAL_REF   = 0,
        EXTERNAL_REF   = 1, // External reference on AIN7 pin
        SYSTEM_REF     = 2,
        EXTERNAL_DIFF  = 3
    };

    enum Resolution {
        BITS_7  = 0, //  7 bits resolution, 64  decimation rate
        BITS_9  = 1, //  9 bits resolution, 128 decimation rate
        BITS_10 = 2, // 10 bits resolution, 256 decimation rate
        BITS_12 = 3  // 12 bits resolution, 512 decimation rate
    };

    ADC(const Channel & channel = SINGLE_ENDED_ADC5, const Reference & reference = SYSTEM_REF, const Resolution & resolution = BITS_12)
    : _channel(channel), _reference(reference), _resolution(resolution) {
        Machine_Model::adc_config(_channel);
    }

    short read() {
        reg(ADCCON3) = (_reference * ADCCON3_EREF) | (_resolution * ADCCON3_EDIV) | (_channel * ADCCON3_ECH);
        while(!(reg(ADCCON1) & ADCCON1_EOC));
        short ret = (reg(ADCH) << 8) + reg(ADCL);
        switch(_resolution) {
            case BITS_7:  ret >>= 9; break;
            case BITS_9:  ret >>= 7; break;
            case BITS_10: ret >>= 6; break;
            case BITS_12: ret >>= 4; break;
        }
        return ret;
    }

    // returns the voltage corresponding to the reading, with three decimal places (e.g. 2534 means 2.534V)
    int convert(short raw_reading, int reference = 3300/*3.3V*/) {
        int limit;
        switch(_resolution) {
            case BITS_7:  limit =   63; break;
            case BITS_9:  limit =  255; break;
            case BITS_10: limit =  511; break;
            case BITS_12: limit = 2047; break;
        }
        return raw_reading * reference / limit;
    }

private:
    volatile CPU::Reg32 & reg(unsigned int o) { return reinterpret_cast<volatile CPU::Reg32*>(ADC_BASE)[o / sizeof(CPU::Reg32)]; }

    Channel _channel;
    Reference _reference;
    Resolution _resolution;
};

__END_SYS

#endif
</code>```

error:

temperature.cc: In function 'int main()': temperature.cc:11: error:
  invalid conversion from 'int' to 'EPOS::S::ADC::Channel'
  temperature.cc:11: error:   initializing argument 1 of
  'EPOS::S::ADC::ADC(const EPOS::S::ADC::Channel&, const
  EPOS::S::ADC::Reference&, const EPOS::S::ADC::Resolution&)'
  temperature.cc:11: error: invalid conversion from 'int' to
  'EPOS::S::ADC::Reference' temperature.cc:11: error:   initializing
  argument 2 of 'EPOS::S::ADC::ADC(const EPOS::S::ADC::Channel&, const
  EPOS::S::ADC::Reference&, const EPOS::S::ADC::Resolution&)'
  temperature.cc:11: error: invalid conversion from 'int' to
  'EPOS::S::ADC::Resolution' temperature.cc:11: error:   initializing
  argument 3 of 'EPOS::S::ADC::ADC(const EPOS::S::ADC::Channel&, const
  EPOS::S::ADC::Reference&, const EPOS::S::ADC::Resolution&)'
  makefile:11: recipe for target 'temperature.o' failed make[2]: *
  [temperature.o] Error 1 make[2]: Leaving directory
  '/home/thiago/Documents/arm/app' makefile:17: recipe for target 'app'
  failed make[1]: * [app] Error 2 make[1]: Leaving directory
  '/home/thiago/Documents/arm' makefile:11: recipe for target 'all'
  failed make: *** [all] Error 2

Programming language: c++

Thanks.

答:
The ADC constructor wants 3 parameters passed by reference, so you must pass variables.

Your code should be, at least:

```<code>int main(void)
{
   Channel channel = TEMPERATURE;
   Reference reference = SYSTEM_REF;
   Resolution resolution = BITS_12;

   temperature = new ADC( channel, reference, resolution);

   return 0;
}
</code>```

EDIT

As already said by other users, you shoud avoid to use dynamic allocation on embedded application with uC with limitated resources (RAM mainly).

So you can instantiate your class like:

```<code>int main(void)
{
   short temperature;

   Channel channel = TEMPERATURE;
   Reference reference = SYSTEM_REF;
   Resolution resolution = BITS_12;

   ADC reader( channel, reference, resolution);

   while (1)
   {
      temperature = reader.read();
   }
}
</code>```

Title: Error getting ADC input

Body:
I am using a Cortex-M3 based board. It is the first time I am programming this kind of board, so I don't know how to read the libraries and make it "happen".

This board comes with a temperature sensor, and I am trying to use the adc lib for reading.

My code:

#include <adc.h>
#include <gpio.h>

using namespace EPOS;
//const NIC::Protocol NIC_PROTOCOL = 42;

ADC * temperature;

int main()
{
   temperature = new ADC( 0xE, 0x2, 0x3);
   //    printf("&temperature");

   return 0;
}

The library

// EPOS ARM Cortex-M Analog to Digital Converter (ADC) Mediator Declarations

#include <system/config.h>
#if !defined(__cortex_adc_h_) && defined(__ADC_H)
#define __cortex_adc_h_

#include <adc.h>
#include <machine.h>

__BEGIN_SYS

class ADC: private ADC_Common, private Machine_Model
{
public:
    enum Channel {
        SINGLE_ENDED_ADC0 = 0,
        SINGLE_ENDED_ADC1 = 1,
        SINGLE_ENDED_ADC2 = 2,
        SINGLE_ENDED_ADC3 = 3,
        SINGLE_ENDED_ADC4 = 4,
        SINGLE_ENDED_ADC5 = 5,
        SINGLE_ENDED_ADC6 = 6,
        SINGLE_ENDED_ADC7 = 7,
        DIFF8             = 8,
        DIFF9             = 9,
        DIFF10            = 10,
        DIFF11            = 11,
        GND               = 12,
        TEMPERATURE       = 14,
        AVDD5_3           = 15,
    };

    enum Reference {
        INTERNAL_REF   = 0,
        EXTERNAL_REF   = 1, // External reference on AIN7 pin
        SYSTEM_REF     = 2,
        EXTERNAL_DIFF  = 3
    };

    enum Resolution {
        BITS_7  = 0, //  7 bits resolution, 64  decimation rate
        BITS_9  = 1, //  9 bits resolution, 128 decimation rate
        BITS_10 = 2, // 10 bits resolution, 256 decimation rate
        BITS_12 = 3  // 12 bits resolution, 512 decimation rate
    };

    ADC(const Channel & channel = SINGLE_ENDED_ADC5, const Reference & reference = SYSTEM_REF, const Resolution & resolution = BITS_12)
    : _channel(channel), _reference(reference), _resolution(resolution) {
        Machine_Model::adc_config(_channel);
    }

    short read() {
        reg(ADCCON3) = (_reference * ADCCON3_EREF) | (_resolution * ADCCON3_EDIV) | (_channel * ADCCON3_ECH);
        while(!(reg(ADCCON1) & ADCCON1_EOC));
        short ret = (reg(ADCH) << 8) + reg(ADCL);
        switch(_resolution) {
            case BITS_7:  ret >>= 9; break;
            case BITS_9:  ret >>= 7; break;
            case BITS_10: ret >>= 6; break;
            case BITS_12: ret >>= 4; break;
        }
        return ret;
    }

    // returns the voltage corresponding to the reading, with three decimal places (e.g. 2534 means 2.534V)
    int convert(short raw_reading, int reference = 3300/*3.3V*/) {
        int limit;
        switch(_resolution) {
            case BITS_7:  limit =   63; break;
            case BITS_9:  limit =  255; break;
            case BITS_10: limit =  511; break;
            case BITS_12: limit = 2047; break;
        }
        return raw_reading * reference / limit;
    }

private:
    volatile CPU::Reg32 & reg(unsigned int o) { return reinterpret_cast<volatile CPU::Reg32*>(ADC_BASE)[o / sizeof(CPU::Reg32)]; }

    Channel _channel;
    Reference _reference;
    Resolution _resolution;
};

__END_SYS

#endif

error:

temperature.cc: In function 'int main()': temperature.cc:11: error:
  invalid conversion from 'int' to 'EPOS::S::ADC::Channel'
  temperature.cc:11: error:   initializing argument 1 of
  'EPOS::S::ADC::ADC(const EPOS::S::ADC::Channel&, const
  EPOS::S::ADC::Reference&, const EPOS::S::ADC::Resolution&)'
  temperature.cc:11: error: invalid conversion from 'int' to
  'EPOS::S::ADC::Reference' temperature.cc:11: error:   initializing
  argument 2 of 'EPOS::S::ADC::ADC(const EPOS::S::ADC::Channel&, const
  EPOS::S::ADC::Reference&, const EPOS::S::ADC::Resolution&)'
  temperature.cc:11: error: invalid conversion from 'int' to
  'EPOS::S::ADC::Resolution' temperature.cc:11: error:   initializing
  argument 3 of 'EPOS::S::ADC::ADC(const EPOS::S::ADC::Channel&, const
  EPOS::S::ADC::Reference&, const EPOS::S::ADC::Resolution&)'
  makefile:11: recipe for target 'temperature.o' failed make[2]: *
  [temperature.o] Error 1 make[2]: Leaving directory
  '/home/thiago/Documents/arm/app' makefile:17: recipe for target 'app'
  failed make[1]: * [app] Error 2 make[1]: Leaving directory
  '/home/thiago/Documents/arm' makefile:11: recipe for target 'all'
  failed make: *** [all] Error 2

Programming language: c++

Thanks.

Body:
The ADC constructor wants 3 parameters passed by reference, so you must pass variables.

Your code should be, at least:

int main(void)
{
   Channel channel = TEMPERATURE;
   Reference reference = SYSTEM_REF;
   Resolution resolution = BITS_12;

   temperature = new ADC( channel, reference, resolution);

   return 0;
}

EDIT

As already said by other users, you shoud avoid to use dynamic allocation on embedded application with uC with limitated resources (RAM mainly).

So you can instantiate your class like:

int main(void)
{
   short temperature;

   Channel channel = TEMPERATURE;
   Reference reference = SYSTEM_REF;
   Resolution resolution = BITS_12;

   ADC reader( channel, reference, resolution);

   while (1)
   {
      temperature = reader.read();
   }
}


来源: stackexchange

问:
Error on Wordpress wp_signon() function
When I run wp_signon () I have several warning similar to this:
"Warning: Cannot modify header information - headers already sent by (output started at /web/htdocs/www.example.com/home/wp-includes/class.wp-styles.php:237) in /web/htdocs/www.mysite.com/home/wp-includes/pluggable.php on line 892"
It do the login anyway, and if I change page then does not give me no problem, but I can not understand these errors.
I am attaching the login code.
Thanks a lot in advance for the help!

header.php :

```<code>    <div id="loginbar">

    <?php   $current_user = wp_get_current_user();
            if(isset($_POST["submit"])){
            custom_login();
            }?>

    <?php if(!is_user_logged_in()): ?>
        <form name="frontlog" method="post">
            <input id= "log" type="text" name="log" placeholder="Username">
            <input id= "pwd" type="password" name="pwd" placeholder="Password">
            <input type= "submit" name="submit" class="linkbuttonleft" id="loginbutton">
        </form>
        <a class="linkbuttonright" title="Registrati" href="http://www.example.com/registrazione/">
        <img id="chiave" src="http://www.example.com/wp-content/themes/BiscuitsTheme/immagini/chiave.png" onmousedown="return false"></a>
    <?php else: ?>
        <p> <?php echo 'Benvenuto ' . $current_user->user_login;?> </p>
        <a class="linkbuttonleft" title="Logout" href="<?php echo wp_logout_url( home_url() ); ?>"></a>
        <img id="lucchetto" src="http://www.example.com/wp-content/themes/BiscuitsTheme/immagini/lucchetto.png" onmousedown="return false"></a>
        <a class="linkbuttonright" title="Profilo" href="http://www.example.com/profilo/">
        <img id="profilo" src="http://www.example.com/wp-content/themes/BiscuitsTheme/immagini/profilo.png" onmousedown="return false"></a>
    <?php endif; ?>
</div>
</code>```

functions.php :

```<code>    function custom_login() {
    $creds = array();
    $creds = array(
        'user_login'    => $_POST["log"],
        'user_password' => $_POST["pwd"],
        'remember'      => true
    );

    $user = wp_signon( $creds, false );

    if ( is_wp_error($user) ) {
        echo $user->get_error_message();
    }
    else {
        wp_set_current_user( $user->ID, $user->name );
        wp_set_auth_cookie( $user->ID, true, false );
    }
};add_action( 'after_setup_theme', 'custom_login' );
</code>```

答:
I have solved wp_signon() function for "first time no loggedIn error" so  you just call set_current_user($user_verify->ID) function below wp_signon() function :</p>

```<code>require('wp-load.php');
$err = '';
$success = '';
global $wpdb,$current_user;
    $response = array();
    $data = json_decode(file_get_contents("php://input"));

    $email    = $data->email_id;
    $password = $data->password;
    $username = $wpdb->escape($email);
    $password = $wpdb->escape($password);
    $remember = true;
    if($remember) $remember = "true";
    else $remember = "false";
    $login_data = array();
    $login_data['user_login'] = $username;
    $login_data['user_password'] = $password;
    $login_data['remember'] = $remember;

    $user_verify = wp_signon( $login_data, false );
    set_current_user($user_verify->ID);
    if (is_user_logged_in())
    {
        get_currentuserinfo();

            $response['user_id']=$user_verify->ID;
            $response['first_name']=$current_user->user_firstname ;
            $response['last_name']=$current_user->user_lastname;
            $response['email']=$current_user->user_email;
      $status="success";
      $msg="";
    } else {
      $status="failed";
      $msg="Invalid Credential.";
     }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Error on Wordpress wp_signon() function

Body:
When I run wp_signon () I have several warning similar to this:
"Warning: Cannot modify header information - headers already sent by (output started at /web/htdocs/www.example.com/home/wp-includes/class.wp-styles.php:237) in /web/htdocs/www.mysite.com/home/wp-includes/pluggable.php on line 892"
It do the login anyway, and if I change page then does not give me no problem, but I can not understand these errors.
I am attaching the login code.
Thanks a lot in advance for the help!

header.php :

    <?php   $current_user = wp_get_current_user();
            if(isset($_POST["submit"])){
            custom_login();
            }?>

    <?php if(!is_user_logged_in()): ?>
        <form name="frontlog" method="post">
            <input id= "log" type="text" name="log" placeholder="Username">
            <input id= "pwd" type="password" name="pwd" placeholder="Password">
            <input type= "submit" name="submit" class="linkbuttonleft" id="loginbutton">
        </form>

    <?php else: ?>

 <?php echo 'Benvenuto ' . $current_user->user_login;?>

        <a class="linkbuttonleft" title="Logout" href="<?php echo wp_logout_url( home_url() ); ?>">

    <?php endif; ?>

functions.php :

    function custom_login() {
    $creds = array();
    $creds = array(
        'user_login'    => $_POST["log"],
        'user_password' => $_POST["pwd"],
        'remember'      => true
    );

    $user = wp_signon( $creds, false );

    if ( is_wp_error($user) ) {
        echo $user->get_error_message();
    }
    else {
        wp_set_current_user( $user->ID, $user->name );
        wp_set_auth_cookie( $user->ID, true, false );
    }
};add_action( 'after_setup_theme', 'custom_login' );

Body:
I have solved wp_signon() function for "first time no loggedIn error" so  you just call set_current_user($user_verify->ID) function below wp_signon() function :

require('wp-load.php');
$err = '';
$success = '';
global $wpdb,$current_user;
    $response = array();
    $data = json_decode(file_get_contents("php://input"));

    $email    = $data->email_id;
    $password = $data->password;
    $username = $wpdb->escape($email);
    $password = $wpdb->escape($password);
    $remember = true;
    if($remember) $remember = "true";
    else $remember = "false";
    $login_data = array();
    $login_data['user_login'] = $username;
    $login_data['user_password'] = $password;
    $login_data['remember'] = $remember;

    $user_verify = wp_signon( $login_data, false );
    set_current_user($user_verify->ID);
    if (is_user_logged_in())
    {
        get_currentuserinfo();

            $response['user_id']=$user_verify->ID;
            $response['first_name']=$current_user->user_firstname ;
            $response['last_name']=$current_user->user_lastname;
            $response['email']=$current_user->user_email;
      $status="success";
      $msg="";
    } else {
      $status="failed";
      $msg="Invalid Credential.";
     }


问:
SUMIFs by only calculating unique values in another column
I currently have a table with five columns:

```<code>A = Campaign
B = Person
C = Opportunity Name
D = Total Cost of Campaign
E = Date
</code>```

I'm trying to use =sumifs to calculate the amount in column D only if: (1) it matches the exact value in cell H2 to column A, (2) the date range, in column E, is greater than the value in cell I2, and (3) it removes duplicates based on value in column C (so you can't sum if value appears more than once).

Please refer to my data table (also attached) as reference:

```<code>Campaign    Person  Opportunity Name    Total Cost of Campaign  Date
A           Bob     Airbnb              5000                   3/2/2017
B           Jim     Sony                10000                  3/2/2017
B           Jane    Coca-Cola           10000                  3/2/2017
C           Jim     Sony                200                    3/2/2017
B           Daniel  Sony                10000                  3/2/2017
B           April   Coca-Cola           10000                  3/5/2017
</code>```

How could I do this?

Thanks in advance for the help!

答:
Try:

=SUM(
  UNIQUE(
   QUERY(A:E,"select C, D where A = '"&H2&"' and E > date '"&TEXT(H3,"YYYY-MM-DD")&"'")))

Query will cut first two conditions. Unique will remove duplicates:

Body:
I currently have a table with five columns:

A = Campaign
B = Person
C = Opportunity Name
D = Total Cost of Campaign
E = Date

I'm trying to use =sumifs to calculate the amount in column D only if: (1) it matches the exact value in cell H2 to column A, (2) the date range, in column E, is greater than the value in cell I2, and (3) it removes duplicates based on value in column C (so you can't sum if value appears more than once).

Please refer to my data table (also attached) as reference:

Campaign    Person  Opportunity Name    Total Cost of Campaign  Date
A           Bob     Airbnb              5000                   3/2/2017
B           Jim     Sony                10000                  3/2/2017
B           Jane    Coca-Cola           10000                  3/2/2017
C           Jim     Sony                200                    3/2/2017
B           Daniel  Sony                10000                  3/2/2017
B           April   Coca-Cola           10000                  3/5/2017

How could I do this?

Thanks in advance for the help!


问:
IE 6 and Silverlight
Does Silverlight work with IE 6, are there any gotchas?

Just wondering if this is an alternative for customers stuck with IE 6.

答: I have worked on sites that run on IE6 and we were able to work well in Silverlight. As Silverlight is a Plugin, it doesn't matter what they underlying browser is, as long as it is the once supported by Silverlight team. We didnt come across any issues, we had worked on data driven app.</p>

ContentLicense: CC BY-SA 2.5

Title: IE 6 and Silverlight


问:
Starting HTML Template when app loads
Noob question here. I am very new to using angular and ionic. I am building an app for a course and I started by using a tutorial and I have just been changing things until it becomes the app I want.

I want to change the initial html page that gets loaded when you run the app. Where do I set this?

Sorry! I am aware that this is probably super obvious but I can't seem to figure it out!

答:
It depends on the approach you are taking on design flow of your application. You can use state and define templates folder and assign each template(.html file) to specific view. for example according to this tutorial of Ionic
http://ionicframework.com/docs/v1/platform-customization/dynamic-templates.html

you can have this simplified version in you app.js file

.state('app.main', {
    url: '/main',
    views: {
      'menuContent': {
        templateUrl: 'templates/main.html',
        controller : 'mainCtrl'
      }
    }
  })

In this case you can edit you html in main.html and mainCtrl is the controller assigned to this template.

Title: Starting HTML Template when app loads


问:
Split a text in excel containing text and number in brackets
I want to split a cell into multiple columns with each own.
Please see below for example.

```<code>Currrent Cell:
Mobile Users (300)
Want to Split into two more cells:
Device Category        Number of Users
Mobile Users           300
</code>```

I have used LEFT formula to separate Mobile Users one but cannot split 300 number successfully out of brackets.

答:
Assuming that you have the content (you wish to split) in cell A3 the following formulas should work.

In cell B4 to get Mobile Users:

```<code>=LEFT(A3,FIND("(",A3)-2)
</code>```

In cell C4 to get the number 300 from within the brackets:

```<code>=VALUE(MID(A3,FIND("(",A3)+1,FIND(")",A3)-FIND("(",A3)-1))
</code>```

Body:
I want to split a cell into multiple columns with each own.
Please see below for example.

Currrent Cell:
Mobile Users (300)
Want to Split into two more cells:
Device Category        Number of Users
Mobile Users           300

I have used LEFT formula to separate Mobile Users one but cannot split 300 number successfully out of brackets.

Body:
Assuming that you have the content (you wish to split) in cell A3 the following formulas should work.

In cell B4 to get Mobile Users:

=LEFT(A3,FIND("(",A3)-2)

In cell C4 to get the number 300 from within the brackets:

=VALUE(MID(A3,FIND("(",A3)+1,FIND(")",A3)-FIND("(",A3)-1))


问:
How can I create binary label from two tables
I'm trying to analyse a trend in data that I have with Pandas. I have a two tables and I'd like to create a new binary column in one if the UID and PID in that row exists in the other table. An example of the tables I currently have would be:

```<code>>>> df_a = pd.DataFrame({"UID": [123, 456, 789, 012], "PID": [12, 55, 56, 89], "TIM": [76, 54, 21, 25]})
>>> df_a
   PID  TIM  UID
0   12   76  123
1   55   54  456
2   56   21  789
3   89   25  010

>>> df_b = pd.DataFrame({'UID': [221, 012, 653, 456], 'PID': [17, 89, 51, 55], 'FOO': [2347, 32447, 3234, 7999]})
>>> df_b
     FOO  PID  UID
0   2347   17  221
1  32447   89  010
2   3234   51  653
3   7999   55  456
</code>```

And I'd like the end result to be:

```<code>>>> df_a
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25  010    1
</code>```

But I'm not sure exactly how to go about doing this. I thought a left join would be the way to go but I'm having trouble pulling that off also. Any help would be appreciated

答:
merge with indicator=True almost gets you there

```<code>df_a.merge(df_b[['PID', 'UID']], how='left', indicator=True)

   PID  TIM  UID     _merge
0   12   76  123  left_only
1   55   54  456       both
2   56   21  789  left_only
3   89   25  012       both
</code>```

With a tweak using map

```<code>m = dict(left_only=0, both=1)
df_a.assign(
    PUR=df_a.merge(df_b[['PID', 'UID']], how='left', indicator=True)._merge.map(m))

   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25  012    1
</code>```

Body:
I'm trying to analyse a trend in data that I have with Pandas. I have a two tables and I'd like to create a new binary column in one if the UID and PID in that row exists in the other table. An example of the tables I currently have would be:

>>> df_a = pd.DataFrame({"UID": [123, 456, 789, 012], "PID": [12, 55, 56, 89], "TIM": [76, 54, 21, 25]})
>>> df_a
   PID  TIM  UID
0   12   76  123
1   55   54  456
2   56   21  789
3   89   25  010

>>> df_b = pd.DataFrame({'UID': [221, 012, 653, 456], 'PID': [17, 89, 51, 55], 'FOO': [2347, 32447, 3234, 7999]})
>>> df_b
     FOO  PID  UID
0   2347   17  221
1  32447   89  010
2   3234   51  653
3   7999   55  456

And I'd like the end result to be:

>>> df_a
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25  010    1

But I'm not sure exactly how to go about doing this. I thought a left join would be the way to go but I'm having trouble pulling that off also. Any help would be appreciated

Body:
merge with indicator=True almost gets you there

df_a.merge(df_b[['PID', 'UID']], how='left', indicator=True)

   PID  TIM  UID     _merge
0   12   76  123  left_only
1   55   54  456       both
2   56   21  789  left_only
3   89   25  012       both

With a tweak using map

m = dict(left_only=0, both=1)
df_a.assign(
    PUR=df_a.merge(df_b[['PID', 'UID']], how='left', indicator=True)._merge.map(m))

   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25  012    1


问:
Abstract type in Julia and member variables
I am very confused as to whether abstract types in Julia can have member variables (like virtual classes in C++). I am sure the docs mention it but I cannot find it!

I tried something like:

```<code>abstract AbstractR
  source
end
</code>```

And now I have a concrete implementation as:

```<code>type RR <: AbstractR
end

function loadSource(reg::RR, x::AbstractString)
  println("Hello")
end
</code>```

However, when I try to load the module, I have:

ERROR: LoadError: LoadError: LoadError: UndefVarError: source not
  defined

So is it that abstract type is just a type name and nothing else? Also, why did the language designers decide to not support member variables (if that is indeed the case). Also, I do not then really see the point of having an abstract type anyway...

EDIT

Module file

```<code>module TestProj
export AbstractR
export RR
include("generic.jl")
include("rr.jl")
end
</code>```

generic.jl

```<code>abstract AbstractR
  source
end
</code>```

rr.jl

```<code>type RR <: AbstractR
end

function loadSource(reg::RR, x::AbstractString)
  println("Hello")
end
</code>```

答:
You are loading a module then?
Perhaps you must import stuff first.
Could you post the entirety of the code?</p>

Body:
I am very confused as to whether abstract types in Julia can have member variables (like virtual classes in C++). I am sure the docs mention it but I cannot find it!

I tried something like:

abstract AbstractR
  source
end

And now I have a concrete implementation as:

type RR <: AbstractR
end

function loadSource(reg::RR, x::AbstractString)
  println("Hello")
end

However, when I try to load the module, I have:

ERROR: LoadError: LoadError: LoadError: UndefVarError: source not
  defined

So is it that abstract type is just a type name and nothing else? Also, why did the language designers decide to not support member variables (if that is indeed the case). Also, I do not then really see the point of having an abstract type anyway...

EDIT

Module file

module TestProj
export AbstractR
export RR
include("generic.jl")
include("rr.jl")
end

generic.jl

abstract AbstractR
  source
end

rr.jl

type RR <: AbstractR
end

function loadSource(reg::RR, x::AbstractString)
  println("Hello")
end


问:
How to time-efficiently remove values next to 'NaN' values?
I'm trying to remove wrong values form my data (a series of 15mln values, 700MB). The values to be removed are values next to 'nan' values, e.g.:

Series: /1/,nan,/2/,3,/4/,nan,nan,nan,/8/,9
Numbers surrounded by slashes i.e. /1/,/2/,/4/,/8/ are values, which should be removed.

The problem is that it takes way too long to compute that with the following code that I have:

```<code>%%time

import numpy as np
import pandas as pd

# sample data
speed = np.random.uniform(0,25,15000000)
next_speed = speed[1:]

# create a dataframe
data_dict = {'speed': speed[:-1],
            'next_speed': next_speed}

df = pd.DataFrame(data_dict)

# calculate difference between the current speed and the next speed
list_of_differences = []

for i in df.index:
    difference = df.next_speed[i]-df.speed[i]
    list_of_differences.append(difference)

df['difference'] = list_of_differences

# add 'nan' to data in form of a string.

for i in range(len(df.difference)):
    # arbitrary condition
    if df.difference[i] < -2:
        df.difference[i] = 'nan'

#########################################
# THE TIME-INEFFICIENT LOOP

# remove wrong values before and after 'nan'.
for i in  range(len(df)):

    # check if the value is a number to skip computations of the following "if" cases
    if not(isinstance(df.difference[i], str)):
        continue

    # case 1: where there's only one 'nan' surrounded by values.
    # Without this case the algo will miss some wrong values because 'nan' will be removed
    # Example of a series: /1/,nan,/2/,3,4,nan,nan,nan,8,9
    # A number surrounded by slashes e.g. /1/ is a value to be removed
    if df.difference[i] == 'nan' and df.difference[i-1] != 'nan' and df.difference[i+1] != 'nan':
        df.difference[i-1]= 'wrong'
        df.difference[i+1]= 'wrong'

    # case 2: where the following values are 'nan': /1/, nan, nan, 4
    # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,8,9
    elif df.difference[i] == 'nan' and df.difference[i+1] == 'nan':
        df.difference[i-1]= 'wrong'

    # case 3: where next value is NOT 'nan'  wrong, nan,nan,4
        # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,/8/,9
    elif df.difference[i] == 'nan' and df.difference[i+1] != 'nan':
        df.difference[i+1]= 'wrong'
</code>```

How to make it more time-efficient?

答:
I am assuming that you don't want either 'nan' or wrong values and nan values are not much compared to size of data. Please try with this:

```<code>nan_idx = df[df['difference']=='nan'].index.tolist()

from copy import deepcopy
drop_list = deepcopy(nan_idx)

for i in nan_idx:
    if (i+1) not in(drop_list) and (i+1) < len(df):
        mm.append(i+1)
    if (i-1) not in(drop_list) and (i-1) < len(df):
        mm.append(i-1)

df.drop(df.index[drop_list])
</code>```

if nan is not a string but it is NaN which is for missing values then use this to get its indexes:

```<code>nan_idx = df[pandas.isnull(df['difference'])].index.tolist()
</code>```

Body:
I'm trying to remove wrong values form my data (a series of 15mln values, 700MB). The values to be removed are values next to 'nan' values, e.g.:

Series: /1/,nan,/2/,3,/4/,nan,nan,nan,/8/,9
Numbers surrounded by slashes i.e. /1/,/2/,/4/,/8/ are values, which should be removed.

The problem is that it takes way too long to compute that with the following code that I have:

%%time

import numpy as np
import pandas as pd

# sample data
speed = np.random.uniform(0,25,15000000)
next_speed = speed[1:]

# create a dataframe
data_dict = {'speed': speed[:-1],
            'next_speed': next_speed}

df = pd.DataFrame(data_dict)

# calculate difference between the current speed and the next speed
list_of_differences = []

for i in df.index:
    difference = df.next_speed[i]-df.speed[i]
    list_of_differences.append(difference)

df['difference'] = list_of_differences

# add 'nan' to data in form of a string.

for i in range(len(df.difference)):
    # arbitrary condition
    if df.difference[i] < -2:
        df.difference[i] = 'nan'

#########################################
# THE TIME-INEFFICIENT LOOP

# remove wrong values before and after 'nan'.
for i in  range(len(df)):

    # check if the value is a number to skip computations of the following "if" cases
    if not(isinstance(df.difference[i], str)):
        continue

    # case 1: where there's only one 'nan' surrounded by values.
    # Without this case the algo will miss some wrong values because 'nan' will be removed
    # Example of a series: /1/,nan,/2/,3,4,nan,nan,nan,8,9
    # A number surrounded by slashes e.g. /1/ is a value to be removed
    if df.difference[i] == 'nan' and df.difference[i-1] != 'nan' and df.difference[i+1] != 'nan':
        df.difference[i-1]= 'wrong'
        df.difference[i+1]= 'wrong'

    # case 2: where the following values are 'nan': /1/, nan, nan, 4
    # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,8,9
    elif df.difference[i] == 'nan' and df.difference[i+1] == 'nan':
        df.difference[i-1]= 'wrong'

    # case 3: where next value is NOT 'nan'  wrong, nan,nan,4
        # E.g.: /1/, nan,/2/,3,/4/,nan,nan,nan,/8/,9
    elif df.difference[i] == 'nan' and df.difference[i+1] != 'nan':
        df.difference[i+1]= 'wrong'

How to make it more time-efficient?

Body:
I am assuming that you don't want either 'nan' or wrong values and nan values are not much compared to size of data. Please try with this:

nan_idx = df[df['difference']=='nan'].index.tolist()

from copy import deepcopy
drop_list = deepcopy(nan_idx)

for i in nan_idx:
    if (i+1) not in(drop_list) and (i+1) < len(df):
        mm.append(i+1)
    if (i-1) not in(drop_list) and (i-1) < len(df):
        mm.append(i-1)

df.drop(df.index[drop_list])

if nan is not a string but it is NaN which is for missing values then use this to get its indexes:

nan_idx = df[pandas.isnull(df['difference'])].index.tolist()


问:
Convert integer (YYYYMMDD) to date format (mm/dd/yyyy) in python
I have following dataframe.

```<code>id int_date
1  20160228
2  20161231
3  20160618
4  20170123
5  20151124
</code>```

How to convert above date in int format to date format of mm/dd/yyyy? Want this in particular format for further excel operations?

```<code>id int_date
1  02/28/2016
2  12/31/2016
3  06/18/2016
4  01/23/2017
5  11/24/2015
</code>```

IS it also possible to generate third column with only Month in words? like January, February etc from int_date?

I tried following

```<code>date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
</code>```

but date is in datetime object, how to put it as date in pandas DF?

答:
There is bound to be a better solution to this, but since you have zeroes instead of single-digit elements in your date (i.e. 06 instead of 6), why not just convert it to string and convert the subsections?

using datetime would also get you the month strings etc.

//edit:
to be a little more precise, something like this should do the job:

```<code>def get_datetime(date):
    date_string = str(date)
    return datetime.date(date_string[:3], date_string[4:6], date_string[6:8]
</code>```

Body:
I have following dataframe.

id int_date
1  20160228
2  20161231
3  20160618
4  20170123
5  20151124

How to convert above date in int format to date format of mm/dd/yyyy? Want this in particular format for further excel operations?

id int_date
1  02/28/2016
2  12/31/2016
3  06/18/2016
4  01/23/2017
5  11/24/2015

IS it also possible to generate third column with only Month in words? like January, February etc from int_date?

I tried following

date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

but date is in datetime object, how to put it as date in pandas DF?

Body:
There is bound to be a better solution to this, but since you have zeroes instead of single-digit elements in your date (i.e. 06 instead of 6), why not just convert it to string and convert the subsections?

using datetime would also get you the month strings etc.

//edit:
to be a little more precise, something like this should do the job:

def get_datetime(date):
    date_string = str(date)
    return datetime.date(date_string[:3], date_string[4:6], date_string[6:8]


问:
Django nested Transaction.atomic not rolled back
I have two logically connected instance in two different data bases. I want them both to be saved or rollbacked. But if I raise an exception in an outer block - nested Transaction.atomic will not rollback, but why?

From documentation:

atomic blocks can be nested. In this case, when an inner block
  completes successfully, its effects can still be rolled back if an
  exception is raised in the outer block at a later point.

```<code>def __commit_to_db(self, mesure, mdm_mesure):
    try:
        with transaction.atomic():
            mesure.save()
            with transaction.atomic(using='mdm'):
                mdm_mesure.save()
            raise Exception('oops')
    except (KeyboardInterrupt, SystemExit):
        raise
    except BaseException as error:
        MainLoger.log_error(error)
    return
</code>```

答:
Transactions are a database-level feature. So although you're nesting the Python code, each database is actually getting its own transaction independent of the other. There are no nested transactions that span databases in Django.

You'll have to restructure your code in some way. For example, putting your code inside both atomic() blocks would work:

```<code>try:
    with transaction.atomic():
        with transaction.atomic(using='mdm'):
            mesure.save()
            mdm_mesure.save()

            # neither transaction will commit
            raise Exception('oops')
except Exception:
    pass
</code>```

Body:
I have two logically connected instance in two different data bases. I want them both to be saved or rollbacked. But if I raise an exception in an outer block - nested Transaction.atomic will not rollback, but why?

From documentation:

atomic blocks can be nested. In this case, when an inner block
  completes successfully, its effects can still be rolled back if an
  exception is raised in the outer block at a later point.

def __commit_to_db(self, mesure, mdm_mesure):
    try:
        with transaction.atomic():
            mesure.save()
            with transaction.atomic(using='mdm'):
                mdm_mesure.save()
            raise Exception('oops')
    except (KeyboardInterrupt, SystemExit):
        raise
    except BaseException as error:
        MainLoger.log_error(error)
    return

Body:
Transactions are a database-level feature. So although you're nesting the Python code, each database is actually getting its own transaction independent of the other. There are no nested transactions that span databases in Django.

You'll have to restructure your code in some way. For example, putting your code inside both atomic() blocks would work:

try:
    with transaction.atomic():
        with transaction.atomic(using='mdm'):
            mesure.save()
            mdm_mesure.save()

            # neither transaction will commit
            raise Exception('oops')
except Exception:
    pass


问:
How to use jQuery's delay() as a sleep()?
Can jQuery be used as a sleep() or wait() function? Suspending the execution of the statements after the wait. I tried $().delay(5000) but there was no 5 second wait. Is delay() only used in effects?

I am not looking for solutions which involve setTimeout delayed execution of another function or a CPU hogging solution. I want a sleep() function which can be reused in different scripts.

Addition:

I didn't mean to suggest a solution which doesn't use setTimeout at all. I have seen solutions which required to move all code after where the delay is needed into its own function so that setTimeout can call it. I don't want that. Either a self contained wrapper function for using setTimeout or use jQuery delay() in a dummy non visual effect just for the purpose of simulating a sleep function.

答:
According to your question
How to use jQuery's delay() as a sleep()? , and to answer this:

I tried $().delay(5000) but there was no 5 second wait. Is delay()
  only used in effects?

Have you already tried jQuery.queue() with delay()?
for e.g.

$.fn.extend({
    changeBgColor: function(color) {
        return this.each(function() {
          $(this).css("background-color", color);
        });
    }
});
$.fn.wait = function(mls, callback) {
    return this.delay(mls).queue(function () {
      $("span").text($(this).queue().length);
      callback();
      $(this).dequeue();
    });
};

$(document).ready(function(){
    $("#start").click(function(){
        var div = $("div");

        div.delay(1000).queue(function () {
            $("span").text(div.queue().length);
            div.css("background-color", "red").text("red");
            $(this).dequeue();
        }).delay(1000).queue(function (next) {
            $("span").text(div.queue().length);
            div.changeBgColor("green").text("green");
            next();
        });

        div.wait(1000,function () {
            div.changeBgColor("yellow").text("yellow");
        }).wait(1000,function () {
            div.changeBgColor("blue").text("blue");
        });
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<p><button id="start">Start</button> <span></span></p>

<div style="display:inline-block;background:blue;height:100px;width:100px;"></div>
<div style="display:inline-block;background:blue;height:100px;width:100px;"></div>
</body>
</html></code>```

The queue() method allows you to create a queue of functions to be
  executed on selected elements. The dequeue() method executes them in
  order.

Body:
According to your question
How to use jQuery's delay() as a sleep()? , and to answer this:

I tried $().delay(5000) but there was no 5 second wait. Is delay()
  only used in effects?

Have you already tried jQuery.queue() with delay()?
for e.g.

$.fn.extend({
    changeBgColor: function(color) {
        return this.each(function() {
          $(this).css("background-color", color);
        });
    }
});
$.fn.wait = function(mls, callback) {
    return this.delay(mls).queue(function () {
      $("span").text($(this).queue().length);
      callback();
      $(this).dequeue();
    });
};

$(document).ready(function(){
    $("#start").click(function(){
        var div = $("div");

        div.delay(1000).queue(function () {
            $("span").text(div.queue().length);
            div.css("background-color", "red").text("red");
            $(this).dequeue();
        }).delay(1000).queue(function (next) {
            $("span").text(div.queue().length);
            div.changeBgColor("green").text("green");
            next();
        });

        div.wait(1000,function () {
            div.changeBgColor("yellow").text("yellow");
        }).wait(1000,function () {
            div.changeBgColor("blue").text("blue");
        });
    });
});

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<p><button id="start">Start</button>&nbsp;<span></span></p>

<div style="display:inline-block;background:blue;height:100px;width:100px;"></div>
<div style="display:inline-block;background:blue;height:100px;width:100px;"></div>
</body>
</html>

The queue() method allows you to create a queue of functions to be
  executed on selected elements. The dequeue() method executes them in
  order.


问:
casting from class to class c++
Suppose I declare classes like this:

foo.h

```<code>namespace foo
{
    class Data
    {
    public:
        void reatain();
        void release()
        {
            _refCnt--;
            if(_refCnt == 0) _alloc->dealloc(_data);
        }

        int _refCnt;
        Allocator *_alloc;
        void *_data;
    };

    class Example
    {
    public:
        // some functions

        Data *_data;
    };
}
</code>```

bar.h

```<code>namespace bar
{
    class Data
    {
        // declare the same with foo
    };

    class Example
    {
    public:
        // some functions

        /* except casting to foo::Example operator*/
        operator foo::Example() const
        {
            foo::Example fooex;
            fooex._data = reinterpret_cast<foo::Data *>(this->_data);
            return fooex;
        }
    };
}
</code>```

main.cpp

```<code>#include <foo.h>
#include <bar.h>

int main(void)
{
    bar::Example barex;
    foo::Example fooex = static_cast<foo::Example>(barex);

    // do smt

    return 0;
}
</code>```

All classes are compiled in the same host, arch, compiler, etc.

I'd like to know with this implementation, is there any hidden bug inside it.

When foo:Example is deallocated. foo think his Data * is foo::Data * but actually, it's bar::Data *. Then it calls _data->release().

I don't know if there's any problem if I implement like this

I don't know how the compiler does.

2 classes are declared the same. So, someday will they cause an error if bar::Data is used as foo:Data ?

答:
My opinion, the code is fragile, but should work.  I'm under the impression field ordering and packing is largely consistent, but I don't believe that's actually a C++ spec thing.

What is more factual, is traditional malloc/free run only off the pointer base address.  Also since you don't have a virtual destructor, your dealloc phase is simple enough to not be problematic.  I can't comment what effect RTTI might have, I never became knowledgable in that area but it's worth considering.

What's important to point out is that you haven't identified what alloc/dealloc you are using, so the "traditional" method may have no application to you at all.  My expectation is yours behaves traditionally.

Title: casting from class to class c++

Body:
Suppose I declare classes like this:

foo.h

namespace foo
{
    class Data
    {
    public:
        void reatain();
        void release()
        {
            _refCnt--;
            if(_refCnt == 0) _alloc->dealloc(_data);
        }

        int _refCnt;
        Allocator *_alloc;
        void *_data;
    };

    class Example
    {
    public:
        // some functions

        Data *_data;
    };
}

bar.h

namespace bar
{
    class Data
    {
        // declare the same with foo
    };

    class Example
    {
    public:
        // some functions

        /* except casting to foo::Example operator*/
        operator foo::Example() const
        {
            foo::Example fooex;
            fooex._data = reinterpret_cast<foo::Data *>(this->_data);
            return fooex;
        }
    };
}

main.cpp

#include <foo.h>
#include <bar.h>

int main(void)
{
    bar::Example barex;
    foo::Example fooex = static_cast<foo::Example>(barex);

    // do smt

    return 0;
}

All classes are compiled in the same host, arch, compiler, etc.

I'd like to know with this implementation, is there any hidden bug inside it.

When foo:Example is deallocated. foo think his Data * is foo::Data * but actually, it's bar::Data *. Then it calls _data->release().

I don't know if there's any problem if I implement like this

I don't know how the compiler does.

2 classes are declared the same. So, someday will they cause an error if bar::Data is used as foo:Data ?


问:
How to display text stored in firebase in android?
I am writing a code for displaying the images about the different cities that my company lets the user visits. I want to display the information about what you are gonna do and travelling to the places in the company's list. I have uploaded the information using a text file in firebase storage. And when I click on my activity, I want to display the information using the text file stored in the firebase. I am not able to do so. I have tried using images and have fetched the images from firebase, but I am still not able to fetch text file. How should I do it?</p>

答:
Hello Hope my Answer helps you

first thing is to upload any text into the json format in the realtime data base for example

let me show you how you can do

firebase console
  1) go to database tab
  2)select rules
  change them to

```<code>{
      "rules": {
        ".read": true,
        ".write": true
      }
    }
</code>```

go to data tab create a json like

```<code>{
      "citydetails" : [ null, {
        "city" : "vizag",
        "image" : "https://firebasestorage.googleapis.com/v0/b/technews-66882.appspot.com/o/techcrunch.png?alt=media&token=fb57c272-be17-459d-aa28-e14f671e7e4f",
        "link" : "https://google.com/",
        "discription" : "some text here"
      }, {
        "city" : "visakhapatnam",
        "image" : "https://firebasestorage.googleapis.com/v0/b/technews-66882.appspot.com/o/thenextweb.png?alt=media&token=7d7c2e44-5fd5-430d-b800-521fc6a57014",
        "link" : "http://google.com/",
        "discription" : "some text here"
      }
    ]}
</code>```

this screen shot helps you to create json in firebase

this is screen shot create city json object in your case

coming to the code in activity

```<code>FirebaseDatabase firebaseDatabase;
 DatabaseReference reference;

firebaseDatabase.getInstance();
        reference=firebaseDatabase.getInstance().getReference("citydetails");
</code>```

created separate method for better understanding:

```<code> private void Traillistners(DatabaseReference databaseReference){
        databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d("checksnap",""+dataSnapshot);
                for(DataSnapshot objects:dataSnapshot.getChildren()){
              // log will shows your result
                Log.d("showdetails",""+objects);
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {

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

call the method to oncreate method thats it

adding images into firebase storage
  upload image
  after uploading  to storage

click on image you can see the file location drop down
copy the image location given and set into json

Body:
Hello Hope my Answer helps you

first thing is to upload any text into the json format in the realtime data base for example

let me show you how you can do

firebase console
  1) go to database tab
  2)select rules
  change them to

{
      "rules": {
        ".read": true,
        ".write": true
      }
    }

go to data tab create a json like

{
      "citydetails" : [ null, {
        "city" : "vizag",
        "image" : "https://firebasestorage.googleapis.com/v0/b/technews-66882.appspot.com/o/techcrunch.png?alt=media&token=fb57c272-be17-459d-aa28-e14f671e7e4f",
        "link" : "https://google.com/",
        "discription" : "some text here"
      }, {
        "city" : "visakhapatnam",
        "image" : "https://firebasestorage.googleapis.com/v0/b/technews-66882.appspot.com/o/thenextweb.png?alt=media&token=7d7c2e44-5fd5-430d-b800-521fc6a57014",
        "link" : "http://google.com/",
        "discription" : "some text here"
      }
    ]}

this screen shot helps you to create json in firebase

this is screen shot create city json object in your case

coming to the code in activity

FirebaseDatabase firebaseDatabase;
 DatabaseReference reference;

firebaseDatabase.getInstance();
        reference=firebaseDatabase.getInstance().getReference("citydetails");

created separate method for better understanding:

 private void Traillistners(DatabaseReference databaseReference){
        databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d("checksnap",""+dataSnapshot);
                for(DataSnapshot objects:dataSnapshot.getChildren()){
              // log will shows your result
                Log.d("showdetails",""+objects);
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }

call the method to oncreate method thats it

adding images into firebase storage
  upload image
  after uploading  to storage

click on image you can see the file location drop down
copy the image location given and set into json


答:
Ionic2

It would be better to share some code. But I will try to answer the question as I got it.

If you created your app with ionic-cli then you will find in the file app.component.ts  the class MyApp. There is a line where the rootPage is set. All you need to do is to change the value of the rootPage to the Class of the page you want to open when your app starts.

```<code>rootPage: any = LoginPage;
</code>```

Please remember to do the following:

Import the target page in the app.component.ts.

Add the page to the declarations and entryComponents  in the NgModule decoration in the file app.module.ts

Title: Starting HTML Template when app loads

Body:
Noob question here. I am very new to using angular and ionic. I am building an app for a course and I started by using a tutorial and I have just been changing things until it becomes the app I want.

I want to change the initial html page that gets loaded when you run the app. Where do I set this?

Sorry! I am aware that this is probably super obvious but I can't seem to figure it out!

Body:
Ionic2

It would be better to share some code. But I will try to answer the question as I got it.

If you created your app with ionic-cli then you will find in the file app.component.ts  the class MyApp. There is a line where the rootPage is set. All you need to do is to change the value of the rootPage to the Class of the page you want to open when your app starts.

rootPage: any = LoginPage;

Please remember to do the following:

Import the target page in the app.component.ts.

Add the page to the declarations and entryComponents  in the NgModule decoration in the file app.module.ts


问:
Multiple jquery ajax on page not working
I've got 2 ajax requests on one page. Both work fine on separate pages, but when they're both on the same page, one stops working after the first has been run.

I'm using the Colorbox plugin for one request and this works fine. The other I've put together myself (I'm new to jquery, so may well have errors) and works if I run it first. But once Colorbox has been activated it stops working.

The page is here: http://dev.thetram.net/times/test2.php and the code below.

Would really appreciate some pointers to where I'm going wrong, thanks!

```<code><script type="text/javascript">
<!--
$(document).ready(function(){

$(function() {
$('#parkride').change(function () {

$.ajax({
    type: "POST",
 url: "http://dev.thetram.net/inc/parkingfinder_script.asp",
 dataType: "application/x-www-form-urlencoded",
 data: "Action=GetPR&Val=" + $("#parkride").val(),
 async: false,
 success: function(msg) {
     $('#output').html("<li>" + msg + "</li>");
 }
 });
return false;
    });
  });

$(function() {
//if submit button is clicked
$('form#frm_journeyplanner #submit').click(function () {

//get form values
var str = $("form#frm_journeyplanner").serialize();

$.ajax({
    type: "POST",
    url: "http://dev.thetram.net/inc/journeyplanner/jp_testscript.asp",
 dataType: "application/x-www-form-urlencoded",
    data: str,
 async: false,
 success: function(msg) {
  $('#results').html(msg);
  $.colorbox({inline:true, href:"#results", opacity:0.6, innerWidth:620, innerHeight:580, title:"Find tram times",
  onOpen:function(){  $("#results").show(); }, //make sure results show in the modal window
  onClosed:function(){ $("#results").hide(); } //stop results from displaying on the main page
   });
 }
 });
return false;
    });
  });

}); // end of doc ready
-->
</script>
</code>```

答:
You did not say which script isn't working.

I'll assume it's the one attached to the #parkride. If so, that one works just fine for me in Chrome 9 (dev).


问:
Why does numpy+mkl make it so my object is not iterable?
This code worked to "gather" all of my text data before installing scipy:

```<code>#load a list with the filenames in root folder with .Spectrum extensions, stripping only the absorbance values
Spectral_Output = []
for file in glob.glob("*.Spectrum"):
    Spectral_Output.append(
        numpy.loadtxt(file, skiprows=1, usecols=(1)))

#convert to a numpy array and print dimensions
spectral_data = numpy.asarray(Spectral_Output)
print(spectral_data.shape)

#take only column 26 or the values for 2268; print stuff
Absorbance2268 = spectral_data[:, 25]
</code>```

I then wanted to run a regression stats.linregress(x,y) on another concentration array, so I installed Scipy.

For some reason pip won't intsall scipy on Windows, so i installed
numpy-1.11.3+mkl-cp27-cp27m-win32.whl
and
scipy-0.19.0-cp27-cp27m-win32.whl
from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ as recommended by scipy's site

Now, the code throws this error:

```<code>Traceback (most recent call last):
  File "C:\Spectrometer\Spectrometer\0330\Spectrum.py", line 31, in <module>
    numpy.loadtxt(file, skiprows=1, usecols=(1)))
  File "C:\Python27\lib\site-packages\numpy\lib\npyio.py", line 790, in loadtxt
    usecols = list(usecols)
TypeError: 'int' object is not iterable
</code>```

I am so out of my league. ANY help would be greatly appreciated.

答:
your tuple of columns only has one element, so you need a trailing comma, otherwise it won't be interpreted as an iterable:

numpy.loadtxt(file, skiprows=1, usecols=(1,)))

In numpy 1.11, an integer value for usecols is not permitted, unlike in the latest version. You likely down-versioned when you installed the whl.

Body:
This code worked to "gather" all of my text data before installing scipy:

#load a list with the filenames in root folder with .Spectrum extensions, stripping only the absorbance values
Spectral_Output = []
for file in glob.glob("*.Spectrum"):
    Spectral_Output.append(
        numpy.loadtxt(file, skiprows=1, usecols=(1)))

#convert to a numpy array and print dimensions
spectral_data = numpy.asarray(Spectral_Output)
print(spectral_data.shape)

#take only column 26 or the values for 2268; print stuff
Absorbance2268 = spectral_data[:, 25]

I then wanted to run a regression stats.linregress(x,y) on another concentration array, so I installed Scipy.

For some reason pip won't intsall scipy on Windows, so i installed
numpy-1.11.3+mkl-cp27-cp27m-win32.whl
and
scipy-0.19.0-cp27-cp27m-win32.whl
from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ as recommended by scipy's site

Now, the code throws this error:

Traceback (most recent call last):
  File "C:\Spectrometer\Spectrometer\0330\Spectrum.py", line 31, in <module>
    numpy.loadtxt(file, skiprows=1, usecols=(1)))
  File "C:\Python27\lib\site-packages\numpy\lib\npyio.py", line 790, in loadtxt
    usecols = list(usecols)
TypeError: 'int' object is not iterable

I am so out of my league. ANY help would be greatly appreciated.


问:
Mock a dependency of a React component using Jest
I have a react component (CreateForm). The React component depends on a module (Store). The CreateForm has a Cancel button. On clicking the cancel button, the handleCancel function of the Store module should be called.

I wrote a test unsuccessfully using Jest:

```<code>test.only('should handle cancel button click', () => {
    jest.mock('../../src/store');
    const store = require('../../src/store');
    const wrapper = shallow(<CreateForm />);
    const cancelButton = wrapper.find('button').at(1);
    cancelButton.simulate('click');
    expect(store.default.handleCancel).toBeCalled();
});
</code>```

The test failed. The mock function did not get called and the test failed. Does the react component not get this version of the mock? If so, how do I fix the test? Thanks.

My CreateForm component looks something like the below:

```<code>import Store from './store';

render() {
   return (
     <Panel>
       <FormControls />
       <button onClick={Store.create}>Create</button>
       <button onClick={Store.handleCancel}>Cancel</button>
    </Panel>
  );
}
</code>```

A second improvised test that works for me is shown below.

```<code>test.only('should handle cancel button click', () => {
  const store = require('../../src/store').default;
  const cancel = store.handleCancel;
  store.handleCancel = jest.fn();

  const wrapper = shallow(<CreateForm />);
  const cancelButton = wrapper.find('button').at(1);
  cancelButton.simulate('click');
  expect(store.handleCancel).toBeCalled();

  store.handleCancel = cancel;
});
</code>```

The above test works. I am manually mocking the function, doing the test and restoring the function back to its original after the test. Is there a better way or Jest way of writing the above test? Thanks.

答:
You forgot to tell jest how to mock the store module, in your case it is just undefined.

```<code>const store = require('../../src/store');
jest.mock('../../src/store', () =>({
 handleCancel: jest.fn()
}));

test.only('should handle cancel button click', () => {
    const wrapper = shallow(<CreateForm />);
    const cancelButton = wrapper.find('button').at(1);
    cancelButton.simulate('click');
    expect(store.default.handleCancel).toBeCalled();//I'm not sure about the default here
});
</code>```

With this solution you tell jest to mock the store with an object that has the handleCancel function which is a jest spy. On this spy you can then test that it was called.

Body:
I have a react component (CreateForm). The React component depends on a module (Store). The CreateForm has a Cancel button. On clicking the cancel button, the handleCancel function of the Store module should be called.

I wrote a test unsuccessfully using Jest:

test.only('should handle cancel button click', () => {
    jest.mock('../../src/store');
    const store = require('../../src/store');
    const wrapper = shallow(<CreateForm />);
    const cancelButton = wrapper.find('button').at(1);
    cancelButton.simulate('click');
    expect(store.default.handleCancel).toBeCalled();
});

The test failed. The mock function did not get called and the test failed. Does the react component not get this version of the mock? If so, how do I fix the test? Thanks.

My CreateForm component looks something like the below:

import Store from './store';

render() {
   return (
     <Panel>
       <FormControls />
       <button onClick={Store.create}>Create</button>
       <button onClick={Store.handleCancel}>Cancel</button>
    </Panel>
  );
}

A second improvised test that works for me is shown below.

test.only('should handle cancel button click', () => {
  const store = require('../../src/store').default;
  const cancel = store.handleCancel;
  store.handleCancel = jest.fn();

  const wrapper = shallow(<CreateForm />);
  const cancelButton = wrapper.find('button').at(1);
  cancelButton.simulate('click');
  expect(store.handleCancel).toBeCalled();

  store.handleCancel = cancel;
});

The above test works. I am manually mocking the function, doing the test and restoring the function back to its original after the test. Is there a better way or Jest way of writing the above test? Thanks.

Body:
You forgot to tell jest how to mock the store module, in your case it is just undefined.

const store = require('../../src/store');
jest.mock('../../src/store', () =>({
 handleCancel: jest.fn()
}));

test.only('should handle cancel button click', () => {
    const wrapper = shallow(<CreateForm />);
    const cancelButton = wrapper.find('button').at(1);
    cancelButton.simulate('click');
    expect(store.default.handleCancel).toBeCalled();//I'm not sure about the default here
});

With this solution you tell jest to mock the store with an object that has the handleCancel function which is a jest spy. On this spy you can then test that it was called.


问:
Entity Framework - DB-First - Composite Foreign Keys
I have a database that has a table with a 2-column primary composite key (one int, one bigint.)  I have two tables that have a composite foreign key, referencing the first table's composite primary key.  The relationships are (as far as I know,) fine and dandy on the database itself.

When generating a DB context via DB-first EF6, these relationships/navigation properties are not represented in the generated models (No virtual members in the two child tables referencing the parent table.)

Since it's db-first, I can't modify the models.

答: In this case you can put those relationships into the onmodelcreating function in db context. We can put constraint there. </p>


问:
How to get focus of textarea in dotnetbrowser?
I am looking through the samples and I have got solution for focusing on dom element using tab.I am trying to focus on textarea which is on site,
so i had used virtual Tab key press to find that particular textarea and its working correctly.
But can anyone suggest how to directly focus on textarea. I also used excuteJavascript function but its not working.</p>

答: DotNetBrowser DOM API provides two methods: DOMElement.Focus() and DOMElement.Blur(). This functionality allows you to request focus on particular HTML DOM element.


问:
Using tensorboard with Jupyter notebooks
I'm trying to send some values to tensorboard from Jupyter notebook

```<code>with tf.Session() as sess:
    param = tf.Variable(0.1)
    param_summary = tf.scalar_summary("param", param)
    merge_op = tf.merge_all_summaries()
    writer = tf.train.SummaryWriter("/tmp/tflogs/test_tb", sess.graph)

    init = tf.initialize_all_variables()
    sess.run(init)

    for i in range(10):
        ass = tf.assign(param, i*0.5)
        sess.run(ass)
        mo = sess.run(merge_op) # Fails with "Duplicate tag param found in summary inputs" message
        writer.add_summary(mo,i)
        writer.flush()
</code>```

The problem is that it fails after the first run with InvalidArgumentError: Duplicate tag param found in summary inputs message (full text here: http://pastebin.com/dTBdCkHc)

How do I make it work with consequent runs?

答:
You could try this

First cell, only run once. This is where you create your graph.

```<code>sess = tf.Session()
param = tf.Variable(0.1)
param_summary = tf.scalar_summary("param", param)
merge_op = tf.merge_all_summaries()
writer = tf.train.SummaryWriter("/tmp/tflogs/test_tb", sess.graph)
</code>```

Second cell, run as many times as you want. This is where you initialize and run your graph (you could also not run the initialization operation every time). You will be writing the summaries to the same tensorboard file every time unless you use a new writer.

```<code>init = tf.global_variables_initializer() #tf.initialize_all_variables() is deprecated
sess.run(init)

for i in range(10):
    ass = tf.assign(param, i*0.5)
    sess.run(ass)
    mo = sess.run(merge_op) # Fails with "Duplicate tag param found in summary inputs" message
    writer.add_summary(mo,i)
    writer.flush()
</code>```

What is happening is that with every call to your cell you are adding a new variable and summary to the graph, duplicating the names of the summary, causing an error. tf.reset_default_graph() also works because it removes all the nodes and then you can create them again, but this is not needed.

Body:
I'm trying to send some values to tensorboard from Jupyter notebook

with tf.Session() as sess:
    param = tf.Variable(0.1)
    param_summary = tf.scalar_summary("param", param)
    merge_op = tf.merge_all_summaries()
    writer = tf.train.SummaryWriter("/tmp/tflogs/test_tb", sess.graph)

    init = tf.initialize_all_variables()
    sess.run(init)

    for i in range(10):
        ass = tf.assign(param, i*0.5)
        sess.run(ass)
        mo = sess.run(merge_op) # Fails with "Duplicate tag param found in summary inputs" message
        writer.add_summary(mo,i)
        writer.flush()

The problem is that it fails after the first run with InvalidArgumentError: Duplicate tag param found in summary inputs message (full text here: http://pastebin.com/dTBdCkHc)

How do I make it work with consequent runs?

Body:
You could try this

First cell, only run once. This is where you create your graph.

sess = tf.Session()
param = tf.Variable(0.1)
param_summary = tf.scalar_summary("param", param)
merge_op = tf.merge_all_summaries()
writer = tf.train.SummaryWriter("/tmp/tflogs/test_tb", sess.graph)

Second cell, run as many times as you want. This is where you initialize and run your graph (you could also not run the initialization operation every time). You will be writing the summaries to the same tensorboard file every time unless you use a new writer.

init = tf.global_variables_initializer() #tf.initialize_all_variables() is deprecated
sess.run(init)

for i in range(10):
    ass = tf.assign(param, i*0.5)
    sess.run(ass)
    mo = sess.run(merge_op) # Fails with "Duplicate tag param found in summary inputs" message
    writer.add_summary(mo,i)
    writer.flush()

What is happening is that with every call to your cell you are adding a new variable and summary to the graph, duplicating the names of the summary, causing an error. tf.reset_default_graph() also works because it removes all the nodes and then you can create them again, but this is not needed.


问:
Nuget Hint Path fails to restore
I have a project

```<code>sln
- Folder1
  - MyProj.csproj

-..Other projects and folders
</code>```

I add a nuget package to 'MyProj', which results in the following in the csproj

```<code><Reference Include="ANUGETPACKAGE, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL">
  <HintPath>..\..\packages\ANUGETPACKAGE.2.0.0\lib\net35\ANUGETPACKAGE.dll</HintPath>
  <Private>True</Private>
</Reference>
</code>```

Then I merge that code into my 'Main' branch which has the same structure setup as Development. The reference is now broken. Nuget fails to restore and fix the reference. I uninstall and re-install package and it results in the same except for:

```<code><HintPath>packages\ANUGETPACKAGE.2.0.0\lib\net35\ANUGETPACKAGE.dll</HintPath>
</code>```

How can I be sure that the path to the package will work in both branches?
(VS2015 Update 2, Nuget 3.4.0)

答:
The reference is now broken. Nuget fails to restore and fix the reference

This is because the relative path of the package are different in the both branches, the HintPath will be different, then the reference was broken.

How can I be sure that the path to the package will work in both branches?

If you want to make sure the path of the package will work in both branches, you could define a absolute path of repositoryPath in the NuGet.config in both branches. You can following the below steps to set it:

Right click on the solution->Add->New Item...

Select the Text file and rename to NuGet.config

Add content like this inside the NuGet.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <add key="repositoryPath" value="C:\packages" />
  </config>
</configuration>

Then reboot Visual Studio and it should work. The path to the package will work in both branches.

Hope this can help you.

Title: Nuget Hint Path fails to restore

Body:
I have a project

sln
- Folder1
  - MyProj.csproj

-..Other projects and folders

I add a nuget package to 'MyProj', which results in the following in the csproj

<Reference Include="ANUGETPACKAGE, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL">
  <HintPath>..\..\packages\ANUGETPACKAGE.2.0.0\lib\net35\ANUGETPACKAGE.dll</HintPath>
  <Private>True</Private>
</Reference>

Then I merge that code into my 'Main' branch which has the same structure setup as Development. The reference is now broken. Nuget fails to restore and fix the reference. I uninstall and re-install package and it results in the same except for:

<HintPath>packages\ANUGETPACKAGE.2.0.0\lib\net35\ANUGETPACKAGE.dll</HintPath>

How can I be sure that the path to the package will work in both branches?
(VS2015 Update 2, Nuget 3.4.0)


问:
Pagination MYSQL count vs PHP count and array_slice
I have a search query which looks for matching values from a search table and returns all possible entries matching the keywords. I did not write the search, it's something that already existed and we're porting it to another framework. Anyway, that's not the point.

What I want is to execute a MySQL query (InnoDB), using LIMIT, and have the COUNT of all results at my disposal for pagination (to calculate number of total pages). I assumed using LIMIT has some effect on the speed but after measuring execution time it doesn't seem to have much (atleast in this case).

The problem:

Using a separate query to COUNT rows (just count) takes as much time as the real query. In this case approximately 11 seconds so the entire execution is about 22 seconds.

```<code>// Fetch Count approximately 11 seconds
SELECT COUNT(id) FROM table WHERE ...

// Fetch All approximately 11 seconds
SELECT id, name FROM table WHERE ...
</code>```

Another method I used was to just search without LIMIT and then use PHP's own count() function to get the number of results I got, then array_slice() to limit the number of entries for the page. This actually proved to be faster as the query took about 12 seconds and PHP a fraction of a second. So it's about half.

```<code>// Fetch All approximately 11-12 seconds
$results = SELECT id, name FROM table WHERE ...
// PHP count and slice took a fraction of a second
$count = count($results);
$results = array_slice($results, $page, $limit);
</code>```

I also tried to use COUNT inside the first LIMIT query so I wouldn't have to use a separate query for it but it seems PDO's own fetchAll returns variating results in each array entry. What I got was 2, 1,  1, 1...

```<code>SELECT COUNT(id) as `count`, id, name FROM table WHERE ...
</code>```

The question:

What is the fastest way to actually query results for pagination having the results and result count at your disposal?

答:
Second option is not an option at all.

On the other hand, 11 seconds is still absolutely unacceptable. So, to make your code proper, you have to optimize the search query. This should be your goal and concern.

Body:
I have a search query which looks for matching values from a search table and returns all possible entries matching the keywords. I did not write the search, it's something that already existed and we're porting it to another framework. Anyway, that's not the point.

What I want is to execute a MySQL query (InnoDB), using LIMIT, and have the COUNT of all results at my disposal for pagination (to calculate number of total pages). I assumed using LIMIT has some effect on the speed but after measuring execution time it doesn't seem to have much (atleast in this case).

The problem:

Using a separate query to COUNT rows (just count) takes as much time as the real query. In this case approximately 11 seconds so the entire execution is about 22 seconds.

// Fetch Count approximately 11 seconds
SELECT COUNT(id) FROM table WHERE ...

// Fetch All approximately 11 seconds
SELECT id, name FROM table WHERE ...

Another method I used was to just search without LIMIT and then use PHP's own count() function to get the number of results I got, then array_slice() to limit the number of entries for the page. This actually proved to be faster as the query took about 12 seconds and PHP a fraction of a second. So it's about half.

// Fetch All approximately 11-12 seconds
$results = SELECT id, name FROM table WHERE ...
// PHP count and slice took a fraction of a second
$count = count($results);
$results = array_slice($results, $page, $limit);

I also tried to use COUNT inside the first LIMIT query so I wouldn't have to use a separate query for it but it seems PDO's own fetchAll returns variating results in each array entry. What I got was 2, 1,  1, 1...

SELECT COUNT(id) as `count`, id, name FROM table WHERE ...

The question:

What is the fastest way to actually query results for pagination having the results and result count at your disposal?


问:
Use ggplot2 to plot multiple curves
Say I have a data frame coefs where each row contains model coefficients for a curve.

```<code>coefs <- structure(list(a1 = c(1.22228259789383, 1.2064168157394, 1.09555089661994, 0.943947433470916, 0.883490658557721, 0.46125552320107), d = c(0.385227755933488, 0.457271644919152, 0.340063262461958, 0.305629949064525, 0.42459163183877, 0.425710112988664), g = c(0, 0, 0, 0, 0, 0), u = c(1, 1, 1, 1, 1, 1)), .Names = c("a1", "d", "g", "u"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L))
</code>```

I'd like to use each row of the data frame to add a new curve to the plot based a defined function: (you may recognize it as a 2PL item response model)

```<code>TWOPL <- function(x,a1,b) {
  1 / (1 + exp(-a1*(x-(b))))
}
</code>```

Based on this and this question I tried the following ggplot command but get the error that computation failed:

```<code>library(ggplot2)
p <- ggplot(coefs, aes(x = 0))
p + stat_function(fun = TWOPL) + xlim(-5,5)
</code>```

I know that I need a way to give the various coefficients to the function. As a test, I tried the function with a fixed parameters to create 1 curve and it works, for example:

```<code>#1 curve based on fixed parameters
TWOPL_copy <- function(x) {
  1 / (1 + exp(-1.22*(x-(.385))))
}

p <- ggplot(data.frame(x = 0), aes(x = 0))
p + stat_function(fun = TWOPL_copy) + xlim(-5,5)
</code>```

I'm wondering how I might send each row of the data frame to ggplot. An ideal next step would be to differentiate the colors of each line somehow.

答:
While you could call stat_function for each set of parameters or with some pain call it programmatically, it's simpler to do the calculations yourself:

library(tidyverse)

coefs %>%
    mutate(curve = letters[row_number()]) %>%    # add curve name
    crossing(x = seq(-5, 5, .1)) %>%    # repeat each row for every occurence of x
    mutate(y = TWOPL(x, a1, d)) %>%    # compute y values
    ggplot(aes(x, y, color = curve)) +
    geom_line()
```

<p><img src="https://i.imgur.com/bfCRab7.png" alt=""></p>

<p>The simplest way to create the curves programmatically is to add a list of <code>stat_function</code> calls to the plot. All aesthetics have to be iterated across, including color. An <code>x</code> aesthetic must be supplied, but if you set <code>xlim</code>, it doesn't matter what it is.</p>

<pre class="lang-r prettyprint-override"><code>curves <- coefs %>%
    mutate(curve = letters[row_number()]) %>%
    pmap(function(...){
             dots <- data_frame(...)
             stat_function(data = dots, aes(0, color = curve),
                           fun = function(x) TWOPL(x, dots$a1, dots$d),
                           xlim = c(-5, 5))
    })

ggplot() + curves
</code>```

Title: Use ggplot2 to plot multiple curves

Body:
Say I have a data frame coefs where each row contains model coefficients for a curve.

coefs <- structure(list(a1 = c(1.22228259789383, 1.2064168157394, 1.09555089661994, 0.943947433470916, 0.883490658557721, 0.46125552320107), d = c(0.385227755933488, 0.457271644919152, 0.340063262461958, 0.305629949064525, 0.42459163183877, 0.425710112988664), g = c(0, 0, 0, 0, 0, 0), u = c(1, 1, 1, 1, 1, 1)), .Names = c("a1", "d", "g", "u"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L))

I'd like to use each row of the data frame to add a new curve to the plot based a defined function: (you may recognize it as a 2PL item response model)

TWOPL <- function(x,a1,b) {
  1 / (1 + exp(-a1*(x-(b))))
}

Based on this and this question I tried the following ggplot command but get the error that computation failed:

library(ggplot2)
p <- ggplot(coefs, aes(x = 0))
p + stat_function(fun = TWOPL) + xlim(-5,5)

I know that I need a way to give the various coefficients to the function. As a test, I tried the function with a fixed parameters to create 1 curve and it works, for example:

#1 curve based on fixed parameters
TWOPL_copy <- function(x) {
  1 / (1 + exp(-1.22*(x-(.385))))
}

p <- ggplot(data.frame(x = 0), aes(x = 0))
p + stat_function(fun = TWOPL_copy) + xlim(-5,5)

I'm wondering how I might send each row of the data frame to ggplot. An ideal next step would be to differentiate the colors of each line somehow.

Body:
While you could call stat_function for each set of parameters or with some pain call it programmatically, it's simpler to do the calculations yourself:

library(tidyverse)

coefs %>%
    mutate(curve = letters[row_number()]) %>%    # add curve name
    crossing(x = seq(-5, 5, .1)) %>%    # repeat each row for every occurence of x
    mutate(y = TWOPL(x, a1, d)) %>%    # compute y values
    ggplot(aes(x, y, color = curve)) +
    geom_line()

The simplest way to create the curves programmatically is to add a list of stat_function calls to the plot. All aesthetics have to be iterated across, including color. An x aesthetic must be supplied, but if you set xlim, it doesn't matter what it is.

curves <- coefs %>%
    mutate(curve = letters[row_number()]) %>%
    pmap(function(...){
             dots <- data_frame(...)
             stat_function(data = dots, aes(0, color = curve),
                           fun = function(x) TWOPL(x, dots$a1, dots$d),
                           xlim = c(-5, 5))
    })

ggplot() + curves


问:
Jquery custom trigger anchor tag
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html></code>```

答:
$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        var secAttr = $(this).next('li').children().attr("href");
        $('a[href="' + secAttr + '"]').tab('show');
        return false;
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html></code>```

Title: Jquery custom trigger anchor tag

Body:
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});

<!DOCTYPE html>

  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Home

Menu 1

Menu 2

Menu 3

HOME

      Form 1

Menu 1

      Form 2

Menu 2

      Form 3

Menu 3

      Form 4

  <button id="nextBtn">Next</button>

Body:
$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        var secAttr = $(this).next('li').children().attr("href");
        $('a[href="' + secAttr + '"]').tab('show');
        return false;
      }
    });
  });
});

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active"><a data-toggle="pill" href="#home">Home</a></li>
    <li><a data-toggle="pill" href="#menu1">Menu 1</a></li>
    <li><a data-toggle="pill" href="#menu2">Menu 2</a></li>
    <li><a data-toggle="pill" href="#menu3">Menu 3</a></li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html>


问:
Prolog code to split parts of a list into consecutive even and odd parts
I've been given the following question:

Any list of integers can (uniquely) be broken into "parity runs" where each run is a (maximal) sequence of consecutive even or odd numbers within the original list. For example, the list
List = [8,0,4,3,7,2,-1,9,9]
can be broken into [8, 0, 4], [3, 7], [2] and [-1, 9, 9]
Write a predicate paruns(List, RunList) that converts a list of numbers into the corresponding list of parity runs. For example:

```<code>?- paruns([8,0,4,3,7,2,-1,9,9], RunList).
RunList = [[8, 0, 4], [3, 7], [2], [-1, 9, 9]]
</code>```

Here was the code which I tried and it seems to work with the above sample case, thanks to one suggestion, but I've got an issue where when I run paruns([8,0,4], RunList). it prints RunList = [[8,0,4],[]]. Any suggestions would be appreciated :)

```<code>paruns([],[]).
paruns([Head | Tail], [E, O | S]) :-
   even([Head | Tail], E, Last),
   odd(Last, O, Last1),
   paruns(Last1, S).

even([Head | Tail], [], [Head | Tail]) :-
   Head mod 2 =:= 1.
even([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 0,
   even(Tail, L, Last).
even([],[],[]).

odd([Head | Tail], [], [Head, Tail]) :-
   Head mod 2 =:= 0.
odd([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 1,
   odd(Tail, L, Last).
odd([],[],[]).
</code>```

答:
I think you have just a typo, in the first odd/3 clause. With the following code

```<code>paruns([],[]).
paruns([Head | Tail], [E, O | S]) :-
   even([Head | Tail], E, Last),
   odd(Last, O, Last1),
   paruns(Last1, S).

even([Head | Tail], [], [Head | Tail]) :-
   Head mod 2 =:= 1.
even([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 0,
   even(Tail, L, Last).
even([],[],[]).

odd([Head | Tail], [], [Head | Tail]) :-  % corrected
   Head mod 2 =:= 0.
odd([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 1,
   odd(Tail, L, Last).
odd([],[],[]).
</code>```

I get

```<code>?- paruns([8,0,4,3,7,2,-1,9,9], RunList).
RunList = [[8, 0, 4], [3, 7], [2], [-1, 9, 9]]
</code>```

edit

A possibility to discard empty sequences (should occurs only at first or last position, I think... so maybe a better approach would be to sanitize the outcome for these cases):

```<code>paruns([],[]).
%paruns([Head | Tail], [E, O | S]) :-
paruns([Head | Tail], R) :-
   even([Head | Tail], E, Last),
   odd(Last, O, Last1),
    (E=[] -> R=[O|S] ; O=[] -> R=[E|S] ; R=[E,O|S]),
   paruns(Last1, S).
</code>```

Body:
I've been given the following question:

Any list of integers can (uniquely) be broken into "parity runs" where each run is a (maximal) sequence of consecutive even or odd numbers within the original list. For example, the list
List = [8,0,4,3,7,2,-1,9,9]
can be broken into [8, 0, 4], [3, 7], [2] and [-1, 9, 9]
Write a predicate paruns(List, RunList) that converts a list of numbers into the corresponding list of parity runs. For example:

?- paruns([8,0,4,3,7,2,-1,9,9], RunList).
RunList = [[8, 0, 4], [3, 7], [2], [-1, 9, 9]]

Here was the code which I tried and it seems to work with the above sample case, thanks to one suggestion, but I've got an issue where when I run paruns([8,0,4], RunList). it prints RunList = [[8,0,4],[]]. Any suggestions would be appreciated :)

paruns([],[]).
paruns([Head | Tail], [E, O | S]) :-
   even([Head | Tail], E, Last),
   odd(Last, O, Last1),
   paruns(Last1, S).

even([Head | Tail], [], [Head | Tail]) :-
   Head mod 2 =:= 1.
even([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 0,
   even(Tail, L, Last).
even([],[],[]).

odd([Head | Tail], [], [Head, Tail]) :-
   Head mod 2 =:= 0.
odd([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 1,
   odd(Tail, L, Last).
odd([],[],[]).

Body:
I think you have just a typo, in the first odd/3 clause. With the following code

paruns([],[]).
paruns([Head | Tail], [E, O | S]) :-
   even([Head | Tail], E, Last),
   odd(Last, O, Last1),
   paruns(Last1, S).

even([Head | Tail], [], [Head | Tail]) :-
   Head mod 2 =:= 1.
even([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 0,
   even(Tail, L, Last).
even([],[],[]).

odd([Head | Tail], [], [Head | Tail]) :-  % corrected
   Head mod 2 =:= 0.
odd([Head | Tail], [Head | L], Last) :-
   Head mod 2 =:= 1,
   odd(Tail, L, Last).
odd([],[],[]).

I get

?- paruns([8,0,4,3,7,2,-1,9,9], RunList).
RunList = [[8, 0, 4], [3, 7], [2], [-1, 9, 9]]

edit

A possibility to discard empty sequences (should occurs only at first or last position, I think... so maybe a better approach would be to sanitize the outcome for these cases):

paruns([],[]).
%paruns([Head | Tail], [E, O | S]) :-
paruns([Head | Tail], R) :-
   even([Head | Tail], E, Last),
   odd(Last, O, Last1),
    (E=[] -> R=[O|S] ; O=[] -> R=[E|S] ; R=[E,O|S]),
   paruns(Last1, S).


问:
R: ggplot heatmap color change
```<code>df.team_data <- expand.grid(teams = c("Team A", "Team B", "Team C", "Team D")
                           ,metrics = c("Metric 1", "Metric 2", "Metric 3", "Metric 4", "Metric 5")
                           )
set.seed(41)
df.team_data$performance <- sample(c(0, 1), 20, replace = TRUE)

head(df.team_data)
ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
  geom_tile(aes(fill = performance))
</code>```

I have a very simple heatmap with just two colors. How do I designate which colors are associated with the value of performance? For this, I would like performance of 1 to be dark blue, and performance of 0 to be light blue. Also, is there a way to change the legend to be binary?

答:
The values in the "performance" column of your data set is in "numeric" format.
Convert that in to a factor using factor() and your graph will have a binary legend:

```<code>df.team_data <- expand.grid(teams = c("Team A", "Team B", "Team C", "Team D")
                            ,metrics = c("Metric 1", "Metric 2", "Metric 3", "Metric 4", "Metric 5")
)
set.seed(41)
df.team_data$performance <- sample(c(0, 1), 20, replace = TRUE)

df.team_data$performance<-factor(df.team_data$performance)
head(df.team_data)
library(ggplot2)

ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
  geom_tile(aes(fill = performance))
</code>```

updated

```<code> col.plot<-c('lightblue','darkblue')
 ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
      geom_tile(aes(fill = performance))+scale_fill_manual(values=col.plot)
</code>```

change the values in col.plot as per your need

Title: R: ggplot heatmap color change

Body:
df.team_data <- expand.grid(teams = c("Team A", "Team B", "Team C", "Team D")
                           ,metrics = c("Metric 1", "Metric 2", "Metric 3", "Metric 4", "Metric 5")
                           )
set.seed(41)
df.team_data$performance <- sample(c(0, 1), 20, replace = TRUE)

head(df.team_data)
ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
  geom_tile(aes(fill = performance))

I have a very simple heatmap with just two colors. How do I designate which colors are associated with the value of performance? For this, I would like performance of 1 to be dark blue, and performance of 0 to be light blue. Also, is there a way to change the legend to be binary?

Body:
The values in the "performance" column of your data set is in "numeric" format.
Convert that in to a factor using factor() and your graph will have a binary legend:

df.team_data <- expand.grid(teams = c("Team A", "Team B", "Team C", "Team D")
                            ,metrics = c("Metric 1", "Metric 2", "Metric 3", "Metric 4", "Metric 5")
)
set.seed(41)
df.team_data$performance <- sample(c(0, 1), 20, replace = TRUE)

df.team_data$performance<-factor(df.team_data$performance)
head(df.team_data)
library(ggplot2)

ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
  geom_tile(aes(fill = performance))

updated

 col.plot<-c('lightblue','darkblue')
 ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
      geom_tile(aes(fill = performance))+scale_fill_manual(values=col.plot)

change the values in col.plot as per your need


问:
control array in xcode
I am quite new to Xcode and still do not know a lot of things Xcode can do. I wanna ask if Xcode or Objective-C uses Control Arrays like VB6.

edit: posted question on seperate page.
How to detect which label or image is selected when they are created dynamically

答:
If you are asking how to detect which label or image is selected which are created at runtime, then:

Assing tags to the labels/images while creating through code.

Write a method which will be invoked when a particular image/label is pressed.

Pass the id of the sender when invoking that method.

When the invoked method is called,write the code for a particular tag of an image or label (you can use switch case here).

That's it.

Title: control array in xcode

ContentLicense: CC BY-SA 4.0


答:
If you use scale_fill_gradient() and set several options regarding the colours for high and low values, I think you could get what you are after. Also you can set the breaks in your performance variable with breaks ().

Using your code I obtain the following:

```<code>df.team_data <- expand.grid(teams = c("Team A", "Team B", "Team C", "Team D")
                            ,metrics = c("Metric 1", "Metric 2", "Metric 3", "Metric 4", "Metric 5")
)

df.team_data$performance <- sample(c(0, 1), 20, replace = TRUE)

head(df.team_data)
ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
  geom_tile(aes(fill = performance)) + scale_fill_gradient('performance', limits=c(0, 1), breaks = c(0, 0.25, 0.5, 0.75, 1),  low = "lightblue", high = "darkblue")
</code>```

Title: R: ggplot heatmap color change

Body:
If you use scale_fill_gradient() and set several options regarding the colours for high and low values, I think you could get what you are after. Also you can set the breaks in your performance variable with breaks ().

Using your code I obtain the following:

df.team_data <- expand.grid(teams = c("Team A", "Team B", "Team C", "Team D")
                            ,metrics = c("Metric 1", "Metric 2", "Metric 3", "Metric 4", "Metric 5")
)

df.team_data$performance <- sample(c(0, 1), 20, replace = TRUE)

head(df.team_data)
ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
  geom_tile(aes(fill = performance)) + scale_fill_gradient('performance', limits=c(0, 1), breaks = c(0, 0.25, 0.5, 0.75, 1),  low = "lightblue", high = "darkblue")