问:
Why apprend("

")is so strange
I got a problem with append in jquery

When i write the code like

```<code><script>
  $(document).ready(function(){
    for(var a=0;a<5;a++){
          var u=$("#nav").append("<li >a_"+a);
               u.append("<ul>");
                   for(var b=0;b<5;b++){
                       u.append("<li>b_"+b+"</li>");
                   }
                u.append("</ul>")

          $("#nav").append("</li>")
     }
    });

 </script>
  <div class="section-tree">
  <ul id="nav"></ul>         </div>
</code>```

It output like:

Is not what i want

What i want is:

```<code>  <ul>

   <li>
    a_0
      <ul>
         <li>b_1</li>
         <li>b_2</li>
         <li>b_3</li>
         <li>b_4</li>
         <li>b_5</li>
      </ul>
   </li>

   <li>
   a_1
      <ul>
        <li>b_1</li>
        <li>b_2</li>
        <li>b_3</li>
        <li>b_4</li>
        <li>b_5</li>
      </ul>
  </li>
        ...
</ul>
</code>```

why it's not right?

hellowworld
hellowworld
hellowworld
hellowworld

答:
concatenate it to a variable first than use .append() see below snippet for more info.

$(document).ready(function() {
  var data = "";
  for (var a = 0; a < 5; a++) {
    data += "
a_" + a;
    data += "
";
    for (var b = 0; b < 5; b++) {
      data += "
b_" + b + "
";
    }
    data += "

";
  }
  $("#nav").append(data)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

</script>
<div class="section-tree">
  <ul id="nav"></ul>
</div></code>```

Title: Why apprend("<ul><li>")is so strange

Body:
I got a problem with append in jquery

When i write the code like

It output like:

Is not what i want

What i want is:

    a_0

b_1

b_2

b_3

b_4

b_5

   a_1

b_1

b_2

b_3

b_4

b_5

        ...

why it's not right?

hellowworld
hellowworld
hellowworld
hellowworld

Body:
concatenate it to a variable first than use .append() see below snippet for more info.

$(document).ready(function() {
  var data = "";
  for (var a = 0; a < 5; a++) {
    data += "<li >a_" + a;
    data += "<ul>";
    for (var b = 0; b < 5; b++) {
      data += "<li>b_" + b + "</li>";
    }
    data += "</ul></li>";
  }
  $("#nav").append(data)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

</script>
<div class="section-tree">
  <ul id="nav"></ul>
</div>


来源: stackexchange

问:
Explaining Python's '__enter__' and '__exit__'
I saw this in someone's code. What does it mean?

```<code>    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()
</code>```

```<code>from __future__ import with_statement#for python2.5

class a(object):
    def __enter__(self):
        print 'sss'
        return 'sss111'
    def __exit__(self ,type, value, traceback):
        print 'ok'
        return False

with a() as s:
    print s

print s
</code>```

答:
I found it strangely difficult to locate the python docs for __enter__ and __exit__ methods by Googling, so to help others here is the link:

https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers

https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers

(detail is the same for both versions)

object.__enter__(self)

Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

object.__exit__(self, exc_type, exc_value, traceback)

Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.

Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility.

I was hoping for a clear description of the __exit__ method arguments. This is lacking but we can deduce them...

Presumably exc_type is the class of the exception.

It says you should not re-raise the passed-in exception. This suggests to us that one of the arguments might be an actual Exception instance ...or maybe you're supposed to instantiate it yourself from the type and value?

We can answer by looking at this article:

http://effbot.org/zone/python-with-statement.htm

For example, the following __exit__ method swallows any TypeError, but lets all other exceptions through:

```<code>def __exit__(self, type, value, traceback):
    return isinstance(value, TypeError)
</code>```

...so clearly value is an Exception instance.

And presumably traceback is a Python traceback object.

Note that there are further docs here:

https://docs.python.org/3/library/stdtypes.html#context-manager-types

...they have a slightly more detailed explanation of the __enter__ and __exit__ methods. Particularly it is more explicit that __exit__ should return a boolean value (though truthy or falsy will work fine, e.g. an implicit None return will give the default behaviour of propagating the exception).

ContentLicense: CC BY-SA 3.0

Body:
I saw this in someone's code. What does it mean?

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        self.stream.close()

from __future__ import with_statement#for python2.5

class a(object):
    def __enter__(self):
        print 'sss'
        return 'sss111'
    def __exit__(self ,type, value, traceback):
        print 'ok'
        return False

with a() as s:
    print s

print s

Body:
I found it strangely difficult to locate the python docs for __enter__ and __exit__ methods by Googling, so to help others here is the link:

https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers

https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers

(detail is the same for both versions)

object.__enter__(self)

Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

object.__exit__(self, exc_type, exc_value, traceback)

Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.

Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility.

I was hoping for a clear description of the __exit__ method arguments. This is lacking but we can deduce them...

Presumably exc_type is the class of the exception.

It says you should not re-raise the passed-in exception. This suggests to us that one of the arguments might be an actual Exception instance ...or maybe you're supposed to instantiate it yourself from the type and value?

We can answer by looking at this article:

http://effbot.org/zone/python-with-statement.htm

For example, the following __exit__ method swallows any TypeError, but lets all other exceptions through:

def __exit__(self, type, value, traceback):
    return isinstance(value, TypeError)

...so clearly value is an Exception instance.

And presumably traceback is a Python traceback object.

Note that there are further docs here:

https://docs.python.org/3/library/stdtypes.html#context-manager-types

...they have a slightly more detailed explanation of the __enter__ and __exit__ methods. Particularly it is more explicit that __exit__ should return a boolean value (though truthy or falsy will work fine, e.g. an implicit None return will give the default behaviour of propagating the exception).

ContentLicense: CC BY-SA 4.0


问:
How to add shadow in dropdown spinner in Android
I am using a Spinner drop down in my Form. But when I drop down my spinner, the color of it is matching to background color. How can I add shadow to my dropdown spinner in Android </p>

答:
Try to add elevation to it (API 21+). Here is how to do it in XML:

```<code>android:elevation="2dp"
</code>```

Body:
Try to add elevation to it (API 21+). Here is how to do it in XML:

android:elevation="2dp"


问:
OkHttp and Retrofit, refresh token with concurrent requests
In my application I implemented Retrofit to call WebServices and I'm using OkHttp to use Interceptor and Authenticator. Some requests need token, and I have implemented Authenticator interface to handle the refresh (following the official documentation). But I have the following issue : time to time in my app I have to call more than one request at once. Because of that, for one of them I will have the 401 error.

Here is my code for request calls :

```<code>public static <S> S createServiceAuthentication(Class<S> serviceClass, boolean hasPagination) {

        final String jwt = JWT.getJWTValue(); //Get jwt value from Realm

        if (hasPagination) {
            Gson gson = new GsonBuilder().
                    registerTypeAdapter(Pagination.class, new PaginationTypeAdapter()).create();

            builder =
                    new Retrofit.Builder()
                            .baseUrl(APIConstant.API_URL)
                            .addConverterFactory(GsonConverterFactory.create(gson));
        }

        OkHttpClient.Builder httpClient =
                new OkHttpClient.Builder();

        httpClient.addInterceptor(new AuthenticationInterceptor(jwt));
        httpClient.authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                if (responseCount(response) >= 2) {
                    // If both the original call and the call with refreshed token failed,
                    // it will probably keep failing, so don't try again.
                    return null;
                }

                if (jwt.equals(response.request().header("Authorization"))) {
                    return null; // If we already failed with these credentials, don't retry.
                }

                APIRest apiRest = createService(APIRest.class, false);
                Call<JWTResponse> call = apiRest.refreshToken(new JWTBody(jwt));
                try {
                    retrofit2.Response<JWTResponse> refreshTokenResponse = call.execute();
                    if (refreshTokenResponse.isSuccessful()) {

                        JWT.storeJwt(refreshTokenResponse.body().getJwt());

                        return response.request().newBuilder()
                                .header(CONTENT_TYPE, APPLICATION_JSON)
                                .header(ACCEPT, APPLICATION)
                                .header(AUTHORIZATION, "Bearer " + refreshTokenResponse.body().getJwt())
                                .build();
                    } else {
                        return null;
                    }
                } catch (IOException e) {
                    return null;
                }
            }
        });

        builder.client(httpClient.build());
        retrofit = builder.build();

        return retrofit.create(serviceClass);
    }

    private static int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }
        return result;
    }
</code>```

The issue is simple, the first request will refresh the token successfully but others will failed because they will try to refresh a token already refreshed. The WebService return an error 500. Is there any elegant solution to avoid this ?

Thank you !

答:
Write Service.

```<code>public class TokenService extends Service {

private static final String TAG = "HelloService";

private boolean isRunning = false;
OkHttpClient client;
JSONObject jsonObject;
public static String URL_LOGIN = "http://server.yoursite";
String phone_number, password;

@Override
public void onCreate() {
    Log.i(TAG, "Service onCreate");
    jsonObject = new JSONObject();
    client = new OkHttpClient();

    SharedPreferences pref_phone = getSharedPreferences("Full_Phone", MODE_PRIVATE);
    phone_number = pref_phone.getString("Phone", "");

    SharedPreferences pref_password = getSharedPreferences("User_Password", MODE_PRIVATE);
    password = pref_password.getString("Password", "");

    isRunning = true;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i(TAG, "Service onStartCommand");
    try {
        jsonObject.put("phone_number", phone_number);
        jsonObject.put("password", password);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (; ; ) {
                try {
                    Thread.sleep(1000 * 60 * 2);
                } catch (Exception e) {
                }

                if (isRunning) {

                    AsyncTaskRunner myTask = new AsyncTaskRunner();
                    myTask.execute();

                } else {

                    Log.d("CHECK__", "Check internet connection");

                }
            }
        }
    }).start();

    return Service.START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {
    Log.i(TAG, "Service onBind");
    return null;
}

