问:
getting a nullpointerexception in the signed apk with unknown source
I am getting this exception opening a Fragment in the MainActivity only in the signed apk and not in the debug version.

FATAL EXCEPTION: main

Process: com.curieo.podcast, PID: 15376
  Theme: themes:{}
  java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
                                                                          at com.curieo.podcast.ui.c.c.f(Unknown Source)
                                                                          at com.curieo.podcast.ui.c.c.a(Unknown Source)
                                                                          at com.curieo.podcast.e.a.a(Unknown Source)
                                                                          at com.curieo.podcast.e.a.onPostExecute(Unknown Source)
                                                                          at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                          at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                          at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:148)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5461)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

This is the fragment which throws the error

```<code>public class DiscoverFragment extends BaseFragment implements DownloadFeedUrlsFromServerTask.DownloadFeedUrlsFromServerTaskInterface, LoaderManager.LoaderCallbacks<Cursor> {

    ExpandableHeightGridView featuredListView;

    TwoWayGridView popularListView, trendingListView;
    private ServerFeed[] feeds;
    ArrayList<ServerFeed> popularList, featuredList, trendingList;
    AVLoadingIndicatorView progress;

    public DiscoverFragment() {
        // Required empty public constructor
    }

    private BroadcastReceiver podcastAddedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            progress.setVisibility(View.GONE);
            progress.smoothToHide();
            popularListView.setAlpha(1);
            featuredListView.setAlpha(1);
            trendingListView.setAlpha(1);
            popularListView.setClickable(true);
            featuredListView.setClickable(true);
            trendingListView.setClickable(true);
            switch (intent.getAction()) {
                case BroadcastHelper.INTENT_PODCAST_PROCESSED:
                    if (intent.getBooleanExtra(BroadcastHelper.EXTRA_SUCCESS, false)) {
                        Channel channel = Parcels.unwrap(intent.getParcelableExtra(BroadcastHelper.EXTRA_CHANNEL));
                        ChannelProfileActivity.openChannelProfile((BaseActivity) getActivity(),
                                channel, null, false);
                    }
                    break;
            }
        }
    };

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_discover;
    }

    @Override
    protected int getFragmentTitleResourceId() {
        return R.string.title_fragment_discover;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_discover, container, false);

        initUI(root);
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        BroadcastHelper.registerReceiver(getActivity(), podcastAddedReceiver,
                BroadcastHelper.INTENT_PODCAST_PROCESSED, BroadcastHelper.INTENT_OPML_PROCESS_FINISH);
    }

    @Override
    public void onPause() {
        super.onPause();
        BroadcastHelper.unregisterReceiver(getActivity(), podcastAddedReceiver);
    }

    @Override
    public void processRequestResponse(String response) {
        if (response != null && !response.isEmpty()) {
            Gson gson = new Gson();
            this.feeds = gson.fromJson(response, ServerFeed[].class);
            this.populateItems();
        }
    }

    private void populateItems() {

        for (int i = 0; i < this.feeds.length; i++) {
            if (this.feeds[i].getWeight() < 100) {
                Log.e("", "populateItems: " + this.feeds[i].getWeight());
                popularList.add(this.feeds[i]);

            } else if (this.feeds[i].getWeight() > 100 && this.feeds[i].getWeight() < 200) {
                Log.e("", "populateItems " + this.feeds[i].getWeight());

                featuredList.add(this.feeds[i]);

            } else if (this.feeds[i].getWeight() > 200) {
                Log.e("", "populateItems " + this.feeds[i].getWeight());

                trendingList.add(this.feeds[i]);
            }
        }

        CustomFeaturedDiscoverAdapter adapter = new CustomFeaturedDiscoverAdapter(getActivity(), R.layout.featured_discover_list_item, popularList);
        CustomFeaturedDiscoverAdapter adapter1 = new CustomFeaturedDiscoverAdapter(getActivity(), R.layout.featured_discover_list_item, featuredList);
        CustomFeaturedDiscoverAdapter adapter2 = new CustomFeaturedDiscoverAdapter(getActivity(), R.layout.featured_discover_list_item, trendingList);
        featuredListView.setAdapter(adapter1);
        popularListView.setAdapter(adapter);
        trendingListView.setAdapter(adapter2);
        popularListView.setOnItemClickListener((parent, view, position, id) -> {
            podcastOnCLick(popularList, position);

        });

        featuredListView.setOnItemClickListener((adapterView, view, i, l) -> {
            podcastOnCLick(featuredList, i);
        });

        trendingListView.setOnItemClickListener((parent, view, position, id) -> {
            podcastOnCLick(trendingList, position);

        });
    }

    private void podcastOnCLick(ArrayList<ServerFeed> featuredList, int i) {

        PodcastSyncService.addPodcastFromUrl(getActivity(), featuredList.get(i).getFeed_link());
        progress.setVisibility(View.VISIBLE);
        progress.smoothToShow();
        featuredListView.setAlpha((float) 0.40);
        popularListView.setAlpha((float) 0.40);
        trendingListView.setAlpha((float) 0.40);
        Toast.makeText(getActivity(), "Please wait, while the podcast loads.", Toast.LENGTH_LONG).show();
        featuredListView.setClickable(false);
        popularListView.setClickable(false);
        trendingListView.setClickable(false);
    }

    private void initUI(View view) {
        progress = (AVLoadingIndicatorView) view.findViewById(R.id.progress_bar_discover_screen);
        popularListView = (TwoWayGridView) view.findViewById(R.id.listview_discover);
        featuredListView = (ExpandableHeightGridView) view.findViewById(R.id.listview_featured);
        trendingListView = (TwoWayGridView) view.findViewById(R.id.listview_trending);
        popularList = new ArrayList<>();
        featuredList = new ArrayList<>();
        trendingList = new ArrayList<>();

        if (this.feeds == null) {
            DownloadFeedUrlsFromServerTask downloadFeedUrlsFromServerTask = new DownloadFeedUrlsFromServerTask();
            downloadFeedUrlsFromServerTask.downloadFeedUrlsFromServerTaskInterface = this;
            downloadFeedUrlsFromServerTask.execute();
        }
    }

    public static DiscoverFragment newInstance(Bundle args) {
        DiscoverFragment fragment = new DiscoverFragment();

        if (args != null) {
            fragment.setArguments(args);
        }

        return fragment;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }
}
</code>```

答:
Some services (like firebase login, push notification) require you to generate SHA certificate fingerprint; that's how such Services identify your app, so you would be able to use their services.
Debug and Release variants each generate different fingerprints. Therefor for that particular Service, your app in Debug mode is a different app from the release mode, so if your async task is requesting data, and it's not authorized, then it's returning null, and you didn't handle null values, so the crash happens.
Either way, you should handle null values: if... else, or at least a try catch thing.
Cheers,

Body:
I am getting this exception opening a Fragment in the MainActivity only in the signed apk and not in the debug version.

FATAL EXCEPTION: main

Process: com.curieo.podcast, PID: 15376
  Theme: themes:{}
  java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
                                                                          at com.curieo.podcast.ui.c.c.f(Unknown Source)
                                                                          at com.curieo.podcast.ui.c.c.a(Unknown Source)
                                                                          at com.curieo.podcast.e.a.a(Unknown Source)
                                                                          at com.curieo.podcast.e.a.onPostExecute(Unknown Source)
                                                                          at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                          at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                          at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:148)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5461)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

This is the fragment which throws the error

public class DiscoverFragment extends BaseFragment implements DownloadFeedUrlsFromServerTask.DownloadFeedUrlsFromServerTaskInterface, LoaderManager.LoaderCallbacks<Cursor> {

    ExpandableHeightGridView featuredListView;

    TwoWayGridView popularListView, trendingListView;
    private ServerFeed[] feeds;
    ArrayList<ServerFeed> popularList, featuredList, trendingList;
    AVLoadingIndicatorView progress;

    public DiscoverFragment() {
        // Required empty public constructor
    }

