问:
Why aren't options being overridden?
In my module pattern, options are 'undefined' for some reason.. does anyone see why they aren't being passed in properly?

```<code>Framework.MyModule = (function(options) {
    var defaults = {
        someOption : 1,
        stuff      : 2
    };
    if (!options) {
        var options = defaults;
    } else {
        for (var index in defaults) {
            if (typeof options[index] == 'undefined')
                options[index] = defaults[index];
        }
    }
    var module = {};

    // Initialize
    _something();

    // Private Methods
    function _something() {}

    // Public Methods
    module.click = function() {};

    return module;
})();

... docready function ...

var options = {
  someOption : 9,
  stuff      : 10
};

Framework.MyModule(options);

... end doc ready ...
</code>```

Please see the fiddle: http://jsfiddle.net/kWHEZ/1/

答:
```<code>var options = { /* ... */};
Framework.MyModule = (function(options) {
  /* .. options are undefined ... */
})();

Framework.MyModule = (function(options) {
  /* .. options are defined... */
})(options);
</code>```

Now if you want the ability to add private/public variables AND still pass options you will need to make it so the a constructor method is returned with your public object - thus not passing options in the function that is run immediately. Because lets be honest .. this doesn't really make sense.

You could do something like this:

```<code>var Module = {};
Module.Foo = (function($){ // jQuery is accessible as $
    var _private = {
        defaults: {
            url: '/default-url', container: '#dummy'
        },
        foos: []
    };

    return function(o){ // returns constructor
        // other _private variables are accessible here
        var opts = $.extend({}, _private.defaults, o);
        var self = { // public return object
            load: function(){
                $(opts.container).load(opts.url);
            }
        };
        _private.foos.push(self);
        return self;
    };
})(jQuery); // scope global variables

var foo1 = Module.Foo({
    url: '/test.php',
    container: '#success'
});

var foo2 = Module.Foo({
    url: '/test2.php',
    container: '#success2'
});

foo1.load();
foo2.load();
</code>```

Title: Why aren't options being overridden?

Body:
In my module pattern, options are 'undefined' for some reason.. does anyone see why they aren't being passed in properly?

Framework.MyModule = (function(options) {
    var defaults = {
        someOption : 1,
        stuff      : 2
    };
    if (!options) {
        var options = defaults;
    } else {
        for (var index in defaults) {
            if (typeof options[index] == 'undefined')
                options[index] = defaults[index];
        }
    }
    var module = {};

    // Initialize
    _something();

    // Private Methods
    function _something() {}

    // Public Methods
    module.click = function() {};

    return module;
})();

... docready function ...

var options = {
  someOption : 9,
  stuff      : 10
};

Framework.MyModule(options);

... end doc ready ...

Please see the fiddle: http://jsfiddle.net/kWHEZ/1/

Body:
var options = { /* ... */};
Framework.MyModule = (function(options) {
  /* .. options are undefined ... */
})();

Framework.MyModule = (function(options) {
  /* .. options are defined... */
})(options);

Now if you want the ability to add private/public variables AND still pass options you will need to make it so the a constructor method is returned with your public object - thus not passing options in the function that is run immediately. Because lets be honest .. this doesn't really make sense.

You could do something like this:

var Module = {};
Module.Foo = (function($){ // jQuery is accessible as $
    var _private = {
        defaults: {
            url: '/default-url', container: '#dummy'
        },
        foos: []
    };

    return function(o){ // returns constructor
        // other _private variables are accessible here
        var opts = $.extend({}, _private.defaults, o);
        var self = { // public return object
            load: function(){
                $(opts.container).load(opts.url);
            }
        };
        _private.foos.push(self);
        return self;
    };
})(jQuery); // scope global variables

var foo1 = Module.Foo({
    url: '/test.php',
    container: '#success'
});

var foo2 = Module.Foo({
    url: '/test2.php',
    container: '#success2'
});

foo1.load();
foo2.load();


来源: stackexchange

问:
how can i write as one query to get count in mysql

I want to get the today count of users and yesterday's users count for that i want to write only one query how can i do that..?

these are my queries I want only one query:

```<code>SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,1 as todayCount

SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,0 as yesterdayCount
</code>```

My expected results or only 2 columns

```<code>todayCount yesterdayCount
     2          4
</code>```

答:
This should do the trick:</p>

