问:
select a div with a certain data attribute without each loop
```<code><div class='bwrap' data-x='home01'></div>
<div class='bwrap hidden' data-x='home02'></div>
<div class='bwrap hidden' data-x='home03'></div>
<div class='bwrap hidden' data-x='home04'></div>
</code>```

I want to show .bwrap with data-x='home04' without each loop.

According to this I tried:

js

```<code>var obj = $('.bwrap[data-x="home04"]');
obj.show();
</code>```

Nothing happens.

答:
Your code worked fine if:-

1.jQuery library added before your script code.

2.code is wrapped inside $(document).ready(function(){...});

3.Since div have no text that's why you may confuse that it's not shown. Add some text to that div and check.

Working example:-

$(document).ready(function(){
  var obj = $('.bwrap[data-x="home04"]');
  obj.show();
  //can change in one-liner like :- $('.bwrap[data-x="home04"]').show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden{
  display:none;
}</code>```

01

02

03

04
```

Body:
I want to show .bwrap with data-x='home04' without each loop.

According to this I tried:

js

var obj = $('.bwrap[data-x="home04"]');
obj.show();

Nothing happens.

Body:
Your code worked fine if:-

1.jQuery library added before your script code.

2.code is wrapped inside $(document).ready(function(){...});

3.Since div have no text that's why you may confuse that it's not shown. Add some text to that div and check.

Working example:-

$(document).ready(function(){
  var obj = $('.bwrap[data-x="home04"]');
  obj.show();
  //can change in one-liner like :- $('.bwrap[data-x="home04"]').show();
});

.hidden{
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!-- jQuery library needed-->
<div class='bwrap' data-x='home01'>01</div><!-- added text to show that your code worked-->
<div class='bwrap hidden' data-x='home02'>02</div><!-- added text to show that your code worked-->
<div class='bwrap hidden' data-x='home03'>03</div><!-- added text to show that your code worked-->
<div class='bwrap hidden' data-x='home04'>04</div><!-- added text to show that your code worked-->


来源: stackexchange

问:
when i try to register by my app i didn't get any respnse
I am trying to save my data to server. can any one help me?

when i am trying to save data through browser it is working fine but when i try it through this code doesn'n give any response??

```<code>public class Register extends AppCompatActivity implements View.OnClickListener {

private static final String TAG = "dRegister";
EditText etName, etEmail, etMobile, etPassword, /*etRePassword*/
        etCity;
Button register;

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

    etName = (EditText) findViewById(R.id.name);
    etEmail = (EditText) findViewById(R.id.email);
    etMobile = (EditText) findViewById(R.id.mobile);
    etCity = (EditText) findViewById(R.id.etCity);
    etPassword = (EditText) findViewById(R.id.password);
    //etRePassword = (EditText) findViewById(R.id.rePassword);
    register = (Button) findViewById(R.id.bRegister);
    register.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    final String name = etName.getText().toString();
    final String email = etEmail.getText().toString();
    final String password = etPassword.getText().toString();
    final String city = etCity.getText().toString();
    final String phoneno = etMobile.getText().toString();

    StringRequest registerRequest = new StringRequest(Request.Method.POST,RegisterRequest.REGISTER_REQUEST_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + " Response");
            if(response.equals("SUCCESS")){
                startActivity(new Intent(Register.this,MainActivity.class));
            }
            else{
                Toast.makeText(Register.this, "You have not Registered!", Toast.LENGTH_SHORT).show();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error " + error.toString());
            if(error.networkResponse == null){
                if(error.getClass().equals(TimeoutError.class));
                Toast.makeText(Register.this, "oops Time out error!", Toast.LENGTH_SHORT).show();
            }
        }
    }){
        @Override
        public Map<String, String> getHeaders()throws AuthFailureError{
            Map<String, String> headers = new HashMap<>();
            headers.put("name",name);
            headers.put("email",email);
            headers.put("password",password);
            headers.put("city",city);
            headers.put("phoneno",phoneno);
            return headers;
        }
    };
    registerRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 15,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    /*Response.Listener<String> responseListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + "");
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");
                if (success) {
                    Intent intent = new Intent(Register.this, MainActivity.class);
                    startActivity(intent);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                    builder.setMessage("Registration failed").setNegativeButton("Retry", null)
                            .create().show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    RegisterRequest registerRequest = new RegisterRequest(name, email, city, phoneno, password, responseListener){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            //super.getHeaders();
            Map<String,String> headers = new HashMap<>();
            String credential = "raju@gmail.com:123";
            String auth = "Basic "+ Base64.encodeToString(credential.getBytes(),Base64.NO_WRAP);
            //headers.put("Content-Type");
            headers.put("Authorization",auth);
            //
            return headers;
        }
    };*/
            RequestQueue queue = Volley.newRequestQueue(Register.this);
            registerRequest.setShouldCache(false);
            queue.add(registerRequest);
}
}
</code>```

Here Is my server code....

```<code>@RequestMapping(value = "/savemobileUser", method = RequestMethod.POST)
public @ResponseBody String saveUser(@RequestBody MobileUserModel mobileUser) {

    MobileUserModel user = new MobileUserModel();
    user.setActivationKey(mobileUser.getActivationKey());
    user.setCity(mobileUser.getCity());
    user.setEmail(mobileUser.getEmail());

    user.setImeino(mobileUser.getImeino());

    user.setName(mobileUser.getName());

    user.setPassword(mobileUser.getPassword());

    user.setPhoneno(mobileUser.getPhoneno());

    userrepository.save(user);

    System.out.println("Saved");

    // return "User has been saved Successfully";
    return "SUCCESS";

}
</code>```

答: Please provide your json response format and also the parameter type that you are sending. It may occur due to different reasons, for example, there is an json array in response and you are mapping it just in simple object or the attributes (variable) that you are mapping into it, names are not  exactly similar to json response filed or there can be different multiple reasons.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to save my data to server. can any one help me?

when i am trying to save data through browser it is working fine but when i try it through this code doesn'n give any response??

public class Register extends AppCompatActivity implements View.OnClickListener {

private static final String TAG = "dRegister";
EditText etName, etEmail, etMobile, etPassword, /*etRePassword*/
        etCity;
Button register;

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

    etName = (EditText) findViewById(R.id.name);
    etEmail = (EditText) findViewById(R.id.email);
    etMobile = (EditText) findViewById(R.id.mobile);
    etCity = (EditText) findViewById(R.id.etCity);
    etPassword = (EditText) findViewById(R.id.password);
    //etRePassword = (EditText) findViewById(R.id.rePassword);
    register = (Button) findViewById(R.id.bRegister);
    register.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    final String name = etName.getText().toString();
    final String email = etEmail.getText().toString();
    final String password = etPassword.getText().toString();
    final String city = etCity.getText().toString();
    final String phoneno = etMobile.getText().toString();

    StringRequest registerRequest = new StringRequest(Request.Method.POST,RegisterRequest.REGISTER_REQUEST_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + " Response");
            if(response.equals("SUCCESS")){
                startActivity(new Intent(Register.this,MainActivity.class));
            }
            else{
                Toast.makeText(Register.this, "You have not Registered!", Toast.LENGTH_SHORT).show();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error " + error.toString());
            if(error.networkResponse == null){
                if(error.getClass().equals(TimeoutError.class));
                Toast.makeText(Register.this, "oops Time out error!", Toast.LENGTH_SHORT).show();
            }
        }
    }){
        @Override
        public Map<String, String> getHeaders()throws AuthFailureError{
            Map<String, String> headers = new HashMap<>();
            headers.put("name",name);
            headers.put("email",email);
            headers.put("password",password);
            headers.put("city",city);
            headers.put("phoneno",phoneno);
            return headers;
        }
    };
    registerRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 15,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    /*Response.Listener<String> responseListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, response + "");
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");
                if (success) {
                    Intent intent = new Intent(Register.this, MainActivity.class);
                    startActivity(intent);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                    builder.setMessage("Registration failed").setNegativeButton("Retry", null)
                            .create().show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    RegisterRequest registerRequest = new RegisterRequest(name, email, city, phoneno, password, responseListener){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            //super.getHeaders();
            Map<String,String> headers = new HashMap<>();
            String credential = "raju@gmail.com:123";
            String auth = "Basic "+ Base64.encodeToString(credential.getBytes(),Base64.NO_WRAP);
            //headers.put("Content-Type");
            headers.put("Authorization",auth);
            //
            return headers;
        }
    };*/
            RequestQueue queue = Volley.newRequestQueue(Register.this);
            registerRequest.setShouldCache(false);
            queue.add(registerRequest);
}
}

Here Is my server code....

@RequestMapping(value = "/savemobileUser", method = RequestMethod.POST)
public @ResponseBody String saveUser(@RequestBody MobileUserModel mobileUser) {

    MobileUserModel user = new MobileUserModel();
    user.setActivationKey(mobileUser.getActivationKey());
    user.setCity(mobileUser.getCity());
    user.setEmail(mobileUser.getEmail());

    user.setImeino(mobileUser.getImeino());

    user.setName(mobileUser.getName());

    user.setPassword(mobileUser.getPassword());

    user.setPhoneno(mobileUser.getPhoneno());

    userrepository.save(user);

    System.out.println("Saved");

    // return "User has been saved Successfully";
    return "SUCCESS";

}


问:
How does Java makes use of multiple cores?
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. Then how does JVM make use of multiple cores which provide multiple OS threads for high concurrency?</p>

答: Green threads were replaced by native threads in Java 1.2.</p>

ContentLicense: CC BY-SA 2.5


问:
WCF service without using proxy in C#
I have got a WCF service from one of my users. I want to check whether the service is working or not without adding any proxy. Is there any way that I can achieve this in my C# code?</p>

答:
You may achieve this by implementing an endpoint at WCF and querying it from the client.
Following is the WCF code I would use.

```<code>// Used for communication between WCF and client. Must be implemented both WCF and client sides
public class Response {
 public int Id { get; set; }
 public string Data { get; set; }
}

// Web Service - Interface
[ServiceContract]
public interface IService
{
      [OperationContract]
      [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "Up")]
      string CheckLogin();
}

// Web service - Implementation
public class ServiceImplementation : IService
{
  public Response isUp()
  {
         Response response = new Response();
         response.ID = 200;
         response.Data = "web service is up";
         return response;
  }
}
</code>```

Following is the client method to test if the service is up.