    private BroadcastReceiver podcastAddedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            progress.setVisibility(View.GONE);
            progress.smoothToHide();
            popularListView.setAlpha(1);
            featuredListView.setAlpha(1);
            trendingListView.setAlpha(1);
            popularListView.setClickable(true);
            featuredListView.setClickable(true);
            trendingListView.setClickable(true);
            switch (intent.getAction()) {
                case BroadcastHelper.INTENT_PODCAST_PROCESSED:
                    if (intent.getBooleanExtra(BroadcastHelper.EXTRA_SUCCESS, false)) {
                        Channel channel = Parcels.unwrap(intent.getParcelableExtra(BroadcastHelper.EXTRA_CHANNEL));
                        ChannelProfileActivity.openChannelProfile((BaseActivity) getActivity(),
                                channel, null, false);
                    }
                    break;
            }
        }
    };

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_discover;
    }

    @Override
    protected int getFragmentTitleResourceId() {
        return R.string.title_fragment_discover;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_discover, container, false);

        initUI(root);
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        BroadcastHelper.registerReceiver(getActivity(), podcastAddedReceiver,
                BroadcastHelper.INTENT_PODCAST_PROCESSED, BroadcastHelper.INTENT_OPML_PROCESS_FINISH);
    }

    @Override
    public void onPause() {
        super.onPause();
        BroadcastHelper.unregisterReceiver(getActivity(), podcastAddedReceiver);
    }

    @Override
    public void processRequestResponse(String response) {
        if (response != null && !response.isEmpty()) {
            Gson gson = new Gson();
            this.feeds = gson.fromJson(response, ServerFeed[].class);
            this.populateItems();
        }
    }

    private void populateItems() {

        for (int i = 0; i < this.feeds.length; i++) {
            if (this.feeds[i].getWeight() < 100) {
                Log.e("", "populateItems: " + this.feeds[i].getWeight());
                popularList.add(this.feeds[i]);

            } else if (this.feeds[i].getWeight() > 100 && this.feeds[i].getWeight() < 200) {
                Log.e("", "populateItems " + this.feeds[i].getWeight());

                featuredList.add(this.feeds[i]);

            } else if (this.feeds[i].getWeight() > 200) {
                Log.e("", "populateItems " + this.feeds[i].getWeight());

                trendingList.add(this.feeds[i]);
            }
        }

        CustomFeaturedDiscoverAdapter adapter = new CustomFeaturedDiscoverAdapter(getActivity(), R.layout.featured_discover_list_item, popularList);
        CustomFeaturedDiscoverAdapter adapter1 = new CustomFeaturedDiscoverAdapter(getActivity(), R.layout.featured_discover_list_item, featuredList);
        CustomFeaturedDiscoverAdapter adapter2 = new CustomFeaturedDiscoverAdapter(getActivity(), R.layout.featured_discover_list_item, trendingList);
        featuredListView.setAdapter(adapter1);
        popularListView.setAdapter(adapter);
        trendingListView.setAdapter(adapter2);
        popularListView.setOnItemClickListener((parent, view, position, id) -> {
            podcastOnCLick(popularList, position);

        });

        featuredListView.setOnItemClickListener((adapterView, view, i, l) -> {
            podcastOnCLick(featuredList, i);
        });

        trendingListView.setOnItemClickListener((parent, view, position, id) -> {
            podcastOnCLick(trendingList, position);

        });
    }

    private void podcastOnCLick(ArrayList<ServerFeed> featuredList, int i) {

        PodcastSyncService.addPodcastFromUrl(getActivity(), featuredList.get(i).getFeed_link());
        progress.setVisibility(View.VISIBLE);
        progress.smoothToShow();
        featuredListView.setAlpha((float) 0.40);
        popularListView.setAlpha((float) 0.40);
        trendingListView.setAlpha((float) 0.40);
        Toast.makeText(getActivity(), "Please wait, while the podcast loads.", Toast.LENGTH_LONG).show();
        featuredListView.setClickable(false);
        popularListView.setClickable(false);
        trendingListView.setClickable(false);
    }

    private void initUI(View view) {
        progress = (AVLoadingIndicatorView) view.findViewById(R.id.progress_bar_discover_screen);
        popularListView = (TwoWayGridView) view.findViewById(R.id.listview_discover);
        featuredListView = (ExpandableHeightGridView) view.findViewById(R.id.listview_featured);
        trendingListView = (TwoWayGridView) view.findViewById(R.id.listview_trending);
        popularList = new ArrayList<>();
        featuredList = new ArrayList<>();
        trendingList = new ArrayList<>();

        if (this.feeds == null) {
            DownloadFeedUrlsFromServerTask downloadFeedUrlsFromServerTask = new DownloadFeedUrlsFromServerTask();
            downloadFeedUrlsFromServerTask.downloadFeedUrlsFromServerTaskInterface = this;
            downloadFeedUrlsFromServerTask.execute();
        }
    }

    public static DiscoverFragment newInstance(Bundle args) {
        DiscoverFragment fragment = new DiscoverFragment();

        if (args != null) {
            fragment.setArguments(args);
        }

        return fragment;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }
}


来源: stackexchange

问:
Unwanted request generated with LINQ to Entities
In order to optimize a method, I look at each line of my code as well as each generated request in order to eliminate a maximum of them. I have serious doubts about the following part:

A planning contains several projects. A project contains several activities. I first load all activities for future needs. This generates, as expected, a "SELECT WHERE IN" request on the Activities table

```<code>var planningProjectIds = p.PlanningProjects.Select(x => x.PlanningProjectId).ToList();
var planningActivities = _db.PlanningActivities.Where(x => planningProjectIds.Contains(x.PlanningProjectId));
var planningActivitiesArr = planningActivities.ToLookup(x => x.PlanningProjectId);
</code>```

Here is a first attempt. The following code generates an unwanted request (between log lines 9b and 10)

```<code>foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
    sw.WriteLine("9");
    pp.PlanningActivities = planningActivitiesArr[pp.PlanningProjectId].ToList();
    sw.WriteLine("9b");
    pp.PlanningActivities = pp.PlanningActivities.OrderBy(x => x.Position).ThenBy(x => x.PlanningActivityId).ToList();
    sw.WriteLine("10");
    // ...
}
</code>```

Here is a second attempt. This code does not generate a query

```<code>foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
    sw.WriteLine("9");
    pp.PlanningActivities = planningActivitiesArr[pp.PlanningProjectId]
        .OrderBy(x => x.Position)
        .ThenBy(x => x.PlanningActivityId)
        .ToList();
    sw.WriteLine("10");
    // ...
}
</code>```

Could you tell me the reason for that? Thank you in advance ;)

Here is an extract of the log where we can see the extra request

```<code>9b
Opened connection at 06/07/2017 10:22:15 +02:00

SELECT
    [Extent1].[PlanningActivityId] AS [PlanningActivityId],
    [Extent1].[FriendlyName] AS [FriendlyName],
    [Extent1].[PlanningProjectId] AS [PlanningProjectId],
    [Extent1].[ActivityId] AS [ActivityId],
    [Extent1].[ScheduleID] AS [ScheduleID],
    [Extent1].[Position] AS [Position]
    FROM [dbo].[PlanningActivities] AS [Extent1]
    WHERE [Extent1].[PlanningProjectId] = @EntityKeyValue1

-- EntityKeyValue1: '847' (Type = Int32, IsNullable = false)

-- Executing at 06/07/2017 10:22:15 +02:00

-- Completed in 7 ms with result: SqlDataReader

Closed connection at 06/07/2017 10:22:15 +02:00

10
</code>```

Do not hesitate to tell me if I could forget valuable details to solve this small problem :)

答:
When you enumerate p.PlanningProjects you are only getting the PlanningProject entity as local variable pp.

It does not populate any navigation properties at this point.

```<code>foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
}
</code>```

Once you call the property getter to fill PlanningActivities for the PlanningProject between "9b" and "10" the database is queried for those planning activities:

```<code>sw.WriteLine("9b");
pp.PlanningActivities = pp.PlanningActivities.OrderBy(x => x.Position).ThenBy(x => x.PlanningActivityId).ToList();
sw.WriteLine("10");
</code>```

Hence the query:

```<code>SELECT ....
FROM [dbo].[PlanningActivities] where [PlanningProjectId] = @EntityKeyValue1
</code>```

With @EntityKeyValue1 being the PlanningProject.PlanningProjectId of your pp variable.

If you don't want the extract queries, use include to load all of the data at once.

ContentLicense: CC BY-SA 3.0

Body:
In order to optimize a method, I look at each line of my code as well as each generated request in order to eliminate a maximum of them. I have serious doubts about the following part:

A planning contains several projects. A project contains several activities. I first load all activities for future needs. This generates, as expected, a "SELECT WHERE IN" request on the Activities table

var planningProjectIds = p.PlanningProjects.Select(x => x.PlanningProjectId).ToList();
var planningActivities = _db.PlanningActivities.Where(x => planningProjectIds.Contains(x.PlanningProjectId));
var planningActivitiesArr = planningActivities.ToLookup(x => x.PlanningProjectId);

Here is a first attempt. The following code generates an unwanted request (between log lines 9b and 10)

foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
    sw.WriteLine("9");
    pp.PlanningActivities = planningActivitiesArr[pp.PlanningProjectId].ToList();
    sw.WriteLine("9b");
    pp.PlanningActivities = pp.PlanningActivities.OrderBy(x => x.Position).ThenBy(x => x.PlanningActivityId).ToList();
    sw.WriteLine("10");
    // ...
}

Here is a second attempt. This code does not generate a query

foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
    sw.WriteLine("9");
    pp.PlanningActivities = planningActivitiesArr[pp.PlanningProjectId]
        .OrderBy(x => x.Position)
        .ThenBy(x => x.PlanningActivityId)
        .ToList();
    sw.WriteLine("10");
    // ...
}

Could you tell me the reason for that? Thank you in advance ;)

Here is an extract of the log where we can see the extra request

9b
Opened connection at 06/07/2017 10:22:15 +02:00

SELECT
    [Extent1].[PlanningActivityId] AS [PlanningActivityId],
    [Extent1].[FriendlyName] AS [FriendlyName],
    [Extent1].[PlanningProjectId] AS [PlanningProjectId],
    [Extent1].[ActivityId] AS [ActivityId],
    [Extent1].[ScheduleID] AS [ScheduleID],
    [Extent1].[Position] AS [Position]
    FROM [dbo].[PlanningActivities] AS [Extent1]
    WHERE [Extent1].[PlanningProjectId] = @EntityKeyValue1

-- EntityKeyValue1: '847' (Type = Int32, IsNullable = false)

-- Executing at 06/07/2017 10:22:15 +02:00

-- Completed in 7 ms with result: SqlDataReader

Closed connection at 06/07/2017 10:22:15 +02:00

10

Do not hesitate to tell me if I could forget valuable details to solve this small problem :)

Body:
When you enumerate p.PlanningProjects you are only getting the PlanningProject entity as local variable pp.

It does not populate any navigation properties at this point.

foreach (PlanningProject pp in p.PlanningProjects)
{
    // ...
}

Once you call the property getter to fill PlanningActivities for the PlanningProject between "9b" and "10" the database is queried for those planning activities:

sw.WriteLine("9b");
pp.PlanningActivities = pp.PlanningActivities.OrderBy(x => x.Position).ThenBy(x => x.PlanningActivityId).ToList();
sw.WriteLine("10");

Hence the query:

SELECT ....
FROM [dbo].[PlanningActivities] where [PlanningProjectId] = @EntityKeyValue1

With @EntityKeyValue1 being the PlanningProject.PlanningProjectId of your pp variable.

If you don't want the extract queries, use include to load all of the data at once.


问:
How can iterate object value from json object in javascript
I tried to implement small google map. I have a json object that is : {"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"}}}  . How can i iterate lat and lng values. please help me.

```<code>{ "app_title":"whether",
  "users": {
     "iv001": {
             "lat":"17.85",
             "lng":"18.45"
       }
   }
 }
</code>```

var latitude = ???; //here we need lat value
var longitude = ???; //here we need lng value

答:
Use dot notation to access object value. data.users.iv001.lat; gives you lat.data.users.iv001.lng; gives you lng

var data ={"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"}}};

var lat = data.users.iv001.lat;
var lag =data.users.iv001.lng;
console.log("Lat:"+lat,"Lag:"+lag);```
</div>
</div>
</p>

<p>OR like this <code>data.users["iv001"].lat;</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data ={"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"}}};

var lat = data.users["iv001"].lat;
var lag =data.users["iv001"].lng;
console.log("Lat:"+lat,"Lag:"+lag);</code>```

Body:
I tried to implement small google map. I have a json object that is : {"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"}}}  . How can i iterate lat and lng values. please help me.

{ "app_title":"whether",
  "users": {
     "iv001": {
             "lat":"17.85",
             "lng":"18.45"
       }
   }
 }

var latitude = ???; //here we need lat value
var longitude = ???; //here we need lng value

Body:
Use dot notation to access object value. data.users.iv001.lat; gives you lat.data.users.iv001.lng; gives you lng

var data ={"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"}}};

var lat = data.users.iv001.lat;
var lag =data.users.iv001.lng;
console.log("Lat:"+lat,"Lag:"+lag);

OR like this data.users["iv001"].lat;

var data ={"app_title":"whether","users":{"iv001":{"lat":"17.85","lng":"18.45"}}};

var lat = data.users["iv001"].lat;
var lag =data.users["iv001"].lng;
console.log("Lat:"+lat,"Lag:"+lag);


问:
Ninject factory interface resolve missing constructor args from kernel
Trying to do this with Ninject's factory extensions.

```<code>void Main()
{
    IKernel kernel = new StandardKernel();
    kernel.Bind<C>().ToMethod(ctx => new C());
    kernel.Bind<IBFactory>().ToFactory();
    var a = kernel.Get<A>();
    a.Do();
}
public class A
{
    IBFactory _fact;

    public A(IBFactory factory)
    {
        _fact = factory;
    }

    public void Do()
    {
        _fact.Get("blah").Dump();
    }
}

public class B
{
    public B(C c, string s)
    {
    }
}

public interface IBFactory
{
    B Get(string s);
}

public class C
{
}
</code>```

The factory interface fails because it does not have a C to throw into the B() constructor. However it knows how to make a C from the kernel, but looking it up is beyond the scope of the default factory method implementation.

I can make a custom IInstanceProvider and pass that into the factory method e.g ToFactory(() => new myCustomIIProvider()) which resolves the C from the kernel, but it seems like a lot of work.

Is there an easier way to get Ninject to self resolve the missing ctor arg ?

答:
Actually, the problem isn't the binding for the C service, but the binding for B.

The default Factory instance provider will create named bindings for methods starting with Get (see here).

Either change your factory method to something other than Get or add this to create an empty named binding for B:

```<code>kernel.Bind<B>().ToSelf().Named("");
</code>```

Body:
Trying to do this with Ninject's factory extensions.

void Main()
{
    IKernel kernel = new StandardKernel();
    kernel.Bind<C>().ToMethod(ctx => new C());
    kernel.Bind<IBFactory>().ToFactory();
    var a = kernel.Get();
    a.Do();
}
public class A
{
    IBFactory _fact;

    public A(IBFactory factory)
    {
        _fact = factory;
    }

    public void Do()
    {
        _fact.Get("blah").Dump();
    }
}

public class B
{
    public B(C c, string s)
    {
    }
}

public interface IBFactory
{
    B Get(string s);
}

public class C
{
}

The factory interface fails because it does not have a C to throw into the B() constructor. However it knows how to make a C from the kernel, but looking it up is beyond the scope of the default factory method implementation.

I can make a custom IInstanceProvider and pass that into the factory method e.g ToFactory(() => new myCustomIIProvider()) which resolves the C from the kernel, but it seems like a lot of work.

Is there an easier way to get Ninject to self resolve the missing ctor arg ?

Body:
Actually, the problem isn't the binding for the C service, but the binding for B.

The default Factory instance provider will create named bindings for methods starting with Get (see here).

Either change your factory method to something other than Get or add this to create an empty named binding for B:

kernel.Bind<B>().ToSelf().Named("");


问:
Capistrano looking for old Github repo after deploy.rb changed to new repo
Recently, a project I'm working on changed source repositories on Github.

The deploy.rb was updated to correctly point to the new github account, but when I run the cap staging deploy, it looks for the old repo.

```<code>cap staging deploy
      * executing `staging'
      * executing `deploy'
      * executing `deploy:updatify'
      * executing "cd /home/deploy/example/current; git fetch origin; git reset --hard origin/staging"
        servers: ["example.com"]
        Password:
        [example.com] executing command
     ** [out :: example.com] ERROR: oldusername/example.git doesn't exist. Did you enter it correctly?
     ** [out :: example.com] fatal: The remote end hung up unexpectedly
     ** [out :: example.com] HEAD is now at 7c92a69 adding changes
        command finished in 4148ms
        triggering after callbacks for `deploy:updatify'
      * executing `bundle:install'
      * executing "cd /home/deploy/example/current && bundle install --gemfile /home/deploy/example/current/Gemfile --path /home/deploy/example/shared/bundle --deployment --quiet --without development test"
        servers: ["example.com"]
        [example.com] executing command
        command finished in 7442ms
      * executing `deploy:restart'
      * executing "cd /home/deploy/example/current; [ -f tmp/pids/unicorn.pid ] && kill -USR2 `cat tmp/pids/unicorn.pid` || bundle exec unicorn_rails -c ./config/unicorn.rb -E staging -D"
        servers: ["example.com"]
        [example.com] executing command
        command finished in 94ms
</code>```

I tried to look for a cached-copy directory as mentioned here: Capistrano still trying to connect to my old repo but on my server, there is no cached-copy directory.

Where is it still referencing the old repository?

deploy.rb:

```<code> require 'bundler/capistrano'

 load 'config/deploy/nginx'
 load 'config/deploy/unicorn'
 load 'config/deploy/updatify'

 # Base Settings ############################################################

 set :user,          'deploy'
 set :application,   'example'
 set :use_sudo,      false
 set :scm,           :git
 set :repository,    'git@github.com:new_repo_user/example.git'
 set :deploy_to,     "/home/#{user}/#{application}"

 # Fake using releases to just use git
 set :current_release, current_path

 ssh_options[:paranoid] = false
 default_run_options[:pty] = true

 # Multistage ###############################################################    ###

 task :production do
   server 'exampleprod.com', :app, :web, :db, :primary => true
   set  :branch,      'origin/production'
   set  :environment, 'production'
   set  :environment_database, defer { production_database }
   set  :environment_dbhost,   defer { production_dbhost }
 end

 task :staging do
   server 'example.com', :app, :web, :db, :primary => true
   set :branch,      'origin/staging'
   set :environment, 'staging'
   set :environment_database, defer { environment_info["database"] }
   set :environment_dbhost,   defer { environment_info["host"] }
 end
</code>```

答:
I had a similar problem after changing repository group.
It turns out that removing repo directory from server repaired a problem with an old repo version reference.</p>

Body:
Recently, a project I'm working on changed source repositories on Github.

The deploy.rb was updated to correctly point to the new github account, but when I run the cap staging deploy, it looks for the old repo.

cap staging deploy
      * executing `staging'
      * executing `deploy'
      * executing `deploy:updatify'
      * executing "cd /home/deploy/example/current; git fetch origin; git reset --hard origin/staging"
        servers: ["example.com"]
        Password:
        [example.com] executing command
     ** [out :: example.com] ERROR: oldusername/example.git doesn't exist. Did you enter it correctly?
     ** [out :: example.com] fatal: The remote end hung up unexpectedly
     ** [out :: example.com] HEAD is now at 7c92a69 adding changes
        command finished in 4148ms
        triggering after callbacks for `deploy:updatify'
      * executing `bundle:install'
      * executing "cd /home/deploy/example/current && bundle install --gemfile /home/deploy/example/current/Gemfile --path /home/deploy/example/shared/bundle --deployment --quiet --without development test"
        servers: ["example.com"]
        [example.com] executing command
        command finished in 7442ms
      * executing `deploy:restart'
      * executing "cd /home/deploy/example/current; [ -f tmp/pids/unicorn.pid ] && kill -USR2 `cat tmp/pids/unicorn.pid` || bundle exec unicorn_rails -c ./config/unicorn.rb -E staging -D"
        servers: ["example.com"]
        [example.com] executing command
        command finished in 94ms

I tried to look for a cached-copy directory as mentioned here: Capistrano still trying to connect to my old repo but on my server, there is no cached-copy directory.

Where is it still referencing the old repository?