```<code>SELECT COUNT(CASE
                WHEN visited_date = CURDATE() THEN 1
             END) AS todayCount ,
       COUNT(CASE
                WHEN visited_date = CURDATE() - INTERVAL 1 DAY THEN 1
             END) AS yesterdayCount
FROM visitors
WHERE visited_date IN (CURDATE(), CURDATE() - INTERVAL 1 DAY)
GROUP BY visited_date
ORDER by visited_date
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to get the today count of users and yesterday's users count for that i want to write only one query how can i do that..?

these are my queries I want only one query:

SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,1 as todayCount

SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,0 as yesterdayCount

My expected results or only 2 columns

todayCount yesterdayCount
     2          4

Body:
This should do the trick:

SELECT COUNT(CASE
                WHEN visited_date = CURDATE() THEN 1
             END) AS todayCount ,
       COUNT(CASE
                WHEN visited_date = CURDATE() - INTERVAL 1 DAY THEN 1
             END) AS yesterdayCount
FROM visitors
WHERE visited_date IN (CURDATE(), CURDATE() - INTERVAL 1 DAY)
GROUP BY visited_date
ORDER by visited_date


问:
Testing scala Play (2.2.1) controllers with CSRF protection
I've been having some problems testing controllers that use Play's CSRF protection. To demonstrate this, I've created a very simple Play application that minimally exhibits the problem.

https://github.com/adamnfish/csrftest

The full details are on the README of that repository, but to summarise here:

Consider a controller that is designed to handle a form submission. It has a GET method that uses CSRFAddToken and a POST method that uses CSRFCheck. The former adds a CSRF Token to the request so that a form field can be put in the rendered view, containing the valid token. When that form is submitted, if the CSRF check passes and the submission is valid, something else will happen (typically a redirect). If the form submission is not valid, the form submission is re-shown along with any errors so the user can correct the form and submit again.

This works great!

However, in the tests we now have some problems. To test the controller you can pass a fake request to it in the test. The CSRF check itself can be skipped by adding the nocheck header to the fake request but the view cannot be rendered because no token available to generate the form field. The test fails with a RuntimeException, "Missing CSRF Token (csrf.scala:51)".

Given that it works when it's actually running but not in the tests, it seems like this must be a problem with the way FakeRequests are run in Play tests but I may be doing something wrong. I've implemented the CSRF protection as described at http://www.playframework.com/documentation/2.2.1/ScalaCsrf and the testing as described at http://www.playframework.com/documentation/2.2.1/ScalaFunctionalTest. I'd appreciate any pointers if anyone has managed to test CSRF protected forms.

答:
I use the following method in my base integration test class:

```<code>def csrfRequest(method: String, uri: String)(implicit app: Application): FakeRequest[AnyContentAsEmpty.type] = {
  val tokenProvider: TokenProvider = app.injector.instanceOf[TokenProvider]
  val csrfTags = Map(Token.NameRequestTag -> "csrfToken", Token.RequestTag -> tokenProvider.generateToken)
  FakeRequest(method, uri, FakeHeaders(), AnyContentAsEmpty, tags = csrfTags)
}
</code>```

Then you can use it in your tests where you would use FakeRequest.

Body:
I use the following method in my base integration test class:

def csrfRequest(method: String, uri: String)(implicit app: Application): FakeRequest[AnyContentAsEmpty.type] = {
  val tokenProvider: TokenProvider = app.injector.instanceOf[TokenProvider]
  val csrfTags = Map(Token.NameRequestTag -> "csrfToken", Token.RequestTag -> tokenProvider.generateToken)
  FakeRequest(method, uri, FakeHeaders(), AnyContentAsEmpty, tags = csrfTags)
}

Then you can use it in your tests where you would use FakeRequest.


问:
How to identify if css property on element is in 'px' or 'vw' unit?
Want to know if applied css on an element e.g. width is a pixel unit or related to viewport because window.getComputedStyle always give value in pixels.

Even tried this to identify percentage, but does not work in case of identified 'em', 'vw', 'rem' units.

Note: Not asking for inline styling on element.

答:
Maybe you can try to simulate a resize event (changing the window.innerWidth) and check if you get the same result from window.getComputedStyle

Simulate event resize


问:
F# yield! (yieldbang) operator
I am learning F# at the moment but I'm having a hard time understanding this:

```<code>let allPrimes =
let rec allPrimes' n =
    seq {
        if isPrime n then
            yield n
        yield! allPrimes' (n + 1) }
allPrimes' 2
</code>```

I am not able to figure out what the yield! operator exactly does even though I've read other simpler examples and it seems yield! returns an inner sequence.

答:
The yield bang operator merges the sub sequence produced by the called sequence expressions into the final sequence. Or in simpler words: it "flattens" the returned sequence to include the elements of the sub sequence in the final sequence.

For your example: Without the yield bang operator you would get something like

```<code>{ prime1 { prime2 { prime3 .... }}}
</code>```

with the yield bang operator you get

```<code>{ prime1 prime2 prime3 ... }
</code>```

where each { denotes a new sequence. Side node: The actual result from my first example would even include more sequences, as it would return sequences only containing sequences as the prime is only returned if n is prime.

Title: F# yield! (yieldbang) operator

Body:
I am learning F# at the moment but I'm having a hard time understanding this:

let allPrimes =
let rec allPrimes' n =
    seq {
        if isPrime n then
            yield n
        yield! allPrimes' (n + 1) }
allPrimes' 2

I am not able to figure out what the yield! operator exactly does even though I've read other simpler examples and it seems yield! returns an inner sequence.

Body:
The yield bang operator merges the sub sequence produced by the called sequence expressions into the final sequence. Or in simpler words: it "flattens" the returned sequence to include the elements of the sub sequence in the final sequence.

For your example: Without the yield bang operator you would get something like

{ prime1 { prime2 { prime3 .... }}}

with the yield bang operator you get

{ prime1 prime2 prime3 ... }

where each { denotes a new sequence. Side node: The actual result from my first example would even include more sequences, as it would return sequences only containing sequences as the prime is only returned if n is prime.


问:
Recycler view does not refresh on filter - ArrayAdapter
I have an edit text and a recycler view, what I intend of the edit text is to use the input as a filter on the list. Here is my code:

Fragment:

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.frag_trains_view, container, false);

        mountain.customwidgets.MontserratRegularAutoComplete editStationSearch =
                (mountain.customwidgets.MontserratRegularAutoComplete)
                        view.findViewById(R.id.autoCompleteSource);

        editStationSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mAdapter.getFilter().filter(s);

            }
        });

        RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        CsvReaderImpl csvReader = new CsvReaderImpl();
        stationNameCodePojoArrayList = csvReader.ReadFromfile("data/stations.txt", getActivity());

        mAdapter = new StationsRecyclerAdapter(getActivity(),stationNameCodePojoArrayList);
        mRecyclerView.setAdapter(mAdapter);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);

        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL) {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                // Do not draw the divider
            }
        });

        return view;

    }
</code>```

Here is my adapter class:

```<code>public class StationsRecyclerAdapter extends RecyclerView.Adapter<StationsRecyclerAdapter.DataObjectHolder> implements Filterable {

    private ArrayList<StationPojo> mDataset;
    private StationTextFilter stationTextFilter;
    private Context ctx;

    public StationsRecyclerAdapter(Context ctx, ArrayList<StationPojo> myDataset) {
        this.mDataset = (new ArrayList<>(myDataset));
        this.ctx = ctx;
        for (int i = 0; i < mDataset.size(); i++) {
            System.out.println("mDatasset Original: " + Arrays.asList(mDataset.get(i).getStationName()));
        }
    }

    @Override
    public Filter getFilter() {
        if (stationTextFilter == null) {
            stationTextFilter = new StationTextFilter(this, mDataset);
        }
        return stationTextFilter;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView = LayoutInflater.from(ctx).inflate(R.layout.row_auto_complete, parent, false);
        return new DataObjectHolder(mView);
    }

    public static class DataObjectHolder extends RecyclerView.ViewHolder {
        TextView stationName;
        TextView stationCode;
        TextView stationElevation;

        public DataObjectHolder(View itemView) {
            super(itemView);
            stationName = (TextView) itemView.findViewById(R.id.textStationName);
            stationCode = (TextView) itemView.findViewById(R.id.textStationCode);
            stationElevation = (TextView) itemView.findViewById(R.id.textStationElevation);
        }
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.stationCode.setText(mDataset.get(position).getStationCode());
        holder.stationElevation.setText(mDataset.get(position).getStationElevation());
        holder.stationName.setText(mDataset.get(position).getStationName());

    }

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

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

}
</code>```

And here is the Filter class:

```<code>public class StationTextFilter extends Filter {

    private final StationsRecyclerAdapter adapter;
    private List<StationPojo> mDataset;
    private final List<StationPojo> filteredList;

    public StationTextFilter(StationsRecyclerAdapter adapter, List<StationPojo> mDataset) {
        super();
        this.adapter = adapter;
        this.mDataset = new ArrayList<>(mDataset);
        this.filteredList = new ArrayList<>();
    }

    @Override
    protected FilterResults performFiltering(CharSequence charSequence) {
        filteredList.clear();
        final FilterResults results = new FilterResults();

        if (charSequence.length() == 0) {
            filteredList.addAll(mDataset);
        } else {
            final String filterPattern = charSequence.toString().toLowerCase().trim();
            for (StationPojo item : mDataset) {
                if (item.getStationName().toLowerCase().contains(filterPattern)) {
                    filteredList.add(item);
                    System.out.println("Match found Word: " + filterPattern);

                }
            }
        }

        results.values = filteredList;
        results.count = filteredList.size();
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
        mDataset.clear();
        mDataset.addAll((ArrayList<StationPojo>) filterResults.values);
        for (int i = 0; i < mDataset.size(); i++) {
            System.out.println("mDatasset at filter: " + Arrays.asList(mDataset.get(i).getStationName()));
        }
        adapter.notifyDataSetChanged();
    }
}
</code>```

I am pretty sure that things work fine till the mDataset.addAll((ArrayList<StationPojo>) filterResults.values); as I can print the filtered results, somehow I am not able to know why notifyDatasetChanged does not work! Any headings?

答:
Because your Adapter is referencing a different ArrayList and not the one in your StationTextFilter. See here

```<code>  public StationTextFilter(StationsRecyclerAdapter adapter, List<StationPojo> mDataset) {
        super();
        this.adapter = adapter;
        this.mDataset = new ArrayList<>(mDataset);
        this.filteredList = new ArrayList<>();
    }
</code>```

The mDataset is the actual referenced ArrayList in your adapter, but here you are creating an entirely new ArrayList and thus does not get reflected in your notifyDataSetChanged.

One way to solve this is to not create a new ArrayList and use it as it is.

```<code>this.mDataset = mDataset;
</code>```

Body:
I have an edit text and a recycler view, what I intend of the edit text is to use the input as a filter on the list. Here is my code:

Fragment:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.frag_trains_view, container, false);

        mountain.customwidgets.MontserratRegularAutoComplete editStationSearch =
                (mountain.customwidgets.MontserratRegularAutoComplete)
                        view.findViewById(R.id.autoCompleteSource);

        editStationSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mAdapter.getFilter().filter(s);

            }
        });

        RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        CsvReaderImpl csvReader = new CsvReaderImpl();
        stationNameCodePojoArrayList = csvReader.ReadFromfile("data/stations.txt", getActivity());

        mAdapter = new StationsRecyclerAdapter(getActivity(),stationNameCodePojoArrayList);
        mRecyclerView.setAdapter(mAdapter);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);

        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL) {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                // Do not draw the divider
            }
        });

        return view;

    }

Here is my adapter class:

public class StationsRecyclerAdapter extends RecyclerView.Adapter<StationsRecyclerAdapter.DataObjectHolder> implements Filterable {

    private ArrayList<StationPojo> mDataset;
    private StationTextFilter stationTextFilter;
    private Context ctx;

    public StationsRecyclerAdapter(Context ctx, ArrayList<StationPojo> myDataset) {
        this.mDataset = (new ArrayList<>(myDataset));
        this.ctx = ctx;
        for (int i = 0; i < mDataset.size(); i++) {
            System.out.println("mDatasset Original: " + Arrays.asList(mDataset.get(i).getStationName()));
        }
    }

    @Override
    public Filter getFilter() {
        if (stationTextFilter == null) {
            stationTextFilter = new StationTextFilter(this, mDataset);
        }
        return stationTextFilter;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView = LayoutInflater.from(ctx).inflate(R.layout.row_auto_complete, parent, false);
        return new DataObjectHolder(mView);
    }

    public static class DataObjectHolder extends RecyclerView.ViewHolder {
        TextView stationName;
        TextView stationCode;
        TextView stationElevation;

        public DataObjectHolder(View itemView) {
            super(itemView);
            stationName = (TextView) itemView.findViewById(R.id.textStationName);
            stationCode = (TextView) itemView.findViewById(R.id.textStationCode);
            stationElevation = (TextView) itemView.findViewById(R.id.textStationElevation);
        }
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        holder.stationCode.setText(mDataset.get(position).getStationCode());
        holder.stationElevation.setText(mDataset.get(position).getStationElevation());
        holder.stationName.setText(mDataset.get(position).getStationName());

    }

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

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

}

And here is the Filter class:

public class StationTextFilter extends Filter {

    private final StationsRecyclerAdapter adapter;
    private List<StationPojo> mDataset;
    private final List<StationPojo> filteredList;

    public StationTextFilter(StationsRecyclerAdapter adapter, List<StationPojo> mDataset) {
        super();
        this.adapter = adapter;
        this.mDataset = new ArrayList<>(mDataset);
        this.filteredList = new ArrayList<>();
    }

    @Override
    protected FilterResults performFiltering(CharSequence charSequence) {
        filteredList.clear();
        final FilterResults results = new FilterResults();

        if (charSequence.length() == 0) {
            filteredList.addAll(mDataset);
        } else {
            final String filterPattern = charSequence.toString().toLowerCase().trim();
            for (StationPojo item : mDataset) {
                if (item.getStationName().toLowerCase().contains(filterPattern)) {
                    filteredList.add(item);
                    System.out.println("Match found Word: " + filterPattern);

                }
            }
        }

        results.values = filteredList;
        results.count = filteredList.size();
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
        mDataset.clear();
        mDataset.addAll((ArrayList<StationPojo>) filterResults.values);
        for (int i = 0; i < mDataset.size(); i++) {
            System.out.println("mDatasset at filter: " + Arrays.asList(mDataset.get(i).getStationName()));
        }
        adapter.notifyDataSetChanged();
    }
}

I am pretty sure that things work fine till the mDataset.addAll((ArrayList<StationPojo>) filterResults.values); as I can print the filtered results, somehow I am not able to know why notifyDatasetChanged does not work! Any headings?

Body:
Because your Adapter is referencing a different ArrayList and not the one in your StationTextFilter. See here

  public StationTextFilter(StationsRecyclerAdapter adapter, List<StationPojo> mDataset) {
        super();
        this.adapter = adapter;
        this.mDataset = new ArrayList<>(mDataset);
        this.filteredList = new ArrayList<>();
    }

The mDataset is the actual referenced ArrayList in your adapter, but here you are creating an entirely new ArrayList and thus does not get reflected in your notifyDataSetChanged.

One way to solve this is to not create a new ArrayList and use it as it is.

this.mDataset = mDataset;


问:
Use entityManager in a single repository
I use spring-data-jpa to access my data. I need a way to detach an Object and store it as a new database row. My approach is currently to add a detach method to the repository, but for that, I need a EntityManager. And I haven't found a (nice) way of obtaining it... Any ideas?

