问:
Firebase query not returning any data
My datamodel looks as follows :

```<code>allcomments
|__$comment_id_5
         |__post_id: <post_id_5>

uid
|
|__activity
     |__comments
            |__$random_activity_id
                       |__post_id : <post_id_5> //ref to post_id_5 in allcomments
                       |__comment_id : <comment_id_5> // ref to comment_id_5 in allcomments
</code>```

My Goal: To check if the user with uid has commented on the post or not. If that person has, then I he can proceed further else he'll be shown something else on the screen. On trying the following query, I am able to only get the callback when a snapshot exists and not otherwise.

```<code>FBDataservice.ds.child("allcomments").queryOrdered(byChild: "post_id").queryEqual(toValue: "post_id_5").observeSingleEvent(of: .ChildAdded) { (snapshot) in
        if let data = snapshot.value as? DataDict {
            let comment = Comment(comId: snapshot.key , comData: data)
            self.checkUserHasResponded(completion: { (hasResponded) in
                if !hasResponded {
                    // Never returns it there is nothng
                    print("You gotta respond first")
                } else {
                    //this part does work
                    print("Welcome to seeing everything")
                }
            })
        }
    }

func checkUserHasResponded(completion: @escaping (Bool) -> ()) {
    FBDataservice.ds.REF_USERS.child(uid).child("activity/comments").queryOrdered(byChild: "post_id").queryEqual(toValue: "post_id_5").observeSingleEvent(of: .value) { (snapshot) in
        snapshot.exists() ? completion(true) : completion(false)
    }
}
</code>```

I even tried tweaking the architecture this way and query it differently, still nothing work and the program behaves in the same exact way as incase of above.

```<code>uid
|
|__activity
     |__comments
            |__post_id_5 : comment_id_5
</code>```

and ran this query:

```<code>func checkUserHasResponded(completion: @escaping (Bool) -> ()) {
    FBDataservice.ds.REF_USERS.child(uid).child("activity/comments").observeSingleEvent(of: .value) { (snapshot) in
        snapshot.hasChild("post_id_5") ? completion(true) : completion(false)
    }
}
</code>```

I tried changing .childAdded to .value. It gives the same exact result. Tried changing .observeSingleEvent(of:) to .observe() as well. But nothing helps. I am not sure what exactly is wrong. Check plenty of answers here, none helped. What exactly am I over looking. Thanks for the help.

答:
Use .value instead of .childAdded, that way it the closure is called whether or not the snapshot exists, Just a quick test shows it works.

```<code>func checkUserHasResponded() {
    let uid = "uid_0"
    let commentsRef = dbRef.child(uid).child("activity").child("comments")
    commentsRef.queryOrdered(byChild: "post_id")
               .queryEqual(toValue: "post_5")
               .observeSingleEvent(of: .value) { snapshot in
        if snapshot.exists() {
            print("post exists")
        } else {
            print("post not found")
        }
    }
}
</code>```

If your structure does not contain a post_id child value that exists then the output is

```<code>post not found
</code>```

So this answer applies to the updated question. The code in the closure will not run if the node you're querying for does not exist because the query is using .childAdded

```<code>FBDataservice.ds.child("allcomments").queryOrdered(byChild: "post_id")
                                 .queryEqual(toValue: "post_id_5")
                                 .observeSingleEvent(of: .childAdded) { (snapshot) in
</code>```

If that's changed to .value, it returns and the code in the closure runs if the node exists. Keeping in mind that you'll want to use

```<code>snapshot.exists()
</code>```

with that as it will be nil if it doesn't.

Title: Firebase query not returning any data

Body:
My datamodel looks as follows :

allcomments
|__$comment_id_5
         |__post_id: <post_id_5>

uid
|
|__activity
     |__comments
            |__$random_activity_id
                       |__post_id : <post_id_5> //ref to post_id_5 in allcomments
                       |__comment_id : <comment_id_5> // ref to comment_id_5 in allcomments

My Goal: To check if the user with uid has commented on the post or not. If that person has, then I he can proceed further else he'll be shown something else on the screen. On trying the following query, I am able to only get the callback when a snapshot exists and not otherwise.

FBDataservice.ds.child("allcomments").queryOrdered(byChild: "post_id").queryEqual(toValue: "post_id_5").observeSingleEvent(of: .ChildAdded) { (snapshot) in
        if let data = snapshot.value as? DataDict {
            let comment = Comment(comId: snapshot.key , comData: data)
            self.checkUserHasResponded(completion: { (hasResponded) in
                if !hasResponded {
                    // Never returns it there is nothng
                    print("You gotta respond first")
                } else {
                    //this part does work
                    print("Welcome to seeing everything")
                }
            })
        }
    }

func checkUserHasResponded(completion: @escaping (Bool) -> ()) {
    FBDataservice.ds.REF_USERS.child(uid).child("activity/comments").queryOrdered(byChild: "post_id").queryEqual(toValue: "post_id_5").observeSingleEvent(of: .value) { (snapshot) in
        snapshot.exists() ? completion(true) : completion(false)
    }
}

I even tried tweaking the architecture this way and query it differently, still nothing work and the program behaves in the same exact way as incase of above.

uid
|
|__activity
     |__comments
            |__post_id_5 : comment_id_5

and ran this query:

func checkUserHasResponded(completion: @escaping (Bool) -> ()) {
    FBDataservice.ds.REF_USERS.child(uid).child("activity/comments").observeSingleEvent(of: .value) { (snapshot) in
        snapshot.hasChild("post_id_5") ? completion(true) : completion(false)
    }
}

I tried changing .childAdded to .value. It gives the same exact result. Tried changing .observeSingleEvent(of:) to .observe() as well. But nothing helps. I am not sure what exactly is wrong. Check plenty of answers here, none helped. What exactly am I over looking. Thanks for the help.

Body:
Use .value instead of .childAdded, that way it the closure is called whether or not the snapshot exists, Just a quick test shows it works.

func checkUserHasResponded() {
    let uid = "uid_0"
    let commentsRef = dbRef.child(uid).child("activity").child("comments")
    commentsRef.queryOrdered(byChild: "post_id")
               .queryEqual(toValue: "post_5")
               .observeSingleEvent(of: .value) { snapshot in
        if snapshot.exists() {
            print("post exists")
        } else {
            print("post not found")
        }
    }
}

If your structure does not contain a post_id child value that exists then the output is

post not found

So this answer applies to the updated question. The code in the closure will not run if the node you're querying for does not exist because the query is using .childAdded