deploy.rb:

 require 'bundler/capistrano'

 load 'config/deploy/nginx'
 load 'config/deploy/unicorn'
 load 'config/deploy/updatify'

 # Base Settings ############################################################

 set :user,          'deploy'
 set :application,   'example'
 set :use_sudo,      false
 set :scm,           :git
 set :repository,    'git@github.com:new_repo_user/example.git'
 set :deploy_to,     "/home/#{user}/#{application}"

 # Fake using releases to just use git
 set :current_release, current_path

 ssh_options[:paranoid] = false
 default_run_options[:pty] = true

 # Multistage ###############################################################    ###

 task :production do
   server 'exampleprod.com', :app, :web, :db, :primary => true
   set  :branch,      'origin/production'
   set  :environment, 'production'
   set  :environment_database, defer { production_database }
   set  :environment_dbhost,   defer { production_dbhost }
 end

 task :staging do
   server 'example.com', :app, :web, :db, :primary => true
   set :branch,      'origin/staging'
   set :environment, 'staging'
   set :environment_database, defer { environment_info["database"] }
   set :environment_dbhost,   defer { environment_info["host"] }
 end


问:
Multiple aggregate functions in Java 8 Stream API
I have a class defined like

```<code>public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}
</code>```

I would like to perform the following SQL statement using Java 8 Stream API.

```<code>SELECT atDate, AVG(occupancy), AVG(efficiency)
FROM TimePeriodCalc
GROUP BY atDate
</code>```

I tried :

```<code>Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), ....
</code>```

What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so.

答:
Assuming that your TimePeriodCalc class has all the necessary getters, this should get you the list you want:

```<code>List<TimePeriodCalc> result = new ArrayList<>(
    list.stream()
    .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate,
        Collectors.collectingAndThen(Collectors.toList(), TimePeriodCalc::avgTimePeriodCalc)))
    .values()
);
</code>```

Where TimePeriodCalc.avgTimePeriodCalc is this method in the TimePeriodCalc class:

```<code>public static TimePeriodCalc avgTimePeriodCalc(List<TimePeriodCalc> list){
    return new TimePeriodCalc(
            list.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getOccupancy)),
            list.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getEfficiency)),
            list.get(0).getAtDate()
            );
}
</code>```

The above can be combined into this monstrosity:

```<code>List<TimePeriodCalc> result = new ArrayList<>(
    list.stream()
    .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate,
        Collectors.collectingAndThen(
            Collectors.toList(), a -> {
                return new TimePeriodCalc(
                        a.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getOccupancy)),
                        a.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getEfficiency)),
                        a.get(0).getAtDate()
                        );
            }
        )))
    .values());
</code>```

With input:

```<code>List<TimePeriodCalc> list = new ArrayList<>();
list.add(new TimePeriodCalc(10,10,"a"));
list.add(new TimePeriodCalc(10,10,"b"));
list.add(new TimePeriodCalc(10,10,"c"));
list.add(new TimePeriodCalc(5,5,"a"));
list.add(new TimePeriodCalc(0,0,"b"));
</code>```

This would give:

```<code>TimePeriodCalc [occupancy=7.5, efficiency=7.5, atDate=a]
TimePeriodCalc [occupancy=5.0, efficiency=5.0, atDate=b]
TimePeriodCalc [occupancy=10.0, efficiency=10.0, atDate=c]
</code>```

Body:
I have a class defined like

public class TimePeriodCalc {
    private double occupancy;
    private double efficiency;
    private String atDate;
}

I would like to perform the following SQL statement using Java 8 Stream API.

SELECT atDate, AVG(occupancy), AVG(efficiency)
FROM TimePeriodCalc
GROUP BY atDate

I tried :

Collection<TimePeriodCalc> collector = result.stream().collect(groupingBy(p -> p.getAtDate(), ....

What can be put into the code to select multiple attributes ? I'm thinking of using multiple Collectors but really don't know how to do so.

Body:
Assuming that your TimePeriodCalc class has all the necessary getters, this should get you the list you want:

List<TimePeriodCalc> result = new ArrayList<>(
    list.stream()
    .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate,
        Collectors.collectingAndThen(Collectors.toList(), TimePeriodCalc::avgTimePeriodCalc)))
    .values()
);

Where TimePeriodCalc.avgTimePeriodCalc is this method in the TimePeriodCalc class:

public static TimePeriodCalc avgTimePeriodCalc(List<TimePeriodCalc> list){
    return new TimePeriodCalc(
            list.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getOccupancy)),
            list.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getEfficiency)),
            list.get(0).getAtDate()
            );
}

The above can be combined into this monstrosity:

List<TimePeriodCalc> result = new ArrayList<>(
    list.stream()
    .collect(Collectors.groupingBy(TimePeriodCalc::getAtDate,
        Collectors.collectingAndThen(
            Collectors.toList(), a -> {
                return new TimePeriodCalc(
                        a.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getOccupancy)),
                        a.stream().collect(Collectors.averagingDouble(TimePeriodCalc::getEfficiency)),
                        a.get(0).getAtDate()
                        );
            }
        )))
    .values());

With input:

List<TimePeriodCalc> list = new ArrayList<>();
list.add(new TimePeriodCalc(10,10,"a"));
list.add(new TimePeriodCalc(10,10,"b"));
list.add(new TimePeriodCalc(10,10,"c"));
list.add(new TimePeriodCalc(5,5,"a"));
list.add(new TimePeriodCalc(0,0,"b"));

This would give:

TimePeriodCalc [occupancy=7.5, efficiency=7.5, atDate=a]
TimePeriodCalc [occupancy=5.0, efficiency=5.0, atDate=b]
TimePeriodCalc [occupancy=10.0, efficiency=10.0, atDate=c]


问:
Java/Hibernate Table does not exist error
I am facing this error for quite a while now. I have managed to find a work-around by mapping the entity in my HibernateUtil class. However, I would like to achieve this using hibernate.cfg.xml.

Error that I am getting:

```<code>Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1441)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:491)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3201)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2411)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at Main.main(Main.java:14)

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydatabase.personentity' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2490)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
... 18 more
</code>```

Hibernate Config:

```<code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- List of mapped classes -->
<mapping class="PersonEntity"/>

</session-factory>
</hibernate-configuration>
</code>```

Entity:

```<code>@Entity
public class PersonEntity
{
private int id;
private String name;

@Id
@Column(name = "ID")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
@Column(name = "Name")
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
}
</code>```

Hibernate Util:

```<code>public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
    Configuration configuration = new Configuration();
    configuration.configure();

    StandardServiceRegistry standardRegistry = new
    StandardServiceRegistryBuilder()
            .configure()
            .build();

    return configuration.buildSessionFactory(standardRegistry);
}
catch(Exception e) {
    throw new ExceptionInInitializerError(e);
}
}

public static Session getSession()
{
return sessionFactory.openSession();
}

public static void close()
{
sessionFactory.close();
}
}
</code>```

Main class which is meant to save some hardcoded values:

```<code>public class Main {
public static void main(String[] args) {
    PersonEntity personEntity = new PersonEntity();

    personEntity.setId(1);
    personEntity.setName("Cris");

    Session session = HibernateUtil.getSession();

    session.beginTransaction();
    session.save(personEntity);
    session.getTransaction().commit();

}

}
</code>```

I would be grateful if someone could help, in my opinion the problem lays in hibernate.cfg.xml, but that's just my guess.
Thanks in advance

答:
Try changing <property name="hbm2ddl.auto"> to <property name="hibernate.hbm2ddl.auto"> (document says so)

You should change your Sql Dialect, too. For MySQL 5.x, you should use org.hibernate.dialect.MySQL5InnoDBDialect if you are using InnoDB tables or org.hibernate.dialect.MySQL5Dialect if you're not.

Refer to Session Configuration document.

Body:
I am facing this error for quite a while now. I have managed to find a work-around by mapping the entity in my HibernateUtil class. However, I would like to achieve this using hibernate.cfg.xml.

Error that I am getting:

Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1441)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:491)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3201)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2411)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at Main.main(Main.java:14)

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydatabase.personentity' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2490)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:205)
... 18 more

Hibernate Config:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping class="PersonEntity"/>

</session-factory>
</hibernate-configuration>

Entity:

@Entity
public class PersonEntity
{
private int id;
private String name;

@Id
@Column(name = "ID")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
@Column(name = "Name")
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
}

Hibernate Util:

public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
    Configuration configuration = new Configuration();
    configuration.configure();

    StandardServiceRegistry standardRegistry = new
    StandardServiceRegistryBuilder()
            .configure()
            .build();

    return configuration.buildSessionFactory(standardRegistry);
}
catch(Exception e) {
    throw new ExceptionInInitializerError(e);
}
}

public static Session getSession()
{
return sessionFactory.openSession();
}

public static void close()
{
sessionFactory.close();
}
}

Main class which is meant to save some hardcoded values:

public class Main {
public static void main(String[] args) {
    PersonEntity personEntity = new PersonEntity();

    personEntity.setId(1);
    personEntity.setName("Cris");

    Session session = HibernateUtil.getSession();

    session.beginTransaction();
    session.save(personEntity);
    session.getTransaction().commit();

}

}

I would be grateful if someone could help, in my opinion the problem lays in hibernate.cfg.xml, but that's just my guess.
Thanks in advance


问:
SSIS - The process cannot access the file because it is being used by another process
I have following Dataflow:

Control:

I just wanted to copy all the data from flatfiles in sourcefolder to sql database and after copying move those files to folder named Done.

But when i run this, i get error:

```<code>[File System Task] Error: An error occurred with the following error message: "The process cannot access the file because it is being used by another process.".
</code>```

Data gets copied to sqlserver , but file does not moves.

My process tab is as follows:

答: If the messages cites your ".ispac" file, you have an unclosed debug. Enter Task Manager and close the Debug Host.</p>

Body:
I have following Dataflow:

Control:

I just wanted to copy all the data from flatfiles in sourcefolder to sql database and after copying move those files to folder named Done.

But when i run this, i get error:

[File System Task] Error: An error occurred with the following error message: "The process cannot access the file because it is being used by another process.".

Data gets copied to sqlserver , but file does not moves.