```<code>@Repository
public interface InteractionRepository
        extends JpaRepository<Interaction, Long>,
                DetatchableItemRepository{}

public interface DetatchableItemRepository {
    void detach(Interaction clone);
}

public class DetatchableItemRepositoryImpl implements DetatchableItemRepository {

    @Autowired
    EntityManager em;

    public void detach(Interaction clone) {
        em.detach(clone);
        clone.id=null;
        em.persist(clone);

    }
}
</code>```

However, spring dies with this error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'interactionRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property detach found for type Interaction!

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property detach found for type Interaction!

答:
you use wrong name convention for custom repository , try this :

```<code> public interface DetatchableItemRepositoryCustom {
        void detach(Interaction clone);
    }

public interface DetatchableItemRepository extends JpaRepository<Interaction, Long>,
                                        DetatchableItemRepositoryCustom {

 }

 public class DetatchableItemRepositoryImpl implements DetatchableItemRepositoryCustom  {
 }
</code>```

spring data use name convention for custom repository and main repository.(see about name Adding custom behavior to single repositories)

If you have some SomeRepository , that extends some base spring data  repository , and want to add custom behavior then it should be like :

```<code>    interface SomeRepositoryCustom{
       someMethod();
    }
    //XXXRepository - any base spring data repository
    interface SomeRepository extends<T ,ID> extend XXXRepository , SomeRepositoryCustom {
         .......
    }

    public class ARepositoryImpl implement SomeRepositoryCustom{
      @Overide
      someMethod(){
        ....
    }
</code>```

Body:
I use spring-data-jpa to access my data. I need a way to detach an Object and store it as a new database row. My approach is currently to add a detach method to the repository, but for that, I need a EntityManager. And I haven't found a (nice) way of obtaining it... Any ideas?

@Repository
public interface InteractionRepository
        extends JpaRepository<Interaction, Long>,
                DetatchableItemRepository{}

public interface DetatchableItemRepository {
    void detach(Interaction clone);
}

public class DetatchableItemRepositoryImpl implements DetatchableItemRepository {

    @Autowired
    EntityManager em;

    public void detach(Interaction clone) {
        em.detach(clone);
        clone.id=null;
        em.persist(clone);

    }
}

However, spring dies with this error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'interactionRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property detach found for type Interaction!

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property detach found for type Interaction!

Body:
you use wrong name convention for custom repository , try this :

 public interface DetatchableItemRepositoryCustom {
        void detach(Interaction clone);
    }

public interface DetatchableItemRepository extends JpaRepository<Interaction, Long>,
                                        DetatchableItemRepositoryCustom {

 }

 public class DetatchableItemRepositoryImpl implements DetatchableItemRepositoryCustom  {
 }

spring data use name convention for custom repository and main repository.(see about name Adding custom behavior to single repositories)

