问:
Class Redefine not working
SO I am trying to redefine a class. I have a class named folder.  In OSGi (using Felix) I have a new Folder class with the same methods but some additional logging.

I am trying to take the Folder Class from Felix and redefine the main Folder class on the main classloader

I do have the agent set on startup.

```<code>new ByteBuddy()
                        .redefine(Class.forName(classToOverride.trim()), ClassFileLocator.ForClassLoader.of(felixClassLoader))
                        .name(classToOverride.trim())
                        .make()                            .load(contextClassLoader);
</code>```

I have tried different strategies in the load method.

Without any strategies I get the following error

```<code>Caused by: java.lang.IllegalStateException: Cannot inject already loaded type: class com.dotmarketing.portlets.folders.model.Folder
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.inject(ClassInjector.java:187) ~[byte-buddy-1.6.12.jar:?]
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:187) ~[byte-buddy-1.6.12.jar:?]
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default.load(ClassLoadingStrategy.java:120) ~[byte-buddy-1.6.12.jar:?]
at net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79) ~[byte-buddy-1.6.12.jar:?]
at net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4376) ~[byte-buddy-1.6.12.jar:?]
at com.dotmarketing.osgi.GenericBundleActivator.publishBundleServices(GenericBundleActivator.java:177) ~[dotcms_4.1.0_563a5c3.jar:?]
</code>```

With ClassReloadingStrategy.fromInstalledAgent  I get no error but doesn't work.

答: On a JVM, you cannot simply redefine an already loaded class. You can only redefine a class using a Java agent where Byte Buddy supplies the AgentBuilder API which you can use. Note that it is only possible to change the content of methods but not a class's layout. You probably want to have a look at the Advice API to do so.

Title: Class Redefine not working

Body:
SO I am trying to redefine a class. I have a class named folder.  In OSGi (using Felix) I have a new Folder class with the same methods but some additional logging.

I am trying to take the Folder Class from Felix and redefine the main Folder class on the main classloader

I do have the agent set on startup.

new ByteBuddy()
                        .redefine(Class.forName(classToOverride.trim()), ClassFileLocator.ForClassLoader.of(felixClassLoader))
                        .name(classToOverride.trim())
                        .make()                            .load(contextClassLoader);

I have tried different strategies in the load method.

Without any strategies I get the following error

Caused by: java.lang.IllegalStateException: Cannot inject already loaded type: class com.dotmarketing.portlets.folders.model.Folder
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.inject(ClassInjector.java:187) ~[byte-buddy-1.6.12.jar:?]
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:187) ~[byte-buddy-1.6.12.jar:?]
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default.load(ClassLoadingStrategy.java:120) ~[byte-buddy-1.6.12.jar:?]
at net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79) ~[byte-buddy-1.6.12.jar:?]
at net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4376) ~[byte-buddy-1.6.12.jar:?]
at com.dotmarketing.osgi.GenericBundleActivator.publishBundleServices(GenericBundleActivator.java:177) ~[dotcms_4.1.0_563a5c3.jar:?]

With ClassReloadingStrategy.fromInstalledAgent  I get no error but doesn't work.


来源: stackexchange

问:
Select2 ajax not working in rails
I'm using select2 in rails with gem rails-select2, currently using 4.0.3 version.

I can't manage to make the ajax version of select2 working, the static version where I set the data as an array is working while the ajax version it's not.

I'm not getting any error and no ajax calls on the backend.

The select appear empty with the select2 style and while I type it does not do anything.

Is there a way to debug or understand where the problem is?

I'm using the following example code:

On the view:

```<code><select class="js-data-example-ajax" style="width:100%">
<option value="3620194" selected="selected">Select a value......</option>
</select>
</code>```

On the javascript:

```<code>$(".js-data-example-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      // parse the results into the format expected by Select2
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data, except to indicate that infinite
      // scrolling can be used
      params.page = params.page || 1;

      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  }

});
</code>```

This is what I got:

No error on javascript console and everything is working if I use array data (so I guess there is no problem with the select2 import).

I need to find a way to better debug the problem to properly understand where the issue is lying.

答: It could be a problem with cross-domain request, you should look into browser console. </p>

ContentLicense: CC BY-SA 3.0

Title: Select2 ajax not working in rails

Body:
I'm using select2 in rails with gem rails-select2, currently using 4.0.3 version.

I can't manage to make the ajax version of select2 working, the static version where I set the data as an array is working while the ajax version it's not.

I'm not getting any error and no ajax calls on the backend.

The select appear empty with the select2 style and while I type it does not do anything.

Is there a way to debug or understand where the problem is?

I'm using the following example code:

On the view:

<select class="js-data-example-ajax" style="width:100%">
<option value="3620194" selected="selected">Select a value......</option>
</select>

On the javascript:

$(".js-data-example-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      // parse the results into the format expected by Select2
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data, except to indicate that infinite
      // scrolling can be used
      params.page = params.page || 1;

      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  }

});

This is what I got:

No error on javascript console and everything is working if I use array data (so I guess there is no problem with the select2 import).

I need to find a way to better debug the problem to properly understand where the issue is lying.


问:
ASP.NET MVC5 OWIN Facebook authentication suddenly not working
Update 2017!

The issue I had when I posted the original question has got nothing to do with the recent changes Facebook made when they forced everyone to version 2.3 of their API.  For a solution to that specific problem, see sammy34's answer below.  Version 2.3 of the /oauth/access_token endpoint now returns JSON instead of form-encoded values

For historical reasons, here's my original question/issue:

I've got an MVC5 Web application which is using the built-in support for authentication via Facebook and Google.  When we built this app a few months ago, we followed this tutorial: http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on and everything worked great.

Now, all of a sudden, the Facebook authentication has just stopped working alltogether.  The Google authentication still works great.

Description of the problem: We click the link to connect using Facebook, we are redirected to Facebook where we are prompted if we wan't to allow our Facebook app access to our profile.  When we click "OK" we are redirected back to our site, but instead of being logged in we simply end up at the login screen.

I've gone through this process in debug mode and I've got this ActionResult in my account controller as per the tutorial mentioned above:

```<code>// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
    ............
</code>```

When stepping through the code and upon returning from Facebook, the loginInfo object is always NULL, which causes the user to be redirected back to the login.

In order to understand what is actually happening behind the scenes, I installed Fiddler and monitored the HTTP traffic.  What I disovered is that upon clicking "OK" at the Facebook permission dialog, Facebook redirects back to our application with this URL:

```<code>https://localhost/signin-facebook?code=<access-token>
</code>```

This URL is not an actual file and probably handled by some controller/handler built into this OWIN framework I'm guessing.  Most likely, it is connecting back to Facebook using the given code to query information about the user which is trying to login.  Now, the problem is that instead of doing that, we are redirected to:

```<code>/Account/ExternalLoginCallback?error=access_denied
</code>```

Which I'm sure is something Facebook is doing, that is, instead of giving us the user data, it's redirecting us back with this error message.

This causes the AuthenticationManager.GetExternalLoginInfoAsync(); to fail and always return NULL.

I'm completely out of ideas.  As far as we know, we did not change anything on our end.

I've tried creating a new Facebook app, I've tried following the tutorial again but I always have the same problem.

Any ideas welcome!

Update!

OK, this is driving me insane!  I've now manually gone through the steps required to perform the authentication and everything works great when I do that.  Why on earth is this not working when using the MVC5 Owin stuff?

This is what I did:

```<code>    // Step 1 - Pasted this into a browser, this returns a code
    https://www.facebook.com/dialog/oauth?response_type=code&client_id=619359858118523&redirect_uri=https%3A%2F%2Flocalhost%2Fsignin-facebook&scope=&state=u9R1m4iRI6Td4yACEgO99ETQw9NAos06bZWilJxJrXRn1rh4KEQhfuEVAq52UPnUif-lEHgayyWrsrdlW6t3ghLD8iFGX5S2iUBHotyTqCCQ9lx2Nl091pHPIw1N0JV23sc4wYfOs2YU5smyw9MGhcEuinvTAEql2QhBowR62FfU6PY4lA6m8pD3odI5MwBYOMor3eMLu2qnpEk0GekbtTVWgQnKnH6t1UcC6KcNXYY

I was redirected back to localhost (which I had shut down at this point to avoid being redirected immediately away).  The URL I was redirected to is this:

https://localhost/signin-facebook?code=<code-received-removed-for-obvious-reasons>

Now, I grabbed the code I got and used it in the URL below:

// Step 2 - opened this URL in a browser, and successfully retrieved an access token
https://graph.facebook.com/oauth/access_token?client_id=619359858118523&redirect_uri=https://localhost/signin-facebook&client_secret=<client-secret>&code=<code-from-step-1>

// Step 3 - Now I'm able to query the facebook graph using the access token from step 2!

https://graph.facebook.com/me?access_token=<access-token-from-step-2>
</code>```

No errors, everything works great!  Then why the hell is this not working when using the MVC5 Owin stuff?  There's obviously something wrong with the OWin implementation.

答: Noticed this problem yesterday. Facebook does not support Microsoft.Owin.Security.Facebook version 3.0.1 anymore. For me it worked to install version 3.1.0. To update to 3.1.0, run the command Install-Package Microsoft.Owin.Security.Facebook in Package Manager Console: https://www.nuget.org/packages/Microsoft.Owin.Security.Facebook

Body:
Update 2017!

The issue I had when I posted the original question has got nothing to do with the recent changes Facebook made when they forced everyone to version 2.3 of their API.  For a solution to that specific problem, see sammy34's answer below.  Version 2.3 of the /oauth/access_token endpoint now returns JSON instead of form-encoded values

For historical reasons, here's my original question/issue:

I've got an MVC5 Web application which is using the built-in support for authentication via Facebook and Google.  When we built this app a few months ago, we followed this tutorial: http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on and everything worked great.

Now, all of a sudden, the Facebook authentication has just stopped working alltogether.  The Google authentication still works great.

Description of the problem: We click the link to connect using Facebook, we are redirected to Facebook where we are prompted if we wan't to allow our Facebook app access to our profile.  When we click "OK" we are redirected back to our site, but instead of being logged in we simply end up at the login screen.

I've gone through this process in debug mode and I've got this ActionResult in my account controller as per the tutorial mentioned above:

// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
    ............

When stepping through the code and upon returning from Facebook, the loginInfo object is always NULL, which causes the user to be redirected back to the login.

In order to understand what is actually happening behind the scenes, I installed Fiddler and monitored the HTTP traffic.  What I disovered is that upon clicking "OK" at the Facebook permission dialog, Facebook redirects back to our application with this URL:

https://localhost/signin-facebook?code=<access-token>

This URL is not an actual file and probably handled by some controller/handler built into this OWIN framework I'm guessing.  Most likely, it is connecting back to Facebook using the given code to query information about the user which is trying to login.  Now, the problem is that instead of doing that, we are redirected to:

/Account/ExternalLoginCallback?error=access_denied

Which I'm sure is something Facebook is doing, that is, instead of giving us the user data, it's redirecting us back with this error message.

This causes the AuthenticationManager.GetExternalLoginInfoAsync(); to fail and always return NULL.

I'm completely out of ideas.  As far as we know, we did not change anything on our end.

I've tried creating a new Facebook app, I've tried following the tutorial again but I always have the same problem.

Any ideas welcome!

Update!

OK, this is driving me insane!  I've now manually gone through the steps required to perform the authentication and everything works great when I do that.  Why on earth is this not working when using the MVC5 Owin stuff?

This is what I did:

    // Step 1 - Pasted this into a browser, this returns a code
    https://www.facebook.com/dialog/oauth?response_type=code&client_id=619359858118523&redirect_uri=https%3A%2F%2Flocalhost%2Fsignin-facebook&scope=&state=u9R1m4iRI6Td4yACEgO99ETQw9NAos06bZWilJxJrXRn1rh4KEQhfuEVAq52UPnUif-lEHgayyWrsrdlW6t3ghLD8iFGX5S2iUBHotyTqCCQ9lx2Nl091pHPIw1N0JV23sc4wYfOs2YU5smyw9MGhcEuinvTAEql2QhBowR62FfU6PY4lA6m8pD3odI5MwBYOMor3eMLu2qnpEk0GekbtTVWgQnKnH6t1UcC6KcNXYY

I was redirected back to localhost (which I had shut down at this point to avoid being redirected immediately away).  The URL I was redirected to is this:

https://localhost/signin-facebook?code=

Now, I grabbed the code I got and used it in the URL below:

// Step 2 - opened this URL in a browser, and successfully retrieved an access token
https://graph.facebook.com/oauth/access_token?client_id=619359858118523&redirect_uri=https://localhost/signin-facebook&client_secret=<client-secret>&code=

// Step 3 - Now I'm able to query the facebook graph using the access token from step 2!

https://graph.facebook.com/me?access_token=<access-token-from-step-2>

No errors, everything works great!  Then why the hell is this not working when using the MVC5 Owin stuff?  There's obviously something wrong with the OWin implementation.


问:
Bash Shell - Change text inside tag AND remove all content inside tag
I need to remove/change some content from an html file

From this one i need to remove everything , from the beggining of the div tag till the end of /div

Document generated by Confluence on 2017/03/27 09:41

                Atlassian

```
</div>
</div>
</p>

<p>And here i need to change the Author and Editor names</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-html lang-html prettyprint-override"><code>Created by <span class='author'>John Smith</span>, last modified by <span class='editor'> John Smith</span> on 2017/03/24</code>```

I know i need to use sed , but i have no idea how to create said expressions

答:
Regarding to the 1st challenge please be more specific.

This is the sed script for the 2nd challenge:

```<code>source="Created by <span class='author'>John Smith</span>, last modified by <span class='editor'> John Smith</span> on 2017/03/24"
author="new author"
editor="new editor"
result=`echo "$source" | sed "s/\(.*author'>\).*\(<\/span>,.*editor'>\).*\(<\/span.*\)/\1$author\2$editor\3/"`

echo $result
</code>```

Body:
I need to remove/change some content from an html file

From this one i need to remove everything , from the beggining of the div tag till the end of /div

Document generated by Confluence on 2017/03/27 09:41

                Atlassian

And here i need to change the Author and Editor names

Created by John Smith, last modified by  John Smith on 2017/03/24

I know i need to use sed , but i have no idea how to create said expressions

Body:
Regarding to the 1st challenge please be more specific.

This is the sed script for the 2nd challenge:

source="Created by <span class='author'>John Smith</span>, last modified by <span class='editor'> John Smith</span> on 2017/03/24"
author="new author"
editor="new editor"
result=`echo "$source" | sed "s/\(.*author'>\).*\(<\/span>,.*editor'>\).*\(<\/span.*\)/\1$author\2$editor\3/"`

echo $result


问:
Remove web element from the IList <IWebElement> using C# in Selenium
I'm actually trying to remove the element from IList if certain condition occurs, but seems like I'm getting the same list .Count number. Below is my code:

```<code>    [FindsBy(How = How.XPath, Using = "//button[@aria-label='delete']")]
    private IList <IWebElement> _deleteIcons;

******** SOME CODE HERE **********

    for (var i = 0; i<_deleteIcons.Count; i++)
                {
                    if (_deleteIcons[i].GetAttribute("disabled").Contains("true"))
                    {
                        _deleteIcons.RemoveAt(i);
                    }
                }
    Debug.WriteLine(_deleteIcons.Count);
</code>```

Imagine there are 6 total elements in the IList, and 2 of them contain "disabled" =="true" At the end I would like to write to debug console the variable count and see 4.  Currently once the piece of code is run, I still get the same amount of 6 elements in IList.

答:
This is what you need to do before your for loop

```<code>_deleteIcons = [CODE_TO_GET_ELEMENETS].ToList()
</code>```

Then this should work

or you can use Linq to achieve this without the need for this loop:

```<code>_deleteIcons = [CODE_TO_GET_ELEMENETS].Where(x => x.GetAttribute("disabled").Contains("true"))
</code>```

Body:
I'm actually trying to remove the element from IList if certain condition occurs, but seems like I'm getting the same list .Count number. Below is my code:

    [FindsBy(How = How.XPath, Using = "//button[@aria-label='delete']")]
    private IList <IWebElement> _deleteIcons;

******** SOME CODE HERE **********

    for (var i = 0; i<_deleteIcons.Count; i++)
                {
                    if (_deleteIcons[i].GetAttribute("disabled").Contains("true"))
                    {
                        _deleteIcons.RemoveAt(i);
                    }
                }
    Debug.WriteLine(_deleteIcons.Count);

Imagine there are 6 total elements in the IList, and 2 of them contain "disabled" =="true" At the end I would like to write to debug console the variable count and see 4.  Currently once the piece of code is run, I still get the same amount of 6 elements in IList.

Body:
This is what you need to do before your for loop

_deleteIcons = [CODE_TO_GET_ELEMENETS].ToList()

Then this should work

or you can use Linq to achieve this without the need for this loop:

_deleteIcons = [CODE_TO_GET_ELEMENETS].Where(x => x.GetAttribute("disabled").Contains("true"))


问:
Calculate distance between two locations in metre
I have two locations and I want to calculate distance in meter. I wrote some code but it's not working perfectly.

```<code>private void getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2)
{
    Location loc1 = new Location("");
    loc1.setLatitude(lat1);
    loc1.setLongitude(lon1);

    Location loc2 = new Location("");
    loc2.setLatitude(lat2);
    loc2.setLongitude(lon2);

    int R = 6371; // km

    double dLat = deg2rad(lat2-lat1);
    double dLon = deg2rad(lon2-lon1);
    double  a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
                            Math.sin(dLon/2) * Math.sin(dLon/2)
            ;
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double distanceInMeters = R * c;
    Log.e("distanceInMeters",distanceInMeters/10000+"mm");
}

public double  deg2rad(double deg) {
    return deg * (Math.PI/180);
}
</code>```

How can I calculate distance in meter? My goal is, if meter > 200 do something. How can i solve my problem?

答:
Use this method to calculate the distance between two lat/long points & their elevation.</p>

```<code>/**
 * Calculate distance between two points in latitude and longitude taking
 * into account height difference using the Haversine method as its base.
 *
 * Elevation should be in meters. If you are not interested in elevation, pass 0.
 *
 * @return Distance in meters
 */
private double distanceBetween(double lat1, double lat2, double lon1,
                               double lon2, double el1, double el2) {

    final int R = 6371; // Radius of the earth

    double latDistance = Math.toRadians(lat2 - lat1);
    double lonDistance = Math.toRadians(lon2 - lon1);
    double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
            + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
            * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = R * c * 1000; // convert to meters

    double height = el1 - el2;

    distance = Math.pow(distance, 2) + Math.pow(height, 2);

    return Math.sqrt(distance);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two locations and I want to calculate distance in meter. I wrote some code but it's not working perfectly.

private void getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2)
{
    Location loc1 = new Location("");
    loc1.setLatitude(lat1);
    loc1.setLongitude(lon1);

    Location loc2 = new Location("");
    loc2.setLatitude(lat2);
    loc2.setLongitude(lon2);

    int R = 6371; // km

    double dLat = deg2rad(lat2-lat1);
    double dLon = deg2rad(lon2-lon1);
    double  a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
                            Math.sin(dLon/2) * Math.sin(dLon/2)
            ;
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double distanceInMeters = R * c;
    Log.e("distanceInMeters",distanceInMeters/10000+"mm");
}

public double  deg2rad(double deg) {
    return deg * (Math.PI/180);
}

How can I calculate distance in meter? My goal is, if meter > 200 do something. How can i solve my problem?

Body:
Use this method to calculate the distance between two lat/long points & their elevation.

/**
 * Calculate distance between two points in latitude and longitude taking
 * into account height difference using the Haversine method as its base.
 *
 * Elevation should be in meters. If you are not interested in elevation, pass 0.
 *
 * @return Distance in meters
 */
private double distanceBetween(double lat1, double lat2, double lon1,
                               double lon2, double el1, double el2) {

    final int R = 6371; // Radius of the earth

    double latDistance = Math.toRadians(lat2 - lat1);
    double lonDistance = Math.toRadians(lon2 - lon1);
    double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
            + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
            * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = R * c * 1000; // convert to meters

    double height = el1 - el2;

    distance = Math.pow(distance, 2) + Math.pow(height, 2);

    return Math.sqrt(distance);
}


问:
BEM Methology: Component thinking and spacing
I'm still not 100% sure if this is the right way of thinking when working with BEM and in general with a component way of styling stuff.

Let's say we have a simple button.

```<code>.btn {
    //wicked styling
}
</code>```

There's no spacing CSS-Attribute inside. The button is placed inside a component (.comp1). So imho here comes the BEM-Mix:

HTML

```<code><div class="comp1">
    <a href="comp1__btn btn">Please press me</a>
</div>
</code>```

CSS

```<code>// _comp1.scss
.comp1__btn {
    margin-bottom: 20px;
}
</code>```

First question:
What if the .btn has in most cases the same margin-bottom: 20px? Do I have to everytime a BEM-Mix?

```<code>//_comp1.scss
.comp1__btn {
    margin-bottom: 20px;
}