FBDataservice.ds.child("allcomments").queryOrdered(byChild: "post_id")
                                 .queryEqual(toValue: "post_id_5")
                                 .observeSingleEvent(of: .childAdded) { (snapshot) in

If that's changed to .value, it returns and the code in the closure runs if the node exists. Keeping in mind that you'll want to use

snapshot.exists()

with that as it will be nil if it doesn't.


来源: stackexchange

问:
Java program to describe SQL Server Stored Procedure
i am trying to write Java program to describe SQL Server Stored procedure. here i have only input is Stored procedure name, from that i need to get SP parameters and Return types and those lengths..

can anybody helpme out..

答:
get SP name from dbo.sysobjects table

get SP parameters/columns from dbo.syscolumns table.

```<code>use pubs

-- list all stored procedures 列出所有存储过程
select * from dbo.sysobjects where OBJECTPROPERTY(id, N'IsProcedure') = 1

-- get parameters/columns of stored procedure 'dt_checkinobject' 获取存储过程'dt_checkinobject'的所有参数
select *
from
    dbo.syscolumns c
    join dbo.sysobjects o  on c.id=o.id
where
    1=1
    and OBJECTPROPERTY(o.id, N'IsProcedure') = 1
    and.o.name='dt_checkinobject'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
get SP name from dbo.sysobjects table

get SP parameters/columns from dbo.syscolumns table.

use pubs

-- list all stored procedures 列出所有存储过程
select * from dbo.sysobjects where OBJECTPROPERTY(id, N'IsProcedure') = 1

-- get parameters/columns of stored procedure 'dt_checkinobject' 获取存储过程'dt_checkinobject'的所有参数
select *
from
    dbo.syscolumns c
    join dbo.sysobjects o  on c.id=o.id
where
    1=1
    and OBJECTPROPERTY(o.id, N'IsProcedure') = 1
    and.o.name='dt_checkinobject'


问:
Do-While won't repeat itself
I need the user to enter their age, then the program has to calculate how much money they are going to have when their age hit pension. The person is saving 500 or 1000 depending on the situation.

My code won't repeat the if and else statement even though I wrote a Do-While loop. Am I supposed to use a bool-statement? How or where? Or there something else I need to look at?

I've tried using only 'while' but I think I need to use a do-while.

```<code>static void Main(string[] args)
{
    Console.Write("Enter age");
    string str = Console.ReadLine();
    int MyAge = Convert.ToInt32(str);
    int money = 15000;
    {
        do
        {
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.Write("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.Write("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
        }
        while (money > 20000 && MyAge > 65);
    }

    Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
}
</code>```

I expected the program to hit at least 65 but it ends by the age of 26 of I type down that I'm 25 years old. So it doesn't loop.

答:
your while loop runs while the age is above 65.

should be while (money > 20000 && MyAge < 65);

ContentLicense: CC BY-SA 4.0

Title: Do-While won't repeat itself

Body:
I need the user to enter their age, then the program has to calculate how much money they are going to have when their age hit pension. The person is saving 500 or 1000 depending on the situation.

My code won't repeat the if and else statement even though I wrote a Do-While loop. Am I supposed to use a bool-statement? How or where? Or there something else I need to look at?

I've tried using only 'while' but I think I need to use a do-while.

static void Main(string[] args)
{
    Console.Write("Enter age");
    string str = Console.ReadLine();
    int MyAge = Convert.ToInt32(str);
    int money = 15000;
    {
        do
        {
            {
                if (money > 20000 || MyAge < 60)
                {
                    Console.Write("You are saving little");
                    money = money + 500;
                }
                else
                {
                    Console.Write("You are saving a lot");
                    money = money + 1000;
                }
                MyAge++;
            }
        }
        while (money > 20000 && MyAge > 65);
    }

    Console.Write("You are retired by the age of " + MyAge + " and you saved " + money + " dollars.");
}

I expected the program to hit at least 65 but it ends by the age of 26 of I type down that I'm 25 years old. So it doesn't loop.


问:
CSS parent border-radius not being applied during transform scale of child
I'm working on a masonry type layout where I have a container with a column-count property, and then items with rounded corners that hold images. I want the images to give a little transform: scale on hover, but with this combination of css the rounded borders disappear during the transition.

Is there any way around it?

.container {
  column-count: 2;
}

.item {
  width: 100%;
  overflow: hidden;
  border-radius: 10px;
}

img {
  max-width: 100%;
  max-height: 100%;
  transition: all 0.2s;
}

img:hover {
  transform: scale(1.1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="item">
    <img src="https://images.unsplash.com/photo-1558834643-1dacaf774843?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60">
  </div>
</div></code>```

答:
Update: As of late, this seems to be happening again, but only in elements using CSS columns. I've filed it as a Chromium bug here.

Update 2: Filed bug was closed as "Won't fix" as it has already been somewhere between v75.* and v77.0.3833.0, there's currently no available info on what caused it and what fixed it.

By default, transform does not trigger a repaint on the parent node at each animation frame, which is precisely why it's the recommended method of animation, along with opacity (which has the same behavior).

But in your case, you want this repaint after each frame. So you need to apply a cheap transform on the parent as well.

In your case, a simple rotate(0) will suffice, but note there are cases when you want to keep the 3d engine running, in which case a good candidate is rotateZ(0).

Additionally, to make sure there's no space between the bottom of the image and it's wrapper, you could apply display:block to the :

.container {
  column-count: 2;
}

.item {
  width: 100%;
  overflow: hidden;
  border-radius: 10px;
  transform: rotate(0);
}

img {
  max-width: 100%;
  max-height: 100%;
  transition: all 0.2s;
  display: block;
  min-width: 100%;
}

img:hover {
  transform: scale(1.1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="item">
    <img src="https://images.unsplash.com/photo-1558834643-1dacaf774843?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60">
  </div>
</div></code>```

Suggestion: since this doesn't seem to be directly related with using column-count, I suggest removing it from title, to increase its indexing and help others, with the same problem but not using column-count, find it easier.

I'd say it's strictly about parent border-radius not being applied during child item transform.

Body:
Update: As of late, this seems to be happening again, but only in elements using CSS columns. I've filed it as a Chromium bug here.

Update 2: Filed bug was closed as "Won't fix" as it has already been somewhere between v75.* and v77.0.3833.0, there's currently no available info on what caused it and what fixed it.

By default, transform does not trigger a repaint on the parent node at each animation frame, which is precisely why it's the recommended method of animation, along with opacity (which has the same behavior).

But in your case, you want this repaint after each frame. So you need to apply a cheap transform on the parent as well.

In your case, a simple rotate(0) will suffice, but note there are cases when you want to keep the 3d engine running, in which case a good candidate is rotateZ(0).

Additionally, to make sure there's no space between the bottom of the image and it's wrapper, you could apply display:block to the <img>:

.container {
  column-count: 2;
}

.item {
  width: 100%;
  overflow: hidden;
  border-radius: 10px;
  transform: rotate(0);
}

img {
  max-width: 100%;
  max-height: 100%;
  transition: all 0.2s;
  display: block;
  min-width: 100%;
}

img:hover {
  transform: scale(1.1);
}

<div class="container">

  <div class="item">
    <img src="https://images.unsplash.com/photo-1558834643-1dacaf774843?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60">
  </div>
</div>

Suggestion: since this doesn't seem to be directly related with using column-count, I suggest removing it from title, to increase its indexing and help others, with the same problem but not using column-count, find it easier.

I'd say it's strictly about parent border-radius not being applied during child item transform.


问:
Cross Product Confusion
I have a question regarding a tutorial that I have been following on the rotation of the camera's view direction in OpenGL.

Whilst I appreciate that prospective respondents are not the authors of the tutorial, I think that this is likely to be a situation which most intermediate-experienced graphics programmers have encountered before so I will seek the advice of members on this topic.

Here is a link to the video to which I refer: https://www.youtube.com/watch?v=7oNLw9Bct1k.

The goal of the tutorial is to create a basic first person camera which the user controls via movement of the mouse.

Here is the function that handles cursor movement (with some variables/members renamed to conform with my personal conventions):

```<code>glm::vec2 Movement { OldCursorPosition - NewCursorPosition };

// camera rotates on y-axis when mouse moved left/right (orientation is { 0.0F, 1.0F, 0.0F }):

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.x) / 2, MVP.view.orientation)
                   * glm::vec4(MVP.view.direction, 0.0F);

glm::vec3 RotateAround { glm::cross(MVP.view.direction, MVP.view.orientation) };

/* why is camera rotating around cross product of view direction and view orientation
rather than just rotating around x-axis when mouse is moved up/down..? : */

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, RotateAround)
                   * glm::vec4(MVP.view.direction, 0.0F);

OldCursorPosition = NewCursorPosition;
</code>```

What I struggle to understand is why obtaining the cross product is even required. What I would naturally expect is for the camera to rotate around the y-axis when the mouse is moved from left to right, and for the camera to rotate around the x-axis when the mouse is moved up and down. I just can't get my head around why the cross product is even relevant.

From my understanding, the cross product will return a vector which is perpendicular to two other vectors; in this case that is the cross product of the view direction and view orientation, but why would one want a cross product of these two vectors? Shouldn't the camera just rotate on the x-axis for up/down movement and then on the y-axis for left/right movement...? What am I missing/overlooking here?

Finally, when I run the program, I can't visually detect any rotation on the z-axis despite the fact that the rotation scalar 'RotateAround' has a z-value greater than or less than 0 on every call to the the function subsequent to the first (which suggests that the camera should rotate at least partially on the z-axis).

Perhaps this is just due to my lack of intuition, but if I change the line:

```<code>MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, RotateAround)
                   * glm::vec4(MVP.view.direction, 0.0F);
</code>```

To:

```<code>MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, glm::vec3(1.0F, 0.0F, 0.0F))
                   * glm::vec4(MVP.view.direction, 0.0F);
