问:
Promise then and catch in nodeJS
I'm having a problem with my nodejs server.

What I want is if an email exists in my db, I want to send an email to that address but if not, I want to send and error message to the client.

I have this controller:

```<code>reset(req, res) {
   return  this.service.getByEmail(req.body.email)
      .then(this.mapper.outputEmail.bind(this.mapper))
      .then(res.json.bind(res)).catch(res.send.bind(res));
  }
</code>```

I send the email in a post method. I use a service that calls my db looking for that email and I have this mapper:

```<code> outputEmail(outputEmail){
      return {
      email: outputEmail.email
    };
  }
</code>```

My service:

```<code>getByEmail(correo) {
    return this.db.find({
      where: { email: correo }
    });
  }
</code>```

My problem is that I don't know how to control if i get an empty json object.. If i send a post with an email that it doesnt exist i get a {} response, but if i send an exist email i get {email: erwrr@gmail.com}.

What i want is if i get an empty json, I just want to return an error saying that email doesnt exist, but if the query in the db gets a real email I want to continue executing another method that to send an email to that address.

答:
You are trying to determine if there is an email field on your JSON object. Just do:</p>

```<code>outputEmail(outputEmail){
    if(outputEmail.email){
        return {
            email: outputEmail.email
        };
    }else{
        throw new Error("No email found!");
    }
}
</code>```

Title: Promise then and catch in nodeJS

Body:
I'm having a problem with my nodejs server.

What I want is if an email exists in my db, I want to send an email to that address but if not, I want to send and error message to the client.

I have this controller:

reset(req, res) {
   return  this.service.getByEmail(req.body.email)
      .then(this.mapper.outputEmail.bind(this.mapper))
      .then(res.json.bind(res)).catch(res.send.bind(res));
  }

I send the email in a post method. I use a service that calls my db looking for that email and I have this mapper:

 outputEmail(outputEmail){
      return {
      email: outputEmail.email
    };
  }

My service:

getByEmail(correo) {
    return this.db.find({
      where: { email: correo }
    });
  }

My problem is that I don't know how to control if i get an empty json object.. If i send a post with an email that it doesnt exist i get a {} response, but if i send an exist email i get {email: erwrr@gmail.com}.

What i want is if i get an empty json, I just want to return an error saying that email doesnt exist, but if the query in the db gets a real email I want to continue executing another method that to send an email to that address.

Body:
You are trying to determine if there is an email field on your JSON object. Just do:

outputEmail(outputEmail){
    if(outputEmail.email){
        return {
            email: outputEmail.email
        };
    }else{
        throw new Error("No email found!");
    }
}


来源: stackexchange

问:
Change the textview's text using button click in Android
I want to change the text on a textView on button click. There can be multiple buttons in activity. The main purpose is to change the name of fruit on button click either any one button is clicked.
For example: Button 1 is clicked change the name, Button 2 is clicked next name, Button 3 is clicked next name and so on. I am trying as given below but the names are not changing.

Main Activity

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView sentence_etx;
    private Button btn_1,btn_2;
    private String[] names = { "Apple","Mango","Cherry","Banana","Extra"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sentence_etx = (TextView) findViewById(R.id.etx_sentence);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);

        for (int i=0;i<=names.length;i++) {
            work(i);
        }
    }

    private void work(final int i) {
            btn_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });

            btn_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });
    }
}
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.awais.test2.MainActivity">

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_marginTop="50dp"
            android:layout_marginRight="30dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/etx_sentence"
            android:text="Names......" />

        <LinearLayout
            android:gravity="center"
            android:layout_marginTop="100dp"
            android:layout_height="wrap_content"
            android:layout_width="match_parent">

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_1"
            android:text="1"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_2"
            android:text="2"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_3"
            android:text="3"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

答:
you only need to set OnClickListener once

```<code>public class MainActivity extends AppCompatActivity {

    private TextView sentence_etx;
    private Button btn_1,btn_2;
    private String[] names = { "Apple","Mango","Cherry","Banana","Extra"};
    private int curIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sentence_etx = (TextView) findViewById(R.id.etx_sentence);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);

        btn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curIndex == names.length - 1) {
                    curIndex = 0;
                }
                sentence_etx.setText(names[curIndex]);
                curIndex++;
            }
        });

        btn_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curIndex == names.length - 1) {
                    curIndex = 0;
                }
                sentence_etx.setText(names[curIndex]);
                curIndex++;
            }
        });
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to change the text on a textView on button click. There can be multiple buttons in activity. The main purpose is to change the name of fruit on button click either any one button is clicked.
For example: Button 1 is clicked change the name, Button 2 is clicked next name, Button 3 is clicked next name and so on. I am trying as given below but the names are not changing.

Main Activity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView sentence_etx;
    private Button btn_1,btn_2;
    private String[] names = { "Apple","Mango","Cherry","Banana","Extra"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sentence_etx = (TextView) findViewById(R.id.etx_sentence);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);

        for (int i=0;i<=names.length;i++) {
            work(i);
        }
    }

    private void work(final int i) {
            btn_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });

            btn_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.awais.test2.MainActivity">

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_marginTop="50dp"
            android:layout_marginRight="30dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/etx_sentence"
            android:text="Names......" />

        <LinearLayout
            android:gravity="center"
            android:layout_marginTop="100dp"
            android:layout_height="wrap_content"
            android:layout_width="match_parent">

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_1"
            android:text="1"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_2"
            android:text="2"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_3"
            android:text="3"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

Body:
you only need to set OnClickListener once

public class MainActivity extends AppCompatActivity {

    private TextView sentence_etx;
    private Button btn_1,btn_2;
    private String[] names = { "Apple","Mango","Cherry","Banana","Extra"};
    private int curIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sentence_etx = (TextView) findViewById(R.id.etx_sentence);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);

        btn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curIndex == names.length - 1) {
                    curIndex = 0;
                }
                sentence_etx.setText(names[curIndex]);
                curIndex++;
            }
        });

        btn_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curIndex == names.length - 1) {
                    curIndex = 0;
                }
                sentence_etx.setText(names[curIndex]);
                curIndex++;
            }
        });
    }

}


问:
Minifiying List of ranges as integer arrays
I have code like this

```<code>public List<int[]> getMinifiedRanges(List<int[]> ranges) {
    for (int[] range : ranges) {

    }
}
</code>```

My goal is to condense the list of ranges, represented by integer arrays which contain the ranges upper & lower bounds

ex. [100, 200] [250, 350] - this example would return the same input because nothing overlaps

[100, 200] [150, 350] [400, 500] - this would return [100, 350] [400, 500] because the second ranges lower bound is inclusive in the first range so the returned range would have its upper bound extended to 350 - notice how it returns only two arrays when the input was 3 arrays.

I am having trouble figuring out how to retrieve a previous range from a current range so that I could extend either the lower or upper bound.

答:
First you can split every range according to this form:

[a,b] range -> (a,1) and (b,2) pairs

Store these pair in a list then sort the list. After sorting you can iterate the list, when a pair like (x,1) comes increment a variable and when a pair like(x,2) comes decrement that variable. Places that varible went from 0 to 1 are starting indexes and places where variable went from 1 to 0 are finishing indexes.

Body:
I have code like this

public List<int[]> getMinifiedRanges(List<int[]> ranges) {
    for (int[] range : ranges) {

    }
}

My goal is to condense the list of ranges, represented by integer arrays which contain the ranges upper & lower bounds

ex. [100, 200] [250, 350] - this example would return the same input because nothing overlaps

[100, 200] [150, 350] [400, 500] - this would return [100, 350] [400, 500] because the second ranges lower bound is inclusive in the first range so the returned range would have its upper bound extended to 350 - notice how it returns only two arrays when the input was 3 arrays.

I am having trouble figuring out how to retrieve a previous range from a current range so that I could extend either the lower or upper bound.


问:
Receiving error when installing bootstrap-sass gem in my ruby on rails app
I've been learning Ruby on Rails for the last few days and i'm following tutorials from a book.
I'm working on an app which requires importing bootstrap however i'm having trouble installing it into my project.

I'm using Ruby version 2.3.1 and Rails version 5.1.1 and i'm using the cloud9 coding environment

I create a new app with the following command:

```<code>rails new bootstrap_app
</code>```

The next instruction is to "add the bootstrap gem to the gemfile" with the following command:

```<code>gem 'bootstrap‐sass' , '~> 3.3.6'
</code>```

I do this and I get the following error:

```<code>ERROR:  While executing gem ... (Gem::CommandLineError)
    Unknown command bootstrap-sass,