```<code>public bool CheckIfUp(string encodedUrl)
{
     WebRequest request;
     WebResponse ws;
     Response response = new Response();
     string url = "http://servicePath/isUp"; // your wcf url
     try
       {
                request = WebRequest.Create(url);
                ws = request.GetResponse();
                return (response.ID == 200);
       }
       catch (Exception e)
       {
                Console.Write(e.StackTrace);
       }
            return false;
 }
</code>```

Hope this helps.

Title: WCF service without using proxy in C#

Body:
You may achieve this by implementing an endpoint at WCF and querying it from the client.
Following is the WCF code I would use.

// Used for communication between WCF and client. Must be implemented both WCF and client sides
public class Response {
 public int Id { get; set; }
 public string Data { get; set; }
}

// Web Service - Interface
[ServiceContract]
public interface IService
{
      [OperationContract]
      [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "Up")]
      string CheckLogin();
}

// Web service - Implementation
public class ServiceImplementation : IService
{
  public Response isUp()
  {
         Response response = new Response();
         response.ID = 200;
         response.Data = "web service is up";
         return response;
  }
}

Following is the client method to test if the service is up.

public bool CheckIfUp(string encodedUrl)
{
     WebRequest request;
     WebResponse ws;
     Response response = new Response();
     string url = "http://servicePath/isUp"; // your wcf url
     try
       {
                request = WebRequest.Create(url);
                ws = request.GetResponse();
                return (response.ID == 200);
       }
       catch (Exception e)
       {
                Console.Write(e.StackTrace);
       }
            return false;
 }

Hope this helps.


问:
MySQL Table - Display name once along with their total score
I have the below data entered into a database from a website:

```<code> USER  |  SCORE
 abc   |    4
 ghi   |    2
 abc   |    6
 def   |    1
 abc   |    3
</code>```

I want to now display a list of all the users, in alphabetical order, without repeating itself, and their total score. So with the table above, it would look something like:

```<code> abc: 13
 def: 1
 ghi: 2
</code>```

How do I do that? I would use php, right? Or javascript?

答:
Try this:

```<code>SELECT User, SUM(Score) as Total_Score
FROM TableName
GROUP BY User
ORDER BY User;
</code>```

No need to use javascript or php to achieve it. SQL is powerful enough to achieve it alone.

Body:
I have the below data entered into a database from a website:

 USER  |  SCORE
 abc   |    4
 ghi   |    2
 abc   |    6
 def   |    1
 abc   |    3

I want to now display a list of all the users, in alphabetical order, without repeating itself, and their total score. So with the table above, it would look something like:

 abc: 13
 def: 1
 ghi: 2

How do I do that? I would use php, right? Or javascript?

Body:
Try this:

SELECT User, SUM(Score) as Total_Score
FROM TableName
GROUP BY User
ORDER BY User;

No need to use javascript or php to achieve it. SQL is powerful enough to achieve it alone.


问:
How do I use an if statement with a returned bool function?
I'm sort of confused on how to return bool values. Basically I need to make a program to check and see if a number is either prime or not. I think I have, for the most part, the right idea, but I'm not quite sure how I'd use an if statement depending on whether or not the bool function returns true or false.Thanks guys</p>

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

bool isPrime(int);
void main()
{
    int InNumber;
    cout << "Enter a number to check if it is prime or not." << endl;
    cin >> InNumber;
    isPrime(InNumber);
    if (isPrime())
    {
        cout << "number is prime." << endl;
    }
}

bool isPrime(int Check)
{
    for (int i = 2; i < Check; i++)
    {
        if (Check % 88 == 0)
            return false;
        else
            return true;
    }
 }
</code>```

答:
You can store the resulting value in a variable, that will be used in the test condition:

```<code>bool isPrimeResult = isPrime(InNumber);
if (isPrimeResult)
{
    cout << "number is prime." << endl;
}
</code>```

Or directly use the resulting value in the test:

```<code>if (isPrime(InNumber))
{
    cout << "number is prime." << endl;
}
</code>```

The first approach is recommended if you have to reuse the returned value many times in the code. The second one is the most recommended in your own case (you just need that value there, so the assignment is "useless").

Body:
I'm sort of confused on how to return bool values. Basically I need to make a program to check and see if a number is either prime or not. I think I have, for the most part, the right idea, but I'm not quite sure how I'd use an if statement depending on whether or not the bool function returns true or false.Thanks guys

#include <iostream>
using namespace std;

bool isPrime(int);
void main()
{
    int InNumber;
    cout << "Enter a number to check if it is prime or not." << endl;
    cin >> InNumber;
    isPrime(InNumber);
    if (isPrime())
    {
        cout << "number is prime." << endl;
    }
}

bool isPrime(int Check)
{
    for (int i = 2; i < Check; i++)
    {
        if (Check % 88 == 0)
            return false;
        else
            return true;
    }
 }

Body:
You can store the resulting value in a variable, that will be used in the test condition:

bool isPrimeResult = isPrime(InNumber);
if (isPrimeResult)
{
    cout << "number is prime." << endl;
}

Or directly use the resulting value in the test:

if (isPrime(InNumber))
{
    cout << "number is prime." << endl;
}

The first approach is recommended if you have to reuse the returned value many times in the code. The second one is the most recommended in your own case (you just need that value there, so the assignment is "useless").


问:
Azure Servicebus: Receive all the message from one session id of a queue
I have 2 question for which I failed to find any solution.

Is there any built in way in azure service bus queue, where I can receive messages only from one session (for that sessionId) in my session handler.

Also is there any way I can receive messages only from the deadlettered queue for that session alone.

I can do this programmatically in my code, but I don't want to write if else logic in my code.

答:
I don't think you can do that for Service Bus queues. You can archieve something similar with Service Bus topic and filtered subscription.

So, you send your messages to a topic, and then you'd have to create a subscription per session ID similar to this:

var filter = new SqlFilter(@"sys.SessionId = \"SESSIONID\"");
namespaceManager.CreateSubscription("YOUR_TOPIC", "SESSIONID_SUBSCRIPTION", filter);
```

<p>and then just receive messages from this subscription:</p>

<pre class="lang-cs prettyprint-override"><code>var client = new SubscriptionClient("...", "YOUR_TOPIC", "SESSIONID_SUBSCRIPTION");
var message = client.Receive();
</code>```

Body:
I don't think you can do that for Service Bus queues. You can archieve something similar with Service Bus topic and filtered subscription.

So, you send your messages to a topic, and then you'd have to create a subscription per session ID similar to this:

var filter = new SqlFilter(@"sys.SessionId = \"SESSIONID\"");
namespaceManager.CreateSubscription("YOUR_TOPIC", "SESSIONID_SUBSCRIPTION", filter);

and then just receive messages from this subscription:

var client = new SubscriptionClient("...", "YOUR_TOPIC", "SESSIONID_SUBSCRIPTION");
var message = client.Receive();


问:
How to test a function with N distinct paths?
I have a function which validates a model class where it has to check every member of the class to be non-null or non-empty in case of a String.

The logic for this is_complete function is something like this:

```<code>def is_complete(profile):
    if profile.first_name in (None, ''):
        return False
    elif profile.last_name in (None, ''):
        return False
    elif profile.dob is None:
        return False
    .
    .
    .# and checks so on for all members of the profile instance
    .
    .

    return True