</code>```

So that the rotation only happens on the x-axis rather than partially on the x-axis and partially on the z-axis, and then run the program, I can't really notice much of a difference to the workings of the camera. It feels like maybe there is a difference but I can't articulate what this is.

答:
The problem here is frame of reference.

rather than just rotating around x-axis when mouse is moved up/down..?

What you consider x axis? If that's an axis of global frame of reference or paralleled one, then yes. If that's x axis for  frame of reference, partially constricted by camera's position, then, in general answer is no. Depends on order of rotations are done and if MVP gets saved between movements.

Provided that in code her MVP gets modified by rotation, this means it gets changed. If Camera would make 180 degrees around x axis, the direction of x axis would change to opposite one.

If camera would rotate around y axis (I assume ISO directions for ground vehicle), direction would change as well. If camera would rotate  around global y by 90 degrees, then around global x by 45 degrees, in result you'll see that view had been tilted by 45 degrees sideways.

Order of rotation around constrained frame of reference for ground-bound vehicles (and possibly, for character of classic 3d shooter) is : around y, around x, around z. For aerial vehicles with airplane-like controls it is around z, around x, around y. In orbital space z and x are inverted, if I remember right (z points down).

Title: Cross Product Confusion

Body:
I have a question regarding a tutorial that I have been following on the rotation of the camera's view direction in OpenGL.

Whilst I appreciate that prospective respondents are not the authors of the tutorial, I think that this is likely to be a situation which most intermediate-experienced graphics programmers have encountered before so I will seek the advice of members on this topic.

Here is a link to the video to which I refer: https://www.youtube.com/watch?v=7oNLw9Bct1k.

The goal of the tutorial is to create a basic first person camera which the user controls via movement of the mouse.

Here is the function that handles cursor movement (with some variables/members renamed to conform with my personal conventions):

glm::vec2 Movement { OldCursorPosition - NewCursorPosition };

// camera rotates on y-axis when mouse moved left/right (orientation is { 0.0F, 1.0F, 0.0F }):

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.x) / 2, MVP.view.orientation)
                   * glm::vec4(MVP.view.direction, 0.0F);

glm::vec3 RotateAround { glm::cross(MVP.view.direction, MVP.view.orientation) };

/* why is camera rotating around cross product of view direction and view orientation
rather than just rotating around x-axis when mouse is moved up/down..? : */

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, RotateAround)
                   * glm::vec4(MVP.view.direction, 0.0F);

OldCursorPosition = NewCursorPosition;

What I struggle to understand is why obtaining the cross product is even required. What I would naturally expect is for the camera to rotate around the y-axis when the mouse is moved from left to right, and for the camera to rotate around the x-axis when the mouse is moved up and down. I just can't get my head around why the cross product is even relevant.

From my understanding, the cross product will return a vector which is perpendicular to two other vectors; in this case that is the cross product of the view direction and view orientation, but why would one want a cross product of these two vectors? Shouldn't the camera just rotate on the x-axis for up/down movement and then on the y-axis for left/right movement...? What am I missing/overlooking here?

Finally, when I run the program, I can't visually detect any rotation on the z-axis despite the fact that the rotation scalar 'RotateAround' has a z-value greater than or less than 0 on every call to the the function subsequent to the first (which suggests that the camera should rotate at least partially on the z-axis).

Perhaps this is just due to my lack of intuition, but if I change the line:

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, RotateAround)
                   * glm::vec4(MVP.view.direction, 0.0F);

To:

MVP.view.direction = glm::rotate(glm::mat4(1.0F), glm::radians(Movement.y) / 2, glm::vec3(1.0F, 0.0F, 0.0F))
                   * glm::vec4(MVP.view.direction, 0.0F);

So that the rotation only happens on the x-axis rather than partially on the x-axis and partially on the z-axis, and then run the program, I can't really notice much of a difference to the workings of the camera. It feels like maybe there is a difference but I can't articulate what this is.


问:
Not able to understand what this C function does
I have seen this piece of code several times but am unable to understand what it does

```<code>inline char nc()
{
    static char buf[100000], *L = buf, *R = buf;
    return L == R && (R = (L = buf) + fread(buf, 1, 100000, stdin), L == R) ? EOF : *L++;
}
</code>```

The condition L==R should always be true , right? since both the pointers point to the same variable. I cant understand what the second part of the condition checks. Could someone please help me out?

答:
All the variables are declared as static which means that they keep their value from the previous function call. The initializations =buf are only run the first time the function is called. It's basically the same thing as if you declared those variables as globals and initialized them before the first function call. Of course with the difference that globals can be accessed from anywhere in the code.

Let's disassemble the second line a bit. It can be rewritten like this:

```<code>char ret;
if(L == R &&
   R = (L = buf) + fread(buf, 1, 100000, stdin), L == R) {
       ret = EOF;
} else {
    ret=*L; // Return the character read
    L++;    // Advance to next character in the buffer
}
return ret;
</code>```

A bit clearer, but still a bit clunky. The second condition R = (L = buf) + fread(buf, 1, 100000, stdin), L == R) is not very clear. It can be rewritten like this:

```<code>L = buf;
int noCharactersRead = fread(buf, 1, 100000, stdin);
R = L + noCharactersRead;
if(L == R)  // If no characters have been read
    ret = EOF;