If you have some SomeRepository , that extends some base spring data  repository , and want to add custom behavior then it should be like :

    interface SomeRepositoryCustom{
       someMethod();
    }
    //XXXRepository - any base spring data repository
    interface SomeRepository extends<T ,ID> extend XXXRepository , SomeRepositoryCustom {
         .......
    }

    public class ARepositoryImpl implement SomeRepositoryCustom{
      @Overide
      someMethod(){
        ....
    }


问:
EC2 FTP User Directory change
Our EC2 instance setup has an ftp user that had successful setup through the vsftpd program with an original home directory of \home\user\, I followed the instructions on this stack overflow, and had the user's shell set to /bin/false

What I'm looking to do is make the ftp user login only accessible to a particular directory, a folder in the html directory - \var\www\html\website.com\userfolder

What I've done:

Added user to a group ftpgroup

Authorized access and ownership of the new directory to the user:ftponly

Changed the user's home directory in /etc/passwd

added .ssh/authorized_keys with user's key in the new directory

changed ChrootDirectory in /etc/ssh/sshd_config to new directory

changed the permissions on the directory to chmod -R 775 user:ftpgroup

mounting \var\www\html\website.com\userfolder

Before these changes I was able to access the FTP, and now upon attempted access I receive the following errors from the Filezilla client:

Error: Disconnected: No supported authentication methods available
(server sent:publickey) ... Status: Connection attempt failed with
"ETIMEDOUT - Connection attempt timed out"

As it was working before, I'm thinking that it might have something to do with permissions, I'm just unsure of where else to change.
Thanks for any insight.

答:
This worked for me.

After creating the user with vsftpd, the user now has access to the directory via FileZilla.
I then added a link from the home/{user} directory to the /var/www/html/{user} directory.
The user can upload files to the home directory and can view it from the html directory.

This is a simple hack. Let me know if this solves your problem.

Title: EC2 FTP User Directory change


问:
How to print request body using spring-test-mvc
I'm using spring-test-mvc to test my controller, but I can't find a way to print request body which is very inconvenient.

with MockMvcResultHandlers.print()

```<code>mvc.perform(put("/payment/1234")
    .content("{\"amount\":2.3")
    .contentType(MediaType.APPLICATION_JSON))
    .andDo(print());
</code>```

I found some body information but don't find the body part:

```<code>MockHttpServletRequest:
     HTTP Method = PUT
     Request URI = /payment/1234
      Parameters = {}
         Headers = {Content-Type=[application/json]}

         Handler:
            Type = com.restbucks.ordering.rest.PaymentResource
          Method = public org.springframework.hateoas.Resource<com.restbucks.ordering.domain.Payment> com.restbucks.ordering.rest.PaymentResource.handle(com.restbucks.ordering.commands.MakePaymentCommand)

           Async:
   Async started = false
    Async result = null
</code>```

Update

After reading some source codes, it seems that I should extends MockMvcResultHandlers to add some print items?

```<code>//PrintingResultHandler.java
protected void printRequest(MockHttpServletRequest request) throws Exception {
    this.printer.printValue("HTTP Method", request.getMethod());
    this.printer.printValue("Request URI", request.getRequestURI());
    this.printer.printValue("Parameters", getParamsMultiValueMap(request));
    this.printer.printValue("Headers", getRequestHeaders(request));
    // add body print?
}
</code>```

Update
Proof of Concept codes:

```<code>public static class CustomMockMvcResultHandlers {

    public static ResultHandler print() {
        return new ConsolePrintingResultHandler();
    }

    /**
     * Have to copy this class from spring
     */
    private static class ConsolePrintingResultHandler extends PrintingResultHandler {

        public ConsolePrintingResultHandler() {
            super(new ResultValuePrinter() {

                @Override
                public void printHeading(String heading) {
                    System.out.println();
                    System.out.println(String.format("%20s:", heading));
                }

                @Override
                public void printValue(String label, Object value) {
                    if (value != null && value.getClass().isArray()) {
                        value = CollectionUtils.arrayToList(value);
                    }
                    System.out.println(String.format("%20s = %s", label, value));
                }

            });

        }

        @Override
        protected void printRequest(MockHttpServletRequest request) throws Exception {
            super.printRequest(request);
            getPrinter().printValue("Body", getContentAsString(request));
        }

        private String getContentAsString(MockHttpServletRequest request) throws IOException {
            BufferedReader reader = request.getReader();

            StringBuilder builder = new StringBuilder();
            String aux;

            while ((aux = reader.readLine()) != null) {
                builder.append(aux);
            }

            return builder.toString();
        }
    }
}
</code>```

答:
I believe this will now be possible with Spring Framework 5.0 M3:

The print() and log() methods in Spring MVC Test now print the request body if the character encoding has been set in the mock request.

Based on this Jira ticket

Also mentioned in the release notes

Body:
I'm using spring-test-mvc to test my controller, but I can't find a way to print request body which is very inconvenient.

with MockMvcResultHandlers.print()

mvc.perform(put("/payment/1234")
    .content("{\"amount\":2.3")
    .contentType(MediaType.APPLICATION_JSON))
    .andDo(print());

I found some body information but don't find the body part:

MockHttpServletRequest:
     HTTP Method = PUT
     Request URI = /payment/1234
      Parameters = {}
         Headers = {Content-Type=[application/json]}

         Handler:
            Type = com.restbucks.ordering.rest.PaymentResource
          Method = public org.springframework.hateoas.Resource<com.restbucks.ordering.domain.Payment> com.restbucks.ordering.rest.PaymentResource.handle(com.restbucks.ordering.commands.MakePaymentCommand)

           Async:
   Async started = false
    Async result = null

Update

After reading some source codes, it seems that I should extends MockMvcResultHandlers to add some print items?

//PrintingResultHandler.java
protected void printRequest(MockHttpServletRequest request) throws Exception {
    this.printer.printValue("HTTP Method", request.getMethod());
    this.printer.printValue("Request URI", request.getRequestURI());
    this.printer.printValue("Parameters", getParamsMultiValueMap(request));
    this.printer.printValue("Headers", getRequestHeaders(request));
    // add body print?
}

Update
Proof of Concept codes:

public static class CustomMockMvcResultHandlers {

    public static ResultHandler print() {
        return new ConsolePrintingResultHandler();
    }

    /**
     * Have to copy this class from spring
     */
    private static class ConsolePrintingResultHandler extends PrintingResultHandler {

        public ConsolePrintingResultHandler() {
            super(new ResultValuePrinter() {

                @Override
                public void printHeading(String heading) {
                    System.out.println();
                    System.out.println(String.format("%20s:", heading));
                }

                @Override
                public void printValue(String label, Object value) {
                    if (value != null && value.getClass().isArray()) {
                        value = CollectionUtils.arrayToList(value);
                    }
                    System.out.println(String.format("%20s = %s", label, value));
                }

            });

        }

        @Override
        protected void printRequest(MockHttpServletRequest request) throws Exception {
            super.printRequest(request);
            getPrinter().printValue("Body", getContentAsString(request));
        }

        private String getContentAsString(MockHttpServletRequest request) throws IOException {
            BufferedReader reader = request.getReader();

            StringBuilder builder = new StringBuilder();
            String aux;

            while ((aux = reader.readLine()) != null) {
                builder.append(aux);
            }

            return builder.toString();
        }
    }
}


问:
redirecting issue with .htaccess file in PHP
I have a site like https://yoursitename.com. I am using .htaccess file for redirection. The code in .htaccess file is as :

```<code>RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]
</code>```

But redirection goes me to another page which has the following htaccess code :

```<code>RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1
</code>```

What I am doing wrong?

Content of .htaccess file

```<code>RewriteEngine on
RewriteBase    /

RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]
RewriteRule ^websites/established /filter.php?module=1&filter=established [R=301,NC,P]
RewriteRule ^websites/starter /filter.php?module=1&filter=starter [R=301,NC,P]
RewriteRule ^websites/active /filter.php?module=1&filter=active [R=301,NC,P]
RewriteRule ^websites/ending /filter.php?module=1&filter=ending [R=301,NC,P]
RewriteRule ^websites/justsold /filter.php?module=1&filter=justsold [R=301,NC,P]
RewriteRule ^websites/dealflow /filter.php?module=1&filter=dealflow [R=301,NC,P]

RewriteRule ^domains/all /filter.php?module=2&filter=all [R=301,NC,P]
RewriteRule ^domains/auction /filter.php?module=2&filter=auction [R=301,NC,P]
RewriteRule ^domains/active /filter.php?module=2&filter=active [R=301,NC,P]
RewriteRule ^domains/ending /filter.php?module=2&filter=ending [R=301,NC,P]
RewriteRule ^domains/justsold /filter.php?module=2&filter=justsold [R=301,NC,P]
RewriteRule ^domains/appraisal /filter.php?module=2&filter=appraisal [R=301,NC,P]
RewriteRule ^domains/brokered /filter.php?module=2&filter=brokered [R=301,NC,P]

RewriteRule ^apps/all /filter.php?module=3&filter=all [R=301,NC,P]
RewriteRule ^apps/ios /filter.php?module=3&filter=ios [R=301,NC,P]
RewriteRule ^apps/android /filter.php?module=3&filter=android [R=301,NC,P]
RewriteRule ^apps/active /filter.php?module=3&filter=active [R=301,NC,P]
RewriteRule ^apps/ending /filter.php?module=3&filter=ending [R=301,NC,P]
RewriteRule ^apps/justsold /filter.php?module=3&filter=justsold [R=301,NC,P]

RewriteRule ^(websites|domains|apps|digitalGoods|sell)($|/) - [L]

RewriteRule ^item/(.*)$ ./show-digital.php?url=$1

RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1

RewriteCond %{HTTP_HOST} ^hiwebby\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.hiwebby\.com$

RewriteRule ^blog\/index\.php$ "http\:\/\/hiwebby\.com\/blog\/index\.php\/Support\/" [R=301,L]
</code>```

答:
Your rewrite rules seem dubious at many lines. In my answer, there
are few questions for you as well. Configuring server behavior with rewrite rules is tricky any misconfiguration will lead to the serious problem with the websites. That's why the complete lookup is necessary. Also, you should consider reading the document https://httpd.apache.org/docs/current/rewrite/flags.html#page-header

```<code>RewriteEngine on
RewriteBase /
</code>```

That's fine.

```<code>RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]
RewriteRule ^websites/established /filter.php?module=1&filter=established [R=301,NC,P]
RewriteRule ^websites/starter /filter.php?module=1&filter=starter [R=301,NC,P]
RewriteRule ^websites/active /filter.php?module=1&filter=active [R=301,NC,P]
RewriteRule ^websites/ending /filter.php?module=1&filter=ending [R=301,NC,P]
RewriteRule ^websites/justsold /filter.php?module=1&filter=justsold [R=301,NC,P]
RewriteRule ^websites/dealflow /filter.php?module=1&filter=dealflow [R=301,NC,P]
</code>```

But in the code shown above:

Probably you are not using a proxy or redirect. So you can use flag [NC,L] instead. And in place of all the seven lines, you can use just

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^websites/(.*)$ filter.php?module=1&filter=$1 [NC,L]
</code>```

Similarly

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^domains/(.*)$ filter.php?module=2&filter=$1 [NC,L]
</code>```

and

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^apps/(.*)$ filter.php?module=3&filter=$1 [NC,L]
</code>```

so on (if there is any).

```<code>RewriteRule ^(websites|domains|apps|digitalGoods|sell)($|/) - [L]
</code>```

In your above line how you are going to handle requests like domain.com/websites. Is there any directory named websites?.

The "-" syntax means that the requested URI is not modified.

```<code>RewriteRule ^item/(.*)$ ./show-digital.php?url=$1
</code>```

In above code . is there for any purpose in ./show-digital.php?url=$1? and also there is no flag provided. You can modify it like

```<code>RewriteRule ^item/(.*)$ show-digital.php?url=$1 [NC,L]
</code>```

```<code>RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1 [NC,P]
</code>```

Here also correct flag would be [NC,L]

```<code>RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1 [NC,L]
</code>```

```<code>RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]
RewriteRule ^websites/established /filter.php?module=1&filter=established [R=301,NC,P]
RewriteRule ^websites/starter /filter.php?module=1&filter=starter [R=301,NC,P]
RewriteRule ^websites/active /filter.php?module=1&filter=active [R=301,NC,P]
RewriteRule ^websites/ending /filter.php?module=1&filter=ending [R=301,NC,P]
RewriteRule ^websites/justsold /filter.php?module=1&filter=justsold [R=301,NC,P]
RewriteRule ^websites/dealflow /filter.php?module=1&filter=dealflow [R=301,NC,P]
</code>```0

In this section can you explain what you want to do.

Body:
I have a site like https://yoursitename.com. I am using .htaccess file for redirection. The code in .htaccess file is as :

RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]

But redirection goes me to another page which has the following htaccess code :

RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1

What I am doing wrong?

Content of .htaccess file

RewriteEngine on
RewriteBase    /

RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]
RewriteRule ^websites/established /filter.php?module=1&filter=established [R=301,NC,P]
RewriteRule ^websites/starter /filter.php?module=1&filter=starter [R=301,NC,P]
RewriteRule ^websites/active /filter.php?module=1&filter=active [R=301,NC,P]
RewriteRule ^websites/ending /filter.php?module=1&filter=ending [R=301,NC,P]
RewriteRule ^websites/justsold /filter.php?module=1&filter=justsold [R=301,NC,P]
RewriteRule ^websites/dealflow /filter.php?module=1&filter=dealflow [R=301,NC,P]

RewriteRule ^domains/all /filter.php?module=2&filter=all [R=301,NC,P]
RewriteRule ^domains/auction /filter.php?module=2&filter=auction [R=301,NC,P]
RewriteRule ^domains/active /filter.php?module=2&filter=active [R=301,NC,P]
RewriteRule ^domains/ending /filter.php?module=2&filter=ending [R=301,NC,P]
RewriteRule ^domains/justsold /filter.php?module=2&filter=justsold [R=301,NC,P]
RewriteRule ^domains/appraisal /filter.php?module=2&filter=appraisal [R=301,NC,P]
RewriteRule ^domains/brokered /filter.php?module=2&filter=brokered [R=301,NC,P]

RewriteRule ^apps/all /filter.php?module=3&filter=all [R=301,NC,P]
RewriteRule ^apps/ios /filter.php?module=3&filter=ios [R=301,NC,P]
RewriteRule ^apps/android /filter.php?module=3&filter=android [R=301,NC,P]
RewriteRule ^apps/active /filter.php?module=3&filter=active [R=301,NC,P]
RewriteRule ^apps/ending /filter.php?module=3&filter=ending [R=301,NC,P]
RewriteRule ^apps/justsold /filter.php?module=3&filter=justsold [R=301,NC,P]

RewriteRule ^(websites|domains|apps|digitalGoods|sell)($|/) - [L]

RewriteRule ^item/(.*)$ ./show-digital.php?url=$1

RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1

RewriteCond %{HTTP_HOST} ^hiwebby\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.hiwebby\.com$

RewriteRule ^blog\/index\.php$ "http\:\/\/hiwebby\.com\/blog\/index\.php\/Support\/" [R=301,L]

Body:
Your rewrite rules seem dubious at many lines. In my answer, there
are few questions for you as well. Configuring server behavior with rewrite rules is tricky any misconfiguration will lead to the serious problem with the websites. That's why the complete lookup is necessary. Also, you should consider reading the document https://httpd.apache.org/docs/current/rewrite/flags.html#page-header

RewriteEngine on
RewriteBase /

That's fine.

RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]
RewriteRule ^websites/established /filter.php?module=1&filter=established [R=301,NC,P]
RewriteRule ^websites/starter /filter.php?module=1&filter=starter [R=301,NC,P]
RewriteRule ^websites/active /filter.php?module=1&filter=active [R=301,NC,P]
RewriteRule ^websites/ending /filter.php?module=1&filter=ending [R=301,NC,P]
RewriteRule ^websites/justsold /filter.php?module=1&filter=justsold [R=301,NC,P]
RewriteRule ^websites/dealflow /filter.php?module=1&filter=dealflow [R=301,NC,P]

But in the code shown above:

Probably you are not using a proxy or redirect. So you can use flag [NC,L] instead. And in place of all the seven lines, you can use just

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^websites/(.*)$ filter.php?module=1&filter=$1 [NC,L]

Similarly

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^domains/(.*)$ filter.php?module=2&filter=$1 [NC,L]

and

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^apps/(.*)$ filter.php?module=3&filter=$1 [NC,L]

so on (if there is any).

RewriteRule ^(websites|domains|apps|digitalGoods|sell)($|/) - [L]

In your above line how you are going to handle requests like domain.com/websites. Is there any directory named websites?.

The "-" syntax means that the requested URI is not modified.

RewriteRule ^item/(.*)$ ./show-digital.php?url=$1

In above code . is there for any purpose in ./show-digital.php?url=$1? and also there is no flag provided. You can modify it like

RewriteRule ^item/(.*)$ show-digital.php?url=$1 [NC,L]

RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1 [NC,P]

Here also correct flag would be [NC,L]

RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1 [NC,L]

RewriteCond %{HTTP_HOST} ^hiwebby\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.hiwebby\.com$

RewriteRule ^blog\/index\.php$ "http\:\/\/hiwebby\.com\/blog\/index\.php\/Support\/" [R=301,L]

In this section can you explain what you want to do.


问:
Angular2/4 : Refresh Data Realtime
I need to refresh the data in a component page in an interval. Also I need to refresh the data after doing some action. I am using Obeservables in the service so that I can subscribe to when the response is ready. I am pushing the subscriptions to a object so that I can clear that on ngDestroy, I think, I have the following methods to achieve the same.

Method 1 : setInterval

I have set an interval on ngOnInit, which will call the refreshData in equal interval. The interval object will be cleared using clearInterval in ngOnDestroy method.

```<code>export class MyComponent implements OnInit, OnDestroy {
    private subscription: Subscription = new Subscription();

    data: any;
    interval: any;

    ngOnInit() {
        this.refreshData();
        this.interval = setInterval(() => {
            this.refreshData();
        }, 5000);
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
        clearInterval(this.interval);
    }

    refreshData(){
        this.subscription.add(
            this.myService.getData()
                .subscribe(data => {
                    this.data = data;
                })
        );
    }

    doAction(){
        this.subscription.add(
            this.myService.doAction()
                .subscribe(result => {
                    if(result === true){
                        this.refreshData();
                    }
                })
        );
    }
}
</code>```

Q1 : On each refresh call a subscription will be added to the subscription object, will that increase the memory usage and may crash the browser if user keeps the page opened for a while?

Method2 : Observable.timer

This method is using a timer which will created after the data is refreshed.

```<code>export class MyComponent implements OnInit, OnDestroy {
    private subscription: Subscription = new Subscription();

    data: any;

    ngOnInit() {
        this.refreshData();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }

    refreshData(){
        this.subscription.add(
            this.myService.getData()
                .subscribe(data => {
                    this.data = data;
                    this.subscribeToData();
                })
        );
    }

    subscribeToData(){
        this.subscription.add(
            Observable.timer(10000).subscribe(() => this.refreshData())
        );
    }

    doAction(){
        this.subscription.add(
            this.myService.doAction()
                .subscribe(result => {
                    if(result === true){
                        this.refreshData();
                    }
                })
        );
    }
}
</code>```

Q2 : I have the same question(Q1) here. This way, will add the timers also to the subscription object, so infact the subscriptions in the subscription object is doubled.

Q3 : To refresh data after the action method - doAction(), the refreshData is called. So will that create another chain of timer?

Q4 : Which is the better way without memory leaks or if there exists any other way?

答:
You should be able to do this without problems:

```<code>ngOnInit() {
    this.refreshData();
    this.interval = setInterval(() => {
        this.refreshData();
    }, 5000);
}

