问:
Face detection differenet sizes of faces using openCV haarcascade_frontalfacedetection
I'm trying to figure out the best face detection algo for me.I've already tried different methods to do so, but the detection isn't working so well.Im using openCV haarcascase(trying out the different kinds).

My question is:how do i set the size of the face detection so it will detect Big faces(Close up on the person) and also small faces(Zoom out) with the same code.

When I'm using the following command im getting true for facedetecting even when there aren't faces in the image:

```<code>faceDetector.detectMultiScale(image, faceDetections, 1.1, 3, 0 | Objdetect.CASCADE_SCALE_IMAGE,
                new Size(**50,50**), new Size());
</code>```

But if I'm using it with new Size(200,200) for example im unable to detect faces in pictures where the faces are "small".

Does anyone have an idea how can I make the detection work for both small and big faces without "inventing" faces that aren't there?

答:
detectMultiScale function has parameters min and max face size. Don't forget to consider you image size before choosing face size. Try smth like that

```<code>double max_face_size_percent = 1;
double min_face_size_percent = 0.15;

cv::Size min_face_size = cv::Size(grayImage.size().width * min_face_size_percent,grayImage.size().height * min_face_size_percent);
cv::Size max_face_size = cv::Size(grayImage.size().width * max_face_size_percent, grayImage.size().height * max_face_size_percent);

detector.detectMultiScale(grayImage, detected_faces, (double) scale_factor, 3, 0, min_face_size, max_face_size);
</code>```

You can choose the biggest face found after that with code like this

```<code>    double best_face_metric = 0;
    std::vector<cv::Rect>::iterator bestFaceIterator = detected_faces.begin();

    for (std::vector<cv::Rect>::iterator it = detected_faces.begin(); it != detected_faces.end(); ++it) {
        double curr_face_metric = it->width + it->height;
        if (curr_face_metric > best_face_metric) {
            best_face_metric = curr_face_metric;
            bestFaceIterator = it;
        }
    }

    cv::Rect_<double> bestFace(bestFaceIterator->x, bestFaceIterator->y, bestFaceIterator->width,
                               bestFaceIterator->height);
</code>```

Or implement any solution of any kind to choose correct faces by yourself

Body:
I'm trying to figure out the best face detection algo for me.I've already tried different methods to do so, but the detection isn't working so well.Im using openCV haarcascase(trying out the different kinds).

My question is:how do i set the size of the face detection so it will detect Big faces(Close up on the person) and also small faces(Zoom out) with the same code.

When I'm using the following command im getting true for facedetecting even when there aren't faces in the image:

faceDetector.detectMultiScale(image, faceDetections, 1.1, 3, 0 | Objdetect.CASCADE_SCALE_IMAGE,
                new Size(**50,50**), new Size());

But if I'm using it with new Size(200,200) for example im unable to detect faces in pictures where the faces are "small".

Does anyone have an idea how can I make the detection work for both small and big faces without "inventing" faces that aren't there?

Body:
detectMultiScale function has parameters min and max face size. Don't forget to consider you image size before choosing face size. Try smth like that

double max_face_size_percent = 1;
double min_face_size_percent = 0.15;

cv::Size min_face_size = cv::Size(grayImage.size().width * min_face_size_percent,grayImage.size().height * min_face_size_percent);
cv::Size max_face_size = cv::Size(grayImage.size().width * max_face_size_percent, grayImage.size().height * max_face_size_percent);

detector.detectMultiScale(grayImage, detected_faces, (double) scale_factor, 3, 0, min_face_size, max_face_size);

You can choose the biggest face found after that with code like this

    double best_face_metric = 0;
    std::vector<cv::Rect>::iterator bestFaceIterator = detected_faces.begin();

    for (std::vector<cv::Rect>::iterator it = detected_faces.begin(); it != detected_faces.end(); ++it) {
        double curr_face_metric = it->width + it->height;
        if (curr_face_metric > best_face_metric) {
            best_face_metric = curr_face_metric;
            bestFaceIterator = it;
        }
    }

    cv::Rect_<double> bestFace(bestFaceIterator->x, bestFaceIterator->y, bestFaceIterator->width,
                               bestFaceIterator->height);

Or implement any solution of any kind to choose correct faces by yourself


来源: stackexchange

问:
Meaning of overlapping when using memcpy
I am trying to understand the function memcpy() which is defined in the C library <string.h>

Syntax: void *memcpy(void*dst,const void*src,size_t n);

I know this function is used to copy the contents of the memory pointed by pointer src to the location pointed by the dst pointer and return the address pointed by dst.

I am not able to understand the following important statement regarding memcpy():

When using memcpy(), the memory address should not overlap, if it overlaps then the memcpy() is undefined.

Another query is:
Is the value passed to the third argument of the function i.e size_t n always an integer value?

答:
memcpy doesn't use any temporary memory to copy from src to dst.

Let say:

src starts @104

dst starts @108

src = "abcdefgh"

Then 'a' will be @104 and 'e' will be @108.

Assuming char as 1 byte then after copying:

dst = "abcdabcd".

As n denotes length to be copied, it should always be an integer.