</code>```

My question since the number of possible paths the execution can take is quite large and increases in proportion to the number of member variables of profile to be checked, how does one reliably write tests for all the possible paths?

Right now, I have two simple test cases:

where only some of the members are set and checks assertFalse(is_complete(foo))

where all the members are set and checks assertTrue(is_complete(foo))

But I have a feeling that this may not be enough.

答:
You can test this with randomization:

Write a function that creates a random Profile object with all the fields filled (could be random, but valid).

Randomly change one or more fields to either None or empty

Pass the object to the is_complete() function.

I can show this only in Java with Qala Datagen. I assume you're interested in the negative paths, so it can look like this:

```<code>@Test void profileIsNotComplete_ifAtLeastOneFieldIsBlank() {
    Profile p = Profile.random();
    callOneOrMore(
        () -> profile.setName(nullOrEmpty()),
        () -> profile.setLastName(nullOrEmpty()),
        ...);
    assertFalse(profile.isComplete();
}
</code>```

Note, that this code actually tests more - it also checks the combination of fields set to null/empty. If in Python there are no such libs, you can write some utility methods for yourself.

NB: only one path is going to be tested per one execution. You can run it many times (a thousand?) to make sure that all the paths pass. Then in CI you can run it only once if this is not a mission-critical functionality and you're not afraid that it's going to break often.

Otherwise if you really want this to be covered 100% for every invocation, you can violate some of the good practices and just combine all these tests in one (otherwise there are going to be too many tests which complicate reading them):

```<code>@Test void profileIsNotComplete_ifOneFieldIsBlank() {
    assertFalse(Profile.random().setName(null).isComplete());
    assertFalse(Profile.random().setName("").isComplete());

    assertFalse(Profile.random().setLastName(null).isComplete());
    assertFalse(Profile.random().setLastName("").isComplete());
    ...
}
</code>```

This doesn't test combinations though, but you can combine both approaches. The positive case is very easy in both approaches:

```<code>@Test void profileIsComplete_ifAllFieldsAreFilled() {
    assertTrue(Profile.random());
}
</code>```

More info on randomized testing is here.

Body:
I have a function which validates a model class where it has to check every member of the class to be non-null or non-empty in case of a String.

The logic for this is_complete function is something like this:

def is_complete(profile):
    if profile.first_name in (None, ''):
        return False
    elif profile.last_name in (None, ''):
        return False
    elif profile.dob is None:
        return False
    .
    .
    .# and checks so on for all members of the profile instance
    .
    .

    return True

My question since the number of possible paths the execution can take is quite large and increases in proportion to the number of member variables of profile to be checked, how does one reliably write tests for all the possible paths?

Right now, I have two simple test cases:

where only some of the members are set and checks assertFalse(is_complete(foo))

where all the members are set and checks assertTrue(is_complete(foo))

But I have a feeling that this may not be enough.

Body:
You can test this with randomization:

Write a function that creates a random Profile object with all the fields filled (could be random, but valid).

Randomly change one or more fields to either None or empty

Pass the object to the is_complete() function.

I can show this only in Java with Qala Datagen. I assume you're interested in the negative paths, so it can look like this:

@Test void profileIsNotComplete_ifAtLeastOneFieldIsBlank() {
    Profile p = Profile.random();
    callOneOrMore(
        () -> profile.setName(nullOrEmpty()),
        () -> profile.setLastName(nullOrEmpty()),
        ...);
    assertFalse(profile.isComplete();
}

Note, that this code actually tests more - it also checks the combination of fields set to null/empty. If in Python there are no such libs, you can write some utility methods for yourself.

NB: only one path is going to be tested per one execution. You can run it many times (a thousand?) to make sure that all the paths pass. Then in CI you can run it only once if this is not a mission-critical functionality and you're not afraid that it's going to break often.

Otherwise if you really want this to be covered 100% for every invocation, you can violate some of the good practices and just combine all these tests in one (otherwise there are going to be too many tests which complicate reading them):

@Test void profileIsNotComplete_ifOneFieldIsBlank() {
    assertFalse(Profile.random().setName(null).isComplete());
    assertFalse(Profile.random().setName("").isComplete());

    assertFalse(Profile.random().setLastName(null).isComplete());
    assertFalse(Profile.random().setLastName("").isComplete());
    ...
}

This doesn't test combinations though, but you can combine both approaches. The positive case is very easy in both approaches:

@Test void profileIsComplete_ifAllFieldsAreFilled() {
    assertTrue(Profile.random());
}

More info on randomized testing is here.


问:
Android 12 hours Time Format getting wrong
I am using

```<code>DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy hh:mm a");
String dateAsString = dateFormat.format(gmt);
</code>```

And getting String 06-06-2017 08:15 a.m.
Why I am getting a.m. instated of AM or PM?

答: The AM/PM/a.m. actually depends on the device. Try the same code on other devices and you might get to see a different result. If you need AM/PM only, then you need to do it manually by replacing the dots and converting it to uppercase.</p>

Body:
I am using

DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy hh:mm a");
String dateAsString = dateFormat.format(gmt);

And getting String 06-06-2017 08:15 a.m.
Why I am getting a.m. instated of AM or PM?


问:
What is the right choice between canvas and svg for circular daily planner
I am a pretty new programmer (wannabe programmer technically) and I would like to ask you guys a question about graphic tools in html5 for my project.
I plan to make a planner app by using electron and the planner form should be round. this is the planner I am talking about. And I want to add event handlers for each circular sector to add new or edit existing lists.
So My question is, Which is the proper method between canvas and svg in this case? What I mean is, which method is easy to implement (or needs shorter codes) and which one has faster rendering speed and better performance?</p>

答:
Find a higher-level library (d3 springs to mind), that looks like it has functions most suitable for your application, and use whatever (canvas, svg, webgl, ...) it is built on.

Other considerations: if your technology choice doesn't work on a platform you need it to, then don't use it. (Unlikely to be an issue, as your tags suggest this is an Electron app.)


问:
Curry universally quantified function
I am trying to write a tactic for currying functions, including universally quantified functions.

```<code>Require Import Coq.Program.Tactics.

Definition curry1 := forall A B C, (A /\ B -> C) -> (A -> B -> C).
Definition curry2 := forall A B, (forall C, A /\ B -> C) -> (forall C, A -> B -> C).
Definition curry3 := forall A, (forall B C, A /\ B -> C) -> (forall B C, A -> B -> C).
(* etc. *)

Ltac curry H :=
  let T := type of H in
  match T with
  | _ /\ _ -> _ =>
    replace_hyp H (fun H1 => fun H2 => H (conj H1 H2))
  | forall x, ?P x =>
    fail 1 "not implemented"
  | _ =>
    fail 1 "not a curried function"
  end.

Example ex1 : curry1.
Proof.
  intros A B C H.
  curry H.
  assumption.
Qed.

Example ex2 : curry2.
Proof.
  intros A B H.
  Fail curry H. (* Tactic failure: not a curried function. *)
  Fail replace_hyp H (fun H1 => let H2 := H H1 in ltac:(curry H2)). (* Cannot infer an existential variable of type "Type" in environment: [...] *)
Abort.
</code>```

How can I extend my curry tactic to handle universally quantified functions?

答:
You can basically pattern-match on all the variants like so:

```<code>Ltac curry H :=
  match type of H with
  | _ /\ _ -> _ =>
      replace_hyp H (fun a b => H (conj a b))
  | forall C, _ /\ _ -> _ =>
      replace_hyp H (fun C a b => H C (conj a b))
  | forall B C, _ /\ _ -> _ =>
      replace_hyp H (fun B C a b => H B C (conj a b))
  | forall A B C, _ /\ _ -> _ =>
      replace_hyp H (fun A B C a b => H A B C (conj a b))
  end.
</code>```

Notice that C has sort Type, not Prop. And if you are willing to work in Prop, you get to use the setoid_rewrite tactic with logical equivalences. For example:

```<code>Require Import Coq.Setoids.Setoid.

Implicit Types C : Prop.

Definition and_curry_uncurry_iff {A B C} : (A /\ B -> C) <-> (A -> B -> C) :=
  conj (fun H a b => H (conj a b)) (and_ind (P := C)).

Ltac find_and_curry :=
  match goal with
  | H : context [_ /\ _ -> _] |- _ =>
      setoid_rewrite and_curry_uncurry_iff in H
  end.

Example ex2_prop A B : (forall C, A /\ B -> C) -> (forall C, A -> B -> C).
Proof. intros H. find_and_curry. assumption. Qed.
</code>```

Title: Curry universally quantified function

Body:
I am trying to write a tactic for currying functions, including universally quantified functions.

Require Import Coq.Program.Tactics.

Definition curry1 := forall A B C, (A /\ B -> C) -> (A -> B -> C).
Definition curry2 := forall A B, (forall C, A /\ B -> C) -> (forall C, A -> B -> C).
Definition curry3 := forall A, (forall B C, A /\ B -> C) -> (forall B C, A -> B -> C).
(* etc. *)

Ltac curry H :=
  let T := type of H in
  match T with
  | _ /\ _ -> _ =>
    replace_hyp H (fun H1 => fun H2 => H (conj H1 H2))
  | forall x, ?P x =>
    fail 1 "not implemented"
  | _ =>
    fail 1 "not a curried function"
  end.

Example ex1 : curry1.
Proof.
  intros A B C H.
  curry H.
  assumption.
Qed.

Example ex2 : curry2.
Proof.
  intros A B H.
  Fail curry H. (* Tactic failure: not a curried function. *)
  Fail replace_hyp H (fun H1 => let H2 := H H1 in ltac:(curry H2)). (* Cannot infer an existential variable of type "Type" in environment: [...] *)
Abort.

How can I extend my curry tactic to handle universally quantified functions?

Body:
You can basically pattern-match on all the variants like so:

Ltac curry H :=
  match type of H with
  | _ /\ _ -> _ =>
      replace_hyp H (fun a b => H (conj a b))
  | forall C, _ /\ _ -> _ =>
      replace_hyp H (fun C a b => H C (conj a b))
  | forall B C, _ /\ _ -> _ =>
      replace_hyp H (fun B C a b => H B C (conj a b))
  | forall A B C, _ /\ _ -> _ =>
      replace_hyp H (fun A B C a b => H A B C (conj a b))
  end.

Notice that C has sort Type, not Prop. And if you are willing to work in Prop, you get to use the setoid_rewrite tactic with logical equivalences. For example:

Require Import Coq.Setoids.Setoid.

Implicit Types C : Prop.

Definition and_curry_uncurry_iff {A B C} : (A /\ B -> C) <-> (A -> B -> C) :=
  conj (fun H a b => H (conj a b)) (and_ind (P := C)).

Ltac find_and_curry :=
  match goal with
  | H : context [_ /\ _ -> _] |- _ =>
      setoid_rewrite and_curry_uncurry_iff in H
  end.

Example ex2_prop A B : (forall C, A /\ B -> C) -> (forall C, A -> B -> C).
Proof. intros H. find_and_curry. assumption. Qed.


问:
Can't remove readonly from a html select using jQuery
I'm trying to dynamically remove the 'readonly' attribute from some HTML elements.

I've created a [JSFiddle here][1] to show my issue, here is my code snippet:

$('#theButton').on('click', function() {
  $('#mySelect').removeProp('readonly');
  $('#textInput').removeProp('readonly');
  //stop the form posting back
  return false;
})```
<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>
<form>
  <label>Some input fields</label>
  <input type='text' class='form-control' id='textInput' readonly>
  <select id='mySelect' readonly class='form-control input-sm '>
    <option>1</option>
    <option>2</option>
    </select>
  <button class='btn btn-primary' id='theButton'>
    Enable Button
    </button>
</form></code>```

答:
The documentation of jQuery's .removeProp() clearly states that it shouldn't be used to remove native properties.

Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.

Use .prop('readonly', false) instead to make your textbox writable. Also, as @guradio suggested, select boxes don't have readonly property. Please use .prop('disabled', false) to prevent users editing it.

More details here.

Body:
I'm trying to dynamically remove the 'readonly' attribute from some HTML elements.

I've created a [JSFiddle here][1] to show my issue, here is my code snippet:

$('#theButton').on('click', function() {
  $('#mySelect').removeProp('readonly');
  $('#textInput').removeProp('readonly');
  //stop the form posting back
  return false;
})

<form>
  Some input fields
  <input type='text' class='form-control' id='textInput' readonly>
  <select id='mySelect' readonly class='form-control input-sm '>
    <option>1</option>
    <option>2</option>
    </select>
  <button class='btn btn-primary' id='theButton'>
    Enable Button
    </button>
</form>


答:
Your use of removeProp is incorrect.

The .removeProp() method removes properties set by the .prop() method.

Take a look what JQuery doc says:

Note: Do not use this method to remove native properties such as
  checked, disabled, or selected. This will remove the property
  completely and, once removed, cannot be added again to element. Use
  .prop() to set these properties to false instead.

You have to use prop property to do this

Get the value of a property for the first element in the set of
  matched elements or set one or more properties for every matched
  element.

Fiddle

SNIPPET

$('#theButton').on('click', function() {
  $('#mySelect').prop('disabled', false);
  $('#textInput').prop('readonly', false);
  return false;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
   <label>Some input fields</label>
   <input type='text' class='form-control' id='textInput' readonly>
   <select id='mySelect' disabled class='form-control input-sm '>
       <option>1</option>
       <option>2</option>
   </select>
   <button class='btn btn-primary' id='theButton'>Enable Button </button>
</form></code>```

Title: Can't remove readonly from a html select using jQuery

Body:
Your use of removeProp is incorrect.

The .removeProp() method removes properties set by the .prop() method.

Take a look what JQuery doc says:

Note: Do not use this method to remove native properties such as
  checked, disabled, or selected. This will remove the property
  completely and, once removed, cannot be added again to element. Use
  .prop() to set these properties to false instead.

You have to use prop property to do this

Get the value of a property for the first element in the set of
  matched elements or set one or more properties for every matched
  element.

Fiddle

SNIPPET

$('#theButton').on('click', function() {
  $('#mySelect').prop('disabled', false);
  $('#textInput').prop('readonly', false);
  return false;
})

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
   <label>Some input fields</label>
   <input type='text' class='form-control' id='textInput' readonly>
   <select id='mySelect' disabled class='form-control input-sm '>
       <option>1</option>
       <option>2</option>
   </select>
   <button class='btn btn-primary' id='theButton'>Enable Button </button>
</form>

ContentLicense: CC BY-SA 4.0


问:
Google play not updating my app automatically for new version
I uploaded my app on play store, and then uploaded a new version of the app. However, I didn't get any notification to update my app. It seems to have updated automatically to the new version.

I have chosen the option to update app over wi-fi only. Many other apps get updated automatically but mine is not. Why is that?

答: because you added a new permission  to the new  apk google play will not auto update your app </p>


问:
Ansible create user with password, dont change it if user exists
I have some servers which I want to administer with ansible. Currently I need to create user acounts on all of them. On some of them, some accounts are already present. I want to create the users with a default password, but if the user exist don't change his password.

Can someone help me with this condition ?

Here is my playbook :

```<code>---
- hosts: all
  become: yes
  vars:
    sudo_users:
       # password is generated through "mkpasswd" command from 'whois' package
      - login: user1
        password: hashed_password
      - login: user1
        password: hashed_password

  tasks:
    - name: Make sure we have a 'sudo' group
      group:
        name: sudo
        state: present

    - user:
        name: "{{ item.login }}"
        #password: "{{ item.password }}"
        shell: /bin/bash
        groups: "{{ item.login }},sudo"
        append: yes
      with_items: "{{ sudo_users }}"
</code>```

答:
From the docs of user module:

update_password (added in 1.3) always/on_create

  always will update passwords if they differ. on_create will only set the password for newly created users.

Body:
I have some servers which I want to administer with ansible. Currently I need to create user acounts on all of them. On some of them, some accounts are already present. I want to create the users with a default password, but if the user exist don't change his password.

Can someone help me with this condition ?

Here is my playbook :

---
- hosts: all
  become: yes
  vars:
    sudo_users:
       # password is generated through "mkpasswd" command from 'whois' package
      - login: user1
        password: hashed_password
      - login: user1
        password: hashed_password

  tasks:
    - name: Make sure we have a 'sudo' group
      group:
        name: sudo
        state: present

    - user:
        name: "{{ item.login }}"
        #password: "{{ item.password }}"
        shell: /bin/bash
        groups: "{{ item.login }},sudo"
        append: yes
      with_items: "{{ sudo_users }}"


问:
ReflectionException error class admin does not exist
I am creating an Admin backend for my laravel project. It is using the laravel Auth scaffolding. I am now getting this error after coming back to it after the weekend and I am struggling to find an error. I have checked all spellings and capitalization. I have ran composer update etc etc but still no luck. Here is the error below, I do have the admin class and its in the namespace App, not sure whats going on:

```<code>ReflectionException error class admin does not exist.
</code>```

Web.php file

```<code>    Route::prefix('admin')->group(function() {
  Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
  Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
  Route::get('/', 'AdminController@index')->name('admin.dashboard');
  Route::get('/logout', 'Auth\AdminLoginController@logout')->name('admin.logout');
});
</code>```

AdminLoginController.php

```<code><?php

namespace App\Http\Controllers\Auth;

use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdminLoginController extends Controller
{

    public function __construct()
    {
        $this->middleware('admin')->except('logout');
    }

    public function showLoginForm()
    {
        return view('auth.admin-login');
    }

    public function login(Request $request)
    {
        //Validate the form data
        $this->validate($request, [
          'email' => 'required|email',
          'password' => 'required|min:6'
        ]);

        // Attempt to log the user in
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
          // If successful, then redirect to tehir inteded page
          return redirect()->intended(route('admin.dashboard'));
        }

        // unsuccessful, then redirect back to the login with the form data
        return redirect()->back()->withInput($request->only('email', 'remember'));
    }

    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('/');
    }
}
</code>```

AdminController.php

```<code><?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin');
    }
}
</code>```

答:
Okay so I have fixed it!! In the AdminLoginController, I added this 'guest:admin' to this instead of just 'admin' betweeen the middleware parenthese :

```<code>public function __construct()
    {
        $this->middleware('guest:admin')->except('logout');
    }
</code>```

Body:
I am creating an Admin backend for my laravel project. It is using the laravel Auth scaffolding. I am now getting this error after coming back to it after the weekend and I am struggling to find an error. I have checked all spellings and capitalization. I have ran composer update etc etc but still no luck. Here is the error below, I do have the admin class and its in the namespace App, not sure whats going on:

ReflectionException error class admin does not exist.

Web.php file

    Route::prefix('admin')->group(function() {
  Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
  Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
  Route::get('/', 'AdminController@index')->name('admin.dashboard');
  Route::get('/logout', 'Auth\AdminLoginController@logout')->name('admin.logout');
});

AdminLoginController.php

<?php

namespace App\Http\Controllers\Auth;

use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdminLoginController extends Controller
{

    public function __construct()
    {
        $this->middleware('admin')->except('logout');
    }

    public function showLoginForm()
    {
        return view('auth.admin-login');
    }

    public function login(Request $request)
    {
        //Validate the form data
        $this->validate($request, [
          'email' => 'required|email',
          'password' => 'required|min:6'
        ]);

        // Attempt to log the user in
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
          // If successful, then redirect to tehir inteded page
          return redirect()->intended(route('admin.dashboard'));
        }

        // unsuccessful, then redirect back to the login with the form data
        return redirect()->back()->withInput($request->only('email', 'remember'));
    }

    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('/');
    }
}