My process tab is as follows:


问:
Check if user hits back button in browser
I'm trying to use the javascript onbeforeunload event to ask the user if they want to exit the page, but I don't want the event to fire (EDIT: "the event" being the dialog box that pops up asking the user to click ok to leave the site or click cancel to stay on the current page) if the user hits the back button since they will be most likely be staying on my site.

So is there a way to tell if a user has hit the back button using javascript or PHP?

I've gotten a solution using a hidden iframe that only works in IE, but I need something that can work for Firefox, Chrome, and Safari if possible.

EDIT: My IE solution works because when the user hits the back button the iframe is sent back but the parent page remains at the same spot. From this I can tell that the user has indeed hit the back button, so I then use history.back(). This little hack doesn't work in any other browser (to my knowledge), so I'm looking for a cross-browser solution.

tl;dr I'm using window.onbeforeunload to pop up a dialog asking users if they want to leave my site or not. I don't want this to pop up when the user hits the back button. How can I tell that the user has hit the back button in their browser?

Thanks,
Rick

答:
You can't know in advance on which page your user will go when he leaves your page. You can't even get the URLs in its current history.

I see no solution to your problem and I doubt there's one, sorry.

ContentLicense: CC BY-SA 2.5


问:
Send value from function to an other VC, swift3
I have this function, which is called when the user clicks on the image on the collectionView. There is a variable url (in the line print("IMAGE CLICKED:", url)) I want to send the value of the url to another viewController and set url in a UIImage.

Here is my unfinished function in the firstVC. From here I'd like to send the url to the secondVC.

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedCommunity = (liveCommunities?[indexPath.row].communityId)!
    let home = HomeViewController()
    home.showCommunityDetail()

    //url is the source for a image in another viewController
    //TODO: Send url to other viewController
    //There is no relation between the thwo viewControllers (only via tabbar)

    print("--------")
    print("IMAGE CLICKED:", url)
    print("--------")

}
</code>```

Is that possible? Thanks for your help in advance!

答:
find some example here https://stackoverflow.com/a/24036067/8263682
how to create controller from storyboard if needed and present it (or you could push it)

// Swift 3.0
let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "someViewController")
self.present(controller, animated: true, completion: nil)
```

<p>This is how you could set image Url as property for it (or send as method parameter)</p>

```controller.url = url
```

<p>But I see you have <strong>second controller in tab bar</strong>. So you could access it this way (see https://stackoverflow.com/a/25393586/8263682)</p>

```var svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController!
svc.url = url
```

Or use NotificationCenter.default.post... if you want

Body:
I have this function, which is called when the user clicks on the image on the collectionView. There is a variable url (in the line print("IMAGE CLICKED:", url)) I want to send the value of the url to another viewController and set url in a UIImage.

Here is my unfinished function in the firstVC. From here I'd like to send the url to the secondVC.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedCommunity = (liveCommunities?[indexPath.row].communityId)!
    let home = HomeViewController()
    home.showCommunityDetail()

    //url is the source for a image in another viewController
    //TODO: Send url to other viewController
    //There is no relation between the thwo viewControllers (only via tabbar)

    print("--------")
    print("IMAGE CLICKED:", url)
    print("--------")

}

Is that possible? Thanks for your help in advance!

Body:
find some example here https://stackoverflow.com/a/24036067/8263682
how to create controller from storyboard if needed and present it (or you could push it)

// Swift 3.0
let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "someViewController")
self.present(controller, animated: true, completion: nil)

This is how you could set image Url as property for it (or send as method parameter)

controller.url = url

But I see you have second controller in tab bar. So you could access it this way (see https://stackoverflow.com/a/25393586/8263682)

var svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController!
svc.url = url

Or use NotificationCenter.default.post... if you want


问:
How to get Ionic toggle on the left hand side of the label?
I have a simple toggle and label in a ion-item:

```<code><ion-item>
    <ion-toggle checked="true"></ion-toggle>
    <ion-label>Aangemeld blijven</ion-label>
</ion-item>
</code>```

I want to acheve that the toggle is placed on the left hand side of the label, but my result is:

I tried the floating-left and right, but it doesn't help.

Do you have any suggestion?

答:
Use these two class to override and show ion-toogle text on right side

```<code>.item-toggle .toggle
{
   left: 16px !important;
}
.item-toggle .ng-binding
{
   margin-left: 98%  !important;
}
</code>```

Sample : https://codepen.io/codeandyou/pen/obvYOG

Body:
I have a simple toggle and label in a ion-item:

<ion-item>
    <ion-toggle checked="true"></ion-toggle>
    <ion-label>Aangemeld blijven</ion-label>
</ion-item>

I want to acheve that the toggle is placed on the left hand side of the label, but my result is:

I tried the floating-left and right, but it doesn't help.

Do you have any suggestion?

Body:
Use these two class to override and show ion-toogle text on right side

.item-toggle .toggle
{
   left: 16px !important;
}
.item-toggle .ng-binding
{
   margin-left: 98%  !important;
}

Sample : https://codepen.io/codeandyou/pen/obvYOG


问:
Regarding I/O operations for OtherOperationCount
In https://msdn.microsoft.com/en-us/library/windows/desktop/ms684125(v=vs.85).aspx
it mentions

OtherOperationCount The number of I/O operations performed, other than
  read and write operations.

But what are examples of these operations?

答:
you need have Windows Research Kernel 1.2 for understand this. look for IopSynchronousServiceTail in base/ntos/io/iomgr/internal.c. at very begin of this function exist next code:

```<code>//
// Update the operation count statistic for the current process.
//

switch( TransferType ) {

case ReadTransfer:
    IopUpdateReadOperationCount();
    break;

case WriteTransfer:
    IopUpdateWriteOperationCount();
    break;

case OtherTransfer:
    IopUpdateOtherOperationCount();
    break;
}
</code>```

so search for string OtherTransfer inside base/ntos/io/iomgr folder - and you found huge count of api which use it:

```<code>NtDeviceIoControlFile
NtFsControlFile
NtQueryDirectoryFil
NtNotifyChangeDirectoryFile
NtLockFile
NtUnlockFile
NtFlushBuffersFile
NtQueryEaFile
NtSetEaFile
NtSetVolumeInformationFile
NtQueryVolumeInformationFile
NtQueryQuotaInformationFile
NtSetQuotaInformationFile
...
</code>```

Body:
you need have Windows Research Kernel 1.2 for understand this. look for IopSynchronousServiceTail in base/ntos/io/iomgr/internal.c. at very begin of this function exist next code:

//
// Update the operation count statistic for the current process.
//

switch( TransferType ) {

case ReadTransfer:
    IopUpdateReadOperationCount();
    break;

case WriteTransfer:
    IopUpdateWriteOperationCount();
    break;

case OtherTransfer:
    IopUpdateOtherOperationCount();
    break;
}

so search for string OtherTransfer inside base/ntos/io/iomgr folder - and you found huge count of api which use it:

NtDeviceIoControlFile
NtFsControlFile
NtQueryDirectoryFil
NtNotifyChangeDirectoryFile
NtLockFile
NtUnlockFile
NtFlushBuffersFile
NtQueryEaFile
NtSetEaFile
NtSetVolumeInformationFile
NtQueryVolumeInformationFile
NtQueryQuotaInformationFile
NtSetQuotaInformationFile
...


问:
openSUSE phpmyadmin Error: The mbstring extension is missing

phpMyAdmin - Error

The mbstring extension is missing. Please check
  your PHP configuration.

I hava installed php-mbstring and php-gettext, my php version is php7.
And I installed php and phpmyadmin through zypper.

答:
install mbstring and restart your apache:

```<code>sudo apt-get install php-mbstring
sudo service apache restart
</code>```

then remove ; from your php.ini file:

```<code>;extension=php_mbstring.dll
</code>```

to

```<code>extension=php_mbstring.dll
</code>```

If it still doesn't work..remove your php setup, without removing the databases from your phpmyadmin. Reinstall it.

NB: * if you want to remove all, all mention the one you need to.

```<code>sudo apt-get remove php*
</code>```

Then install the php and modules of the php version that you need. here, php 7.1:

```<code>sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-fpm php7.1-curl php7.1-gd php7.1-bz2 php7.1-mcrypt php7.1-json php7.1-tidy php7.1-mbstring php-redis php-memcached
</code>```

restart your apache and check the php version.

```<code>sudo service apache restart
php -v
</code>```

when all this is done, execute the following command to enable mbstring forcefully and restart your apache.

```<code>sudo phpenmod mbstring
sudo service apache restart
</code>```

following the php manual for php upgrade:

Hope it helps.
It did to me :)

Body:
install mbstring and restart your apache:

sudo apt-get install php-mbstring
sudo service apache restart

then remove ; from your php.ini file:

;extension=php_mbstring.dll

to

extension=php_mbstring.dll

If it still doesn't work..remove your php setup, without removing the databases from your phpmyadmin. Reinstall it.

NB: * if you want to remove all, all mention the one you need to.

sudo apt-get remove php*

Then install the php and modules of the php version that you need. here, php 7.1:

sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-fpm php7.1-curl php7.1-gd php7.1-bz2 php7.1-mcrypt php7.1-json php7.1-tidy php7.1-mbstring php-redis php-memcached

restart your apache and check the php version.

sudo service apache restart
php -v

when all this is done, execute the following command to enable mbstring forcefully and restart your apache.

sudo phpenmod mbstring
sudo service apache restart

following the php manual for php upgrade:

Hope it helps.
It did to me :)


问:
Can not get BLE characteristics to appear for primary service using BLENO on node js
I have a simple app shown below. I have created a primary service and added characteristics to my service using BLENO on node js on Rpi3.