To copy overlapping areas, you can use memmove function which uses temporary memory to copy.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
OOP representation of data from a JOIN query
I have four tables: department (id, name), course (id, name), staff (id, name, dept_id) and staff_to_course (staff_id, course_id). I need to show how many people from each department have (and haven't) completed each course as well as an average for each department and a for each course:

```<code>       | Course 1 | Course 2 | Average |
----------------------------------------
Dept 1 |      20% |      30% |     25% |
----------------------------------------
Dept 2 |      10% |      40% |     25% |
----------------------------------------
All    |      18% |      33% |     25% |
----------------------------------------
</code>```

I can do the SQL join query but I'm confused about how to properly use objects to represent the data internally.

I've currently got Course and Department objects but writing methods like $course->percentComplete($dept_id) feels kinda wrong and $course->percentComplete('all') feels even more wrong. The course average figure isn't a sensible property of a course instance object but putting it on the department object would mean duplicating the code across two classes which is definitely wrong.

I expect there's some basic OO principle I'm violating here but I can't see what it is.

答:
I would put the code in the Staff class in static methods.

For example...

```<code>public class Staff extends MyAbstractDB{

   // your attributes

   // your getter/setter

   public static List<Staff> listCompleted(Department dep){
     // here you should execute the sql query or use a criteria builder if you are using Hibernate
   }

   public static List<Staff> listCompleted(){
     // ...
   }

}
</code>```

Could this solution work for you?

ContentLicense: CC BY-SA 2.5

Body:
I have four tables: department (id, name), course (id, name), staff (id, name, dept_id) and staff_to_course (staff_id, course_id). I need to show how many people from each department have (and haven't) completed each course as well as an average for each department and a for each course:

       | Course 1 | Course 2 | Average |
----------------------------------------
Dept 1 |      20% |      30% |     25% |
----------------------------------------
Dept 2 |      10% |      40% |     25% |
----------------------------------------
All    |      18% |      33% |     25% |
----------------------------------------

I can do the SQL join query but I'm confused about how to properly use objects to represent the data internally.

I've currently got Course and Department objects but writing methods like $course->percentComplete($dept_id) feels kinda wrong and $course->percentComplete('all') feels even more wrong. The course average figure isn't a sensible property of a course instance object but putting it on the department object would mean duplicating the code across two classes which is definitely wrong.

I expect there's some basic OO principle I'm violating here but I can't see what it is.

Body:
I would put the code in the Staff class in static methods.

For example...

public class Staff extends MyAbstractDB{

   // your attributes

   // your getter/setter

   public static List<Staff> listCompleted(Department dep){
     // here you should execute the sql query or use a criteria builder if you are using Hibernate
   }

   public static List<Staff> listCompleted(){
     // ...
   }

}

Could this solution work for you?


问:
Parsing Json Array
I have been using the the Json library to try and parse the following Json data:

```<code>{"dailygameschedule": {
    "lastUpdatedOn": "2016-12-19 12:32:56 AM",
    "gameentry": [
        {
            "id": "37705",
            "date": "2016-04-03",
            "time": "1:30PM",
            "awayTeam": {
                ID: "133",
                City: "St. Louis",
                Name: "Cardinals"
                Abbreviation: "STL"
            },
            "homeTeam": {
                "ID": "132",
                "City": "Pittsburgh",
                "Name": "Pirates",
                "Abbreviation": "PIT"
            },
            "location": "PNC Park"
        },

        ...

    ]
}
</code>```

I cant figure out how to get the "gameentry" array. I was looking at other threads for guidance but it is not quite working for me. Heres what I have so far:

```<code>    JSONObject obj = new JSONObject(todaysGames);
    String pageName = obj.getJSONObject("dailygameschedule").getString("lastUpdatedOn");

    System.out.println("2 asdfasdf "+ pageName);

    JSONArray arr = obj.getJSONArray("gameentry");
    for (int i = 0; i < arr.length(); i++)
    {
        //String post_id = arr.getJSONObject(i).getString("id");
        System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
    }
</code>```

There error that im getting is:

Exception in thread "main" org.json.JSONException:
  JSONObject["gameentry"] not found.

Thanks!

答:
gameentry array is a member of dailygameschedule object, so you need to access it first.

```<code> JSONArray arr = obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");
    for (int i = 0; i < arr.length(); i++)
    {
        //String post_id = arr.getJSONObject(i).getString("id");
        System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
    }
</code>```

Title: Parsing Json Array

Body:
I have been using the the Json library to try and parse the following Json data:

{"dailygameschedule": {
    "lastUpdatedOn": "2016-12-19 12:32:56 AM",
    "gameentry": [
        {
            "id": "37705",
            "date": "2016-04-03",
            "time": "1:30PM",
            "awayTeam": {
                ID: "133",
                City: "St. Louis",
                Name: "Cardinals"
                Abbreviation: "STL"
            },
            "homeTeam": {
                "ID": "132",
                "City": "Pittsburgh",
                "Name": "Pirates",
                "Abbreviation": "PIT"
            },
            "location": "PNC Park"
        },

        ...

    ]
}

I cant figure out how to get the "gameentry" array. I was looking at other threads for guidance but it is not quite working for me. Heres what I have so far:

    JSONObject obj = new JSONObject(todaysGames);
    String pageName = obj.getJSONObject("dailygameschedule").getString("lastUpdatedOn");

    System.out.println("2 asdfasdf "+ pageName);

    JSONArray arr = obj.getJSONArray("gameentry");
    for (int i = 0; i < arr.length(); i++)
    {
        //String post_id = arr.getJSONObject(i).getString("id");
        System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
    }

There error that im getting is:

Exception in thread "main" org.json.JSONException:
  JSONObject["gameentry"] not found.

Thanks!

Body:
gameentry array is a member of dailygameschedule object, so you need to access it first.

 JSONArray arr = obj.getJSONObject("dailygameschedule").getJSONArray("gameentry");
    for (int i = 0; i < arr.length(); i++)
    {
        //String post_id = arr.getJSONObject(i).getString("id");
        System.out.println(arr.getJSONObject(i).getString("awayTeam.ID"));
    }


问:
C# Interop write array of arrays to worksheet
I'm trying to write a 2d array to worksheet and I'm getting the following error:

Specified array was not of the expected type.

This is my code:

```<code>            string[][] allEvars = new string[evars.Count][];

            for (var i = 0; i < evars.Count; i++) {
                var evarsList = new List<string>();
                evarsList.Add(evars[i].id.Value);
                evarsList.Add(evars[i].name.Value);
                if (evars[i].enabled != null)
                    evarsList.Add(evars[i].enabled.Value.ToString());
                else
                    evarsList.Add("");
                if (evars[i].description != null)
                    evarsList.Add(evars[i].description.Value);
                else
                    evarsList.Add("");
                string[] evarsArray = evarsList.ToArray();
                //var range = (Excel.Range)wsEvars.Range[wsEvars.Cells[i + 5, 2], wsEvars.Cells[i + 5, evarsArray.Length]];
                //range.Value = evarsArray;
                allEvars[i] = evarsList.ToArray();
            }
            var range = (Excel.Range)wsEvars.Range[wsEvars.Cells[5, 2], wsEvars.Cells[allEvars.Length, 3]];
            range.Value2 = allEvars; // This is the line with the exception
</code>```

The 2 commented lines from my code add the array to the worksheet one by one and I'm trying to add them all at once to save some time.

答:
You can cast array of arrays to 2d array. Use Jon Skeet method from this
answer

```<code>static T[,] CreateRectangularArray<T>(T[][] arrays)
    {
        // TODO: Validation and special-casing for arrays.Count == 0
        int minorLength = arrays[0].Length;
        T[,] ret = new T[arrays.Length, minorLength];
        for (int i = 0; i < arrays.Length; i++)
        {
            var array = arrays[i];
            if (array.Length != minorLength)
            {
                throw new ArgumentException
                    ("All arrays must be the same length");
            }
            for (int j = 0; j < minorLength; j++)
            {
                ret[i, j] = array[j];
            }
        }
        return ret;
    }
</code>```

In your code:

```<code>        string[][] allEvars = new string[evars.Count][];

        for (var i = 0; i < evars.Count; i++) {
            var evarsList = new List<string>();
            evarsList.Add(evars[i].id.Value);
            evarsList.Add(evars[i].name.Value);
            if (evars[i].enabled != null)
                evarsList.Add(evars[i].enabled.Value.ToString());
            else
                evarsList.Add("");
            if (evars[i].description != null)
                evarsList.Add(evars[i].description.Value);
            else
                evarsList.Add("");
            string[] evarsArray = evarsList.ToArray();
            //var range = (Excel.Range)wsEvars.Range[wsEvars.Cells[i + 5, 2], wsEvars.Cells[i + 5, evarsArray.Length]];
            //range.Value = evarsArray;
            allEvars[i] = evarsList.ToArray();
        }
        var range = (Excel.Range)wsEvars.Range[wsEvars.Cells[5, 2], wsEvars.Cells[allEvars.Length, 3]];
        string[,] newallEvars = CreateRectangularArray<string>(allEvars); //added row
        range.Value2 = newallEvars; // changed row
</code>```

Body:
I'm trying to write a 2d array to worksheet and I'm getting the following error:

Specified array was not of the expected type.

This is my code:

            string[][] allEvars = new string[evars.Count][];

            for (var i = 0; i < evars.Count; i++) {
                var evarsList = new List<string>();
                evarsList.Add(evars[i].id.Value);
                evarsList.Add(evars[i].name.Value);
                if (evars[i].enabled != null)
                    evarsList.Add(evars[i].enabled.Value.ToString());
                else
                    evarsList.Add("");
                if (evars[i].description != null)
                    evarsList.Add(evars[i].description.Value);
                else
                    evarsList.Add("");
                string[] evarsArray = evarsList.ToArray();
                //var range = (Excel.Range)wsEvars.Range[wsEvars.Cells[i + 5, 2], wsEvars.Cells[i + 5, evarsArray.Length]];
                //range.Value = evarsArray;
                allEvars[i] = evarsList.ToArray();
            }
            var range = (Excel.Range)wsEvars.Range[wsEvars.Cells[5, 2], wsEvars.Cells[allEvars.Length, 3]];
            range.Value2 = allEvars; // This is the line with the exception

The 2 commented lines from my code add the array to the worksheet one by one and I'm trying to add them all at once to save some time.

Body:
You can cast array of arrays to 2d array. Use Jon Skeet method from this
answer

static T[,] CreateRectangularArray<T>(T[][] arrays)
    {
        // TODO: Validation and special-casing for arrays.Count == 0
        int minorLength = arrays[0].Length;
        T[,] ret = new T[arrays.Length, minorLength];
        for (int i = 0; i < arrays.Length; i++)
        {
            var array = arrays[i];
            if (array.Length != minorLength)
            {
                throw new ArgumentException
                    ("All arrays must be the same length");
            }
            for (int j = 0; j < minorLength; j++)
            {
                ret[i, j] = array[j];
            }
        }
        return ret;
    }

In your code:

        string[][] allEvars = new string[evars.Count][];

        for (var i = 0; i < evars.Count; i++) {
            var evarsList = new List<string>();
            evarsList.Add(evars[i].id.Value);
            evarsList.Add(evars[i].name.Value);
            if (evars[i].enabled != null)
                evarsList.Add(evars[i].enabled.Value.ToString());
            else
                evarsList.Add("");
            if (evars[i].description != null)
                evarsList.Add(evars[i].description.Value);
            else
                evarsList.Add("");
            string[] evarsArray = evarsList.ToArray();
            //var range = (Excel.Range)wsEvars.Range[wsEvars.Cells[i + 5, 2], wsEvars.Cells[i + 5, evarsArray.Length]];
            //range.Value = evarsArray;
            allEvars[i] = evarsList.ToArray();
        }
        var range = (Excel.Range)wsEvars.Range[wsEvars.Cells[5, 2], wsEvars.Cells[allEvars.Length, 3]];
        string[,] newallEvars = CreateRectangularArray<string>(allEvars); //added row
        range.Value2 = newallEvars; // changed row


问:
Illuminate\Validation\Factory::make() must be of the type array, object given

Framework : Laravel 5.4

Problem :

I got the error as title when I uploaded a file.
But if I don't upload a file, the validation is ok.
I also checked the $request, but I still don't know what is the problem.

Here is my $request schreenshot
$request

Here is my code

```<code>$rules = [
          'edu_title'  => 'max:255',
          'edu_author' => 'max:10',
          'categories' => 'max:100',
          'file_name'  => 'nullable|file',
          'updated_at' => 'date|before:tomorrow'
         ];

    $messages = [
                'required' => '此欄位必填',
                'max'      => '此欄位最大長度必須小於 :max',
                'date'     => '請選擇日期',
                'before'   => '選擇的日期錯誤'
                ];

    $validate = Validator::make($request->all(), $rules, $messages);

    if($validate->fails()) {
        return back()->witherrors($validate)->withInput();
    }

    $path = '';

    if($request->hasFile('file_name')) {

    $validate = Validator::make($request->file_name, ['file_name' => 'file']);

    if( Storage::disk('local')->exists($directories.'/'.$file_name) ) {
            return back()->with('file exists', '檔案已經存在或檔名重複')->withInput();
        }

        $path = $request->file('file_name')->storeAs(
                $directories, $file_name);
    }

    OtherTeachingMaterial::find($id)->update([
                            'edu_title'  => $request->edu_title,
                            'edu_author' => $request->edu_author,
                            'file_path'  => $path,
                            'categories' => $request->categories,
                            'updated_at' => $request->updated_at
                        ]);

    return redirect()->route('others_teahcing_material.dashboard')->with('success', '更新成功');
</code>```

答:
You can add your file rule into your $rules array and delete your second Validate::make() method so your $rules array will be:

```<code>$rules = [
          'edu_title'  => 'max:255',
          'edu_author' => 'max:10',
          'categories' => 'max:100',
          'file_name'  => 'nullable|file',
          'updated_at' => 'date|before:tomorrow',
          'file_name' => 'file'
         ];
</code>```

Body:
Framework : Laravel 5.4

Problem :

I got the error as title when I uploaded a file.
But if I don't upload a file, the validation is ok.
I also checked the $request, but I still don't know what is the problem.

Here is my $request schreenshot
$request

Here is my code

$rules = [
          'edu_title'  => 'max:255',
          'edu_author' => 'max:10',
          'categories' => 'max:100',
          'file_name'  => 'nullable|file',
          'updated_at' => 'date|before:tomorrow'
         ];

    $messages = [
                'required' => '此欄位必填',
                'max'      => '此欄位最大長度必須小於 :max',
                'date'     => '請選擇日期',
                'before'   => '選擇的日期錯誤'
                ];

    $validate = Validator::make($request->all(), $rules, $messages);

    if($validate->fails()) {
        return back()->witherrors($validate)->withInput();
    }

    $path = '';

    if($request->hasFile('file_name')) {

    $validate = Validator::make($request->file_name, ['file_name' => 'file']);

    if( Storage::disk('local')->exists($directories.'/'.$file_name) ) {
            return back()->with('file exists', '檔案已經存在或檔名重複')->withInput();
        }

        $path = $request->file('file_name')->storeAs(
                $directories, $file_name);
    }

    OtherTeachingMaterial::find($id)->update([
                            'edu_title'  => $request->edu_title,
                            'edu_author' => $request->edu_author,
                            'file_path'  => $path,
                            'categories' => $request->categories,
                            'updated_at' => $request->updated_at
                        ]);

    return redirect()->route('others_teahcing_material.dashboard')->with('success', '更新成功');

Body:
You can add your file rule into your $rules array and delete your second Validate::make() method so your $rules array will be:

$rules = [
          'edu_title'  => 'max:255',
          'edu_author' => 'max:10',
          'categories' => 'max:100',
          'file_name'  => 'nullable|file',
          'updated_at' => 'date|before:tomorrow',
          'file_name' => 'file'
         ];


问:
Is it possible to use WebClient to retrieve a file from the browser cache without checking for a newer version of the file?
I am using an instance of WebClient in my Silverlight application to retrieve an image file for display. In order to service this application, I have set up a WCF REST service. The following is a snippet of code I wrote for that service:

```<code>DateTime modSince = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.IfModifiedSince]
    == null
    ? DateTime.MinValue
    : DateTime.Parse(WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.IfModifiedSince].ToString());

FileInfo fInfo = new FileInfo(filePath);

if (fInfo.LastWriteTime > modSince)
{
    WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
    WebOperationContext.Current.OutgoingResponse.LastModified = fInfo.LastWriteTime;
}
else
{
    WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotModified;
}
</code>```

The service is set up such that on a request for an image file, the if-modified-since attribute of the request header is examined.  If this value is less than the last time the file is modified, the file is returned.  Otherwise, a 304 message is returned.

We are interested in making the transaction faster.  Since the images rarely, if ever, change it is desirable to look up the cache for a copy of the image before making a request to the server, which would save on network latency.  In trying to implement this for IE, I have changed the Temporary Internet Files settings to "never check for newer versions of stored pages".  When I enter in the browser's address bar the REST service URL for an image that has a copy stored in the cache, the copy is retrieved from the cache without the server being called.  However, when the URL is entered as a parameter to the WebClient's OpenReadAsync method a GET request is sent to the server, leading to a 304 message.

Is there any way I could use the WebClient to look up the cache without a GET request being sent to the server?

答:
You can't prevent the request from code in Silverlight.  The "never check" setting of IE is only used in the absence of cache control directives from the server, I would not recommend you use it.

I'm not sure why you are using WCF Rest to deliver images to the client instead of simply placing the images in a folder on the server and fetching them as standard static content?

Either way the correct approach to the your problem is for the server to specify how the images should be cached by including a Cache-Control header in the response.  Something like "Cache-Control: max-age=86400".

Body:
I am using an instance of WebClient in my Silverlight application to retrieve an image file for display. In order to service this application, I have set up a WCF REST service. The following is a snippet of code I wrote for that service:

DateTime modSince = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.IfModifiedSince]
    == null
    ? DateTime.MinValue
    : DateTime.Parse(WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.IfModifiedSince].ToString());

FileInfo fInfo = new FileInfo(filePath);

if (fInfo.LastWriteTime > modSince)
{
    WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
    WebOperationContext.Current.OutgoingResponse.LastModified = fInfo.LastWriteTime;
}
else
{
    WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotModified;
}

The service is set up such that on a request for an image file, the if-modified-since attribute of the request header is examined.  If this value is less than the last time the file is modified, the file is returned.  Otherwise, a 304 message is returned.

We are interested in making the transaction faster.  Since the images rarely, if ever, change it is desirable to look up the cache for a copy of the image before making a request to the server, which would save on network latency.  In trying to implement this for IE, I have changed the Temporary Internet Files settings to "never check for newer versions of stored pages".  When I enter in the browser's address bar the REST service URL for an image that has a copy stored in the cache, the copy is retrieved from the cache without the server being called.  However, when the URL is entered as a parameter to the WebClient's OpenReadAsync method a GET request is sent to the server, leading to a 304 message.

Is there any way I could use the WebClient to look up the cache without a GET request being sent to the server?


问:
Redraw multiple Paths at same positions from previous layout orientation
Based on my previous question of "How to create a BottomBar as StickyBottomCaptureLayout in camera2 Android api?", I created a layout with a StickyBar (SB) which is always locked above/near the system bar. I set the default positions and coordinates of the SB and the other layout in onLayout() (exactly as my answer).

The upper layout is a simple custom DrawView which has an ArrayList of Paths drew by the user. When the device rotates, it recalls onDraw() and calls several times canvas.drawPath(). However, the Paths are redrew with the same coordinates as before but on a different position and layout size. These screenshots demonstrate the actual behavior:

left: portrait - right: landscape

But I want to keep the same coordinates and positions when the orientation changed, like this:

left: same portrait as above - right: landscape with "portrait" coordinates

Locking my activity with android:orientation="portrait" is not the expected solution. I use android:configChanges="orientation" and an OrientationListener to detect the rotation and prevent the total recreation of the Activity.

I tried to set other different positions in onLayout() but obviously, this is not the right way.

I previously tried to transform the multiple Paths like this:

```<code>for (Path path : mPathList) {
    Matrix matrix = new Matrix();
    RectF bounds = new RectF();
    path.computeBounds(bounds, true);

    // center points to rotate
    final float px = bounds.centerX();
    final float py = bounds.centerY();
    // distance points to move
    final float dx; // ?
    final float dy; // ?
    /** I tried many calculations without success, it's
        not worth to paste these dumb calculations here... **/

    matrix.postRotate(rotation, px, py); // rotation is 90°, -90° or 0
    matrix.postTranslate(dx, dy); // ?
    path.transform(matrix);
}
</code>```

I also tried to rotate the canvas as follows:

```<code>@Override
protected void onDraw(Canvas canvas) {
    canvas.save();
    canvas.rotate(rotation); // rotation is 90°, -90° or 0

    canvas.drawColor(mDrawHelper.getBackgroundViewColor());
    for (int i=0; i < mPathList.size(); i++) {
       canvas.drawPath(mPathList.get(i), mPaintList.get(i));
    }
    if (mPath != null && mPaint != null)
       canvas.drawPath(mPath, mPaint);

    canvas.restore();
}
</code>```

Anyway, I tried many manipulations but nothing seems to work in this specific case. Does someone have a bright and fabulous idea to share which can lead me in the right direction?

Thanks in advance for the help.

答:
Instead of implementing a solution that is very specific to your problem, you can just implement a more generic one. For example a layout that will rotate everything what is inside, which in my opinion is much more elegant.

```<code>public class RotatedLayout extends FrameLayout {

    public RotatedLayout(Context context) {
        super(context);
    }

    ...

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int rotation = 0;
        boolean swapDimensions = false;
        int translationX = 0;
        int translationY = 0;

        final Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        switch (display.getRotation()) {
            case Surface.ROTATION_0:
                rotation = 0;
                break;
            case Surface.ROTATION_90:
                rotation = -90;
                swapDimensions = true;
                break;
            case Surface.ROTATION_180:
                rotation = 180;
                break;
            case Surface.ROTATION_270:
                rotation = 90;
                swapDimensions = true;
                break;
        }

        if (swapDimensions) {
            final int width = MeasureSpec.getSize(widthMeasureSpec);
            final int height = MeasureSpec.getSize(heightMeasureSpec);
            translationX = (width - height) / 2;
            translationY = (height - width) / 2;
            final int tmpMeasureSpec = heightMeasureSpec;
            heightMeasureSpec = widthMeasureSpec;
            widthMeasureSpec = tmpMeasureSpec;
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setTranslationX(translationX);
        setTranslationY(translationY);
        setRotation(rotation);
    }
}
</code>```

This layout is rather straightforward. It forces itself to be measured with swapped dimensions if displayed in landscape mode. It doesn't care what is inside, so you can put everything there, also a regular interface. After measuring itself (and children) with swapped MeasureSpecs it rotates itself and translates, using view properties, to fit the new position. As a bonus of using view properties - touch events works just fine and this button can be pressed as usual.

In portrait orientation:

Rotated to the left:

Problem with onConfigurationChanged

Although this layout will always draw itself in correct orientation, there must be some event that will cause it to be re-drawn. This may be a problem if you rely only on onConfigurationChanged. In your case Activity can react on changes from landscape to portrait and portrait to landscape. But there is no event sent when switching directly from:

portrait orientation to reverted portrait (if you have the reversed portrait enabled in your AndroidManifest) - marked in blue.

landscape orientation to reversed landscape - marked in red

Please keep in mind that such direct orientation swapping to the reversed orientation is a normal interaction on regular device, it is not something artificial that you can do on emulator only.

There is no standard event sent that will cause views to redraw themselves - no onConfigurationChanged, onMeasure, onLayout, onDraw etc. is invoked.
System just rotates everything for you (without even redrawing it) and it will result in wrong rotation of the view RotatedLayout had no changes to correct it. So be aware that you have to handle this case.

You can see it here in an answered by Dianne Hackborn.

This is simply not a configuration change. There is no notification the
  platform provides for when it does this, because it is invisible to the
  environment the app is in.

To solve this problem you would have to use SensorManager and register OrientationEventListener to determine when to refresh your view instead of relying on onConfigurationChanged method.

Body:
Based on my previous question of "How to create a BottomBar as StickyBottomCaptureLayout in camera2 Android api?", I created a layout with a StickyBar (SB) which is always locked above/near the system bar. I set the default positions and coordinates of the SB and the other layout in onLayout() (exactly as my answer).

The upper layout is a simple custom DrawView which has an ArrayList of Paths drew by the user. When the device rotates, it recalls onDraw() and calls several times canvas.drawPath(). However, the Paths are redrew with the same coordinates as before but on a different position and layout size. These screenshots demonstrate the actual behavior:

left: portrait - right: landscape

But I want to keep the same coordinates and positions when the orientation changed, like this:

left: same portrait as above - right: landscape with "portrait" coordinates

Locking my activity with android:orientation="portrait" is not the expected solution. I use android:configChanges="orientation" and an OrientationListener to detect the rotation and prevent the total recreation of the Activity.

I tried to set other different positions in onLayout() but obviously, this is not the right way.

I previously tried to transform the multiple Paths like this:

for (Path path : mPathList) {
    Matrix matrix = new Matrix();
    RectF bounds = new RectF();
    path.computeBounds(bounds, true);

    // center points to rotate
    final float px = bounds.centerX();
    final float py = bounds.centerY();
    // distance points to move
    final float dx; // ?
    final float dy; // ?
    /** I tried many calculations without success, it's
        not worth to paste these dumb calculations here... **/

    matrix.postRotate(rotation, px, py); // rotation is 90°, -90° or 0
    matrix.postTranslate(dx, dy); // ?
    path.transform(matrix);
}

I also tried to rotate the canvas as follows:

@Override
protected void onDraw(Canvas canvas) {
    canvas.save();
    canvas.rotate(rotation); // rotation is 90°, -90° or 0

    canvas.drawColor(mDrawHelper.getBackgroundViewColor());
    for (int i=0; i < mPathList.size(); i++) {
       canvas.drawPath(mPathList.get(i), mPaintList.get(i));
    }
    if (mPath != null && mPaint != null)
       canvas.drawPath(mPath, mPaint);

    canvas.restore();
}

Anyway, I tried many manipulations but nothing seems to work in this specific case. Does someone have a bright and fabulous idea to share which can lead me in the right direction?

Thanks in advance for the help.

Body:
Instead of implementing a solution that is very specific to your problem, you can just implement a more generic one. For example a layout that will rotate everything what is inside, which in my opinion is much more elegant.

public class RotatedLayout extends FrameLayout {

    public RotatedLayout(Context context) {
        super(context);
    }

    ...

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int rotation = 0;
        boolean swapDimensions = false;
        int translationX = 0;
        int translationY = 0;

        final Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        switch (display.getRotation()) {
            case Surface.ROTATION_0:
                rotation = 0;
                break;
            case Surface.ROTATION_90:
                rotation = -90;
                swapDimensions = true;
                break;
            case Surface.ROTATION_180:
                rotation = 180;
                break;
            case Surface.ROTATION_270:
                rotation = 90;
                swapDimensions = true;
                break;
        }

        if (swapDimensions) {
            final int width = MeasureSpec.getSize(widthMeasureSpec);
            final int height = MeasureSpec.getSize(heightMeasureSpec);
            translationX = (width - height) / 2;
            translationY = (height - width) / 2;
            final int tmpMeasureSpec = heightMeasureSpec;
            heightMeasureSpec = widthMeasureSpec;
            widthMeasureSpec = tmpMeasureSpec;
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setTranslationX(translationX);
        setTranslationY(translationY);
        setRotation(rotation);
    }
}

This layout is rather straightforward. It forces itself to be measured with swapped dimensions if displayed in landscape mode. It doesn't care what is inside, so you can put everything there, also a regular interface. After measuring itself (and children) with swapped MeasureSpecs it rotates itself and translates, using view properties, to fit the new position. As a bonus of using view properties - touch events works just fine and this button can be pressed as usual.

In portrait orientation:

Rotated to the left:

Problem with onConfigurationChanged

Although this layout will always draw itself in correct orientation, there must be some event that will cause it to be re-drawn. This may be a problem if you rely only on onConfigurationChanged. In your case Activity can react on changes from landscape to portrait and portrait to landscape. But there is no event sent when switching directly from:

portrait orientation to reverted portrait (if you have the reversed portrait enabled in your AndroidManifest) - marked in blue.

landscape orientation to reversed landscape - marked in red

Please keep in mind that such direct orientation swapping to the reversed orientation is a normal interaction on regular device, it is not something artificial that you can do on emulator only.

There is no standard event sent that will cause views to redraw themselves - no onConfigurationChanged, onMeasure, onLayout, onDraw etc. is invoked.
System just rotates everything for you (without even redrawing it) and it will result in wrong rotation of the view RotatedLayout had no changes to correct it. So be aware that you have to handle this case.

You can see it here in an answered by Dianne Hackborn.

This is simply not a configuration change. There is no notification the
  platform provides for when it does this, because it is invisible to the
  environment the app is in.

To solve this problem you would have to use SensorManager and register OrientationEventListener to determine when to refresh your view instead of relying on onConfigurationChanged method.


问:
Android studio and gradle internet
Is it compulsory that Android studio must be connected to the internet to use gradle for debugging an android project and creating an apk file</p>

答: You can run in offline mode. But any update to build.gradle will need internet connection to sync the project</p>

Title: Android studio and gradle internet


问:
boost::shared_array<char> to std::string
What is the best way to convert a boost::shared_array<char> to a std::string?
The following snippet works but it does not look very elegant.

```<code>boost::shared_array<char> boostString = DatabaseFileName.GetCString(CZString::eAscii);
std::string stdString;
for(size_t i = 0; boostString[i] != 0; i++)
{
    stdString.append(1, boostString[i]);
}
</code>```

答:
Boost shared array uses new[] to allocate its data, which means it's all contiguous in memory. That means you can get a pointer to the first element as a C-style string, from which you can create a std::string instance.

This of course requires the data to either have a terminator, or for you to know the length of the "string".

Body:
What is the best way to convert a boost::shared_array<char> to a std::string?
The following snippet works but it does not look very elegant.

boost::shared_array<char> boostString = DatabaseFileName.GetCString(CZString::eAscii);
std::string stdString;
for(size_t i = 0; boostString[i] != 0; i++)
{
    stdString.append(1, boostString[i]);
}


问:
PhpStorm - Mark multiple lines
Is it possible to mark multiple lines in PhpStorm?

e.g.

```<code>LineA
LineB
LineC
</code>```

lets say I try to mark LineA and LineC to copy paste them to another place, is this possible?

```<code>LineA
LineC
</code>```

答:
Use multiple cursors. The keyboard shortcuts may vary (those described in the documentation do not work for me on Linux).

Explore clicking around the text while various combinations of the Ctrl, Alt and Shift keys are pressed. On macOS also try Cmd. One of them allows you to place multiple carets in the text (f.e. at the beginning of the lines you want to copy).

After you placed all the carets you need use Shift and the arrows to extend the selection. Use Copy and Paste as usual. Use Escape or click anywhere in the text to deselect and go back to the regular, single-caret, status.

Title: PhpStorm - Mark multiple lines

Body:
Is it possible to mark multiple lines in PhpStorm?

e.g.

LineA
LineB
LineC

lets say I try to mark LineA and LineC to copy paste them to another place, is this possible?

LineA
LineC


问:
select data header join detail last doc_num header is promotion?
I have two tables, named t_header and t_detail.

this data header

```<code>ID | doc_num | promotion
1     0001      0
2     0002      1
</code>```

this data detail

```<code>ID | doc_num | item | price
1     0001      2      100
2     0001      3      170
3     0001      4      102
4     0001      5      105
5     0002      3      120
6     0002      4       99
7     0002      7      165
</code>```

if promo = 1, then the price in detail would take detailed data promo price, for the table above if the item = 3 then will take the price = 120 because the item with doc_num 002 promo = 1, if no promo it will take prices docnum 001, 001 num doc standard prices, and group by item

output

```<code>ID | doc_num | item | price | promotion
1     0001      2      100    0
5     0002      3      120    1
6     0002      4      99     1
4     0001      5      105    0
7     0002      7      165    0
</code>```

答:
As I can see in you desired result, you don't want items to be shown twice. Next to this I assume you have an items table in your database. Then I came up with this query.
First part is to extract items in promo.
Second part add only those items which are not in promo, but exclude items that have a promo on them.

```<code>SELECT d.id, d.doc_num, d.item, d.price, h.promo
FROM items AS i
  INNER JOIN detail AS d ON i.id = d.id
  INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1
UNION ALL
SELECT nopromo.*
FROM (SELECT d.id, d.doc_num, d.item, d.price, h.promo
      FROM items AS i
        INNER JOIN detail AS d ON i.id = d.id
        INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 0) AS nopromo
  LEFT OUTER JOIN
    (SELECT d.id, d.doc_num, d.item, d.price, h.promo
     FROM item AS i
       INNER JOIN detail AS d ON i.id = d.id
       INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1) AS ipromo
  ON nopromo.item = ipromo.item
WHERE ipromo.id IS NULL
ORDER BY item
</code>```

Result

```<code>+---+--------+-----+------+------+
|id |doc_num |item |price |promo |
+---+--------+-----+------+------+
|1  |0001    |2    |100   |0     |
|5  |0002    |3    |120   |1     |
|6  |0002    |4    |99    |1     |
|4  |0001    |5    |105   |0     |
|7  |0002    |7    |165   |1     |
+---+--------+-----+------+------+
</code>```

Body:
I have two tables, named t_header and t_detail.

this data header

ID | doc_num | promotion
1     0001      0
2     0002      1

this data detail

ID | doc_num | item | price
1     0001      2      100
2     0001      3      170
3     0001      4      102
4     0001      5      105
5     0002      3      120
6     0002      4       99
7     0002      7      165

if promo = 1, then the price in detail would take detailed data promo price, for the table above if the item = 3 then will take the price = 120 because the item with doc_num 002 promo = 1, if no promo it will take prices docnum 001, 001 num doc standard prices, and group by item

output

ID | doc_num | item | price | promotion
1     0001      2      100    0
5     0002      3      120    1
6     0002      4      99     1
4     0001      5      105    0
7     0002      7      165    0

Body:
As I can see in you desired result, you don't want items to be shown twice. Next to this I assume you have an items table in your database. Then I came up with this query.
First part is to extract items in promo.
Second part add only those items which are not in promo, but exclude items that have a promo on them.

SELECT d.id, d.doc_num, d.item, d.price, h.promo
FROM items AS i
  INNER JOIN detail AS d ON i.id = d.id
  INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1
UNION ALL
SELECT nopromo.*
FROM (SELECT d.id, d.doc_num, d.item, d.price, h.promo
      FROM items AS i
        INNER JOIN detail AS d ON i.id = d.id
        INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 0) AS nopromo
  LEFT OUTER JOIN
    (SELECT d.id, d.doc_num, d.item, d.price, h.promo
     FROM item AS i
       INNER JOIN detail AS d ON i.id = d.id
       INNER JOIN header AS h ON h.doc_num = d.doc_num AND h.promo = 1) AS ipromo
  ON nopromo.item = ipromo.item
WHERE ipromo.id IS NULL
ORDER BY item

Result

+---+--------+-----+------+------+
|id |doc_num |item |price |promo |
+---+--------+-----+------+------+
|1  |0001    |2    |100   |0     |
|5  |0002    |3    |120   |1     |
|6  |0002    |4    |99    |1     |
|4  |0001    |5    |105   |0     |
|7  |0002    |7    |165   |1     |
+---+--------+-----+------+------+


问:
Validation in MVC?
In my project Validation messages are not displaying, not getting any error just messages are not displaying. What is mistake?

Here is portion of code of model, view and controller:

Model:

```<code> [Required(ErrorMessage = "Username is required")]
 public string Username { get; set; }

 [Required(ErrorMessage = "Password is required")]
 public string Password { get; set; }
</code>```

Controller:

```<code> public ActionResult Index()
 {
     return View();
 }
</code>```

View:

```<code> <div class="form-group">
     <label id="label">Username</label>
     @Html.TextBoxFor(model => model.Username, new { @class ="form-control", placeholder = "Please enter your Username", @style = "height : 45px" })
     @Html.ValidationMessageFor(m => m.Username, "", new {@class = "text-danger"})
 </div>
 <div class="form-group">
      <label id="label">Password</label>
      @Html.TextBoxFor(model => model.Password, new { @class = "form-control", placeholder = "Please enter your Password", @style = "height : 45px" })
      @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
 </div>
</code>```

答:
My guess is that you are not including 'jquery.unobtrusive-ajax.min.js' and/or 'jquery.validate.unobtrusive.min.js'. I believe these are required to interpret the metadata added by DataAnnotations and supply the validation methods your looking for.

Refer this link for the better understanding

https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/validation-with-the-data-annotation-validators-cs

Title: Validation in MVC?

Body:
In my project Validation messages are not displaying, not getting any error just messages are not displaying. What is mistake?

Here is portion of code of model, view and controller:

Model:

 [Required(ErrorMessage = "Username is required")]
 public string Username { get; set; }

 [Required(ErrorMessage = "Password is required")]
 public string Password { get; set; }

Controller:

 public ActionResult Index()
 {
     return View();
 }

View:

     Username
     @Html.TextBoxFor(model => model.Username, new { @class ="form-control", placeholder = "Please enter your Username", @style = "height : 45px" })
     @Html.ValidationMessageFor(m => m.Username, "", new {@class = "text-danger"})

      Password
      @Html.TextBoxFor(model => model.Password, new { @class = "form-control", placeholder = "Please enter your Password", @style = "height : 45px" })
      @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })


问:
Issue when trying to iterate through textfile lines
I am trying something pretty simple but i have issue I do not understand.
Basically I have a file that is filled with text with this form

```<code>Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
</code>```

What I want to do is write all blocks of 3 lines that have an accuracy above 0.90 in another file.
To navigate through the lines I used the solution proposed here.
My code is the following :

```<code>with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     for line in range(1,int(len(oldfile.readlines()))):
         print(line)
         if line%3==0:
             f=oldfile.readlines()[line-2]
             f=f.split(' ')[3]
             if int(f)>0.90:
                 newfile.write(oldfile.readlines()[line-2])
                 newfile.write(oldfile.readlines()[line-1])
                 newfile.write(oldfile.readlines()[line])
</code>```

Starting here I have 2 issues I do not understand ...
the first one is

f=oldfile.readlines()[line-2] IndexError: list index out of range

That i don't understand as I print the length that is 13599, and my modulo is working so 3-2=1, no negative number of lines

The second issue that I never got before is that when I uncomment the print(len(oldfile.readlines()))line, I have no errors as it prints the value, but then stop without doing nothing. It is like the print is killing the program as it does not enter the for loop....

Thx

答:
You can't use oldfile.readlines() multiple times.

Instead of it, assign the content of the file into a variable as follows:

```<code>contentOfTheFile = oldfile.readlines()
</code>```