AdminController.php

<?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin');
    }
}

Body:
Okay so I have fixed it!! In the AdminLoginController, I added this 'guest:admin' to this instead of just 'admin' betweeen the middleware parenthese :

public function __construct()
    {
        $this->middleware('guest:admin')->except('logout');
    }


问:
How to access index.html file under WEB-INF
In my sample web application being built on eclipse I tried placing the index.html file under WEB-INF folder and then updating the deployment descriptor web.xml file as below to load the same on deployment:

```<code><welcome-file>WEB-INF/index.html</welcome-file>
</code>```

But when I try deploying the web app in Tomcat server it doesn't load the index.html file. However when I move the index.html file directly to the root of the application , i.e. directly under the WebContent folder, the index.html file does get loaded successfully in the browser.

I guess if I have to place the default index.html file under WEB-INF then I need to write a servlet and keep it as <load-on-startup>0</load-on-startup>

in my web.xml file.
Otherwise there is no way the Tomcat container can directly access the index.html under WEB-INF.

Feel free to add if I am missing something.

答:
It is impossible.

Servlet 3.1 specification

Most of the WEB-INF node is not part of the public document tree of
  the application. Except for static resources and JSPs packaged in the
  METAINF/resources of a JAR file that resides in the WEB-INF/lib
  directory, no other files contained in the WEB-INF directory may be
  served directly to a client by the container.

Best practice is put your file index.html inside src/main/webapp.

Reference

http://download.oracle.com/otn-pub/jcp/servlet-3_1-fr-eval-spec/servlet-3_1-final.pdf (page 10-105)

https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

Body:
In my sample web application being built on eclipse I tried placing the index.html file under WEB-INF folder and then updating the deployment descriptor web.xml file as below to load the same on deployment:

<welcome-file>WEB-INF/index.html</welcome-file>

But when I try deploying the web app in Tomcat server it doesn't load the index.html file. However when I move the index.html file directly to the root of the application , i.e. directly under the WebContent folder, the index.html file does get loaded successfully in the browser.

I guess if I have to place the default index.html file under WEB-INF then I need to write a servlet and keep it as <load-on-startup>0</load-on-startup>

in my web.xml file.
Otherwise there is no way the Tomcat container can directly access the index.html under WEB-INF.

Feel free to add if I am missing something.


问:
How to create image and labels using location data stored in NSArray
i have to create an 2images and 3 labels by using code (cgrectmake)and i am having X location, y location, width and height all are stored in arrays(which i have retrieved from the web services)how can i create the image and labels can any one help me</p>

答:
You can join the elements of an array together with the NSString componentsJoinedByString class method:

```<code>NSString myString = [myNSArray componentsJoinedByString:@"x"];
</code>```

where x is the characters you'd like to appear between each array element.

Edited to add

So in your newly-added code if these are the label values:

lbl = @"zero"

lbl1 = @"one"

lbl2 = @"two"

and you want to join them together with a space character then if you did this:

```<code>NSString *temp = [labelArray componentsJoinedByString:@" "];
NSLog(@"temp = %@", temp);
</code>```

then this is what would be logged:

zero one two

Edited to further add

If you are instead trying to join the label values together to make xml elements then you might do something like this:

```<code>NSString *joinedElements = [labelArray componentsJoinedByString:@"</label><label>"];
NSString *temp = [NSString stringWithFormat:@"<label>%@</label>", joinedElements];
NSLog(@"temp = %@", temp);
</code>```

then this is what would be logged:

zeroonetwo

Body:
You can join the elements of an array together with the NSString componentsJoinedByString class method:

NSString myString = [myNSArray componentsJoinedByString:@"x"];

where x is the characters you'd like to appear between each array element.

Edited to add

So in your newly-added code if these are the label values:

lbl = @"zero"

lbl1 = @"one"

lbl2 = @"two"

and you want to join them together with a space character then if you did this:

NSString *temp = [labelArray componentsJoinedByString:@" "];
NSLog(@"temp = %@", temp);

then this is what would be logged:

zero one two

Edited to further add

If you are instead trying to join the label values together to make xml elements then you might do something like this:

NSString *joinedElements = [labelArray componentsJoinedByString:@"</label><label>"];
NSString *temp = [NSString stringWithFormat:@"<label>%@</label>", joinedElements];
NSLog(@"temp = %@", temp);

then this is what would be logged:

<label>zero</label><label>one</label><label>two</label>