refreshData(){
    this.myService.getData()
        .subscribe(data => {
            this.data = data;
        })
    );
}
</code>```

As per this post Angular will take care of cleaning up after itself.

However, if you're going to have a live data stream in your app I'd suggest changing your component so that rather than subscribing to each response of your service's http request, you instead subscribe once to a new observable data$ property of your service in your component's ngOnInit(). Then, on interval (as you're doing) call updateData() on your service (or setup the interval inside your service) but don't subscribe. When your service successfully fetches the data, it pushes the next value to its observable data$ property, giving you a stream of data from your service that you can react to anywhere in your app.

```<code>ngOnInit() {
    this.myService.data$.subscribe(data => { // subscribe once to the data stream
        this.data = data;
    })

    this.refreshData();
    this.interval = setInterval(() => {
        this.refreshData();
    }, 5000);
}

refreshData(){
    this.myService.updateData(); // simply signal for the service to update its data stream
}
</code>```

With myService.data$ being an observable BehaviourSubject updated in your service, something like this:

```<code>public data$: BehaviorSubject<any> = new BehaviorSubject({});

updateData() {
    let data = this.http.get('http://www.data.com').map((data)=>{
        return data.json();
    }).do((data)=>{
        this.data$.next(data);
    })
}
</code>```

That way you can avoid multiple subscriptions and make the data stream available to any component that needs it.

Title: Angular2/4 : Refresh Data Realtime

Body:
I need to refresh the data in a component page in an interval. Also I need to refresh the data after doing some action. I am using Obeservables in the service so that I can subscribe to when the response is ready. I am pushing the subscriptions to a object so that I can clear that on ngDestroy, I think, I have the following methods to achieve the same.

Method 1 : setInterval

I have set an interval on ngOnInit, which will call the refreshData in equal interval. The interval object will be cleared using clearInterval in ngOnDestroy method.

export class MyComponent implements OnInit, OnDestroy {
    private subscription: Subscription = new Subscription();

    data: any;
    interval: any;

    ngOnInit() {
        this.refreshData();
        this.interval = setInterval(() => {
            this.refreshData();
        }, 5000);
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
        clearInterval(this.interval);
    }

    refreshData(){
        this.subscription.add(
            this.myService.getData()
                .subscribe(data => {
                    this.data = data;
                })
        );
    }

    doAction(){
        this.subscription.add(
            this.myService.doAction()
                .subscribe(result => {
                    if(result === true){
                        this.refreshData();
                    }
                })
        );
    }
}

Q1 : On each refresh call a subscription will be added to the subscription object, will that increase the memory usage and may crash the browser if user keeps the page opened for a while?

Method2 : Observable.timer

This method is using a timer which will created after the data is refreshed.

export class MyComponent implements OnInit, OnDestroy {
    private subscription: Subscription = new Subscription();

    data: any;

    ngOnInit() {
        this.refreshData();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }

    refreshData(){
        this.subscription.add(
            this.myService.getData()
                .subscribe(data => {
                    this.data = data;
                    this.subscribeToData();
                })
        );
    }

    subscribeToData(){
        this.subscription.add(
            Observable.timer(10000).subscribe(() => this.refreshData())
        );
    }

    doAction(){
        this.subscription.add(
            this.myService.doAction()
                .subscribe(result => {
                    if(result === true){
                        this.refreshData();
                    }
                })
        );
    }
}

Q2 : I have the same question(Q1) here. This way, will add the timers also to the subscription object, so infact the subscriptions in the subscription object is doubled.

Q3 : To refresh data after the action method - doAction(), the refreshData is called. So will that create another chain of timer?

Q4 : Which is the better way without memory leaks or if there exists any other way?

Body:
You should be able to do this without problems:

ngOnInit() {
    this.refreshData();
    this.interval = setInterval(() => {
        this.refreshData();
    }, 5000);
}

refreshData(){
    this.myService.getData()
        .subscribe(data => {
            this.data = data;
        })
    );
}

As per this post Angular will take care of cleaning up after itself.

However, if you're going to have a live data stream in your app I'd suggest changing your component so that rather than subscribing to each response of your service's http request, you instead subscribe once to a new observable data$ property of your service in your component's ngOnInit(). Then, on interval (as you're doing) call updateData() on your service (or setup the interval inside your service) but don't subscribe. When your service successfully fetches the data, it pushes the next value to its observable data$ property, giving you a stream of data from your service that you can react to anywhere in your app.

ngOnInit() {
    this.myService.data$.subscribe(data => { // subscribe once to the data stream
        this.data = data;
    })

    this.refreshData();
    this.interval = setInterval(() => {
        this.refreshData();
    }, 5000);
}

refreshData(){
    this.myService.updateData(); // simply signal for the service to update its data stream
}

With myService.data$ being an observable BehaviourSubject updated in your service, something like this:

public data$: BehaviorSubject<any> = new BehaviorSubject({});

updateData() {
    let data = this.http.get('http://www.data.com').map((data)=>{
        return data.json();
    }).do((data)=>{
        this.data$.next(data);
    })
}

That way you can avoid multiple subscriptions and make the data stream available to any component that needs it.


问:
How to keep output window always open in Visual Studio 2017
I am developing C# Windows Forms App, and need to output some debug message using Debug.Print(). However, the output window is always being minimised on each new debug session. How do I keep it dock'ed to the window so I don't have to click it every single time?

Also, how can I reset the window layout in coding and debugging mode separately? Especially the debugging mode, it seems not saving the layout...

I found similar questions about opening the output window during building, but couldn't find any reference on debugging.

---- update

Thanks for the contributions. Although it was not the solution. I tried to reset the layout again and a few times and it now works fine. It was weird that it wasn't working.

Since no one submitted the solution and I am still expecting if anyone knows the cause and solution, I am leaving this question open without accepting any of the answers.

Thanks again.

2017.08.03.

答:
Go to "Tools" -> "Options..." and under the "Projects and Solutions" tab
expander, you can find a checkbox labeled "Show Output window when build starts". Check it to enable the output window/pane to appear automatically when you build your project. Keep it unchecked, if you don't want to open it automatically.


问:
CRC-CCITT Implementation
I am using the following function to generate a CRC sum and it doesn't appear to be returning the same checksum when compared to online CRC-CCITT calculators.

This function specifically uses the XMODEM CRC generation with a 0x8408 polynomial with an initial fcs of 0xFFFF.

```<code>uint16_t crc16(uint8_t byte, uint16_t fcs)
{
    uint8_t bit;

    for(bit=0; bit<8; bit++)
    {
        fcs ^= (byte & 0x01);
        fcs = (fcs & 0x01) ? (fcs >> 1) ^ 0x8408 : (fcs >> 1);
        byte = byte >> 1;
    }
    return fcs;
}
</code>```

Am I doing something wrong? If I send 0xFF, or 0x00 I do not get the same checksum as I do on http://depa.usst.edu.cn/chenjq/www2/SDesign/JavaScript/CRCcalculation.htm

```<code>printf("%04X\n", crc16(0x31, 0xFFFF)); //returns 2F8D
</code>```

答:
I have read your questions and I also had the similar problem like you.

I have solved this issue for calculating CRC-CCITT in XMODEM. here I am attaching the sample program to calculate CRC-CCITT.

I have tried the data with the online converter and this program. Please use this if you wish.

```<code>unsigned short crc16(char *ptr, int count)
{
   int  crc;
   char i;
   crc = 0;
   while (--count >= 0)
   {
      crc = crc ^ (int) *ptr++ << 8;
      i = 8;
      do
      {
         if (crc & 0x8000)
            crc = crc << 1 ^ 0x1021;
         else
            crc = crc << 1;
      } while(--i);
   }
   return (crc);
}
</code>```

CRC should be defined as unsigned short since the crc16 function returns an unsigned short. CRC is defined as an int which on most systems is 4 bytes.

Title: CRC-CCITT Implementation

Body:
I am using the following function to generate a CRC sum and it doesn't appear to be returning the same checksum when compared to online CRC-CCITT calculators.

This function specifically uses the XMODEM CRC generation with a 0x8408 polynomial with an initial fcs of 0xFFFF.

uint16_t crc16(uint8_t byte, uint16_t fcs)
{
    uint8_t bit;

    for(bit=0; bit<8; bit++)
    {
        fcs ^= (byte & 0x01);
        fcs = (fcs & 0x01) ? (fcs >> 1) ^ 0x8408 : (fcs >> 1);
        byte = byte >> 1;
    }
    return fcs;
}

Am I doing something wrong? If I send 0xFF, or 0x00 I do not get the same checksum as I do on http://depa.usst.edu.cn/chenjq/www2/SDesign/JavaScript/CRCcalculation.htm

printf("%04X\n", crc16(0x31, 0xFFFF)); //returns 2F8D

Body:
I have read your questions and I also had the similar problem like you.

I have solved this issue for calculating CRC-CCITT in XMODEM. here I am attaching the sample program to calculate CRC-CCITT.

I have tried the data with the online converter and this program. Please use this if you wish.

unsigned short crc16(char *ptr, int count)
{
   int  crc;
   char i;
   crc = 0;
   while (--count >= 0)
   {
      crc = crc ^ (int) *ptr++ << 8;
      i = 8;
      do
      {
         if (crc & 0x8000)
            crc = crc << 1 ^ 0x1021;
         else
            crc = crc << 1;
      } while(--i);
   }
   return (crc);
}

CRC should be defined as unsigned short since the crc16 function returns an unsigned short. CRC is defined as an int which on most systems is 4 bytes.

ContentLicense: CC BY-SA 4.0


问:
Remove whitespace using PIG
I have comma(,) delimited (csv) data set. Where there is a white space after each delimiter which I want to remove in Pig script. Example row looks like:

```<code>"Sachin", "India", "batsaman", "99", "kolkata", " ", "xyz"
</code>```

After removing whitespace after comma it should look like:

```<code>"Sachin","India","batsaman","99","kolkata"," ","xyz"
</code>```

答:
Load it into a single field and use REPLACE.</p>

```<code>A = LOAD 'data.txt' USING TextLoader();
B = FOREACH A GENERATE REPLACE($0,' ','');
</code>```

Title: Remove whitespace using PIG

Body:
I have comma(,) delimited (csv) data set. Where there is a white space after each delimiter which I want to remove in Pig script. Example row looks like:

"Sachin", "India", "batsaman", "99", "kolkata", " ", "xyz"

After removing whitespace after comma it should look like:

"Sachin","India","batsaman","99","kolkata"," ","xyz"

Body:
Load it into a single field and use REPLACE.

A = LOAD 'data.txt' USING TextLoader();
B = FOREACH A GENERATE REPLACE($0,' ','');


问:
android c2dm registration ID
I read in the explanation in Android Cloud to Device Messaging Framework.
After our app register successfully to C2DM server, we receive a registration ID. The registration ID lasts until the application explicitly unregisters itself, or until Google refreshes the registration ID for your application. When is exactly Google refreshes the registration ID for your application?? How do we know it so we can register again and send our new registration ID to our server.

Thank you.

答:
According to discussions on the android-c2dm mailing list, refreshing the registration ID is not a frequent event, but your application should be able to handle it. The OS will fire the registration Intent again with the new registration ID.

See the following threads on Google Groups: [1] [2] [3]

ContentLicense: CC BY-SA 2.5

Title: android c2dm registration ID


问:
How to add hashes to itself and remove duplicates in Ruby?
I have a hash:

```<code>h = { ["alpha"]=>[{  "bit"=>"100", "colour"=>"red"},
                  {   "id"=>"100", "colour"=>"red"},
                  { "value"=>"65", "colour"=>"red"}],
      ["beta"] =>[{   "id"=>"070", "colour"=>"black"},
                  {"value"=>"338", "colour"=>"black"}]
}
</code>```

I want to add hashes in values to itself and delete duplicated pairs from every item to get

```<code>h = { ["alpha"]=>[{"bit"=>"100", "id"=>"100", "value"=>"65", "colour"=>"red"}],
      ["beta"] =>[{"id"=>"070", "value"=>"338", "colour"=>"black"}]
}
</code>```

I tried so far converting hashes to array and remove duplicates but how to convert array to hash again? And I also think it is not effective and elegant solution. Any other ideas?

答:
for Ruby >= 2.4.0 - method #transform_values with methods #inject and #merge

```<code>h.transform_values { |v| v.inject(:merge) }
</code>```

For lower versions:

```<code>h.map { |k, v| [k, v.inject(:merge)] }.to_h
</code>```

Body:
I have a hash:

h = { ["alpha"]=>[{  "bit"=>"100", "colour"=>"red"},
                  {   "id"=>"100", "colour"=>"red"},
                  { "value"=>"65", "colour"=>"red"}],
      ["beta"] =>[{   "id"=>"070", "colour"=>"black"},
                  {"value"=>"338", "colour"=>"black"}]
}

I want to add hashes in values to itself and delete duplicated pairs from every item to get

h = { ["alpha"]=>[{"bit"=>"100", "id"=>"100", "value"=>"65", "colour"=>"red"}],
      ["beta"] =>[{"id"=>"070", "value"=>"338", "colour"=>"black"}]
}

I tried so far converting hashes to array and remove duplicates but how to convert array to hash again? And I also think it is not effective and elegant solution. Any other ideas?

Body:
for Ruby >= 2.4.0 - method #transform_values with methods #inject and #merge

h.transform_values { |v| v.inject(:merge) }

For lower versions:

h.map { |k, v| [k, v.inject(:merge)] }.to_h


问:
Javascript - Month Year range automatically on selectlist
I'm try to automacially create a select list that has the following:

```<code><select name="Range" id="ranges">
  <option value="July 2017">July 2017</option>
   <option value="June 2017">June 2017</option>
     <option value="May 2017">May 2017</option>