and use this variable instead of oldfile.readlines() in the the code.

Body:
I am trying something pretty simple but i have issue I do not understand.
Basically I have a file that is filled with text with this form

Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================
Text Accuracy: 0.568221 F1 = 22 recall=0.54
with paramters A=xxx B=11 C=222...
=============================

What I want to do is write all blocks of 3 lines that have an accuracy above 0.90 in another file.
To navigate through the lines I used the solution proposed here.
My code is the following :

with open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree.txt') as oldfile, open('G:\Mayeul\Distribution images\Features_importance\LogDecisionTree2.txt', 'w') as newfile:
     #print(len(oldfile.readlines()))
     for line in range(1,int(len(oldfile.readlines()))):
         print(line)
         if line%3==0:
             f=oldfile.readlines()[line-2]
             f=f.split(' ')[3]
             if int(f)>0.90:
                 newfile.write(oldfile.readlines()[line-2])
                 newfile.write(oldfile.readlines()[line-1])
                 newfile.write(oldfile.readlines()[line])

Starting here I have 2 issues I do not understand ...
the first one is

f=oldfile.readlines()[line-2] IndexError: list index out of range

That i don't understand as I print the length that is 13599, and my modulo is working so 3-2=1, no negative number of lines

The second issue that I never got before is that when I uncomment the print(len(oldfile.readlines()))line, I have no errors as it prints the value, but then stop without doing nothing. It is like the print is killing the program as it does not enter the for loop....