问:
How to print a value with the same criteria - JavaScript
I am trying to print numbers that are divisible by 3 and 5.
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in
the console. Otherwise, just print out the number.

Tried these codes:

```<code>var i;

for(i = 1; i <= 20; i++){
  if(i % 3 === 0){
     console.log("Fizz");
  }else if(i % 5 === 0){
     console.log("Buzz");
 }else if(i % 3 === 0 && i % 5 === 0){
      console.log("FizzBuzz");
  }else {
   console.log(i);
}
}
</code>```

But it seems it passing out the 3rd else if...
Is there a better way to do this?

答:
You could move the combined comparsion to top of the comparisons, because if both conditions are true, you need not to check the others.

var i;

for (i = 1; i <= 20; i++) {
    if (i % 3 === 0 && i % 5 === 0) { // check first, includes
        console.log("FizzBuzz");
    } else if (i % 3 === 0) {         // this comparison and
        console.log("Fizz");
    } else if (i % 5 === 0) {         // this as well.
        console.log("Buzz");
    } else {
        console.log(i);
    }
}```

Body:
I am trying to print numbers that are divisible by 3 and 5.
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in
the console. Otherwise, just print out the number.

Tried these codes:

var i;

for(i = 1; i <= 20; i++){
  if(i % 3 === 0){
     console.log("Fizz");
  }else if(i % 5 === 0){
     console.log("Buzz");
 }else if(i % 3 === 0 && i % 5 === 0){
      console.log("FizzBuzz");
  }else {
   console.log(i);
}
}

But it seems it passing out the 3rd else if...
Is there a better way to do this?


问:
Angular Material directive to hide element on small/mobile display
Is there an 'angular material way' to hide elements on small/mobile displays using a directive of some kind? Having used Angular and Angular Material for a while now, I thought this should be simple, but I'm just not finding it. I know about the ng-show / ng-hide directives, but I don't know if I can write an expression that inspects the current display size somehow.

Do I just need to fall back to good old media queries in CSS?

EDIT - forgot to include reference to Angular Material in my original post... oops!

答: Use hide-sm css class. This class is provided by angular material</p>


问:
Script recording using Jmeter
I am using mozilla firefox browser to record a script using jmenter. I have set the browser proxy settings correctly. But, when I start recording the script, the webpage of an application is not getting loaded completely with all the content and correct alignment. Why? Could some one help me out here please.

Thanks

答:
My expectation is that this is due to incorrect HTTPS configuration, try importing JMeter's self-signed certificate into Firefox like:

Choose the following options:

Tools / Options

Advanced / Certificates

View Certificates

Authorities

Import …

Browse to the JMeter launch directory, and click on the file
ApacheJMeterTemporaryRootCA.crt, press Open

Click View and check that the certificate details agree with the ones displayed by the JMeter Test Script Recorder

If OK, select "Trust this CA to identify web sites", and press OK

Close dialogs by pressing OK as necessary

More information: HTTPS recording and certificates section of the HTTP(S) Test Script Recorder JMeter User Manual chapter.

You can also consider an alternative solution of recording a JMeter test: use JMeter Chrome Extension, in this case you won't need to worry about proxies and certificate, just follow your test scenario steps and they will be recorded automatically.

Title: Script recording using Jmeter


问:
Nib view differs from Simulator
My nib

My Simulator. I can't understand why constraints don't work

I think code does not have influence, however see it below:

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    if let headeView = Bundle.main.loadNibNamed("HeaderViewCell", owner: self, options: nil)?.first as? HeaderViewCell {

        //headeView.categoryLabel.text = "FFF"
        return headeView
    }

    return UIView()
}
</code>```

答:
Perhaps you need to call layoutIfNeeded() on the loaded view.

The best place to do this is willDisplayHeaderView:forSection().

Also, do check your contraints setup.

Title: Nib view differs from Simulator

Body:
My nib

My Simulator. I can't understand why constraints don't work

I think code does not have influence, however see it below:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    if let headeView = Bundle.main.loadNibNamed("HeaderViewCell", owner: self, options: nil)?.first as? HeaderViewCell {

        //headeView.categoryLabel.text = "FFF"
        return headeView
    }

    return UIView()
}


问:
MTLBuffer contents causing EXC_BAD_ACCESS
I created an buffer filled in by an array of float values. Unfortunately, when I try to query its contents() property (when I was trying to debug a problem), I was getting an EXC_BAD_ACCESS. Here's the code:

```<code>let inputData  = [Float32](repeatElement(5, count: 16384)) // Declaration

// Declaration of the buffer and filling contents...
inputBuffer = device.makeBuffer(bytes: inputData, length: MemoryLayout<Float32>.size * inputData.count, options: MTLResourceOptions())

// Crash occurs here:
let contents = inputBuffer.contents().load(as: [Float32].self)
</code>```

I would like to know why the crash occurs. Other similar buffer declarations have worked correctly, so I guess this might be an issue with accessing the contents.

答:
To get the entire array, you can do:</p>

```<code>let count = buffer.length / MemoryLayout<Float>.stride
var output = [Float](repeating: 0, count: count)
_ = output.withUnsafeMutableBytes { ptr in
  memcpy(ptr.baseAddress, buffer.contents(), buffer.length)
}
</code>```

Body:
I created an buffer filled in by an array of float values. Unfortunately, when I try to query its contents() property (when I was trying to debug a problem), I was getting an EXC_BAD_ACCESS. Here's the code:

let inputData  = [Float32](repeatElement(5, count: 16384)) // Declaration

// Declaration of the buffer and filling contents...
inputBuffer = device.makeBuffer(bytes: inputData, length: MemoryLayout<Float32>.size * inputData.count, options: MTLResourceOptions())

// Crash occurs here:
let contents = inputBuffer.contents().load(as: [Float32].self)

I would like to know why the crash occurs. Other similar buffer declarations have worked correctly, so I guess this might be an issue with accessing the contents.

Body:
To get the entire array, you can do:

let count = buffer.length / MemoryLayout<Float>.stride
var output = [Float](repeating: 0, count: count)
_ = output.withUnsafeMutableBytes { ptr in
  memcpy(ptr.baseAddress, buffer.contents(), buffer.length)
}


问:
Aggregate by sub-category, then order by category in SQL
I am trying to aggregate (count) data by sub-category but I need them to be ordered based on overall category count in descending order?

For example, my column headers are:

```<code>tbl (table name)
singularity_id (key)
product_cat (category)
consumption_location (sub-category)
</code>```

My SQL query is:

```<code>SELECT
    product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count
FROM
    tbl
GROUP BY
    product_cat, consumption_location
ORDER BY
    product_cat, consumption_location, count DESC;
</code>```

This groups product_cat and consumption_location but does not order by product_cat count desc.

So my data currently looks like this, based on my query:

```<code>product_cat | consumption_location | count
------------+----------------------+--------
Fruit Juice | Store                |  200
Fruit Juice | Home                 |  600
Soft Drink  | Store                | 1200
Soft Drink  | Home                 |  100
Water       | Store                |  400
Water       | Home                 |  500
</code>```

What I want is:

```<code>product_cat | consumption_location | count
------------+----------------------+--------
Soft Drink  | Store                | 1200
Soft Drink  | Home                 |  100
Water       | Store                |  400
Water       | Home                 |  500
Fruit Juice | Store                |  200
Fruit Juice | Home                 |  600
</code>```

Since Soft Drink has the most overall entries, followed by Water, then Fruit Juice.

答:
Without a temp table you can add in a count for the partition by for a "total"

```<code>SELECT
product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count,
count(*) over (partition by product_cat) as total
FROM
tbl
GROUP BY
product_cat, consumption_location
ORDER BY
total Desc, product_cat, consumption_location
</code>```

but you can leave out the total completely from the select statement and add it in the order by since it's an aggregate

```<code>SELECT
product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count
FROM
tbl
GROUP BY
product_cat, consumption_location
ORDER BY
count(*) over (partition by product_cat) Desc, consumption_location
</code>```

This should get you what you need in your sample though I'm not sure why you have the store at the top always. So I am only ordering it by these two the other fields don't seem to matter in your example only the final total then consumption_location seems to be ascending after the grand total

Body:
I am trying to aggregate (count) data by sub-category but I need them to be ordered based on overall category count in descending order?

For example, my column headers are:

tbl (table name)
singularity_id (key)
product_cat (category)
consumption_location (sub-category)

My SQL query is:

SELECT
    product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count
FROM
    tbl
GROUP BY
    product_cat, consumption_location
ORDER BY
    product_cat, consumption_location, count DESC;

This groups product_cat and consumption_location but does not order by product_cat count desc.

So my data currently looks like this, based on my query:

product_cat | consumption_location | count
------------+----------------------+--------
Fruit Juice | Store                |  200
Fruit Juice | Home                 |  600
Soft Drink  | Store                | 1200
Soft Drink  | Home                 |  100
Water       | Store                |  400
Water       | Home                 |  500

What I want is:

product_cat | consumption_location | count
------------+----------------------+--------
Soft Drink  | Store                | 1200
Soft Drink  | Home                 |  100
Water       | Store                |  400
Water       | Home                 |  500
Fruit Juice | Store                |  200
Fruit Juice | Home                 |  600

Since Soft Drink has the most overall entries, followed by Water, then Fruit Juice.

Body:
Without a temp table you can add in a count for the partition by for a "total"

SELECT
product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count,
count(*) over (partition by product_cat) as total
FROM
tbl
GROUP BY
product_cat, consumption_location
ORDER BY
total Desc, product_cat, consumption_location

but you can leave out the total completely from the select statement and add it in the order by since it's an aggregate

SELECT
product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count
FROM
tbl
GROUP BY
product_cat, consumption_location
ORDER BY
count(*) over (partition by product_cat) Desc, consumption_location

This should get you what you need in your sample though I'm not sure why you have the store at the top always. So I am only ordering it by these two the other fields don't seem to matter in your example only the final total then consumption_location seems to be ascending after the grand total


问:
kafka offset and log retention configuration at topic level
We have a topic with 5 partitions. We are defining the partition based on the checksum of the key. There are cases where there are no key resolving to partition 3 and so there are no commits made. Hence after the configured number of days for offset retention, the consumer current offset starts showing unknown. We will need to resolve this, hence thought we will have to set log and offset retention at topic level.
In the config, I see that we have config:retention.ms is for log retention but did not find corresponding offset retention configuration. Can someone please help on the same.