</code>```

I looked up this error and I found it on stackoverflow here however "restarting the server" didn't work in my case.

The next instruction in the tutorial, is the command

```<code>bundle install
</code>```

I do this and it tells me a list of dependencies that are installed (bootstrap is not listed)

I tried the command gem install bootstrap-sass and it said it installed the gem successfully however when i try to import bootstrap in my CSS file as follows:

```<code>@import "bootstrap‐sprockets" ;
@import "bootstrap";
</code>```

i get the following error:

```<code>ActionController::RoutingError (No route matches [GET] "/assets/bootstrap%E2%80%90sprockets"):
</code>```

any ideas on how i can get this working? Thanks

答:
As CD-RUM stated, you will need to add both the gem bootstrap-sass & gem sass-rails in to your Gemfile.  I would also suggest adding gem 'sprockets', '2.11.0' as well since the newer version of sprockets that comes with rails 5 has had some issues working well with Bootstrap. Then run bundle install.

You will also want to rename your application.css file to application.scss
and add the import files (@import "bootstrap-sprockets" & @import "bootstrap") there . Now restart your server.

Read through the Ruby on Rails installation instructions here: bootsrap-sass gem & if you're still having issues consider changing the version of the bootstrap-sass gem to an earlier version (I use gem 'bootstrap-sass', '~> 3.3.5.1') since some people seem to experience version conflicts.

Body:
I've been learning Ruby on Rails for the last few days and i'm following tutorials from a book.
I'm working on an app which requires importing bootstrap however i'm having trouble installing it into my project.

I'm using Ruby version 2.3.1 and Rails version 5.1.1 and i'm using the cloud9 coding environment

I create a new app with the following command:

rails new bootstrap_app

The next instruction is to "add the bootstrap gem to the gemfile" with the following command:

gem 'bootstrap‐sass' , '~> 3.3.6'

I do this and I get the following error:

ERROR:  While executing gem ... (Gem::CommandLineError)
    Unknown command bootstrap-sass,

I looked up this error and I found it on stackoverflow here however "restarting the server" didn't work in my case.

The next instruction in the tutorial, is the command

bundle install

I do this and it tells me a list of dependencies that are installed (bootstrap is not listed)

I tried the command gem install bootstrap-sass and it said it installed the gem successfully however when i try to import bootstrap in my CSS file as follows:

@import "bootstrap‐sprockets" ;
@import "bootstrap";

i get the following error:

ActionController::RoutingError (No route matches [GET] "/assets/bootstrap%E2%80%90sprockets"):

any ideas on how i can get this working? Thanks


问:
Shifting from turbo to Code::Blocks
I have been using turbo c++ but not I have shifted to Code::Blocks and facing following problems

clrscr() function of conio.h is not working.

Using void main() but it's still asking for return type.

getch() showing some error.

What should I do?

```<code> #include<iostream>
 #include<conio.h>

 Using namespace std;

 void main(){
     clrscr ();
     int x=10;
     cout<<"hi"<<x;
     getch();
 }
</code>```

答: The return type of main is int not void. You may also want to put return 0 at the end of main but that's not necessary. The other 2 functions aren't supported in code blocks so look for alternatives</p>

Title: Shifting from turbo to Code::Blocks

Body:
I have been using turbo c++ but not I have shifted to Code::Blocks and facing following problems

clrscr() function of conio.h is not working.

Using void main() but it's still asking for return type.

getch() showing some error.

What should I do?

 #include<iostream>
 #include<conio.h>

 Using namespace std;

 void main(){
     clrscr ();
     int x=10;
     cout<<"hi"<<x;
     getch();
 }


问:
How to sent a POST request with form-data and parameters in PL/SQL
I'm trying to call REST WebService in PL/SQL but it doesn't work. I get this error:

Content-type must be multipart/form-data

Here is what I have:

```<code>DECLARE
  req   UTL_HTTP.REQ;
  resp  UTL_HTTP.RESP;
  value VARCHAR2(1024);  -- URL to post to
  v_url VARCHAR2(200) := 'http://local/api/ws';
  -- Post Parameters
  v_param VARCHAR2(500) := 'art=11111\&qty=1';
  v_param_length NUMBER := length(v_param);
BEGIN
  req := UTL_HTTP.BEGIN_REQUEST (url=> v_url, method => 'POST');
  UTL_HTTP.SET_HEADER(req, 'User-Agent', 'Mozilla/4.0');
  UTL_HTTP.SET_HEADER (r      =>  req,
                       name   =>  'Content-Type',
                       value  =>  'multipart/form-data; charset=utf-8; boundary=/');
  UTL_HTTP.SET_HEADER (r      =>   req,
                       name   =>   'Content-Length',
                       value  =>   v_param_length);
  UTL_HTTP.WRITE_TEXT (r      =>   req,
                       data   =>   v_param);

     resp := UTL_HTTP.GET_RESPONSE(req);
  LOOP
    UTL_HTTP.READ_LINE(resp, value, TRUE);
    DBMS_OUTPUT.PUT_LINE(value);
  END LOOP;
  UTL_HTTP.END_RESPONSE(resp);
EXCEPTION
  WHEN UTL_HTTP.END_OF_BODY THEN
    UTL_HTTP.END_RESPONSE(resp);
END;
</code>```

Here is an example with CURL :

```<code>curl -v -X POST -H "Content-Type: multipart/form-data" -F "art=11111" -F "qty=1" http://local/api/ws
</code>```

This example works fine with curl but i don't know why it doesn't in PL/SQL.
Can you help me ?

答:
I use a similar procedure with POST method at the http request, however I'd set header like:

```<code>UTL_HTTP.set_header( v_http_request,
                     'Content-Type',
                     'application/x-www-form-urlencoded;charset=utf-8' );
</code>```

Be aware also that, if the web-service site implements a security certificate, your DBA must create a wallet server-side, and before opening the request you should invoke that wallet:

```<code>utl_http.set_wallet('file:<your wallet file route>', '<your pass>');
</code>```

More on Wallets can be found here

Body:
I'm trying to call REST WebService in PL/SQL but it doesn't work. I get this error:

Content-type must be multipart/form-data

Here is what I have:

DECLARE
  req   UTL_HTTP.REQ;
  resp  UTL_HTTP.RESP;
  value VARCHAR2(1024);  -- URL to post to
  v_url VARCHAR2(200) := 'http://local/api/ws';
  -- Post Parameters
  v_param VARCHAR2(500) := 'art=11111\&qty=1';
  v_param_length NUMBER := length(v_param);
BEGIN
  req := UTL_HTTP.BEGIN_REQUEST (url=> v_url, method => 'POST');
  UTL_HTTP.SET_HEADER(req, 'User-Agent', 'Mozilla/4.0');
  UTL_HTTP.SET_HEADER (r      =>  req,
                       name   =>  'Content-Type',
                       value  =>  'multipart/form-data; charset=utf-8; boundary=/');
  UTL_HTTP.SET_HEADER (r      =>   req,
                       name   =>   'Content-Length',
                       value  =>   v_param_length);
  UTL_HTTP.WRITE_TEXT (r      =>   req,
                       data   =>   v_param);

     resp := UTL_HTTP.GET_RESPONSE(req);
  LOOP
    UTL_HTTP.READ_LINE(resp, value, TRUE);
    DBMS_OUTPUT.PUT_LINE(value);
  END LOOP;
  UTL_HTTP.END_RESPONSE(resp);
EXCEPTION
  WHEN UTL_HTTP.END_OF_BODY THEN
    UTL_HTTP.END_RESPONSE(resp);
END;

Here is an example with CURL :

curl -v -X POST -H "Content-Type: multipart/form-data" -F "art=11111" -F "qty=1" http://local/api/ws

This example works fine with curl but i don't know why it doesn't in PL/SQL.
Can you help me ?

Body:
I use a similar procedure with POST method at the http request, however I'd set header like:

UTL_HTTP.set_header( v_http_request,
                     'Content-Type',
                     'application/x-www-form-urlencoded;charset=utf-8' );

Be aware also that, if the web-service site implements a security certificate, your DBA must create a wallet server-side, and before opening the request you should invoke that wallet:

utl_http.set_wallet('file:<your wallet file route>', '<your pass>');

More on Wallets can be found here

ContentLicense: CC BY-SA 4.0


问:
How to use TensorFlow to predict large csv files by chunks and glue results together
Now that I've trained a predicting model with TensorFlow, and there's a large test.csv file that's too big to fit into memory, can it be possible to feed it by a smaller chunk at a time and then concat them again within one session?</p>

答: Using tf.estimator.Estimator for your model and calling the predict method using the numpy_input_fn will give you all the pieces to build what you want.


问:
How to get user list from active directory in MVC?
I am trying to get user names from active directory. I used below code and it gives me usernames for some people but it is not all.There are missing names. What do i wrong? I am new on Mvc and ldap. Anyone can help me?</p>

```<code>   public ActionResult GetUserList()
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://domain.com", "username", "password");

        DirectorySearcher searcher;
        SearchResultCollection results;

        searcher = new DirectorySearcher(entry);

        searcher.Filter = "(&(objectClass=user)(displayname=*))";
        searcher.SearchScope = SearchScope.Subtree;
        List<string> list= new List<string>();

        using (searcher)
        {
            results = searcher.FindAll();

            foreach (SearchResult result in results)
            {
                string searchOK = result.Properties["displayname"][0].ToString();
                list.Add(searchOK);
            }
        }
        return View(list);

    }