</code>```

So the complete refactored code (with some extra refactoring) will be

```<code>char nc()
{
#define BUFSIZE 100000
    static char buf[BUFSIZE], *L = buf, *R = buf;
    if(L == R) { // If buffer is empty
        L = buf; // Reset L to beginning of buffer

        // Read next character from stdin, put it in the buffer
        // and check if read was successful
        int noCharactersRead = fread(buf, 1, BUFSIZE, stdin);

        // Return EOF on read failure
        if(noCharactersRead == 0)
            return EOF;

        // Advance R one step if a character was read
        R = L + noCharactersRead;

    }

    // If the buffer was not empty, or if the buffer was empty and we
    // successfully read a new character into the buffer, return the next
    // character in the buffer and advance L
    return *L++;
}
</code>```

I removed the inline because the function contains static variables. An alternative would be to declare the function as static inline.

It is essentially a buffered version of getchar() function, but written in a very unreadable way. Do also note that it has very little protection for buffer overflow. It basically relies on the buffer being big enough to not cause any issues. A way to solve this would be changing the call to fread to fread(buf, 1, BUFSIZE - (R-L), stdin)

Body:
I have seen this piece of code several times but am unable to understand what it does

inline char nc()
{
    static char buf[100000], *L = buf, *R = buf;
    return L == R && (R = (L = buf) + fread(buf, 1, 100000, stdin), L == R) ? EOF : *L++;
}

The condition L==R should always be true , right? since both the pointers point to the same variable. I cant understand what the second part of the condition checks. Could someone please help me out?

Body:
All the variables are declared as static which means that they keep their value from the previous function call. The initializations =buf are only run the first time the function is called. It's basically the same thing as if you declared those variables as globals and initialized them before the first function call. Of course with the difference that globals can be accessed from anywhere in the code.

Let's disassemble the second line a bit. It can be rewritten like this:

char ret;
if(L == R &&
   R = (L = buf) + fread(buf, 1, 100000, stdin), L == R) {
       ret = EOF;
} else {
    ret=*L; // Return the character read
    L++;    // Advance to next character in the buffer
}
return ret;

A bit clearer, but still a bit clunky. The second condition R = (L = buf) + fread(buf, 1, 100000, stdin), L == R) is not very clear. It can be rewritten like this:

L = buf;
int noCharactersRead = fread(buf, 1, 100000, stdin);
R = L + noCharactersRead;
if(L == R)  // If no characters have been read
    ret = EOF;

So the complete refactored code (with some extra refactoring) will be

char nc()
{
#define BUFSIZE 100000
    static char buf[BUFSIZE], *L = buf, *R = buf;
    if(L == R) { // If buffer is empty
        L = buf; // Reset L to beginning of buffer

        // Read next character from stdin, put it in the buffer
        // and check if read was successful
        int noCharactersRead = fread(buf, 1, BUFSIZE, stdin);

        // Return EOF on read failure
        if(noCharactersRead == 0)
            return EOF;

        // Advance R one step if a character was read
        R = L + noCharactersRead;

    }

    // If the buffer was not empty, or if the buffer was empty and we
    // successfully read a new character into the buffer, return the next
    // character in the buffer and advance L
    return *L++;
}

I removed the inline because the function contains static variables. An alternative would be to declare the function as static inline.

It is essentially a buffered version of getchar() function, but written in a very unreadable way. Do also note that it has very little protection for buffer overflow. It basically relies on the buffer being big enough to not cause any issues. A way to solve this would be changing the call to fread to fread(buf, 1, BUFSIZE - (R-L), stdin)


问:
Docker Container Exits Immediately Upon Start
I am trying to run the new Elasticsearch 6.0 docker container on an Amazon Linux AMI (the standard one). I previously had 5.6 running with no issues on a different instance, but my container is immediately crashing when I start it up.

Here's the command I'm using: docker run -it -p 9200:9200 -p 9300:9300 -d docker.elastic.co/elasticsearch/elasticsearch:6.0.0

I referenced this post on Docker crashing, but still seemed to run into the same issues: Why docker container exits immediately

I ran docker logs  and get the following response:

```<code>[2017-11-28T19:00:30,946][INFO ][o.e.n.Node               ] [] initializing ...
[2017-11-28T19:00:31,013][INFO ][o.e.e.NodeEnvironment    ] [eEXrI6m] using [1] data paths, mounts [[/ (overlay)]], net usable_space [4.5gb], net total_space [7.7gb], types [overlay]
[2017-11-28T19:00:31,014][INFO ][o.e.e.NodeEnvironment    ] [eEXrI6m] heap size [989.8mb], compressed ordinary object pointers [true]
[2017-11-28T19:00:31,015][INFO ][o.e.n.Node               ] node name [eEXrI6m] derived from node ID [eEXrI6mGTci22tpTNMMh8w]; set [node.name] to override
[2017-11-28T19:00:31,015][INFO ][o.e.n.Node               ] version[6.0.0], pid[1], build[8f0685b/2017-11-10T18:41:22.859Z], OS[Linux/4.9.62-21.56.amzn1.x86_64/amd64], JVM[Oracle Corporation/OpenJDK 64-Bit Server VM/1.8.0_151/25.151-b12]
[2017-11-28T19:00:31,015][INFO ][o.e.n.Node               ] JVM arguments [-Xms1g, -Xmx1g, -XX:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=75, -XX:+UseCMSInitiatingOccupancyOnly, -XX:+AlwaysPreTouch, -Xss1m, -Djava.awt.headless=true, -Dfile.encoding=UTF-8, -Djna.nosys=true, -XX:-OmitStackTraceInFastThrow, -Dio.netty.noUnsafe=true, -Dio.netty.noKeySetOptimization=true, -Dio.netty.recycler.maxCapacityPerThread=0, -Dlog4j.shutdownHookEnabled=false, -Dlog4j2.disable.jmx=true, -XX:+HeapDumpOnOutOfMemoryError, -Des.cgroups.hierarchy.override=/, -Des.path.home=/usr/share/elasticsearch, -Des.path.conf=/usr/share/elasticsearch/config]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [aggs-matrix-stats]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [analysis-common]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [ingest-common]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [lang-expression]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [lang-mustache]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [lang-painless]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [parent-join]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [percolator]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [reindex]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [repository-url]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [transport-netty4]
[2017-11-28T19:00:32,284][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [tribe]
[2017-11-28T19:00:32,284][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded plugin [ingest-geoip]
[2017-11-28T19:00:32,284][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded plugin [ingest-user-agent]
[2017-11-28T19:00:32,284][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded plugin [x-pack]
[2017-11-28T19:00:34,795][INFO ][o.e.x.m.j.p.l.CppLogMessageHandler] [controller/120] [Main.cc@128] controller (64 bit): Version 6.0.0 (Build 8e6ab35cf803a2) Copyright (c) 2017 Elasticsearch BV
[2017-11-28T19:00:34,834][INFO ][o.e.d.DiscoveryModule    ] [eEXrI6m] using discovery type [zen]
[2017-11-28T19:00:35,513][INFO ][o.e.n.Node               ] initialized
[2017-11-28T19:00:35,513][INFO ][o.e.n.Node               ] [eEXrI6m] starting ...
[2017-11-28T19:00:35,648][INFO ][o.e.t.TransportService   ] [eEXrI6m] publish_address {xxx.xx.x.x:9300}, bound_addresses {0.0.0.0:9300}
[2017-11-28T19:00:35,664][INFO ][o.e.b.BootstrapChecks    ] [eEXrI6m] bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks

ERROR: [2] bootstrap checks failed
[1]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536]
[2]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
[2017-11-28T19:00:35,675][INFO ][o.e.n.Node               ] [eEXrI6m] stopping ...
[2017-11-28T19:00:35,734][INFO ][o.e.n.Node               ] [eEXrI6m] stopped
[2017-11-28T19:00:35,734][INFO ][o.e.n.Node               ] [eEXrI6m] closing ...
[2017-11-28T19:00:35,745][INFO ][o.e.n.Node               ] [eEXrI6m] closed
</code>```

答:
You can try adding ulimit section:

```<code>services:
  elastic:
      image: elasticsearch
      ulimits:
          nofile:
              soft: 65536
              hard: 65536
</code>```

or change the limit in

```<code>/etc/security/limits.conf
</code>```

you can see the actual limits with

```<code>cat /proc/<pid>/limits
</code>```

when the process is running.

Body:
I am trying to run the new Elasticsearch 6.0 docker container on an Amazon Linux AMI (the standard one). I previously had 5.6 running with no issues on a different instance, but my container is immediately crashing when I start it up.

Here's the command I'm using: docker run -it -p 9200:9200 -p 9300:9300 -d docker.elastic.co/elasticsearch/elasticsearch:6.0.0

I referenced this post on Docker crashing, but still seemed to run into the same issues: Why docker container exits immediately

I ran docker logs  and get the following response:

[2017-11-28T19:00:30,946][INFO ][o.e.n.Node               ] [] initializing ...
[2017-11-28T19:00:31,013][INFO ][o.e.e.NodeEnvironment    ] [eEXrI6m] using [1] data paths, mounts [[/ (overlay)]], net usable_space [4.5gb], net total_space [7.7gb], types [overlay]
[2017-11-28T19:00:31,014][INFO ][o.e.e.NodeEnvironment    ] [eEXrI6m] heap size [989.8mb], compressed ordinary object pointers [true]
[2017-11-28T19:00:31,015][INFO ][o.e.n.Node               ] node name [eEXrI6m] derived from node ID [eEXrI6mGTci22tpTNMMh8w]; set [node.name] to override
[2017-11-28T19:00:31,015][INFO ][o.e.n.Node               ] version[6.0.0], pid[1], build[8f0685b/2017-11-10T18:41:22.859Z], OS[Linux/4.9.62-21.56.amzn1.x86_64/amd64], JVM[Oracle Corporation/OpenJDK 64-Bit Server VM/1.8.0_151/25.151-b12]
[2017-11-28T19:00:31,015][INFO ][o.e.n.Node               ] JVM arguments [-Xms1g, -Xmx1g, -XX:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=75, -XX:+UseCMSInitiatingOccupancyOnly, -XX:+AlwaysPreTouch, -Xss1m, -Djava.awt.headless=true, -Dfile.encoding=UTF-8, -Djna.nosys=true, -XX:-OmitStackTraceInFastThrow, -Dio.netty.noUnsafe=true, -Dio.netty.noKeySetOptimization=true, -Dio.netty.recycler.maxCapacityPerThread=0, -Dlog4j.shutdownHookEnabled=false, -Dlog4j2.disable.jmx=true, -XX:+HeapDumpOnOutOfMemoryError, -Des.cgroups.hierarchy.override=/, -Des.path.home=/usr/share/elasticsearch, -Des.path.conf=/usr/share/elasticsearch/config]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [aggs-matrix-stats]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [analysis-common]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [ingest-common]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [lang-expression]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [lang-mustache]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [lang-painless]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [parent-join]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [percolator]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [reindex]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [repository-url]
[2017-11-28T19:00:32,283][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [transport-netty4]
[2017-11-28T19:00:32,284][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded module [tribe]
[2017-11-28T19:00:32,284][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded plugin [ingest-geoip]
[2017-11-28T19:00:32,284][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded plugin [ingest-user-agent]
[2017-11-28T19:00:32,284][INFO ][o.e.p.PluginsService     ] [eEXrI6m] loaded plugin [x-pack]
[2017-11-28T19:00:34,795][INFO ][o.e.x.m.j.p.l.CppLogMessageHandler] [controller/120] [Main.cc@128] controller (64 bit): Version 6.0.0 (Build 8e6ab35cf803a2) Copyright (c) 2017 Elasticsearch BV
[2017-11-28T19:00:34,834][INFO ][o.e.d.DiscoveryModule    ] [eEXrI6m] using discovery type [zen]
[2017-11-28T19:00:35,513][INFO ][o.e.n.Node               ] initialized
[2017-11-28T19:00:35,513][INFO ][o.e.n.Node               ] [eEXrI6m] starting ...
[2017-11-28T19:00:35,648][INFO ][o.e.t.TransportService   ] [eEXrI6m] publish_address {xxx.xx.x.x:9300}, bound_addresses {0.0.0.0:9300}
[2017-11-28T19:00:35,664][INFO ][o.e.b.BootstrapChecks    ] [eEXrI6m] bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks

ERROR: [2] bootstrap checks failed
[1]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536]
[2]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
[2017-11-28T19:00:35,675][INFO ][o.e.n.Node               ] [eEXrI6m] stopping ...
[2017-11-28T19:00:35,734][INFO ][o.e.n.Node               ] [eEXrI6m] stopped
[2017-11-28T19:00:35,734][INFO ][o.e.n.Node               ] [eEXrI6m] closing ...
[2017-11-28T19:00:35,745][INFO ][o.e.n.Node               ] [eEXrI6m] closed

Body:
You can try adding ulimit section:

services:
  elastic:
      image: elasticsearch
      ulimits:
          nofile:
              soft: 65536
              hard: 65536

or change the limit in

/etc/security/limits.conf

you can see the actual limits with

cat /proc/<pid>/limits

when the process is running.


问:
Slow navigation when inheriting from a base form
I am using a base form that has a menu on it so that I don't have to re-do the code for the whole application.

Essentially this form is called StudentBase.cs

Then I have another form called StudentProfile that inherits from StudentBase

```<code>    public partial class StudentProfile : StudentBase
    {
       public string selectedPage;
    }
</code>```

This then inherits the menu that is in StudentBase and I don't have to re-do the menu.

On the menu, there are buttons for the individual forms.

So let's say I press on Student Profile I use this to navigate:

```<code>    private void btnProfile_Click(object sender, EventArgs e)
    {
          //I don't want the page to reload if it is the current page
          if (selectedPage != "Profile")
          {
             StudentProfile profile = new StudentProfile();
             profile.Show();
             this.Hide();
          }
    }
</code>```

Doing this produces a very laggy result, as well as it looks very glitchy

I override selectedPage in the child forms so in the case of StudentProfile I use:

```<code>   private void StudentProfile_Load(object sender, EventArgs e)
    {
        selectedPage = "Profile";
    }
</code>```

I have tested this on my friend's code and his navigation works without lag or glitch. He didn't do the inheritance on the form

答:
So, I couldn't properly figure out how to use the UserControls. I put it on my to-do list so I can try that at the end of the project if I still have time left.

But, I figured out why it was taking so long to move from one navigation to the other.

I was selecting the student details in the base form using

```<code>Student student = new Student();
Student studentDetailsFound = student.GetStudent(2);
</code>```

I never stopped it from selecting from the database every time it navigates to a new form, thus, the two-second delay every time.
So there were two options to fix this: Static variables or caching.

I used the latter and now it switches to the pages rather fast.

By adding a transition on the form, it made it a lot smoother on the eyes.

Also note: if you are getting the data like I am you should first wait for the designing of the form to finish. So put the GetStudent part into this if:

```<code>if (this.Site == null || !this.Site.DesignMode)
{
    studentDetailsFound = GetStudent();
}
</code>```

Body:
I am using a base form that has a menu on it so that I don't have to re-do the code for the whole application.

Essentially this form is called StudentBase.cs

Then I have another form called StudentProfile that inherits from StudentBase

    public partial class StudentProfile : StudentBase
    {
       public string selectedPage;
    }

This then inherits the menu that is in StudentBase and I don't have to re-do the menu.

On the menu, there are buttons for the individual forms.

So let's say I press on Student Profile I use this to navigate:

    private void btnProfile_Click(object sender, EventArgs e)
    {
          //I don't want the page to reload if it is the current page
          if (selectedPage != "Profile")
          {
             StudentProfile profile = new StudentProfile();
             profile.Show();
             this.Hide();
          }
    }

Doing this produces a very laggy result, as well as it looks very glitchy

I override selectedPage in the child forms so in the case of StudentProfile I use:

   private void StudentProfile_Load(object sender, EventArgs e)
    {
        selectedPage = "Profile";
    }

I have tested this on my friend's code and his navigation works without lag or glitch. He didn't do the inheritance on the form

Body:
So, I couldn't properly figure out how to use the UserControls. I put it on my to-do list so I can try that at the end of the project if I still have time left.

But, I figured out why it was taking so long to move from one navigation to the other.

I was selecting the student details in the base form using

Student student = new Student();
Student studentDetailsFound = student.GetStudent(2);

I never stopped it from selecting from the database every time it navigates to a new form, thus, the two-second delay every time.
So there were two options to fix this: Static variables or caching.

I used the latter and now it switches to the pages rather fast.

By adding a transition on the form, it made it a lot smoother on the eyes.

Also note: if you are getting the data like I am you should first wait for the designing of the form to finish. So put the GetStudent part into this if:

if (this.Site == null || !this.Site.DesignMode)
{
    studentDetailsFound = GetStudent();
}


问:
How to use different images as form submit button which passes different values to the php page?
I made a html and a php page. I put 3 images in html page showing different genre of movies- horror, fantasy, romance. I want the images to work as form submit button and should get redirected to the php page and the php page should get the genre of the image.

What I already tried- I tried lot of different things but nothing worked.
And I wonder how php page will take different inputs from different images using $_POST method.

Expected output-
Suppose if user clicked on image of genre 'horror', then in php page value of $genre should be Horror.

答:
You can use an  tag inside a <button> element.

```<code><form method="post">
<button name="genre" value="horror" type="submit"><img src="./img/horror.jpg"></button>
<button name="genre" value="comedy" type="submit"><img src="./img/comedy.jpg"></button>
</form>
</code>```

You can access the value of the submit button in your PHP using $_POST['genre'] (or whatever the name attribute of your buttons is)

Body:
You can use an <img> tag inside a <button> element.

<form method="post">
<button name="genre" value="horror" type="submit"><img src="./img/horror.jpg"></button>
<button name="genre" value="comedy" type="submit"><img src="./img/comedy.jpg"></button>
</form>

You can access the value of the submit button in your PHP using $_POST['genre'] (or whatever the name attribute of your buttons is)


问:
Only show SQL results from users with exact three entries
```<code>SELECT *
FROM PlanData
WHERE GeneralEventCode = 'VM'
  AND AirlineCode = 'LH'
  AND DateStart > '2019-05-01'
  AND UserHomeBaseAirportCode = 'FRA'
</code>```

In this table I have also the field UserId. I would like to get only results, if a UserId has exact 3 entries in that table.

Thanks for the help

答:
You can use window functions.  The following assumes that you mean three rows that match your conditions:

```<code>SELECT pd.*
FROM (SELECT pd.*,
             COUNT(*) OVER (PARTITION BY userid) as cnt
      FROM PlanData pd
      WHERE GeneralEventCode = 'VM' and
            AirlineCode='LH' and
            DateStart > '2019-05-01' and
            UserHomeBaseAirportCode = 'FRA'
    ) pd
WHERE cnt = 3;
</code>```

If you mean three rows of any sort, then:

```<code>SELECT pd.*
FROM (SELECT pd.*,
             COUNT(*) OVER (PARTITION BY userid) as cnt
      FROM PlanData pd
     ) pd
WHERE GeneralEventCode = 'VM' and
      AirlineCode='LH' and
      DateStart > '2019-05-01' and
      UserHomeBaseAirportCode = 'FRA' and
      cnt = 3;
</code>```

Body:
SELECT *
FROM PlanData
WHERE GeneralEventCode = 'VM'
  AND AirlineCode = 'LH'
  AND DateStart > '2019-05-01'
  AND UserHomeBaseAirportCode = 'FRA'

In this table I have also the field UserId. I would like to get only results, if a UserId has exact 3 entries in that table.

Thanks for the help

Body:
You can use window functions.  The following assumes that you mean three rows that match your conditions:

SELECT pd.*
FROM (SELECT pd.*,
             COUNT(*) OVER (PARTITION BY userid) as cnt
      FROM PlanData pd
      WHERE GeneralEventCode = 'VM' and
            AirlineCode='LH' and
            DateStart > '2019-05-01' and
            UserHomeBaseAirportCode = 'FRA'
    ) pd
WHERE cnt = 3;

If you mean three rows of any sort, then:

SELECT pd.*
FROM (SELECT pd.*,
             COUNT(*) OVER (PARTITION BY userid) as cnt
      FROM PlanData pd
     ) pd
WHERE GeneralEventCode = 'VM' and
      AirlineCode='LH' and
      DateStart > '2019-05-01' and
      UserHomeBaseAirportCode = 'FRA' and
      cnt = 3;


问:
How to pass value in input tag?
normally, i am trying passing value in p,div and pre tag and values are show in above tag now i am passing country name in input tag. but value are not show in input tag. Here is my code:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Get browser and ip address </title>
</head>
<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>
<input type="text" name="country_name" id="country_name" value="">
<p id="country_name"></p>
<div id="ip"></div>
<div id="city"></div>
<pre id="response">```

```

Thanks.

答:
input fields take value attribute. Try changing this line:
$("#country_name").val(response.country_name);

Also, like @Khaleb said, element IDs must be unique.

Title: How to pass value in input tag?

Body:
normally, i am trying passing value in p,div and pre tag and values are show in above tag now i am passing country name in input tag. but value are not show in input tag. Here is my code:

<!DOCTYPE html>

    <title>Get browser and ip address </title>

ipdata.co - IP geolocation API

<input type="text" name="country_name" id="country_name" value="">

Thanks.


问:
automaticallyMergesChangesFromParent doesn't do anything
I was watching a WWDC 2016 (What's new in Core Data) video about some "new" changes and at some point it's said that this new property automaticallyMergesChangesFromParent is supposed to automatically merge the changes from the parent on the child context.

I created a simple test case:

```<code>CustomObject *customObject = [[CustomObject alloc] initWithContext:self.persistentContainer.viewContext];
customObject.name = @"TEST";
customObject.customID = 2252;
self.persistentContainer.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;

NSManagedObjectContext *firstContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
firstContext.parentContext = self.persistentContainer.viewContext;
firstContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
firstContext.automaticallyMergesChangesFromParent = YES;

CustomObject *contextObj = [firstContext objectWithID:customObject.objectID];
NSLog(@"NAME [%@]", contextObj.name);
customObject.name = @"JO";
[self.persistentContainer.viewContext save:NULL];
NSLog(@"NAME [%@]", contextObj.name);
</code>```

The output is:

```<code> NAME [TEST]
 NAME [TEST]
</code>```

I was hoping it would be:

```<code>NAME [TEST]
NAME [JO]
</code>```

if I use a [firstContext refreshAllObjects]; it will work as I expect, but it makes not difference if automaticallyMergesChangesFromParent is set to YES or NO.

Am I missing something on how this is supposed to work? The documentation doesn't help much.

Thanks.

答:
When you set automaticallyMergesChangesFromParent = YES; and then make save in your parent context CoreData automatically calls mergeChangesFromContextDidSaveNotification: on your child context by dispatching this block on the child queue (by calling performBlock: as usual).
As soon as both your contexts work on the main queue you'll see changes only on the next main loop

Try

```<code>CustomObject *contextObj = [firstContext objectWithID:customObject.objectID];
NSLog(@"NAME [%@]", contextObj.name);
customObject.name = @"JO";
[self.persistentContainer.viewContext save:NULL];
dispatch_async(dispatch_get_main_queue(), ^{
   NSLog(@"NAME [%@]", contextObj.name);
});

</code>```

Body:
I was watching a WWDC 2016 (What's new in Core Data) video about some "new" changes and at some point it's said that this new property automaticallyMergesChangesFromParent is supposed to automatically merge the changes from the parent on the child context.

I created a simple test case:

CustomObject *customObject = [[CustomObject alloc] initWithContext:self.persistentContainer.viewContext];
customObject.name = @"TEST";
customObject.customID = 2252;
self.persistentContainer.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;

NSManagedObjectContext *firstContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
firstContext.parentContext = self.persistentContainer.viewContext;
firstContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy;
firstContext.automaticallyMergesChangesFromParent = YES;

CustomObject *contextObj = [firstContext objectWithID:customObject.objectID];
NSLog(@"NAME [%@]", contextObj.name);
customObject.name = @"JO";
[self.persistentContainer.viewContext save:NULL];
NSLog(@"NAME [%@]", contextObj.name);

The output is:

 NAME [TEST]
 NAME [TEST]

I was hoping it would be:

NAME [TEST]
NAME [JO]

if I use a [firstContext refreshAllObjects]; it will work as I expect, but it makes not difference if automaticallyMergesChangesFromParent is set to YES or NO.

Am I missing something on how this is supposed to work? The documentation doesn't help much.

Thanks.

Body:
When you set automaticallyMergesChangesFromParent = YES; and then make save in your parent context CoreData automatically calls mergeChangesFromContextDidSaveNotification: on your child context by dispatching this block on the child queue (by calling performBlock: as usual).
As soon as both your contexts work on the main queue you'll see changes only on the next main loop

Try

CustomObject *contextObj = [firstContext objectWithID:customObject.objectID];
NSLog(@"NAME [%@]", contextObj.name);
customObject.name = @"JO";
[self.persistentContainer.viewContext save:NULL];
dispatch_async(dispatch_get_main_queue(), ^{
   NSLog(@"NAME [%@]", contextObj.name);
});


问:
Language switcher with PHP with a two dimensional array in short syntax
I like to create a language switcher for a website in three languages.
It would be nice to use a multidimensional array in the shorthand syntax.

Unfortunately I'm completely new to PHP, therefor it is difficult to find a script, which I only have to edit for my purpose.

The situation, which is a standard usecase I suppose:
There's a website with 3 languages (for the example I use 3 different pages for each lanuage).

```<code>https://example.tld/de/
https://example.tld/en/
https://example.tld/fr/

https://example.tld/de/zimmer
https://example.tld/en/rooms
https://example.tld/fr/chambres

https://example.tld/de/seminarbereich
https://example.tld/en/seminar-area
https://example.tld/fr/zone-seminaires
</code>```

Can I use the following two dimensional array to solve the task?

```<code>$myarray = [
['de', 'en', 'fr'], //language and as well the first part of the url
['Sprachumschalter', 'Language Switcher', 'Sélecteur de langue'], //aria-label
['Diese Seite auf Deutsch', 'This page in English', 'Cette page en français'], //title
['', '', ''], // page 1, start page of each language
['zimmer', 'rooms', 'chambres'], // page 2
['seminarbereich', 'seminar-area', 'zone-seminaires'] // page 3
]
</code>```

The result in form of HTML5 on each page should be - here in form of the page "rooms":

```<code><nav aria-label="Sprachumschalter">
    <ol>
        <li class="aktiv"><a href="/de/zimmer" lang="de" title="Diese Seite auf Deutsch">de</a></li>
        <li><a href="/en/rooms" lang="en" title="This page in English">en</a></li>
        <li><a href="/fr/chambres" lang="fr" title="Cette page en Français">fr</a></li>
    </ol>
</nav>
</code>```

Can you give me please a hint, where I can find a script which uses a comparable two dimenisional array for such a purpose?

I suppose I need a script which "asks"

"if the first of the url is 'de' than go to the array to position '...' and pick the appropriate content".

If there's someone who likes to help me, I would appreciate it. Thanks in advance.

答: You could use gettext instead of multi dimentional arrays</p>

Body:
I like to create a language switcher for a website in three languages.
It would be nice to use a multidimensional array in the shorthand syntax.

Unfortunately I'm completely new to PHP, therefor it is difficult to find a script, which I only have to edit for my purpose.

The situation, which is a standard usecase I suppose:
There's a website with 3 languages (for the example I use 3 different pages for each lanuage).

https://example.tld/de/
https://example.tld/en/
https://example.tld/fr/

https://example.tld/de/zimmer
https://example.tld/en/rooms
https://example.tld/fr/chambres

https://example.tld/de/seminarbereich
https://example.tld/en/seminar-area
https://example.tld/fr/zone-seminaires

Can I use the following two dimensional array to solve the task?

$myarray = [
['de', 'en', 'fr'], //language and as well the first part of the url
['Sprachumschalter', 'Language Switcher', 'Sélecteur de langue'], //aria-label
['Diese Seite auf Deutsch', 'This page in English', 'Cette page en français'], //title
['', '', ''], // page 1, start page of each language
['zimmer', 'rooms', 'chambres'], // page 2
['seminarbereich', 'seminar-area', 'zone-seminaires'] // page 3
]

The result in form of HTML5 on each page should be - here in form of the page "rooms":

de

en

fr

Can you give me please a hint, where I can find a script which uses a comparable two dimenisional array for such a purpose?

I suppose I need a script which "asks"

"if the first of the url is 'de' than go to the array to position '...' and pick the appropriate content".

If there's someone who likes to help me, I would appreciate it. Thanks in advance.


问:
Apache-poi decimal formatting is being applied only after selection
Could you please suggest on next case?

I`ve set up dataformat and cell type ("#,###.00", NUMERIC)
(I want thounsand separator plus two decimal numbers)

It works as I expected but to have formatted cells I need to select them first
Before selection data looks not formatted

In other words I have to select cell so that it is formatted, otherwise it stays without any formatting

```<code>CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.RIGHT);
style.setLocked(locked);
style.setDataFormat(workbook.createDataFormat().getFormat("#,###.00"));

cell.setCellStyle(style);
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(<big decimal value>.toString());
</code>```

答:
Simply do not set cell value as string if you need a numeric cell value. If you set cell value as String, then the cell type also will be string. This is independent of setting CellType before setting cell value. While setting a String cell value the type changes to string always.

See API documentation which shows that Cell.setCellType is deprecated and what Cell.setCellValue methods are possible.

You needs setting a double cell value if cell shall have numeric content.

Example:

```<code>import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.math.BigDecimal;
import java.util.Random;

class CreateExcelCellNumberFormat {

 public static void main(String[] args) throws Exception {

  try (Workbook workbook = new XSSFWorkbook();
       FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {

   CellStyle style = workbook.createCellStyle();
   style.setDataFormat(workbook.createDataFormat().getFormat("#,###.00"));

   Sheet sheet = workbook.createSheet();

   for (int r = 0; r < 10; r++) {
    Cell cell = sheet.createRow(r).createCell(0);
    cell.setCellStyle(style);

    BigDecimal bigDecimal = new BigDecimal(new Random().nextDouble() * 10000000000000d);
    cell.setCellValue(bigDecimal.doubleValue());

   }

   sheet.setColumnWidth(0, 25 * 256);

   workbook.write(fileout);
  }
 }
}
</code>```

Body:
Could you please suggest on next case?

I`ve set up dataformat and cell type ("#,###.00", NUMERIC)
(I want thounsand separator plus two decimal numbers)

It works as I expected but to have formatted cells I need to select them first
Before selection data looks not formatted

In other words I have to select cell so that it is formatted, otherwise it stays without any formatting

CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.RIGHT);
style.setLocked(locked);
style.setDataFormat(workbook.createDataFormat().getFormat("#,###.00"));

cell.setCellStyle(style);
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(<big decimal value>.toString());

Body:
Simply do not set cell value as string if you need a numeric cell value. If you set cell value as String, then the cell type also will be string. This is independent of setting CellType before setting cell value. While setting a String cell value the type changes to string always.

See API documentation which shows that Cell.setCellType is deprecated and what Cell.setCellValue methods are possible.

You needs setting a double cell value if cell shall have numeric content.

Example:

import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.math.BigDecimal;
import java.util.Random;

class CreateExcelCellNumberFormat {

 public static void main(String[] args) throws Exception {

  try (Workbook workbook = new XSSFWorkbook();
       FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {

   CellStyle style = workbook.createCellStyle();
   style.setDataFormat(workbook.createDataFormat().getFormat("#,###.00"));

   Sheet sheet = workbook.createSheet();

   for (int r = 0; r < 10; r++) {
    Cell cell = sheet.createRow(r).createCell(0);
    cell.setCellStyle(style);

    BigDecimal bigDecimal = new BigDecimal(new Random().nextDouble() * 10000000000000d);
    cell.setCellValue(bigDecimal.doubleValue());

   }

   sheet.setColumnWidth(0, 25 * 256);

   workbook.write(fileout);
  }
 }
}


问:
How to update a dropdown onchange of another dropdown and save it using AJAX and JavaScript
I have never done an AJAX call before...

I have a page where there are two dropdown fields, one of who to send a transcript to and the other is the type of hearing. I added onchange functionality to the type of hearing to make the send transcript to field change, depending on what was selected.

The problem is that the person could choose another option before the job is saved, so if you read the value of the send to dropdown, it doesn't change in code, even though the display changes. I was thinking that maybe I need to do an AJAX call to save the dropdown before I read it, but I'm stuck. I've never used AJAX before.

There are a lot of examples of reading from a file or reading to a file and using jQuery, but I need to use JavaScript and write to a database.

This is the field with the onchange event:

```<code> echo form_label('Type:', 'hearingtype') . form_dropdown('hearingtype[r]', $hearingtypes, isset($job['hearingtype']) ? $job['hearingtype'] : '', array('onchange' => 'changeEmail($(this));')) . '<br />';
</code>```

This is the field that should change:

```<code>echo form_label('Send transcript to:', 'emailkey') .
            form_dropdown('emailkey', $operationsemails, isset($job) ? $job['emailkey'] : '', 'id="emailkey"') . '<br />';
</code>```

And this is the JavaScript:

```<code><script type="text/javascript">
    function changeEmail(name) {
        let hearingType = name.value.toString();
        let emailkey = document.getElementById('emailkey').innerHTML;
        let xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                if (hearingType == 16) {
                    if (emailkey.indexOf('selected="selected">John Doe') > 0) {
                        // All correct
                    } else {
                        // Change and flash green
                        document.getElementById('emailkey').value = '1';
                        document.getElementById('emailkey').setStyle('background-color', 'lightgreen');
                        setTimeout(function() {
                            document.getElementById('emailkey').setStyle('background-color', 'white');
                        }, 250);
                     }
                   } else {
                      if (emailkey.indexOf('selected="selected">Lisa Black') > 0) {
                          // Correct, do nothing.
                      } else {
                          // Change and flash green
                          document.getElementById('emailkey').value = '0';
                                document.getElementById('emailkey').setStyle('background-color', 'lightgreen');
                                setTimeout(function() {
                                    document.getElementById('emailkey').setStyle('background-color', 'white');
                                }, 250);
                            }
                        }
                    }
                };
                xhttp.open('GET', 'test.txt', true);
                xhttp.send();
            }
        </script>
</code>```

The test.txt is obviously not correct. I am stumped as to what to put in there to write to the database. Would I put a call to a function ($this->functioName)? Everything else works perfectly.

I don't know if there's another way to read what's displayed on the webpage, not what's in the code...

答:
If anyone is interested, I ended up doing the following and got it to work:

```<code> echo form_label('Type:', 'hearingtype') . form_dropdown('hearingtype[r]', $hearingtypes, isset($job['hearingtype']) ? $job['hearingtype'] : '', array('onchange' => 'changeEmail($(this));')) . '<br />';
</code>```

And:

```<code>        <script type="text/javascript">
            function changeEmail(name) {
                let hearingType = name.value.toString();
                if (hearingType === '16') {
                    let x = document.getElementById('emailkey');
                    for (let i = 0; i < x.options.length; i++) {
                        let optionValue = x.options[i].innerHTML;
                        if (optionValue.includes('Janet') > 0) {
                            x.options[i].selected = 'selected';
                            document.getElementById('emailkey').setStyle('background-color', 'lightgreen');
                            setTimeout(function() {
                                document.getElementById('emailkey').setStyle('background-color', 'white');
                            }, 250);
                        }
                    }
                } else {
                    let x = document.getElementById('emailkey');
                    for (let i = 0; i < x.options.length; i++) {
                        let optionValue = x.options[i].innerHTML;
                        if (optionValue.includes('Michelle') > 0) {
                            x.options[i].selected = 'selected';
                            document.getElementById('emailkey').setStyle('background-color', 'lightgreen');
                            setTimeout(function() {
                                document.getElementById('emailkey').setStyle('background-color', 'white');
                            }, 250);
                        }
                    }
                }
            }
        </script>
</code>```

Body:
I have never done an AJAX call before...

I have a page where there are two dropdown fields, one of who to send a transcript to and the other is the type of hearing. I added onchange functionality to the type of hearing to make the send transcript to field change, depending on what was selected.

The problem is that the person could choose another option before the job is saved, so if you read the value of the send to dropdown, it doesn't change in code, even though the display changes. I was thinking that maybe I need to do an AJAX call to save the dropdown before I read it, but I'm stuck. I've never used AJAX before.

There are a lot of examples of reading from a file or reading to a file and using jQuery, but I need to use JavaScript and write to a database.

This is the field with the onchange event:

 echo form_label('Type:', 'hearingtype') . form_dropdown('hearingtype[r]', $hearingtypes, isset($job['hearingtype']) ? $job['hearingtype'] : '', array('onchange' => 'changeEmail($(this));')) . '
';

This is the field that should change:

echo form_label('Send transcript to:', 'emailkey') .
            form_dropdown('emailkey', $operationsemails, isset($job) ? $job['emailkey'] : '', 'id="emailkey"') . '
';

And this is the JavaScript:

The test.txt is obviously not correct. I am stumped as to what to put in there to write to the database. Would I put a call to a function ($this->functioName)? Everything else works perfectly.

I don't know if there's another way to read what's displayed on the webpage, not what's in the code...

Body:
If anyone is interested, I ended up doing the following and got it to work:

 echo form_label('Type:', 'hearingtype') . form_dropdown('hearingtype[r]', $hearingtypes, isset($job['hearingtype']) ? $job['hearingtype'] : '', array('onchange' => 'changeEmail($(this));')) . '<br />';

And:

        <script type="text/javascript">
            function changeEmail(name) {
                let hearingType = name.value.toString();
                if (hearingType === '16') {
                    let x = document.getElementById('emailkey');
                    for (let i = 0; i < x.options.length; i++) {
                        let optionValue = x.options[i].innerHTML;
                        if (optionValue.includes('Janet') > 0) {
                            x.options[i].selected = 'selected';
                            document.getElementById('emailkey').setStyle('background-color', 'lightgreen');
                            setTimeout(function() {
                                document.getElementById('emailkey').setStyle('background-color', 'white');
                            }, 250);
                        }
                    }
                } else {
                    let x = document.getElementById('emailkey');
                    for (let i = 0; i < x.options.length; i++) {
                        let optionValue = x.options[i].innerHTML;
                        if (optionValue.includes('Michelle') > 0) {
                            x.options[i].selected = 'selected';
                            document.getElementById('emailkey').setStyle('background-color', 'lightgreen');
                            setTimeout(function() {
                                document.getElementById('emailkey').setStyle('background-color', 'white');
                            }, 250);
                        }
                    }
                }
            }
        </script>


问:
Using pivot in one select statement
I have table with columns:

```<code>[Date]       [Name]     [Result]
2010-01-01   Name01     11
2010-01-01   Name02     22
2010-07-04   Name01     32
2010-07-04   Name02     54
</code>```

I'm working on SELECT statement which give me a result like this:

```<code>[Name]  [2010-01-01] [2010-07-04]
Name01       11           32
Name02       22           54
</code>```

I've tried PIVOT function, but it's not working.

SELECT * FROM (

```<code>SELECT Date,Name,Result
FROM tbl_Results
WHERE (..conditions..)
)
PIVOT (
Result FOR Date in
([1],[2],[3],[2],[5])
)
</code>```

Error message

Incorrect syntax near the keyword 'PIVOT'.

It's SQL server 2005, I'm not sure if PIVOT is available?

Maybe use any other function ?

Also I don't know how to set column name as date from select.

UPDATE

Thank you for all answers. The problem is that I don't know how many columns will be in the result. So I can't use fixed dates values like '2010-07-04'. The date is used "on the fly" in statement from table.

答:
I see in your update that you will need DYNAMIC SQL.   Here is a stored procedure that will pivot virtually any table, or ad-hoc query.   There is also the added utility of creating additional row aggregations

Example

```<code>Exec [prc-Pivot] '#YourTable','Date','sum([Result])[]','Name','count(*)[Records],min(Result)[MinValue],max(Result)[MaxValue]'
</code>```

Or As Simple As

```<code>Exec [prc-Pivot] '#YourTable','Date','sum([Result])[]','Name',null
</code>```

Returns

The Stored Procedure

```<code>CREATE PROCEDURE [dbo].[prc-Pivot] (
    @Source varchar(1000),          -- Any Table or Select Statement
    @PvotCol varchar(250),          -- Field name or expression ie. Month(Date)
    @Summaries varchar(250),        -- aggfunction(aggValue)[optionalTitle]
    @GroupBy varchar(250),          -- Optional additional Group By
    @OtherCols varchar(500) )       -- Optional Group By or aggregates