// _comp2.scss
.comp2__btn {
    margin-bottom: 20px;
}
</code>```

Of course I could do a general rule in .btn (margin-bottom: 20px) and then overwrite it in the _comp1.scss etc. But then the order of the scss matters I think you mess up everthing?

What is here the best practice? SASS Extend?

Second question (similar):
For "bigger" components like a panel with other components inside I have like a _verticalrhythm.scss:

```<code>//_verticalrhythm.scss
.comp1,
.comp2,
.comp3 {
    margin-bottom: 40px;
}
</code>```

I recent projects it worked pretty good - but I'm wondering how do you guys are managing these margin stuff.

Thx for answering!

答:
What if the .btn has in most cases the same margin-bottom: 20px? Do I have to everytime a BEM-Mix?

You should not include geometry or positioning styling in general blocks. See https://en.bem.info/methodology/css/#external-geometry-and-positioning for more info.

But then the order of the scss matters I think you mess up everthing?

You may use some BEM tooling to guarantee order. See https://en.bem.info/methodology/build/ for theoretical info and consider https://github.com/gulp-bem/gulp-bem-bundle-builder as ready made implementation.

As for vertical rhythm you may create special block to keep styling at the same place and mix it every time you need it.

Body:
I'm still not 100% sure if this is the right way of thinking when working with BEM and in general with a component way of styling stuff.

Let's say we have a simple button.

.btn {
    //wicked styling
}

There's no spacing CSS-Attribute inside. The button is placed inside a component (.comp1). So imho here comes the BEM-Mix:

HTML

    Please press me

CSS

// _comp1.scss
.comp1__btn {
    margin-bottom: 20px;
}

First question:
What if the .btn has in most cases the same margin-bottom: 20px? Do I have to everytime a BEM-Mix?

//_comp1.scss
.comp1__btn {
    margin-bottom: 20px;
}

// _comp2.scss
.comp2__btn {
    margin-bottom: 20px;
}

Of course I could do a general rule in .btn (margin-bottom: 20px) and then overwrite it in the _comp1.scss etc. But then the order of the scss matters I think you mess up everthing?

What is here the best practice? SASS Extend?

Second question (similar):
For "bigger" components like a panel with other components inside I have like a _verticalrhythm.scss:

//_verticalrhythm.scss
.comp1,
.comp2,
.comp3 {
    margin-bottom: 40px;
}

I recent projects it worked pretty good - but I'm wondering how do you guys are managing these margin stuff.

Thx for answering!


问:
Define a big array of integers in C
I am trying to define an array of N = 1000000000 integers on the heap. My code is the following:

```<code>#define N 1000000000
int A[N];
</code>```

But I am getting the following error when I try to compile my code:

This works for smaller numbers so why isn't it working now?

EDIT: After suggestions, I have defined A like this:

```<code>int *A = malloc(4000000000ULL);
</code>```

I am now getting the error: Initializer element is not constant. It should also be noted that this is a global array.

答:
Your declared array is allocated on the stack, rather than the heap. Memory is allocated on the heap by calling malloc.

This leads to the error you're seeing here because the stack has a maximum size that isn't just bounded by the amount of RAM available. Per the MSDN docs, each thread has a max stack size, and this is configurable (or can be set for a PE by the linker).

In practice, it would be unusual to declare an array like this on the stack.

Title: Define a big array of integers in C

Body:
I am trying to define an array of N = 1000000000 integers on the heap. My code is the following:

#define N 1000000000
int A[N];

But I am getting the following error when I try to compile my code:

This works for smaller numbers so why isn't it working now?

EDIT: After suggestions, I have defined A like this:

int *A = malloc(4000000000ULL);

I am now getting the error: Initializer element is not constant. It should also be noted that this is a global array.


问:
A little help needed catching events being raised inside a seperate thread
To begin, I'm working on a pretty high level file system where I need to be able to (with very pin point accuracy) identify and process files in a timely manner.  With that said, I am working on a system that will be using the FileSystemWatcher.  The whole problem with the watcher though is the fact that it tends to have issues when throwing events when there are large files involved.

To remedy this I'm working on an abstract class that can handle the files individualy once they are created by the file system watcher.

The current road block that I am running into is that my out of process validation on the file is throwing an event, I'm just having problems catching it.

```<code>public abstract class absFile
    {
        public delegate void FileAvailable(object sender, FileEventArgs e);
        public event FileAvailable OnFileAvailable;

        public void isAvailable()
        {
            // Create a new threaded instance of the AvailableCheck private void
            // This method will be run out of process to allow other operations to continue.
            Thread toAvailableCheck = new Thread(new ThreadStart(AvailableCheck));

            // Once the threaded object is created, start it.
            toAvailableCheck.Start();
        }

 private void AvailableCheck()
        {
            // Declaring the file stream toThisFile to be used later with the File.Open
            FileStream toThisFile;

            // Declaring and instantiating the attempt counter for the loop
            int tiAttemptNumber = 0;

            // Declaring the event args for returning the events that are
            // used by this object.

            FileEventArgs toFileEventArgs = new FileEventArgs();

            do {
                try
                {
                    // Attempt to open the file.  If this fails the try
                    // will interrupt the processing and it will be caught.
                    toThisFile = File.Open(this.FilePath, FileMode.Open);

                    // If the file.open method does not fail, the isFileAvailable
                    // property will be set to true by updating the mbIsAvailable
                    // private boolean.
                    mbIsAvailable = true;

                    // populate the file event args to send back
                    // the number of attempts made at the file and the pause lenght
                    toFileEventArgs.Attempts = tiAttemptNumber;
                    toFileEventArgs.Pause = this.AttemptPause / 1000;

                    // This event is called when the file is complete.
                    // The client application will be able to handle this event.
                    OnFileAvailable(this, toFileEventArgs);

                    // close and dispose of the filestream.
                    toThisFile.Close();
                    toThisFile.Dispose();
                }
                catch (Exception toException)
                {
                    // Since the open failed, add 1 to the counter so that
                    // it will eventually time out.
                    tiAttemptNumber++;

                    // Set the isFileAvailable property to false.  This property
                    // will default as false, but as a part of standard, make sure that
                    // if the open fails that the flag IS set to false by updating the
                    // mbIsAvailable private boolean.
                    mbIsAvailable = false;

                    // Put the thread to sleep for the ammount of time specified
                    // by the AttemptPause.  This will give the file time to finish
                    // whatever process it is involved in.
                    Thread.Sleep(this.AttemptPause);
                }

              // Continue to make attempts until either the file is marked as available
              // or the number of current attempts is the same as or greater than the
              // AccessAttempts property.
            } while (!this.isFileAvailable && this.AccessAttempts > tiAttemptNumber);
        }
</code>```

this is the code that I am running as you can see in the private void AvailableCheck, OnfileAvailable is the delegate called passing back this and the file event args.

now i have inherited this abstract class, and i need to be able to catch that event.

```<code>        toWatcher.Created += new FileSystemEventHandler(OnCreated);
</code>```

is called in the main and farther down the code is the following method

```<code>private void OnCreated(object source, FileSystemEventArgs e)
{
    lstStatus.Invoke(new MethodInvoker(delegate {
        lstStatus.Items.Add(DateTime.Now.ToString("g") + " - " + e.Name + " - File Created Event Detected for: " + e.FullPath);
        lstStatus.TopIndex = lstStatus.Items.Count - 1;
        tgtFile ThisFile = new tgtFile(e.FullPath);
        lstStatus.Items.Add(DateTime.Now.ToString("g") + " - " + e.Name + " - Creating tgtFile Object");
    }));
}
</code>```

The instatiation of the tgtFile object is passed the path which makes its way down the pike to the is available method.

as you can see the chance exists for the OnFileAvailable event to be fired from the tgtFile object.

Also as you can see, the the possibility for multiple tgtFile objects to exist in memory at the same time is there as well based on the threading design of the filesystemwatcher.

in my main application then i want to be able to do something like:

```<code>public tgtFile ThisFile;
ThisFile.OnFileAvailable += new EventHandler(OnFileAvailable);
</code>```

but the EventHandler errors out, and that is where I am stuck.

答:
First things first...  Ensure the event is subscribed, before calling it.  Wrap the event call in an IF statement:</p>

```<code>if (OnFileAvailable != null)
    OnFileAvailable(this, toFileEventArgs);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
To begin, I'm working on a pretty high level file system where I need to be able to (with very pin point accuracy) identify and process files in a timely manner.  With that said, I am working on a system that will be using the FileSystemWatcher.  The whole problem with the watcher though is the fact that it tends to have issues when throwing events when there are large files involved.

To remedy this I'm working on an abstract class that can handle the files individualy once they are created by the file system watcher.

The current road block that I am running into is that my out of process validation on the file is throwing an event, I'm just having problems catching it.

public abstract class absFile
    {
        public delegate void FileAvailable(object sender, FileEventArgs e);
        public event FileAvailable OnFileAvailable;

        public void isAvailable()
        {
            // Create a new threaded instance of the AvailableCheck private void
            // This method will be run out of process to allow other operations to continue.
            Thread toAvailableCheck = new Thread(new ThreadStart(AvailableCheck));

            // Once the threaded object is created, start it.
            toAvailableCheck.Start();
        }

 private void AvailableCheck()
        {
            // Declaring the file stream toThisFile to be used later with the File.Open
            FileStream toThisFile;

            // Declaring and instantiating the attempt counter for the loop
            int tiAttemptNumber = 0;

            // Declaring the event args for returning the events that are
            // used by this object.

            FileEventArgs toFileEventArgs = new FileEventArgs();

            do {
                try
                {
                    // Attempt to open the file.  If this fails the try
                    // will interrupt the processing and it will be caught.
                    toThisFile = File.Open(this.FilePath, FileMode.Open);

                    // If the file.open method does not fail, the isFileAvailable
                    // property will be set to true by updating the mbIsAvailable
                    // private boolean.
                    mbIsAvailable = true;

                    // populate the file event args to send back
                    // the number of attempts made at the file and the pause lenght
                    toFileEventArgs.Attempts = tiAttemptNumber;
                    toFileEventArgs.Pause = this.AttemptPause / 1000;

                    // This event is called when the file is complete.
                    // The client application will be able to handle this event.
                    OnFileAvailable(this, toFileEventArgs);

                    // close and dispose of the filestream.
                    toThisFile.Close();
                    toThisFile.Dispose();
                }
                catch (Exception toException)
                {
                    // Since the open failed, add 1 to the counter so that
                    // it will eventually time out.
                    tiAttemptNumber++;

                    // Set the isFileAvailable property to false.  This property
                    // will default as false, but as a part of standard, make sure that
                    // if the open fails that the flag IS set to false by updating the
                    // mbIsAvailable private boolean.
                    mbIsAvailable = false;

                    // Put the thread to sleep for the ammount of time specified
                    // by the AttemptPause.  This will give the file time to finish
                    // whatever process it is involved in.
                    Thread.Sleep(this.AttemptPause);
                }

              // Continue to make attempts until either the file is marked as available
              // or the number of current attempts is the same as or greater than the
              // AccessAttempts property.
            } while (!this.isFileAvailable && this.AccessAttempts > tiAttemptNumber);
        }

this is the code that I am running as you can see in the private void AvailableCheck, OnfileAvailable is the delegate called passing back this and the file event args.

now i have inherited this abstract class, and i need to be able to catch that event.

        toWatcher.Created += new FileSystemEventHandler(OnCreated);

is called in the main and farther down the code is the following method

private void OnCreated(object source, FileSystemEventArgs e)
{
    lstStatus.Invoke(new MethodInvoker(delegate {
        lstStatus.Items.Add(DateTime.Now.ToString("g") + " - " + e.Name + " - File Created Event Detected for: " + e.FullPath);
        lstStatus.TopIndex = lstStatus.Items.Count - 1;
        tgtFile ThisFile = new tgtFile(e.FullPath);
        lstStatus.Items.Add(DateTime.Now.ToString("g") + " - " + e.Name + " - Creating tgtFile Object");
    }));
}

The instatiation of the tgtFile object is passed the path which makes its way down the pike to the is available method.

as you can see the chance exists for the OnFileAvailable event to be fired from the tgtFile object.

Also as you can see, the the possibility for multiple tgtFile objects to exist in memory at the same time is there as well based on the threading design of the filesystemwatcher.

in my main application then i want to be able to do something like:

public tgtFile ThisFile;
ThisFile.OnFileAvailable += new EventHandler(OnFileAvailable);

but the EventHandler errors out, and that is where I am stuck.

Body:
First things first...  Ensure the event is subscribed, before calling it.  Wrap the event call in an IF statement:

if (OnFileAvailable != null)
    OnFileAvailable(this, toFileEventArgs);


问:
Finding Symmetric Difference in an array test fail
sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]) should return [1, 4, 5]
The expected return is shown above. But I couldn't find why it fails this test. What kind of fix is needed to code below?