Thx

Body:
You can't use oldfile.readlines() multiple times.

Instead of it, assign the content of the file into a variable as follows:

contentOfTheFile = oldfile.readlines()

and use this variable instead of oldfile.readlines() in the the code.


问:
Open docx content within Eclipse XML editor
Given the docx format basically just consists of a bunch of zipped xml files, I wonder whether it is possible to view / edit it within the Eclipse IDE without manual unzipping and rezipping.

答:
This plugin provides the wanted feature:

Eclipse Zip Editor

Usage:

Install plugin via Eclipse Marketplace

Right-click on a docx file

Choose Open With > Other and select ZipEditor

Double-click on document.xml

Run the formatter via Ctrl+Shift+F

Edit the content and save

On tab close ZipEditor asks about updating the zip file


问:
scale_y_discrete ignores breaks/labels
Bug? Possibly related to this..

```<code>dat = data.frame(x = 1:4, y = ordered(c(4,'>5',1,1), levels = c(1:5, '>5')), grp = 1)

ggplot(dat, aes(x, y, group=grp)) + geom_step() +
  scale_y_discrete(breaks = levels(dat$y), labels = levels(dat$y))
</code>```

答:
```<code>ggplot(dat, aes(x, y, group=grp)) + geom_step() +
  scale_y_discrete(breaks = levels(dat$y), labels = levels(dat$y), drop = FALSE)
</code>```

Title: scale_y_discrete ignores breaks/labels

Body:
Bug? Possibly related to this..

dat = data.frame(x = 1:4, y = ordered(c(4,'>5',1,1), levels = c(1:5, '>5')), grp = 1)

ggplot(dat, aes(x, y, group=grp)) + geom_step() +
  scale_y_discrete(breaks = levels(dat$y), labels = levels(dat$y))


问:
Update only specific variable on PHP/HTML
```<code><form>
<table>
    <tr>
        <!--starting time is enter by user-->
        <th>Start Time:</th>
        <td><input type="time" name="startTime"></td>
    </tr>
    <tr>
        <!--interval is select by user-->
        <th>Interval:</th>
        <td>
            <select name="interval" >
                <option value="30 minutes">30 minutes</option>
                <option value="1 hours">1 hours</option>
            </select>
        </td>
    </tr>
    <tr>
        <th>End Time:</th>
        <td>
        <!-- show end time here
        and data should be readonly(not editable) -->
        </td>
    </tr>
</table>
</form>
</code>```

end time should be update (add startTime&interval) itself after start time and interval is selected. And data from start time and interval should remain. So I only want it to update the end time variable. How can I achieve that?

I had try used input type:button to update the end time. But the start time and interval data is refreshed.