@Override
public void onDestroy() {

    isRunning = false;
    Log.i(TAG, "Service onDestroy");
}

String post(String url, JSONObject login) {
    try {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, login.toString());
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(body)
                .build();

        okhttp3.Response response = client.newCall(request).execute();

        try {
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

String response;

private class AsyncTaskRunner extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            response = post(
                    URL_LOGIN, jsonObject);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("---OKHTTP---", response);
    }
}
</code>```

}

Body:
In my application I implemented Retrofit to call WebServices and I'm using OkHttp to use Interceptor and Authenticator. Some requests need token, and I have implemented Authenticator interface to handle the refresh (following the official documentation). But I have the following issue : time to time in my app I have to call more than one request at once. Because of that, for one of them I will have the 401 error.

Here is my code for request calls :

public static <S> S createServiceAuthentication(Class<S> serviceClass, boolean hasPagination) {

        final String jwt = JWT.getJWTValue(); //Get jwt value from Realm

        if (hasPagination) {
            Gson gson = new GsonBuilder().
                    registerTypeAdapter(Pagination.class, new PaginationTypeAdapter()).create();

            builder =
                    new Retrofit.Builder()
                            .baseUrl(APIConstant.API_URL)
                            .addConverterFactory(GsonConverterFactory.create(gson));
        }

        OkHttpClient.Builder httpClient =
                new OkHttpClient.Builder();

        httpClient.addInterceptor(new AuthenticationInterceptor(jwt));
        httpClient.authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                if (responseCount(response) >= 2) {
                    // If both the original call and the call with refreshed token failed,
                    // it will probably keep failing, so don't try again.
                    return null;
                }

                if (jwt.equals(response.request().header("Authorization"))) {
                    return null; // If we already failed with these credentials, don't retry.
                }

                APIRest apiRest = createService(APIRest.class, false);
                Call<JWTResponse> call = apiRest.refreshToken(new JWTBody(jwt));
                try {
                    retrofit2.Response<JWTResponse> refreshTokenResponse = call.execute();
                    if (refreshTokenResponse.isSuccessful()) {

                        JWT.storeJwt(refreshTokenResponse.body().getJwt());

                        return response.request().newBuilder()
                                .header(CONTENT_TYPE, APPLICATION_JSON)
                                .header(ACCEPT, APPLICATION)
                                .header(AUTHORIZATION, "Bearer " + refreshTokenResponse.body().getJwt())
                                .build();
                    } else {
                        return null;
                    }
                } catch (IOException e) {
                    return null;
                }
            }
        });

        builder.client(httpClient.build());
        retrofit = builder.build();

        return retrofit.create(serviceClass);
    }

    private static int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }
        return result;
    }

The issue is simple, the first request will refresh the token successfully but others will failed because they will try to refresh a token already refreshed. The WebService return an error 500. Is there any elegant solution to avoid this ?

Thank you !

Body:
Write Service.

public class TokenService extends Service {

private static final String TAG = "HelloService";

private boolean isRunning = false;
OkHttpClient client;
JSONObject jsonObject;
public static String URL_LOGIN = "http://server.yoursite";
String phone_number, password;

@Override
public void onCreate() {
    Log.i(TAG, "Service onCreate");
    jsonObject = new JSONObject();
    client = new OkHttpClient();

    SharedPreferences pref_phone = getSharedPreferences("Full_Phone", MODE_PRIVATE);
    phone_number = pref_phone.getString("Phone", "");

    SharedPreferences pref_password = getSharedPreferences("User_Password", MODE_PRIVATE);
    password = pref_password.getString("Password", "");

    isRunning = true;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i(TAG, "Service onStartCommand");
    try {
        jsonObject.put("phone_number", phone_number);
        jsonObject.put("password", password);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (; ; ) {
                try {
                    Thread.sleep(1000 * 60 * 2);
                } catch (Exception e) {
                }

                if (isRunning) {

                    AsyncTaskRunner myTask = new AsyncTaskRunner();
                    myTask.execute();

                } else {

                    Log.d("CHECK__", "Check internet connection");

                }
            }
        }
    }).start();

    return Service.START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {
    Log.i(TAG, "Service onBind");
    return null;
}

@Override
public void onDestroy() {

    isRunning = false;
    Log.i(TAG, "Service onDestroy");
}

String post(String url, JSONObject login) {
    try {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, login.toString());
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(body)
                .build();

        okhttp3.Response response = client.newCall(request).execute();

        try {
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

String response;

private class AsyncTaskRunner extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            response = post(
                    URL_LOGIN, jsonObject);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("---OKHTTP---", response);
    }
}

}


问:
Why CSS and Bootstrap elements disappear with node express server?
I firstly made a basic node server like this:

```<code>  var connect = require('connect');

  var serveStatic = require('serve-static');
  connect().use(serveStatic(__dirname)).listen(8080, function() {
    console.log('Server running on 8080...');
  });
</code>```

Then I replaced it with an express server like this:

```<code>   var express = require("express");
   var app     = express();
   var path    = require("path");

   app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));

   });

   app.use(express.static("public"));

   app.listen(8080);

   console.log("Running at Port 8080");
</code>```

With the first one, everything worked fine. CSS, JQuery, images etc..., but with the second one, some of my style elements totally disappeared and it can't reach the pictures on the site. What did I miss? How can I solve it?

答:
In order to serve static files have a look at https://expressjs.com/en/starter/static-files.html which shows you can use:

```<code>app.use(express.static('public'))
app.use(express.static('files'))
</code>```

to serve static files from the public and files folder. In your example code you are only serving the index.html.

Body:
I firstly made a basic node server like this:

  var connect = require('connect');

  var serveStatic = require('serve-static');
  connect().use(serveStatic(__dirname)).listen(8080, function() {
    console.log('Server running on 8080...');
  });

Then I replaced it with an express server like this:

   var express = require("express");
   var app     = express();
   var path    = require("path");

   app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));

   });

   app.use(express.static("public"));

   app.listen(8080);

   console.log("Running at Port 8080");

With the first one, everything worked fine. CSS, JQuery, images etc..., but with the second one, some of my style elements totally disappeared and it can't reach the pictures on the site. What did I miss? How can I solve it?

Body:
In order to serve static files have a look at https://expressjs.com/en/starter/static-files.html which shows you can use:

app.use(express.static('public'))
app.use(express.static('files'))

to serve static files from the public and files folder. In your example code you are only serving the index.html.


问:
Custom domain for API Gateway returning 403
I am creating an api using API Gateway and Lambda. Using the url designated in the API Gateway Stage editor everything works fine; however, when I try and move to a custom domain I am running into some issues.

The first thing I tried was using a CNAME record in Route 53 straight from my domain onto the domain that I got from the API Gateway. That was returning some errors and I think it is the incorrect solution is that correct?

Next I tried the Custom Domain Names feature in API Gateway. My understanding is this will roll up a CloudFront distribution that I can then map onto from Route 53. When I created the custom domain and added a Domain Mapping it provides me with a url to what I assume is a CloudFront distribution. The link is returning a 403 response and no distribution has been made in CloudFront. What is a good way of debugging this problem?

答:
You need to use host header in your request. Host should be your custom domain.</p>

```<code>curl https://<cf-id>.cloudfront.net/myapi -H "Host: api.myapi.com"
</code>```

Body:
You need to use host header in your request. Host should be your custom domain.

curl https://<cf-id>.cloudfront.net/myapi -H "Host: api.myapi.com"


问:
shuffle two consecutive blocks of data
I have data file (php) with 24 blocks of data, structured as below.

```<code>//ts1
$P[] = [0];
$S[] = [[1,95.8172406762736],[2,104.97526726371],[3,112.03839938973],[4,101.70457396977],];
$F[] = [];
$FB[] = [];
//ts2
$P[] = [0];
$S[] = [[1,103.190939795922],[2,105.297198378469],[3,105.829786652111]];
$F[] = [];
$FB[] = [];
//ts3
$P[] = [0];
$S[] = [[1,107.285278217373],[2,103.557795069809],[3,105.686758569246],[4,103.748341353355]];
$F[] = [];
$FB[] = [];
</code>```

I need to shuffle the first 12 blocks and then shuffle block 13-24. The code I have does not appear to work as it still shuffles all 24 blocks at once. I'm not sure how it should be written otherwise..

```<code>// DATA INITIALISATION
// - Reads all data sets from server
// - Generates list of objects
// - Randomises list of objects
function DataInit1()
{
    SeriesList = [];
    CurrentGraph.Series = 0;

    // load all the data sets from server
    $.getJSON("datademo.php",
        function(Data1)
        {
            for(var i=0; i<Data1.length; i+=4)
            {
                var P = Data1[i+0];
                var S = Data1[i+1];
                var F = Data1[i+2];
                var FB = Data1[i+3];
                var NewSeries = new SeriesClass(P,S,F,FB);
                NewSeries.SeriesNumber = (i/4)+1;
                SeriesList.push(NewSeries);
            }
        }
    );
// shuffle each of the series lists to a random order
    s1 = SeriesList.length/2;
    s2 = SeriesList.length;
    for(var i=0; i<s1; i++)
    {
           var j = Math.floor(Math.random() * (i+1));
           var x = SeriesList[i];
           SeriesList[i] = SeriesList[j];
           SeriesList[j] = x;
         }
    for(var i=s1; i<s2; i++)
    {
           var j = Math.floor(Math.random() * (i+1));
           var x = SeriesList[i];
           SeriesList[i] = SeriesList[j];
           SeriesList[j] = x;
         }
    }