function sym(args) {
 //debugger;
 var arr=Array.from(arguments);
  var resArr=[];

  arr.forEach(function(arrVal){
        var c=0;

      arrVal.forEach(function(val,index){
      console.log("arrVal",arrVal,"index",index,"val",val,"|",arrVal.slice(index+1-c));
        if(index<arrVal.length-1 && arrVal.slice(index+1-c).indexOf(val)!==-1){
        console.log("here");

          arrVal.splice(index-c,1);
          c++;
        }
                    console.log("arrVal",arrVal,"index",index,"|",arrVal);

      });

      resArr.push(arrVal);
    });
  console.log(resArr);

  resArr=resArr.reduce(function(acc,curr){
   return acc.concat(curr.filter(function(val){
     var notContains=acc.indexOf(val)==-1;
     if(!notContains)
       acc.splice(acc.indexOf(val),1);
     return notContains;
    }));
  },[]);

 console.log(resArr);
  return resArr;
}

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]);```

答:
Use Sets. Their support should be sufficent. Extend their prototype and benefit from meaningful methods (union, intersection and difference taken from MDN):

```<code>Set.prototype.union = function(setB) {
    var union = new Set(this);
    for (var elem of setB) {
        union.add(elem);
    }
    return union;
}

Set.prototype.intersection = function(setB) {
    var intersection = new Set();
    for (var elem of setB) {
        if (this.has(elem)) {
            intersection.add(elem);
        }
    }
    return intersection;
}

Set.prototype.difference = function(setB) {
    var difference = new Set(this);
    for (var elem of setB) {
        difference.delete(elem);
    }
    return difference;
}

Set.prototype.symmetricDifference = function(setB) {
    return this.union(setB).difference(this.intersection(setB));
}

var set1 = new Set([1, 1, 2, 5]);
var set2 = new Set([2, 2, 3, 5]);
var set3 = new Set([3, 4, 5, 5]);
var result = set1.symmetricDifference(set2).symmetricDifference(set3);
console.log(result); // as Set
console.log([...result]); // as Array
</code>```

Body:
Use Sets. Their support should be sufficent. Extend their prototype and benefit from meaningful methods (union, intersection and difference taken from MDN):

Set.prototype.union = function(setB) {
    var union = new Set(this);
    for (var elem of setB) {
        union.add(elem);
    }
    return union;
}

Set.prototype.intersection = function(setB) {
    var intersection = new Set();
    for (var elem of setB) {
        if (this.has(elem)) {
            intersection.add(elem);
        }
    }
    return intersection;
}

Set.prototype.difference = function(setB) {
    var difference = new Set(this);
    for (var elem of setB) {
        difference.delete(elem);
    }
    return difference;
}

Set.prototype.symmetricDifference = function(setB) {
    return this.union(setB).difference(this.intersection(setB));
}

var set1 = new Set([1, 1, 2, 5]);
var set2 = new Set([2, 2, 3, 5]);
var set3 = new Set([3, 4, 5, 5]);
var result = set1.symmetricDifference(set2).symmetricDifference(set3);
console.log(result); // as Set
console.log([...result]); // as Array


问:
Electron error on canceling file open dialog
When I press the cancel button on file open dialog (code below) I receive the following error:

```<code>A JavaScript error occurred in the main process

Uncaught Exception:
TypeError: Error processing argument -1.
    at TypeError (native)
    at [object Object].Object.defineProperty.set (/Applications/Electron.app/Contents/Resources/atom.asar/browser/api/lib/web-contents.js:92:24)
    at main.js:37:20
    at Function.wrappedCallback (/Applications/Electron.app/Contents/Resources/atom.asar/browser/api/lib/dialog.js:80:16)
</code>```

The error is presented as a modal popup:

I have only tested on a Mac so far.

My code is as follows:

The main process code that handles the creation of dialog is as follows:

```<code>import electron, { ipcMain } from 'electron'

const app = electron.app
const BrowserWindow = electron.BrowserWindow

electron.crashReporter.start()

let mainWindow = null

app.on('window-all-closed', () => {
  if (process.platform != 'darwin') app.quit()
})

app.on('ready', () => {

  mainWindow = new BrowserWindow({
    width: 800,
    height: 600
  })

  mainWindow.loadURL(`file://${__dirname}/index.html`)
  mainWindow.webContents.openDevTools()

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  ipcMain.on('file:open', (e, arg) => {
    electron.dialog.showOpenDialog(mainWindow, {
      properties: ['openFile'],
      filters: [{
        name: 'Outlines',
        extensions: ['pxo']
      }]
    }, (filePathList) => {
      debugger
      e.returnValue = filePathList
    })
  })

})
</code>```

My debugger statement is never reached. Also the code works fine when some files are actually selected, and only fails if cancel is pressed.

The code (ES6+JSX) that triggers the IPC call is as follows:

```<code>class Welcome extends React.Component {

  render() {
    const styles = this.getStyles()

    return (
      <div style={styles.outerContainer}>
              <a style={styles.btnSetLink} onClick={this.initFileSelection.bind(this)}>
                Open File
              </a>
      </div>
    )
  }

  initFileSelection() {
    const filePathList = ipcRenderer.sendSync('file:open')
  }

  ...
</code>```

The code is processed through babel 6. My .babelrc is as follows:

```<code>{
  "presets": ["react", "es2015"]
}
</code>```

Version of electron: v0.35.1.

Versions of babel dependencies:

```<code>├─┬ babel-preset-es2015@6.3.13
│ ├── babel-plugin-check-es2015-constants@6.3.13
│ ├── babel-plugin-transform-es2015-arrow-functions@6.3.13
│ ├── babel-plugin-transform-es2015-block-scoped-functions@6.3.13
│ ├─┬ babel-plugin-transform-es2015-block-scoping@6.3.13
│ │ ├─┬ babel-template@6.3.13
│ │ │ └── babylon@6.3.18
│ │ ├─┬ babel-traverse@6.3.19
│ │ │ ├── babylon@6.3.18
│ │ │ ├── globals@8.15.0
│ │ │ └─┬ repeating@1.1.3
│ │ │   └─┬ is-finite@1.0.1
│ │ │     └── number-is-nan@1.0.0
│ │ └─┬ babel-types@6.3.18
│ │   ├── esutils@2.0.2
│ │   └── to-fast-properties@1.0.1
│ ├─┬ babel-plugin-transform-es2015-classes@6.3.15
│ │ ├── babel-helper-define-map@6.3.13
│ │ ├── babel-helper-function-name@6.3.15
│ │ ├── babel-helper-optimise-call-expression@6.3.13
│ │ ├── babel-helper-replace-supers@6.3.13
│ │ └── babel-messages@6.3.18
│ ├── babel-plugin-transform-es2015-computed-properties@6.3.13
│ ├── babel-plugin-transform-es2015-destructuring@6.3.15
│ ├── babel-plugin-transform-es2015-for-of@6.3.13
│ ├── babel-plugin-transform-es2015-function-name@6.3.19
│ ├── babel-plugin-transform-es2015-literals@6.3.13
│ ├─┬ babel-plugin-transform-es2015-modules-commonjs@6.3.16
│ │ └── babel-plugin-transform-strict-mode@6.3.13
│ ├── babel-plugin-transform-es2015-object-super@6.3.13
│ ├─┬ babel-plugin-transform-es2015-parameters@6.3.18
│ │ ├─┬ babel-helper-call-delegate@6.3.13
│ │ │ └── babel-helper-hoist-variables@6.3.13
│ │ └── babel-helper-get-function-arity@6.3.13
│ ├── babel-plugin-transform-es2015-shorthand-properties@6.3.13
│ ├── babel-plugin-transform-es2015-spread@6.3.14
│ ├─┬ babel-plugin-transform-es2015-sticky-regex@6.3.13
│ │ └── babel-helper-regex@6.3.13
│ ├── babel-plugin-transform-es2015-template-literals@6.3.13
│ ├── babel-plugin-transform-es2015-typeof-symbol@6.3.13
│ ├─┬ babel-plugin-transform-es2015-unicode-regex@6.3.13
│ │ └─┬ regexpu@1.3.0
│ │   ├── esprima@2.7.1
│ │   ├─┬ recast@0.10.33
│ │   │ ├── ast-types@0.8.12
│ │   │ └── esprima-fb@15001.1001.0-dev-harmony-fb
│ │   ├── regenerate@1.2.1
│ │   ├── regjsgen@0.2.0
│ │   └─┬ regjsparser@0.1.5
│ │     └── jsesc@0.5.0
│ └─┬ babel-plugin-transform-regenerator@6.3.18
│   ├── babel-core@6.3.17
│   ├── babel-plugin-syntax-async-functions@6.3.13
│   ├── babylon@6.3.18
│   └── private@0.1.6
├─┬ babel-preset-react@6.3.13
│ ├── babel-plugin-syntax-flow@6.3.13
│ ├── babel-plugin-syntax-jsx@6.3.13
│ ├── babel-plugin-transform-flow-strip-types@6.3.15
│ ├── babel-plugin-transform-react-display-name@6.3.13
│ ├─┬ babel-plugin-transform-react-jsx@6.3.13
│ │ └── babel-helper-builder-react-jsx@6.3.13
│ └── babel-plugin-transform-react-jsx-source@6.3.13
├─┬ babel-register@6.3.13
│ ├─┬ babel-core@6.3.17
│ │ ├─┬ babel-code-frame@6.3.13
│ │ │ ├─┬ chalk@1.1.1
│ │ │ │ ├── ansi-styles@2.1.0
│ │ │ │ ├── escape-string-regexp@1.0.3
│ │ │ │ ├─┬ has-ansi@2.0.0
│ │ │ │ │ └── ansi-regex@2.0.0
│ │ │ │ ├── strip-ansi@3.0.0
│ │ │ │ └── supports-color@2.0.0
│ │ │ ├── js-tokens@1.0.1
│ │ │ └─┬ line-numbers@0.2.0
│ │ │   └── left-pad@0.0.3
│ │ ├─┬ babel-generator@6.3.19
│ │ │ ├─┬ detect-indent@3.0.1
│ │ │ │ ├── get-stdin@4.0.1
│ │ │ │ └── minimist@1.2.0
│ │ │ ├── is-integer@1.0.6
│ │ │ └── trim-right@1.0.1
│ │ ├── babel-helpers@6.3.13
│ │ ├── babylon@6.3.18
│ │ ├── convert-source-map@1.1.2
│ │ ├─┬ debug@2.2.0
│ │ │ └── ms@0.7.1
│ │ ├── json5@0.4.0
│ │ ├─┬ minimatch@2.0.10
│ │ │ └─┬ brace-expansion@1.1.2
│ │ │   ├── balanced-match@0.3.0
│ │ │   └── concat-map@0.0.1
│ │ ├── path-is-absolute@1.0.0
│ │ ├── shebang-regex@1.0.0
│ │ ├── slash@1.0.0
│ │ └── source-map@0.5.3
│ ├── babel-runtime@5.8.34
│ ├── core-js@1.2.6
│ ├─┬ home-or-tmp@1.0.0
│ │ ├── os-tmpdir@1.0.1
│ │ └── user-home@1.1.1
│ ├── lodash@3.10.1
│ ├── path-exists@1.0.0
│ └─┬ source-map-support@0.2.10
│   └─┬ source-map@0.1.32
│     └── amdefine@1.0.0
</code>```

Any help resolving the error would be highly appreciated.

答:
i use this to handle it</p>

```<code>process.on('uncaughtException', function (exception) {
   // handle or ignore error
});
</code>```

Body:
When I press the cancel button on file open dialog (code below) I receive the following error:

A JavaScript error occurred in the main process

Uncaught Exception:
TypeError: Error processing argument -1.
    at TypeError (native)
    at [object Object].Object.defineProperty.set (/Applications/Electron.app/Contents/Resources/atom.asar/browser/api/lib/web-contents.js:92:24)
    at main.js:37:20
    at Function.wrappedCallback (/Applications/Electron.app/Contents/Resources/atom.asar/browser/api/lib/dialog.js:80:16)

The error is presented as a modal popup:

I have only tested on a Mac so far.

My code is as follows:

The main process code that handles the creation of dialog is as follows:

import electron, { ipcMain } from 'electron'

const app = electron.app
const BrowserWindow = electron.BrowserWindow

electron.crashReporter.start()

let mainWindow = null

app.on('window-all-closed', () => {
  if (process.platform != 'darwin') app.quit()
})

app.on('ready', () => {

  mainWindow = new BrowserWindow({
    width: 800,
    height: 600
  })

  mainWindow.loadURL(`file://${__dirname}/index.html`)
  mainWindow.webContents.openDevTools()

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  ipcMain.on('file:open', (e, arg) => {
    electron.dialog.showOpenDialog(mainWindow, {
      properties: ['openFile'],
      filters: [{
        name: 'Outlines',
        extensions: ['pxo']
      }]
    }, (filePathList) => {
      debugger
      e.returnValue = filePathList
    })
  })

})