</code>```

答:
Change

```<code>searcher.Filter = "(&(objectClass=user)(displayname=*))";
</code>```

to

```<code>searcher.Filter = "(objectClass=user)";
</code>```

Not every user must have a display name.
Please also read the samAccountName property

Body:
I am trying to get user names from active directory. I used below code and it gives me usernames for some people but it is not all.There are missing names. What do i wrong? I am new on Mvc and ldap. Anyone can help me?

   public ActionResult GetUserList()
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://domain.com", "username", "password");

        DirectorySearcher searcher;
        SearchResultCollection results;

        searcher = new DirectorySearcher(entry);

        searcher.Filter = "(&(objectClass=user)(displayname=*))";
        searcher.SearchScope = SearchScope.Subtree;
        List<string> list= new List<string>();

        using (searcher)
        {
            results = searcher.FindAll();

            foreach (SearchResult result in results)
            {
                string searchOK = result.Properties["displayname"][0].ToString();
                list.Add(searchOK);
            }
        }
        return View(list);

    }

Body:
Change

searcher.Filter = "(&(objectClass=user)(displayname=*))";

to

searcher.Filter = "(objectClass=user)";

Not every user must have a display name.
Please also read the samAccountName property


问:
Adding extra multiple fields in Drupal(6.19) comment form
I am a complete novice to Drupal and module integration. I am given a task of letting the user give ratings in various ways along with their comment against a particular post. The rating will be 5 star rating. These rating will be for multiple fields such as Cleanliness(5 star rating), Communication(5 star rating) etc.

I have installed modules comment_cck, csm, token and fivestar. Just not able to put them together

How will i achieve this.

Thanks in advance

答:
In order to use the fivestar module, you need to install voting API, and to build a view using the API, you need views.

Please follow this screencast - it should provide you with valuable info on how to use these modules. It's a little bit complex.

ContentLicense: CC BY-SA 2.5


问:
Merging different SQL scripts into one script
I have 3 query scripts that are working on the same table; one is counting total number of rows, another one is counting total number of duplicated rows and the other one is counting total number of distinct (unique) rows.

To count the total number of rows:

```<code>select count(*) as total_rows from <table_name>
</code>```

To count the duplicated rows:

```<code>select COUNT (<column_name>) as total_duplicate from <table_name> group by (<column_name>) HAVING count(<column_name>) > 1
</code>```

To count the unique rows:

```<code>select COUNT(DISTINCT <column_name>) as total_unique from <table_name>
</code>```

I am trying to merge all 3 into a single script. I am able to do it for total count and unique count; But, I am not sure how to include the duplicated count query since it has a group by statement.

Any idea please.

答:
```<code>select      sum(rows_per_col)   as total_rows
           ,count (is_dup)      as total_duplicate
           ,count(*)            as total_unique

from       (select      column_name
                       ,case when count(*) > 1 then 1 end   as is_dup
                       ,count(*)                            as rows_per_col

            from        table_name

            group by    column_name
            ) t
</code>```

Demo

```<code>with table_name as (select explode(array(1,1,1,2,3,3,4,4,4,4,4,5)) as column_name)

select      sum(rows_per_col)   as total_rows
           ,count (is_dup)      as total_duplicate
           ,count(*)            as total_unique

from       (select      column_name
                       ,case when count(*) > 1 then 1 end   as is_dup
                       ,count(*)                            as rows_per_col

            from        table_name

            group by    column_name
            ) t

</code>```

```<code>+------------+-----------------+--------------+
| total_rows | total_duplicate | total_unique |
+------------+-----------------+--------------+
|         12 |               3 |            5 |
+------------+-----------------+--------------+
</code>```

Body:
I have 3 query scripts that are working on the same table; one is counting total number of rows, another one is counting total number of duplicated rows and the other one is counting total number of distinct (unique) rows.

To count the total number of rows:

select count(*) as total_rows from <table_name>

To count the duplicated rows:

select COUNT (<column_name>) as total_duplicate from <table_name> group by (<column_name>) HAVING count(<column_name>) > 1

To count the unique rows:

select COUNT(DISTINCT <column_name>) as total_unique from <table_name>

I am trying to merge all 3 into a single script. I am able to do it for total count and unique count; But, I am not sure how to include the duplicated count query since it has a group by statement.

Any idea please.

Body:
select      sum(rows_per_col)   as total_rows
           ,count (is_dup)      as total_duplicate
           ,count(*)            as total_unique

from       (select      column_name
                       ,case when count(*) > 1 then 1 end   as is_dup
                       ,count(*)                            as rows_per_col

            from        table_name

            group by    column_name
            ) t

Demo

with table_name as (select explode(array(1,1,1,2,3,3,4,4,4,4,4,5)) as column_name)

select      sum(rows_per_col)   as total_rows
           ,count (is_dup)      as total_duplicate
           ,count(*)            as total_unique

from       (select      column_name
                       ,case when count(*) > 1 then 1 end   as is_dup
                       ,count(*)                            as rows_per_col

            from        table_name

            group by    column_name
            ) t

+------------+-----------------+--------------+
| total_rows | total_duplicate | total_unique |
+------------+-----------------+--------------+
|         12 |               3 |            5 |
+------------+-----------------+--------------+


问:
How can a dictionary and if function co-exist without conflicting eachother? (Tkinter)
I have written a program using Python's tkinter module. The premise is that after giving a password, it produces a response depending on how strong it is.

```<code>from tkinter import *

def click():
    entered_text = entry.get()
    if len(entered_text) < 9:
        output.delete(0.0, END)
        output.insert(END, 'This is too short')     #Click function
    elif entered_text in pass_Type:
        strength = pass_Type[entered_text]
        output.delete(0.0, END)
        output.insert(END, strength)
    else:
        output.delete(0.0, END)
        output.insert(END, "This password is acceptable!") #When the password is ok

Password = Tk()
Password.title('Password tester')

label = Label(Password, text="Password:")
label.grid(row=0, column=0, sticky=W)    #Entry label

entry = Entry(width=20, bg='light blue')
entry.grid(row=1, column=0, sticky=W)     #Entry box

Button(Password, text='SUBMIT',width=5, command=click).grid(row=2,column=0, sticky=W)  #Button

label = Label(Password, text='Strength:')
label.grid(row=4, column=0, sticky=W)          #Output label

output = Text(Password, width=75, height=6, wrap=WORD, background='light blue')
output.grid(row=5, column=0, columnspan=2, sticky=W)                              #Output box

pass_Type = {
  'Password': 'This is a very predicatable password. You should incorporate numbers',
  'password': 'This is a very predicatable password. You should incorporate numbers and capital letters',  #Common password glossary
  '12345': 'Try and incorporate some letters',
  'qwerty': 'Try to jumble up your letters so the password is not so predictable.'
  }

Password.mainloop()
</code>```

This code runs prefectly fine. However, when I run one of the common passwords from the dictionary ('pass_type,')the message for the length runs.

Thus, I tried adding this along with the rest of 'def click():.'

```<code>def click():
entered_text = entry.get()
if len(entered_text) < 9:
    output.delete(0.0, END)
    output.insert(END, 'This is too short')     #Click function
elif entered_text in pass_Type:
    strength = pass_Type[entered_text]
    output.delete(0.0, END)
    output.insert(END, strength)
elif strength and len(entered_text) < 9: }
   output.delete(0.0, END)               }
   output.insert(END, strength)          } #What I entered
else:
    output.delete(0.0, END)
    output.insert(END, "This password is acceptable!") #When the password is ok
</code>```

This still returns the message 'this is too short' from the length check, despite the fact I assigned it to strength.

How can I get the common password still assigned with their attributed dictionary sentence?

答:
To solve when you added

```<code>elif strength and len(entered_text) < 9:
    output.delete(0.0, END)
    output.insert(END, strength)
</code>```

the earlier code never passes through the first elif statement and therefore never assigns a value to strength and therefore it is referenced before assignment.

Body:
I have written a program using Python's tkinter module. The premise is that after giving a password, it produces a response depending on how strong it is.

from tkinter import *

def click():
    entered_text = entry.get()
    if len(entered_text) < 9:
        output.delete(0.0, END)
        output.insert(END, 'This is too short')     #Click function
    elif entered_text in pass_Type:
        strength = pass_Type[entered_text]
        output.delete(0.0, END)
        output.insert(END, strength)
    else:
        output.delete(0.0, END)
        output.insert(END, "This password is acceptable!") #When the password is ok

Password = Tk()
Password.title('Password tester')

label = Label(Password, text="Password:")
label.grid(row=0, column=0, sticky=W)    #Entry label

entry = Entry(width=20, bg='light blue')
entry.grid(row=1, column=0, sticky=W)     #Entry box

Button(Password, text='SUBMIT',width=5, command=click).grid(row=2,column=0, sticky=W)  #Button

label = Label(Password, text='Strength:')
label.grid(row=4, column=0, sticky=W)          #Output label

output = Text(Password, width=75, height=6, wrap=WORD, background='light blue')
output.grid(row=5, column=0, columnspan=2, sticky=W)                              #Output box

pass_Type = {
  'Password': 'This is a very predicatable password. You should incorporate numbers',
  'password': 'This is a very predicatable password. You should incorporate numbers and capital letters',  #Common password glossary
  '12345': 'Try and incorporate some letters',
  'qwerty': 'Try to jumble up your letters so the password is not so predictable.'
  }

Password.mainloop()

This code runs prefectly fine. However, when I run one of the common passwords from the dictionary ('pass_type,')the message for the length runs.

Thus, I tried adding this along with the rest of 'def click():.'

def click():
entered_text = entry.get()
if len(entered_text) < 9:
    output.delete(0.0, END)
    output.insert(END, 'This is too short')     #Click function
elif entered_text in pass_Type:
    strength = pass_Type[entered_text]
    output.delete(0.0, END)
    output.insert(END, strength)
elif strength and len(entered_text) < 9: }
   output.delete(0.0, END)               }
   output.insert(END, strength)          } #What I entered
else:
    output.delete(0.0, END)
    output.insert(END, "This password is acceptable!") #When the password is ok

This still returns the message 'this is too short' from the length check, despite the fact I assigned it to strength.

How can I get the common password still assigned with their attributed dictionary sentence?

Body:
To solve when you added

elif strength and len(entered_text) < 9:
    output.delete(0.0, END)
    output.insert(END, strength)

the earlier code never passes through the first elif statement and therefore never assigns a value to strength and therefore it is referenced before assignment.


问:
Angular Service function not returning anything, trying to do multiple http requests and return single observable
Unfortunately, the way the site is setup that I need to retrieve data from, is that this data is spread across multiple sites (the exact same type of data and JSON return format) but they are at different URLs.  They are classified by the URLs, so I do need to retain the URLs in order to further classify it throughout the app.  I have the following service function where I am trying to pass a set of topics (which are then passed to the URL), retrieve the data and return a single observable.  However, this is returning nothing:

```<code>getDataTopicItems(topicArray) {
    return this.items = topicArray.forEach((topic, i, topicArray) => {
        return this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options)
            .map(res => res.json())
            .map(items => items.d.results)
            .do(data => console.log(data))
            .concatMap(data => data)
      }
    )
}
</code>```

I am subscribing to it in the template of the component where I am calling this function through an *ngFor plus an async pipe.  What am I doing wrong?

Update:  I also tried the following:

```<code>return this.http.get(this.baseUrl + topicArray[0] + this.policyOptions, this.options)
            .map(res => res.json())
            .map(items => this.policies = items.d.results)
            .do(data => console.log(data))
            .flatMap((policies) => topicArray.forEach((topic, i, topicArray) => {
                if (i < 0) {
                    this.http.get(this.baseUrl + topic + this.policyOptions)
                        .map(res => res.json())
                        .map(items => this.policies = items.d.results)
                        .do(data => console.log(data))
                }
            }))