</code>```

edit: I've changed it now to the following (not pretty but I don't have time to tidy it). Now it randomizes series 1-12, but series 13-24 is now not randomized. I don't code that often and I can't see why it would work in the first bit but not the second one.

```<code>// shuffle the series list to a random order
    for(var i=SeriesList.length-13; i>0; i--)
    {
        var j = Math.floor(Math.random() * (i+1));
        var x = SeriesList[i];
        SeriesList[i] = SeriesList[j];
        SeriesList[j] = x;
    }
        for(var i={from: 12, to: 23}; i>0; i--)
    {
        var j = Math.floor(Math.random() * (i+1));
        var x = SeriesList[i];
        SeriesList[i] = SeriesList[j];
        SeriesList[j] = x;
    }
</code>```

答:
I think the easiest way is to break it into two arrays, shuffle them separately, then push them back together. I've used the shuffle method from this question: How can I shuffle an array?, and the method of joining arrays from How to extend an existing JavaScript array with another array, without creating a new array?

See the fiddle at https://jsfiddle.net/u25ta64x/1/

```<code>var SeriesList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26];

var firstHalf = SeriesList.slice(0,13);
var secondHalf = SeriesList.slice(13,26);

function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}

shuffle(firstHalf);
shuffle(secondHalf)
var shuffledList = firstHalf;
Array.prototype.push.apply(shuffledList, secondHalf);

console.log(shuffledList);
</code>```

Title: shuffle two consecutive blocks of data

Body:
I have data file (php) with 24 blocks of data, structured as below.

//ts1
$P[] = [0];
$S[] = [[1,95.8172406762736],[2,104.97526726371],[3,112.03839938973],[4,101.70457396977],];
$F[] = [];
$FB[] = [];
//ts2
$P[] = [0];
$S[] = [[1,103.190939795922],[2,105.297198378469],[3,105.829786652111]];
$F[] = [];
$FB[] = [];
//ts3
$P[] = [0];
$S[] = [[1,107.285278217373],[2,103.557795069809],[3,105.686758569246],[4,103.748341353355]];
$F[] = [];
$FB[] = [];

I need to shuffle the first 12 blocks and then shuffle block 13-24. The code I have does not appear to work as it still shuffles all 24 blocks at once. I'm not sure how it should be written otherwise..

// DATA INITIALISATION
// - Reads all data sets from server
// - Generates list of objects
// - Randomises list of objects
function DataInit1()
{
    SeriesList = [];
    CurrentGraph.Series = 0;

    // load all the data sets from server
    $.getJSON("datademo.php",
        function(Data1)
        {
            for(var i=0; i<Data1.length; i+=4)
            {
                var P = Data1[i+0];
                var S = Data1[i+1];
                var F = Data1[i+2];
                var FB = Data1[i+3];
                var NewSeries = new SeriesClass(P,S,F,FB);
                NewSeries.SeriesNumber = (i/4)+1;
                SeriesList.push(NewSeries);
            }
        }
    );
// shuffle each of the series lists to a random order
    s1 = SeriesList.length/2;
    s2 = SeriesList.length;
    for(var i=0; i<s1; i++)
    {
           var j = Math.floor(Math.random() * (i+1));
           var x = SeriesList[i];
           SeriesList[i] = SeriesList[j];
           SeriesList[j] = x;
         }
    for(var i=s1; i<s2; i++)
    {
           var j = Math.floor(Math.random() * (i+1));
           var x = SeriesList[i];
           SeriesList[i] = SeriesList[j];
           SeriesList[j] = x;
         }
    }

edit: I've changed it now to the following (not pretty but I don't have time to tidy it). Now it randomizes series 1-12, but series 13-24 is now not randomized. I don't code that often and I can't see why it would work in the first bit but not the second one.

// shuffle the series list to a random order
    for(var i=SeriesList.length-13; i>0; i--)
    {
        var j = Math.floor(Math.random() * (i+1));
        var x = SeriesList[i];
        SeriesList[i] = SeriesList[j];
        SeriesList[j] = x;
    }
        for(var i={from: 12, to: 23}; i>0; i--)
    {
        var j = Math.floor(Math.random() * (i+1));
        var x = SeriesList[i];
        SeriesList[i] = SeriesList[j];
        SeriesList[j] = x;
    }

Body:
I think the easiest way is to break it into two arrays, shuffle them separately, then push them back together. I've used the shuffle method from this question: How can I shuffle an array?, and the method of joining arrays from How to extend an existing JavaScript array with another array, without creating a new array?

See the fiddle at https://jsfiddle.net/u25ta64x/1/

var SeriesList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26];

var firstHalf = SeriesList.slice(0,13);
var secondHalf = SeriesList.slice(13,26);

function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}

shuffle(firstHalf);
shuffle(secondHalf)
var shuffledList = firstHalf;
Array.prototype.push.apply(shuffledList, secondHalf);

console.log(shuffledList);


问:
Nexus 6P stuck in charge mode when plugged in to my computer
I was developping android apps like many times on my Nexus 6P, but since few days my phone isn't detected on my PC.
I Googled it but I didn't find any solutions !

More about my problem :
I'm running Ubuntu 16.04 LTS on my computer and Android Nougat 7.1.2 N2G47O on my Nexus 6P.

I have Android Studio 2.3, SDK updated and adb installed.
I have Developer Mode and USB Debugging switched on.

When I plug my phone to computer, I don't get the "Debugging" and "Connected to computer" notifications.

I tried to connect another phone to my pc (Samsung Galaxy Y) and everything worked perfectly.

Maybe I forget to do something on my phone ?
Hope you can help me !
Thanks :)

答:
I remember having some issues on Linux with this device.

First check that the option "USB debugging" in the section "Debugging" is on.
Then on your udev rules (/etc/udev/rules.d/) add these two rules :

SUBSYSTEM=="usb", ATTR{idVendor}=="05c6",  MODE="0666", GROUP="plugdev"
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev"

The first one is for Qualcom vendor and the second one for Google. I know it is weird but if you do an lsusb, you will see that this device is sometimes detected as being a Qualcom device.


问:
Interpolation function approx() in r gives error - need at least two non-NA values to interpolate
I am using R Studio on Windows 8 machine. I am trying to interpolate a point between two points.

```<code>x1 = -159.9, y1 = 56.5,
x2 = -159.9, y2 = 56.3
</code>```

I am using approx() function in the following manner (reproducible)

```<code>approx(c(-159.9,-159.9), c(56.5,56.3), n = 3)
</code>```

which gives me an error

```<code>Error in approx(c(-159.9, -159.9), c(56.5, 56.3), n = 3) :
need at least two non-NA values to interpolate
</code>```

Its expecting two non-NA values, which I have provided.

The function is working flawlessly for other points. Just this is the problem.
If you have come across any such error, please let me know how did you solve this?

答:
The approx function can't interpolate values where the x-coordinates are the same.

Hence, I would tackle this problem as follows:

Group all the cases where the x-coordinates are equal and aggregate them by for example the median, mean, or a custom built function

Use you intended interpolation scheme, for example the approx function.

Body:
I am using R Studio on Windows 8 machine. I am trying to interpolate a point between two points.

x1 = -159.9, y1 = 56.5,
x2 = -159.9, y2 = 56.3

I am using approx() function in the following manner (reproducible)

approx(c(-159.9,-159.9), c(56.5,56.3), n = 3)

which gives me an error

Error in approx(c(-159.9, -159.9), c(56.5, 56.3), n = 3) :
need at least two non-NA values to interpolate

Its expecting two non-NA values, which I have provided.

The function is working flawlessly for other points. Just this is the problem.
If you have come across any such error, please let me know how did you solve this?


问:
DXL - Cannot repopulate ListView
I'm writing a script that will display all modules within a folder and subfolder of the users' choice. I can populate my ListView dialog box element once, but I cannot seem to update the results or display new results when running the search on a different folder.

So far I've tried simply overriding the data in the exisiting rows and columns, but that just appends the information. I've also tried calling the empty(listView) method, as well as calling realize(Main_Dialog) after that as specified here on the IBM DXL forums.

I can still update the information in the first column after using the empty method, as such I've tried deleting the other columns and re-adding them, this has the same result as the empty() -> realize() calls.

Any help would be greatly appreciated.

答:
This question was answered by Mathias Mamsch on the IBM Developer Forums

The empty() method was working, but I was not correctly setting the values of the list after emptying it with void set(DBE listView, int item, int column, string value)

Full explanation is on the forum (linked previously)

Title: DXL - Cannot repopulate ListView


问:
Managing PHP Errors
I have been searching all over the net to try and find a way to catch all errors thrown by PHP (5.3)

I have been reading through the documentation and it looks like set_error_handler is what I need but it doesn't get fatal/parse errors. I'm not sure if this is possible...

Here is my source: https://github.com/tarnfeld/PHP-Error-Handler
Feel free to fork/commit if you know better solutions to all of this.

Thanks in advanced!

Updated!

Using the answers below I finished writing an error handler, it takes care of E_ERROR|E_PARSE|E_WARNING|E_NOTICE and will kill the script when it is fatal! :-)

答:
No, catching fatal and parse errors is not possible.
Parse errors because they're raised before script is even compiled.
Fatal errors because they're ... fatal (i.e. script cannot continue running after encountering them)</p>

ContentLicense: CC BY-SA 2.5

Title: Managing PHP Errors


问:
Connection to JMS broker failing
I have a Glassfish server (4.1.2) and following this tutorial I have integrated Apache ActiveMQ to the server. Afterwards I developed a standalone Client for messaging according to this part of the same tutorial. Finished with that I followed the last part of this tutorial to develop  a MessageDrivenBean listening to the queue used in the steps before.

Everything compiled fine. ActiveMQ is also running. But whenever I deploy the EJB the following is logged in my GF server log:

```<code>Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   JTS5014: Recoverable JTS instance, serverId = [3700]
Warning:   RAR8000 : The method setDestinationLookup is not present in the class : org.apache.activemq.ra.ActiveMQActivationSpec
Warning:   RAR7097: No setter method present for the property destinationLookup in the class org.apache.activemq.ra.ActiveMQActivationSpec
Info:   2017-06-06 11:43:00,675 [min-listener(1)] INFO  ActiveMQEndpointWorker         - Starting
Info:   2017-06-06 11:43:00,682 [ad-pool-1; w: 4] INFO  ActiveMQEndpointWorker         - Establishing connection to broker [vm://0.0.0.0:6616]
Info:   WELD-000900: 2.2.13 (Final)
WARN:   WELD-001700: Interceptor annotation class javax.ejb.PostActivate not found, interception based on it is not enabled
WARN:   WELD-001700: Interceptor annotation class javax.ejb.PrePassivate not found, interception based on it is not enabled
WARN:   WELD-000411: Observer method [BackedAnnotatedMethod] public org.glassfish.jms.injection.JMSCDIExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds.
WARN:   WELD-000411: Observer method [BackedAnnotatedMethod] org.glassfish.sse.impl.ServerSentEventCdiExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>, BeanManager) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds.
WARN:   WELD-000411: Observer method [BackedAnnotatedMethod] private org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds.
Info:   AmdMDB was successfully deployed in 5.290 milliseconds.
Info:   2017-06-06 11:43:31,695 [ad-pool-1; w: 4] ERROR ActiveMQEndpointWorker         - Failed to connect to broker [vm://0.0.0.0:6616]: Could not create Transport. Reason: java.net.URISyntaxException: Illegal character in scheme name at index 0: 0.0.0.0:6616
javax.jms.JMSException: Could not create Transport. Reason: java.net.URISyntaxException: Illegal character in scheme name at index 0: 0.0.0.0:6616
    at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:36)
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:260)
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:273)
    at org.apache.activemq.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:194)
    at org.apache.activemq.ra.ActiveMQResourceAdapter.makeConnection(ActiveMQResourceAdapter.java:132)
    at org.apache.activemq.ra.ActiveMQEndpointWorker$1.run(ActiveMQEndpointWorker.java:109)
    at com.sun.enterprise.connectors.work.OneWork.doWork(OneWork.java:107)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.net.URISyntaxException: Illegal character in scheme name at index 0: 0.0.0.0:6616
    at java.net.URI$Parser.fail(URI.java:2848)
    at java.net.URI$Parser.checkChars(URI.java:3021)
    at java.net.URI$Parser.checkChar(URI.java:3031)
    at java.net.URI$Parser.parse(URI.java:3047)
    at java.net.URI.<init>(URI.java:588)
    at org.apache.activemq.util.URISupport.parseComposite(URISupport.java:390)
    at org.apache.activemq.util.URISupport.parseComposite(URISupport.java:279)
    at org.apache.activemq.transport.vm.VMTransportFactory.doCompositeConnect(VMTransportFactory.java:63)
    at org.apache.activemq.transport.vm.VMTransportFactory.doConnect(VMTransportFactory.java:54)
    at org.apache.activemq.transport.TransportFactory.connect(TransportFactory.java:64)
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:258)
    ... 7 more