It seems that my app starts and runs ok. I have used two tools to view my BLE service i.e. Nordic nRF application and a simple app I wrote in Android.

Using these apps I can see my BLE app advertising and i can also connect to it. When connected I can see three services which are two generic and one being my "unknown service" which has matching UUID as i have set in my BLE server app.

The problem I am having is when I expend my service, it tells me there are no characteristics set for my service.

I would appreciate if someone could review the code below and check possible reason for no characteristics appearing in my service.

```<code>`var bleno = require("bleno");
var BlenoPrimaryService = bleno.PrimaryService;
var Characteristic = bleno.Characteristic;
var Descriptor = bleno.Descriptor;
//var UserConfigCharecteristic = require('./user-config-characteristic');

bleno.on('stateChange', function (state) {
    console.log('on -> stateChagne: ' + state);
    if (state === 'poweredOn') {
        console.log('ble has been powered on');
        bleno.startAdvertising('rpi-ble-app', ['fffffffffffffffffffffffffffffff0']);
    } else {
        bleno.stopAdvertising();
    }
});

bleno.on('advertisingStart', function () {
console.log('-> advertising start');
bleno.setServices([
    new BlenoPrimaryService(
            {
                uuid: 'fffffffffffffffffffffffffffffff0',
                charecteristics: [
                    new Characteristic({
                        uuid: 'fffffffffffffffffffffffffffffff1', // or 'fff1' for 16-bit
                        properties: ['read', 'write'], // can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
                        secure: [], // enable security for properties, can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
                        value: null, // optional static value, must be of type Buffer - for read only characteristics
                        descriptors: [],
                        onReadRequest: null, // optional read request handler, function(offset, callback) { ... }
                        onWriteRequest: null, // optional write request handler, function(data, offset, withoutResponse, callback) { ...}
                        onSubscribe: null, // optional notify/indicate subscribe handler, function(maxValueSize, updateValueCallback) { ...}
                        onUnsubscribe: null, // optional notify/indicate unsubscribe handler, function() { ...}
                        onNotify: null, // optional notify sent handler, function() { ...}
                        onIndicate: null // optional indicate confirmation received handler, function() { ...}
                    })
                ]
            }
    )], function (error) {
    console.log('setServices: ' + (error ? 'error ' + error : 'success'));
});

});

bleno.on('servicesSet', function () {
    console.log('services set.');
});`
</code>```

Output for my node.js app is

```<code>on -> stateChagne: poweredOn
ble has been powered on
-> advertising start
services set.
setServices: success
</code>```

答:
Check this one. https://github.com/sandeepmistry/bleno/issues/301.
However, my problem was that services were not visible.</p>

Body:
I have a simple app shown below. I have created a primary service and added characteristics to my service using BLENO on node js on Rpi3.

It seems that my app starts and runs ok. I have used two tools to view my BLE service i.e. Nordic nRF application and a simple app I wrote in Android.

Using these apps I can see my BLE app advertising and i can also connect to it. When connected I can see three services which are two generic and one being my "unknown service" which has matching UUID as i have set in my BLE server app.

The problem I am having is when I expend my service, it tells me there are no characteristics set for my service.

I would appreciate if someone could review the code below and check possible reason for no characteristics appearing in my service.

`var bleno = require("bleno");
var BlenoPrimaryService = bleno.PrimaryService;
var Characteristic = bleno.Characteristic;
var Descriptor = bleno.Descriptor;
//var UserConfigCharecteristic = require('./user-config-characteristic');

bleno.on('stateChange', function (state) {
    console.log('on -> stateChagne: ' + state);
    if (state === 'poweredOn') {
        console.log('ble has been powered on');
        bleno.startAdvertising('rpi-ble-app', ['fffffffffffffffffffffffffffffff0']);
    } else {
        bleno.stopAdvertising();
    }
});

bleno.on('advertisingStart', function () {
console.log('-> advertising start');
bleno.setServices([
    new BlenoPrimaryService(
            {
                uuid: 'fffffffffffffffffffffffffffffff0',
                charecteristics: [
                    new Characteristic({
                        uuid: 'fffffffffffffffffffffffffffffff1', // or 'fff1' for 16-bit
                        properties: ['read', 'write'], // can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
                        secure: [], // enable security for properties, can be a combination of 'read', 'write', 'writeWithoutResponse', 'notify', 'indicate'
                        value: null, // optional static value, must be of type Buffer - for read only characteristics
                        descriptors: [],
                        onReadRequest: null, // optional read request handler, function(offset, callback) { ... }
                        onWriteRequest: null, // optional write request handler, function(data, offset, withoutResponse, callback) { ...}
                        onSubscribe: null, // optional notify/indicate subscribe handler, function(maxValueSize, updateValueCallback) { ...}
                        onUnsubscribe: null, // optional notify/indicate unsubscribe handler, function() { ...}
                        onNotify: null, // optional notify sent handler, function() { ...}
                        onIndicate: null // optional indicate confirmation received handler, function() { ...}
                    })
                ]
            }
    )], function (error) {
    console.log('setServices: ' + (error ? 'error ' + error : 'success'));
});

});

bleno.on('servicesSet', function () {
    console.log('services set.');
});`

Output for my node.js app is

on -> stateChagne: poweredOn
ble has been powered on
-> advertising start
services set.
setServices: success


问:
Sencha Architect creates ViewModel and ViewController Automaticly
I am working on Sencha Architect and following this video which made by Sencha dev-team to walks around basics of application.

I got errors when i run the project and later figure out that somehow Sencha Architect created 'ViewModel' and 'ViewController' automatically.

Why could be? or is there any setting in application to block?

Here is a sample folder structure of 'View'. Files with '(*)' symbol not created by me..

```<code>view/
.. TicketDataView.js
.. TicketDataViewViewController.js (*)
.. TicketDataViewViewModel.js (*)
.. TicketPanel.js
.. TicketPanelViewController.js (*)
.. TicketPanelViewModel.js (*)
</code>```

答:
The issue is that the video is four years old. Back then, the newest version of ExtJS was 4.x, and the MVVM model, which uses ViewModels and ViewControllers, was not available. With 5.x, released three years ago, the superior MVVM development model was introduced, so Sencha Architect assumes that in 2017, you always want to write MVVM instead of MVC. By the way, you will stumble over more outdated documentation along your steep journey trying to master ExtJS.

That said, you should make a new question including your code and error message to get help with your actual problem.

Body:
I am working on Sencha Architect and following this video which made by Sencha dev-team to walks around basics of application.

I got errors when i run the project and later figure out that somehow Sencha Architect created 'ViewModel' and 'ViewController' automatically.

Why could be? or is there any setting in application to block?

Here is a sample folder structure of 'View'. Files with '(*)' symbol not created by me..

view/
.. TicketDataView.js
.. TicketDataViewViewController.js (*)
.. TicketDataViewViewModel.js (*)
.. TicketPanel.js
.. TicketPanelViewController.js (*)
.. TicketPanelViewModel.js (*)


问:
non standard locale with java.util.Calendar
We have a customer in Sweden, using the software in English. So we set the Locale(en, SV). We did hope the Calendar class would adhere to the country settings, but it uses the language and with this locale it assumes US settings.

So I am now searching for a way to let the calendar get to know the new firstDayOfWeek and minimumDayinFirstWeek settings preferred by a standard way other than setting it manually and thus hardcoded.

For clarification: The 29. August 2010 is in Sweden in CW 34 (also in Germany and Great Britain) but in the US it is reported as CW 36. The different results from the fact that the 01.01.2010 is a Friday and the 29.08.2010 a Sunday.

I cannot change the language setting itself to Swedish and use the English fallback since we do not support Swedish as language, but Sun/Oracle/.. does, so the Swing UI would have a mixture of Swedish and English texts, which not acceptable.

And just adding a properties file named "sun.util.resources.CalendarData_en_SV.properties" does not work out: it does not get read! Manually as a ResourceBundle that's possible. Somehow LocaleData.getCalendarData(Locale) does its own magic in reading the resourcfiles which i cannot find out since the source of it is not available. The method is called here: java.util.Calendar.setWeekCountData(Locale).

I also found the java.util.spi package but it does not provide access to the firstDayOfWeek and minimumDaysInFirstWeek settings.

Perhaps I can try to intercept the calls to the resourcebundles and use the default fallback to English and only let the calls to CalendarData proceed!? But that sounds hacky.

```<code>package de.drews.i18n;

import java.util.Calendar;
import java.util.Locale;
import java.util.ResourceBundle;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
       // en_GB = 34
       // en_US = 36
       // sv_SV = 34
       // en_SV = 36 --> wrong

       printTest("en", "GB", 34);
       printTest("en", "US", 36);
       printTest("sv", "SV", 34);
       printTest("en", "SV", 34);
    }

    private static void printTest(String language, String country, int expected) {
       Locale locale = new Locale(language, country);

       Calendar cal = Calendar.getInstance(locale);

       cal.set(Calendar.YEAR, 2010);
       cal.set(Calendar.MONTH, Calendar.AUGUST);
       cal.set(Calendar.DATE, 29);

       int actual = cal.get(Calendar.WEEK_OF_YEAR);

       System.out.println(actual + "\t" + expected + "\t"
        + ((actual == expected) ? "Yeah!" : "-") + "\t" + language
        + "\t" + country);
    }
}
</code>```

答:
One ugly workaround that I can offer is to reflectively obtain the cachedLocaleData static field of the Calendar class, and put there the following:

```<code>key = new Locale(..); // your english-swedish locale
value = new int[] {firstDayOfWeek, minimalDaysInFirstWeek};
</code>```

This can be done at init-time and will work for the entire application

Body:
We have a customer in Sweden, using the software in English. So we set the Locale(en, SV). We did hope the Calendar class would adhere to the country settings, but it uses the language and with this locale it assumes US settings.