</code>```

答:
Callback function to the Array.forEach method doesn't expect to receive anything, so maybe you wanted to use Array.map instead.

If you're looking for "more RxJS" approach you could use mergeMap to do something like this:

```<code>return Observable.from(topicArray)
    .mergeMap(topic => this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options)
        .map(res => res.json())
        .map(items => items.d.results)
        .do(data => console.log(data))
        .concatMap(data => data);
</code>```

Eventually you could use concatMap instead of mergeMap to run all requests in order and use concatAll instead of .concatMap(data => data); which makes it a little more obvious what you were trying to do.

Btw, be aware that by using this.items = ... you just assign an Observable to this.items not the result.

Also note that you need to subscribe to the returned Observable if you want  to get any results. For example:

```<code>getDataTopicItems([...]).subscribe(result => this.items = result);
</code>```

See live demo: https://jsbin.com/nuzifo/9/edit?html,js,console

Body:
Unfortunately, the way the site is setup that I need to retrieve data from, is that this data is spread across multiple sites (the exact same type of data and JSON return format) but they are at different URLs.  They are classified by the URLs, so I do need to retain the URLs in order to further classify it throughout the app.  I have the following service function where I am trying to pass a set of topics (which are then passed to the URL), retrieve the data and return a single observable.  However, this is returning nothing:

getDataTopicItems(topicArray) {
    return this.items = topicArray.forEach((topic, i, topicArray) => {
        return this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options)
            .map(res => res.json())
            .map(items => items.d.results)
            .do(data => console.log(data))
            .concatMap(data => data)
      }
    )
}

I am subscribing to it in the template of the component where I am calling this function through an *ngFor plus an async pipe.  What am I doing wrong?

Update:  I also tried the following:

return this.http.get(this.baseUrl + topicArray[0] + this.policyOptions, this.options)
            .map(res => res.json())
            .map(items => this.policies = items.d.results)
            .do(data => console.log(data))
            .flatMap((policies) => topicArray.forEach((topic, i, topicArray) => {
                if (i < 0) {
                    this.http.get(this.baseUrl + topic + this.policyOptions)
                        .map(res => res.json())
                        .map(items => this.policies = items.d.results)
                        .do(data => console.log(data))
                }
            }))

Body:
Callback function to the Array.forEach method doesn't expect to receive anything, so maybe you wanted to use Array.map instead.

If you're looking for "more RxJS" approach you could use mergeMap to do something like this:

return Observable.from(topicArray)
    .mergeMap(topic => this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options)
        .map(res => res.json())
        .map(items => items.d.results)
        .do(data => console.log(data))
        .concatMap(data => data);

Eventually you could use concatMap instead of mergeMap to run all requests in order and use concatAll instead of .concatMap(data => data); which makes it a little more obvious what you were trying to do.

Btw, be aware that by using this.items = ... you just assign an Observable to this.items not the result.

Also note that you need to subscribe to the returned Observable if you want  to get any results. For example:

getDataTopicItems([...]).subscribe(result => this.items = result);

See live demo: https://jsbin.com/nuzifo/9/edit?html,js,console


问:
functions inside a class
We need to make a class called Series with two methods

triNums - function that returns you a triangular series by the number it recives eg: if the function gets 5 - 1, 3, 6, 10, 15

fibNums - function that returns you a fibonacci sequence by the number it
recives eg: if the function gets 5 - 0,1,1,2,3,5

Each of the functions need to be executed when pressing on a button (fibo)(tri) and each element of the result should be displayed on a button

class Series {
  tri() {
    const num = document.querySelector("#num").value
    if (num) {
      addBtns(triNums(num));
    }
  }

  addBtns(arr) {
    const feed = document.querySelector("#feed");
    var btns = ""; //no buttons by default
    for (let v of arr) { //iterate over all values
      btns += "<button>" + v + "</button>";
    }
    feed.innerHTML = btns;
  }
  triNums(num) {
    var triNums = [];
    for (let n = 0; n < num.value; n++) {
      triNums[n] = n * (n + 1) / 2;
    }
    return triNums;
  }
  triNum(n) {
      return (n * (n + 1) / 2);
  }
}        ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html lang="en-US">

<head>
  <meta charset="UTF-8" />
  <title></title>
  <script src="home6617.js"></script>
</head>

<body>
  Enter Name <input id="name" placeholder="Enter name"></input>
  <button onclick="sayHello()">Click me</button>
  <h1 id="hello"></h1>
  <input id="num"></input>
  <button onclick="tri()">triangular</button>
  <div id="feed"></div>
</body>

</html></code>```

答:
You made some mistakes:

you pass #num.value to triNums, which is a Number, and then you try to access its value, which is unneccessary and impossible.

You cannot call tri() as it is part of a Series instance. You could do (new Series).tri() .

Same applies for inner function calls, you must access them via this :

class Series {
  tri() {
    const num = document.querySelector("#num").value
    if (num) {
      this.addBtns(this.triNums(num));
    }
  }

  addBtns(arr) {
    const feed = document.querySelector("#feed");
    var btns = ""; //no buttons by default
    for (let v of arr) { //iterate over all values
      btns += "<button>" + v + "</button>";
    }
    feed.innerHTML = btns;
  }
  triNums(num) {
    var triNums = [];
    for (let n = 0; n < num; n++) {
      triNums[n] = n * (n + 1) / 2;
    }
    return triNums;
  }
  triNum(n) {
      return (n * (n + 1) / 2);
  }
}

function start(){
 (new Series).tri();
}    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html lang="en-US">

<head>
  <meta charset="UTF-8" />
  <title></title>
  <script src="home6617.js"></script>
</head>

<body>
 <div id="feed"></div>
 <input id="num" />
 <button onclick="start()">Start</button>
</body>

</html></code>```

Title: functions inside a class

Body:
We need to make a class called Series with two methods

triNums - function that returns you a triangular series by the number it recives eg: if the function gets 5 - 1, 3, 6, 10, 15

fibNums - function that returns you a fibonacci sequence by the number it
recives eg: if the function gets 5 - 0,1,1,2,3,5

Each of the functions need to be executed when pressing on a button (fibo)(tri) and each element of the result should be displayed on a button

class Series {
  tri() {
    const num = document.querySelector("#num").value
    if (num) {
      addBtns(triNums(num));
    }
  }

  addBtns(arr) {
    const feed = document.querySelector("#feed");
    var btns = ""; //no buttons by default
    for (let v of arr) { //iterate over all values
      btns += "<button>" + v + "</button>";
    }
    feed.innerHTML = btns;
  }
  triNums(num) {
    var triNums = [];
    for (let n = 0; n < num.value; n++) {
      triNums[n] = n * (n + 1) / 2;
    }
    return triNums;
  }
  triNum(n) {
      return (n * (n + 1) / 2);
  }
}

<!DOCTYPE HTML>

  <meta charset="UTF-8" />
  <title></title>

  Enter Name <input id="name" placeholder="Enter name"></input>
  <button onclick="sayHello()">Click me</button>

  <input id="num"></input>
  <button onclick="tri()">triangular</button>

Body:
You made some mistakes:

you pass #num.value to triNums, which is a Number, and then you try to access its value, which is unneccessary and impossible.

You cannot call tri() as it is part of a Series instance. You could do (new Series).tri() .

Same applies for inner function calls, you must access them via this :

class Series {
  tri() {
    const num = document.querySelector("#num").value
    if (num) {
      this.addBtns(this.triNums(num));
    }
  }

  addBtns(arr) {
    const feed = document.querySelector("#feed");
    var btns = ""; //no buttons by default
    for (let v of arr) { //iterate over all values
      btns += "<button>" + v + "</button>";
    }
    feed.innerHTML = btns;
  }
  triNums(num) {
    var triNums = [];
    for (let n = 0; n < num; n++) {
      triNums[n] = n * (n + 1) / 2;
    }
    return triNums;
  }
  triNum(n) {
      return (n * (n + 1) / 2);
  }
}

function start(){
 (new Series).tri();
}

<!DOCTYPE HTML>
<html lang="en-US">

<head>
  <meta charset="UTF-8" />
  <title></title>
  <script src="home6617.js"></script>
</head>

<body>
 <div id="feed"></div>
 <input id="num" />
 <button onclick="start()">Start</button>
</body>

</html>


问:
Timer doesn't want to start again after it was disabled
I am writing a simple C# program that attempts to do something every x amount of seconds using System.Forms.Timer

The tick event calls a method that starts a new thread and disables the timer, then when the thread is done with its work, it enables the timer again, but the problem is, now it doesn't tick after it's been enabled.

```<code>static System.Windows.Forms.Timer testtimer = new System.Windows.Forms.Timer();

    static void Main()
    {
        testtimer.Tick += testtimertick;
        testtimer.Interval = 5000;
        testtimer.Enabled = true;
        testtimer.Start();

        while (true)
        {
            Application.DoEvents();  //Prevents application from exiting
        }

    }

 private static void testtimertick(object sender, System.EventArgs e)
    {

            testtimer.Enabled = false;
            Thread t = new Thread(dostuff);
            t.Start();
    }