Info:   2017-06-06 11:43:31,697 [ad-pool-1; w: 4] ERROR ActiveMQEndpointWorker         - Endpoint will try to reconnect to the JMS broker in 30 seconds
Info:   2017-06-06 11:43:40,060 [jb-thread-pool1] INFO  ActiveMQEndpointWorker         - Stopping
</code>```

The Stopping at the end is due to the undeployment I did, because the same error would come every thirty seconds with the reconnection try.

I am not quite sure, where the error is. The port is 6616 by the way isn't a typo, it is the actual port where ActiveMQ is running because port 61616 is in use by another process.

Can you please give me a hint, on where to search for the mistake?

By the way: When I send a message to the queue with the standalone client, no Exception is thrown (so this seems to be working.) However, I am also unable to send a message via the ActiveMQ Admin console to the server.

Thanks a lot...

答:
According to http://activemq.apache.org/vm-transport-reference.html, when using activemq vm tranport, it should be the broker name after "vm://".

If want to use the ip and port, config this way:

```<code>vm:(broker:(tcp://localhost:6000)?persistent=false)?marshal=false
</code>```

Title: Connection to JMS broker failing

Body:
I have a Glassfish server (4.1.2) and following this tutorial I have integrated Apache ActiveMQ to the server. Afterwards I developed a standalone Client for messaging according to this part of the same tutorial. Finished with that I followed the last part of this tutorial to develop  a MessageDrivenBean listening to the queue used in the steps before.

Everything compiled fine. ActiveMQ is also running. But whenever I deploy the EJB the following is logged in my GF server log:

Info:   visiting unvisited references
Info:   visiting unvisited references
Info:   JTS5014: Recoverable JTS instance, serverId = [3700]
Warning:   RAR8000 : The method setDestinationLookup is not present in the class : org.apache.activemq.ra.ActiveMQActivationSpec
Warning:   RAR7097: No setter method present for the property destinationLookup in the class org.apache.activemq.ra.ActiveMQActivationSpec
Info:   2017-06-06 11:43:00,675 [min-listener(1)] INFO  ActiveMQEndpointWorker         - Starting
Info:   2017-06-06 11:43:00,682 [ad-pool-1; w: 4] INFO  ActiveMQEndpointWorker         - Establishing connection to broker [vm://0.0.0.0:6616]
Info:   WELD-000900: 2.2.13 (Final)
WARN:   WELD-001700: Interceptor annotation class javax.ejb.PostActivate not found, interception based on it is not enabled
WARN:   WELD-001700: Interceptor annotation class javax.ejb.PrePassivate not found, interception based on it is not enabled
WARN:   WELD-000411: Observer method [BackedAnnotatedMethod] public org.glassfish.jms.injection.JMSCDIExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds.
WARN:   WELD-000411: Observer method [BackedAnnotatedMethod] org.glassfish.sse.impl.ServerSentEventCdiExtension.processAnnotatedType(@Observes ProcessAnnotatedType<Object>, BeanManager) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds.
WARN:   WELD-000411: Observer method [BackedAnnotatedMethod] private org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider.processAnnotatedType(@Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using @WithAnnotations or a generic type with bounds.
Info:   AmdMDB was successfully deployed in 5.290 milliseconds.
Info:   2017-06-06 11:43:31,695 [ad-pool-1; w: 4] ERROR ActiveMQEndpointWorker         - Failed to connect to broker [vm://0.0.0.0:6616]: Could not create Transport. Reason: java.net.URISyntaxException: Illegal character in scheme name at index 0: 0.0.0.0:6616
javax.jms.JMSException: Could not create Transport. Reason: java.net.URISyntaxException: Illegal character in scheme name at index 0: 0.0.0.0:6616
    at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:36)
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:260)
    at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:273)
    at org.apache.activemq.ActiveMQConnectionFactory.createConnection(ActiveMQConnectionFactory.java:194)
    at org.apache.activemq.ra.ActiveMQResourceAdapter.makeConnection(ActiveMQResourceAdapter.java:132)
    at org.apache.activemq.ra.ActiveMQEndpointWorker$1.run(ActiveMQEndpointWorker.java:109)
    at com.sun.enterprise.connectors.work.OneWork.doWork(OneWork.java:107)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
    at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.net.URISyntaxException: Illegal character in scheme name at index 0: 0.0.0.0:6616
    at java.net.URI$Parser.fail(URI.java:2848)
    at java.net.URI$Parser.checkChars(URI.java:3021)
    at java.net.URI$Parser.checkChar(URI.java:3031)
    at java.net.URI$Parser.parse(URI.java:3047)
    at java.net.URI.<init>(URI.java:588)
    at org.apache.activemq.util.URISupport.parseComposite(URISupport.java:390)
    at org.apache.activemq.util.URISupport.parseComposite(URISupport.java:279)
    at org.apache.activemq.transport.vm.VMTransportFactory.doCompositeConnect(VMTransportFactory.java:63)
    at org.apache.activemq.transport.vm.VMTransportFactory.doConnect(VMTransportFactory.java:54)
    at org.apache.activemq.transport.TransportFactory.connect(TransportFactory.java:64)
    at org.apache.activemq.ActiveMQConnectionFactory.createTransport(ActiveMQConnectionFactory.java:258)
    ... 7 more
Info:   2017-06-06 11:43:31,697 [ad-pool-1; w: 4] ERROR ActiveMQEndpointWorker         - Endpoint will try to reconnect to the JMS broker in 30 seconds
Info:   2017-06-06 11:43:40,060 [jb-thread-pool1] INFO  ActiveMQEndpointWorker         - Stopping

The Stopping at the end is due to the undeployment I did, because the same error would come every thirty seconds with the reconnection try.

I am not quite sure, where the error is. The port is 6616 by the way isn't a typo, it is the actual port where ActiveMQ is running because port 61616 is in use by another process.

Can you please give me a hint, on where to search for the mistake?

By the way: When I send a message to the queue with the standalone client, no Exception is thrown (so this seems to be working.) However, I am also unable to send a message via the ActiveMQ Admin console to the server.

Thanks a lot...

Body:
According to http://activemq.apache.org/vm-transport-reference.html, when using activemq vm tranport, it should be the broker name after "vm://".

If want to use the ip and port, config this way:

vm:(broker:(tcp://localhost:6000)?persistent=false)?marshal=false


问:
How to pass enum as method parameter?
The task is to write a simple method that can sort int array (in ascending or descending order - should be set as enum type parameter of this method). I have written the method itself and enum, but I have no idea how to set enum as method parameter:( </p>

<p>Would be great to get any help from you, guys, cause I am completely new to coding. </p>

```<code>class Program
{

    public enum options
    {
        UpSortOption,
        DownSortOption
    }

    public static void Main(string[] args)
    {
        int[] arr = new int[] { 3, 8, 0, 2, 16 };
    }

    static void orderArray(int [] array, options op)
    {
        switch(op)
        {
            case options.UpSortOption:
                Array.Sort(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

            case options.DownSortOption:
                Array.Sort(array);
                Array.Reverse(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

        }
    }
}
</code>```

答:
This is how you pass it as a parameter

```<code>orderArray(int [] array, typeof(options)){
    //Beep bap boop
}
</code>```

Hope this aids you.

Title: How to pass enum as method parameter?

Body:
The task is to write a simple method that can sort int array (in ascending or descending order - should be set as enum type parameter of this method). I have written the method itself and enum, but I have no idea how to set enum as method parameter:(

Would be great to get any help from you, guys, cause I am completely new to coding.

class Program
{

    public enum options
    {
        UpSortOption,
        DownSortOption
    }

    public static void Main(string[] args)
    {
        int[] arr = new int[] { 3, 8, 0, 2, 16 };
    }

    static void orderArray(int [] array, options op)
    {
        switch(op)
        {
            case options.UpSortOption:
                Array.Sort(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

            case options.DownSortOption:
                Array.Sort(array);
                Array.Reverse(array);
                foreach (int number in array)
                {
                    Console.Write(number + " ");
                }
                break;

        }
    }
}

Body:
This is how you pass it as a parameter

orderArray(int [] array, typeof(options)){
    //Beep bap boop
}

Hope this aids you.


问:
How to make a multidimensional array using while loop in C#
I'm a beginner in c# and I have to write a multidimensional array using while loop. I just can't go through it. So far I have made what I exactly need with nested for loop but can't convert it to while loop. Any help would be greatly appreciated.</p>

```<code>int[][] tab = new int[4][];
tab[0] = new int[4];
tab[1] = new int[3];
tab[2] = new int[2];
tab[3] = new int[1];

int num = 1;

for(int i = 0; i < tab.Length; i++)
{
    for(int j = 0; j < tab[i].Length; j++)
    {
        tab[i][j] = num++;
    }
}

for(int i = 0; i < tab.Length; i++)
{
    Console.Write("tab[{0}] = ", i);
    for(int j = 0; j < tab[i].Length; j++)
    {
        Console.Write("{0} ", tab[i][j]);
    }
    Console.WriteLine("");
}
</code>```

答:
Updated answer to remove redundant console write line loop</p>

```<code>while (ai < tab.Length)
{
    bj = 0;
    Console.Write("tab[{0}] = ", ai);
    while (bj < tab[ai].Length)
    {
        tab[ai][bj] = num++;
        Console.Write("{0} ", tab[ai][bj]);
        bj++;
    }
    Console.WriteLine("");
    ai++;
}
</code>```

Body:
I'm a beginner in c# and I have to write a multidimensional array using while loop. I just can't go through it. So far I have made what I exactly need with nested for loop but can't convert it to while loop. Any help would be greatly appreciated.

int[][] tab = new int[4][];
tab[0] = new int[4];
tab[1] = new int[3];
tab[2] = new int[2];
tab[3] = new int[1];

int num = 1;

for(int i = 0; i < tab.Length; i++)
{
    for(int j = 0; j < tab[i].Length; j++)
    {
        tab[i][j] = num++;
    }
}

for(int i = 0; i < tab.Length; i++)
{
    Console.Write("tab[{0}] = ", i);
    for(int j = 0; j < tab[i].Length; j++)
    {
        Console.Write("{0} ", tab[i][j]);
    }
    Console.WriteLine("");
}

Body:
Updated answer to remove redundant console write line loop

while (ai < tab.Length)
{
    bj = 0;
    Console.Write("tab[{0}] = ", ai);
    while (bj < tab[ai].Length)
    {
        tab[ai][bj] = num++;
        Console.Write("{0} ", tab[ai][bj]);
        bj++;
    }
    Console.WriteLine("");
    ai++;
}


问:
Vagrant install docker with puppet
I am trying to install docker on the trusty64 vagrant image:

Vagrantfile

```<code># -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.hostname = "apps.local"
  config.vm.provision "shell", inline: <<-SHELL
    puppet module install garethr-docker
  SHELL

  config.vm.provision "puppet"
end
</code>```

manifests/default.pp

```<code>include 'docker'

docker::image { 'ubuntu':
  image_tag => 'trusty'
}
</code>```

And the output of vagrant up :

```<code>==> default: Running provisioner: shell...
    default: Running: inline script
==> default: Notice: Preparing to install into /etc/puppet/modules ...
==> default: Notice: Downloading from https://forge.puppetlabs.com ...
==> default: Notice: Installing -- do not interrupt ...
==> default: /etc/puppet/modules
==> default: └─┬ garethr-docker (v5.3.0)
==> default:   ├── puppetlabs-apt (v3.0.0)
==> default:   ├── puppetlabs-stdlib (v4.17.0)
==> default:   └── stahnma-epel (v1.2.2)
==> default: Running provisioner: puppet...
==> default: Running Puppet with default.pp...
==> default: Warning: Config file /etc/puppet/hiera.yaml not found, using Hiera defaults
==> default: Error: Syntax error at 'Variant'; expected ')' at /etc/puppet/modules/apt/manifests/init.pp:6 on node carcosa.local
==> default: Error: Syntax error at 'Variant'; expected ')' at /etc/puppet/modules/apt/manifests/init.pp:6 on node carcosa.local
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.
</code>```

Can someone tell me what am I doing wrong ?

答:
If your goal is just to have docker installed on the VM, the easiest is to let vagrant install it. Vagrant has docker provisioner and if not installed it will try to install

This simple Vagrantfile

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

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.provision "docker"
end
</code>```

will install docker on trusty64 - the provisioner has after many advantages if you want to work with docker images etc ...

Title: Vagrant install docker with puppet

Body:
I am trying to install docker on the trusty64 vagrant image:

Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.hostname = "apps.local"
  config.vm.provision "shell", inline: <<-SHELL
    puppet module install garethr-docker
  SHELL

  config.vm.provision "puppet"
end

manifests/default.pp

include 'docker'

docker::image { 'ubuntu':
  image_tag => 'trusty'
}

And the output of vagrant up :

==> default: Running provisioner: shell...
    default: Running: inline script
==> default: Notice: Preparing to install into /etc/puppet/modules ...
==> default: Notice: Downloading from https://forge.puppetlabs.com ...
==> default: Notice: Installing -- do not interrupt ...
==> default: /etc/puppet/modules
==> default: └─┬ garethr-docker (v5.3.0)
==> default:   ├── puppetlabs-apt (v3.0.0)
==> default:   ├── puppetlabs-stdlib (v4.17.0)
==> default:   └── stahnma-epel (v1.2.2)
==> default: Running provisioner: puppet...
==> default: Running Puppet with default.pp...
==> default: Warning: Config file /etc/puppet/hiera.yaml not found, using Hiera defaults
==> default: Error: Syntax error at 'Variant'; expected ')' at /etc/puppet/modules/apt/manifests/init.pp:6 on node carcosa.local
==> default: Error: Syntax error at 'Variant'; expected ')' at /etc/puppet/modules/apt/manifests/init.pp:6 on node carcosa.local
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

Can someone tell me what am I doing wrong ?

Body:
If your goal is just to have docker installed on the VM, the easiest is to let vagrant install it. Vagrant has docker provisioner and if not installed it will try to install

This simple Vagrantfile

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

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.provision "docker"
end

will install docker on trusty64 - the provisioner has after many advantages if you want to work with docker images etc ...


问:
NSTableview - Drag and Drop split into two classes and controllers
i found this helpfully tutorial for realize drag an drop with nstabelview:
https://drive.google.com/open?id=0B8PBtMQt9GdONzV3emZGQWUtdmM

this works fine.

but i would like to split both table views into differente view controllers and classes with a split view:

one split view controller:

item 1: viewcontroller with source nstableview (SourceTableView.class)

item 2: viewcontroller with target nstableview (TargetTableView.class)

how can i do this with this project?
i know how can i create a split view controller in storyboard.
but i dont know, if i have two different classes, how the iBoutlet SourceTabelView of class SourceTableView.class assign the iBoutlet TargetTableView of class TargetTableView.class

UPDATE

```<code>var person = [Person]()
</code>```

NSManagedObject.class

```<code>import Foundation
import CoreData

@objc(Person)
public class Person: NSManagedObject {
    @NSManaged public var firstName: String
    @NSManaged public var secondName: String
}
</code>```

答:
Example of drag and drop between two table views inside a split view. Dragging inside one table view and multiple selection will work. Hold the Option key to drag a copy.

The datasource of each table view is the view controller inside the split view. Each table view has its own view controller and each view controller controls one table view. Both view controllers are the same NSViewController subclass:

```<code>class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {

    @IBOutlet weak var myTableView: NSTableView!
    var dataArray: NSMutableArray = ["John Doe", "Jane Doe", "Mary Jane"]

    override func viewDidLoad() {
        super.viewDidLoad()
        myTableView.register(forDraggedTypes: ["com.yoursite.yourproject.yourstringstype"])
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    // NSTableViewDataSource data methods

    func numberOfRows(in tableView: NSTableView) -> Int {
        return dataArray.count
    }

    func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
        return dataArray[row] as AnyObject!;
    }

    // NSTableViewDataSource drag methods

    func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
        // the dragging destination needs the strings of the rows to add to its own data,
        // we, the dragging source, need the indexes of the rows to remove the dropped rows.
        pboard.declareTypes(["com.yoursite.yourproject.yourstringstype", "com.yoursite.yourproject.yourindexestype"],
            owner: nil)
        pboard.setData(NSKeyedArchiver.archivedData(withRootObject: (dataArray as NSArray).objects(at:rowIndexes as IndexSet)), forType: "com.yoursite.yourproject.yourstringstype")
        pboard.setData(NSKeyedArchiver.archivedData(withRootObject: rowIndexes), forType: "com.yoursite.yourproject.yourindexestype")
        return true
    }

    func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession,
            endedAt screenPoint: NSPoint, operation: NSDragOperation) {
        // remove the dragged rows if the rows are dragged to the trash or were moved to somewhere else.
        var removeRows = false
        if operation == .delete {
            // trash
            removeRows = true
        } else if operation == .move {
            // check if the point where the rows were dropped is inside our table view.
            let windowRect = tableView.convert(tableView.bounds, to: nil)
            let screenRect = view.window!.convertToScreen(windowRect)
            if !NSPointInRect(screenPoint, screenRect) {
                removeRows = true
            }
        }
        if removeRows {
            // remove the rows, the indexes are on the pasteboard
            let data = session.draggingPasteboard.data(forType: "com.yoursite.yourproject.yourindexestype")!
            let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: data) as! NSIndexSet
            (dataArray as NSMutableArray).removeObjects(at: rowIndexes as IndexSet)
            tableView.reloadData()
        }
    }

    // NSTableViewDataSource drop methods

    func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int,
            proposedDropOperation dropOperation: NSTableViewDropOperation) -> NSDragOperation {
        // only accept drop above rows, not on rows.
        if dropOperation == .above {
            // return move if the dragging source allows move
            if info.draggingSourceOperationMask().contains(.move) {
                return .move
            }
            // return copy if the dragging source allows copy
            if info.draggingSourceOperationMask().contains(.copy) {
                return .copy
            }
        }
        return []
    }

    func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int,
            dropOperation: NSTableViewDropOperation) -> Bool {
        // if the rows were moved inside the same table view we do a reorder
        var dropRow = row
        if info.draggingSource() as AnyObject === myTableView as AnyObject &&
            info.draggingSourceOperationMask().contains(.move) {
            // remove the rows from their old position
            let data = info.draggingPasteboard().data(forType: "com.yoursite.yourproject.yourindexestype")!
            let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: data) as! NSIndexSet
            (dataArray as NSMutableArray).removeObjects(at: rowIndexes as IndexSet)
            // recalculate the row of the drop
            dropRow -= rowIndexes.countOfIndexes(in: NSMakeRange(0, dropRow))
        }
        // insert the dragged rows
        let data = info.draggingPasteboard().data(forType: "com.yoursite.yourproject.yourstringstype")!
        let draggedStrings = NSKeyedUnarchiver.unarchiveObject(with: data) as! [Any]
        dataArray.insert(draggedStrings, at:IndexSet(integersIn:dropRow..<(dropRow + draggedStrings.count)))
        tableView.reloadData()
        return true
    }

}
</code>```

To make dragging to the trash work, subclass NSTableView and override:

```<code>override func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor
        context: NSDraggingContext) -> NSDragOperation {
    let test = super.draggingSession(session, sourceOperationMaskFor: context)
    Swift.print("sourceOperationMaskFor \(test)")
    switch context {
        case .withinApplication:
            return [.move, .copy]
        case .outsideApplication:
            return [.delete]
    }
}
</code>```

p.s. I'm not familiar with Swift and had some trouble with arrays and indexsets so I used NSMutableArray and NSIndexSet.

Body:
i found this helpfully tutorial for realize drag an drop with nstabelview:
https://drive.google.com/open?id=0B8PBtMQt9GdONzV3emZGQWUtdmM

this works fine.

but i would like to split both table views into differente view controllers and classes with a split view:

one split view controller:

item 1: viewcontroller with source nstableview (SourceTableView.class)

item 2: viewcontroller with target nstableview (TargetTableView.class)

how can i do this with this project?
i know how can i create a split view controller in storyboard.
but i dont know, if i have two different classes, how the iBoutlet SourceTabelView of class SourceTableView.class assign the iBoutlet TargetTableView of class TargetTableView.class

UPDATE

var person = [Person]()

NSManagedObject.class

import Foundation
import CoreData

@objc(Person)
public class Person: NSManagedObject {
    @NSManaged public var firstName: String
    @NSManaged public var secondName: String
}

Body:
Example of drag and drop between two table views inside a split view. Dragging inside one table view and multiple selection will work. Hold the Option key to drag a copy.

The datasource of each table view is the view controller inside the split view. Each table view has its own view controller and each view controller controls one table view. Both view controllers are the same NSViewController subclass:

class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {

    @IBOutlet weak var myTableView: NSTableView!
    var dataArray: NSMutableArray = ["John Doe", "Jane Doe", "Mary Jane"]

    override func viewDidLoad() {
        super.viewDidLoad()
        myTableView.register(forDraggedTypes: ["com.yoursite.yourproject.yourstringstype"])
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    // NSTableViewDataSource data methods

    func numberOfRows(in tableView: NSTableView) -> Int {
        return dataArray.count
    }

    func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
        return dataArray[row] as AnyObject!;
    }

    // NSTableViewDataSource drag methods

    func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
        // the dragging destination needs the strings of the rows to add to its own data,
        // we, the dragging source, need the indexes of the rows to remove the dropped rows.
        pboard.declareTypes(["com.yoursite.yourproject.yourstringstype", "com.yoursite.yourproject.yourindexestype"],
            owner: nil)
        pboard.setData(NSKeyedArchiver.archivedData(withRootObject: (dataArray as NSArray).objects(at:rowIndexes as IndexSet)), forType: "com.yoursite.yourproject.yourstringstype")
        pboard.setData(NSKeyedArchiver.archivedData(withRootObject: rowIndexes), forType: "com.yoursite.yourproject.yourindexestype")
        return true
    }

    func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession,
            endedAt screenPoint: NSPoint, operation: NSDragOperation) {
        // remove the dragged rows if the rows are dragged to the trash or were moved to somewhere else.
        var removeRows = false
        if operation == .delete {
            // trash
            removeRows = true
        } else if operation == .move {
            // check if the point where the rows were dropped is inside our table view.
            let windowRect = tableView.convert(tableView.bounds, to: nil)
            let screenRect = view.window!.convertToScreen(windowRect)
            if !NSPointInRect(screenPoint, screenRect) {
                removeRows = true
            }
        }
        if removeRows {
            // remove the rows, the indexes are on the pasteboard
            let data = session.draggingPasteboard.data(forType: "com.yoursite.yourproject.yourindexestype")!
            let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: data) as! NSIndexSet
            (dataArray as NSMutableArray).removeObjects(at: rowIndexes as IndexSet)
            tableView.reloadData()
        }
    }

    // NSTableViewDataSource drop methods

    func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int,
            proposedDropOperation dropOperation: NSTableViewDropOperation) -> NSDragOperation {
        // only accept drop above rows, not on rows.
        if dropOperation == .above {
            // return move if the dragging source allows move
            if info.draggingSourceOperationMask().contains(.move) {
                return .move
            }
            // return copy if the dragging source allows copy
            if info.draggingSourceOperationMask().contains(.copy) {
                return .copy
            }
        }
        return []
    }

    func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int,
            dropOperation: NSTableViewDropOperation) -> Bool {
        // if the rows were moved inside the same table view we do a reorder
        var dropRow = row
        if info.draggingSource() as AnyObject === myTableView as AnyObject &&
            info.draggingSourceOperationMask().contains(.move) {
            // remove the rows from their old position
            let data = info.draggingPasteboard().data(forType: "com.yoursite.yourproject.yourindexestype")!
            let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: data) as! NSIndexSet
            (dataArray as NSMutableArray).removeObjects(at: rowIndexes as IndexSet)
            // recalculate the row of the drop
            dropRow -= rowIndexes.countOfIndexes(in: NSMakeRange(0, dropRow))
        }
        // insert the dragged rows
        let data = info.draggingPasteboard().data(forType: "com.yoursite.yourproject.yourstringstype")!
        let draggedStrings = NSKeyedUnarchiver.unarchiveObject(with: data) as! [Any]
        dataArray.insert(draggedStrings, at:IndexSet(integersIn:dropRow..<(dropRow + draggedStrings.count)))
        tableView.reloadData()
        return true
    }

}