My debugger statement is never reached. Also the code works fine when some files are actually selected, and only fails if cancel is pressed.

The code (ES6+JSX) that triggers the IPC call is as follows:

class Welcome extends React.Component {

  render() {
    const styles = this.getStyles()

    return (

                Open File

    )
  }

  initFileSelection() {
    const filePathList = ipcRenderer.sendSync('file:open')
  }

  ...

The code is processed through babel 6. My .babelrc is as follows:

{
  "presets": ["react", "es2015"]
}

Version of electron: v0.35.1.

Versions of babel dependencies:

├─┬ babel-preset-es2015@6.3.13
│ ├── babel-plugin-check-es2015-constants@6.3.13
│ ├── babel-plugin-transform-es2015-arrow-functions@6.3.13
│ ├── babel-plugin-transform-es2015-block-scoped-functions@6.3.13
│ ├─┬ babel-plugin-transform-es2015-block-scoping@6.3.13
│ │ ├─┬ babel-template@6.3.13
│ │ │ └── babylon@6.3.18
│ │ ├─┬ babel-traverse@6.3.19
│ │ │ ├── babylon@6.3.18
│ │ │ ├── globals@8.15.0
│ │ │ └─┬ repeating@1.1.3
│ │ │   └─┬ is-finite@1.0.1
│ │ │     └── number-is-nan@1.0.0
│ │ └─┬ babel-types@6.3.18
│ │   ├── esutils@2.0.2
│ │   └── to-fast-properties@1.0.1
│ ├─┬ babel-plugin-transform-es2015-classes@6.3.15
│ │ ├── babel-helper-define-map@6.3.13
│ │ ├── babel-helper-function-name@6.3.15
│ │ ├── babel-helper-optimise-call-expression@6.3.13
│ │ ├── babel-helper-replace-supers@6.3.13
│ │ └── babel-messages@6.3.18
│ ├── babel-plugin-transform-es2015-computed-properties@6.3.13
│ ├── babel-plugin-transform-es2015-destructuring@6.3.15
│ ├── babel-plugin-transform-es2015-for-of@6.3.13
│ ├── babel-plugin-transform-es2015-function-name@6.3.19
│ ├── babel-plugin-transform-es2015-literals@6.3.13
│ ├─┬ babel-plugin-transform-es2015-modules-commonjs@6.3.16
│ │ └── babel-plugin-transform-strict-mode@6.3.13
│ ├── babel-plugin-transform-es2015-object-super@6.3.13
│ ├─┬ babel-plugin-transform-es2015-parameters@6.3.18
│ │ ├─┬ babel-helper-call-delegate@6.3.13
│ │ │ └── babel-helper-hoist-variables@6.3.13
│ │ └── babel-helper-get-function-arity@6.3.13
│ ├── babel-plugin-transform-es2015-shorthand-properties@6.3.13
│ ├── babel-plugin-transform-es2015-spread@6.3.14
│ ├─┬ babel-plugin-transform-es2015-sticky-regex@6.3.13
│ │ └── babel-helper-regex@6.3.13
│ ├── babel-plugin-transform-es2015-template-literals@6.3.13
│ ├── babel-plugin-transform-es2015-typeof-symbol@6.3.13
│ ├─┬ babel-plugin-transform-es2015-unicode-regex@6.3.13
│ │ └─┬ regexpu@1.3.0
│ │   ├── esprima@2.7.1
│ │   ├─┬ recast@0.10.33
│ │   │ ├── ast-types@0.8.12
│ │   │ └── esprima-fb@15001.1001.0-dev-harmony-fb
│ │   ├── regenerate@1.2.1
│ │   ├── regjsgen@0.2.0
│ │   └─┬ regjsparser@0.1.5
│ │     └── jsesc@0.5.0
│ └─┬ babel-plugin-transform-regenerator@6.3.18
│   ├── babel-core@6.3.17
│   ├── babel-plugin-syntax-async-functions@6.3.13
│   ├── babylon@6.3.18
│   └── private@0.1.6
├─┬ babel-preset-react@6.3.13
│ ├── babel-plugin-syntax-flow@6.3.13
│ ├── babel-plugin-syntax-jsx@6.3.13
│ ├── babel-plugin-transform-flow-strip-types@6.3.15
│ ├── babel-plugin-transform-react-display-name@6.3.13
│ ├─┬ babel-plugin-transform-react-jsx@6.3.13
│ │ └── babel-helper-builder-react-jsx@6.3.13
│ └── babel-plugin-transform-react-jsx-source@6.3.13
├─┬ babel-register@6.3.13
│ ├─┬ babel-core@6.3.17
│ │ ├─┬ babel-code-frame@6.3.13
│ │ │ ├─┬ chalk@1.1.1
│ │ │ │ ├── ansi-styles@2.1.0
│ │ │ │ ├── escape-string-regexp@1.0.3
│ │ │ │ ├─┬ has-ansi@2.0.0
│ │ │ │ │ └── ansi-regex@2.0.0
│ │ │ │ ├── strip-ansi@3.0.0
│ │ │ │ └── supports-color@2.0.0
│ │ │ ├── js-tokens@1.0.1
│ │ │ └─┬ line-numbers@0.2.0
│ │ │   └── left-pad@0.0.3
│ │ ├─┬ babel-generator@6.3.19
│ │ │ ├─┬ detect-indent@3.0.1
│ │ │ │ ├── get-stdin@4.0.1
│ │ │ │ └── minimist@1.2.0
│ │ │ ├── is-integer@1.0.6
│ │ │ └── trim-right@1.0.1
│ │ ├── babel-helpers@6.3.13
│ │ ├── babylon@6.3.18
│ │ ├── convert-source-map@1.1.2
│ │ ├─┬ debug@2.2.0
│ │ │ └── ms@0.7.1
│ │ ├── json5@0.4.0
│ │ ├─┬ minimatch@2.0.10
│ │ │ └─┬ brace-expansion@1.1.2
│ │ │   ├── balanced-match@0.3.0
│ │ │   └── concat-map@0.0.1
│ │ ├── path-is-absolute@1.0.0
│ │ ├── shebang-regex@1.0.0
│ │ ├── slash@1.0.0
│ │ └── source-map@0.5.3
│ ├── babel-runtime@5.8.34
│ ├── core-js@1.2.6
│ ├─┬ home-or-tmp@1.0.0
│ │ ├── os-tmpdir@1.0.1
│ │ └── user-home@1.1.1
│ ├── lodash@3.10.1
│ ├── path-exists@1.0.0
│ └─┬ source-map-support@0.2.10
│   └─┬ source-map@0.1.32
│     └── amdefine@1.0.0

Any help resolving the error would be highly appreciated.

Body:
i use this to handle it

process.on('uncaughtException', function (exception) {
   // handle or ignore error
});


问:
edit timer made in a main form via sub form in c#
I have a timer in the main form, yet I want to change the interval of the timer via the second sub form. However, the within the subform there is a 'System.NullReferenceException' upon taking the textbox text, the code is visible below. Any suggestions, examples, tips or help will be much appreciated.

Main Form with the timer (added via designer);

```<code>public partial class Booyaa : Form
{
    private void Booyaa_Load(object sender, EventArgs e)
    {
        BooyaaTimer.Interval = 45 * 60 * 1000); // 45 mins
        BooyaaTimer.Tick += new EventHandler(BooyaaTimer_Tick);
        BooyaaTimer.Start();

        if (!Properties.Settings.Default.SettingShutdown)
        {
            MessageBox.Show("Time");
            GetPass pass = new GetPass();
            DialogResult result = pass.ShowDialog();
            if (result == DialogResult.OK)
            {
                Properties.Settings.Default.SettingShutdown = true;
                Properties.Settings.Default.Save();
            }
            else
            {
                Close();
            }
        }
    }
}
</code>```

Other sub form for timer control:

```<code>public partial class TimerControl : Form
{
    public static Timer BooyaaTimer { get; internal set; }

    public TimerControl()
    {
        InitializeComponent();
    }

    private void btn_confirm_Click(object sender, EventArgs e)
    {
        BooyaaTimer.Interval = Int32.Parse(textBox1.Text);
    }
}
</code>```

答:
As pointed by @gusman, check in the main form Booyaa form to make sure BooyaaTimer is there (that is it is not null). If you did not drag-drop timer control on to form the please make sure you call BooyaaTimer = new Timer() in form's constructor.

So if things are alright till here, you are not passing timer to the sub-form. If GetPass is actually TimerControl (which I suspect), then you need to modify Booyaa_Load call like this:

```<code>MessageBox.Show("Time");
GetPass pass = new GetPass();
/*****-----------******/
pass.BooyaaTimer = BooyaaTimer;//set sub-form's property

DialogResult result = pass.ShowDialog();
</code>```

Also, in sub-form it does not hurt to check for nulls before using the objects that will be set from some other place.

```<code>if(BooyaaTimer!=null)
  BooyaaTimer.Interval = Int32.Parse(textBox1.Text);
</code>```

Next, try using int.TryParse.

Body:
I have a timer in the main form, yet I want to change the interval of the timer via the second sub form. However, the within the subform there is a 'System.NullReferenceException' upon taking the textbox text, the code is visible below. Any suggestions, examples, tips or help will be much appreciated.

Main Form with the timer (added via designer);

public partial class Booyaa : Form
{
    private void Booyaa_Load(object sender, EventArgs e)
    {
        BooyaaTimer.Interval = 45 * 60 * 1000); // 45 mins
        BooyaaTimer.Tick += new EventHandler(BooyaaTimer_Tick);
        BooyaaTimer.Start();