private static void dostuff()
    {

       //Executes some code
       testtimer.Enabled = true; //Re enables the timer but it doesn't work
       testtimer.Start();
     }
</code>```

答:
If you really want to stick to the GUI timer, and start it from non UI thread, you can try to do similar stuff, then write to GUI from non UI thread.

Not the ideal solution, I know.

```<code>this.Invoke((MethodInvoker)delegate
{
    refreshTimer.Enabled = true;
    refreshTimer.Start();
});
</code>```

Body:
I am writing a simple C# program that attempts to do something every x amount of seconds using System.Forms.Timer

The tick event calls a method that starts a new thread and disables the timer, then when the thread is done with its work, it enables the timer again, but the problem is, now it doesn't tick after it's been enabled.

static System.Windows.Forms.Timer testtimer = new System.Windows.Forms.Timer();

    static void Main()
    {
        testtimer.Tick += testtimertick;
        testtimer.Interval = 5000;
        testtimer.Enabled = true;
        testtimer.Start();

        while (true)
        {
            Application.DoEvents();  //Prevents application from exiting
        }

    }

 private static void testtimertick(object sender, System.EventArgs e)
    {

            testtimer.Enabled = false;
            Thread t = new Thread(dostuff);
            t.Start();
    }

private static void dostuff()
    {

       //Executes some code
       testtimer.Enabled = true; //Re enables the timer but it doesn't work
       testtimer.Start();
     }

Body:
If you really want to stick to the GUI timer, and start it from non UI thread, you can try to do similar stuff, then write to GUI from non UI thread.

Not the ideal solution, I know.

this.Invoke((MethodInvoker)delegate
{
    refreshTimer.Enabled = true;
    refreshTimer.Start();
});


问:
Strange object assignment behaviour c++
I have a strange behavior with object assignments. I will much appreciate, if you can explain why this assignment works like this. It has cost me already a lot of time.
I am using Visual Studio Enterprise 2017 (all default settings).

Code:

```<code>#include "stdafx.h"
#include <iostream>

using namespace std;

class Test
{
public:

    Test()
    {
        cout << "Constructor of " << this << endl;
    }

    ~Test()
    {
        cout << "Destructor of " << this << endl;
    }
};

int main()
{
    cout << "Assignment 1" << endl;
    auto t = Test();
    cout << "Assignment 2" << endl;
    t = Test();

    int i = 0;
    cin >> i;
    return 0;
}
</code>```

Output (up to cin):

```<code>Assignment 1
Constructor of 006FFC9F
Assignment 2
Constructor of 006FFBC7
Destructor of 006FFBC7
</code>```

Expected Output (up to cin):

```<code>Assignment 1
Constructor of 006FFC9F
Assignment 2
Destructor of 006FFC9F
Constructor of 006FFBC7
</code>```

I wanted to write a test function which creates an object of my (template) class, do some tests, then create a new object and do some more testing. The problem is that t holds the already destructed object after the second assignment.
I know that I can just use dynamic allocation which results in the expected behavior, but why does this program behave different?

Thank you very much.
Regards.

PS: Results are the same, independent of Release/Debug or 64/32 bit compilation

EDIT: More verbose example:

```<code>#include "stdafx.h"
#include <iostream>

using namespace std;

class Test
{
private:
    float* val;
public:
    Test()
    {
        val = new float;
        cout << "Constructor of " << this << ", addr. of val: " << val << endl;
    }

    ~Test()
    {
        cout << "Destructor of " << this << ", addr. of val: " << val << " --> DELETING VAL!" << endl;
        delete val;
    }

    float* getVal() { return this->val; }
};

int main()
{
    cout << "Assignment 1" << endl;
    auto t = Test();
    cout << "Assignment 2" << endl;
    t = Test();
    cout << "Val Address: " << t.getVal() << endl;

    int i = 0;
    cin >> i;
    return 0;
}
</code>```

Output (it holds a deleted pointer at the end!!!):

```<code>Assignment 1
Constructor of 004FFBDC, addr. of val: 0072AEB0
Assignment 2
Constructor of 004FFB04, addr. of val: 00723928
Destructor of 004FFB04, addr. of val: 00723928 --> DELETING VAL!
Val Address: 00723928
</code>```

答:
Your confusion seems to be a mistaken expectation that the original object is destroyed when assignment takes place. Like, in this code:

```<code>cout << "Assignment 2" << endl;
t = Test();
</code>```

This piece of code invokes the move-assign operator. Since you didn't define one, the default one generated by the compiler is more-or-less going to look like this:

```<code>Test & operator=(Test &&) {}
</code>```

Note how there's no invocation of a constructor or (critically) a destructor in that code. The only Constructors and Destructors that are going to run are on the temporary object (which is what you observe in the actual output). The original object doesn't get destroyed until the code goes out of scope; and why would it? It's not like you can stop using the stack space before then.

Edit: Something which might help you understand what's going on:

```<code>#include<iostream>

struct Test {
    Test() {std::cout << "Constructed.\n";}
    ~Test() {std::cout << "Destructed.\n";}
    Test(Test const&) {std::cout << "Copy-Constructed.\n";}
    Test(Test &&) {std::cout << "Move-Constructed.\n";}
    Test & operator=(Test const&) {std::cout << "Copy-Assigned.\n"; return *this;}
    Test & operator=(Test &&) {std::cout << "Move-Assigned.\n"; return *this;}
};