To make dragging to the trash work, subclass NSTableView and override:

override func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor
        context: NSDraggingContext) -> NSDragOperation {
    let test = super.draggingSession(session, sourceOperationMaskFor: context)
    Swift.print("sourceOperationMaskFor \(test)")
    switch context {
        case .withinApplication:
            return [.move, .copy]
        case .outsideApplication:
            return [.delete]
    }
}

p.s. I'm not familiar with Swift and had some trouble with arrays and indexsets so I used NSMutableArray and NSIndexSet.


问:
filter datatable using parent id

I have a datatable and it has 2 fields FolderId,Parent_Id .

I want to filter all children of a parent and save it into another datatable.
I'm able to achieve this using two methods and 3 different loop, isnt there a more simple and fast way to achieve this using Linq or something.

Here is my code

```<code> public DataTable ChildrenOf(string parent, DataTable dtFolders)
{
    DataTable result = new DataTable();
    try
    {
        if (dtFolders != null)
        {
            result = dtFolders.Clone();
            foreach (DataRow child in dtFolders.Rows)
            {

                if (child["FolderId"].ToString() == parent)
                {
                    result.Rows.Add(child.ItemArray);
                }
            }
            foreach (DataRow dr in dtFolders.Rows)
            {
                if (ChildrenOfParent(parent, dtFolders) != null)
                {
                    result.Rows.Add(ChildrenOfParent(parent, dtFolders).ItemArray);
                    parent = ChildrenOfParent(parent, dtFolders).ItemArray[0].ToString();
                }
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
    return result;
}

public DataRow ChildrenOfParent(string parent, DataTable dtChild)
{
    DataRow drChild;
    drChild = null;
    try
    {
        foreach (DataRow dr in dtChild.Rows)
        {
            if (dr["ParentId"].ToString() == parent)
            {
                drChild = dr;
            }
        }
    }
    catch (Exception)
    {
        throw;
    }

    return drChild;
}
</code>```