So I am now searching for a way to let the calendar get to know the new firstDayOfWeek and minimumDayinFirstWeek settings preferred by a standard way other than setting it manually and thus hardcoded.

For clarification: The 29. August 2010 is in Sweden in CW 34 (also in Germany and Great Britain) but in the US it is reported as CW 36. The different results from the fact that the 01.01.2010 is a Friday and the 29.08.2010 a Sunday.

I cannot change the language setting itself to Swedish and use the English fallback since we do not support Swedish as language, but Sun/Oracle/.. does, so the Swing UI would have a mixture of Swedish and English texts, which not acceptable.

And just adding a properties file named "sun.util.resources.CalendarData_en_SV.properties" does not work out: it does not get read! Manually as a ResourceBundle that's possible. Somehow LocaleData.getCalendarData(Locale) does its own magic in reading the resourcfiles which i cannot find out since the source of it is not available. The method is called here: java.util.Calendar.setWeekCountData(Locale).

I also found the java.util.spi package but it does not provide access to the firstDayOfWeek and minimumDaysInFirstWeek settings.

Perhaps I can try to intercept the calls to the resourcebundles and use the default fallback to English and only let the calls to CalendarData proceed!? But that sounds hacky.

package de.drews.i18n;

import java.util.Calendar;
import java.util.Locale;
import java.util.ResourceBundle;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
       // en_GB = 34
       // en_US = 36
       // sv_SV = 34
       // en_SV = 36 --> wrong

       printTest("en", "GB", 34);
       printTest("en", "US", 36);
       printTest("sv", "SV", 34);
       printTest("en", "SV", 34);
    }

    private static void printTest(String language, String country, int expected) {
       Locale locale = new Locale(language, country);

       Calendar cal = Calendar.getInstance(locale);

       cal.set(Calendar.YEAR, 2010);
       cal.set(Calendar.MONTH, Calendar.AUGUST);
       cal.set(Calendar.DATE, 29);

       int actual = cal.get(Calendar.WEEK_OF_YEAR);

       System.out.println(actual + "\t" + expected + "\t"
        + ((actual == expected) ? "Yeah!" : "-") + "\t" + language
        + "\t" + country);
    }
}

Body:
One ugly workaround that I can offer is to reflectively obtain the cachedLocaleData static field of the Calendar class, and put there the following:

key = new Locale(..); // your english-swedish locale
value = new int[] {firstDayOfWeek, minimalDaysInFirstWeek};

This can be done at init-time and will work for the entire application


问:
NPM installation issue ubuntu
I want to install npm for use angular2 with laravel5.2 , but while installation of npm. I got below issue :  </p>

```<code>npm WARN npm npm does not support Node.js v0.10.25
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm You can find the latest version at https://nodejs.org/

/usr/local/lib/node_modules/npm/lib/install.js:298
        [this, (next) => { computeMetadata(this.idealTree); next() }],
                       ^
npm ERR! Unexpected token >

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/swapnily/.npm/_logs/2017-07-06T07_21_24_104Z-debug.log
</code>```

<p>Please let me know if anyone aware about same.  </p>

答:
npm does not support Node.js v0.10.25

You're using v0.10.25 which was long deprecated hence this error.

You need node v4 or higher to run this program.

To install an old and unsupported version of npm that works on node v0.12 and prior, clone the git repo and dig through the old tags and branches.

Source npm's doc

I have install " curl -sL deb.nodesource.com/setup_6.x

It isn't clear whether this succeed or not. Assuming that this succeed without errors. Check which version of node is currently being used.

```<code>sridharrajs@debian:~$ which node
/home/sridharrajs/.nvm/versions/node/v5.11.1/bin/node  -- In mycase I'm using version 5.11.1
</code>```

Switch to v6.x.x which you've just installed and retry installing.

If you still had issues in installing and switching node versions I recommend you to check
nvm. Using this you can  install and switch versions easily.

Title: NPM installation issue ubuntu

Body:
I want to install npm for use angular2 with laravel5.2 , but while installation of npm. I got below issue :

npm WARN npm npm does not support Node.js v0.10.25
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm You can find the latest version at https://nodejs.org/

/usr/local/lib/node_modules/npm/lib/install.js:298
        [this, (next) => { computeMetadata(this.idealTree); next() }],
                       ^
npm ERR! Unexpected token >

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/swapnily/.npm/_logs/2017-07-06T07_21_24_104Z-debug.log

Please let me know if anyone aware about same.

Body:
npm does not support Node.js v0.10.25

You're using v0.10.25 which was long deprecated hence this error.

You need node v4 or higher to run this program.

To install an old and unsupported version of npm that works on node v0.12 and prior, clone the git repo and dig through the old tags and branches.

Source npm's doc

I have install " curl -sL deb.nodesource.com/setup_6.x

It isn't clear whether this succeed or not. Assuming that this succeed without errors. Check which version of node is currently being used.

sridharrajs@debian:~$ which node
/home/sridharrajs/.nvm/versions/node/v5.11.1/bin/node  -- In mycase I'm using version 5.11.1

Switch to v6.x.x which you've just installed and retry installing.

If you still had issues in installing and switching node versions I recommend you to check
nvm. Using this you can  install and switch versions easily.


问:
using drop-downs in the toolbar filter fields in jqgrid removes column values
I used info in this question, I put the mentioned properties directly in the field properties not through a function like this :

```<code>{
    name:'A_ORG_SECTOR',
    index:'A_ORG_SECTOR',
    align: 'left',
    width:80,
    sortable:true,
    search:true,
    stype:'select',
    editable:false,
    cellEdit: false ,
    formatter:'select',
    searchoptions: {
        sopt:['eq'],
        value: ':All;1:IT;2:Strategy'
    }
},
</code>```

... drop down appears correctly but the column values are now cleared @ loading as per the attached image ... any help ???

jquery version : 1.9.1

jqGrid version : 4.5.0

Concerning fork, I am not sure, It's actually part of the liferay libraries, but seems to be the free version.

The values were apearing correctly before converting the search to select instead of text

答:
I suppose that your main reason could be missing editoptions.value (or it could be formatoptions.value in case of usage free jqGrid fork) (see the old documentation):

```<code>{
    name:'A_ORG_SECTOR',
    width:80,
    formatter:'select',
    editoptions: { value: '1:IT;2:Strategy' },
    stype:'select',
    searchoptions: {
        sopt:['eq'],
        value: ':All;1:IT;2:Strategy'
    }
},
</code>```

Additionally you should verify that the input data, used for filing the grid, contains values like 1 and 2 and not the texts IT or Strategy.

The exact behavior of jqGrid could heavy depend on the version of jqGrid, which you use and from the fork of jqGrid. Please insert more full information about the version/fork of jqGrid, which you use.

Body:
I used info in this question, I put the mentioned properties directly in the field properties not through a function like this :

{
    name:'A_ORG_SECTOR',
    index:'A_ORG_SECTOR',
    align: 'left',
    width:80,
    sortable:true,
    search:true,
    stype:'select',
    editable:false,
    cellEdit: false ,
    formatter:'select',
    searchoptions: {
        sopt:['eq'],
        value: ':All;1:IT;2:Strategy'
    }
},

... drop down appears correctly but the column values are now cleared @ loading as per the attached image ... any help ???

jquery version : 1.9.1

jqGrid version : 4.5.0

Concerning fork, I am not sure, It's actually part of the liferay libraries, but seems to be the free version.

The values were apearing correctly before converting the search to select instead of text

Body:
I suppose that your main reason could be missing editoptions.value (or it could be formatoptions.value in case of usage free jqGrid fork) (see the old documentation):

{
    name:'A_ORG_SECTOR',
    width:80,
    formatter:'select',
    editoptions: { value: '1:IT;2:Strategy' },
    stype:'select',
    searchoptions: {
        sopt:['eq'],
        value: ':All;1:IT;2:Strategy'
    }
},

Additionally you should verify that the input data, used for filing the grid, contains values like 1 and 2 and not the texts IT or Strategy.

The exact behavior of jqGrid could heavy depend on the version of jqGrid, which you use and from the fork of jqGrid. Please insert more full information about the version/fork of jqGrid, which you use.


问:
Does s4cmd support signature version 4 because i am unable to upload files to s3 bucket (LONDON)
I am trying to upload files to s3 bucket(LONDON) i.e. eu-west-2. S4cmd is not working.

s4cmd put /home/username/Documents/file-1.json s3://[BUCKETNAME]/file-1.json

error when i run this command is  : -

```<code>[Exception] An error occurred (400) when calling the HeadObject operation: Bad Request
[Thread Failure] An error occurred (400) when calling the HeadObject operation: Bad Request
</code>```

S3cmd works but it is slow. s4cmd works for US standard region but for London region it is not working.

Thanks in advance.

答: The aws s3 cp command in the AWS Command-Line Interface (CLI) uses multi-part upload to fully utilize available bandwidth, so it should give you pretty much the best speed possible.

Body:
I am trying to upload files to s3 bucket(LONDON) i.e. eu-west-2. S4cmd is not working.

s4cmd put /home/username/Documents/file-1.json s3://[BUCKETNAME]/file-1.json

error when i run this command is  : -

[Exception] An error occurred (400) when calling the HeadObject operation: Bad Request
[Thread Failure] An error occurred (400) when calling the HeadObject operation: Bad Request

S3cmd works but it is slow. s4cmd works for US standard region but for London region it is not working.

Thanks in advance.