int main() {
    std::cout << "Test t;\n";
    Test t; //Construction
    std::cout << "Test t2(t);\n";
    Test t2(t); //Copy-Construct
    std::cout << "Test t3(std::move(t2));\n";
    Test t3(std::move(t2)); //Move-Construct
    std::cout << "Test t4 = t;\n";
    Test t4 = t; //Copy Construct, due to Copy Ellision
    std::cout << "Test t5 = Test();\n";
    Test t5 = Test(); //Will probably be a normal Construct, due to Copy Ellision
    std::cout << "t = t2;\n";
    t = t2; //Copy Assign
    std::cout << "t = Test();\n";
    t = Test(); //Move Assign, will invoke Constructor and Destructor on temporary
    std::cout << "Done! Cleanup will now happen!\n";
    return 0;
}
</code>```

Results as seen when compiled here:

```<code>Test t;
Constructed.
Test t2(t);
Copy-Constructed.
Test t3(std::move(t2));
Move-Constructed.
Test t4 = t;
Copy-Constructed.
Test t5 = Test();
Constructed.
t = t2;
Copy-Assigned.
t = Test();
Constructed.
Move-Assigned.
Destructed.
Done! Cleanup will now happen!
Destructed.
Destructed.
Destructed.
Destructed.
Destructed.
</code>```

DOUBLE EDIT COMBO!:

As I mentioned in comments, val is just a pointer. 8 bytes (on a 64-bit machine) allocated as part of Test's storage. If you're trying to make sure that Test always contains a valid value for val that hasn't been deleted, you need to implement the Rule of Five (previously known as the Rule of Three):

```<code>class Test {
    float * val;
public:
    Test() {val = new float;}
    ~Test() {delete val;
    Test(Test const& t) {
        val = new float(*(t.val));
    }
    Test(Test && t) {std::swap(val, t.val);}
    Test & operator=(Test const& t) {
        float * temp = new float(*(t.val)); //Gives Strong Exception Guarantee
        delete val;
        val = temp;
        return *this;
    }
    Test & operator=(Test && t) {std::swap(val, t.val); return *this;};

    float & get_val() const {return *val;} //Return by reference, not by pointer, to
        //prevent accidental deletion.
};
</code>```

Title: Strange object assignment behaviour c++

Body:
I have a strange behavior with object assignments. I will much appreciate, if you can explain why this assignment works like this. It has cost me already a lot of time.
I am using Visual Studio Enterprise 2017 (all default settings).

Code:

#include "stdafx.h"
#include <iostream>

using namespace std;

class Test
{
public:

    Test()
    {
        cout << "Constructor of " << this << endl;
    }

    ~Test()
    {
        cout << "Destructor of " << this << endl;
    }
};

int main()
{
    cout << "Assignment 1" << endl;
    auto t = Test();
    cout << "Assignment 2" << endl;
    t = Test();

    int i = 0;
    cin >> i;
    return 0;
}

Output (up to cin):

Assignment 1
Constructor of 006FFC9F
Assignment 2
Constructor of 006FFBC7
Destructor of 006FFBC7

Expected Output (up to cin):

Assignment 1
Constructor of 006FFC9F
Assignment 2
Destructor of 006FFC9F
Constructor of 006FFBC7

I wanted to write a test function which creates an object of my (template) class, do some tests, then create a new object and do some more testing. The problem is that t holds the already destructed object after the second assignment.
I know that I can just use dynamic allocation which results in the expected behavior, but why does this program behave different?

Thank you very much.
Regards.

PS: Results are the same, independent of Release/Debug or 64/32 bit compilation

EDIT: More verbose example:

#include "stdafx.h"
#include <iostream>

using namespace std;

class Test
{
private:
    float* val;
public:
    Test()
    {
        val = new float;
        cout << "Constructor of " << this << ", addr. of val: " << val << endl;
    }

    ~Test()
    {
        cout << "Destructor of " << this << ", addr. of val: " << val << " --> DELETING VAL!" << endl;
        delete val;
    }

    float* getVal() { return this->val; }
};

int main()
{
    cout << "Assignment 1" << endl;
    auto t = Test();
    cout << "Assignment 2" << endl;
    t = Test();
    cout << "Val Address: " << t.getVal() << endl;

    int i = 0;
    cin >> i;
    return 0;
}

Output (it holds a deleted pointer at the end!!!):

Assignment 1
Constructor of 004FFBDC, addr. of val: 0072AEB0
Assignment 2
Constructor of 004FFB04, addr. of val: 00723928
Destructor of 004FFB04, addr. of val: 00723928 --> DELETING VAL!
Val Address: 00723928

Body:
Your confusion seems to be a mistaken expectation that the original object is destroyed when assignment takes place. Like, in this code:

cout << "Assignment 2" << endl;
t = Test();

This piece of code invokes the move-assign operator. Since you didn't define one, the default one generated by the compiler is more-or-less going to look like this:

Test & operator=(Test &&) {}

Note how there's no invocation of a constructor or (critically) a destructor in that code. The only Constructors and Destructors that are going to run are on the temporary object (which is what you observe in the actual output). The original object doesn't get destroyed until the code goes out of scope; and why would it? It's not like you can stop using the stack space before then.

Edit: Something which might help you understand what's going on:

#include<iostream>

struct Test {
    Test() {std::cout << "Constructed.\n";}
    ~Test() {std::cout << "Destructed.\n";}
    Test(Test const&) {std::cout << "Copy-Constructed.\n";}
    Test(Test &&) {std::cout << "Move-Constructed.\n";}
    Test & operator=(Test const&) {std::cout << "Copy-Assigned.\n"; return *this;}
    Test & operator=(Test &&) {std::cout << "Move-Assigned.\n"; return *this;}
};

int main() {
    std::cout << "Test t;\n";
    Test t; //Construction
    std::cout << "Test t2(t);\n";
    Test t2(t); //Copy-Construct
    std::cout << "Test t3(std::move(t2));\n";
    Test t3(std::move(t2)); //Move-Construct
    std::cout << "Test t4 = t;\n";
    Test t4 = t; //Copy Construct, due to Copy Ellision
    std::cout << "Test t5 = Test();\n";
    Test t5 = Test(); //Will probably be a normal Construct, due to Copy Ellision
    std::cout << "t = t2;\n";
    t = t2; //Copy Assign
    std::cout << "t = Test();\n";
    t = Test(); //Move Assign, will invoke Constructor and Destructor on temporary
    std::cout << "Done! Cleanup will now happen!\n";
    return 0;
}

Results as seen when compiled here:

Test t;
Constructed.
Test t2(t);
Copy-Constructed.
Test t3(std::move(t2));
Move-Constructed.
Test t4 = t;
Copy-Constructed.
Test t5 = Test();
Constructed.
t = t2;
Copy-Assigned.
t = Test();
Constructed.
Move-Assigned.
Destructed.
Done! Cleanup will now happen!
Destructed.
Destructed.
Destructed.
Destructed.
Destructed.

DOUBLE EDIT COMBO!:

As I mentioned in comments, val is just a pointer. 8 bytes (on a 64-bit machine) allocated as part of Test's storage. If you're trying to make sure that Test always contains a valid value for val that hasn't been deleted, you need to implement the Rule of Five (previously known as the Rule of Three):

class Test {
    float * val;
public:
    Test() {val = new float;}
    ~Test() {delete val;
    Test(Test const& t) {
        val = new float(*(t.val));
    }
    Test(Test && t) {std::swap(val, t.val);}
    Test & operator=(Test const& t) {
        float * temp = new float(*(t.val)); //Gives Strong Exception Guarantee
        delete val;
        val = temp;
        return *this;
    }
    Test & operator=(Test && t) {std::swap(val, t.val); return *this;};

    float & get_val() const {return *val;} //Return by reference, not by pointer, to
        //prevent accidental deletion.
};


问:
How to handle login errors with Ionic custom auth?
I'm trying to implement a user login with Ionic Cloud's Auth Service, and would prefer to no show the Cordova inAppBrowser. In case of an authentication error (e.g. wrong password), I would expect the error handler to fire, but for some reason this never seems to be the case.

The method in my login component contains this:

```<code>let loginData = {
  email: this.email,
  password: this.password
};
let loginOptions: AuthLoginOptions = {
  inAppBrowserOptions: {
    hidden: true
  }
};
this.auth.login('custom', loginData, loginOptions).then(() => {
  console.log('login success');
}, (err) => {
  console.log('login error', err); // <-- this never gets executed.
});
</code>```

I made sure that my authentication server responds with an HTTP status of 401 and a JSON body that contains an error property. This is the code (PHP, Laravel 3):

```<code>  public function get_login()
  {
    try {
      $redirect_uri = CustomAuthentication::process(
        $_GET['token'],
        $_GET['state'],
        $_GET['redirect_uri']
      );
      return Redirect::to($redirect_uri);
    } catch (\Exception $e) {
      return Response::json(array(
        'ok' => false,
        'error' => $e->getMessage(),
        'code' => $e->getCode()
      ), 401);
    }
  }
</code>```

I found two issues on github that seem relevant:

https://github.com/driftyco/ionic-cloud/issues/53

https://github.com/driftyco/ionic-cloud-angular/issues/22

Apparently there is no way to get this to work at the moment, when the inAppBrowser is hidden. Or is there another option?

In case there's no way to achieve this for now, what would be an alternative, in order to provide the users with a nice login flow, that shoes them a meaningful error message for unsuccessful login attempts?

Should I try to implement this with a visible inAppBrowser? If so, where can I find docs or an example?

Unfortunately the official docs don't tell much (http://docs.ionic.io/services/auth/custom-auth.html#login) and the tutorials I found are  outdated.

答:
I had the same issue!!

In your server, you have to redirect when there is an authentication error instead of rendering a JSON.

Something like this:

public function get_login()
  {
    try {
      $redirect_uri = CustomAuthentication::process(
        $_GET['token'],
        $_GET['state'],
        $_GET['redirect_uri']
      );
      return Redirect::to($redirect_uri);
    } catch (\Exception $e) {
        $redirect_uri = $_GET['redirect_uri'] . '&' . http_build_query([
            'error' =>  $e->getMessage(),
            'state' => 401,
            'code' => $e->getCode(),
        ]);
        return Redirect::to($redirect_uri);
    }
  }
```

<p>(Sorry if there is an error in the code, I don't know Lavarel ;))</p>

<p>This code is based on https://github.com/ionic-team/ionic-cloud/issues/53#issuecomment-296369084</p>

<p>In the Ruby on Rails world:</p>

<pre class="lang-rb prettyprint-override"><code>error_params = { error: error, state: 401 }
url = "#{params[:redirect_uri]}&#{error_params.to_query}"
redirect_to url
</code>```

Immediately after I made this change on my server, the ionic application started to work.

Body:
I'm trying to implement a user login with Ionic Cloud's Auth Service, and would prefer to no show the Cordova inAppBrowser. In case of an authentication error (e.g. wrong password), I would expect the error handler to fire, but for some reason this never seems to be the case.

The method in my login component contains this:

let loginData = {
  email: this.email,
  password: this.password
};
let loginOptions: AuthLoginOptions = {
  inAppBrowserOptions: {
    hidden: true
  }
};
this.auth.login('custom', loginData, loginOptions).then(() => {
  console.log('login success');
}, (err) => {
  console.log('login error', err); // <-- this never gets executed.
});

I made sure that my authentication server responds with an HTTP status of 401 and a JSON body that contains an error property. This is the code (PHP, Laravel 3):

  public function get_login()
  {
    try {
      $redirect_uri = CustomAuthentication::process(
        $_GET['token'],
        $_GET['state'],
        $_GET['redirect_uri']
      );
      return Redirect::to($redirect_uri);
    } catch (\Exception $e) {
      return Response::json(array(
        'ok' => false,
        'error' => $e->getMessage(),
        'code' => $e->getCode()
      ), 401);
    }
  }

I found two issues on github that seem relevant:

https://github.com/driftyco/ionic-cloud/issues/53

https://github.com/driftyco/ionic-cloud-angular/issues/22

Apparently there is no way to get this to work at the moment, when the inAppBrowser is hidden. Or is there another option?

In case there's no way to achieve this for now, what would be an alternative, in order to provide the users with a nice login flow, that shoes them a meaningful error message for unsuccessful login attempts?

Should I try to implement this with a visible inAppBrowser? If so, where can I find docs or an example?

Unfortunately the official docs don't tell much (http://docs.ionic.io/services/auth/custom-auth.html#login) and the tutorials I found are  outdated.

Body:
I had the same issue!!

In your server, you have to redirect when there is an authentication error instead of rendering a JSON.

Something like this:

public function get_login()
  {
    try {
      $redirect_uri = CustomAuthentication::process(
        $_GET['token'],
        $_GET['state'],
        $_GET['redirect_uri']
      );
      return Redirect::to($redirect_uri);
    } catch (\Exception $e) {
        $redirect_uri = $_GET['redirect_uri'] . '&' . http_build_query([
            'error' =>  $e->getMessage(),
            'state' => 401,
            'code' => $e->getCode(),
        ]);
        return Redirect::to($redirect_uri);
    }
  }

(Sorry if there is an error in the code, I don't know Lavarel ;))

This code is based on https://github.com/ionic-team/ionic-cloud/issues/53#issuecomment-296369084

In the Ruby on Rails world:

error_params = { error: error, state: 401 }
url = "#{params[:redirect_uri]}&#{error_params.to_query}"
redirect_to url

Immediately after I made this change on my server, the ionic application started to work.


答:
Remove for because listeners need to be set once

```<code>  for (int i=0;i<=names.length;i++) {
        work(i);
    }
</code>```

so signature of work would be

```<code> private void work() {
</code>```

and call it once from onCreate

Declare i as global and put an if condition while setting the next value to avoid index bound exception

```<code>public class MainActivity extends AppCompatActivity {

    private int i=0;
    // code

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // code
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);
        // initialize listener
        work();
    }

    private void work() {
            btn_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // check bounds
                    if (++i<names.length) {
                        sentence_etx.setText(names[i]);
                    }
                    // else{ // uncomment to reset the value of i
                    //     i=0;
                    // }
                }
            });

            btn_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (++i<names.length) {
                        sentence_etx.setText(names[i]);
                    }
                     // else{ // uncomment to reset the value of i
                    //     i=0;
                    // }
                }
            });
    }
}
</code>```

Your all buttons are doing same work , so you can simply have a listener and apply it on all button objects rather than creating separate anonymous listeners and

```<code>public class MainActivity extends AppCompatActivity {

    private TextView sentence_etx;
    private Button btn_1,btn_2;
    private String[] names = { "Apple","Mango","Cherry","Banana","Extra"};
    private int i=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sentence_etx = (TextView) findViewById(R.id.etx_sentence);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);

        // initialize listener
        btn_1.setOnClickListener(listner);
        btn_2.setOnClickListener(listner);
    }

    OnClickListener listner=new OnClickListener() {

        @Override
        public void onClick(View v) {
            // check bounds
            if (++i<names.length) {
                sentence_etx.setText(names[i]);
            }
            // else{ // uncomment to reset the value of i
            //     i=0;
            // }

            // note you can also add some conditional statement
            // to check which button is clicked using v.getId();
        }
    };

}
</code>```

Title: Change the textview's text using button click in Android

Body:
I want to change the text on a textView on button click. There can be multiple buttons in activity. The main purpose is to change the name of fruit on button click either any one button is clicked.
For example: Button 1 is clicked change the name, Button 2 is clicked next name, Button 3 is clicked next name and so on. I am trying as given below but the names are not changing.

Main Activity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView sentence_etx;
    private Button btn_1,btn_2;
    private String[] names = { "Apple","Mango","Cherry","Banana","Extra"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sentence_etx = (TextView) findViewById(R.id.etx_sentence);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);

        for (int i=0;i<=names.length;i++) {
            work(i);
        }
    }

    private void work(final int i) {
            btn_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });

            btn_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sentence_etx.setText(names[i]);
                }
            });
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.awais.test2.MainActivity">

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_marginTop="50dp"
            android:layout_marginRight="30dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/etx_sentence"
            android:text="Names......" />

        <LinearLayout
            android:gravity="center"
            android:layout_marginTop="100dp"
            android:layout_height="wrap_content"
            android:layout_width="match_parent">

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_1"
            android:text="1"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_2"
            android:text="2"/>

        <Button
            android:layout_height="50dp"
            android:layout_width="50dp"
            android:id="@+id/btn_3"
            android:text="3"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

Body:
Remove for because listeners need to be set once

  for (int i=0;i<=names.length;i++) {
        work(i);
    }

so signature of work would be

 private void work() {

and call it once from onCreate

Declare i as global and put an if condition while setting the next value to avoid index bound exception

public class MainActivity extends AppCompatActivity {

    private int i=0;
    // code

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // code
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);
        // initialize listener
        work();
    }

    private void work() {
            btn_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // check bounds
                    if (++i<names.length) {
                        sentence_etx.setText(names[i]);
                    }
                    // else{ // uncomment to reset the value of i
                    //     i=0;
                    // }
                }
            });

            btn_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (++i<names.length) {
                        sentence_etx.setText(names[i]);
                    }
                     // else{ // uncomment to reset the value of i
                    //     i=0;
                    // }
                }
            });
    }
}

Your all buttons are doing same work , so you can simply have a listener and apply it on all button objects rather than creating separate anonymous listeners and

public class MainActivity extends AppCompatActivity {

    private TextView sentence_etx;
    private Button btn_1,btn_2;
    private String[] names = { "Apple","Mango","Cherry","Banana","Extra"};
    private int i=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sentence_etx = (TextView) findViewById(R.id.etx_sentence);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);

        // initialize listener
        btn_1.setOnClickListener(listner);
        btn_2.setOnClickListener(listner);
    }

    OnClickListener listner=new OnClickListener() {

        @Override
        public void onClick(View v) {
            // check bounds
            if (++i<names.length) {
                sentence_etx.setText(names[i]);
            }
            // else{ // uncomment to reset the value of i
            //     i=0;
            // }

            // note you can also add some conditional statement
            // to check which button is clicked using v.getId();
        }
    };

}


问:
Sitecore glass mapper general link in Mvc 4
Hi i'm currently learning sitecore 7 with MVC4 and glassmapper and I'm having some issues with the general linkfield. I can't seem to ouput the external links (not links to items) correctly from a general linkfield. What am I doing wrong?

My model:

```<code>[SitecoreType(TemplateId = "{F8168BAF-6916-47FE-BC7F-DE3B033CE233}")]
public class SocialLink : AbstractBase
{

