问:
OnclickListener on RecylerView and getting the Id of clicked Item
I need to set onClickListener on RecyclerView which gets the Json Id of an Item Clicked and redirects to the fragment which displays the details of the product based on that Json ID.  How Can I implement this in adapter? I am stuck here. I was able to set onClickListener but I couldn't get the Json ID.

This is my Adapter.

```<code>import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dell.retroexample.MainActivity;
import com.example.dell.retroexample.R;
import com.example.dell.retroexample.apiHandlers.model.Ad;

import java.util.List;

/**
 * Created by dell on 7/3/2017.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{

    private List<Ad> ads;
    private Context context;

    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);

    }

    @Override
    public int getItemCount() {
        return ads.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        ImageView thumbnail;
        TextView name, details;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
        }

    }
}
</code>```

This is my MainActivity

```<code>package com.example.dell.retroexample;

import android.content.res.Resources;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import com.example.dell.retroexample.apiHandlers.adapter.RecyclerAdapter;
import com.example.dell.retroexample.apiHandlers.model.Ad;
import com.example.dell.retroexample.apiHandlers.rest.ApiInterface;
import com.example.dell.retroexample.apiHandlers.rest.ApiClient;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerAdapter adapter=null;
    private List<Ad> ads;
    private ApiInterface apiInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView=(RecyclerView)findViewById(R.id.ads_recycler_view);
                // calculating the number of columns
        int columns=2;
        DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
        double widthPixels = lDisplayMetrics.widthPixels;
        Log.e("Width", String.valueOf(widthPixels));
        columns=(int)widthPixels/dpToPx(170);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this,  columns);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        apiInterface=ApiClient.getClient().create(ApiInterface.class);

        Call <List<Ad>> call=apiInterface.getads();

        call.enqueue(new Callback<List<Ad>>() {
            @Override
            public void onResponse(Call<List<Ad>> call, Response<List<Ad>> response) {
                ads=response.body();
                adapter=new RecyclerAdapter(ads, MainActivity.this);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<List<Ad>> call, Throwable t) {

                Log.e(TAG, t.toString());
            }
        });

    }

    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

}
</code>```

答:
Try this:

```<code>itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getLayoutPosition();
                    String id=ads.get(position).getId();
                    // call fragment
                }
}
</code>```

Add this in ViewHolder Constructor.

Body:
I need to set onClickListener on RecyclerView which gets the Json Id of an Item Clicked and redirects to the fragment which displays the details of the product based on that Json ID.  How Can I implement this in adapter? I am stuck here. I was able to set onClickListener but I couldn't get the Json ID.

This is my Adapter.

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dell.retroexample.MainActivity;
import com.example.dell.retroexample.R;
import com.example.dell.retroexample.apiHandlers.model.Ad;

import java.util.List;