Edit:
bin/kafka-topics.sh --zookeeper XXX --alter --topic XXXX --config retention.ms=86400000

The above is used to set the log retention time specific to the topic. But how can we specify the offset retention in the query.

答:
I think you're looking for log.retention.bytes.

That there is no data at all within the retention period is however something you should fix. Either by decreasing the number of partitions or use another algorithm to create the key.


问:
How to set custom icon for UITableview row action buttons?
How to set custom image icons for UItablebview rowactions? Currently i tried acheiving it by setting the rowaction background image using patternimage, but it is of no use.
And then i had created a custom icon font file with all the request icons and tried setting the rowaction title using this custom font.But this was also not successful. Could someone tell me how to set these icons for rowactions?
Tried looking at many online blogs and posts,but they are not that helpful to fix my issue.</p>

答:
You can try using the following lib https://github.com/MortimerGoro/MGSwipeTableCell .
It allows to set images and titles for row actions</p>


问:
R columns replace alphabet by other columns in a data frame
I have a data frame with three reference columns ref, het and hom in every row and I want to replace the alphabet/genotype in the columns which G=C, A=T, AG=TC or vice versa based on the reference columns.

```<code>structure(list(SNP = c("rs1", "rs2", "rs3", "rs4", "rs5", "rs6",
"rs7", "rs8", "rs9"), ref = c("GG", "AA", "AA", "GG", "GG", "GG",
"AA", "CC", "GG"), het = c("AG", "AG", "AG", "AG", "AG", "AG",
"AG", "AC", "AG"), hom = c("AA", "GG", "GG", "AA", "AA", "AA",
"GG", "AA", "AA"), A = c("TC", "TC", "CC", "AG", "TT", "TC",
"AA", "GG", "GG"), B = c("CC", "TT", "CC", "AG", "TT", "CC",
"AA", "TG", "GG"), C = c("CC", "CC", "CC", "GG", "CC", "TT",
"AA", "TG", "GG"), D = c("TT", "TC", "CC", "AG", "TT", "TT",
"AA", "GG", "AG"), E = c("CC", "TT", "CC", "AG", "TC", "TT",
"AA", "TG", "GG"), F = c("TC", "TT", "TC", "GG", "TC", "TC",
"AA", "GG", "GG"), G = c("TC", "TC", "CC", "AG", "TC", "TC",
"AA", "GG", "GG"), H = c("TC", "TC", "TC", "GG", "TC", "TC",
"AA", "TG", "GG")), .Names = c("SNP", "ref", "het", "hom", "A",
"B", "C", "D", "E", "F", "G", "H"), class = "data.frame", row.names =
c(NA,
-9L))

Input:
SNP ref het hom A   B   C   D   E   F   G   H   I
rs1 GG  AG  AA  TC  CC  CC  TT  CC  TC  TC  TC  …
rs2 AA  AG  GG  TC  TT  CC  TC  TT  TT  TC  TC  …
rs3 AA  AG  GG  CC  CC  CC  CC  CC  TC  CC  TC  …
rs4 GG  AG  AA  AG  AG  GG  AG  AG  GG  AG  GG  …
rs5 GG  AG  AA  TT  TT  CC  TT  TC  TC  TC  TC  …
rs6 GG  AG  AA  TC  CC  TT  TT  TT  TC  TC  TC  …
rs7 AA  AG  GG  AA  AA  AA  AA  AA  AA  AA  AA  …
rs8 CC  AC  AA  GG  TG  TG  GG  TG  GG  GG  TG  …
rs9 GG  AG  AA  GG  GG  GG  AG  GG  GG  GG  GG  …

Desired Output:
SNP ref het hom A   B   C   D   E   F   G   H   I
rs1 GG  AG  AA  AG  GG  GG  AA  GG  AG  AG  AG  …
rs2 AA  AG  GG  AG  AA  GG  AG  AA  AA  AG  AG  …
rs3 AA  AG  GG  GG  GG  GG  GG  GG  AG  GG  AG  …
rs4 GG  AG  AA  AG  AG  GG  AG  AG  GG  AG  GG  …
rs5 GG  AG  AA  AA  AA  GG  AA  AG  AG  AG  AG  …
rs6 GG  AG  AA  AG  GG  AA  AA  AA  AG  AG  AG  …
rs7 AA  AG  GG  AA  AA  AA  AA  AA  AA  AA  AA  …
rs8 CC  AC  AA  AA  AC  AC  CC  AC  CC  CC  AC  …
rs9 GG  AG  AA  GG  GG  GG  AG  GG  GG  GG  GG  …
</code>```

how can I write a function to replace these alphabet based on the reference columns? Thank you.

答:
We can use chartr

```<code>df1[5:12] <- lapply(df1[5:12], function(x) chartr('TC', 'AG', x))
df1
#  SNP ref het hom  A  B  C  D  E  F  G  H I
#1 rs1  GG  AG  AA AG GG GG AA GG AG AG AG …
#2 rs2  AA  AG  GG AG AA GG AG AA AA AG AG …
#3 rs3  AA  AG  GG GG GG GG GG GG AG GG AG …
#4 rs4  GG  AG  AA AG AG GG AG AG GG AG GG …
#5 rs5  GG  AG  AA AA AA GG AA AG AG AG AG …
#6 rs6  GG  AG  AA AG GG AA AA AA AG AG AG …
#7 rs7  AA  AG  GG AA AA AA AA AA AA AA AA …
#8 rs8  CC  AC  AA GG AG AG GG AG GG GG AG …
#9 rs9  GG  AG  AA GG GG GG AG GG GG GG GG …
</code>```

Body:
I have a data frame with three reference columns ref, het and hom in every row and I want to replace the alphabet/genotype in the columns which G=C, A=T, AG=TC or vice versa based on the reference columns.

structure(list(SNP = c("rs1", "rs2", "rs3", "rs4", "rs5", "rs6",
"rs7", "rs8", "rs9"), ref = c("GG", "AA", "AA", "GG", "GG", "GG",
"AA", "CC", "GG"), het = c("AG", "AG", "AG", "AG", "AG", "AG",
"AG", "AC", "AG"), hom = c("AA", "GG", "GG", "AA", "AA", "AA",
"GG", "AA", "AA"), A = c("TC", "TC", "CC", "AG", "TT", "TC",
"AA", "GG", "GG"), B = c("CC", "TT", "CC", "AG", "TT", "CC",
"AA", "TG", "GG"), C = c("CC", "CC", "CC", "GG", "CC", "TT",
"AA", "TG", "GG"), D = c("TT", "TC", "CC", "AG", "TT", "TT",
"AA", "GG", "AG"), E = c("CC", "TT", "CC", "AG", "TC", "TT",
"AA", "TG", "GG"), F = c("TC", "TT", "TC", "GG", "TC", "TC",
"AA", "GG", "GG"), G = c("TC", "TC", "CC", "AG", "TC", "TC",
"AA", "GG", "GG"), H = c("TC", "TC", "TC", "GG", "TC", "TC",
"AA", "TG", "GG")), .Names = c("SNP", "ref", "het", "hom", "A",
"B", "C", "D", "E", "F", "G", "H"), class = "data.frame", row.names =
c(NA,
-9L))

Input:
SNP ref het hom A   B   C   D   E   F   G   H   I
rs1 GG  AG  AA  TC  CC  CC  TT  CC  TC  TC  TC  …
rs2 AA  AG  GG  TC  TT  CC  TC  TT  TT  TC  TC  …
rs3 AA  AG  GG  CC  CC  CC  CC  CC  TC  CC  TC  …
rs4 GG  AG  AA  AG  AG  GG  AG  AG  GG  AG  GG  …
rs5 GG  AG  AA  TT  TT  CC  TT  TC  TC  TC  TC  …
rs6 GG  AG  AA  TC  CC  TT  TT  TT  TC  TC  TC  …
rs7 AA  AG  GG  AA  AA  AA  AA  AA  AA  AA  AA  …
rs8 CC  AC  AA  GG  TG  TG  GG  TG  GG  GG  TG  …
rs9 GG  AG  AA  GG  GG  GG  AG  GG  GG  GG  GG  …

Desired Output:
SNP ref het hom A   B   C   D   E   F   G   H   I
rs1 GG  AG  AA  AG  GG  GG  AA  GG  AG  AG  AG  …
rs2 AA  AG  GG  AG  AA  GG  AG  AA  AA  AG  AG  …
rs3 AA  AG  GG  GG  GG  GG  GG  GG  AG  GG  AG  …
rs4 GG  AG  AA  AG  AG  GG  AG  AG  GG  AG  GG  …
rs5 GG  AG  AA  AA  AA  GG  AA  AG  AG  AG  AG  …
rs6 GG  AG  AA  AG  GG  AA  AA  AA  AG  AG  AG  …
rs7 AA  AG  GG  AA  AA  AA  AA  AA  AA  AA  AA  …
rs8 CC  AC  AA  AA  AC  AC  CC  AC  CC  CC  AC  …
rs9 GG  AG  AA  GG  GG  GG  AG  GG  GG  GG  GG  …

how can I write a function to replace these alphabet based on the reference columns? Thank you.

Body:
We can use chartr

df1[5:12] <- lapply(df1[5:12], function(x) chartr('TC', 'AG', x))
df1
#  SNP ref het hom  A  B  C  D  E  F  G  H I
#1 rs1  GG  AG  AA AG GG GG AA GG AG AG AG …
#2 rs2  AA  AG  GG AG AA GG AG AA AA AG AG …
#3 rs3  AA  AG  GG GG GG GG GG GG AG GG AG …
#4 rs4  GG  AG  AA AG AG GG AG AG GG AG GG …
#5 rs5  GG  AG  AA AA AA GG AA AG AG AG AG …
#6 rs6  GG  AG  AA AG GG AA AA AA AG AG AG …
#7 rs7  AA  AG  GG AA AA AA AA AA AA AA AA …
#8 rs8  CC  AC  AA GG AG AG GG AG GG GG AG …
#9 rs9  GG  AG  AA GG GG GG AG GG GG GG GG …


问:
Restrict login if user is disabled in Laravel not working quite well
I'm trying to make simple admin function to disable/enable users rather than delete them.

So far I have admin function which successfully update table users and change the status to 0(enabled) and 1(disabled).

Now I have problems when user trying to log and checking his status.

This is my function for login in UserController.php

```<code>public function loginSubmit() {

    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user = User::where('is_disabled', 0)->first();
    if ($user->is_disabled == 1) {
        $validator->messages()->add('username', 'User not found.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);

    return Redirect::to('/');
}
</code>```