        if (!Properties.Settings.Default.SettingShutdown)
        {
            MessageBox.Show("Time");
            GetPass pass = new GetPass();
            DialogResult result = pass.ShowDialog();
            if (result == DialogResult.OK)
            {
                Properties.Settings.Default.SettingShutdown = true;
                Properties.Settings.Default.Save();
            }
            else
            {
                Close();
            }
        }
    }
}

Other sub form for timer control:

public partial class TimerControl : Form
{
    public static Timer BooyaaTimer { get; internal set; }

    public TimerControl()
    {
        InitializeComponent();
    }

    private void btn_confirm_Click(object sender, EventArgs e)
    {
        BooyaaTimer.Interval = Int32.Parse(textBox1.Text);
    }
}

Body:
As pointed by @gusman, check in the main form Booyaa form to make sure BooyaaTimer is there (that is it is not null). If you did not drag-drop timer control on to form the please make sure you call BooyaaTimer = new Timer() in form's constructor.

So if things are alright till here, you are not passing timer to the sub-form. If GetPass is actually TimerControl (which I suspect), then you need to modify Booyaa_Load call like this:

MessageBox.Show("Time");
GetPass pass = new GetPass();
/*****-----------******/
pass.BooyaaTimer = BooyaaTimer;//set sub-form's property

DialogResult result = pass.ShowDialog();

Also, in sub-form it does not hurt to check for nulls before using the objects that will be set from some other place.

if(BooyaaTimer!=null)
  BooyaaTimer.Interval = Int32.Parse(textBox1.Text);

Next, try using int.TryParse.


问:
p5.js && ecmascript6 notation
I want use p5.js function inside a class with ECMAScript notation.

How to fix this code?

```<code>class Sketch {
    constructor(p, params) {
        // generate vars use in class with object
        if (typeof params !== 'undefined') {
            for (let key in params) this[key] = params[key];
        }
        // p5.js object
        this.p = p;
    }
    // p5.js setup method
    setup() {
        this.p.createCanvas();
    }
    // p5.js draw method
    draw() {
    }
}
sketch = new Sketch(p5,{});
</code>```

Error:

this.p.createCanvas is not a function

答:
The docs say that you must instantiate p5 and pass your initialiser function that creates the method on p:

```<code>const myp5 = new p5(p => {
    p.setup = () => {
        p.createCanvas();
    };
    …
});
</code>```

See also the Global and instance mode tutorial.

This is a really weird construction however. Although it's not documented, in ES6 it should be possible to subclass p5:

```<code>class Sketch extends p5 {
    constructor(params) {
        super(p => {
            // do any setup in here that needs to happen before the sketch starts
            // (e.g. create event handlers)
            // `p` refers to the instance that becomes `this` after the super() call
            // so for example
            if (typeof params == 'object' && params != null)
                for (let key in params)
                    p[key] = params[key];
        });

        // `this` itself is the p5.js object
    }
    // p5.js setup method
    setup() {
        this.createCanvas();
    }
    // p5.js draw method
    draw() {
    }
}
const myp5 = new Sketch({});
</code>```

Notice that the p5 constructor will invoke your methods; you don't have to do myp5.setup() yourself.

Title: p5.js && ecmascript6 notation

Body:
I want use p5.js function inside a class with ECMAScript notation.

How to fix this code?

class Sketch {
    constructor(p, params) {
        // generate vars use in class with object
        if (typeof params !== 'undefined') {
            for (let key in params) this[key] = params[key];
        }
        // p5.js object
        this.p = p;
    }
    // p5.js setup method
    setup() {
        this.p.createCanvas();
    }
    // p5.js draw method
    draw() {
    }
}
sketch = new Sketch(p5,{});

Error:

this.p.createCanvas is not a function

Body:
The docs say that you must instantiate p5 and pass your initialiser function that creates the method on p:

const myp5 = new p5(p => {
    p.setup = () => {
        p.createCanvas();
    };
    …
});

See also the Global and instance mode tutorial.

This is a really weird construction however. Although it's not documented, in ES6 it should be possible to subclass p5:

class Sketch extends p5 {
    constructor(params) {
        super(p => {
            // do any setup in here that needs to happen before the sketch starts
            // (e.g. create event handlers)
            // `p` refers to the instance that becomes `this` after the super() call
            // so for example
            if (typeof params == 'object' && params != null)
                for (let key in params)
                    p[key] = params[key];
        });

        // `this` itself is the p5.js object
    }
    // p5.js setup method
    setup() {
        this.createCanvas();
    }
    // p5.js draw method
    draw() {
    }
}
const myp5 = new Sketch({});

Notice that the p5 constructor will invoke your methods; you don't have to do myp5.setup() yourself.


问:
Laravel/PHP/HHVM error log showing line number -1
I'm using Laravel 5.4, php 5.5.9 and HHVM 3.15.3
I'm getting error logs, but showing line number is -1, like:

Fatal error: Class undefined: App\Http\Controllers\XXXX in XXXX/XXXXController.php on line -1

Hoping to get some help on this.
Thanks.

答: Your probably trying to use a class you forgot to import at the top. Hard to tell with no code though.</p>


问:
Shared Preferences - max length of a single value
I am storing String into shared preferences, but I wasn't able to find out maximal length of string I can store. Do you know this value?</p>

答:
When I trying to save the max length string into the SharedPreferences in my device, it throw a Memory Exception when SharedPreferences data exceed 1.42 MB.

So if you have more than 1.42 MB data size to save its better to save use SQLite database.

According to developer.android.com:

If you have a relatively small collection of key-values that you'd
  like to save, you should use the SharedPreferences APIs.


问:
simple dynamic allocation question
What is the difference between this:-

```<code>width = new int;
</code>```

And this:-

```<code>int width;
</code>```

i.e. of what use is the dynamic allocation in the first code?

答:
What you meant is probably:

```<code>int* w1 = new int;
int  w2;
</code>```

The first is allocated on the heap and you have to take care of thememory with operator delete.

The second is on the stack and ceases to exist after it gets out of the scope (so you do not have to take care of the memory yourself).

Title: simple dynamic allocation question

Body:
What is the difference between this:-

width = new int;

And this:-

int width;

i.e. of what use is the dynamic allocation in the first code?

Body:
What you meant is probably:

int* w1 = new int;
int  w2;

The first is allocated on the heap and you have to take care of thememory with operator delete.

The second is on the stack and ceases to exist after it gets out of the scope (so you do not have to take care of the memory yourself).


问:
Can I match class that implements annotated Interface with knowledge only about annotation type?
just like in the topic. I have my resource class :

```<code>public class HelloWorldEndpoint implements IRest {

    public String sayHello()
    {
      return "Hello world!";
  }

}
</code>```

And Interface :

```<code>@Path("/helloworld")
public interface IRest {

    @GET
    @Path("/hello")
    String sayHello();
}
</code>```

Is it possible to match sayHello() from HelloWorldEndpoint using only @Path class annotation? This is very specific example of resource class implementation, but it shows that it is possible to have REST endpoint without any annotation in class.. I've tried with inheritsAnnotation() and isAnnotatedWith() but it's not working that way unfortunatly.  My goal is to find all resource classes :)

答:
Annotations of interfaces are not inherited in accordance to the Java Langauge specification. They are neither exposed by the reflection API, for example.

In order to discover the annotation, you can manually travers the class hierarchy and look for the annotation in question. This is possible by hasSuperType(isAnnotatedWith(...)). Note that this is a rather expensive matching condition.

Body:
just like in the topic. I have my resource class :

public class HelloWorldEndpoint implements IRest {

    public String sayHello()
    {
      return "Hello world!";
  }

}

And Interface :

@Path("/helloworld")
public interface IRest {

    @GET
    @Path("/hello")
    String sayHello();
}

Is it possible to match sayHello() from HelloWorldEndpoint using only @Path class annotation? This is very specific example of resource class implementation, but it shows that it is possible to have REST endpoint without any annotation in class.. I've tried with inheritsAnnotation() and isAnnotatedWith() but it's not working that way unfortunatly.  My goal is to find all resource classes :)


问:
Swift tableview load more data
I am implementing a method to load more results returned from my sql server when the table view reaches the bottom.

The issue I am facing is that the getData() method is called in a loop and I cant figure out why.

The log repeats the output below until the application is terminated:

Index Path:12

  Last Element: 12

  Index Path:12

  Last Element: 12

I suspect its one of those which is creating the loop but I can't work out what to change.

Any assistance with this is much appreciated

This is my willDisplayCell method:

  func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let lastElement = id.count - 1
        if indexPath.row == lastElement {

            print("Index Path:\(indexPath.row)")
            print("Last Element: \(lastElement)")
                limitf = "\(lastElement)"
                getData()
        }
    }
```

<p>and the function I am using to get the data:</p>

<pre class="lang-html prettyprint-override"><code> func getData(){

        let defaults = UserDefaults.standard
        let userID =  defaults.string(forKey: "id")

        if(limitf == ""){
        id.removeAll()
        firstname.removeAll()
        lastname.removeAll()
        fbid.removeAll()
        image.removeAll()
        totalratings.removeAll()
        mobile.removeAll()
        }

        let url = NSURL(string: "https://www.****/getapplications.php?&jobid=\(jobid)&limitf=\(limitf)")
       // print(url!)
        let task = URLSession.shared.dataTask(with: url as! URL) { (data, response, error) -> Void in
            if let urlContent = data {
                do {
                    if let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as? [[String:AnyObject]] {
                        var i = 0
                        while i < jsonResult.count {

                            self.id.append(jsonResult[i]["id"]! as! String)
                            self.firstname.append(jsonResult[i]["firstname"]! as! String)
                            self.lastname.append(jsonResult[i]["lastname"]! as! String)
                            self.fbid.append(jsonResult[i]["fbid"]! as! String)
                            self.image.append(jsonResult[i]["image"]! as! String)
                            self.totalratings.append(jsonResult[i]["totalratings"]! as! String)
                            self.mobile.append(jsonResult[i]["mobile"]! as! String)

                            i = i + 1
                        }
                    }
                } catch {
                    print("JSON serialization failed")
                }
            } else {
                print("ERROR FOUND HERE")
            }

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }

        }

        task.resume()

    }
}
</code>```

答:
If you only have 12 records on the server, and the 12th record is visible on screen, then every time it is displayed, getData() will be called. The server will probably return no more records (so the count will remain 12) and the call to .reloadData() will cause the 12 records to be displayed again,  which will call getData() again on the 12th,  and so on ...

You should not call reloadData() when no new records were received.

Title: Swift tableview load more data

Body:
I am implementing a method to load more results returned from my sql server when the table view reaches the bottom.

The issue I am facing is that the getData() method is called in a loop and I cant figure out why.

The log repeats the output below until the application is terminated:

Index Path:12

  Last Element: 12

  Index Path:12

  Last Element: 12

I suspect its one of those which is creating the loop but I can't work out what to change.

Any assistance with this is much appreciated

This is my willDisplayCell method:

  func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let lastElement = id.count - 1
        if indexPath.row == lastElement {

            print("Index Path:\(indexPath.row)")
            print("Last Element: \(lastElement)")
                limitf = "\(lastElement)"
                getData()
        }
    }

and the function I am using to get the data:

 func getData(){

        let defaults = UserDefaults.standard
        let userID =  defaults.string(forKey: "id")

        if(limitf == ""){
        id.removeAll()
        firstname.removeAll()
        lastname.removeAll()
        fbid.removeAll()
        image.removeAll()
        totalratings.removeAll()
        mobile.removeAll()
        }

        let url = NSURL(string: "https://www.****/getapplications.php?&jobid=\(jobid)&limitf=\(limitf)")
       // print(url!)
        let task = URLSession.shared.dataTask(with: url as! URL) { (data, response, error) -> Void in
            if let urlContent = data {
                do {
                    if let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as? [[String:AnyObject]] {
                        var i = 0
                        while i < jsonResult.count {

                            self.id.append(jsonResult[i]["id"]! as! String)
                            self.firstname.append(jsonResult[i]["firstname"]! as! String)
                            self.lastname.append(jsonResult[i]["lastname"]! as! String)
                            self.fbid.append(jsonResult[i]["fbid"]! as! String)
                            self.image.append(jsonResult[i]["image"]! as! String)
                            self.totalratings.append(jsonResult[i]["totalratings"]! as! String)
                            self.mobile.append(jsonResult[i]["mobile"]! as! String)

                            i = i + 1
                        }
                    }
                } catch {
                    print("JSON serialization failed")
                }
            } else {
                print("ERROR FOUND HERE")
            }

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }

        }

        task.resume()

    }
}


问:
references to overloaded methods and generics
I have a the following code:

```<code>List<Move> moves = getMoves();
moves.sort(Comparator.comparingInt(Move::getScore).reversed());
</code>```

which was working great with this as the method definition in Move:

```<code>public int getScore() { return myScore; }
</code>```

however I then overloaded getScore():

```<code>public int getScore(boolean doubleIt) { return myScore*2; }
</code>```

and now the comparingInt() method above complains unless I do:

```<code>Comparator.<Move>comparingInt(Move::getScore).reversed()
</code>```

Can someone explain why the compiler needs the additional <Move> when there are references to overloaded methods?

error message is:

```<code>incompatible types: cannot infer type-variable(s) T
(argument mismatch; invalid method reference
  incompatible types: java.lang.Object cannot be converted to boolean)
</code>```

This is on MacOS Sierra, JDK is:

```<code>java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
</code>```

example code: http://ideone.com/RxcXW6

答: You have introduced generic ambiguity and the compiler requires you to explicitly state which method you intend to be statically linked to this block.  The functional notation allows for the parameter to be passed implicitly, but without specifying the class, the compiler does not know which of the two valid methods to bind.  Since this isn't a polymorphic concern it will be bound at compile time, and the compiler needs explicit instructions on which to use.</p>

Body:
I have a the following code:

List<Move> moves = getMoves();
moves.sort(Comparator.comparingInt(Move::getScore).reversed());

which was working great with this as the method definition in Move:

public int getScore() { return myScore; }

however I then overloaded getScore():

public int getScore(boolean doubleIt) { return myScore*2; }

and now the comparingInt() method above complains unless I do:

Comparator.<Move>comparingInt(Move::getScore).reversed()

Can someone explain why the compiler needs the additional <Move> when there are references to overloaded methods?

error message is:

incompatible types: cannot infer type-variable(s) T
(argument mismatch; invalid method reference
  incompatible types: java.lang.Object cannot be converted to boolean)

This is on MacOS Sierra, JDK is:

java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

example code: http://ideone.com/RxcXW6


问:
remove vectors which are subsets of other vectors in a list
I have a list with vectors of different length, for example:

```<code>a=c(12345,12367,91670,87276,92865)
b=c(12345,87276,89250)
c=c(12367,91670)
d=c(23753,82575,91475,10957,92865,24311)
mylist=list(a,b,c,d)
mylist

# [[1]]
# [1] 12345 12367 91670 87276 92865
#
# [[2]]
# [1] 12345 87276 89250
#
# [[3]]
# [1] 12367 91670
#
# [[4]]
# [1] 23753 82575 91475 10957 92865 24311
</code>```

my question is how can I remove the vectors of this list which are a subset of another vector of the same list. i.e. in this case how can I remove the 3rd object of the list which is a subset of the 1st object??

答:
This gives a new list without the elements that are subsets of others...    </p>

```<code>newlist <- mylist[!sapply(seq_along(mylist), function(i) max(sapply(mylist[-i],function(L) all(mylist[[i]] %in% L))))]
</code>```

Body:
I have a list with vectors of different length, for example:

a=c(12345,12367,91670,87276,92865)
b=c(12345,87276,89250)
c=c(12367,91670)
d=c(23753,82575,91475,10957,92865,24311)
mylist=list(a,b,c,d)
mylist

# [[1]]
# [1] 12345 12367 91670 87276 92865
#
# [[2]]
# [1] 12345 87276 89250
#
# [[3]]
# [1] 12367 91670
#
# [[4]]
# [1] 23753 82575 91475 10957 92865 24311

my question is how can I remove the vectors of this list which are a subset of another vector of the same list. i.e. in this case how can I remove the 3rd object of the list which is a subset of the 1st object??

Body:
This gives a new list without the elements that are subsets of others...

newlist <- mylist[!sapply(seq_along(mylist), function(i) max(sapply(mylist[-i],function(L) all(mylist[[i]] %in% L))))]


问:
EF query with conditions from multiple tables
I have a table named "Employees". The employeeId from this table MAY be in another table (a many-to-many join tbale) named "Tasks". The other field in the "Tasks" table is a taskId linked to the "TaskDetails" table. This table includes details such as budgetHours.

Using EF4, how do I write the WHERE statement such that the return is employees assigned to tasks where the budgetHours is > 120 hours?

THe WHERE statement in the following limits rows in the Employees table but now I need to add the conditions on the TaskDetails table.

```<code>var assocOrg = Employees.Where(x => x.EmployeeTypeID == 2 && x.DepartmentName == "ABC").Select (x => x.EmployeeID);
</code>```

Thanks!

答:
If Employees has a navigation property named Tasks, try this:</p>

```<code>var assocOrg = Employees.Where(x => x.EmployeeTypeID == 2 &&
                                    x.DepartmentName == "ABC" &&
                                    x.Tasks.Any(t => t.BudgetHours > 120))
                        .Select (x => x.EmployeeID);
</code>```

Body:
I have a table named "Employees". The employeeId from this table MAY be in another table (a many-to-many join tbale) named "Tasks". The other field in the "Tasks" table is a taskId linked to the "TaskDetails" table. This table includes details such as budgetHours.

Using EF4, how do I write the WHERE statement such that the return is employees assigned to tasks where the budgetHours is > 120 hours?

THe WHERE statement in the following limits rows in the Employees table but now I need to add the conditions on the TaskDetails table.

var assocOrg = Employees.Where(x => x.EmployeeTypeID == 2 && x.DepartmentName == "ABC").Select (x => x.EmployeeID);

Thanks!

Body:
If Employees has a navigation property named Tasks, try this:

var assocOrg = Employees.Where(x => x.EmployeeTypeID == 2 &&
                                    x.DepartmentName == "ABC" &&
                                    x.Tasks.Any(t => t.BudgetHours > 120))
                        .Select (x => x.EmployeeID);


问:
use of decision variables in constraint assignments - PuLP
I am working on a specific problem utilizing linear programming and am trying to familiarize myself with PuLP. My issue is that several of my constraints contain only some of the decision variables and I am trying to find an efficient way to select them.

Here's what I mean:

I setup a list for all my Decision Variables.

```<code>investments = ["1_t1", "2_t1", "1_t2", "2_t2", "1_t3", "2_t3"]
</code>```

Then I put those variables in a dictionary.

```<code>invmt_vars = LpVariable.dicts("Invmts",investments,lowBound=0,cat='Continuous')
</code>```

Then I setup the Objective Function, simply as the sum of those variables.