    [SitecoreField]
    public virtual string Description { get; set; }

    [SitecoreField]
    public virtual string Class { get; set; }

    [SitecoreField(FieldType = SitecoreFieldType.GeneralLink)]
    public virtual Link Url { get; set; }

}
</code>```

in the view:

```<code>@foreach (var socialLink in Model.SocialFolder.Socials)
{
     <a href="@socialLink.Url" class="connect @socialLink.Class">@socialLink.Description</a>
}
</code>```

Output:

```<code><a href="Glass.Mapper.Sc.Fields.Link" class="connect slideshare">Read us on Slideshare</a>
</code>```

Thanks in advance.

答:
So that Anchors and Querystrings are supported, it's best to use link.BuildUrl((SafeDictionary<string>)null)

There are two Link.BuildUrl()methods and, annoyingly, they both have default parameters (although one marked as obsolete). You will need to specify which one via a typed null, or...

You can add an extension method which will make things easier

```<code>public static class GlassFieldExtensions
{
    public static string GetUrl(this Link link)
    {
        return link.BuildUrl(null as SafeDictionary<string>);
    }
}
</code>```

And in the HTML:

```<code>@foreach (var socialLink in Model.SocialFolder.Socials)
{
     <a href="@socialLink.GetUrl()" class="connect @socialLink.Class">@socialLink.Description</a>
}
</code>```

Body:
Hi i'm currently learning sitecore 7 with MVC4 and glassmapper and I'm having some issues with the general linkfield. I can't seem to ouput the external links (not links to items) correctly from a general linkfield. What am I doing wrong?

My model:

[SitecoreType(TemplateId = "{F8168BAF-6916-47FE-BC7F-DE3B033CE233}")]
public class SocialLink : AbstractBase
{

    [SitecoreField]
    public virtual string Description { get; set; }

    [SitecoreField]
    public virtual string Class { get; set; }

    [SitecoreField(FieldType = SitecoreFieldType.GeneralLink)]
    public virtual Link Url { get; set; }

}

in the view:

@foreach (var socialLink in Model.SocialFolder.Socials)
{
     @socialLink.Description
}

Output:

Read us on Slideshare

Thanks in advance.

Body:
So that Anchors and Querystrings are supported, it's best to use link.BuildUrl((SafeDictionary<string>)null)

There are two Link.BuildUrl()methods and, annoyingly, they both have default parameters (although one marked as obsolete). You will need to specify which one via a typed null, or...

You can add an extension method which will make things easier

public static class GlassFieldExtensions
{
    public static string GetUrl(this Link link)
    {
        return link.BuildUrl(null as SafeDictionary<string>);
    }
}

And in the HTML:

@foreach (var socialLink in Model.SocialFolder.Socials)
{
     <a href="@socialLink.GetUrl()" class="connect @socialLink.Class">@socialLink.Description</a>
}


问:
Dependency ordering error for multi-job make
The Makefile below has to create (multiple) output directories, and generate output in those directories, from input in the directory above. So, on entry, dirn exists, and dirn/file.foo exists. The build has to create dirn/out/file.bar.

This Makefile works when run as a single job (note that it creates the two required source directories and files in the $(shell)). It presumably works because makedirs is the first/leftmost prerequisite for all. However, it doesn't work for a multi-job make (ie. make -j4/whatever).

Any ideas on how to fix the dependencies to ensure that the output directories are made before they're required?

EDIT

I should have made it clear that I have tried various order-only prerequisite solutions, but I couldn't do this and guarantee that the target actually rebuilt (the point of order-only is generally to prevent rebuilding, not enforce dependency ordering). If you have an OO solution, please check it! Thanks.

```<code># expected output:
# made directories
# copying dir1/out/../file.foo to dir1/out/file.bar
# copying dir2/out/../file.foo to dir2/out/file.bar
# created all output files
# done

    $(shell mkdir dir1 >& /dev/null; touch dir1/file.foo; \
            mkdir dir2 >& /dev/null; touch dir2/file.foo)

    OUTDIRS = dir1/out dir2/out
    OUTPUTS = dir1/out/file.bar dir2/out/file.bar

    .DEFAULT_GOAL := all

    .PHONY: makedirs $(OUTDIRS)

    .SUFFIXES: .foo .bar

    %.bar : ../%.foo
        @echo "copying $< to $@"
        @cp $< $@

    all : makedirs outputs
        @echo "done"

    outputs : $(OUTPUTS)
        @echo "created all output files"

    makedirs : $(OUTDIRS)
        @mkdir -p $(OUTDIRS)
        @echo "made directories"

    clean :
        @rm -rf dir1 dir2