The problem is that when the condition is true ($user->is_disabled == 1) it is logged me in with the next user from table e.g. first user which is is_disabled = 0.

How can I make this in proper way?

答:
you have made things a bit complicated, i dont know why you are checking the user 2 times, try something like this, hope it will help</p>

```<code>$user = User::where('username', Input::get('username'))->first(['is_disabled']);
    if (!$user || $user->is_disabled==1) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }
else if($user && $user->is_disabled==0){
the code you want to process for logged in user
}
else{
 $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
</code>```

Body:
I'm trying to make simple admin function to disable/enable users rather than delete them.

So far I have admin function which successfully update table users and change the status to 0(enabled) and 1(disabled).

Now I have problems when user trying to log and checking his status.

This is my function for login in UserController.php

public function loginSubmit() {

    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user = User::where('is_disabled', 0)->first();
    if ($user->is_disabled == 1) {
        $validator->messages()->add('username', 'User not found.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);

    return Redirect::to('/');
}

The problem is that when the condition is true ($user->is_disabled == 1) it is logged me in with the next user from table e.g. first user which is is_disabled = 0.

How can I make this in proper way?

Body:
you have made things a bit complicated, i dont know why you are checking the user 2 times, try something like this, hope it will help

$user = User::where('username', Input::get('username'))->first(['is_disabled']);
    if (!$user || $user->is_disabled==1) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }
else if($user && $user->is_disabled==0){
the code you want to process for logged in user
}
else{
 $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}


问:
Pros and Cons of table name having spaces
In one of my project, it was required to have a table with space in between. Some suggest me not to include spaces because it is not a good technique.

we can still implement it using single-double quotes for table name in queries. But i need a solid backing for not opting spaces. Please help.

答:
I would never use spaces (nor other special characters) in table or column names.

Out of lazyness is one point (so typing SQL queries is a lot easier because you don't need those dreaded quotes)

Secondly a lot of tools out there might still have problems with non-standard table names.

Btw: the quote character for non-standard object names is a double quote (")
If you really go down that road, I would highly recommend to put MySQL into "ANSI Mode" in order to be compatible with the rest of the (DBMS) world.

(Single quotes are for character literals, double quotes for "escaping" non-standard names)


问:
select a div with a certain data attribute without each loop
```<code><div class='bwrap' data-x='home01'></div>
<div class='bwrap hidden' data-x='home02'></div>
<div class='bwrap hidden' data-x='home03'></div>
<div class='bwrap hidden' data-x='home04'></div>
</code>```

I want to show .bwrap with data-x='home04' without each loop.

According to this I tried:

js

```<code>var obj = $('.bwrap[data-x="home04"]');
obj.show();
</code>```

Nothing happens.

答:
Just to show (means remove hidden class)

You can do just following

```<code>$('.bwrap[data-x="home04"]').show();
</code>```

Body:
I want to show .bwrap with data-x='home04' without each loop.

According to this I tried:

js

var obj = $('.bwrap[data-x="home04"]');
obj.show();

Nothing happens.

Body:
Just to show (means remove hidden class)

You can do just following

$('.bwrap[data-x="home04"]').show();


问:
how to get only user's photo list by Listview django
All.

I want to use Listview to show only user's photo list not other user's photo list. but it doesn't work. user can get other user's photo.

this is views.py

```<code>class PhotoListView(ListView):
model = Photo

def get(self, *args, **kwargs):

    #if user connect to other user's page, go to the user's page.
    if kwargs['username'] != self.request.user.username:
         return redirect('index')

    #to get only user's photo list.
    username = self.request.user.username
    return super(PhotoListView, self).get(username=username, *args, **kwargs)
</code>```

this is model.py

```<code>class Photo(models.Model):
    user = models.ForeignKey(User)
    image_file = ProcessedImageField(upload_to='%Y/%m/%d/orig', format='JPEG', options={'quality': 100})
    source = TaggableManager(through=Taggedsource, related_name='source')
    subject = TaggableManager(through=Taggedsubject, related_name='subject')
    description = models.TextField(max_length=500, blank=True)
    comments = models.PositiveSmallIntegerField(default=0, null=True)
    posted_on = models.DateTimeField(default=datetime.now)
</code>```

答:
In views.py

```<code>class PhotoListView(ListView):
model = Photo

def get(self, *args, **kwargs):

    #if user connect to other user's page, go to the user's page.
    if kwargs['username'] != self.request.user.username:
        return redirect('index')

    #to get only user's photo list.
    username = self.request.user.username
    photos = Photo.objects.filter(user=username)
    return photos
</code>```

Photo.objects.filter(user=username) will get only photos of that user.

Body:
All.

I want to use Listview to show only user's photo list not other user's photo list. but it doesn't work. user can get other user's photo.

this is views.py

class PhotoListView(ListView):
model = Photo

def get(self, *args, **kwargs):

    #if user connect to other user's page, go to the user's page.
    if kwargs['username'] != self.request.user.username:
         return redirect('index')

    #to get only user's photo list.
    username = self.request.user.username
    return super(PhotoListView, self).get(username=username, *args, **kwargs)

this is model.py

class Photo(models.Model):
    user = models.ForeignKey(User)
    image_file = ProcessedImageField(upload_to='%Y/%m/%d/orig', format='JPEG', options={'quality': 100})
    source = TaggableManager(through=Taggedsource, related_name='source')
    subject = TaggableManager(through=Taggedsubject, related_name='subject')
    description = models.TextField(max_length=500, blank=True)
    comments = models.PositiveSmallIntegerField(default=0, null=True)
    posted_on = models.DateTimeField(default=datetime.now)

Body:
In views.py

class PhotoListView(ListView):
model = Photo

def get(self, *args, **kwargs):

    #if user connect to other user's page, go to the user's page.
    if kwargs['username'] != self.request.user.username:
        return redirect('index')

    #to get only user's photo list.
    username = self.request.user.username
    photos = Photo.objects.filter(user=username)
    return photos

Photo.objects.filter(user=username) will get only photos of that user.


问:
Python set loog as a variable
I have assignment where I need to get all data from api using ids. Here is my code so far:

```<code>import json, requests

ids = [
'tt0111161',
'tt0068646',
'tt0071562',
...
]

for i in ids:
    url = 'http://www.omdbapi.com/?i={}'.format(ids)+apikey

r = requests.get(url)
val = json.loads(r.text)
print val
</code>```

The problem is that the code is printing out details only about last id and I don't really know where my mistake is. I want to iterate by all ids list and print data about each one separately.

答: It seems that you are substituting ids in url in a loop but running requests.get only once because of the indentation - indent the last 3 lines to the level of the body of the for and things will be as you expect them to be.</p>

Title: Python set loog as a variable

Body:
I have assignment where I need to get all data from api using ids. Here is my code so far:

import json, requests

ids = [
'tt0111161',
'tt0068646',
'tt0071562',
...
]

for i in ids:
    url = 'http://www.omdbapi.com/?i={}'.format(ids)+apikey

r = requests.get(url)
val = json.loads(r.text)
print val

The problem is that the code is printing out details only about last id and I don't really know where my mistake is. I want to iterate by all ids list and print data about each one separately.


问:
Laravel Query Builder Joins
Good afternoon pips, I would like to ask for your help.

Could you please help me apply this query into the Laravel Query Builder. I only know how to query into the database using raw query.

Query:

```<code>SELECT users.first_name, users.last_name, users.id as userID, bookmarks.id,
products.title, products.price, products.id AS productID FROM users,
products, bookmarks WHERE bookmarks.user_id = $user_id AND products.id =
bookmarks.product_id AND users.id = products.user_id;
</code>```

Thank you for those people that would help me.

答:
SELECT users.first_name, users.last_name, users.id as userID,
  bookmarks.id,  products.title, products.price, products.id AS
  productID FROM users, products, bookmarks WHERE bookmarks.user_id =
  $user_id AND products.id =  bookmarks.product_id AND users.id =
  products.user_id;

You can use the eloquent with method and just access the relations but if you want the laravel query method. You can use the DB::raw to have your own raw query.

```<code>DB::select(DB::raw("Select a.first_name, a.last_name, a.id as user_id, b.id, c.title, c.price, c.id from users as a INNER JOIN bookmarks as b on b.user_id = $user_id INNER JOIN Products as c on c.id = b.product_id where  user_id = c.user_id"));
</code>```

This is just an example, it's still up to you on how you manipulate your queries.

Love,
Poop

Title: Laravel Query Builder Joins

Body:
Good afternoon pips, I would like to ask for your help.

Could you please help me apply this query into the Laravel Query Builder. I only know how to query into the database using raw query.

Query:

SELECT users.first_name, users.last_name, users.id as userID, bookmarks.id,
products.title, products.price, products.id AS productID FROM users,
products, bookmarks WHERE bookmarks.user_id = $user_id AND products.id =
bookmarks.product_id AND users.id = products.user_id;

Thank you for those people that would help me.

Body:
SELECT users.first_name, users.last_name, users.id as userID,
  bookmarks.id,  products.title, products.price, products.id AS
  productID FROM users, products, bookmarks WHERE bookmarks.user_id =
  $user_id AND products.id =  bookmarks.product_id AND users.id =
  products.user_id;

You can use the eloquent with method and just access the relations but if you want the laravel query method. You can use the DB::raw to have your own raw query.

DB::select(DB::raw("Select a.first_name, a.last_name, a.id as user_id, b.id, c.title, c.price, c.id from users as a INNER JOIN bookmarks as b on b.user_id = $user_id INNER JOIN Products as c on c.id = b.product_id where  user_id = c.user_id"));

This is just an example, it's still up to you on how you manipulate your queries.

Love,
Poop


问:
Haswell Transactional Memory read-set and write-set information
Recently, Intel release haswell machines which support hardware transactional memory called transactional synchronization extension(TSX).

As Intel manual said, Speculative memory operations, write-set and read-set, are buffered in L1 cache and L2 cache each. (not exactly)

Then, Can I track transactional memory operations and get information like address, and values of read/write-set?

答: Read-Set and Write-Set are in CPU Cache, there is no address to access, You can't track, but you can clean the cache by code. For Example, you can give assignments to the array.</p>


问:
Exception "CKR_FUNCTION_NOT_SUPPORTED", PKCS11Interop with OpenSC
I am trying to use PKCS11Interop Library with latest version (0.16) of OpenSC (opensc-pkcs11.dll). I have tried USB tokens from three vendors which are Yubico 4, NitroKey Pro/Start, Fetian ePass2003 but unable to use most of the functions from PKCS11Interop Library. I receive Net.Pkcs11Interop.Common.Pkcs11Exception: 'Method C_SignRecoverInit returned CKR_FUNCTION_NOT_SUPPORTED' for most of functions provided by the library. The functions that throw this exception are C_GetOperationState, C_SetOperationState, C_GenerateKey, C_GenerateKeyPair, Encrypt/Decrypt functions, Sign/Verify functions etc.

The strange thing is functions like GetSlotInfo, GetMechanisms, Login, Session works fine.

I have spent a lot of time trying to find a solution here. Would appreciate if anyone can help on this.

答: C_SignRecoverInit functions are not implemented in most of the drivers in OpenSC. The other functions should be fine and if not, read what to do and how to report the bugs in the OpenSC wiki.


问:
Good pattern for redux action in callback
Supposing I have an update comment action. When a user updates comment after getting a successful result from Promise I should close comment editor. This is my sample code from my project:

```<code>export const updateComment = (comment,callBack/* ? */) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             callback() /* ? */
       })
    }
}
</code>```

In react component I use action like the following code:

```<code>handleUpdateComment(){
  dispatch(actions.updateComment(this.state.comment,this.closeCommentEitor)
}
</code>```

It works well but I think is not a good pattern to close comment editor. I'm looking a correct pattern to close editor without passing callBack like I did if any.

答:
The only thing that updates your application's state is your reducers.

The reducer should be responsible to update the state of your application and not your action (you are now passing getState).

I suggest you to look at redux-promise-middleware

The middleware enables optimistic updates and dispatches pending, fulfilled and rejected actions, which can be intercepted by the reducer.

Body:
Supposing I have an update comment action. When a user updates comment after getting a successful result from Promise I should close comment editor. This is my sample code from my project:

export const updateComment = (comment,callBack/* ? */) => {
   return (dispatch, getState){
      api.updateComment({...comment}).then((result) => {
             /* Do something */
             callback() /* ? */
       })
    }
}

In react component I use action like the following code:

handleUpdateComment(){
  dispatch(actions.updateComment(this.state.comment,this.closeCommentEitor)
}

It works well but I think is not a good pattern to close comment editor. I'm looking a correct pattern to close editor without passing callBack like I did if any.


答:
If the code you posted is exactly as posted, indent the stuff you want to happen in a loop, so that it is clearly in the loop</p>

```<code>import json, requests

ids = [
'tt0111161',
'tt0068646',
'tt0071562',
...
]

for i in ids:
    #url = 'http://www.omdbapi.com/?i={}'.format(ids)+apikey
    url = 'http://www.omdbapi.com/?i={}'.format(i)+apikey
    #                                           ^--- did you mean current ids here?

    r = requests.get(url)
    val = json.loads(r.text)
    print val
</code>```

Title: Python set loog as a variable

Body:
If the code you posted is exactly as posted, indent the stuff you want to happen in a loop, so that it is clearly in the loop

import json, requests

ids = [
'tt0111161',
'tt0068646',
'tt0071562',
...
]

for i in ids:
    #url = 'http://www.omdbapi.com/?i={}'.format(ids)+apikey
    url = 'http://www.omdbapi.com/?i={}'.format(i)+apikey
    #                                           ^--- did you mean current ids here?

    r = requests.get(url)
    val = json.loads(r.text)
    print val


问:
Additional characters are coming during bulk insert
I am trying to bulk insert the first row from a csv file into a table with only one column.
But I am getting some extra characters('n++') in the begining like this:

```<code>n++First Column;Second Column;Third Column;Fourth Column;Fifth Columnm;Sixth Column
</code>```

CSV file contents are like:

```<code>First Column;Second Column;Third Column;Fourth Column;Fifth Columnm;Sixth Column
</code>```

You can find the test.csv file here

And this is the code I am using to get the first row data in a table

```<code>declare @importSQL nvarchar(2000)
declare @tempstr varchar(max)
declare @path varchar(100)

SET @path = 'D:\test.csv'

CREATE TABLE #tbl (line VARCHAR(max))

SET @importSQL =
'BULK INSERT #tbl
FROM ''' + @path + '''
WITH (
LASTROW = 1,
FIELDTERMINATOR = ''\n'',
ROWTERMINATOR = ''\n''
)'

EXEC sp_executesql @stmt=@importSQL

SET @tempstr = (SELECT TOP 1 RTRIM(REPLACE(Line, CHAR(9), ';')) FROM #tbl)

print @tempstr
drop table #tbl
</code>```

Any idea where this extra 'n++' is coming from?

答:
It might be the Unicode Byte Order Mark that are being picked up.

I suggest your try setting the DATAFILETYPE option as part of your statement.  See MSDN documentation for more detail: http://msdn.microsoft.com/en-us/library/aa173832%28SQL.80%29.aspx

Body:
I am trying to bulk insert the first row from a csv file into a table with only one column.
But I am getting some extra characters('n++') in the begining like this:

n++First Column;Second Column;Third Column;Fourth Column;Fifth Columnm;Sixth Column

CSV file contents are like:

First Column;Second Column;Third Column;Fourth Column;Fifth Columnm;Sixth Column

You can find the test.csv file here

And this is the code I am using to get the first row data in a table

declare @importSQL nvarchar(2000)
declare @tempstr varchar(max)
declare @path varchar(100)

SET @path = 'D:\test.csv'

CREATE TABLE #tbl (line VARCHAR(max))

SET @importSQL =
'BULK INSERT #tbl
FROM ''' + @path + '''
WITH (
LASTROW = 1,
FIELDTERMINATOR = ''\n'',
ROWTERMINATOR = ''\n''
)'

EXEC sp_executesql @stmt=@importSQL

SET @tempstr = (SELECT TOP 1 RTRIM(REPLACE(Line, CHAR(9), ';')) FROM #tbl)

print @tempstr
drop table #tbl

Any idea where this extra 'n++' is coming from?


问:
Why can't I open a URL in Python 3?
I am unable to open a URL in Python3.
I am using an online editor named Repl.it for coding (https://repl.it/languages/python3)

Code:

```<code>import urllib.request
fp = urllib.request.urlopen("http://www.python.org")
mybytes = fp.read()
print(mybytes)
</code>```

Error:

```<code>Traceback (most recent call last):
  File "python", line 2, in <module>

urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
</code>```

答:
I can't comment.
I am able to replicate the problem on Repl.it.
It seems to come from Repl.it. I do not have problem executing your code directly from python prompt In my computer.</p>

Title: Why can't I open a URL in Python 3?

Body:
I am unable to open a URL in Python3.
I am using an online editor named Repl.it for coding (https://repl.it/languages/python3)

Code:

import urllib.request
fp = urllib.request.urlopen("http://www.python.org")
mybytes = fp.read()
print(mybytes)

Error:

Traceback (most recent call last):
  File "python", line 2, in <module>

urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>


问:
Can WeakReference.get() return non-null after their are no strong references left?
In the following snippet, is it technically possible for widgetRef.get() to return a non-null value after the last strong reachable reference to the Widget has disappeared?

```<code>private class Foo {
    private final WeakReference<Widget> widgetRef;

    public Foo(WeakReference<Widget> widgetRef) {
        this.widgetRef = widgetRef;
    }

    public bar() {
        final Widget widget = widgetRef.get();
        if (widget != null) {
            widget.stuff();
        }
    }
}
</code>```

In other words, can you rely on the garbage collector immediately handling all weak/soft/phantom references as soon as an object becomes weakly reachable?

I believe you cannot rely on the garbage collector doing this, as it may run at any time (and is not running constantly). The WeakReference documentation implies that weak references are only handled when the garbage collector runs:

Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable. At that time it will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references.

Is there some more explicit documentation about this behaviour?

答:
In the following snippet, is it technically possible for widgetRef,get() to return a non-null value after the last strong reachable reference to the Widget has disappeared?

It is not only technically possible, it is very likely to happen in practice. You should implement some kind of lifecycle for the object that puts it into a detached/closed state when it ends. If it has a single owner then that owner ought to be responsible for that. If it has multiple owners you can use a counter or a list of owners, essentially implementing reference-counting.

The garbage collector is only meant to manage memory, not other resources or application-level lifecycles.

In other words, can you rely on the garbage collector immediately handling all weak/soft/phantom references as soon as an object becomes weakly reachable?

No.

Is there some more explicit documentation about this behaviour?

Which part of the docs you cited do you consider ambiguous for the purpose of your question? The phrasing "at a certain point in time" can be read as "does not guarantee immediate action".

Body:
In the following snippet, is it technically possible for widgetRef.get() to return a non-null value after the last strong reachable reference to the Widget has disappeared?

private class Foo {
    private final WeakReference<Widget> widgetRef;

    public Foo(WeakReference<Widget> widgetRef) {
        this.widgetRef = widgetRef;
    }

    public bar() {
        final Widget widget = widgetRef.get();
        if (widget != null) {
            widget.stuff();
        }
    }
}

In other words, can you rely on the garbage collector immediately handling all weak/soft/phantom references as soon as an object becomes weakly reachable?

I believe you cannot rely on the garbage collector doing this, as it may run at any time (and is not running constantly). The WeakReference documentation implies that weak references are only handled when the garbage collector runs:

Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable. At that time it will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references.

Is there some more explicit documentation about this behaviour?


问:
 link puts page name at end of url
Sorry if the title is confusing, I wasn't exactly sure how to word this.

Basically what I want to do is make a link, simple enough. The page is tylerofcinema.github.io and if I make a link to say, google.com the url that I get is tylerofcinema.github.io/google.com.

Code is in a repo here, let me know if there is any clarification needed.

Thanks, Diego

答:
You did not include the protocol of the url, causing the href to think it needs to open a page in the same directory.

Try adding http:// (or https://) to your href and it will open the specified url.

```<code> <a target="_blank" href="https://tylerofcinema.github.io/r/twitter"><button class="homesmb">Twitter</button></a>
</code>```

Title: <a> link puts page name at end of url

Body:
You did not include the protocol of the url, causing the href to think it needs to open a page in the same directory.

Try adding http:// (or https://) to your href and it will open the specified url.

 <a target="_blank" href="https://tylerofcinema.github.io/r/twitter"><button class="homesmb">Twitter</button></a>