问:
UWP C# How to change Xaml UI rectangle fill outside of MainPage in async method?
(Windows 10, UWP, C#, XAML)
I'm trying to change a rectangle's Fill from a class that is not the main method. I've sent my rectangle to the other class and from there I can set it's Fill. However, I need the Fill to change during an ongoing asynchronous method (rather, during a method that is being called by an on-going asynchronous method) but when I try that, I get an exception about threading:

The application called an interface that was marshalled for a
  different thread. (Exception from HRESULT: 0x8001010E
  (RPC_E_WRONG_THREAD))

So, I've read about using Dispatcher to solve this sort of problem. It works for me ONLY when I don't leave the MainPage:

```<code>    public async void printer()
    {
        await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            Debug.WriteLine("I'm inside the printer before");
           this.staffImageBorder.Fill = new SolidColorBrush(Colors.Blue);
            Debug.WriteLine("I'm inside the printer after");
        });
}
</code>```

However, when I call this printer() method from my other class, it just skips right over the Fill change. Both Debug statements print.

I tried to move the Dispatcher code over to my other class but that class doesn't know what "Dispatcher" is (and neither do I ...).

Sorry I couldn't provide more code, I'm having difficulty replicating it on a simpler example. Any help would be greatly appreciated!

答:
Dispatcher essentially manages dispatching events on the UI thread (and any updates to the UI need to be done on the UI thread!).

If you want to access it from outside a page you can access it via Window.Current.Dispatcher (or assign it as a static variable somewhere if you can't access Window - there's only ONE dispatcher per UI thread / Window that everything in that Window shares)

If it's printing both Debug statements however it's more than likely NOT skipping over your code, but you've got some issue elsewhere.

BTW, you probably want to re-write as a Task and NOT as an async void.

```<code>public Task SetPrintFillAsync()
{
    return this.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
    {
        Debug.WriteLine("I'm inside the printer before");
        this.staffImageBorder.Fill = new SolidColorBrush(Colors.Blue);
        Debug.WriteLine("I'm inside the printer after");
    });
}
</code>```

And call like

```<code>await SetPrintFillAsync()
</code>```

Body:
(Windows 10, UWP, C#, XAML)
I'm trying to change a rectangle's Fill from a class that is not the main method. I've sent my rectangle to the other class and from there I can set it's Fill. However, I need the Fill to change during an ongoing asynchronous method (rather, during a method that is being called by an on-going asynchronous method) but when I try that, I get an exception about threading:

The application called an interface that was marshalled for a
  different thread. (Exception from HRESULT: 0x8001010E
  (RPC_E_WRONG_THREAD))

So, I've read about using Dispatcher to solve this sort of problem. It works for me ONLY when I don't leave the MainPage:

    public async void printer()
    {
        await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            Debug.WriteLine("I'm inside the printer before");
           this.staffImageBorder.Fill = new SolidColorBrush(Colors.Blue);
            Debug.WriteLine("I'm inside the printer after");
        });
}

However, when I call this printer() method from my other class, it just skips right over the Fill change. Both Debug statements print.

I tried to move the Dispatcher code over to my other class but that class doesn't know what "Dispatcher" is (and neither do I ...).

Sorry I couldn't provide more code, I'm having difficulty replicating it on a simpler example. Any help would be greatly appreciated!

Body:
Dispatcher essentially manages dispatching events on the UI thread (and any updates to the UI need to be done on the UI thread!).

If you want to access it from outside a page you can access it via Window.Current.Dispatcher (or assign it as a static variable somewhere if you can't access Window - there's only ONE dispatcher per UI thread / Window that everything in that Window shares)

If it's printing both Debug statements however it's more than likely NOT skipping over your code, but you've got some issue elsewhere.

BTW, you probably want to re-write as a Task and NOT as an async void.

public Task SetPrintFillAsync()
{
    return this.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
    {
        Debug.WriteLine("I'm inside the printer before");
        this.staffImageBorder.Fill = new SolidColorBrush(Colors.Blue);
        Debug.WriteLine("I'm inside the printer after");
    });
}

And call like

await SetPrintFillAsync()


问:
Data manipulation with gsub
I have a variable which has character values like "Futrelle, Mrs. Jacques Heath (Lily May Peel)"

After using below set of codes I am getting output as "Mrs" alone

```<code>gsub("[.,(,,)]",'',a$V1)

gsub('(.*,)|(\\..*)','',a$V1)
</code>```

Please help me in understanding above codes, what it does exactly?

答:
The basic pattern of gsub is the following:
gsub(pattern, replacement, x, ...).

pattern is the string you want to be replaced.

replacementis what you want to replace your pattern for.

xis the object where you wish to apply your replacements.

In your case, the first gsubfunction you posted will replace the pattern "[.,(,,)]", by the pattern '' and this replacement will be applied on a$V1

```<code>> # considering the following data frame
> df <- df <- data.frame(color = c("green", "yellow", "blue"), shape=c("squared", "triangle", "octagon"))
> df
   color    shape
1  green  squared
2 yellow triangle
3   blue  octagon
> # Let's say you want to replace, under df$color the string "green" by "purple", you could run the following command:
> df_new <- as.data.frame(lapply(df, function(x) {gsub(pattern = "green", replacement = "purple", df$color)}))
> # which gives you:
> df_new
   color  shape
1 purple purple
2 yellow yellow
3   blue   blue
</code>```

When working with data frames (I see that this is you case because of your x (a$V1) keep in mind to wrap the gsubfunction within lapply. Otherwise the ouptput can get quite messy.

Title: Data manipulation with gsub

Body:
I have a variable which has character values like "Futrelle, Mrs. Jacques Heath (Lily May Peel)"

After using below set of codes I am getting output as "Mrs" alone

gsub("[.,(,,)]",'',a$V1)

gsub('(.*,)|(\\..*)','',a$V1)

Please help me in understanding above codes, what it does exactly?

Body:
The basic pattern of gsub is the following:
gsub(pattern, replacement, x, ...).

pattern is the string you want to be replaced.

replacementis what you want to replace your pattern for.

xis the object where you wish to apply your replacements.

In your case, the first gsubfunction you posted will replace the pattern "[.,(,,)]", by the pattern '' and this replacement will be applied on a$V1

> # considering the following data frame
> df <- df <- data.frame(color = c("green", "yellow", "blue"), shape=c("squared", "triangle", "octagon"))
> df
   color    shape
1  green  squared
2 yellow triangle
3   blue  octagon
> # Let's say you want to replace, under df$color the string "green" by "purple", you could run the following command:
> df_new <- as.data.frame(lapply(df, function(x) {gsub(pattern = "green", replacement = "purple", df$color)}))
> # which gives you:
> df_new
   color  shape
1 purple purple
2 yellow yellow
3   blue   blue

When working with data frames (I see that this is you case because of your x (a$V1) keep in mind to wrap the gsubfunction within lapply. Otherwise the ouptput can get quite messy.


问:
How to change my below Pgsql Query
I would like to execute the below query by passing some values from applet side tables.

My table is

```<code>style_no       | version_no | style_id
---------------------+------------+----
 Menshirt      |     1      |      861
 Menshirt      |     2      |      870
 Tops          |     1      |      893
 Childwear     |     1      |      856
 Childwear     |     2      |      978
</code>```

If user select MenShirt with version 1,Tops with version 1,ChildWear with version 2 details, so my StylenoStr arguments = (MenShirt, Tops, Childwear) and VernoStr argument = (1, 1, 2). My problem is the below query retrieves the data with MenShirt details for Version 2 which is no needed here. How do I write a query to get results for only selected data? I am using Pgsql.

Actual query:

```<code>select style_id, style_no, version_no
from style
where style_no in (" + StylenoStr + ")
  and version_no in (" + VernoStr + ")
</code>```

Executed query:

```<code>select style_id, style_no, version_no
from style
where style_no in ('Menshirt', 'Tops', 'Childwear')
  and version_no in ('1', '1', '2');
</code>```

Result I am getting:

```<code>style_id | style_no        | version_no
---------+-----------------+------------
     861 | Menshirt        |     1
     870 | Menshirt        |     2
     893 | Tops            |     1
     978 | Childwear       |     2
</code>```

Result I need is:

```<code> style_id | style_no       | version_no
----------+----------------+------------
      861 | Menshirt       |     1
      893 | Tops           |     1
      978 | Childwear      |     2
</code>```

Thanks a lot.

答:
```<code>select style_id, style_no, version_no
from style
where (style_no, version_no) in (('Menshirt', '1'),
                                 ('Tops', '1'),
                                 ('Childwear', '2'));
</code>```

Title: How to change my below Pgsql Query

Body:
I would like to execute the below query by passing some values from applet side tables.

My table is

style_no       | version_no | style_id
---------------------+------------+----
 Menshirt      |     1      |      861
 Menshirt      |     2      |      870
 Tops          |     1      |      893
 Childwear     |     1      |      856
 Childwear     |     2      |      978

If user select MenShirt with version 1,Tops with version 1,ChildWear with version 2 details, so my StylenoStr arguments = (MenShirt, Tops, Childwear) and VernoStr argument = (1, 1, 2). My problem is the below query retrieves the data with MenShirt details for Version 2 which is no needed here. How do I write a query to get results for only selected data? I am using Pgsql.

Actual query:

select style_id, style_no, version_no
from style
where style_no in (" + StylenoStr + ")
  and version_no in (" + VernoStr + ")

Executed query:

select style_id, style_no, version_no
from style
where style_no in ('Menshirt', 'Tops', 'Childwear')
  and version_no in ('1', '1', '2');

Result I am getting:

style_id | style_no        | version_no
---------+-----------------+------------
     861 | Menshirt        |     1
     870 | Menshirt        |     2
     893 | Tops            |     1
     978 | Childwear       |     2

Result I need is:

 style_id | style_no       | version_no
----------+----------------+------------
      861 | Menshirt       |     1
      893 | Tops           |     1
      978 | Childwear      |     2

Thanks a lot.