```<code>prob += lpSum(invmt_vars[i] for i in invmt_vars), 'Sum of all investments'
</code>```

Then I have Constraints like this example:

```<code>prob += 1_t1 + 2_t2 + 3_t2 <= 25
</code>```

This works for a smaller number of variables, but I'd eventually like to add hundreds of variables. Is there a way to loop through the variables dictionary so that I only get the variables I'm looking for, without having to type them all out?

So far, I have really only seen constraint assignments that involve looping through the whole dictionary, like this:

```<code>prob += lpSum([ingredient_vars[i] for i in Ingredients]) == 100, "PercentagesSum"
</code>```

It would be great, for example, if I could simply leave Decision Variables in a list and use range loop.

I appreciate any input.

答: Pulp leverages the power of list comprehensions to do this look at the documentation in, http://www.secnetix.de/olli/Python/list_comprehensions.hawk</p>

Body:
I am working on a specific problem utilizing linear programming and am trying to familiarize myself with PuLP. My issue is that several of my constraints contain only some of the decision variables and I am trying to find an efficient way to select them.

Here's what I mean:

I setup a list for all my Decision Variables.

investments = ["1_t1", "2_t1", "1_t2", "2_t2", "1_t3", "2_t3"]

Then I put those variables in a dictionary.

invmt_vars = LpVariable.dicts("Invmts",investments,lowBound=0,cat='Continuous')

Then I setup the Objective Function, simply as the sum of those variables.

prob += lpSum(invmt_vars[i] for i in invmt_vars), 'Sum of all investments'

Then I have Constraints like this example:

prob += 1_t1 + 2_t2 + 3_t2 <= 25

This works for a smaller number of variables, but I'd eventually like to add hundreds of variables. Is there a way to loop through the variables dictionary so that I only get the variables I'm looking for, without having to type them all out?

So far, I have really only seen constraint assignments that involve looping through the whole dictionary, like this:

prob += lpSum([ingredient_vars[i] for i in Ingredients]) == 100, "PercentagesSum"

It would be great, for example, if I could simply leave Decision Variables in a list and use range loop.

I appreciate any input.


问:
Off-delay timer
Is there a way to write a safe one-second off-delay timer class in C# using exactly one System.Threading.Timer object?

Alternatively, what would be the simplest solution in general, assuming the input can get turned on and off a lot faster than once per second?

An off-delay timer could be described by this interface:

```<code>public interface IOffDelay
{
    /// <summary>
    /// May be set to any value from any thread.
    /// </summary>
    bool Input { get; set; }

    /// <summary>
    /// Whenever Input is true, Output is also true.
    /// The Output is only false at startup
    /// or after the Input has been continuously off for at least 1 second.
    /// </summary>
    bool Output { get; }
}
</code>```

This is my first attempt:

```<code>public sealed class OffDelay : IOffDelay, IDisposable
{
    public OffDelay()
    {
        timer = new Timer(TimerCallback, null, Timeout.Infinite, Timeout.Infinite);
    }

    public void Dispose()
    {
        timer.Dispose();
    }

    public bool Input
    {
        get
        {
            lock (locker)
                return _input;
        }
        set
        {
            lock (locker)
            {
                if (value == _input)
                    return;

                _input = value;

                if (_input == false)
                    timer.Change(1000, Timeout.Infinite);
                else
                {
                    _output = true;
                    timer.Change(Timeout.Infinite, Timeout.Infinite);
                }
            }
        }
    }
    private bool _input;

    public bool Output
    {
        get
        {
            lock (locker)
                return _output;
        }
    }
    private bool _output;

    private readonly Timer timer;
    private readonly object locker = new object();

    private void TimerCallback(object state)
    {
        lock (locker)
            _output = false;
    }
}
</code>```

I can see that there is a race condition in this solution:

At the end of a one-second off period, the timer schedules the callback to run.

Someone quickly sets and resets the input, restarting the timer.

The callback now finally runs, checks the input and sets the output to false even though it should be true for another second.

Edit

Peter Duniho provided the correct answer, but it turns out I'm terrible at asking the right question. The OffDelay class should also do some operation when the output changes to false. Here is the modified code adapting Peter's basic principle:

```<code>public sealed class OffDelay : IOffDelay, IDisposable
{
    public OffDelay()
    {
        timer = new Timer(TimerCallback, null, Timeout.Infinite, Timeout.Infinite);
    }

    public void Dispose()
    {
        timer.Dispose();
    }

    public bool Input
    {
        get
        {
            lock (locker)
                return _input;
        }
        set
        {
            lock (locker)
            {
                if (value == _input)
                    return;

                _input = value;

                if (_input == true)
                    _output = true;
                else
                {
                    stopwatch.Restart();
                    if (!timerRunning)
                        timer.Change(1000, Timeout.Infinite);
                }
            }
        }
    }
    private bool _input;

    public bool Output
    {
        get
        {
            lock (locker)
                return _output;
        }
    }
    private bool _output;

    private readonly object locker = new object();
    private readonly Timer timer;
    private readonly Stopwatch stopwatch = new Stopwatch();
    private bool timerRunning;

    private void TimerCallback(object state)
    {
        lock (locker)
        {
            if (_input == true)
                timerRunning = false;
            else
            {
                var remainingTimeMs = 1000 - stopwatch.ElapsedMilliseconds;
                if (remainingTimeMs > 0)
                    timer.Change(remainingTimeMs, Timeout.Infinite);
                else
                {
                    _output = false;
                    timerRunning = false;
                    DoSomething();
                }
            }
        }
    }

    private void DoSomething()
    {
        // ...
    }
}
</code>```

答:
Without a good Minimal, Complete, and Verifiable code example that clearly illustrates the question, including showing exactly what the context is and what constraints might exist, it's impossible to know for sure what answer would work for you.

But based on what you've included in your question, I would change your implementation so it doesn't rely on the timer:

```<code>public sealed class OffDelay : IOffDelay
{
    public bool Input
    {
        get { lock (locker) return _input; }
        set
        {
            lock (locker)
            {
                if (value == _input)
                    return;

                _input = value;
                _lastInput = DateTime.UtcNow;
            }
        }
    }
    private bool _input;

    public bool Output
    {
        get { lock (locker) return (DateTime.UtcNOw - _lastInput).TotalSeconds < 1; }
    }
    private DateTime _lastInput;
}
</code>```

Note that the above is susceptible to clock changes on the computer. If you have a need to work independently of the clock, you can replace DateTime.UtcNow with a Stopwatch instance, call Reset() on each change to the Input property, and use the Elapsed property of the Stopwatch to determine the length of time since last input.

Title: Off-delay timer

Body:
Is there a way to write a safe one-second off-delay timer class in C# using exactly one System.Threading.Timer object?

Alternatively, what would be the simplest solution in general, assuming the input can get turned on and off a lot faster than once per second?

An off-delay timer could be described by this interface:

public interface IOffDelay
{
    ///
    /// May be set to any value from any thread.
    ///
    bool Input { get; set; }

    ///
    /// Whenever Input is true, Output is also true.
    /// The Output is only false at startup
    /// or after the Input has been continuously off for at least 1 second.
    ///
    bool Output { get; }
}

This is my first attempt:

public sealed class OffDelay : IOffDelay, IDisposable
{
    public OffDelay()
    {
        timer = new Timer(TimerCallback, null, Timeout.Infinite, Timeout.Infinite);
    }

    public void Dispose()
    {
        timer.Dispose();
    }

    public bool Input
    {
        get
        {
            lock (locker)
                return _input;
        }
        set
        {
            lock (locker)
            {
                if (value == _input)
                    return;

                _input = value;

                if (_input == false)
                    timer.Change(1000, Timeout.Infinite);
                else
                {
                    _output = true;
                    timer.Change(Timeout.Infinite, Timeout.Infinite);
                }
            }
        }
    }
    private bool _input;

    public bool Output
    {
        get
        {
            lock (locker)
                return _output;
        }
    }
    private bool _output;

    private readonly Timer timer;
    private readonly object locker = new object();

    private void TimerCallback(object state)
    {
        lock (locker)
            _output = false;
    }
}

I can see that there is a race condition in this solution:

At the end of a one-second off period, the timer schedules the callback to run.

Someone quickly sets and resets the input, restarting the timer.

The callback now finally runs, checks the input and sets the output to false even though it should be true for another second.

Edit

Peter Duniho provided the correct answer, but it turns out I'm terrible at asking the right question. The OffDelay class should also do some operation when the output changes to false. Here is the modified code adapting Peter's basic principle:

public sealed class OffDelay : IOffDelay, IDisposable
{
    public OffDelay()
    {
        timer = new Timer(TimerCallback, null, Timeout.Infinite, Timeout.Infinite);
    }

    public void Dispose()
    {
        timer.Dispose();
    }

    public bool Input
    {
        get
        {
            lock (locker)
                return _input;
        }
        set
        {
            lock (locker)
            {
                if (value == _input)
                    return;

                _input = value;

                if (_input == true)
                    _output = true;
                else
                {
                    stopwatch.Restart();
                    if (!timerRunning)
                        timer.Change(1000, Timeout.Infinite);
                }
            }
        }
    }
    private bool _input;

    public bool Output
    {
        get
        {
            lock (locker)
                return _output;
        }
    }
    private bool _output;

    private readonly object locker = new object();
    private readonly Timer timer;
    private readonly Stopwatch stopwatch = new Stopwatch();
    private bool timerRunning;

    private void TimerCallback(object state)
    {
        lock (locker)
        {
            if (_input == true)
                timerRunning = false;
            else
            {
                var remainingTimeMs = 1000 - stopwatch.ElapsedMilliseconds;
                if (remainingTimeMs > 0)
                    timer.Change(remainingTimeMs, Timeout.Infinite);
                else
                {
                    _output = false;
                    timerRunning = false;
                    DoSomething();
                }
            }
        }
    }

    private void DoSomething()
    {
        // ...
    }
}

Body:
Without a good Minimal, Complete, and Verifiable code example that clearly illustrates the question, including showing exactly what the context is and what constraints might exist, it's impossible to know for sure what answer would work for you.

But based on what you've included in your question, I would change your implementation so it doesn't rely on the timer:

public sealed class OffDelay : IOffDelay
{
    public bool Input
    {
        get { lock (locker) return _input; }
        set
        {
            lock (locker)
            {
                if (value == _input)
                    return;

                _input = value;
                _lastInput = DateTime.UtcNow;
            }
        }
    }
    private bool _input;

    public bool Output
    {
        get { lock (locker) return (DateTime.UtcNOw - _lastInput).TotalSeconds < 1; }
    }
    private DateTime _lastInput;
}

Note that the above is susceptible to clock changes on the computer. If you have a need to work independently of the clock, you can replace DateTime.UtcNow with a Stopwatch instance, call Reset() on each change to the Input property, and use the Elapsed property of the Stopwatch to determine the length of time since last input.