答:
try code </p>

```<code>public DataTable ChildrenOf(string parent, DataTable dtFolders)
{
    DataTable result = new DataTable();
    try
    {
       if (dtFolders != null)
       {
          result = dtFolders.Clone();
          foreach (DataRow child in dtFolders.Rows)
          {

            if (child["FolderId"].ToString() == parent)
            {
                result.Rows.Add(child.ItemArray);
            }

            if (child ["ParentId"]!=null && child ["ParentId"].ToString() == parent)
            {
                result.Rows.Add(child.ItemArray);
                parent =child.ItemArray.ToString();
            }

         }

    }
}
catch (Exception)
{
    throw;
}
return result;

}
</code>```

Title: filter datatable using parent id

Body:
I have a datatable and it has 2 fields FolderId,Parent_Id .

I want to filter all children of a parent and save it into another datatable.
I'm able to achieve this using two methods and 3 different loop, isnt there a more simple and fast way to achieve this using Linq or something.

Here is my code

 public DataTable ChildrenOf(string parent, DataTable dtFolders)
{
    DataTable result = new DataTable();
    try
    {
        if (dtFolders != null)
        {
            result = dtFolders.Clone();
            foreach (DataRow child in dtFolders.Rows)
            {

                if (child["FolderId"].ToString() == parent)
                {
                    result.Rows.Add(child.ItemArray);
                }
            }
            foreach (DataRow dr in dtFolders.Rows)
            {
                if (ChildrenOfParent(parent, dtFolders) != null)
                {
                    result.Rows.Add(ChildrenOfParent(parent, dtFolders).ItemArray);
                    parent = ChildrenOfParent(parent, dtFolders).ItemArray[0].ToString();
                }
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
    return result;
}

public DataRow ChildrenOfParent(string parent, DataTable dtChild)
{
    DataRow drChild;
    drChild = null;
    try
    {
        foreach (DataRow dr in dtChild.Rows)
        {
            if (dr["ParentId"].ToString() == parent)
            {
                drChild = dr;
            }
        }
    }
    catch (Exception)
    {
        throw;
    }

    return drChild;
}

Body:
try code

public DataTable ChildrenOf(string parent, DataTable dtFolders)
{
    DataTable result = new DataTable();
    try
    {
       if (dtFolders != null)
       {
          result = dtFolders.Clone();
          foreach (DataRow child in dtFolders.Rows)
          {

            if (child["FolderId"].ToString() == parent)
            {
                result.Rows.Add(child.ItemArray);
            }

            if (child ["ParentId"]!=null && child ["ParentId"].ToString() == parent)
            {
                result.Rows.Add(child.ItemArray);
                parent =child.ItemArray.ToString();
            }

         }

    }
}
catch (Exception)
{
    throw;
}
return result;

}


答:
Exactly that's how you set up Enum as a method parameter.

To call this method use:

```<code>orderArray(arr, options.UpSortOption);
</code>```

You can also assign enum value to a variable and use this to call a method:

```<code>options sortOpt = options.UpSortOption;
orderArray(arr, sortOpt);
</code>```

You can also cast integer to an enum:

```<code>orderArray(arr, (options)0);

OR

int opt = 0;
orderArray(arr, (options)opt);
</code>```

Remembering, that if not specified otherwise, first element is 0, second is 1 and so on.

By the way, you should rather use PascalCase to name an enum type, like:

```<code>public enum Options
{ ... }
</code>```

Title: How to pass enum as method parameter?

Body:
Exactly that's how you set up Enum as a method parameter.

To call this method use:

orderArray(arr, options.UpSortOption);

You can also assign enum value to a variable and use this to call a method:

options sortOpt = options.UpSortOption;
orderArray(arr, sortOpt);

You can also cast integer to an enum:

orderArray(arr, (options)0);

OR

int opt = 0;
orderArray(arr, (options)opt);

Remembering, that if not specified otherwise, first element is 0, second is 1 and so on.

By the way, you should rather use PascalCase to name an enum type, like:

public enum Options
{ ... }


问:
pass the variable as class name in jquery
I have the class name 'views-row5' in a variable 'classN'.I want to pass this to the jquery for find the class name 'views-row5' using variable 'classN' and add the class 'hello'.

jQuery(document).ready(function($) {
var classN="views-row5"
$('.carousel-inner li').each(function()
  {$(this).find(classN).addClass('hello');});
 }); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner">
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
</div></code>```

答:
jQuery(document).ready(function($) {
  var classN = "views-row5"
  $('.carousel-inner li').each(function() {
    $(this).find("."+classN).addClass('hello');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hello {
  color: red
}</code>```

1

2

1

2

```

Add . to find the class you are looking for

Body:
I have the class name 'views-row5' in a variable 'classN'.I want to pass this to the jquery for find the class name 'views-row5' using variable 'classN' and add the class 'hello'.

jQuery(document).ready(function($) {
var classN="views-row5"
$('.carousel-inner li').each(function()
  {$(this).find(classN).addClass('hello');});
 });

1

2

1

2

Body:
jQuery(document).ready(function($) {
  var classN = "views-row5"
  $('.carousel-inner li').each(function() {
    $(this).find("."+classN).addClass('hello');
  });
});

.hello {
  color: red
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner">
  <li>
    <div class="views-row4">1</div>
    <div class="views-row5">2</div>
  </li>
  <li>
    <div class="views-row4">1</div>
    <div class="views-row5">2</div>
  </li>
</div>

Add . to find the class you are looking for


答:
you are forget the . represent the class in selector

jQuery(document).ready(function($) {
var classN="views-row5"
$('.carousel-inner li').each(function()
  {$(this).find('.'+classN).addClass('hello');});
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hello{
color:green;
font-size:20px;
}</code>```

1

2

1

2

```

Title: pass the variable as class name in jquery

Body:
you are forget the . represent the class in selector

jQuery(document).ready(function($) {
var classN="views-row5"
$('.carousel-inner li').each(function()
  {$(this).find('.'+classN).addClass('hello');});
 });

.hello{
color:green;
font-size:20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner">
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
  <li>
     <div class="views-row4">1</div>
     <div class="views-row5">2</div>
  </li>
</div>


问:
Android: Sending user a notification 7 days before a certain date.
I am trying to create an app that sends an android notification 7 days before a specified date. Right now, I am reading in the right date and setting the calendar correctly, but for some reason, the alarm is not triggering. Additionally, when I do adb shell dumpsys alarm to see if the alarm is set, the dump does not display any alarms related to my app. My code that creates the AlarmManager and notification right now is

```<code>calendar.set(year, month, day, hour, min);
calendar.add(Calendar.DAY_OF_MONTH, -7);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent intent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
PendingIntent broadcast = PendingIntent.getBroadcast(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);
</code>```

What could be going wrong with this? Is this not the correct way to set an alarm? I got the idea from here

答:
I am doing to the following:
use getNotification() and your calandar.getTime() as parameters for scheduleNotification

```<code>private void scheduleNotification(Notification notification, Date alarmTime) {

    Intent notificationIntent = new Intent(this, NotificationReceiver.class);
    notificationIntent.putExtra(NotificationReceiver.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(NotificationReceiver.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime.getTime(), pendingIntent);
}

private Notification getNotification() {
    int colour = getNotificationColour();
    Bitmap largeNotificationImage = getLargeNotificationImage();
    return new RandomNotification(this).getNotification(
            "Text",
            "More text",
            getNotificationImage(),
            largeNotificationImage,
            colour);
}

private int getNotificationColour() {
    return ContextCompat.getColor(this, R.color.colorAccent);
}

private Bitmap getLargeNotificationImage() {
    return BitmapFactory.decodeResource(this.getResources(),
            R.mipmap.ic_launcher);
}
</code>```

My RandomNotification Class:

```<code>public class RandomNotification {

    private Context context;

    public RandomNotification(Context context) {
        this.context = context;
    }

    public Notification getNotification(String title, String message, int imageResourceId, Bitmap largeResource, int colour) {

        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Notification.Builder builder = new Notification.Builder(context)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(imageResourceId)
                .setLargeIcon(largeResource)
                .setTicker("Ticker")
                .addAction(0, "Button", getButtonIntent())
                .setSound(soundUri)
                .setLights(Color.BLUE, 300, 100)
                .setAutoCancel(true)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(getPendingNotificationIntent());

        handleNotificationColor(builder, colour);

        Notification notification = builder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
        return notification;
    }

    private Notification.Builder handleNotificationColor(Notification.Builder builder, int colour) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setColor(colour);
        }
        return builder;
    }

    private PendingIntent getPendingNotificationIntent() {
        Intent notificationIntent = new Intent(context, HomeActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context, 1,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        return pendingNotificationIntent;
    }

    private PendingIntent getButtonIntent() {
        Intent notificationButtonReceiver = new Intent(context, NotificationButtonReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationButtonReceiver, PendingIntent.FLAG_CANCEL_CURRENT);
        return pendingIntent;
    }

}
</code>```

My notification button receiver class:

```<code>public class NotificationButtonReceiver extends BroadcastReceiver {

    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        // do something

    }

}
</code>```

My updated notification receiver class

```<code>public class NotificationReceiver extends BroadcastReceiver {

    public static String NOTIFICATION_ID = "notification-id";

    public static String NOTIFICATION = "notification";

    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        notificationManager.notify(id, notification);
    }
}
</code>```

My manifest file:

```<code><receiver
    android:name=".NotificationButtonReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.NOTIFY" />
    </intent-filter>
</receiver>
    <receiver
        android:name=".NotificationReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.NOTIFY" />
        </intent-filter>
    </receiver>
</code>```

Body:
I am trying to create an app that sends an android notification 7 days before a specified date. Right now, I am reading in the right date and setting the calendar correctly, but for some reason, the alarm is not triggering. Additionally, when I do adb shell dumpsys alarm to see if the alarm is set, the dump does not display any alarms related to my app. My code that creates the AlarmManager and notification right now is

calendar.set(year, month, day, hour, min);
calendar.add(Calendar.DAY_OF_MONTH, -7);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent intent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
PendingIntent broadcast = PendingIntent.getBroadcast(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);

What could be going wrong with this? Is this not the correct way to set an alarm? I got the idea from here

Body:
I am doing to the following:
use getNotification() and your calandar.getTime() as parameters for scheduleNotification

private void scheduleNotification(Notification notification, Date alarmTime) {

    Intent notificationIntent = new Intent(this, NotificationReceiver.class);
    notificationIntent.putExtra(NotificationReceiver.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(NotificationReceiver.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime.getTime(), pendingIntent);
}

private Notification getNotification() {
    int colour = getNotificationColour();
    Bitmap largeNotificationImage = getLargeNotificationImage();
    return new RandomNotification(this).getNotification(
            "Text",
            "More text",
            getNotificationImage(),
            largeNotificationImage,
            colour);
}

private int getNotificationColour() {
    return ContextCompat.getColor(this, R.color.colorAccent);
}

private Bitmap getLargeNotificationImage() {
    return BitmapFactory.decodeResource(this.getResources(),
            R.mipmap.ic_launcher);
}

My RandomNotification Class:

public class RandomNotification {

    private Context context;

    public RandomNotification(Context context) {
        this.context = context;
    }

    public Notification getNotification(String title, String message, int imageResourceId, Bitmap largeResource, int colour) {

        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Notification.Builder builder = new Notification.Builder(context)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(imageResourceId)
                .setLargeIcon(largeResource)
                .setTicker("Ticker")
                .addAction(0, "Button", getButtonIntent())
                .setSound(soundUri)
                .setLights(Color.BLUE, 300, 100)
                .setAutoCancel(true)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(getPendingNotificationIntent());

        handleNotificationColor(builder, colour);

        Notification notification = builder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
        return notification;
    }

    private Notification.Builder handleNotificationColor(Notification.Builder builder, int colour) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setColor(colour);
        }
        return builder;
    }

    private PendingIntent getPendingNotificationIntent() {
        Intent notificationIntent = new Intent(context, HomeActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context, 1,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        return pendingNotificationIntent;
    }

    private PendingIntent getButtonIntent() {
        Intent notificationButtonReceiver = new Intent(context, NotificationButtonReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationButtonReceiver, PendingIntent.FLAG_CANCEL_CURRENT);
        return pendingIntent;
    }

}

My notification button receiver class:

public class NotificationButtonReceiver extends BroadcastReceiver {

    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        // do something

    }

}

My updated notification receiver class

public class NotificationReceiver extends BroadcastReceiver {

    public static String NOTIFICATION_ID = "notification-id";

    public static String NOTIFICATION = "notification";

    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        notificationManager.notify(id, notification);
    }
}

My manifest file:

<receiver
    android:name=".NotificationButtonReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.NOTIFY" />
    </intent-filter>
</receiver>
    <receiver
        android:name=".NotificationReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.NOTIFY" />
        </intent-filter>
    </receiver>


问:
Running python code on server
I'm building a website with some backprocessing with python. I want to know how to execute my python code from the server ?

There is no direct link between my HTML pages and my python code.

Let's say I want to do an addition with python in the server, how can I do that ?

Thanks so much in advence :)

答:
is your server is linux or windows?

for linux: you can add a script to run your script on runlevel 3 or 5
write a script put it under /etc/init.d/ folder then link your script /etc/rc3.d or /etc/rc5.d to be start

Title: Running python code on server


问:
How to open links in new browser window using ie 11
Can I open links on click in new browser (not a popup) window?

Things I have tried:

```<code><a href='http://osric.net/' onclick='return !window.open(this.href);'>osric.net web hosting</a>
</code>```

A function onclick:

```<code>var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes, toolbar=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
}
</code>```

but with these it opens in new tab only.

答:
This works on IE 11:

```<code><script>
function popupBrowser(url) {
  window.open(url, "WindowName", "config=menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes,fullscreen=yes");
}
</script>