</code>```

答:
make $(OUTPUTS) have an order-only dependency on the directories themselves:

```<code> $(OUTDIRS) :
      mkdir -p $@

 $(OUTPUTS) : | $(OUTDIRS)
</code>```

This will guarentee that the directories are created before $(OUTPUTS), but will not cause the outputs to rebuild if the directories are newer than the targets (which is important, as a directories' time stamp is set each time a file is added to it...).

Note: you can also add a mkdir -p in your output recipe's which will create the directory if it's not already there each time you run an output rule, but I prefer the above method.

Note2: in your existing makefile you could also just add a line: $(OUTPUTS): makedirs, which would force the makedirs rule to be run before any of the outputs are built, but again, I prefer the above solution :-)

---- EDIT: -----

Something is odd then -- what version of make are you using?  I just ran the following:   notice the sleep 1's when making the directories, which means if there was a concurrency issue, it would definitely have hit:

```<code>$(shell mkdir dir1 >& /dev/null; touch dir1/file.foo; \
        mkdir dir2 >& /dev/null; touch dir2/file.foo)

OUTDIRS = dir1/out dir2/out
OUTPUTS = dir1/out/file.bar dir2/out/file.bar

.DEFAULT_GOAL := all

$(OUTPUTS) : | $(OUTDIRS)

$(OUTDIRS) :
        @echo "making $@"
        sleep 1
        mkdir -p $@
        @echo "done making $@"

%.bar : ../%.foo
        @echo "copying $< to $@"
        @cp $< $@

all : outputs
        @echo "done $@"

outputs : $(OUTPUTS)
        @echo "created all output files"

clean :
        @rm -rf dir1 dir2
</code>```

And the output was:

```<code>~/sandbox/tmp20> make -j -f Makefile2
making dir1/out
making dir2/out
sleep 1
sleep 1
mkdir -p dir1/out
mkdir -p dir2/out
done making dir1/out
done making dir2/out
copying dir1/out/../file.foo to dir1/out/file.bar
copying dir2/out/../file.foo to dir2/out/file.bar
created all output files
done all
</code>```

Notice it concurrently builds dir1/out and dir2/out, and doesn't run the pattern rules until both are finished.  I also verified that the solution I mentioned in note2 also works (at least on my machine...).

When doing pattern rules, you can specify dependencies outside of the pattern, so you can do:

```<code>foo.o: foo.h

%.o: %.c
    recipe here...
</code>```

which will rebuild foo.o if foo.h is newer, or try to build foo.h if it doesn't exist before foo.o is built.

Body:
The Makefile below has to create (multiple) output directories, and generate output in those directories, from input in the directory above. So, on entry, dirn exists, and dirn/file.foo exists. The build has to create dirn/out/file.bar.

This Makefile works when run as a single job (note that it creates the two required source directories and files in the $(shell)). It presumably works because makedirs is the first/leftmost prerequisite for all. However, it doesn't work for a multi-job make (ie. make -j4/whatever).

Any ideas on how to fix the dependencies to ensure that the output directories are made before they're required?

EDIT

I should have made it clear that I have tried various order-only prerequisite solutions, but I couldn't do this and guarantee that the target actually rebuilt (the point of order-only is generally to prevent rebuilding, not enforce dependency ordering). If you have an OO solution, please check it! Thanks.

# expected output:
# made directories
# copying dir1/out/../file.foo to dir1/out/file.bar
# copying dir2/out/../file.foo to dir2/out/file.bar
# created all output files
# done

    $(shell mkdir dir1 >& /dev/null; touch dir1/file.foo; \
            mkdir dir2 >& /dev/null; touch dir2/file.foo)

    OUTDIRS = dir1/out dir2/out
    OUTPUTS = dir1/out/file.bar dir2/out/file.bar

    .DEFAULT_GOAL := all

    .PHONY: makedirs $(OUTDIRS)

    .SUFFIXES: .foo .bar

    %.bar : ../%.foo
        @echo "copying $< to $@"
        @cp $< $@

    all : makedirs outputs
        @echo "done"

    outputs : $(OUTPUTS)
        @echo "created all output files"

    makedirs : $(OUTDIRS)
        @mkdir -p $(OUTDIRS)
        @echo "made directories"

    clean :
        @rm -rf dir1 dir2

Body:
make $(OUTPUTS) have an order-only dependency on the directories themselves:

 $(OUTDIRS) :
      mkdir -p $@

 $(OUTPUTS) : | $(OUTDIRS)

This will guarentee that the directories are created before $(OUTPUTS), but will not cause the outputs to rebuild if the directories are newer than the targets (which is important, as a directories' time stamp is set each time a file is added to it...).

Note: you can also add a mkdir -p in your output recipe's which will create the directory if it's not already there each time you run an output rule, but I prefer the above method.

Note2: in your existing makefile you could also just add a line: $(OUTPUTS): makedirs, which would force the makedirs rule to be run before any of the outputs are built, but again, I prefer the above solution :-)

---- EDIT: -----

Something is odd then -- what version of make are you using?  I just ran the following:   notice the sleep 1's when making the directories, which means if there was a concurrency issue, it would definitely have hit:

$(shell mkdir dir1 >& /dev/null; touch dir1/file.foo; \
        mkdir dir2 >& /dev/null; touch dir2/file.foo)

OUTDIRS = dir1/out dir2/out
OUTPUTS = dir1/out/file.bar dir2/out/file.bar

.DEFAULT_GOAL := all

$(OUTPUTS) : | $(OUTDIRS)

$(OUTDIRS) :
        @echo "making $@"
        sleep 1
        mkdir -p $@
        @echo "done making $@"

%.bar : ../%.foo
        @echo "copying $< to $@"
        @cp $< $@

all : outputs
        @echo "done $@"

outputs : $(OUTPUTS)
        @echo "created all output files"

clean :
        @rm -rf dir1 dir2

And the output was:

~/sandbox/tmp20> make -j -f Makefile2
making dir1/out
making dir2/out
sleep 1
sleep 1
mkdir -p dir1/out
mkdir -p dir2/out
done making dir1/out
done making dir2/out
copying dir1/out/../file.foo to dir1/out/file.bar
copying dir2/out/../file.foo to dir2/out/file.bar
created all output files
done all

Notice it concurrently builds dir1/out and dir2/out, and doesn't run the pattern rules until both are finished.  I also verified that the solution I mentioned in note2 also works (at least on my machine...).

When doing pattern rules, you can specify dependencies outside of the pattern, so you can do:

foo.o: foo.h

%.o: %.c
    recipe here...

which will rebuild foo.o if foo.h is newer, or try to build foo.h if it doesn't exist before foo.o is built.


问:
How do I set the SMB username and password?
I have a Vagrantfile (copied below) that uses SMB shared folders. On up, Vagrant always prompts for the username and password. How do I set the username and password once and stop the prompts?!

Windows 10 Pro x64 1703

Vagrant 1.9.5

VirtualBox 5.1.22

Vagrantfile

```<code># -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://atlas.hashicorp.com/search.
  config.vm.box = "ubuntu/xenial64"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  config.vm.synced_folder "./www", "/var/www", type: "smb",
    mount_options: ["username=mymail@live.ru","password=mypass"] # <------------------- correct

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
    vb.cpus = 2
    vb.memory = 2048
  end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
  # such as FTP and Heroku are also available. See the documentation at
  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
  # config.push.define "atlas" do |push|
  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
  # end

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end
</code>```

答:
You can specify smb_username and smb_password (see https://www.vagrantup.com/docs/synced-folders/smb.html#smb_username)

```<code>config.vm.synced_folder "./www", "/var/www", type: "smb",
    smb_password: "mypass", smb_username: "mymail@live.ru",
    mount_options: ["username=mymail@live.ru","password=mypass"]
</code>```

Body:
I have a Vagrantfile (copied below) that uses SMB shared folders. On up, Vagrant always prompts for the username and password. How do I set the username and password once and stop the prompts?!

Windows 10 Pro x64 1703

Vagrant 1.9.5

VirtualBox 5.1.22

Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://atlas.hashicorp.com/search.
  config.vm.box = "ubuntu/xenial64"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  config.vm.synced_folder "./www", "/var/www", type: "smb",
    mount_options: ["username=mymail@live.ru","password=mypass"] # <------------------- correct

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
    vb.cpus = 2
    vb.memory = 2048
  end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
  # such as FTP and Heroku are also available. See the documentation at
  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
  # config.push.define "atlas" do |push|
  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
  # end

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end

Body:
You can specify smb_username and smb_password (see https://www.vagrantup.com/docs/synced-folders/smb.html#smb_username)

config.vm.synced_folder "./www", "/var/www", type: "smb",
    smb_password: "mypass", smb_username: "mymail@live.ru",
    mount_options: ["username=mymail@live.ru","password=mypass"]