答:
If you want to change the site without reloading the site itself, you should use javascript/jquery, since javascript is only client-sided the user could change the values all by himself. (But still it wouldn't change anything on the server itself).

If you want to do it over this way you have to change a few things in the form

```<code><td><input type="time" name="startTime" id="startTime" onchange="changeTime()"></td>

<select name="interval" id="interval" onchange="changeTime()">
     <option value="30">30 minutes</option>
     <option value="60">1 hours</option>
</select>

<th>End Time:</th>
  <td>
    <p id="endTime"></p>
  </td>
</code>```

After that I wrote a JavaScript which updates every time something is changed. Since I don't really know how to handle the input type time, I just split it in to an array and then just updates those values:

```<code><script>
function changeTime(){
    var startTime = document.getElementById("startTime").value;
    startTime = startTime.split(":");
    var hours = startTime[0];
    var minutes = startTime[1];
    var interval = document.getElementById("interval").value;

    minutes = parseInt(minutes)+parseInt(interval);

    if (minutes > 60) {  //check if an hour should be added
        minutes-= 60;
        hours++;
    }
    document.getElementById("endTime").innerHTML = hours+":"+minutes;
}
</code>```

And after that, if you are sending the values to your server, you can still just take the values and load it into a php file, but this is not client-sided so the user won't see it directly without a reload.

Here are a few things I used here:

Split

GetElementByID

More Infos about Javascript

Or if you have any open questions feel free to ask me

Body:
<form>

        Start Time:
        <input type="time" name="startTime">

        Interval:

            <select name="interval" >
                <option value="30 minutes">30 minutes</option>
                <option value="1 hours">1 hours</option>
            </select>

        End Time:

</form>

end time should be update (add startTime&interval) itself after start time and interval is selected. And data from start time and interval should remain. So I only want it to update the end time variable. How can I achieve that?

I had try used input type:button to update the end time. But the start time and interval data is refreshed.

Body:
If you want to change the site without reloading the site itself, you should use javascript/jquery, since javascript is only client-sided the user could change the values all by himself. (But still it wouldn't change anything on the server itself).

If you want to do it over this way you have to change a few things in the form

<td><input type="time" name="startTime" id="startTime" onchange="changeTime()"></td>

<select name="interval" id="interval" onchange="changeTime()">
     <option value="30">30 minutes</option>
     <option value="60">1 hours</option>
</select>

<th>End Time:</th>
  <td>
    <p id="endTime"></p>
  </td>

After that I wrote a JavaScript which updates every time something is changed. Since I don't really know how to handle the input type time, I just split it in to an array and then just updates those values:

<script>
function changeTime(){
    var startTime = document.getElementById("startTime").value;
    startTime = startTime.split(":");
    var hours = startTime[0];
    var minutes = startTime[1];
    var interval = document.getElementById("interval").value;

    minutes = parseInt(minutes)+parseInt(interval);

    if (minutes > 60) {  //check if an hour should be added
        minutes-= 60;
        hours++;
    }
    document.getElementById("endTime").innerHTML = hours+":"+minutes;
}

And after that, if you are sending the values to your server, you can still just take the values and load it into a php file, but this is not client-sided so the user won't see it directly without a reload.

Here are a few things I used here:

Split

GetElementByID

More Infos about Javascript

Or if you have any open questions feel free to ask me


问:
Different types shown when iterating over a String's UTF8View
I'm currently studying string in swift. I have two version of the same code

The variable in the for in loop are suppose to have the same type, but as you can see, the type is actually different?

I must be missing something here, but can't seem to figure out.

答:
This is merely a presentation thing – the _IndexableBase protocol (which Collection internally derives from) declares an _Element associated type as a workaround for a conformance cycle:

```<code>protocol _IndexableBase {

      // ...

      // The declaration of _Element and subscript here is a trick used to
      // break a cyclic conformance/deduction that Swift can't handle.  We
      // need something other than a Collection.Iterator.Element that can
      // be used as IndexingIterator<T>'s Element.  Here we arrange for
      // the Collection itself to have an Element type that's deducible from
      // its subscript.  Ideally we'd like to constrain this Element to be the same
      // as Collection.Iterator.Element (see below), but we have no way of
      // expressing it today.
      associatedtype _Element

      // ...
      subscript(position: Index) -> _Element { get }
      // ...
}
</code>```

(Note this will all change once recursive protocol constraints are implemented)

In practice, this associated type should always be satisfied by the same type as the Collection's Iterator.Element, due to the fact that Collection has a

```<code>subscript(position: Index) -> Iterator.Element { get }
</code>```

requirement. Thus when conforming to Collection, the compiler will by default deduce that Iterator.Element == _Element.

With String.UTF8View, it implements Collection with an Iterator.Element of type UTF8.CodeUnit (aka. UInt8). Therefore the types String.UTF8View._Element, String.UTF8View.Iterator.Element, UTF8.CodeUnit and UInt8 are all the same.

You can easily verify this for yourself by comparing the metatype values:

```<code>print(UInt8.self == UTF8.CodeUnit.self)                    // true
print(UInt8.self == String.UTF8View._Element.self)         // true
print(UInt8.self == String.UTF8View.Iterator.Element.self) // true
</code>```

Xcode simply chooses to display different type aliases in this case. Although  in Xcode 8.3 beta 4, they are both displayed as UTF8.CodeUnit.

Body:
This is merely a presentation thing – the _IndexableBase protocol (which Collection internally derives from) declares an _Element associated type as a workaround for a conformance cycle:

protocol _IndexableBase {

      // ...

      // The declaration of _Element and subscript here is a trick used to
      // break a cyclic conformance/deduction that Swift can't handle.  We
      // need something other than a Collection.Iterator.Element that can
      // be used as IndexingIterator<T>'s Element.  Here we arrange for
      // the Collection itself to have an Element type that's deducible from
      // its subscript.  Ideally we'd like to constrain this Element to be the same
      // as Collection.Iterator.Element (see below), but we have no way of
      // expressing it today.
      associatedtype _Element

      // ...
      subscript(position: Index) -> _Element { get }
      // ...
}

(Note this will all change once recursive protocol constraints are implemented)

In practice, this associated type should always be satisfied by the same type as the Collection's Iterator.Element, due to the fact that Collection has a

subscript(position: Index) -> Iterator.Element { get }

requirement. Thus when conforming to Collection, the compiler will by default deduce that Iterator.Element == _Element.

With String.UTF8View, it implements Collection with an Iterator.Element of type UTF8.CodeUnit (aka. UInt8). Therefore the types String.UTF8View._Element, String.UTF8View.Iterator.Element, UTF8.CodeUnit and UInt8 are all the same.

You can easily verify this for yourself by comparing the metatype values:

print(UInt8.self == UTF8.CodeUnit.self)                    // true
print(UInt8.self == String.UTF8View._Element.self)         // true
print(UInt8.self == String.UTF8View.Iterator.Element.self) // true

Xcode simply chooses to display different type aliases in this case. Although  in Xcode 8.3 beta 4, they are both displayed as UTF8.CodeUnit.


Title: Unstack and merge based on column value as key

Body:
I get an output from my grep command as below.

 grep -r GFD . | cut -d: -f2
out_GFD_994     NSE_FO_BHP_1703   -9425     6800       361.45      11900     359.96      5100      0.34%    6137085.0  -15.36
out_GFD_994     NSE_FO_BHP_1704   15651     -6800      360.38      6800      362.04      13600     26.66%   7374430.0  21.22
out_GFD_994     NSE_FO_TLS_1703        -4996     2000       603.57      5000      602.68      3000      0.46%    4825900.0  -10.35
out_GFD_994     NSE_FO_TLS_1704        4480      -2000      605.71      3000      606.44      5000      29.62%   4849350.0  9.24
out_GFD_994     NSE_FO_MQG_1703          -11717    -20000     148.64      50000     148.64      70000     0.46%    17837250.0  -6.57
out_GFD_994     NSE_FO_MQG_1704          17213     20000      149.29      75000     149.39      55000     36.11%   19413500.0  8.87
out_GFD_Part2                        NSE_FO_BHP_1703   -17597    -20000     0           0         39.25       20000     0.07%    785000.0  -224.17
out_GFD_Part2                        NSE_FO_BHP_1704   14481     20000      39.6        20000     0           0         1.38%    792000.0  182.84
out_GFD_Part2                        NSE_FO_TLS_1703         28312     1200       643.93      16800     645.52      15600     0.54%    20888220.0  13.55
out_GFD_Part2                        NSE_FO_TLS_1704         -23813    -1200      647.91      16800     646.87      18000     34.11%   22528620.0  -10.57
out_GFD_Part2                        NSE_FO_MQG_1703   -133456    8800       1029.33     25300     1025.86     16500     0.55%    42968915.0  -31.06 unhedged
out_GFD_Part2                        NSE_FO_MQG_1704   141534    -7700      1031.26     33000     1033.85     40700     49.62%   76109605.0  18.60

I need a purge/merge/unstack (whatever word sounds appropriate) according to 2nd column value as key.
So that output data transforms to (summation of corresponding values)

out_GFD_994     out_GFD_Part2    NSE_FO_BHP_1703   -9425-17597     6800-20000       361.45      11900     359.96      5100      0.34%    6137085.0  -15.36
out_GFD_994     out_GFD_Part2    NSE_FO_BHP_1704   15651+14481     -6800+20000      360.38      6800      362.04      13600     26.66%   7374430.0  21.22
out_GFD_994     out_GFD_Part2    NSE_FO_TLS_1703        -4996+28312     2000+1200       603.57      5000      602.68      3000      0.46%    4825900.0  -10.35
out_GFD_994     out_GFD_Part2    NSE_FO_TLS_1704        4480-23813     -2000-1200      605.71      3000      606.44      5000      29.62%   4849350.0  9.24
out_GFD_994     out_GFD_Part2    NSE_FO_MQG_1703          -11717-133456    -20000+8800     148.64      50000     148.64      70000     0.46%    17837250.0  -6.57
out_GFD_994     out_GFD_Part2    NSE_FO_MQG_1704          17213+141534     20000-7700      149.29      75000     149.39      55000     36.11%   19413500.0  8.87

                                       (only 2 columns shown in expected output format)

I can give names to columns and load it as pandas dataframe if that paves the way to solve this problem.

Update 1:

I would work on just 5 columns for now and have loaded it into my pandas dataframe as below

>>> df
      grep_string              key    val1   val2     val3
0     out_GFD_994  NSE_FO_BHP_1703   -9425   6800   361.45
1     out_GFD_994  NSE_FO_BHP_1704   15651  -6800   360.38
2     out_GFD_994  NSE_FO_TLS_1703   -4996   2000   603.57
3     out_GFD_994  NSE_FO_TLS_1704    4480  -2000   605.71
4     out_GFD_994  NSE_FO_MQG_1703  -11717 -20000   148.64
5     out_GFD_994  NSE_FO_MQG_1704   17213  20000   149.29
6   out_GFD_Part2  NSE_FO_BHP_1703  -17597 -20000     0.00
7   out_GFD_Part2  NSE_FO_BHP_1704   14481  20000    39.60
8   out_GFD_Part2  NSE_FO_TLS_1703   28312   1200   643.93
9   out_GFD_Part2  NSE_FO_TLS_1704  -23813  -1200   647.91
10  out_GFD_Part2  NSE_FO_MQG_1703 -133456   8800  1029.33
11  out_GFD_Part2  NSE_FO_MQG_1704  141534  -7700  1031.26

How do I do a  (summation) merge using key column

Update 2:

The summed column values are to be added to a logfile as below:

NSE_FO_BHP_1703_MAXLONGPOS = 200000
NSE_FO_BHP_1703_MAXSHORTPOS = 200000
NSE_FO_BHP_1703_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1703_MAXSHORTEXPOSURE = 250000
NSE_FO_BHP_1704_MAXLONGPOS = 200000
NSE_FO_BHP_1704_MAXSHORTPOS = 200000
NSE_FO_BHP_1704_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1704_MAXSHORTEXPOSURE = 250000
NSE_FO_TLS_1703_MAXLONGPOS = 100000
NSE_FO_TLS_1703_MAXSHORTPOS = 100000
NSE_FO_TLS_1703_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1703_MAXSHORTEXPOSURE = 200000
NSE_FO_TLS_1704_MAXLONGPOS = 100000
NSE_FO_TLS_1704_MAXSHORTPOS = 100000
NSE_FO_TLS_1704_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1704_MAXSHORTEXPOSURE = 200000
NSE_FO_MQG_1703_MAXLONGPOS = 300000
NSE_FO_MQG_1703_MAXSHORTPOS = 300000
NSE_FO_MQG_1703_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1703_MAXSHORTEXPOSURE = 400000
NSE_FO_DEF_1704_MAXLONGPOS = 300000
NSE_FO_MQG_1704_MAXSHORTPOS = 300000
NSE_FO_MQG_1704_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1704_MAXSHORTEXPOSURE = 400000

Can we add summed output value we get in df (say column d )to be added/subtracted to the above file by mapping it to substring. example we get -13200 in column d.  We have NSE_FO_BHP_1703_MAXLONGPOS = 200000. In the a file, change this to 213200 and change NSE_FO_BHP_1703_MAXSHORTPOS to 186800. Change the MAXLONGEXPOSURE and MAXSHORTEXPOSURE to 263200 and 236800 .

Body:
You can use groupby with agg by dict created by dict comprehension. Last create from first column another 2 by split:

print (df)
               0                1       2      3        4      5        6   \
0     out_GFD_994  NSE_FO_BHP_1703   -9425   6800   361.45  11900   359.96
1     out_GFD_994  NSE_FO_BHP_1704   15651  -6800   360.38   6800   362.04
2     out_GFD_994  NSE_FO_TLS_1703   -4996   2000   603.57   5000   602.68
3     out_GFD_994  NSE_FO_TLS_1704    4480  -2000   605.71   3000   606.44
4     out_GFD_994  NSE_FO_MQG_1703  -11717 -20000   148.64  50000   148.64
5     out_GFD_994  NSE_FO_MQG_1704   17213  20000   149.29  75000   149.39
6   out_GFD_Part2  NSE_FO_BHP_1703  -17597 -20000     0.00      0    39.25
7   out_GFD_Part2  NSE_FO_BHP_1704   14481  20000    39.60  20000     0.00
8   out_GFD_Part2  NSE_FO_TLS_1703   28312   1200   643.93  16800   645.52
9   out_GFD_Part2  NSE_FO_TLS_1704  -23813  -1200   647.91  16800   646.87
10  out_GFD_Part2  NSE_FO_MQG_1703 -133456   8800  1029.33  25300  1025.86
11  out_GFD_Part2  NSE_FO_MQG_1704  141534  -7700  1031.26  33000  1033.85

       7       8           9       10
0    5100   0.34%   6137085.0  -15.36
1   13600  26.66%   7374430.0   21.22
2    3000   0.46%   4825900.0  -10.35
3    5000  29.62%   4849350.0    9.24
4   70000   0.46%  17837250.0   -6.57
5   55000  36.11%  19413500.0    8.87
6   20000   0.07%    785000.0 -224.17
7       0   1.38%    792000.0  182.84
8   15600   0.54%  20888220.0   13.55
9   18000  34.11%  22528620.0  -10.57
10  16500   0.55%  42968915.0  -31.06
11  40700  49.62%  76109605.0   18.60

#sum all columns without first,second and 9 column with percentage
d = {x:'sum' for x in df if not x in [0,1,8]}
#add custom function for first column
d.update({0:'|'.join})
print (d)
{0: <built-in method join of str object at 0x0000000001180AE8>, 2: 'sum',
 3: 'sum', 4: 'sum', 5: 'sum', 6: 'sum', 7: 'sum', 9: 'sum', 10: 'sum'}

df = df.groupby(1).agg(d).reset_index()
df[[-2,-1]] = df.pop(0).str.split('|', expand=True)
#change order of columns
df = df.sort_index(axis=1)
#reset column names to  default (0,1...)
df.columns = np.arange(len(df.columns))
print (df)
            0              1                2       3      4        5   \
0  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1703  -27022 -13200   361.45
1  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1704   30132  13200   399.98
2  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1703 -145173 -11200  1177.97
3  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1704  158747  12300  1180.55
4  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1703   23316   3200  1247.50
5  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1704  -19333  -3200  1253.62

       6        7      8           9       10
0   11900   399.21  25100   6922085.0 -239.53
1   26800   362.04  13600   8166430.0  204.06
2   75300  1174.50  86500  60806165.0  -37.63
3  108000  1183.24  95700  95523105.0   27.47
4   21800  1248.20  18600  25714120.0    3.20
5   19800  1253.31  23000  27377970.0   -1.33

Solution with custom column names:

df.columns = list('abcdefghijk')
print (df)
                a                b       c      d        e      f        g  \
0     out_GFD_994  NSE_FO_BHP_1703   -9425   6800   361.45  11900   359.96
1     out_GFD_994  NSE_FO_BHP_1704   15651  -6800   360.38   6800   362.04
2     out_GFD_994  NSE_FO_TLS_1703   -4996   2000   603.57   5000   602.68
3     out_GFD_994  NSE_FO_TLS_1704    4480  -2000   605.71   3000   606.44
4     out_GFD_994  NSE_FO_MQG_1703  -11717 -20000   148.64  50000   148.64
5     out_GFD_994  NSE_FO_MQG_1704   17213  20000   149.29  75000   149.39
6   out_GFD_Part2  NSE_FO_BHP_1703  -17597 -20000     0.00      0    39.25
7   out_GFD_Part2  NSE_FO_BHP_1704   14481  20000    39.60  20000     0.00
8   out_GFD_Part2  NSE_FO_TLS_1703   28312   1200   643.93  16800   645.52
9   out_GFD_Part2  NSE_FO_TLS_1704  -23813  -1200   647.91  16800   646.87
10  out_GFD_Part2  NSE_FO_MQG_1703 -133456   8800  1029.33  25300  1025.86
11  out_GFD_Part2  NSE_FO_MQG_1704  141534  -7700  1031.26  33000  1033.85

        h       i           j       k
0    5100   0.34%   6137085.0  -15.36
1   13600  26.66%   7374430.0   21.22
2    3000   0.46%   4825900.0  -10.35
3    5000  29.62%   4849350.0    9.24
4   70000   0.46%  17837250.0   -6.57
5   55000  36.11%  19413500.0    8.87
6   20000   0.07%    785000.0 -224.17
7       0   1.38%    792000.0  182.84
8   15600   0.54%  20888220.0   13.55
9   18000  34.11%  22528620.0  -10.57
10  16500   0.55%  42968915.0  -31.06
11  40700  49.62%  76109605.0   18.60

d = {x:'sum' for x in df if not x in ['a','b', 'i']}
#add custom function for first column
d.update({'a':'|'.join})
print (d)
{'e': 'sum', 'k': 'sum', 'a': <built-in method join of str object at 0x0000000001180AE8>,
'f': 'sum', 'd': 'sum', 'g': 'sum', 'j': 'sum', 'c': 'sum', 'h': 'sum'}
df = df.groupby('b').agg(d).reset_index()
df1 = df.pop('a').str.split('|', expand=True)
df1.columns = ['out_' + str(x) for x in df1.columns]
df = pd.concat([df1, df],axis=1)
print (df)
         out_0          out_1                b        e       k       f  \
0  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1703   361.45 -239.53   11900
1  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1704   399.98  204.06   26800
2  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1703  1177.97  -37.63   75300
3  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1704  1180.55   27.47  108000
4  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1703  1247.50    3.20   21800
5  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1704  1253.62   -1.33   19800

       d        g           j       c      h
0 -13200   399.21   6922085.0  -27022  25100
1  13200   362.04   8166430.0   30132  13600
2 -11200  1174.50  60806165.0 -145173  86500
3  12300  1183.24  95523105.0  158747  95700
4   3200  1248.20  25714120.0   23316  18600
5  -3200  1253.31  27377970.0  -19333  23000


问:
Stretch image (not background) to full browser width in Wordpress with HTML and CSS
I'm trying to make a GIF display to full browser size, however I want it below menu (site-header div) and above footer. In order to do that I hid the page-header div and am stuck in a small container. `

```<code><div id="content" class="site-content"><div class="page-header"><div class="container"><h1 class="entry-title">Kampania</h1></div></div><div id="content-inside" class="container no-sidebar"><div id="primary" class="content-area"><main id="main" class="site-main" role="main"><article id="post-1259" class="post-1259 page type-page status-publish hentry"><header class="entry-header"></header><div class="entry-content"><p><img src="https://shop.sin.org.pl/wp-content/uploads/2017/03/gif.gif" id="selector"></p></div></article></main></div></div></div>
</code>```

What is packed in div "content-area" I need to move to the "site-content" div. How do I achieve that?

https://shop.sin.org.pl/pl/kampania/

Thanks!

答:
Have you tried setting your page template to 100% width?

If that doesn't work you can manualy set the page widht to 100%;

```<code>#content-inside {
    width:100%;
    max-width:inherit !important;
    padding:0 !important;
}
</code>```

Body:
I'm trying to make a GIF display to full browser size, however I want it below menu (site-header div) and above footer. In order to do that I hid the page-header div and am stuck in a small container. `

Kampania

What is packed in div "content-area" I need to move to the "site-content" div. How do I achieve that?

https://shop.sin.org.pl/pl/kampania/

Thanks!

Body:
Have you tried setting your page template to 100% width?

If that doesn't work you can manualy set the page widht to 100%;

#content-inside {
    width:100%;
    max-width:inherit !important;
    padding:0 !important;
}


问:
Laravel Eloquent: How to select from multiple tables
I'm using Laravel and the Eloquent ORM that it provides but I'm struggling to select the data I need.  I have 3 Models

House

Occupants

Job

A house can have multiple occupants and I can easily get these using the following.

```<code>$house= House::find($house_id);
$occupants = $house->occupants()->where('active', 1)->get();
</code>```

This works nicely but I also want to select the job of each occupant.  I've got this as a one to one relationship but the jobs are in a seperate table.

Is there a way to also select the related job for each occupant from the jobs table efficiently?  I'm guessing it would be something like this

```<code>$occupants_and_jobs = $house->occupants()->where('active', 1)->job()->get();
</code>```

答:
You could just try what you are suggesting and see what happens.
You can also do some eager loading of the relationships

```<code>$house = House::with(["occupants","occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
     print_r($occupant->job);
}
</code>```

As @AlexeyMezenin if you need to constrain the relationship then you need to (as the docs suggest under Constraining Eager Loads) do:

```<code>$house = House::with(["occupants" => function ($query) {
    $query->where("active","=",1);
},"occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
    print_r($occupant->job);
}
</code>```

Now the fine-print: Laravel will include "with" relationships in the order it finds them and also include all intermediate relationships of the nesting, e.g. ::with("occupants.job") implies ::with(["occupants","occupants.job"]) however if you already have set a previous relationship then it is maintained (which is how this works). occupants will not be overwritten when occupants.job is set.

Body:
I'm using Laravel and the Eloquent ORM that it provides but I'm struggling to select the data I need.  I have 3 Models

House

Occupants

Job

A house can have multiple occupants and I can easily get these using the following.

$house= House::find($house_id);
$occupants = $house->occupants()->where('active', 1)->get();

This works nicely but I also want to select the job of each occupant.  I've got this as a one to one relationship but the jobs are in a seperate table.

Is there a way to also select the related job for each occupant from the jobs table efficiently?  I'm guessing it would be something like this

$occupants_and_jobs = $house->occupants()->where('active', 1)->job()->get();

Body:
You could just try what you are suggesting and see what happens.
You can also do some eager loading of the relationships

$house = House::with(["occupants","occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
     print_r($occupant->job);
}

As @AlexeyMezenin if you need to constrain the relationship then you need to (as the docs suggest under Constraining Eager Loads) do:

$house = House::with(["occupants" => function ($query) {
    $query->where("active","=",1);
},"occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
    print_r($occupant->job);
}

Now the fine-print: Laravel will include "with" relationships in the order it finds them and also include all intermediate relationships of the nesting, e.g. ::with("occupants.job") implies ::with(["occupants","occupants.job"]) however if you already have set a previous relationship then it is maintained (which is how this works). occupants will not be overwritten when occupants.job is set.


问:
TextWatcher warnings and slow type in android
I want to change on type a character in android. If user type space or - it will change it to _

So I tried:

```<code>TextWatcher tt = null;

final EditText etUsername = (EditText) findViewById(R.id.etUsername);
   tt = new TextWatcher() {
        public void afterTextChanged(Editable s){
            etUsername.setSelection(s.length());
        }
        public void beforeTextChanged(CharSequence s,int start,int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            etUsername.removeTextChangedListener(tt);
            etUsername.setText(etUsername.getText().toString().replace(" ", "_"));
            etUsername.setText(etUsername.getText().toString().replace("-", "_"));
            etUsername.addTextChangedListener(tt);
        }
    };
    etUsername.addTextChangedListener(tt);
</code>```

it "works" but if user types fast some letters will not appear and I got some warnings:

```<code>W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
</code>```

any ideas what is wrong?

答:
Try this Textwatcher</p>

```<code>  TextWatcher watch = new TextWatcher(){

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int a, int b, int c) {
        // TODO Auto-generated method stub

        output.setText(s);
        if(a == 9){
            Toast.makeText(getApplicationContext(), "Maximum Limit Reached", Toast.LENGTH_SHORT).show();
        }
    }};
</code>```

Body:
I want to change on type a character in android. If user type space or - it will change it to _

So I tried:

TextWatcher tt = null;

final EditText etUsername = (EditText) findViewById(R.id.etUsername);
   tt = new TextWatcher() {
        public void afterTextChanged(Editable s){
            etUsername.setSelection(s.length());
        }
        public void beforeTextChanged(CharSequence s,int start,int count, int after){}
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            etUsername.removeTextChangedListener(tt);
            etUsername.setText(etUsername.getText().toString().replace(" ", "_"));
            etUsername.setText(etUsername.getText().toString().replace("-", "_"));
            etUsername.addTextChangedListener(tt);
        }
    };
    etUsername.addTextChangedListener(tt);

it "works" but if user types fast some letters will not appear and I got some warnings:

W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: commitText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: requestCursorAnchorInfo on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection

any ideas what is wrong?

Body:
Try this Textwatcher

  TextWatcher watch = new TextWatcher(){

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int a, int b, int c) {
        // TODO Auto-generated method stub

        output.setText(s);
        if(a == 9){
            Toast.makeText(getApplicationContext(), "Maximum Limit Reached", Toast.LENGTH_SHORT).show();
        }
    }};


问:
Google Shopping PHP API Last Page ProductList
I am cycling through the Product List pages, I know each page returns several fields and one of them is nextPageToken, the thing is that so far, all pages have this token, I haven't been able to find a way to recognize the last page.
Any idea on how to do it?

答: the last page is simply the page with no nextPageToken in the body it returns


问:
Gradle Output Jar has no Main-Class
I have the following simple build.gradle file:

```<code>apply plugin: 'application'
apply plugin: 'java'

mainClassName = 'com.kurtis.HelloGradle'
</code>```

And the following single java file located at src/main/java/com/kurtis/HelloGradle.java:

```<code>package com.kurtis;

public class HelloGradle {

    public static void main(String[] args) {

        System.out.println("Hello gradle");
    }

}
</code>```

However, if I run gradle build I get a jar in the build/lib directory that has no main class set. It's manifest file has no Main-Class entry. Why is this?

答:
It's due to the way application plugin works. mainClassName is a property used by application plugin, when it creates an executable jar, it doesn't need to have a Main-Class in the manifest, since it doesn't use it.

If you need to have a Main-Class in your jar, then you have to provide it vie jar configuration of the java plugin as follows:

```<code>jar {
  manifest {
    attributes(
      'Main-Class': 'com.kurtis.HelloGradle'
    )
  }
}
</code>```

Otherwise, just use an executable, which is generated by application plugin, whether via run task or via distributions it can create for you, with scripts to run your application and all it's dependencies.

Title: Gradle Output Jar has no Main-Class

Body:
I have the following simple build.gradle file:

apply plugin: 'application'
apply plugin: 'java'

mainClassName = 'com.kurtis.HelloGradle'

And the following single java file located at src/main/java/com/kurtis/HelloGradle.java:

package com.kurtis;

public class HelloGradle {

    public static void main(String[] args) {

        System.out.println("Hello gradle");
    }

}

However, if I run gradle build I get a jar in the build/lib directory that has no main class set. It's manifest file has no Main-Class entry. Why is this?

Body:
It's due to the way application plugin works. mainClassName is a property used by application plugin, when it creates an executable jar, it doesn't need to have a Main-Class in the manifest, since it doesn't use it.

If you need to have a Main-Class in your jar, then you have to provide it vie jar configuration of the java plugin as follows:

jar {
  manifest {
    attributes(
      'Main-Class': 'com.kurtis.HelloGradle'
    )
  }
}

Otherwise, just use an executable, which is generated by application plugin, whether via run task or via distributions it can create for you, with scripts to run your application and all it's dependencies.