<a href="javascript:popupBrowser('http://www.cnn.com')">Open a new browser for IE11</a>
</code>```

It just imitates browser by using windows.open()

JSFiddle demo

Body:
Can I open links on click in new browser (not a popup) window?

Things I have tried:

osric.net web hosting

A function onclick:

var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes, toolbar=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
}

but with these it opens in new tab only.

Body:
This works on IE 11:

<script>
function popupBrowser(url) {
  window.open(url, "WindowName", "config=menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes,fullscreen=yes");
}
</script>

<a href="javascript:popupBrowser('http://www.cnn.com')">Open a new browser for IE11</a>

It just imitates browser by using windows.open()

JSFiddle demo


问:
Wordpress/PHP: Shorten title if title characters are more than 8 characters
I am trying to learn how to shorten a title only if it is over 8 characters long. If it is longer than 8 characters, then echo the first 8 characters and put an ellipse after it.

Here is how I am getting the title:

<?php echo $post->post_title ?>

Any help would be greatly appreciated. This will be a great learning lesson for me so I can replicate this in the future, so again any help would be amazing.

答:
```<code><?php

    if (strlen($post->post_title) > 8)
       echo substr($post->post_title, 0, 8) . ' ...';
    else
       echo $post->post_title;

?>
</code>```

Alternatively, if You have the mbstring extension is enabled, there's also a shorter way as suggested by Gordon's answer. If the post's encoding is multibyte, You'd need to use mbstring anyway, otherwise characters are counted incorrectly.

```<code>echo mb_strimwidth($post->title, 0, 8, ' ...');
</code>```

Body:
<?php

    if (strlen($post->post_title) > 8)
       echo substr($post->post_title, 0, 8) . ' ...';
    else
       echo $post->post_title;

?>

Alternatively, if You have the mbstring extension is enabled, there's also a shorter way as suggested by Gordon's answer. If the post's encoding is multibyte, You'd need to use mbstring anyway, otherwise characters are counted incorrectly.

echo mb_strimwidth($post->title, 0, 8, ' ...');