</code>```

all the way down to August 2015

```<code>     <option value="August 2015">August 2015</option>

</select>
</code>```

The first option must be the current Month and Year

is this possible to be automatically populated via javascript?

答:
Here is an updated solution to your requirement, with just plain JQuery and no datepicker:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var currentMonthName = months[new Date().getMonth() + 1];

for (i = new Date().getFullYear(); i > 2014; i--) {
  $.each(months, function(index, value) {
    if (i == 2015 && value == 'Sep')
      return false;

    if (i == new Date().getFullYear()) {
      if (value == currentMonthName) {
        return false;
      } else {
        $('#yearMonthInput').append($('<option />').val(index + "_" + i).html(value + " " + i));
      }
    } else {
      $('#yearMonthInput').append($('<option />').val(index + "_" + i).html(value + " " + i));
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="yearMonthInput"></select></code>```

Body:
I'm try to automacially create a select list that has the following:

<select name="Range" id="ranges">
  <option value="July 2017">July 2017</option>
   <option value="June 2017">June 2017</option>
     <option value="May 2017">May 2017</option>

all the way down to August 2015

     <option value="August 2015">August 2015</option>

</select>

The first option must be the current Month and Year

is this possible to be automatically populated via javascript?

Body:
Here is an updated solution to your requirement, with just plain JQuery and no datepicker:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var currentMonthName = months[new Date().getMonth() + 1];