AS

Set NoCount On
Set Ansi_Warnings Off

Declare @Vals varchar(max),@SQL varchar(max);
Set @Vals = ''
Set @OtherCols= IsNull(', ' + @OtherCols,'')
Set @Source = case when @Source Like 'Select%' then @Source else 'Select * From '+@Source end
Create Table #TempPvot  (Pvot varchar(100))
Insert Into #TempPvot
Exec ('Select Distinct Convert(varchar(100),' + @PvotCol + ') as Pvot FROM (' + @Source + ') A')
Select @Vals = @Vals + ', isnull(' + Replace(Replace(@Summaries,'(','(CASE WHEN ' + @PvotCol + '=''' + Pvot +  ''' THEN '),')[', ' END),0) As [' + Pvot ) From #TempPvot Order by Pvot
Drop Table #TempPvot
Set @SQL = Replace('Select ' + Isnull(@GroupBy,'') + @OtherCols + @Vals + ' From (' + @Source + ') PvtFinal ' + case when Isnull(@GroupBy,'')<>'' then 'Group By ' + @GroupBy + ' Order by ' + @GroupBy else '' end,'Select , ','Select ')
--Print @SQL
Exec (@SQL)

Set NoCount Off
Set Ansi_Warnings on
</code>```

Title: Using pivot in one select statement

Body:
I have table with columns:

[Date]       [Name]     [Result]
2010-01-01   Name01     11
2010-01-01   Name02     22
2010-07-04   Name01     32
2010-07-04   Name02     54

I'm working on SELECT statement which give me a result like this:

[Name]  [2010-01-01] [2010-07-04]
Name01       11           32
Name02       22           54

I've tried PIVOT function, but it's not working.

SELECT * FROM (

SELECT Date,Name,Result
FROM tbl_Results
WHERE (..conditions..)
)
PIVOT (
Result FOR Date in
([1],[2],[3],[2],[5])
)

Error message

Incorrect syntax near the keyword 'PIVOT'.

It's SQL server 2005, I'm not sure if PIVOT is available?

Maybe use any other function ?

Also I don't know how to set column name as date from select.

UPDATE

Thank you for all answers. The problem is that I don't know how many columns will be in the result. So I can't use fixed dates values like '2010-07-04'. The date is used "on the fly" in statement from table.

Body:
I see in your update that you will need DYNAMIC SQL.   Here is a stored procedure that will pivot virtually any table, or ad-hoc query.   There is also the added utility of creating additional row aggregations

Example

Exec [prc-Pivot] '#YourTable','Date','sum([Result])[]','Name','count(*)[Records],min(Result)[MinValue],max(Result)[MaxValue]'

Or As Simple As

Exec [prc-Pivot] '#YourTable','Date','sum([Result])[]','Name',null

Returns

The Stored Procedure

CREATE PROCEDURE [dbo].[prc-Pivot] (
    @Source varchar(1000),          -- Any Table or Select Statement
    @PvotCol varchar(250),          -- Field name or expression ie. Month(Date)
    @Summaries varchar(250),        -- aggfunction(aggValue)[optionalTitle]
    @GroupBy varchar(250),          -- Optional additional Group By
    @OtherCols varchar(500) )       -- Optional Group By or aggregates
AS

Set NoCount On
Set Ansi_Warnings Off

Declare @Vals varchar(max),@SQL varchar(max);
Set @Vals = ''
Set @OtherCols= IsNull(', ' + @OtherCols,'')
Set @Source = case when @Source Like 'Select%' then @Source else 'Select * From '+@Source end
Create Table #TempPvot  (Pvot varchar(100))
Insert Into #TempPvot
Exec ('Select Distinct Convert(varchar(100),' + @PvotCol + ') as Pvot FROM (' + @Source + ') A')
Select @Vals = @Vals + ', isnull(' + Replace(Replace(@Summaries,'(','(CASE WHEN ' + @PvotCol + '=''' + Pvot +  ''' THEN '),')[', ' END),0) As [' + Pvot ) From #TempPvot Order by Pvot
Drop Table #TempPvot
Set @SQL = Replace('Select ' + Isnull(@GroupBy,'') + @OtherCols + @Vals + ' From (' + @Source + ') PvtFinal ' + case when Isnull(@GroupBy,'')<>'' then 'Group By ' + @GroupBy + ' Order by ' + @GroupBy else '' end,'Select , ','Select ')
--Print @SQL
Exec (@SQL)

Set NoCount Off
Set Ansi_Warnings on


问:
displaying column based on value of another column
There is a table like this:

```<code>Parent | Child
1      | 11
11     | 12
11     | 13
12     | 14
12     | 14
</code>```

If pass 1, it should return all the ‘1’ children’s: 11, 12, 13, 14

答:
You could have a look at recursive queries using CTE.
Links about the topic:

Simple example of recursive CTE

Example from MSDN

Body:
There is a table like this:

Parent | Child
1      | 11
11     | 12
11     | 13
12     | 14
12     | 14

If pass 1, it should return all the ‘1’ children’s: 11, 12, 13, 14


问:
Working with haven_labelled_spss - data looses "label" after setting NA values
I have a labelled_spss dataset, imported with
haven::read_sav("path/file.sav", user_na = TRUE). Somehow, after using labelled::na_values I loose the label-tag in my attributes and I can't figure out why.

An example:

```<code>#Before
attributes(a$q24)
</code>```

$label
  [1] "If tomorrow would be a referendum, how would you vote?"

$format.spss
   [1] "F3.0"

$class
   [1] "haven_labelled"

$labels
   Country should be in Union  Country should leave            wouldn't vote
                                   1                                  2                                966
           don't know
                                 977

# Setting NA
na_values(a$q24) <- 977
attributes(a$q24)
```

$format.spss
   [1] "F3.0"

$class
   [1] "haven_labelled"

$labels
   Country should be in Union  Country should leave            wouldn't vote
                                   1                                  2                                966
           don't know
                                 977

$na_values
  [1] 977

Can someone help me please?

答: It was a bug in labelled. It should be fixed in the development version.

Body:
I have a labelled_spss dataset, imported with
haven::read_sav("path/file.sav", user_na = TRUE). Somehow, after using labelled::na_values I loose the label-tag in my attributes and I can't figure out why.

An example:

#Before
attributes(a$q24)

$label
  [1] "If tomorrow would be a referendum, how would you vote?"

$format.spss
   [1] "F3.0"

$class
   [1] "haven_labelled"

$labels
   Country should be in Union  Country should leave            wouldn't vote
                                   1                                  2                                966
           don't know
                                 977

# Setting NA
na_values(a$q24) <- 977
attributes(a$q24)

$format.spss
   [1] "F3.0"

$class
   [1] "haven_labelled"

$labels
   Country should be in Union  Country should leave            wouldn't vote
                                   1                                  2                                966
           don't know
                                 977

$na_values
  [1] 977

Can someone help me please?


问:
How to change JSON response format in the ResponseEntity?
I have some REST controller which generate a response to a user and send it.

```<code>  @RequestMapping(method = RequestMethod.GET, value = "/hello/contacts")
    public ResponseEntity<Page<ContactDto>> getContacts(@RequestParam(name = "nameFilter") String nameFilter
    , @RequestParam(name = "page", required = false, defaultValue = "1") int page
    , @RequestParam(name = "size", required = false, defaultValue = "100") int size) {

        List<ContactDto> contacts = contactService.getContacts(nameFilter);

        Pageable pagiable = PageRequest.of(page - 1, size);
        int start = (page - 1) * size;
        int end = start + size;

        Page<ContactDto> pages;
        if (end <= contacts.size()) {
            pages = new PageImpl<>(contacts.subList(start, end), pagiable, contacts.size());
            return new ResponseEntity<>(pages, HttpStatus.OK);
        } else {
            if (start < contacts.size()) {
                contacts.size();
                pages = new PageImpl<>(contacts.subList(start, contacts.size()), pagiable, contacts.size());
                return new ResponseEntity<>(pages, HttpStatus.OK);
            }
        }

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
</code>```

After sending response user get JSON response in next format:

```<code>{
    "content": [
        {
            "id": 1,
            "name": "Rm7W8bDq7z"
        },
        {
            "id": 2,
            "name": "vYYWLImOWe"
        },
        {
            "id": 3,
            "name": "gRKokZFEdf"
        }],``
    "pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 100,
        "paged": true,
        "unpaged": false
    },
    "totalPages": 10,
    "totalElements": 999,
    "last": false,
    "size": 100,
    "number": 0,
    "sort": {
        "sorted": false,
        "unsorted": true,
        "empty": true
    },
    "numberOfElements": 100,
    "first": true,
    "empty": false
}
</code>```

I want change JSON property name content to another name, for example, "contacts".
How can I do this?

答:
Generally you can't. Because the Page has content and it's not related to business. For Page it's neutral that what it contains.

But I think the below workaround can help.

You need to create a custom page class.

```<code>public class CustomPageImpl<T> extends PageImpl<T>{
@JsonProperty("contacts")
public List<T> getContent() {
  return super.getContent();
}
}
</code>```

Then use this custom page class to return results.

Body:
I have some REST controller which generate a response to a user and send it.

  @RequestMapping(method = RequestMethod.GET, value = "/hello/contacts")
    public ResponseEntity<Page<ContactDto>> getContacts(@RequestParam(name = "nameFilter") String nameFilter
    , @RequestParam(name = "page", required = false, defaultValue = "1") int page
    , @RequestParam(name = "size", required = false, defaultValue = "100") int size) {

        List<ContactDto> contacts = contactService.getContacts(nameFilter);

        Pageable pagiable = PageRequest.of(page - 1, size);
        int start = (page - 1) * size;
        int end = start + size;

        Page<ContactDto> pages;
        if (end <= contacts.size()) {
            pages = new PageImpl<>(contacts.subList(start, end), pagiable, contacts.size());
            return new ResponseEntity<>(pages, HttpStatus.OK);
        } else {
            if (start < contacts.size()) {
                contacts.size();
                pages = new PageImpl<>(contacts.subList(start, contacts.size()), pagiable, contacts.size());
                return new ResponseEntity<>(pages, HttpStatus.OK);
            }
        }

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

After sending response user get JSON response in next format:

{
    "content": [
        {
            "id": 1,
            "name": "Rm7W8bDq7z"
        },
        {
            "id": 2,
            "name": "vYYWLImOWe"
        },
        {
            "id": 3,
            "name": "gRKokZFEdf"
        }],``
    "pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 100,
        "paged": true,
        "unpaged": false
    },
    "totalPages": 10,
    "totalElements": 999,
    "last": false,
    "size": 100,
    "number": 0,
    "sort": {
        "sorted": false,
        "unsorted": true,
        "empty": true
    },
    "numberOfElements": 100,
    "first": true,
    "empty": false
}

I want change JSON property name content to another name, for example, "contacts".
How can I do this?

Body:
Generally you can't. Because the Page has content and it's not related to business. For Page it's neutral that what it contains.

But I think the below workaround can help.

You need to create a custom page class.

public class CustomPageImpl<T> extends PageImpl<T>{
@JsonProperty("contacts")
public List<T> getContent() {
  return super.getContent();
}
}

Then use this custom page class to return results.