/**
 * Created by dell on 7/3/2017.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{

    private List<Ad> ads;
    private Context context;

    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);

    }

    @Override
    public int getItemCount() {
        return ads.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        ImageView thumbnail;
        TextView name, details;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
        }

    }
}

This is my MainActivity

package com.example.dell.retroexample;

import android.content.res.Resources;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import com.example.dell.retroexample.apiHandlers.adapter.RecyclerAdapter;
import com.example.dell.retroexample.apiHandlers.model.Ad;
import com.example.dell.retroexample.apiHandlers.rest.ApiInterface;
import com.example.dell.retroexample.apiHandlers.rest.ApiClient;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerAdapter adapter=null;
    private List<Ad> ads;
    private ApiInterface apiInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView=(RecyclerView)findViewById(R.id.ads_recycler_view);
                // calculating the number of columns
        int columns=2;
        DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
        double widthPixels = lDisplayMetrics.widthPixels;
        Log.e("Width", String.valueOf(widthPixels));
        columns=(int)widthPixels/dpToPx(170);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this,  columns);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        apiInterface=ApiClient.getClient().create(ApiInterface.class);

        Call <List<Ad>> call=apiInterface.getads();

        call.enqueue(new Callback<List<Ad>>() {
            @Override
            public void onResponse(Call<List<Ad>> call, Response<List<Ad>> response) {
                ads=response.body();
                adapter=new RecyclerAdapter(ads, MainActivity.this);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<List<Ad>> call, Throwable t) {

                Log.e(TAG, t.toString());
            }
        });

    }

    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

}

Body:
Try this:

itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getLayoutPosition();
                    String id=ads.get(position).getId();
                    // call fragment
                }
}

Add this in ViewHolder Constructor.


来源: stackexchange

问:
Confused about testCompile and androidTestCompile in Android Gradle
I'm new to testing world and even more to Android testing world. While doing research on Robolectric that aids with tests on android one thing confuses me the most. Sometimes on the web I see people using testCompile keyword in dependencies of the gradle build script when referencing Robolectric while others use androidTestCompile. Certainly both can't be valid?

Can somebody explain the difference between the both and which of these should be the one used when using Robolectric?

答:
//unit testing

```<code>testCompile 'junit:junit:4.12'
</code>```

The above code is a dependency of JUnit 4 in build.gradle file in android studio.
You see that it has testCompile, beacuse JUnit runs on JVM and does not require a device or emulator  to run. That also means that JUnit tests will not require the application context to run and if they require we would need to "MOCK" them.

//Insturmented Unit Testing

```<code>androidTestCompile('com.android.support.test:runner:0.5', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
</code>```

Now we see androidTestCompile here, because this time we intend to use the device or emulator for tests, that is Instrumentation testing. For beter clarification I would suggest to read from developer.android.com

ContentLicense: CC BY-SA 3.0

Body:
//unit testing

testCompile 'junit:junit:4.12'

The above code is a dependency of JUnit 4 in build.gradle file in android studio.
You see that it has testCompile, beacuse JUnit runs on JVM and does not require a device or emulator  to run. That also means that JUnit tests will not require the application context to run and if they require we would need to "MOCK" them.

//Insturmented Unit Testing

androidTestCompile('com.android.support.test:runner:0.5', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

Now we see androidTestCompile here, because this time we intend to use the device or emulator for tests, that is Instrumentation testing. For beter clarification I would suggest to read from developer.android.com


答:
You can add Ad ad = ads.get(RecyclerAdapter.MyViewHolder.this.getAdapterPosition()); in your OnCkick method to retrieve the current object. Then use Interface to pass the value to the fragment.

```<code> @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
                Ad ad = ads.get(RecyclerAdapter.MyViewHolder.this.getAdapterPosition());
               //use interface to pass ad to the fragment....
            }
</code>```

Title: OnclickListener on RecylerView and getting the Id of clicked Item

Body:
You can add Ad ad = ads.get(RecyclerAdapter.MyViewHolder.this.getAdapterPosition()); in your OnCkick method to retrieve the current object. Then use Interface to pass the value to the fragment.

 @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
                Ad ad = ads.get(RecyclerAdapter.MyViewHolder.this.getAdapterPosition());
               //use interface to pass ad to the fragment....
            }


问:
How to us ng-Repeat for angular translate for array objects?
I am currently working on an Angular project with the plugin angular translate from Pascal Precht. I have an FAQ page which has a tabs for answer. What I want to achieve is to have a dynamic values for questions. So that I will just have a loop for those questions and those questions will be in a translation file as Json array. here is my sample json file.

```<code>"FAQS_QUESTION"  : [
   {
     "question" : "Question 1?",
     "answer"   : "Answer 1 "
   },
   {
     "question" : "Question 2?",
     "answer"   : "Answer 2"
   },
   {
     "question" : "Question 3?",
     "answer"   : "Answer 3"
   }
]
</code>```

I tried the code below but it is not working. I get a "angular.js:14525 Translation for FAQS_QUESTION doesn't exist"

```<code>ul( ng-repeat="thumbnail in 'FAQS_QUESTION' | translate ")
   li
       | {{thumbnail.question}}
       | {{thumbnail.answer}}
</code>```

I Also tried loading it in my Controller with no luck

```<code>$translate('FAQS_QUESTION').then(function (translations) {
    console.log(translations.questions);
}, function (translationIds) {
    console.log(translationIds);
});
</code>```

I found a workaround and the implementation is like this:

```<code>ul(ng-init="count = ('FAQS_QUESTION_COUNT' | translate)")
  li(ng-repeat="item in getQuestionCount(count) track by $index")
     p(translate="FAQS_QUESTION.{{$index}}.question")
     p(translate="FAQS_QUESTION.{{$index}}.answer")
</code>```

It solves my problem. But it will be a tedious for maintenance to indicate the count for each Iteration. Since we are planning to have a section for each quetions

Can anyone help me for the workaround for this one? I am not sure I appreciate all your help. Thanks

答:
In this snippet

```<code>ul( ng-repeat="thumbnail in 'FAQS_QUESTION' | translate ")
   li
       | {{thumbnail.question}}
       | {{thumbnail.answer}}
</code>```

your value 'FAQS_QUESTION' is just a plain string, so you're not referencing your data. Also, the translate-filter doesn't work with collections i believe.

Instead, try doing something like this:

```<code>ul( ng-repeat="thumbnail in FAQS_QUESTION")
   li
       | {{thumbnail.question | translate}}
       | {{thumbnail.answer | translate}}
</code>```

Body:
I am currently working on an Angular project with the plugin angular translate from Pascal Precht. I have an FAQ page which has a tabs for answer. What I want to achieve is to have a dynamic values for questions. So that I will just have a loop for those questions and those questions will be in a translation file as Json array. here is my sample json file.

"FAQS_QUESTION"  : [
   {
     "question" : "Question 1?",
     "answer"   : "Answer 1 "
   },
   {
     "question" : "Question 2?",
     "answer"   : "Answer 2"
   },
   {
     "question" : "Question 3?",
     "answer"   : "Answer 3"
   }
]

I tried the code below but it is not working. I get a "angular.js:14525 Translation for FAQS_QUESTION doesn't exist"

ul( ng-repeat="thumbnail in 'FAQS_QUESTION' | translate ")
   li
       | {{thumbnail.question}}
       | {{thumbnail.answer}}

I Also tried loading it in my Controller with no luck

$translate('FAQS_QUESTION').then(function (translations) {
    console.log(translations.questions);
}, function (translationIds) {
    console.log(translationIds);
});

I found a workaround and the implementation is like this:

ul(ng-init="count = ('FAQS_QUESTION_COUNT' | translate)")
  li(ng-repeat="item in getQuestionCount(count) track by $index")
     p(translate="FAQS_QUESTION.{{$index}}.question")
     p(translate="FAQS_QUESTION.{{$index}}.answer")

It solves my problem. But it will be a tedious for maintenance to indicate the count for each Iteration. Since we are planning to have a section for each quetions

Can anyone help me for the workaround for this one? I am not sure I appreciate all your help. Thanks

Body:
In this snippet

ul( ng-repeat="thumbnail in 'FAQS_QUESTION' | translate ")
   li
       | {{thumbnail.question}}
       | {{thumbnail.answer}}

your value 'FAQS_QUESTION' is just a plain string, so you're not referencing your data. Also, the translate-filter doesn't work with collections i believe.

Instead, try doing something like this:

ul( ng-repeat="thumbnail in FAQS_QUESTION")
   li
       | {{thumbnail.question | translate}}
       | {{thumbnail.answer | translate}}


问:
Binding with CollectionViewSource
I am trying to implement some combo box sorting using CollectionViewSource.  This combo box is actually part of a data template and is repeated in a list view.  My first approach seemed to work (using CollectionViewSource) but all my combo boxes shared the same data context.  This made it so whenever one of the other boxes was changed all the others changed to reflect - not a desired side effect.

I decided to just pull back and try to implement a basic combo box (not inside a data template) using inline xaml for specifying the CollectionViewSource (as opposed to creating the cvs as a static resource).  I have not been able to successfully get my data to display.  I'm probably going about this entirely wrong as I'm still new to WPF.

Here is the xaml for my combo box:

```<code><ComboBox>
    <ComboBox.ItemsSource>
        <Binding>
            <Binding.Source>
                <CollectionViewSource Source="{Binding Path=Configurations}">
                    <CollectionViewSource.SortDescriptions>
                        <scm:SortDescription PropertyName="AgencyName" />
                    </CollectionViewSource.SortDescriptions>
                </CollectionViewSource>
            </Binding.Source>
        </Binding>
    </ComboBox.ItemsSource>
</ComboBox>
</code>```

The DataContext of the user control where this combo box lives is bound to an object which has an ObservableCollection called Configurations and each configuration has a property called AgencyName.  I've verified that this works fine using standard binding without the cvs so I know everything is fine in that accord.

Any help would be greatly appreciated as I have ran out of excuses to my boss :).  I also don't want to have to drop down into code and do the sorting in the code behind (which I could when I build the ObservableCollection but IMHO that violates the DRY principle).

答:
Binding depends on VisualTree which cvs is not a visual, so Binding doesn't work.

You can use x:Reference instead.

```<code><Border x:Name="border" />
<ComboBox>
    <ComboBox.ItemsSource>
        <Binding>
            <Binding.Source>
                <CollectionViewSource Source="{Binding Path=DataContext.Configurations, Source={x:Reference border}}">
                    <CollectionViewSource.SortDescriptions>
                        <scm:SortDescription PropertyName="AgencyName" />
                    </CollectionViewSource.SortDescriptions>
                </CollectionViewSource>
            </Binding.Source>
        </Binding>
    </ComboBox.ItemsSource>
</ComboBox>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Binding with CollectionViewSource

Body:
I am trying to implement some combo box sorting using CollectionViewSource.  This combo box is actually part of a data template and is repeated in a list view.  My first approach seemed to work (using CollectionViewSource) but all my combo boxes shared the same data context.  This made it so whenever one of the other boxes was changed all the others changed to reflect - not a desired side effect.

I decided to just pull back and try to implement a basic combo box (not inside a data template) using inline xaml for specifying the CollectionViewSource (as opposed to creating the cvs as a static resource).  I have not been able to successfully get my data to display.  I'm probably going about this entirely wrong as I'm still new to WPF.

Here is the xaml for my combo box:

<ComboBox>
    <ComboBox.ItemsSource>
        <Binding>
            <Binding.Source>
                <CollectionViewSource Source="{Binding Path=Configurations}">
                    <CollectionViewSource.SortDescriptions>
                        <scm:SortDescription PropertyName="AgencyName" />
                    </CollectionViewSource.SortDescriptions>
                </CollectionViewSource>
            </Binding.Source>
        </Binding>
    </ComboBox.ItemsSource>
</ComboBox>

The DataContext of the user control where this combo box lives is bound to an object which has an ObservableCollection called Configurations and each configuration has a property called AgencyName.  I've verified that this works fine using standard binding without the cvs so I know everything is fine in that accord.

Any help would be greatly appreciated as I have ran out of excuses to my boss :).  I also don't want to have to drop down into code and do the sorting in the code behind (which I could when I build the ObservableCollection but IMHO that violates the DRY principle).

Body:
Binding depends on VisualTree which cvs is not a visual, so Binding doesn't work.

You can use x:Reference instead.

<Border x:Name="border" />
<ComboBox>
    <ComboBox.ItemsSource>
        <Binding>
            <Binding.Source>
                <CollectionViewSource Source="{Binding Path=DataContext.Configurations, Source={x:Reference border}}">
                    <CollectionViewSource.SortDescriptions>
                        <scm:SortDescription PropertyName="AgencyName" />
                    </CollectionViewSource.SortDescriptions>
                </CollectionViewSource>
            </Binding.Source>
        </Binding>
    </ComboBox.ItemsSource>
</ComboBox>


问:
Cannot printout concatenated tensor by tf.concat() (tensorflow 1.2.1 - gpu / py36)
Learning Tensorflow (Python bindings) since the last month. I've been reading the docs on tf.concat(), but cannot resolve the problem as shown below, so I'm asking for your help!

What I want to do is to see the contents of the concatenated tensor.
I tried Tensor.eval().

```<code>import tensorflow as tf
import numpy as np

a=np.zeros([3,3])
a_trail=np.ones([3,3])

with tf.Session() as sess:
    concatenated=tf.concat([a, a_trail], axis=0)
    print(concatenated)
    print(type(concatenated))
    concatenated.eval()
    sess.run(concatenated)
    sess.run(tf.constant(concatenated))
</code>```

Output:

```<code>Tensor("concat_2:0", shape=(6, 3), dtype=float64)
<class 'tensorflow.python.framework.ops.Tensor'>
(nothing prints)
(nothing shows up either meh =/)
Error: List of Tensors when single Tensor expected
</code>```

tf.concat() supposed to return Tensor and looks like it does. But why aren't T.eval() and sess.run() not working?

答:
Most of TF functions take tensors as parameters. This applies to tf.concat. As you can see from the documentation:

values: A list of Tensor objects or a single Tensor.

And you provide numpy arrays and not tensors. Here is a working example.

```<code>import tensorflow as tf
import numpy as np

a=np.zeros([3,3])
b=np.ones([3,3])

A = tf.constant(a)
B = tf.constant(b)
concatenated=tf.concat([A, B], axis=0)

with tf.Session() as sess:
    print sess.run(concatenated)
</code>```

Not related to your question, but separate a graph definition from a graph execution (you do everything in tf.session, I define everything outside and only execute in the session

Body:
Learning Tensorflow (Python bindings) since the last month. I've been reading the docs on tf.concat(), but cannot resolve the problem as shown below, so I'm asking for your help!

What I want to do is to see the contents of the concatenated tensor.
I tried Tensor.eval().

import tensorflow as tf
import numpy as np

a=np.zeros([3,3])
a_trail=np.ones([3,3])

with tf.Session() as sess:
    concatenated=tf.concat([a, a_trail], axis=0)
    print(concatenated)
    print(type(concatenated))
    concatenated.eval()
    sess.run(concatenated)
    sess.run(tf.constant(concatenated))

Output:

Tensor("concat_2:0", shape=(6, 3), dtype=float64)
<class 'tensorflow.python.framework.ops.Tensor'>
(nothing prints)
(nothing shows up either meh =/)
Error: List of Tensors when single Tensor expected

tf.concat() supposed to return Tensor and looks like it does. But why aren't T.eval() and sess.run() not working?

Body:
Most of TF functions take tensors as parameters. This applies to tf.concat. As you can see from the documentation:

values: A list of Tensor objects or a single Tensor.

And you provide numpy arrays and not tensors. Here is a working example.

import tensorflow as tf
import numpy as np

a=np.zeros([3,3])
b=np.ones([3,3])

A = tf.constant(a)
B = tf.constant(b)
concatenated=tf.concat([A, B], axis=0)

with tf.Session() as sess:
    print sess.run(concatenated)

Not related to your question, but separate a graph definition from a graph execution (you do everything in tf.session, I define everything outside and only execute in the session


问:
How should I close a socket in a signal handler?
I'm writing a very simple server that loops forever until Ctrl-C is pressed. I'd like to have the signal handler for ctrl-c close the open sockets and shut down the server, but I don't know what the scope is for a signal handler, and I don't like the idea of declaring the socket(s) I would need to close to be global.

Can someone offer suggestions? Is there some standard way to do this?

答:
Well, since you have signal handlers, I'm going to assume you're on a Unix variant. If so:

A socket is identified to the kernel by the file number, which is an int. See socket(2).

That int is valid for your process

That int is valid for any processes forked after creating it

If not close-on-exec, it is valid for any process you exec.

So, it's perfectly valid in your signal handler. How you make your signal handler aware of which number to use depends on the language you're writing in, which you didn't specify. There are two approaches that will work in pretty much any language

If you don't have any cleanup to do except close and exit, just call exit. Or set the signal action to default, which is exit. The kernel will close the sockets.

Set a flag (which will generally be a global of some sort) to tell your select/poll loop to clean up and exit. Advantageous in that you don't have to worry about if various parts of your program are safe to call from a signal handler.

OwnerDisplayName: Zxaos

LastEditorDisplayName: Greg Hewgill

OwnerDisplayName: derobert


问:
Identifying which element invoked the event
I have following html code

```<code><input type="button"  id ="b1" value="Click me" onclick="msg()" />
<input type="button" id="b2"   value="Click me" onclick="msg()" />
</code>```

now in my javascript i want to identify whether button one was clicked or button 2. How can i do it?

答:
You should not mix JavaScript directly into your HTML with JavaScript attributes such as onclick. You should instead programmatically attach your handlers using JavaScript. At the simplest:

```<code>function msg = function( evt ){
  // For old IE versions that don't pass in the event,
  // get the global event object.
  if (!evt) evt = window.event;

  // Use currentTarget if available, target if not,
  // and srcElement for old versions of IE
  var receiver = evt.currentTarget || evt.target || evt.srcElement;

  alert( receiver.id );
};
document.getElementById('b1').onclick = msg;
</code>```

Event handlers are passed an event object as their first parameter (except for very old IE versions, which set a global event property).

The difference between the currentTarget and target properties has to do with event bubbling. If an event occurs on a child element, but then bubbles up to some ancestor that has a handler for that event, the currentTarget property is the child element and the target property is the ancestor that has the event handler.

Old versions of IE do not have currentTarget or target properties, but instead use srcElement to mean the same thing as target.

Now, if you are attaching your event handlers in code to elements directly (not using bubbling), you already (at one point) have a reference to the element. So here's the alternative, more-advanced-but-simpler method:

```<code>var inputs = document.getElementsByTagName('input');
for (var i=0,len=inputs.length;i<len;++i){
  if (inputs[i].type=='button'){
    inputs[i].onclick = (function(i){
      return function(){
        alert(inputs[i].id);
      }
    })(i);
  }
};
</code>```

Body:
I have following html code

<input type="button"  id ="b1" value="Click me" onclick="msg()" />
<input type="button" id="b2"   value="Click me" onclick="msg()" />

now in my javascript i want to identify whether button one was clicked or button 2. How can i do it?

Body:
You should not mix JavaScript directly into your HTML with JavaScript attributes such as onclick. You should instead programmatically attach your handlers using JavaScript. At the simplest:

function msg = function( evt ){
  // For old IE versions that don't pass in the event,
  // get the global event object.
  if (!evt) evt = window.event;

  // Use currentTarget if available, target if not,
  // and srcElement for old versions of IE
  var receiver = evt.currentTarget || evt.target || evt.srcElement;

  alert( receiver.id );
};
document.getElementById('b1').onclick = msg;

Event handlers are passed an event object as their first parameter (except for very old IE versions, which set a global event property).

The difference between the currentTarget and target properties has to do with event bubbling. If an event occurs on a child element, but then bubbles up to some ancestor that has a handler for that event, the currentTarget property is the child element and the target property is the ancestor that has the event handler.

Old versions of IE do not have currentTarget or target properties, but instead use srcElement to mean the same thing as target.

Now, if you are attaching your event handlers in code to elements directly (not using bubbling), you already (at one point) have a reference to the element. So here's the alternative, more-advanced-but-simpler method:

var inputs = document.getElementsByTagName('input');
for (var i=0,len=inputs.length;i<len;++i){
  if (inputs[i].type=='button'){
    inputs[i].onclick = (function(i){
      return function(){
        alert(inputs[i].id);
      }
    })(i);
  }
};


问:
Inserting new rows in a table
When I add news rows using the Insert into select code, the new rows get added randomly in between the already existing rows, instead of getting added to the end of the table.

I'm using, Insert into Table1 (Name1) select Name from Table2.

答:
I agree with Tim's answer. But if you still want the data inserted in the way you want, then you can try to add the primary key yourself which is incremental (like 1,2,3 ... or 10,20,30 ...).
Although I don't recommend it, but I think following can help you if you don't want to handle the primary key yourself.

How do I add a auto_increment primary key in SQL Server database?

Title: Inserting new rows in a table


问:
Google Sheet API - How to get all sheets name in spreadsheet file?
I use Google Sheet API Version 4.
And i want to get all sheets name what available in that spreadsheet file?
So if you have any way to do it, tell me please. Thanks</p>

答:
We can call spreadsheet object to get all information of spreadsheet.

```<code>   $service = new Google_Service_Sheets($client);
   $spreadsheetId = 'your spredsheetid';
   $sheetInfo = $service->spreadsheets->get($spreadsheetId);
   $allsheet_info = $sheetInfo['sheets'];
   $idCats = array_column($allsheet_info, 'properties');
</code>```

Thanks

Body:
We can call spreadsheet object to get all information of spreadsheet.

   $service = new Google_Service_Sheets($client);
   $spreadsheetId = 'your spredsheetid';
   $sheetInfo = $service->spreadsheets->get($spreadsheetId);
   $allsheet_info = $sheetInfo['sheets'];
   $idCats = array_column($allsheet_info, 'properties');

Thanks


问:
Not able to read InputStream from RS232 Bluetooth module
I am trying to read values from a weighing machine connected to bluetooth module(M143 RS232 Bluetooth Serial Adapter purchased from eBay).I am able to connect the device and i am getting Socket object.But the InputStream is blocking and not able to read data from the stream(inputstream.available() is always returns zero).There is no issue when i write something to the OutputStream.I tried using BufferedReader but no change.Following is the code i tried.

```<code>InputStream inputStream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
   total.append(line).append('\n');
}
//code is not reaching here it is blocking in the while loop
if(outputStream!=null){
  outputStream.flush();
  outputStream.close();
}
</code>```

答:
Communication via bluetooth with other android devices or microcontrollers such as Arduino Android Smooth Bluetooth

// This thread runs during a connection with a remote device.

// It handles all incoming and outgoing transmissions.

```<code>private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket, String socketType) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
</code>```

Body:
I am trying to read values from a weighing machine connected to bluetooth module(M143 RS232 Bluetooth Serial Adapter purchased from eBay).I am able to connect the device and i am getting Socket object.But the InputStream is blocking and not able to read data from the stream(inputstream.available() is always returns zero).There is no issue when i write something to the OutputStream.I tried using BufferedReader but no change.Following is the code i tried.

InputStream inputStream = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
   total.append(line).append('\n');
}
//code is not reaching here it is blocking in the while loop
if(outputStream!=null){
  outputStream.flush();
  outputStream.close();
}

Body:
Communication via bluetooth with other android devices or microcontrollers such as Arduino Android Smooth Bluetooth

// This thread runs during a connection with a remote device.

// It handles all incoming and outgoing transmissions.

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket, String socketType) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }


问:
Filtering two arrays returns blank array
I have these two arrays and have a simple method to filter the matching items from both the data array and the data2 array. But it returns empty array when it should return two items. What am i doing wrong?

var data =  [{ teamId: 74, teamName: 'Blah' },
 { teamId: 94, teamName: 'Panhi' },
 { teamId: 30, teamName: 'Writer' },
 { teamId: 121, teamName: 'People' },
 { teamId: 85, teamName: 'Perf' },
 { teamId: 31, teamName: 'Tell' },
 { teamId: 32, teamName: 'Gall' },
 { teamId: 137, teamName: 'Bird' },
 { teamId: 79, teamName: 'Blue' },
 { teamId: 119, teamName: 'Red' },
 { teamId: 66, teamName: 'Pluto' },
 { teamId: 56, teamName: 'PolarBear' },
 { teamId: 33, teamName: 'Praxis' },
 { teamId: 62, teamName: 'Purple' }
];

var data2 = [ { id: 1, reId: 52, teamId: 94 },
  { id: 2, reId: 52, teamId: 32 } ];

var found = data.filter(i => i.teamId === data2.teamId);
console.log(found);```

答:
data2 is an array, you should loop through it to filter with each of its elements.

refer the below example:

var data =  [{ teamId: 74, teamName: 'Blah' },
 { teamId: 94, teamName: 'Panhi' },
 { teamId: 30, teamName: 'Writer' },
 { teamId: 121, teamName: 'People' },
 { teamId: 85, teamName: 'Perf' },
 { teamId: 31, teamName: 'Tell' },
 { teamId: 32, teamName: 'Gall' },
 { teamId: 137, teamName: 'Bird' },
 { teamId: 79, teamName: 'Blue' },
 { teamId: 119, teamName: 'Red' },
 { teamId: 66, teamName: 'Pluto' },
 { teamId: 56, teamName: 'PolarBear' },
 { teamId: 33, teamName: 'Praxis' },
 { teamId: 62, teamName: 'Purple' }
];

var data2 = [ { id: 1, reId: 52, teamId: 94 },
  { id: 2, reId: 52, teamId: 32 } ];

var found = data.filter(i => i.teamId === data2[0].teamId || i.teamId === data2[1].teamId);
console.log(found);```


问:
Overriding Grails config for plugins
I am trying to figure out how to separate deployment specific config from my Grails 3 app. In Grails 2 I could setup a config location lookup which would load my dev specific config file. And in Grails 3 I have found that I can provide additional spring configs when running the app, i.e.:

```<code>./grailsw -Dspring.config.location=classpath:application.yml,file:///home/nigel/src/app/dev.yml run-app
</code>```

However, this doesn't work if I'm using plugins, such as below, where it will just used the config in grails-app/conf/application.yml:

```<code>./grailsw -Dspring.config.location=classpath:application.yml,file:///home/nigel/src/app/dev.yml url-mappings-report
</code>```

So my question is, how do I provide deployment/dev specific config files to grails so that it works with the grails plugins.

答:
For grails 3, you can use external config plugin. And configure the config locations.</p>

```<code>grails.config.locations = ["classpath:myconfig.groovy"]
</code>```

Title: Overriding Grails config for plugins

Body:
I am trying to figure out how to separate deployment specific config from my Grails 3 app. In Grails 2 I could setup a config location lookup which would load my dev specific config file. And in Grails 3 I have found that I can provide additional spring configs when running the app, i.e.:

./grailsw -Dspring.config.location=classpath:application.yml,file:///home/nigel/src/app/dev.yml run-app

However, this doesn't work if I'm using plugins, such as below, where it will just used the config in grails-app/conf/application.yml:

./grailsw -Dspring.config.location=classpath:application.yml,file:///home/nigel/src/app/dev.yml url-mappings-report

So my question is, how do I provide deployment/dev specific config files to grails so that it works with the grails plugins.

Body:
For grails 3, you can use external config plugin. And configure the config locations.

grails.config.locations = ["classpath:myconfig.groovy"]


问:
Bind nullable DateTime to MaskedTextBox
I have a masked text box bound to a nullabe datetime, but when the date is blanked out, the validation on the masked text box won't complete.  Is there a way to force this behaviour?  I want a blanked out text box to equal a null DateTime.

When the textbox is already null, the validation works.  It only breaks when there is a date already bound and I try to blank it out.

答:
You can simply give date format as below:</p>

```<code>maskTextBox1.DataBindings.Add("Text", bs, "SummitDate1", true, DataSourceUpdateMode.OnPropertyChanged, null, "dd/MM/yyyy");
</code>```

Title: Bind nullable DateTime to MaskedTextBox

Body:
You can simply give date format as below:

maskTextBox1.DataBindings.Add("Text", bs, "SummitDate1", true, DataSourceUpdateMode.OnPropertyChanged, null, "dd/MM/yyyy");


问:
How to properly abstract Firebase
I'm interested in how to properly abstract Firebase in order to decouple it with my app in case I want to switch back ends in the future.

Right now I have a single class with static methods that access the Realtime Database and Storage. I call these static methods throughout the app.

Is this the best way to use Firebase in a production environment? My app is written in Swift.

答:
You can create a Wrapper class

```<code>class YourWrapperClass: NSObject {
}
</code>```

Import the frameworks like Firebase that you want to use with this wrapper.

```<code>import Firebase
</code>```

Create the methods with the use of Completion Handler/Closures/Blocks
That’s It. By this way you can use the code reusability.

Whenever you want to stop using Firebase, you will have to just stop calling methods from this wrapper class & implement alternative methods you want to call/use instead. Hope this will help.

Title: How to properly abstract Firebase

Body:
You can create a Wrapper class

class YourWrapperClass: NSObject {
}

Import the frameworks like Firebase that you want to use with this wrapper.

import Firebase

Create the methods with the use of Completion Handler/Closures/Blocks
That’s It. By this way you can use the code reusability.

Whenever you want to stop using Firebase, you will have to just stop calling methods from this wrapper class & implement alternative methods you want to call/use instead. Hope this will help.


问:
How would you go about making this if else if program much more simplistic and less code redundant (C++)?
Write a program that asks for the names of three runners and the time it took each
of them to finish a race. The program should display who came in first, second, and
third place.
Input Validation: Only accept positive numbers for the times.

My Code

```<code>#include <iostream>
#include <string>
using namespace std;

int main()
{
    string runner1, runner2, runner3;
    int time1, time2, time3;

    cout << "Please enter the names of three runners" << endl;
    cin >> runner1 >> runner2 >> runner3;
    cout << "How many minutes did it take " << runner1 << " to finish the race?" << endl;
    cin >> time1;
    cout << "How many minutes did it take " << runner2 << " to finish the race?" << endl;
    cin >> time2;
    cout << "How many minutes did it take " << runner3 << " to finish the race?" << endl;
    cin >> time3;

    if (time1 < time2 && time1 < time3)
    {
        cout << runner1 << " is 1st place!" << endl;

        if (time2 < time3)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time2)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time2 < time1 && time2 < time3)
    {
        cout << runner2 << " is 1st place!" << endl;

        if (time1 < time3)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time1)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time3 < time2 && time3 < time1)
    {
        cout << runner3 << " is 1st Place!" << endl;

        if (time2 < time1)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner1 << " is 3rd place!" << endl;
        }
        else if (time1 < time2)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else
    {
        cout << "Error! Please restart the program and input a positive value" << endl;
    }
    return 0;
}
</code>```

答:
Keep the runners ordered in an array by their time, iterate over the runners array and output  (name + i + " place")

I think a linked list would be really good, but it might lose to a raw array if the runners don't change place very often or if there aren't many runners.

"Separate the drawing code from the game logic"

Your drawing code is cout calls. Your game logic is determining what place each runner is in. Then you draw based on that state that you calculated.

Your way is the most direct and fastest way to solve the problem of printing out runner places though.

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

using namespace std;

struct Runner {
    int time;
    int id;

    int operator<(Runner runner) {
        return time < runner.time;
    }
};

char* pickSuffix(int place) {
    switch (place) {
    case 1:
        return "st";
    case 2:
        return "nd";
    case 3:
        return "rd";
    default:
        return "th";
    }
}

int main() {

    //make my runners, read in my times, runner 1 first
    Runner runners[3];
    for (int i = 0; i < 3; i++) {
        cout << "Enter runner " << i+1 << "'s time: ";
        cin >> runners[i].time;
        cout << endl;
        runners[i].id = i+1; //setup their id, used like a name
    }

    //figure out what place each runner came in
    //must overload operator< for object to use sort
    sort(runners, &runners[2]);

    //the position of the runner in the array is the place they came in
    //since it is sorted by their times
    for (int i = 0; i < 3; i++) {
        cout << "Runner #" << runners[i].id << " came in " << i+1 << pickSuffix(i+1)  << " place!" << endl;
        cout << runners[i].time << endl;
    }

    system("pause");

    return 0;
}
</code>```

Here is a sample of the code written the way I described. I think for most purposes you wouldn't want to sort the runners in the array though, you would add a member variable place and just store their calculated position.

Body:
Write a program that asks for the names of three runners and the time it took each
of them to finish a race. The program should display who came in first, second, and
third place.
Input Validation: Only accept positive numbers for the times.

My Code

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string runner1, runner2, runner3;
    int time1, time2, time3;

    cout << "Please enter the names of three runners" << endl;
    cin >> runner1 >> runner2 >> runner3;
    cout << "How many minutes did it take " << runner1 << " to finish the race?" << endl;
    cin >> time1;
    cout << "How many minutes did it take " << runner2 << " to finish the race?" << endl;
    cin >> time2;
    cout << "How many minutes did it take " << runner3 << " to finish the race?" << endl;
    cin >> time3;

    if (time1 < time2 && time1 < time3)
    {
        cout << runner1 << " is 1st place!" << endl;

        if (time2 < time3)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time2)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time2 < time1 && time2 < time3)
    {
        cout << runner2 << " is 1st place!" << endl;

        if (time1 < time3)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner3 << " is 3rd place!" << endl;
        }
        else if (time3 < time1)
        {
            cout << runner3 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else if (time3 < time2 && time3 < time1)
    {
        cout << runner3 << " is 1st Place!" << endl;

        if (time2 < time1)
        {
            cout << runner2 << " is 2nd place!" << endl;
            cout << runner1 << " is 3rd place!" << endl;
        }
        else if (time1 < time2)
        {
            cout << runner1 << " is 2nd place!" << endl;
            cout << runner2 << " is 3rd place!" << endl;
        }
    }
    else
    {
        cout << "Error! Please restart the program and input a positive value" << endl;
    }
    return 0;
}

Body:
Keep the runners ordered in an array by their time, iterate over the runners array and output  (name + i + " place")

I think a linked list would be really good, but it might lose to a raw array if the runners don't change place very often or if there aren't many runners.

"Separate the drawing code from the game logic"

Your drawing code is cout calls. Your game logic is determining what place each runner is in. Then you draw based on that state that you calculated.

Your way is the most direct and fastest way to solve the problem of printing out runner places though.

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

using namespace std;

struct Runner {
    int time;
    int id;

    int operator<(Runner runner) {
        return time < runner.time;
    }
};

char* pickSuffix(int place) {
    switch (place) {
    case 1:
        return "st";
    case 2:
        return "nd";
    case 3:
        return "rd";
    default:
        return "th";
    }
}

int main() {

    //make my runners, read in my times, runner 1 first
    Runner runners[3];
    for (int i = 0; i < 3; i++) {
        cout << "Enter runner " << i+1 << "'s time: ";
        cin >> runners[i].time;
        cout << endl;
        runners[i].id = i+1; //setup their id, used like a name
    }

    //figure out what place each runner came in
    //must overload operator< for object to use sort
    sort(runners, &runners[2]);

    //the position of the runner in the array is the place they came in
    //since it is sorted by their times
    for (int i = 0; i < 3; i++) {
        cout << "Runner #" << runners[i].id << " came in " << i+1 << pickSuffix(i+1)  << " place!" << endl;
        cout << runners[i].time << endl;
    }

    system("pause");

    return 0;
}

Here is a sample of the code written the way I described. I think for most purposes you wouldn't want to sort the runners in the array though, you would add a member variable place and just store their calculated position.


问:
Field "features" does not exist. SparkML
I am trying to build a model in Spark ML with Zeppelin.
I am new to this area and would like some help. I think i need to set the correct datatypes to the column and set the first column as the label. Any help would be greatly appreciated, thank you

```<code>val training = sc.textFile("hdfs:///ford/fordTrain.csv")
val header = training.first
val inferSchema = true
val df = training.toDF

val lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.3)
.setElasticNetParam(0.8)

 val lrModel = lr.fit(df)

// Print the coefficients and intercept for multinomial logistic regression
println(s"Coefficients: \n${lrModel.coefficientMatrix}")
println(s"Intercepts: ${lrModel.interceptVector}")
</code>```

A snippet of the csv file i am using is:

```<code>IsAlert,P1,P2,P3,P4,P5,P6,P7,P8,E1,E2
0,34.7406,9.84593,1400,42.8571,0.290601,572,104.895,0,0,0,
</code>```

答:
As you have mentioned, you are missing the features column. It is a vector containing all predictor variables. You have to create it using VectorAssembler.

IsAlert is the label and all others variables (p1,p2,...) are predictor variables, you can create features column (actually you can name it anything you want instead of features) by:

```<code>import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.linalg.Vectors

//creating features column
val assembler = new VectorAssembler()
  .setInputCols(Array("P1","P2","P3","P4","P5","P6","P7","P8","E1","E2"))
  .setOutputCol("features")

val lr = new LogisticRegression()
  .setMaxIter(10)
  .setRegParam(0.3)
  .setElasticNetParam(0.8)
  .setFeaturesCol("features")   // setting features column
  .setLabelCol("IsAlert")       // setting label column

//creating pipeline
val pipeline = new Pipeline().setStages(Array(assembler,lr))

//fitting the model
val lrModel = pipeline.fit(df)
</code>```

Refer: https://spark.apache.org/docs/latest/ml-features.html#vectorassembler.

Body:
I am trying to build a model in Spark ML with Zeppelin.
I am new to this area and would like some help. I think i need to set the correct datatypes to the column and set the first column as the label. Any help would be greatly appreciated, thank you

val training = sc.textFile("hdfs:///ford/fordTrain.csv")
val header = training.first
val inferSchema = true
val df = training.toDF

val lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.3)
.setElasticNetParam(0.8)

 val lrModel = lr.fit(df)

// Print the coefficients and intercept for multinomial logistic regression
println(s"Coefficients: \n${lrModel.coefficientMatrix}")
println(s"Intercepts: ${lrModel.interceptVector}")

A snippet of the csv file i am using is:

IsAlert,P1,P2,P3,P4,P5,P6,P7,P8,E1,E2
0,34.7406,9.84593,1400,42.8571,0.290601,572,104.895,0,0,0,

Body:
As you have mentioned, you are missing the features column. It is a vector containing all predictor variables. You have to create it using VectorAssembler.

IsAlert is the label and all others variables (p1,p2,...) are predictor variables, you can create features column (actually you can name it anything you want instead of features) by:

import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.linalg.Vectors

//creating features column
val assembler = new VectorAssembler()
  .setInputCols(Array("P1","P2","P3","P4","P5","P6","P7","P8","E1","E2"))
  .setOutputCol("features")

val lr = new LogisticRegression()
  .setMaxIter(10)
  .setRegParam(0.3)
  .setElasticNetParam(0.8)
  .setFeaturesCol("features")   // setting features column
  .setLabelCol("IsAlert")       // setting label column

//creating pipeline
val pipeline = new Pipeline().setStages(Array(assembler,lr))

//fitting the model
val lrModel = pipeline.fit(df)

Refer: https://spark.apache.org/docs/latest/ml-features.html#vectorassembler.


问:
Changing the height of a html div down to top without using transition
I need to do tank animation, where according to the liquid level, the height of the tank(image) changes. For this I have written HTML code as below:

```<code><div>
<img id='T1' style="height:0px;position:absolute">
</div>
</code>```

Now I am obtaining the level information from database using ajax and trying to change the height of the image according to the value of the level parameter using JavaScript.

```<code>  var level=response;
 document.getElementById('T1').height=level."px";
</code>```

This is changing the height from top to down, but I want down to top.
Inverting the div using transform is not working. Also transition is not working as transition-time cannot be specified in this case.
Please provide me some suggestions.

答:
You can add following CSS for this

```<code>#t1 {
    position: absolute;
    left: 0px;
    bottom: 0px;
}
</code>```

or

```<code><div>
    <img id='T1' style="height:0px;position:absolute; bottom: 0px; left: 0px;">
</div>
</code>```

Body:
I need to do tank animation, where according to the liquid level, the height of the tank(image) changes. For this I have written HTML code as below:

Now I am obtaining the level information from database using ajax and trying to change the height of the image according to the value of the level parameter using JavaScript.

  var level=response;
 document.getElementById('T1').height=level."px";

This is changing the height from top to down, but I want down to top.
Inverting the div using transform is not working. Also transition is not working as transition-time cannot be specified in this case.
Please provide me some suggestions.

Body:
You can add following CSS for this

#t1 {
    position: absolute;
    left: 0px;
    bottom: 0px;
}

or

<div>
    <img id='T1' style="height:0px;position:absolute; bottom: 0px; left: 0px;">
</div>


问:
How to convert seconds to HH:mm to HH:mm:ss in moment.js
Suppose I have a time as 13:45.

Now I want to convert this into 13:45:00 using moment.js.

I am doing
moment('13:45').format('h:m:s'); but it is not working.

答:
Use moment constructor to create a object then use format()

console.log(moment('13:45', 'HH:mm').format('HH:mm:ss'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
Use moment constructor to create a object then use format()

console.log(moment('13:45', 'HH:mm').format('HH:mm:ss'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
how to solve Duplication class error in android studio
I am a beginner in Android Development . How to solve duplicate class Error in android studio ? The error is something like duplicate

class: com.example.android;countscore.R

snapshot

答:
You should probably go to the dropdown menu and clean your build. Most of the time the errors with .R will disappear when you clean your build.

If this doesn't work you probably have 2 different R.java files in different directories. Search and locate those and delete them. Then rebuild. This should do the trick. I recommend trying the first solution before doing the second solution.


问:
How to compress image before uploading in Laravel?
I'm making a images gallery website where users can upload any image and they will be displayed on frontend. I need to compress images without effecting it's quality to reduce there size so that page load speed should not effect that much. I'm using following code to upload image:</p>

```<code>$rules = array('file' => 'required');
$destinationPath = 'assets/images/pages'
$validator = Validator::make(array('file' => $file), $rules);
if ($validator->passes()) {
   $filename = time() . $uploadcount . '.' . $file->getClientOriginalExtension();
   $file->move($destinationPath, $filename);
   return $filename;
} else {
   return '';
}
</code>```

答:
https://tinypng.com provides an API service for compressing images. All you need to do is install their PHP library in Laravel, get a developer key from their website. After that by the adding the below code, you can compress your uploaded image. In the code, I am assuming you have stored your file under 'storage' directory.

```<code>$filepath = public_path('storage/profile_images/'.$filename);
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile($filepath);
$source->toFile($filepath);
</code>```

Here is the link to a blog which explains how to upload and compress images in Laravel http://artisansweb.net/guide-upload-compress-images-laravel

Body:
I'm making a images gallery website where users can upload any image and they will be displayed on frontend. I need to compress images without effecting it's quality to reduce there size so that page load speed should not effect that much. I'm using following code to upload image:

$rules = array('file' => 'required');
$destinationPath = 'assets/images/pages'
$validator = Validator::make(array('file' => $file), $rules);
if ($validator->passes()) {
   $filename = time() . $uploadcount . '.' . $file->getClientOriginalExtension();
   $file->move($destinationPath, $filename);
   return $filename;
} else {
   return '';
}

Body:
https://tinypng.com provides an API service for compressing images. All you need to do is install their PHP library in Laravel, get a developer key from their website. After that by the adding the below code, you can compress your uploaded image. In the code, I am assuming you have stored your file under 'storage' directory.

$filepath = public_path('storage/profile_images/'.$filename);
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile($filepath);
$source->toFile($filepath);

Here is the link to a blog which explains how to upload and compress images in Laravel http://artisansweb.net/guide-upload-compress-images-laravel


问:
Is there a way to use an ionic app as a web app?
I'm setting out to create a mobile app using Ionic.

However I would also like my app to work well and look good on a desktop.

Is there any way to create one app one time that looks good and works well on both platforms (and perhaps more platforms as well)?

答:
Some cordova plugin like sqlite-2,socialsharing,file-opner2 not supporting on browser.
If used this plugin you can't work on web app.
Cordova is not support for web app.</p>


问:
Type parameters in type and data constructors
If I understand correctly,

```<code>data Int = 1 | 2 | 3 | 4 | ...
</code>```

All things on the right-hand side are just values.

In the following,

```<code>data Maybe b = Nothing
             | Just b
</code>```

Do b in Maybe b and b in Just b mean the same thing? To me, it looks like that b in Maybe b is a type variable, and b in Just b is a value variable of type b.

答:
data Maybe b means that the type is generic, and that b is the generic type variable.

Just b does, indeed, indicate that one of the ways you can create a value of Maybe b is by supplying a value of the type b.

```<code>Prelude> Just "foo"
Just "foo"
Prelude> Just 42
Just 42
</code>```

Here, Just "Foo" has the type Maybe String, so the type type variable b is String. In Haskell, types are variables as well.

If you, however, examine the type of Just 42, you'll see that it's still abstract:

```<code>Prelude> :t Just 42
Just 42 :: Num a => Maybe a
</code>```

This means that it could be any Maybe a as long as a is an instance of the Num typeclass. So in this case, the type is still 'variable'.

(The first example, data Int, doesn't compile...)

Body:
If I understand correctly,

data Int = 1 | 2 | 3 | 4 | ...

All things on the right-hand side are just values.

In the following,

data Maybe b = Nothing
             | Just b

Do b in Maybe b and b in Just b mean the same thing? To me, it looks like that b in Maybe b is a type variable, and b in Just b is a value variable of type b.

Body:
data Maybe b means that the type is generic, and that b is the generic type variable.

Just b does, indeed, indicate that one of the ways you can create a value of Maybe b is by supplying a value of the type b.

Prelude> Just "foo"
Just "foo"
Prelude> Just 42
Just 42

Here, Just "Foo" has the type Maybe String, so the type type variable b is String. In Haskell, types are variables as well.

If you, however, examine the type of Just 42, you'll see that it's still abstract:

Prelude> :t Just 42
Just 42 :: Num a => Maybe a

This means that it could be any Maybe a as long as a is an instance of the Num typeclass. So in this case, the type is still 'variable'.

(The first example, data Int, doesn't compile...)


问:
batch: ampersand causing issues with findstr
This part works well until there is an ampersand in the filename, in which case it crashes my script completely.

```<code>echo %filename% | findstr /i /b /c:"%name% (%year%)"
</code>```

I can't just put the filename into quotation marks because I need to find the string at the beginning. So how can I do both?

答:
For command line use:

```<code>echo %file^name:^&=^^^&% | ...
</code>```

Inside a batch file

```<code>echo %%filename:^&=^^^&%% | ...
</code>```

How it works?

As a pipe creates two new cmd.exe instances, the echo ... will be parsed twice.

The trick is to expand the filename only in the second expansion.

And then to expand and replace the & with ^& to avoid problems with the &.

The caret will be used to escape the ampersand and itself will be removed.

In the second expansion the parser only sees echo %filename:&=^&%.

To force the expansion into the second parse step, the percent signs have to be doubled for batch files.

From the command line, this doesn't work, but a simple caret anywhere in the variable name works.

Alternative solution:

```<code>echo "%filename%" | findstr /i /b /c:^"\"%filename% (%year%)\""
</code>```

This adds simply quotes and uses also quotes in the search expression

Body:
This part works well until there is an ampersand in the filename, in which case it crashes my script completely.

echo %filename% | findstr /i /b /c:"%name% (%year%)"

I can't just put the filename into quotation marks because I need to find the string at the beginning. So how can I do both?

Body:
For command line use:

echo %file^name:^&=^^^&% | ...

Inside a batch file

echo %%filename:^&=^^^&%% | ...

How it works?

As a pipe creates two new cmd.exe instances, the echo ... will be parsed twice.

The trick is to expand the filename only in the second expansion.

And then to expand and replace the & with ^& to avoid problems with the &.

The caret will be used to escape the ampersand and itself will be removed.

In the second expansion the parser only sees echo %filename:&=^&%.

To force the expansion into the second parse step, the percent signs have to be doubled for batch files.

From the command line, this doesn't work, but a simple caret anywhere in the variable name works.

Alternative solution:

echo "%filename%" | findstr /i /b /c:^"\"%filename% (%year%)\""

This adds simply quotes and uses also quotes in the search expression


问:
Visual studio before publish target is not triggering
I want to run a gulp task before publishing to a local folder. So tried using "BeforePublish" target, but it not working properly. Am i doing anything wrong in it ?</p>

```<code><Target Name="BeforePublish">
    <Message Text="Before publish triggered...."></Message>
  </Target>
</code>```

答:
I use the VS2017 in my side. I could get the text in the command prompt with the MSbuild.exe.

So please make sure that you edit the .xxproj file correctly, and run the msbuild command line correctly in your side. I just test it using a simple Winform app.

Update:

If you just want to call it during you publish using the VS IDE, I think you could get the workaround here:

How to execute a PowerShell script only before a web deploy Publish task in VS 2012?

Body:
I want to run a gulp task before publishing to a local folder. So tried using "BeforePublish" target, but it not working properly. Am i doing anything wrong in it ?

<Target Name="BeforePublish">
    <Message Text="Before publish triggered...."></Message>
  </Target>


问:
JQuery Not Working in Chrome
This code works properly in Firefox but not in Chrome, If you need more of the code I would be glad to provide it, a button changes a background image:

```<code>$(document).ready(function() {
var bg = 1;
$("#changePic").click(function () {
    if (bg == 1)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge1.jpg");
        bg=2;
    }
    else if (bg == 2)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge2.jpg");
        bg=3;
    }
    else
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge.jpg");
        bg=1;
    }
  });
});
</code>```

I'm not getting any errors in the Chrome Console. Thanks!

答:
As an aside, you can really factor out a lot of that common code:</p>

```<code>$(document).ready(function() {
    var bg= 0;
    $("#changePic").click(function () {
        bg= (bg+1) % 3;
        var name= ["lodge", "lodge1", "lodge2"][bg];
        $("#outerWrapper").css("background-image", "url(images/background-"+name+".jpg)");
    });
});
</code>```

Title: JQuery Not Working in Chrome

Body:
This code works properly in Firefox but not in Chrome, If you need more of the code I would be glad to provide it, a button changes a background image:

$(document).ready(function() {
var bg = 1;
$("#changePic").click(function () {
    if (bg == 1)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge1.jpg");
        bg=2;
    }
    else if (bg == 2)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge2.jpg");
        bg=3;
    }
    else
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge.jpg");
        bg=1;
    }
  });
});

I'm not getting any errors in the Chrome Console. Thanks!

Body:
As an aside, you can really factor out a lot of that common code:

$(document).ready(function() {
    var bg= 0;
    $("#changePic").click(function () {
        bg= (bg+1) % 3;
        var name= ["lodge", "lodge1", "lodge2"][bg];
        $("#outerWrapper").css("background-image", "url(images/background-"+name+".jpg)");
    });
});


问:
Updating Webpage from Within Thread
I have a webpage that runs a lengthy procedure, it's all working apart from displaying the progress on the page.

I have the following progress bar (Bootstrap):

```<code><div class="col-md-8">
  <label for="product-feed-progress">Progress</label>
    <div class="progress">
     <div class="progress-bar" role="progressbar" runat="server" id="prgProdFeed" style="min-width: 0em; width: 0%;">
                                    0%
     </div>
  </div>
</div>
</code>```

During the thread, I have the following snippet that adjusts the width property of prgProdFeed:

```<code>prgProdFeed.Attributes.Add("style", "width:" & ((p_objFeedInfo.Progress / p_objFeedInfo.Total) * 100).ToString() + "%")
</code>```

I have also tried:

```<code>prgProdFeed.Style.Item("width") = ((p_objFeedInfo.Progress / p_objFeedInfo.Total) * 100).ToString() + "%"
</code>```

They both change the width property of the bar which currently sits in an update panel (updated on the tick of a timer).

How come my progress bar is not updating on the page? I can see using the inspector that the update panel is refreshing, and in the debugger it's showing the width being correct - just nothing changes visually.

Any help would be appreciated.

答:
Working code is below.

I would suggest you make sure your update panel is actually being refreshed. with my code you can do a hard updated of the web page (eg F5) and you'll see updated progress. Initially, my code to refresh the update panel wasn't triggering. I was using Query to trigger a click on the refresh linkbutton in the update panel but I needed to change the code to call the __doPostBack.

Another thing I would would check in your code is that p_objFeedInfo.Progress is a double and p_objFeedInfo.Total is a double. You could be having an issue where one is an int and the double result from (p_objFeedInfo.Progress / p_objFeedInfo.Total) being less than 1 is converted as in integer rounded down to 0 before being multiplied by 100.

Besides that I am combining the width attribute into a string and also setting prgProdFeed.InnerText to that string so I don't need worry about inspecting an element to see if the width is changing. I am also setting the width use Style("Width"):

```<code>Dim progressAttribute As String = progress & "%"
Me.prgProdFeed.Style("Width") = progressAttribute
Me.prgProdFeed.InnerText = progressAttribute
</code>```

To simulate your long running thread I created a feed class that takes Total as a constructor. It returns progress as double based on the number of seconds that have passed since the class was created.

Public Class ProgressBar
    Inherits System.Web.UI.Page

    Public Class FeedInfo
        Public ReadOnly Property Progress As Double
            Get
                Return Math.Min(Now.Subtract(Created).TotalSeconds, Total)
            End Get
        End Property

        Public Total As Double
        Public Created As DateTime
        Public Sub New(Total)
            Me.Total = Total
            Created = Now
        End Sub
    End Class
    Private Property info As FeedInfo
        Get
            If (Not Session("info") Is Nothing) Then
                Return Session("info")
            End If
            Return Nothing
        End Get
        Set(value As FeedInfo)
            Session("info") = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim progress As Integer = 0
        If (Not info Is Nothing) Then
            Dim tracker As FeedInfo = info
            Dim trackerProgress As Double = tracker.Progress
            Dim trackerTotal As Double = tracker.Total
            progress = ((trackerProgress / trackerTotal) * 100)
        End If
        Dim progressAttribute As String = progress & "%"
        Me.prgProdFeed.Style("Width") = progressAttribute
        Me.prgProdFeed.InnerText = progressAttribute

    End Sub

    Private Sub runProc_Click(sender As Object, e As EventArgs) Handles runProc.Click
        info = New FeedInfo(600)
    End Sub
End Class
```

<pre class="lang-html prettyprint-override"><code><%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ProgressBar.aspx.vb" Inherits="EFWCFVB.ProgressBar" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Long Running Task Progress Bar</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script>
        var timerId = 0;
        function trackProgress() {
            if (timerId && timerId != 0)
                return;
            timerId = window.setInterval(refreshProgress, 2000);
        }
        function refreshProgress() {
            if ($('.progress-bar').html() == "100%") {
                window.clearInterval(timerId); return;
            }
            //  $('#btnRefresh').click(); does not work
            // var href = $('#btnRefresh').attr("href").split[0]; //"javascript:__doPostBack('btnRefresh','')"
            __doPostBack('btnRefresh', '');

        }
        $(document).ready(function () {
            trackProgress();
            $('#runProc').click(function () { trackProgress();})
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <h2>Long Running Task Progress Bar</h2>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <div class="form-group">
                    <div class="col-md-8">

                        <label for="product-feed-progress">Progress</label>
                        <div class="progress">
                            <div class="progress-bar" role="progressbar" runat="server" id="prgProdFeed" style="min-width: 0em; width: 0%;">
                                0%
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-8">
                        <asp:Button ID="runProc" runat="server" Text="Run" />
                        <asp:LinkButton ID="btnRefresh" runat="server" Text="Refresh Panel">

                        </asp:LinkButton>
                    </div>
                </div>
            </ContentTemplate>

        </asp:UpdatePanel>

    </form>
</body>
</html>
</code>```

Title: Updating Webpage from Within Thread

Body:
I have a webpage that runs a lengthy procedure, it's all working apart from displaying the progress on the page.

I have the following progress bar (Bootstrap):

  Progress

                                    0%

During the thread, I have the following snippet that adjusts the width property of prgProdFeed:

prgProdFeed.Attributes.Add("style", "width:" & ((p_objFeedInfo.Progress / p_objFeedInfo.Total) * 100).ToString() + "%")

I have also tried:

prgProdFeed.Style.Item("width") = ((p_objFeedInfo.Progress / p_objFeedInfo.Total) * 100).ToString() + "%"

They both change the width property of the bar which currently sits in an update panel (updated on the tick of a timer).

How come my progress bar is not updating on the page? I can see using the inspector that the update panel is refreshing, and in the debugger it's showing the width being correct - just nothing changes visually.

Any help would be appreciated.

Body:
Working code is below.

I would suggest you make sure your update panel is actually being refreshed. with my code you can do a hard updated of the web page (eg F5) and you'll see updated progress. Initially, my code to refresh the update panel wasn't triggering. I was using Query to trigger a click on the refresh linkbutton in the update panel but I needed to change the code to call the __doPostBack.

Another thing I would would check in your code is that p_objFeedInfo.Progress is a double and p_objFeedInfo.Total is a double. You could be having an issue where one is an int and the double result from (p_objFeedInfo.Progress / p_objFeedInfo.Total) being less than 1 is converted as in integer rounded down to 0 before being multiplied by 100.

Besides that I am combining the width attribute into a string and also setting prgProdFeed.InnerText to that string so I don't need worry about inspecting an element to see if the width is changing. I am also setting the width use Style("Width"):

Dim progressAttribute As String = progress & "%"
Me.prgProdFeed.Style("Width") = progressAttribute
Me.prgProdFeed.InnerText = progressAttribute

To simulate your long running thread I created a feed class that takes Total as a constructor. It returns progress as double based on the number of seconds that have passed since the class was created.

Public Class ProgressBar
    Inherits System.Web.UI.Page

    Public Class FeedInfo
        Public ReadOnly Property Progress As Double
            Get
                Return Math.Min(Now.Subtract(Created).TotalSeconds, Total)
            End Get
        End Property

        Public Total As Double
        Public Created As DateTime
        Public Sub New(Total)
            Me.Total = Total
            Created = Now
        End Sub
    End Class
    Private Property info As FeedInfo
        Get
            If (Not Session("info") Is Nothing) Then
                Return Session("info")
            End If
            Return Nothing
        End Get
        Set(value As FeedInfo)
            Session("info") = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim progress As Integer = 0
        If (Not info Is Nothing) Then
            Dim tracker As FeedInfo = info
            Dim trackerProgress As Double = tracker.Progress
            Dim trackerTotal As Double = tracker.Total
            progress = ((trackerProgress / trackerTotal) * 100)
        End If
        Dim progressAttribute As String = progress & "%"
        Me.prgProdFeed.Style("Width") = progressAttribute
        Me.prgProdFeed.InnerText = progressAttribute

    End Sub

    Private Sub runProc_Click(sender As Object, e As EventArgs) Handles runProc.Click
        info = New FeedInfo(600)
    End Sub
End Class

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ProgressBar.aspx.vb" Inherits="EFWCFVB.ProgressBar" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Long Running Task Progress Bar</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script>
        var timerId = 0;
        function trackProgress() {
            if (timerId && timerId != 0)
                return;
            timerId = window.setInterval(refreshProgress, 2000);
        }
        function refreshProgress() {
            if ($('.progress-bar').html() == "100%") {
                window.clearInterval(timerId); return;
            }
            //  $('#btnRefresh').click(); does not work
            // var href = $('#btnRefresh').attr("href").split[0]; //"javascript:__doPostBack('btnRefresh','')"
            __doPostBack('btnRefresh', '');

        }
        $(document).ready(function () {
            trackProgress();
            $('#runProc').click(function () { trackProgress();})
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <h2>Long Running Task Progress Bar</h2>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <div class="form-group">
                    <div class="col-md-8">

                        <label for="product-feed-progress">Progress</label>
                        <div class="progress">
                            <div class="progress-bar" role="progressbar" runat="server" id="prgProdFeed" style="min-width: 0em; width: 0%;">
                                0%
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-8">
                        <asp:Button ID="runProc" runat="server" Text="Run" />
                        <asp:LinkButton ID="btnRefresh" runat="server" Text="Refresh Panel">

                        </asp:LinkButton>
                    </div>
                </div>
            </ContentTemplate>

        </asp:UpdatePanel>

    </form>
</body>
</html>


问:
GTK3: Widget mouse events pass-through
I have a custom GtkDrawingArea-based widget inside a GtkHeaderBar which is basically a slider that receives mouse clicks and moves. Everything worked fine in GTK 3.14-something, but in 3.22 things went south: when I click and drag inside my widget, GTK thinks I'm trying to drag the window (first few pixels go to the widget, but then the window takes over).

How do I prevent mouse events from propagating to the window?

Both motion-notify-event and button-press-event return TRUE (that did the trick in 3.14, not anymore).

```<code>g_sinal_connect(Something->DrawingArea, "motion-notify-event", G_CALLBACK(Something_motion), Something);
g_signal_connect(Something->DrawingArea, "button-press-event", G_CALLBACK(Something_press), Something);
</code>```

答:
Answering as an answer, as I can't input code into the 'comments'.

I suspect you have to enable the EventMask corresponding to the DrawingArea. This is somewhat different from other widgets, I guess.

Below is a small demo program in Python3 (this basically connects directly to the Gtk3.2x libraries, so should be similar to what you want to do in C.

Changing the return True to False in area_button_press() will make it transparent to the button_press_event, as expected. Commenting the line with ...add_events(Gdk.EventMask.BUTTON_PRESS_MASK) is needed in the code to make the button-press-event to be recognized at all:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  test_headerbar_events.py
#
#  Copyright 2017 John Coppens <john@jcoppens.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#

from gi.repository import Gtk, Gdk

class MainWindow(Gtk.Window):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.connect("destroy", lambda x: Gtk.main_quit())
        self.set_default_size(200, -1)

        hdrbar = Gtk.HeaderBar(title = "Header bar")
        hdrbar.connect("button-press-event", self.hdrbar_button_press)

        drawing_area = Gtk.DrawingArea()
        drawing_area.set_size_request(30, 30)
        drawing_area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        drawing_area.connect("button-press-event", self.area_button_press)

        frame = Gtk.Frame()
        frame.add(drawing_area)

        hdrbar.pack_start(frame)

        self.add(hdrbar)
        self.show_all()

    def area_button_press(self, btn, event):
        print("Button pressed on Drawing Area")
        return True

    def hdrbar_button_press(self, btn, event):
        print("Button pressed on Header Bar")
        return False

    def run(self):
        Gtk.main()

def main(args):
    mainwdw = MainWindow()
    mainwdw.run()

    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))
</code>```

EDIT: If you use set_titlebar(), the events seem to go directly to the windowmanager (which would probably be what you want normally), instead of the underlying window. If you want to control (block) the movement of the window you could

Not use set_titlebar() and use set_decorations(False), which will hide the window's titlebar and show your headerbar at the top. Then the events will be controllable. Use a VBox to store your headerbar and the content of the rest of the window.

Of course. this way you will have to implement window dragging yourself (which is not too complicated). If needed, have a look at the GUI frontend I made for the Wcalc calculator (years ago - you may need to tweak the Gtk calls),

Title: GTK3: Widget mouse events pass-through

Body:
I have a custom GtkDrawingArea-based widget inside a GtkHeaderBar which is basically a slider that receives mouse clicks and moves. Everything worked fine in GTK 3.14-something, but in 3.22 things went south: when I click and drag inside my widget, GTK thinks I'm trying to drag the window (first few pixels go to the widget, but then the window takes over).

How do I prevent mouse events from propagating to the window?

Both motion-notify-event and button-press-event return TRUE (that did the trick in 3.14, not anymore).

g_sinal_connect(Something->DrawingArea, "motion-notify-event", G_CALLBACK(Something_motion), Something);
g_signal_connect(Something->DrawingArea, "button-press-event", G_CALLBACK(Something_press), Something);

Body:
Answering as an answer, as I can't input code into the 'comments'.

I suspect you have to enable the EventMask corresponding to the DrawingArea. This is somewhat different from other widgets, I guess.

Below is a small demo program in Python3 (this basically connects directly to the Gtk3.2x libraries, so should be similar to what you want to do in C.

Changing the return True to False in area_button_press() will make it transparent to the button_press_event, as expected. Commenting the line with ...add_events(Gdk.EventMask.BUTTON_PRESS_MASK) is needed in the code to make the button-press-event to be recognized at all:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  test_headerbar_events.py
#
#  Copyright 2017 John Coppens <john@jcoppens.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#

from gi.repository import Gtk, Gdk

class MainWindow(Gtk.Window):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.connect("destroy", lambda x: Gtk.main_quit())
        self.set_default_size(200, -1)

        hdrbar = Gtk.HeaderBar(title = "Header bar")
        hdrbar.connect("button-press-event", self.hdrbar_button_press)

        drawing_area = Gtk.DrawingArea()
        drawing_area.set_size_request(30, 30)
        drawing_area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        drawing_area.connect("button-press-event", self.area_button_press)

        frame = Gtk.Frame()
        frame.add(drawing_area)

        hdrbar.pack_start(frame)

        self.add(hdrbar)
        self.show_all()

    def area_button_press(self, btn, event):
        print("Button pressed on Drawing Area")
        return True

    def hdrbar_button_press(self, btn, event):
        print("Button pressed on Header Bar")
        return False

    def run(self):
        Gtk.main()

def main(args):
    mainwdw = MainWindow()
    mainwdw.run()

    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

EDIT: If you use set_titlebar(), the events seem to go directly to the windowmanager (which would probably be what you want normally), instead of the underlying window. If you want to control (block) the movement of the window you could

Not use set_titlebar() and use set_decorations(False), which will hide the window's titlebar and show your headerbar at the top. Then the events will be controllable. Use a VBox to store your headerbar and the content of the rest of the window.

Of course. this way you will have to implement window dragging yourself (which is not too complicated). If needed, have a look at the GUI frontend I made for the Wcalc calculator (years ago - you may need to tweak the Gtk calls),


问:
Store authentification data in MVC
I have created a custom Authorize attribute where I use the Office Graph to get AAD groups the current user is member of, and based on those I reject or authorize the user. I want to save the groups, because the call to Office Graph takes some performance. What would be the correct way to save that kind of data? I can see some people saves it to a SQL server, but then I would need to ensure cleanup etc.

Also I can see in some threads the session state is stated to be a bad choice due to concurrency. So the question is what options do you have to store this kind of information?

All suggestions are welcome.

答:
If you were only using the group_id info, there is no need to use Office Graph and store it at all. We can enable Azure AD issue the groups claims by change the manifest of Azure AD like below:(refer this code sample)

```<code>"groupMembershipClaims": "All",
</code>```

And if you are also using other info about groups, you can store these info into claims. Here is a code sample that add the name of groups into claims for your reference:

```<code>AuthorizationCodeReceived = async context =>
{
    ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
    string userObjectId = context.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
    AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
    AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
        context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId);

    ActiveDirectoryClient graphClient = new ActiveDirectoryClient(new Uri(ConfigHelper.GraphServiceRoot),
  async () => { return await Task.FromResult(result.AccessToken); }
  );

    try
    {
        foreach (var groupClaim in context.AuthenticationTicket.Identity.FindAll("groups"))
        {

            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri($"https://graph.windows.net/adfei.onmicrosoft.com/groups/{groupClaim.Value}?api-version=1.6"),
                Method = HttpMethod.Get,
            };

            request.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);

            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage httpResponse = httpClient.SendAsync(request).Result;
                var retJSON = httpResponse.Content.ReadAsStringAsync().Result;

                var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(retJSON);
                ((ClaimsIdentity)context.AuthenticationTicket.Identity).AddClaim(new Claim("groupName", dict["displayName"].ToString()));
            }
        }

    }
    catch (Exception ex)
    {

    }
},
</code>```

Then we can these info from controller using the code below:

```<code>ClaimsPrincipal.Current.FindAll("groupName")
</code>```

Title: Store authentification data in MVC

Body:
If you were only using the group_id info, there is no need to use Office Graph and store it at all. We can enable Azure AD issue the groups claims by change the manifest of Azure AD like below:(refer this code sample)

"groupMembershipClaims": "All",

And if you are also using other info about groups, you can store these info into claims. Here is a code sample that add the name of groups into claims for your reference:

AuthorizationCodeReceived = async context =>
{
    ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
    string userObjectId = context.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
    AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
    AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
        context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId);

    ActiveDirectoryClient graphClient = new ActiveDirectoryClient(new Uri(ConfigHelper.GraphServiceRoot),
  async () => { return await Task.FromResult(result.AccessToken); }
  );

    try
    {
        foreach (var groupClaim in context.AuthenticationTicket.Identity.FindAll("groups"))
        {

            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri($"https://graph.windows.net/adfei.onmicrosoft.com/groups/{groupClaim.Value}?api-version=1.6"),
                Method = HttpMethod.Get,
            };

            request.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);

            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage httpResponse = httpClient.SendAsync(request).Result;
                var retJSON = httpResponse.Content.ReadAsStringAsync().Result;

                var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(retJSON);
                ((ClaimsIdentity)context.AuthenticationTicket.Identity).AddClaim(new Claim("groupName", dict["displayName"].ToString()));
            }
        }

    }
    catch (Exception ex)
    {

    }
},

Then we can these info from controller using the code below:

ClaimsPrincipal.Current.FindAll("groupName")