for (i = new Date().getFullYear(); i > 2014; i--) {
  $.each(months, function(index, value) {
    if (i == 2015 && value == 'Sep')
      return false;

    if (i == new Date().getFullYear()) {
      if (value == currentMonthName) {
        return false;
      } else {
        $('#yearMonthInput').append($('<option />').val(index + "_" + i).html(value + " " + i));
      }
    } else {
      $('#yearMonthInput').append($('<option />').val(index + "_" + i).html(value + " " + i));
    }
  });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="yearMonthInput"></select>


问:
How to select max aggregate within a subquery with a join in eloquent
I want to select the most recent entry but there are no timestamps(created_at) it can be identified by selecting the max on the primary key. The problem is to this within a subquery and tables needs to be joined.

The query is like:

```<code>        $prodarr = DB::table('onhand_inventory')
            ->leftJoin('mapping', 'onhand_inventory.sku', '=', 'mapping.sku')
            ->where('mapping.mid', function ($query) {
                $query->select('mapping.mid')->from('mapping')
                    ->whereRaw('onhand_inventory.sku = mapping.sku')
                    ->max('mapping.mid');
            })->leftJoin('order_products', 'order_products.sku', '=', 'onhand_inventory.sku')
            ->leftJoin('vendors', 'mapping.v_id', '=', 'vendors.vid')
            ->where('onhand_inventory.shipped_with_box', 0)
            ->groupBy('onhand_inventory.inv_id')
            ->orderBy('onhand_inventory.inv_id')
            ->get();
</code>```

On executing the above query following error is thrown
Column not found: 1054 Unknown column 'onhand_inventory.sku' in 'where clause'

How to get the onhand_inventory's data to be compared with the mapping's inside the subquery.

答:
You already joined the mapping table so you dont need the sub query.

```<code>$prodarr = DB::table('onhand_inventory')
            ->leftJoin('mapping', 'onhand_inventory.sku', '=', 'mapping.sku')
           ->leftJoin('order_products', 'order_products.sku', '=', 'onhand_inventory.sku')
            ->leftJoin('vendors', 'mapping.v_id', '=', 'vendors.vid')
            ->where('onhand_inventory.shipped_with_box', 0)
            ->orderBy('mapping.mid', 'desc')
            ->groupBy('onhand_inventory.inv_id')
            ->orderBy('onhand_inventory.inv_id')
            ->limit(1)
            ->get();
</code>```

I didnt run the code but i hope this will help.

Body:
I want to select the most recent entry but there are no timestamps(created_at) it can be identified by selecting the max on the primary key. The problem is to this within a subquery and tables needs to be joined.

The query is like:

        $prodarr = DB::table('onhand_inventory')
            ->leftJoin('mapping', 'onhand_inventory.sku', '=', 'mapping.sku')
            ->where('mapping.mid', function ($query) {
                $query->select('mapping.mid')->from('mapping')
                    ->whereRaw('onhand_inventory.sku = mapping.sku')
                    ->max('mapping.mid');
            })->leftJoin('order_products', 'order_products.sku', '=', 'onhand_inventory.sku')
            ->leftJoin('vendors', 'mapping.v_id', '=', 'vendors.vid')
            ->where('onhand_inventory.shipped_with_box', 0)
            ->groupBy('onhand_inventory.inv_id')
            ->orderBy('onhand_inventory.inv_id')
            ->get();

On executing the above query following error is thrown
Column not found: 1054 Unknown column 'onhand_inventory.sku' in 'where clause'

How to get the onhand_inventory's data to be compared with the mapping's inside the subquery.

Body:
You already joined the mapping table so you dont need the sub query.

$prodarr = DB::table('onhand_inventory')
            ->leftJoin('mapping', 'onhand_inventory.sku', '=', 'mapping.sku')
           ->leftJoin('order_products', 'order_products.sku', '=', 'onhand_inventory.sku')
            ->leftJoin('vendors', 'mapping.v_id', '=', 'vendors.vid')
            ->where('onhand_inventory.shipped_with_box', 0)
            ->orderBy('mapping.mid', 'desc')
            ->groupBy('onhand_inventory.inv_id')
            ->orderBy('onhand_inventory.inv_id')
            ->limit(1)
            ->get();

I didnt run the code but i hope this will help.


问:
Shell Script ( Send the file from date wise directory ) - Linux
What I have in the system :

There is archive directory ( date wise ) where one file is getting saved after its processing every day.

example(s) are :
The directory name would be: 20170707 > temp_process.txt
The directory name would be: 20170708 > temp_process.txt

Requirement is:
I would like to write a shell script which sends this file every day to the specific email every day only once.

Here, it should fetch the file from date wise directory ( i.e No static directory ).

Please help me for the same.

Thank you in advance!!

答:
Use find:

```<code>fil=$(find / -name "*.temp_process.txt" -ctime 0)
echo "test" | mailx -s test -a $fil someone@someserver.com
</code>```

ctime 0 will only search for files created with in the last 24 hours

The results can then be used to action an email

Body:
Use find:

fil=$(find / -name "*.temp_process.txt" -ctime 0)
echo "test" | mailx -s test -a $fil someone@someserver.com

ctime 0 will only search for files created with in the last 24 hours

The results can then be used to action an email


问:
Parsing and grouping text in a string using Python
I need to parse a series of short strings that are comprised of 3 parts: a question and 2 possible answers. The string will follow a consistent format:

This is the question "answer_option_1 is in quotes" "answer_option_2 is in quotes"

I need to identify the question part and the two possible answer choices that are in single or double quotes.

Ex.:
What color is the sky today? "blue" or "grey"

Who will win the game 'Michigan' 'Ohio State'

How do I do this in python?

答:
Pyparsing will give you a solution that will adapt to some variability in the input text:

```<code>questions = """\
What color is the sky today? "blue" or "grey"
Who will win the game 'Michigan' 'Ohio State'""".splitlines()

from pyparsing import *

quotedString.setParseAction(removeQuotes)
q_and_a = SkipTo(quotedString)("Q") + delimitedList(quotedString, Optional("or"))("A")

for qn in questions:
    print qn
    qa = q_and_a.parseString(qn)
    print "qa.Q", qa.Q
    print "qa.A", qa.A
    print
</code>```

Will print:

```<code>What color is the sky today? "blue" or "grey"
qa.Q What color is the sky today?
qa.A ['blue', 'grey']

Who will win the game 'Michigan' 'Ohio State'
qa.Q Who will win the game
qa.A ['Michigan', 'Ohio State']
</code>```

Body:
Pyparsing will give you a solution that will adapt to some variability in the input text:

questions = """\
What color is the sky today? "blue" or "grey"
Who will win the game 'Michigan' 'Ohio State'""".splitlines()

from pyparsing import *

quotedString.setParseAction(removeQuotes)
q_and_a = SkipTo(quotedString)("Q") + delimitedList(quotedString, Optional("or"))("A")

for qn in questions:
    print qn
    qa = q_and_a.parseString(qn)
    print "qa.Q", qa.Q
    print "qa.A", qa.A
    print

Will print:

What color is the sky today? "blue" or "grey"
qa.Q What color is the sky today?
qa.A ['blue', 'grey']

Who will win the game 'Michigan' 'Ohio State'
qa.Q Who will win the game
qa.A ['Michigan', 'Ohio State']


问:
Issue with creating shaped div at 100% width
I am trying to create diagonal div, at the bottom of another div. It should look like this: http://storage8.static.itmages.com/i/17/0706/h_1499339517_4995911_421bf6ae42.png.

I have problem when I adding 100vw value to my border-left, because horizontal scrollbar appears on my website. I also tried use Jquery to find the width of the body. It works but when I resize my browser, border width does not change. Any suggestions how to fix it?

     var actualInnerWidth = $(".background-gradient").prop("clientWidth");
$('.background-gradient').css({
   'border-top':'50px solid red',
   'border-left': actualInnerWidth + 'px solid transparent'
}); ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    .banner {
   min-height: 50vh;
   margin: 0;
   padding:0;
   background-color: red;
 }
.background-gradient {
   width:100%;
   height:50px;
   background-color:yellow;
 }</code>```

```

Here is jsfiddle: https://jsfiddle.net/b49mmm9a/1/

答:
Here is simple JS/jQuery Code.

```<code>function setBorder(){
      var actualInnerWidth = $(".background-gradient").prop("clientWidth");
      $('.background-gradient').css({
        'border-top':'50px solid red',
        'border-left': actualInnerWidth + 'px solid transparent'
            });
        }

$(document).ready(function(){
    setBorder();
});

      $(window).resize( function(){
        setBorder();
      });
</code>```

check codepen here https://codepen.io/sajiddesigner/pen/PjBRxQ

Body:
I am trying to create diagonal div, at the bottom of another div. It should look like this: http://storage8.static.itmages.com/i/17/0706/h_1499339517_4995911_421bf6ae42.png.

I have problem when I adding 100vw value to my border-left, because horizontal scrollbar appears on my website. I also tried use Jquery to find the width of the body. It works but when I resize my browser, border width does not change. Any suggestions how to fix it?

     var actualInnerWidth = $(".background-gradient").prop("clientWidth");
$('.background-gradient').css({
   'border-top':'50px solid red',
   'border-left': actualInnerWidth + 'px solid transparent'
});

    .banner {
   min-height: 50vh;
   margin: 0;
   padding:0;
   background-color: red;
 }
.background-gradient {
   width:100%;
   height:50px;
   background-color:yellow;
 }

Here is jsfiddle: https://jsfiddle.net/b49mmm9a/1/

Body:
Here is simple JS/jQuery Code.

function setBorder(){
      var actualInnerWidth = $(".background-gradient").prop("clientWidth");
      $('.background-gradient').css({
        'border-top':'50px solid red',
        'border-left': actualInnerWidth + 'px solid transparent'
            });
        }

$(document).ready(function(){
    setBorder();
});

      $(window).resize( function(){
        setBorder();
      });

check codepen here https://codepen.io/sajiddesigner/pen/PjBRxQ


问:
i have 5 worksheets in my excel workbook but i want to specifically protect 3rd and 5th worksheets with password
I have 5 worksheets in my excel workbook but I want specifically protect 3rd and 5th worksheets with password. Have below macro which protects only one sheet. what needs to be added to protect more than one sheet but not all sheets.  Kindly guide me.

Thanks in Advance!!

```<code>      Private Sub Workbook_SheetActivate(ByVal Sh As Object)
      Dim MySheets As String, Response As String
      MySheet = "Sheet1"
      If ActiveSheet.Name = MySheet Then
      ActiveSheet.Visible = False
            Response = InputBox("Enter password to view sheet")
             If Response = "pass" Then
             Sheets(MySheet).Visible = True
             Application.EnableEvents = False
             Sheets(MySheet).Select
              Application.EnableEvents = True
              End If
       End If
       Sheets(MySheet).Visible = True
 End Sub
</code>```

答:
Try this: </p>

```<code>Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySheets As String, Response As String
MySheet = ActiveSheet.Name
Select Case MySheet
Case "Sheet1", "Sheet3", "Sheet5"
ActiveSheet.Visible = False
     Response = InputBox("Enter password to view sheet")
      If Response = "pass" Then
        Sheets(MySheet).Visible = True
        Application.EnableEvents = False
        Sheets(MySheet).Select
        Application.EnableEvents = True
      End If
End Select
Sheets(MySheet).Visible = True
End Sub
</code>```

<p>But hardcoding the password doesnt make it that safe. </p>

Body:
I have 5 worksheets in my excel workbook but I want specifically protect 3rd and 5th worksheets with password. Have below macro which protects only one sheet. what needs to be added to protect more than one sheet but not all sheets.  Kindly guide me.

Thanks in Advance!!

      Private Sub Workbook_SheetActivate(ByVal Sh As Object)
      Dim MySheets As String, Response As String
      MySheet = "Sheet1"
      If ActiveSheet.Name = MySheet Then
      ActiveSheet.Visible = False
            Response = InputBox("Enter password to view sheet")
             If Response = "pass" Then
             Sheets(MySheet).Visible = True
             Application.EnableEvents = False
             Sheets(MySheet).Select
              Application.EnableEvents = True
              End If
       End If
       Sheets(MySheet).Visible = True
 End Sub

Body:
Try this:

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySheets As String, Response As String
MySheet = ActiveSheet.Name
Select Case MySheet
Case "Sheet1", "Sheet3", "Sheet5"
ActiveSheet.Visible = False
     Response = InputBox("Enter password to view sheet")
      If Response = "pass" Then
        Sheets(MySheet).Visible = True
        Application.EnableEvents = False
        Sheets(MySheet).Select
        Application.EnableEvents = True
      End If
End Select
Sheets(MySheet).Visible = True
End Sub

But hardcoding the password doesnt make it that safe.


问:
How come php in include executed first?
How come php in include is executed before html? Because user input is from html.  Shouldn't included script be at last? </p>

```<code><?php
include('login.php'); // Includes Login Script

if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
</code>```

答:
PHP is a server-side language, whereas HTML is client-side. This means the PHP code gets executed on the web server before then being passed to the client's browser.

See this question for details on the differences between client-side and server-side programming.

Title: How come php in include executed first?

Body:
How come php in include is executed before html? Because user input is from html.  Shouldn't included script be at last?

<?php
include('login.php'); // Includes Login Script

if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<!DOCTYPE html>

<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">

PHP Login Session Example

Login Form

<form action="" method="post">
UserName :
<input id="name" name="username" placeholder="username" type="text">
Password :
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<?php echo $error; ?>
</form>


问:
Interesting Applications of Interfaces
Why are interfaces useful?

Actually, I have a [small] idea of why interfaces are useful/necessary but...

What are [interesting or realistic] applications of interfaces?

答:
I assume you mean "interface" in the programming language sense rather than in the other senses, e.g. "User Interface".

An interface in languages like Java or C# serves two purposes. The first is to provide a contract for a type to implement; a suite of method names and signatures that the type provides to other types that use it. The second is to provide polymorphism upon that interface for the type. For example, if I have a type that implements the IFoo interface, I can pass an instance of that type to another class where the other class needs only know about the IFoo interface rather than every detail of my class that implements IFoo.

OwnerDisplayName: koldfyre

Title: Interesting Applications of Interfaces

OwnerDisplayName: Randolpho


问:
Insert space between arguments to concat function
When I concat($name, $surname), is there a way of putting a space in between the $name $surname using my sql not php so when i get the result it formats a little cleaner?

答:
Just add a space in there.

```<code>SELECT CONCAT(name,' ',surname) AS full_name FROM table;
</code>```

EDIT oops, bad spelling there... ;p

Body:
Just add a space in there.

SELECT CONCAT(name,' ',surname) AS full_name FROM table;

EDIT oops, bad spelling there... ;p


问:
Save/Pass/GET event after page reload
I try to open a cordova-app with custom-url-scheme.

When i use it after triggering an event i works fine like this:

```<code><input id="myInput" onkeydown="checkKey(event);"/>

function checkKey(event) {
    if (event.which == 13 || event.keyCode == 13) {
        window.open('blablabla'); // call the App
    }
};
</code>```

Unfortunately in my case by pressing the Enter-key, the value has to be checked by a backend system, wich then reloads the page.

So i tried this:

```<code>document.addEventListener('DOMContentLoaded', function() {
   window.open('blablabla'); // call the App
}, false);
</code>```

The problem here is that have no active event, so chrome makes a navigation.block an the App cannot be opened.

Is there a way not to lose the event by reloading the page?

答:
Why not:

prevent the default behavior on press enter

send the value via ajax

get the response

open the app

List item

Conclusion:

Problem solved

no need for page reload

faster end result

Title: Save/Pass/GET event after page reload

Body:
I try to open a cordova-app with custom-url-scheme.

When i use it after triggering an event i works fine like this:

<input id="myInput" onkeydown="checkKey(event);"/>

function checkKey(event) {
    if (event.which == 13 || event.keyCode == 13) {
        window.open('blablabla'); // call the App
    }
};

Unfortunately in my case by pressing the Enter-key, the value has to be checked by a backend system, wich then reloads the page.

So i tried this:

document.addEventListener('DOMContentLoaded', function() {
   window.open('blablabla'); // call the App
}, false);

The problem here is that have no active event, so chrome makes a navigation.block an the App cannot be opened.

Is there a way not to lose the event by reloading the page?


问:
Reference to variable
I'm kind of confused about references in C++. Could anyone explain me this :

```<code>    class Dog
    {
        public:
            Dog( void ) {
                age = 3;
                name = "dummy";
            }

            void setAge( const int & a ) {
                age = a;
            }

         string & getName( void ) {
                return name;
            }

            void print( void ) {
                cout << name << endl;
            }

        private:
            int age;
            string name;

    };

int main( void ) {
    Dog d;
    string & name = d.getName(); // this works and I return reference, so the address of name will be the same as address of name in Dog class.

  int a = 5;
  int & b = a; // why this works? by the logic from before this should not work but the code below should.
  int & c = &a // why this does not work but the code above works?
}
</code>```

Also when i remove & and make the function like this string getName the code won't work.

答:
In case

```<code> int & b = a;
</code>```

b is reference to a and memory allocated for data of type int is available by both names a and b.

In case

```<code> int & c = &a;
</code>```

you are trying to save address of memory allocated for a - result of unary & - to int & c ... this lead to error.

In case of method

```<code> string & getName( void )
</code>```

reference to string is returned, so string & name (variable in main) will provide access to memory of private class member string name;

Title: Reference to variable

Body:
I'm kind of confused about references in C++. Could anyone explain me this :

    class Dog
    {
        public:
            Dog( void ) {
                age = 3;
                name = "dummy";
            }

            void setAge( const int & a ) {
                age = a;
            }

         string & getName( void ) {
                return name;
            }

            void print( void ) {
                cout << name << endl;
            }

        private:
            int age;
            string name;

    };

int main( void ) {
    Dog d;
    string & name = d.getName(); // this works and I return reference, so the address of name will be the same as address of name in Dog class.

  int a = 5;
  int & b = a; // why this works? by the logic from before this should not work but the code below should.
  int & c = &a // why this does not work but the code above works?
}

Also when i remove & and make the function like this string getName the code won't work.

Body:
In case

 int & b = a;

b is reference to a and memory allocated for data of type int is available by both names a and b.

In case

 int & c = &a;

you are trying to save address of memory allocated for a - result of unary & - to int & c ... this lead to error.

In case of method

 string & getName( void )

reference to string is returned, so string & name (variable in main) will provide access to memory of private class member string name;


问:
Why city name missing for some locations from Google Maps API result?
When I enter the location details in the google API developer page, the city name is missing from the results.

The Location details are "Canarsie, Brooklyn, NY, United States".

I entered the details in the form appearing in the following link.

https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

But city name is missing from it. This doesn't happen for all the locations. It only happens for some locations. Please help me to find a solution.

答:
Address component type for "city" varies across regions, specially in New York.

For more details, see paragraph right under the form, in https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform


问:
PAC Fetch failed with error [NSURLErrorDomain:-1003]
I see this error in my logs and I don't know what it means:

```<code>PAC Fetch failed with error [NSURLErrorDomain:-1003]
2017-06-08 17:07:56.157874+0200 xxxxxx[27059:7093559] [] nw_proxy_resolver_create_parsed_array PAC evaluation error: NSURLErrorDomain: -1003
</code>```

At the same time I have a problem with a collectionView in my app. Don't know if it's related to the error or not:

Sometimes, and only if the app is used in one remote office of our Company, both with the simulator and a real device, a collectionView that simply receives an images array and show them on the screen, just stops working.

It's not like it didn't just load the images, it seems like the entire collectionView doesn't show up.

I'm testing the same app with simulators and devices in another office (another city) and it NEVER happened to me. Other that that "PAC" error, I only see some auto layout constraint problems, but I see the same errors in my logs and it still works perfectly.

The persons that are testing the app on the remote location say that they have to remove and reinstall the app to make it work again.

Any clue?

答:
Had a similar problem fixed it by this method. Hope this helps.
The simulator uses your computers network connection, so I recommend checking the System Preferences > Network > Advanced > Proxies > Automatic Proxy Configuration : You must disable Auto Proxy Discovery.</p>

Body:
I see this error in my logs and I don't know what it means:

PAC Fetch failed with error [NSURLErrorDomain:-1003]
2017-06-08 17:07:56.157874+0200 xxxxxx[27059:7093559] [] nw_proxy_resolver_create_parsed_array PAC evaluation error: NSURLErrorDomain: -1003

At the same time I have a problem with a collectionView in my app. Don't know if it's related to the error or not:

Sometimes, and only if the app is used in one remote office of our Company, both with the simulator and a real device, a collectionView that simply receives an images array and show them on the screen, just stops working.

It's not like it didn't just load the images, it seems like the entire collectionView doesn't show up.

I'm testing the same app with simulators and devices in another office (another city) and it NEVER happened to me. Other that that "PAC" error, I only see some auto layout constraint problems, but I see the same errors in my logs and it still works perfectly.

The persons that are testing the app on the remote location say that they have to remove and reinstall the app to make it work again.

Any clue?


答: PHP process your request in the server and return you a html file (in this case). That is, you make a request with all informations that you need and it returns you a processed information.</p>

Title: How come php in include executed first?