问:
PHP MySQL select all results with ASC references
Suppose I have the following table:

```<code>ID|Reference
1 |23
1 |27
1 |47
1 |48
2 |16
2 |17
2 |18
2 |33
3 |16
3 |19
3 |22
4 |2
5 |6
5 |8
5 |7
5 |12
</code>```

I want to select all the ID's that have at least 2 ASC references with a difference of 1. So for instance when I execute the query, I want a return of:

```<code>ID|Reference
1 |47
1 |48
2 |16
2 |17
2 |18
5 |6
5 |8
5 |7
</code>```

Ofcourse, I could use a query like:

```<code>SELECT ID, Reference FROM Table ORDER BY Reference ASC
</code>```

and loop through the results and check it manually. However, I am wondering whether MySQL could achieve this in a single query and pop back the right results, since this will optimize performance (I guess)

答:
Joins should be fast if you have useful indexes.

I would suggest just doing a couple of simple queries (using simple joins) , and unioning the results together

```<code>SELECT T1.ID,
        T1.Reference
FROM Table T1
INNER JOIN Table T2
ON T1.ID = T2.ID
AND T1.Reference = T2.Reference + 1
UNION
SELECT T1.ID,
        T1.Reference
FROM Table T1
INNER JOIN Table T2
ON T1.ID = T2.ID
AND T1.Reference = T2.Reference - 1
ORDER BY Reference ASC
</code>```

Body:
Suppose I have the following table:

ID|Reference
1 |23
1 |27
1 |47
1 |48
2 |16
2 |17
2 |18
2 |33
3 |16
3 |19
3 |22
4 |2
5 |6
5 |8
5 |7
5 |12

I want to select all the ID's that have at least 2 ASC references with a difference of 1. So for instance when I execute the query, I want a return of:

ID|Reference
1 |47
1 |48
2 |16
2 |17
2 |18
5 |6
5 |8
5 |7

Ofcourse, I could use a query like:

SELECT ID, Reference FROM Table ORDER BY Reference ASC

and loop through the results and check it manually. However, I am wondering whether MySQL could achieve this in a single query and pop back the right results, since this will optimize performance (I guess)

Body:
Joins should be fast if you have useful indexes.

I would suggest just doing a couple of simple queries (using simple joins) , and unioning the results together

SELECT T1.ID,
        T1.Reference
FROM Table T1
INNER JOIN Table T2
ON T1.ID = T2.ID
AND T1.Reference = T2.Reference + 1
UNION
SELECT T1.ID,
        T1.Reference
FROM Table T1
INNER JOIN Table T2
ON T1.ID = T2.ID
AND T1.Reference = T2.Reference - 1
ORDER BY Reference ASC


来源: stackexchange

问:
Is there a way to get the React / Redux's bundle.js on the local hard drive?
When the Reach / Redux app is finally running, there is a file bindle.js, but if I use

```<code>find . -name '*bundle.js*' | xargs ls -l
</code>```

all the bundle.js files in the repo are not the one that was just built (meaning, those are older files and do not have a current timestamp if I just edited my project 10 seconds ago).

Is the only way to get this file from http://localhost:8080/bundle.js ? This file should have been made and sit inside the hard drive, and I think the server doesn't make it every time when the browser requests it.

答: webpack-dev-server and similar only create the bundles in memory for performance reasons. You can do single builds with the webpack command.

ContentLicense: CC BY-SA 3.0

Body:
When the Reach / Redux app is finally running, there is a file bindle.js, but if I use

find . -name '*bundle.js*' | xargs ls -l

all the bundle.js files in the repo are not the one that was just built (meaning, those are older files and do not have a current timestamp if I just edited my project 10 seconds ago).

Is the only way to get this file from http://localhost:8080/bundle.js ? This file should have been made and sit inside the hard drive, and I think the server doesn't make it every time when the browser requests it.


问:
Pandas: reverse rows with same values
I have a DataFrame, where rows are 'grouped' by the third column (rows in one 'group' have the same value at the third column):

```<code>c1 c2 c3
0   b  1
1   r  1
2   f  2
3   x  2
4   n  2
5   r  3
6   f  3
</code>```

But the values in the second column have a wrong order. I need to reverse rows in each 'group', so DataFrame should look like this:

```<code>c1 c2 c3
0   r  1
1   b  1
2   n  2
3   x  2
4   f  2
5   f  3
6   r  3
</code>```

Is there an effective way to transform the first DataFrame to the second one with pandas?

UPD: Updated with more clear example. The values should be exactly reversed, not just became located in the alphabetical order.

答:
It seems you need sort_values:

```<code>df = df.sort_values(['c3','c2'])
print (df)
   c1   c2  c3
1   1    a   1
0   0    b   1
4   4   aa   2
3   3   bb   2
2   2   cc   2
6   6  xxx   3
5   5  zzz   3
</code>```

EDIT:

You can use groupby and change order by [::-1]:

```<code>#more general solution, working with not unique index also
def reversing(x):
    x['c2'] = x['c2'].iloc[::-1].values
    return x

df = df.groupby('c3', sort=False)).apply(reversing)
print (df)
   c1 c2  c3
0   0  r   1
1   1  b   1
2   2  n   2
3   3  x   2
4   4  f   2
5   5  f   3
6   6  r   3

#solution working only with unique monotonic increasing index, because reset index
df['c2'] = df.groupby('c3', sort=False)['c2'].apply(lambda x: x[::-1]).reset_index(drop=True)
print (df)
   c1 c2  c3
0   0  r   1
1   1  b   1
2   2  n   2
3   3  x   2
4   4  f   2
5   5  f   3
6   6  r   3
</code>```

Solutions, where order of values in c1 is changed:

You can sorting by index (has to be unique monotonic increasing).

```<code>df=df.reset_index().sort_values(['c3','index'],ascending=[True, False]).drop('index',axis=1)
print (df)
   c1 c2  c3
1   1  r   1
0   0  b   1
4   4  n   2
3   3  x   2
2   2  f   2
6   6  f   3
5   5  r   3
</code>```

If column c1 is unique monotonic increasing (0,1,2..) as default index:

```<code>df = df.sort_values(['c3','c1'], ascending=[True, False])
print (df)
   c1 c2  c3
1   1  r   1
0   0  b   1
4   4  n   2
3   3  x   2
2   2  f   2
6   6  f   3
5   5  r   3
</code>```

Title: Pandas: reverse rows with same values

Body:
I have a DataFrame, where rows are 'grouped' by the third column (rows in one 'group' have the same value at the third column):

c1 c2 c3
0   b  1
1   r  1
2   f  2
3   x  2
4   n  2
5   r  3
6   f  3

But the values in the second column have a wrong order. I need to reverse rows in each 'group', so DataFrame should look like this:

c1 c2 c3
0   r  1
1   b  1
2   n  2
3   x  2
4   f  2
5   f  3
6   r  3

Is there an effective way to transform the first DataFrame to the second one with pandas?

UPD: Updated with more clear example. The values should be exactly reversed, not just became located in the alphabetical order.

Body:
It seems you need sort_values:

df = df.sort_values(['c3','c2'])
print (df)
   c1   c2  c3
1   1    a   1
0   0    b   1
4   4   aa   2
3   3   bb   2
2   2   cc   2
6   6  xxx   3
5   5  zzz   3

EDIT:

You can use groupby and change order by [::-1]:

#more general solution, working with not unique index also
def reversing(x):
    x['c2'] = x['c2'].iloc[::-1].values
    return x

df = df.groupby('c3', sort=False)).apply(reversing)
print (df)
   c1 c2  c3
0   0  r   1
1   1  b   1
2   2  n   2
3   3  x   2
4   4  f   2
5   5  f   3
6   6  r   3

#solution working only with unique monotonic increasing index, because reset index
df['c2'] = df.groupby('c3', sort=False)['c2'].apply(lambda x: x[::-1]).reset_index(drop=True)
print (df)
   c1 c2  c3
0   0  r   1
1   1  b   1
2   2  n   2
3   3  x   2
4   4  f   2
5   5  f   3
6   6  r   3

Solutions, where order of values in c1 is changed:

You can sorting by index (has to be unique monotonic increasing).

df=df.reset_index().sort_values(['c3','index'],ascending=[True, False]).drop('index',axis=1)
print (df)
   c1 c2  c3
1   1  r   1
0   0  b   1
4   4  n   2
3   3  x   2
2   2  f   2
6   6  f   3
5   5  r   3

If column c1 is unique monotonic increasing (0,1,2..) as default index:

df = df.sort_values(['c3','c1'], ascending=[True, False])
print (df)
   c1 c2  c3
1   1  r   1
0   0  b   1
4   4  n   2
3   3  x   2
2   2  f   2
6   6  f   3
5   5  r   3


问:
Number of images in each classes
Currently, I am training a model for image detection, and I want to know how many images do I need per class, do i need to have the same numbers of each object.

Please i need some advice.

I use Tensorflow, and Yolo v2 model.

Thanks,

答:
You need as many as you can get, but definitely in the order of tens of thousands at least if you're training the network from scratch (there are pre-trained weights for YOLOv2 trained on
 - http://host.robots.ox.ac.uk/pascal/VOC/).

It's best to have balanced classes, meaning the number of images for each class must be close, it's easier to train this way.

Why are you training the network yourself? Can't you use some pre-trained models, drop the FC layers and insert your own classes? This way it's much faster, and you don't need that many images.

Title: Number of images in each classes


问:
Watermark on image while uploading to phpmyadmin
I am trying to upload image to phpmyadmin with automatic watermark. I am able simply to upload image, which saves image name (image.jpg) in phpmyadmin and also saves that image in spesific folder. But I need to make automatic watermark beeing add on image, when it saves in specific folder. How to do that?

code for upload form and display of image:

```<code><?php
                          $sql = "SELECT * FROM paminklai";
                          $result = mysqli_query($connection, $sql);
                          while($row = mysqli_fetch_array($result)){
                            ?>
                        <div class="iso-box lunch col-md-4 col-sm-6">
                          <div class="gallery-thumb">
                            <a href="images/paminklai/<?php echo $row['image'] ?>" data-lightbox-gallery="food-gallery">
                              <img src="images/paminklai/<?php echo $row['image'] ?>" class="fluid-img" alt="Gallery">
                                <div class="gallery-overlay">
                                  <div class="gallery-item">
                                    <i class="fa fa-search"></i>
                                  </div>
                                </div>
                            </a>
                          </div>
                        </div>
                            <?php
                          }
                         ?>

                            <div class="iso-box lunch col-md-4 col-sm-6">
                          <div class="gallery-thumb addimg">

                               <form method="post" action="uploadimg.php" enctype="multipart/form-data">
                                <input type="hidden" name="size" value="100000">
                                <div style="margin:10px">
                                    <input id="selectedFile" type="file" onpropertychange="add()" style="position:absolute;visibility:hidden;" name="image">
                                    <input type="button" id="browseButton" value="Pasirinkti nuotrauka" onclick="selectedFile.click()">
                                </div>
                                <div>
                                    <input type="text" name="text" class="form-control" placeholder="Pavadinimas">
                                </div>
                                <div>
                                    <input type="submit" name="upload" value="Išsaugoti" style="margin:10px">
                                </div>
                            </form>
                          </div>
                        </div>
</code>```

Code for uploading:

```<code><?php include "config.php"; ?>
<?php
if(isset($_POST['upload'])){
    $target = "images/paminklai/".basename($_FILES['image']['name']);

    $image = strtolower($_FILES['image']['name']);
    $text = $_POST['text'];
    $sql = "INSERT INTO paminklai (image, text) VALUES ('$image', '$text')";
    mysqli_query($connection, $sql);

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
       header("Location: paminklaiadmin.php");
    } else {
        echo "There was a problem uploadin image";
    }
}
?>
</code>```

phpmyadmin table:
enter image description here

答:
Use below sample script to add watermark in images.</p>

```<code><?php
  error_reporting(0);
  if(!isset($_GET['src']) && $_GET['src']==""){  echo "provide image url in url";exit;}
  header('content-type: image/jpeg');
  $src = $_GET['src'];
  $path = pathinfo($src);
  $watermark = imagecreatefrompng('watermark.png');
  $watermark_width = imagesx($watermark);
  $watermark_height = imagesy($watermark);
  $image = imagecreatetruecolor($watermark_width, $watermark_height);
  if ($path['extension']=='png')
       $image = imagecreatefrompng($src);
  else if ($path['extension']=='jpg'||$path['extension']=='jpeg')
       $image = imagecreatefromjpeg($src);
  $size = getimagesize($_GET['src']);
  $dest_x = $size[0] - $watermark_width-200;
  $dest_y = $size[1] - $watermark_height-200;
  imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0,$watermark_width, $watermark_height, 50);
  imagejpeg($image,'image.jpg', 85);
  imagedestroy($image);
  imagedestroy($watermark);
?>
</code>```

Body:
I am trying to upload image to phpmyadmin with automatic watermark. I am able simply to upload image, which saves image name (image.jpg) in phpmyadmin and also saves that image in spesific folder. But I need to make automatic watermark beeing add on image, when it saves in specific folder. How to do that?

code for upload form and display of image:

<?php
                          $sql = "SELECT * FROM paminklai";
                          $result = mysqli_query($connection, $sql);
                          while($row = mysqli_fetch_array($result)){
                            ?>

                            <a href="images/paminklai/<?php echo $row['image'] ?>" data-lightbox-gallery="food-gallery">
                              <img src="images/paminklai/<?php echo $row['image'] ?>" class="fluid-img" alt="Gallery">

                            <?php
                          }
                         ?>

                               <form method="post" action="uploadimg.php" enctype="multipart/form-data">
                                <input type="hidden" name="size" value="100000">

                                    <input id="selectedFile" type="file" onpropertychange="add()" style="position:absolute;visibility:hidden;" name="image">
                                    <input type="button" id="browseButton" value="Pasirinkti nuotrauka" onclick="selectedFile.click()">

                                    <input type="text" name="text" class="form-control" placeholder="Pavadinimas">

                                    <input type="submit" name="upload" value="Išsaugoti" style="margin:10px">

                            </form>

Code for uploading:

<?php include "config.php"; ?>
<?php
if(isset($_POST['upload'])){
    $target = "images/paminklai/".basename($_FILES['image']['name']);

    $image = strtolower($_FILES['image']['name']);
    $text = $_POST['text'];
    $sql = "INSERT INTO paminklai (image, text) VALUES ('$image', '$text')";
    mysqli_query($connection, $sql);

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
       header("Location: paminklaiadmin.php");
    } else {
        echo "There was a problem uploadin image";
    }
}
?>

phpmyadmin table:
enter image description here

Body:
Use below sample script to add watermark in images.

<?php
  error_reporting(0);
  if(!isset($_GET['src']) && $_GET['src']==""){  echo "provide image url in url";exit;}
  header('content-type: image/jpeg');
  $src = $_GET['src'];
  $path = pathinfo($src);
  $watermark = imagecreatefrompng('watermark.png');
  $watermark_width = imagesx($watermark);
  $watermark_height = imagesy($watermark);
  $image = imagecreatetruecolor($watermark_width, $watermark_height);
  if ($path['extension']=='png')
       $image = imagecreatefrompng($src);
  else if ($path['extension']=='jpg'||$path['extension']=='jpeg')
       $image = imagecreatefromjpeg($src);
  $size = getimagesize($_GET['src']);
  $dest_x = $size[0] - $watermark_width-200;
  $dest_y = $size[1] - $watermark_height-200;
  imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0,$watermark_width, $watermark_height, 50);
  imagejpeg($image,'image.jpg', 85);
  imagedestroy($image);
  imagedestroy($watermark);
?>


问:
The speed of JIT compiling method call compared to reflection in .NET
Reflection is usually said to be slow. However, when .NET JIT compiler needs to compile a call to a method it needs to refer to the same module metadata tables (if I understand it correctly). Does method (and field) lookup incur the same perf. hit in JIT compilation and in reflection?</p>

答: I think the two might be comparable, but don't forget that JITting is a one-time cost, while using reflection isn't.</p>

ContentLicense: CC BY-SA 2.5


问:
Best way to handle long-running tasks on a web server
For the past few days I've been googling about how should I handle long running tasks on a web server. I have found a lot of good answers of how to run them in a specific language, but not what languages to choose for this kind of job.

So, I have a web server which is running some kind of custom e-commerce platform. There is another server where some products dostributor is providing access to its data through API. I have to sync products list across these two servers. Product base is pretty big (about 100000 products).

My Idea was to write php script which collects data from various API endpoints and updates database accordingly. But it gonna take a long time, so without hard modofications and deep-diving to php itself it will timeout.

Now I'm thinking, maybe I should write python script which goes through API endpoints and collects data about each product. After data about product is collected python script could initiate php script which could update data in database about that particular product..

What are your toughts about it? What would be the best way to handle it?

答:
This sounds like something you could be better off doing from the server-side with Cron, for example and not from a browser. Unless, of course, you need to do this manually at random times by people who have no terminal access.

If it has to be PHP, you can run that with cron or from terminal and disable the timeout (see: http://php.net/manual/en/function.set-time-limit.php ) and even leave it as a background process if needed with &. This way you wouldn't be limited by Apache (or whatever server you are using) time limits.


问:
Getting blank response from Linkedin
I am trying to request for user information after successful login in Codename one application, but when, after login user redirected to the application, But not getting any response.

Following is my code:

```<code>linked.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {

               Oauth2 auth2 = new Oauth2("https://www.linkedin.com/oauth/v2/authorization",
                "XXXXXXXXXX",
                "https://www.codenameone.com","",
                "https://www.linkedin.com/oauth/v2/accessToken",
                "XXXXXXXXXX");

       //auth2.authenticate();
        auth2.showAuthentication(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent evt) {
                       AccessToken token = (AccessToken) evt.getSource();
                       JSONObject object = new JSONObject(token);
                       try {
                           TOKEN = object.getString("token");
                           Log.p(TOKEN);

                             ConnectionRequest linkedinreq = new ConnectionRequest(){
                   @Override
                   protected void readResponse(InputStream input) throws IOException {
                      Log.p(input.toString());
                   }

             };
             linkedinreq.setPost(false);
             linkedinreq.setUrl("https://api.linkedin.com/v1/people/~:(id,num-connections,picture-url)");
             linkedinreq.addArgumentNoEncoding("oauth2_access_token", TOKEN);
            linkedinreq.addArgumentNoEncoding("format", "json");
             NetworkManager.getInstance().addToQueue(linkedinreq);

                       } catch (JSONException ex) {
                           ex.printStackTrace();
                       }
                   }
               });
                Oauth2.setBackToParent(true);

       }
        });
</code>```

And the network monitor snapshot which display empty response

And the out put display in console

```<code>[Network Thread] 0:0:1,12 - com.codename1.impl.javase.JavaSEPort$67@41ca2b3e
</code>```

答:
you can get any error message after override this message
and call setreadResponseErrors(true); which will display error message and response code.</p>

```<code>linkedinreq.setReadResponseForErrors(true);
     @Override
                protected void handleErrorResponseCode(int code, String message) {
                    System.out.println("code: " + code + "message: " + message);
                }
</code>```

Title: Getting blank response from Linkedin

Body:
I am trying to request for user information after successful login in Codename one application, but when, after login user redirected to the application, But not getting any response.

Following is my code:

linked.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {

               Oauth2 auth2 = new Oauth2("https://www.linkedin.com/oauth/v2/authorization",
                "XXXXXXXXXX",
                "https://www.codenameone.com","",
                "https://www.linkedin.com/oauth/v2/accessToken",
                "XXXXXXXXXX");

       //auth2.authenticate();
        auth2.showAuthentication(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent evt) {
                       AccessToken token = (AccessToken) evt.getSource();
                       JSONObject object = new JSONObject(token);
                       try {
                           TOKEN = object.getString("token");
                           Log.p(TOKEN);

                             ConnectionRequest linkedinreq = new ConnectionRequest(){
                   @Override
                   protected void readResponse(InputStream input) throws IOException {
                      Log.p(input.toString());
                   }

             };
             linkedinreq.setPost(false);
             linkedinreq.setUrl("https://api.linkedin.com/v1/people/~:(id,num-connections,picture-url)");
             linkedinreq.addArgumentNoEncoding("oauth2_access_token", TOKEN);
            linkedinreq.addArgumentNoEncoding("format", "json");
             NetworkManager.getInstance().addToQueue(linkedinreq);

                       } catch (JSONException ex) {
                           ex.printStackTrace();
                       }
                   }
               });
                Oauth2.setBackToParent(true);

       }
        });

And the network monitor snapshot which display empty response

And the out put display in console

[Network Thread] 0:0:1,12 - com.codename1.impl.javase.JavaSEPort$67@41ca2b3e

Body:
you can get any error message after override this message
and call setreadResponseErrors(true); which will display error message and response code.

linkedinreq.setReadResponseForErrors(true);
     @Override
                protected void handleErrorResponseCode(int code, String message) {
                    System.out.println("code: " + code + "message: " + message);
                }


问:
Stored Proc that picks from 2 different Select Statements
I have the following Select statements, I need to create a stored proc that will choose which statement to run, guessing this would have to be based on variables (newb here). I've read about Passed Parameters but have not seen an example that applies to this situation in my searches, please help me out.

I am in SQL Server 2014.

First statement

```<code>select
   cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
   case
          when datepart(hour,dateadd(hour,-4,getdate()))>=8 and datepart(hour,dateadd(hour,-4,getdate()))<22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='00:30:00.0000000' then 'alert'
          else 'no alert'
   end as alert_status
from activity_table
</code>```

Second Statement

```<code>select
   cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
   case
          when datepart(hour,dateadd(hour,-4,getdate()))<8 and datepart(hour,dateadd(hour,-4,getdate()))>=22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='01:00:00.0000000' then 'alert'
          else 'no alert'
   end as alert_status
from activity_table
</code>```

答:
Will something like this work

```<code>CREATE PROCEDURE ChooseWhichOne
    @Selection BIT
AS
BEGIN

    IF @Selection = 0
    BEGIN
        select
           cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
           case
                  when datepart(hour,dateadd(hour,-4,getdate()))>=8 and datepart(hour,dateadd(hour,-4,getdate()))<22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='00:30:00.0000000' then 'alert'
                  else 'no alert'
           end as alert_status
        from activity_table
    END
    ELSE
    BEGIN
        select
           cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
           case
                  when datepart(hour,dateadd(hour,-4,getdate()))<8 and datepart(hour,dateadd(hour,-4,getdate()))>=22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='01:00:00.0000000' then 'alert'
                  else 'no alert'
           end as alert_status
        from activity_table
    END

    RETURN 0

END
</code>```

AND to execute the stored PROCEDURE

```<code>EXEC dbo.ChooseWhichOne @Selection = 0 -- bit
EXEC dbo.ChooseWhichOne @Selection = 1 -- bit
</code>```

Body:
I have the following Select statements, I need to create a stored proc that will choose which statement to run, guessing this would have to be based on variables (newb here). I've read about Passed Parameters but have not seen an example that applies to this situation in my searches, please help me out.

I am in SQL Server 2014.

First statement

select
   cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
   case
          when datepart(hour,dateadd(hour,-4,getdate()))>=8 and datepart(hour,dateadd(hour,-4,getdate()))<22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='00:30:00.0000000' then 'alert'
          else 'no alert'
   end as alert_status
from activity_table

Second Statement

select
   cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
   case
          when datepart(hour,dateadd(hour,-4,getdate()))<8 and datepart(hour,dateadd(hour,-4,getdate()))>=22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='01:00:00.0000000' then 'alert'
          else 'no alert'
   end as alert_status
from activity_table

Body:
Will something like this work

CREATE PROCEDURE ChooseWhichOne
    @Selection BIT
AS
BEGIN

    IF @Selection = 0
    BEGIN
        select
           cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
           case
                  when datepart(hour,dateadd(hour,-4,getdate()))>=8 and datepart(hour,dateadd(hour,-4,getdate()))<22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='00:30:00.0000000' then 'alert'
                  else 'no alert'
           end as alert_status
        from activity_table
    END
    ELSE
    BEGIN
        select
           cast(dateadd(hour,-4,getdate())-max(esig_date) as time) as time_since_last_esig,
           case
                  when datepart(hour,dateadd(hour,-4,getdate()))<8 and datepart(hour,dateadd(hour,-4,getdate()))>=22 and cast(dateadd(hour,-4,getdate())-max(esig_date) as time)>='01:00:00.0000000' then 'alert'
                  else 'no alert'
           end as alert_status
        from activity_table
    END

    RETURN 0

END

AND to execute the stored PROCEDURE

EXEC dbo.ChooseWhichOne @Selection = 0 -- bit
EXEC dbo.ChooseWhichOne @Selection = 1 -- bit


问:
Onclicking Add student button in home_v.php page, open another view page user_v.php
```<code><html>
<head><head>
<title>Home Page</title>
<body>
<style>
.looks
{
border:1px solid black;
}
</style>
<center><h1>Welcome Students!</h1><br><br></center>
<span style="float: right;">
<a href="<?php echo site_url().'/user_c/logout' ?>">Logout</a>
</span>
<h2>List of Students in system are : </h2>
<div id="list">
<table class='looks'>
<tr><th>Student Name</th>
<th></th><th></th><th></th></tr>
<?php
    foreach ($list->result() as $row)
    {
    echo "<tr>";
    echo "<td style='width:30%'>".$row->name."</td>";
    echo "<td><input type='submit' value='Add Student' style='float:left'
    onclick="site_url().'/user_c/add'"></td>";
    echo '<td><input type="submit" value="Update Student"
    style="float:left"></td>';
    echo '<td><input type="submit" value="Delete Student"
    style="float:left"></td>';
    echo "</tr>";
    }
?>
</table>
</div>
</body>
</html>
</code>```

Parse Error

The foreach loop is executed and the values of student are displayed on the
 home_v.php page. Besides the names of these students, I have added a button
 (Add Student).On clicking this button I want to open another view page
 user_v.php, for which I have used onclick tag in the button. But it is not
 working and I get the error attached below. Kindly help as what is the mistake
 I am making.

```<code>    //controller
    function add()
    {
        $this->load->view('user_v');
    }
</code>```

答:
You are making mistake in concatenating PHP and HTML data.
And to make it work on the click do following changes:</p>

```<code>echo "<td><input type='submit' value='Add Student' style='float:left'
onclick=window.location='". site_url("user_c/add")."'></td>";
</code>```

Body:
<title>Home Page</title>

Welcome Students!

<a href="<?php echo site_url().'/user_c/logout' ?>">Logout

List of Students in system are :

Student Name

<?php
    foreach ($list->result() as $row)
    {
    echo "
";
    echo "".$row->name."	";
    echo "<input type='submit' value='Add Student' style='float:left'
    onclick="site_url().'/user_c/add'">	";
    echo '<input type="submit" value="Update Student"
    style="float:left">	';
    echo '<input type="submit" value="Delete Student"
    style="float:left">	';
    echo "
";
    }
?>

Parse Error

The foreach loop is executed and the values of student are displayed on the
 home_v.php page. Besides the names of these students, I have added a button
 (Add Student).On clicking this button I want to open another view page
 user_v.php, for which I have used onclick tag in the button. But it is not
 working and I get the error attached below. Kindly help as what is the mistake
 I am making.

    //controller
    function add()
    {
        $this->load->view('user_v');
    }

Body:
You are making mistake in concatenating PHP and HTML data.
And to make it work on the click do following changes:

echo "<td><input type='submit' value='Add Student' style='float:left'
onclick=window.location='". site_url("user_c/add")."'></td>";


问:
Pick random property and value from Javascript object
I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I accomplished

```<code>var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}
</code>```

Now I want to add more options for such as books, games.. so I've created an object for it:

```<code>var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}
</code>```

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random.
And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

答:
Here you go,

```<code>    var options = {
        watch: ["star wars", "lotr", "moonlight", "avengers"],
        read: ["scott pilgrim", "harry potter", "eragon"],
        play: ["starbound", "skyrim", "bioshock", "fallout"]
    };

    for( i in options){
        //i is will be iterating with values "watch","read","play"
        t = Math.floor( Math.random()* options[i].length);
        //options[i] is to access the value of property eg: options["watch"]
        //will return ["star wars", "lotr", "moonlight", "avengers"]
        console.log("You should " + i +" "+ options[i][t]);
    }
</code>```

Instead logging to something else with the code :)

Body:
I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I accomplished

var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}

Now I want to add more options for such as books, games.. so I've created an object for it:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random.
And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

Body:
Here you go,

    var options = {
        watch: ["star wars", "lotr", "moonlight", "avengers"],
        read: ["scott pilgrim", "harry potter", "eragon"],
        play: ["starbound", "skyrim", "bioshock", "fallout"]
    };

    for( i in options){
        //i is will be iterating with values "watch","read","play"
        t = Math.floor( Math.random()* options[i].length);
        //options[i] is to access the value of property eg: options["watch"]
        //will return ["star wars", "lotr", "moonlight", "avengers"]
        console.log("You should " + i +" "+ options[i][t]);
    }

Instead logging to something else with the code :)


问:
Ocaml representation of values - Atoms
I looked at the internal representation of some OCaml values. The representation of an empty array is an atom(0), i.e. a block with tag=0 and size=0. Empty arrays of floats are represented by an atom(0) too.

Is there any OCaml value represented by an atom with tag > 0? If not: for what purpose the OCaml bytecode set contains the ATOM n instruction?

答:
A tag > 0 is used for constructors with arguments, which would make them not atoms. Constructors without arguments on the other hand are stored as int instead of blocks so again not atoms. So I think atom(0) is not used. Except ...

What about having a constructor with inline record that is empty?

```<code># type t = A of int | B of { };;
Error: Syntax error
</code>```

Seems empty records are not allowed. I can't think of another way to create a 0 size block with tag other than creating such a block directly. But that wouldn't be using the ATOM instruction.

Title: Ocaml representation of values - Atoms

Body:
A tag > 0 is used for constructors with arguments, which would make them not atoms. Constructors without arguments on the other hand are stored as int instead of blocks so again not atoms. So I think atom(0) is not used. Except ...

What about having a constructor with inline record that is empty?

# type t = A of int | B of { };;
Error: Syntax error

Seems empty records are not allowed. I can't think of another way to create a 0 size block with tag other than creating such a block directly. But that wouldn't be using the ATOM instruction.


问:
Does my property update my field or am I using MVVM incorrectly
I'm trying to figure out MVVM and WPF and I wanted to test some easy code to get the hang of it.

I've done this before so I thought that this wouldn't be a problem but I'm losing my mind cause of this.

This is not the full code but I've toned it down just for the specific problem

I have a model

```<code>private string _btnName;
public string BtnName { get {return _btnName;} set{ _btnName = value; } }
</code>```

And my view model like this

```<code>BtnName {get { return model.BtnName;} set{ model.BtnName = value;}}
ICommand ChangeButtonName = new RelayCommand(ChangeName)

Public void ChangeName(object a){ BtnName = "test"; }
</code>```

And the view like this

```<code><Button Content={Binding MV.BtnName} Command={Binding MV.ChangeButtonName}/>
</code>```

Where MV is my ViewModel Class and model is my Model Class.

When I click on the button it goes into my function and does indeed "change" name, but on the view the button will still have the old content. Meaning that it doesn't update.

And I don't understand why.

Why does my button not update the content text?

Should I have properties in my ViewModel?

答:
You have to implement INotifyPropertyChanged in your ViewModel.

```<code>public class MainViewModel : INotifyPropertyChanged
{
    public RelayCommand DoSomethingCommand { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}
</code>```

And you have to change your property to notify your View when the property was updated.

```<code>private string _btnName;
public string BtnName { get { return _btnName; } set { _btnName = value; OnPropertyChanged("BtnName"); } }
</code>```

Body:
I'm trying to figure out MVVM and WPF and I wanted to test some easy code to get the hang of it.

I've done this before so I thought that this wouldn't be a problem but I'm losing my mind cause of this.

This is not the full code but I've toned it down just for the specific problem

I have a model

private string _btnName;
public string BtnName { get {return _btnName;} set{ _btnName = value; } }

And my view model like this

BtnName {get { return model.BtnName;} set{ model.BtnName = value;}}
ICommand ChangeButtonName = new RelayCommand(ChangeName)

Public void ChangeName(object a){ BtnName = "test"; }

And the view like this

<Button Content={Binding MV.BtnName} Command={Binding MV.ChangeButtonName}/>

Where MV is my ViewModel Class and model is my Model Class.

When I click on the button it goes into my function and does indeed "change" name, but on the view the button will still have the old content. Meaning that it doesn't update.

And I don't understand why.

Why does my button not update the content text?

Should I have properties in my ViewModel?

Body:
You have to implement INotifyPropertyChanged in your ViewModel.

public class MainViewModel : INotifyPropertyChanged
{
    public RelayCommand DoSomethingCommand { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

And you have to change your property to notify your View when the property was updated.

private string _btnName;
public string BtnName { get { return _btnName; } set { _btnName = value; OnPropertyChanged("BtnName"); } }


问:
Button onClick event
For a study  Project I try to make a sidebar for an interactive map.

I have a button which trigger an onClick() Event which Shows
a
 with an form Input.

So far I have 3 questions.

1) Can I check if the button was already clicked so I can hide my additional Content again? If so, how can I achieve that?

2) At the Moment I only display the content but I would like to have  an Animation. Again, you may give me some Infos to do this or provide an link / tutorial.

3) Is there a better Solution for my Problem, if so. May you give me a hint?

function showDropdown(x) {
  let id = x;

  if (id == 1) {
    document.getElementById("1").style.display = "block";
    console.log(id);
  }

  if (id == 2) {
    document.getElementById("2").style.display = "block";
    console.log(id);
  }

  if (id == 3) {
    document.getElementById("3").style.display = "block";
    console.log(id);
  } else {
    console.log(id);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-sidebar>ul {
  display: none;
}</code>```

        <button type="button" onclick="showDropdown(1)" class="dropdown-header">Einwohner</button>

Feld 1:<input type="text" Placeholder="a" size="2"

Feld 2:<input type="text" Placeholder="b" size="2"

Feld 3:<input type="text" Placeholder="c" size="2"

```

答:
1- Check if button is clicked.

You can do this by assigning a variable i=0 outside, and when you perform onClick operation makeit i=1, and before you perform onclick operations, check if the value is 1 or 0.

But there is another way of doing it using jquery.

Hide and show elements using jquery

If you want to do it in little animation way. use fade function in Jquery

Hide and show elements using fade()

if you want tutorial on side navigation bar

W3schools sidenav tutorial

Title: Button onClick event

Body:
For a study  Project I try to make a sidebar for an interactive map.

I have a button which trigger an onClick() Event which Shows
a
 with an form Input.

So far I have 3 questions.

1) Can I check if the button was already clicked so I can hide my additional Content again? If so, how can I achieve that?

2) At the Moment I only display the content but I would like to have  an Animation. Again, you may give me some Infos to do this or provide an link / tutorial.

3) Is there a better Solution for my Problem, if so. May you give me a hint?

function showDropdown(x) {
  let id = x;

  if (id == 1) {
    document.getElementById("1").style.display = "block";
    console.log(id);
  }

  if (id == 2) {
    document.getElementById("2").style.display = "block";
    console.log(id);
  }

  if (id == 3) {
    document.getElementById("3").style.display = "block";
    console.log(id);
  } else {
    console.log(id);
  }
}

.nav-sidebar>ul {
  display: none;
}

        <button type="button" onclick="showDropdown(1)" class="dropdown-header">Einwohner</button>

Feld 1:<input type="text" Placeholder="a" size="2"

Feld 2:<input type="text" Placeholder="b" size="2"

Feld 3:<input type="text" Placeholder="c" size="2"


问:
how to pass new parameter in loopback login?
i have a problem in login with looback i wanna add 3rd paramter

this is default code of loopback

```<code>```
 User.login({username: 'foo', password: 'bar'}, function (err, token) {
     console.log(token.id);
   });```
</code>```

i wanna pass a new parameter like

```<code>```User.login({username: 'foo', password: 'bar',is_deleted:'0'}, function (err, token) {
     console.log(token.id);
   });```
</code>```

i also try pass third parameter is_deleted=0 but it is not worked in my case

答:
You can do login by following combination:

username & password

email & password

So if you want to inject some logic before login then you can use operation hooks, do some stuff and perform login with any of above mentioned combination.

Sample code :

```<code>extentedUser.beforeRemote('login', function (context, user, next) {
      // Do some operation or validation here
      next();
  });
</code>```

Body:
i have a problem in login with looback i wanna add 3rd paramter

this is default code of loopback

 User.login({username: 'foo', password: 'bar'}, function (err, token) {
     console.log(token.id);
   });

i wanna pass a new parameter like

User.login({username: 'foo', password: 'bar',is_deleted:'0'}, function (err, token) {
     console.log(token.id);
   });

i also try pass third parameter is_deleted=0 but it is not worked in my case

Body:
You can do login by following combination:

username & password

email & password

So if you want to inject some logic before login then you can use operation hooks, do some stuff and perform login with any of above mentioned combination.

Sample code :

extentedUser.beforeRemote('login', function (context, user, next) {
      // Do some operation or validation here
      next();
  });


问:
Use invokeLater to show dialogs one by one
In 2 different action listeners, a dialog will be shown when some conditions are met.
If both of the action listeners need to show dialog, 2 dialogs will be shown at the same time. But I want them to be shown one by one.

Simplified code:

```<code>        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JOptionPane.showMessageDialog(getTopLevelAncestor(), "dialog 1");
            }
        });

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JOptionPane.showMessageDialog(getTopLevelAncestor(), "dialog 2");
            }
        });
</code>```

Those 2 "SwingUtilities.invokeLater" invocations are in different classes.

答:
This is related to the modality of dialogs. There is quite useful article about this topic http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/modality/. Dialogs have different modality types with different priorities. You can solve your problem by creating the second dialog with lower priority:

```<code>JOptionPane pane = new JOptionPane("dialog 2", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog("Message");
dialog.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
dialog.setVisible(true);
</code>```

Hopefully this helps.

Body:
In 2 different action listeners, a dialog will be shown when some conditions are met.
If both of the action listeners need to show dialog, 2 dialogs will be shown at the same time. But I want them to be shown one by one.

Simplified code:

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JOptionPane.showMessageDialog(getTopLevelAncestor(), "dialog 1");
            }
        });

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JOptionPane.showMessageDialog(getTopLevelAncestor(), "dialog 2");
            }
        });

Those 2 "SwingUtilities.invokeLater" invocations are in different classes.

Body:
This is related to the modality of dialogs. There is quite useful article about this topic http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/modality/. Dialogs have different modality types with different priorities. You can solve your problem by creating the second dialog with lower priority:

JOptionPane pane = new JOptionPane("dialog 2", JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog("Message");
dialog.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
dialog.setVisible(true);

Hopefully this helps.


问:
php allow access to pages to only logged in users
I have 3 pages have html code similar to just example

<!DOCTYPE html>

html code

html code

html code

```

and have 2 php files login.php and logout.php , is it possible to strict access to the 3 pages only to login users

答:
First, Put in header page this session_start();, Ofcourse the header page is included||required in every php page you have.

Second, When the user Login using your Login page, Put the sessions if his data are valid

```<code><?php
if($user && password_verify($password, $user['password'])){
     $_SESSION['id'] = $user['id'];
}
 ?>
</code>```

In this one we used his id inside session, Now all you have to do is checking if this session is active, If it is not active, You redirect the visitor using header() to the index||404 page like this

```<code><?php
if(!isset($_SESSION['id'])){
    die(header("location: 404.php"));
}
?>
</code>```

and remove the ! for signup & login pages, Since you don't want a logged in user to access the login or register page again.

Third, For logout page, Just put

```<code><?php
session_start();
session_unset();
session_destroy();
header("location: index.php");
exit();
?>
</code>```

inside it

Body:
I have 3 pages have html code similar to just example

<!DOCTYPE html>

html code

html code

html code

and have 2 php files login.php and logout.php , is it possible to strict access to the 3 pages only to login users

Body:
First, Put in header page this session_start();, Ofcourse the header page is included||required in every php page you have.

Second, When the user Login using your Login page, Put the sessions if his data are valid

<?php
if($user && password_verify($password, $user['password'])){
     $_SESSION['id'] = $user['id'];
}
 ?>

In this one we used his id inside session, Now all you have to do is checking if this session is active, If it is not active, You redirect the visitor using header() to the index||404 page like this

<?php
if(!isset($_SESSION['id'])){
    die(header("location: 404.php"));
}
?>

and remove the ! for signup & login pages, Since you don't want a logged in user to access the login or register page again.

Third, For logout page, Just put

<?php
session_start();
session_unset();
session_destroy();
header("location: index.php");
exit();
?>

inside it


问:
How to identify particular descendant element found under first-or-second descendant of another element
Please suggest to identify the MFENCED, which is having MFRAC as descendant of MSUB or not.

Here some scenarios mentioned as below to stretch the MFENCED (inserting one attribute):

If MFRAC found and which is not under MSUB, then attribute STRETCH

required for MFENCED.

If MFRAC found as descendant to MFENCED and
under FIRST-CHILD-DESCENDANT of MSUB, then STRETCH required.

In third MATH from input xml, 2nd MFENCED required STRETCH, even that MFRAC descendant of 2nd child descendant of MSUB, but with within that MFENCED, MFRAC is not having MSUB as its ancestor.

Newly added further explanations:

If MFENCED under (descendant from (this) present MFENCED) any MFRAC found, then that MFENCED can stretch, where MFENCE/ancestor should not, because, with respect to main MFENCE, FRAC found under subs 2nd child-descendant. If not clear, i will give further explanations.

Input XML:

```<code><article>

<math>
    <mrow>
        <mfenced open="(" close=")">
            <!--stretch required -->
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                            <mrow><mn>9999</mn></mrow>
                            <mrow>
                                <mfenced open="(" close=")">
                                    <!--stretch required -->
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

<math>
    <mrow>
        <mfenced open="(" close=")"><!--Stretch  required, bcs descendant Frac, found as first child of msub, if descendant mfrac, found under (descendant) second child of MSUB, then no need to stretch-->
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                        <msub>
                            <mrow>
                                <mfenced open="(" close=")"><!--Stretch required, because under this mfen, 'mfrac' found under first child of 'msub' -->
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                            <mrow><mn>9999</mn></mrow>
                        </msub>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

<math>
    <mrow>
        <mfenced open="(" close=")"><!-- this mfence, no need to stretch, because, descendant MFRAC found under second child-descendant of MSUB -->
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                        <msub>
                            <mrow><mn>9999</mn></mrow>
                            <mrow>
                                <mfenced open="(" close=")"><!--Stretch required, because under this mfen, 'mfrac' found (even MFRAC under 2nd child-descendant of MSUB, but under existing MFENCE, MFRAC is not having ancestor MSUB -->
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                        </msub>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>
</article>
</code>```

XSLT 2.0:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mfenced">
    <xsl:variable name="varFrac">
        <xsl:for-each select="descendant::mfenced">
            <xsl:for-each select="descendant::*[name()='mfrac']">
                <xsl:choose>
                    <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]
                        [generate-id(ancestor::mmlmfenced[1])=generate-id(current()/ancestor::mmlmfenced[1])])">Yes2</xsl:when>
                    <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]
                        [generate-id(ancestor::mmlmfenced[1])=generate-id(current()/ancestor::mmlmfenced[1])])">Yes21</xsl:when>
                </xsl:choose>
            </xsl:for-each>
        </xsl:for-each>

        <xsl:for-each select="descendant::*[name()='mfrac']">
            <xsl:choose>
                <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes1a</xsl:when>
                <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes11a</xsl:when>
            </xsl:choose>
        </xsl:for-each>
    </xsl:variable>

        <xsl:choose>
            <xsl:when test="contains($varFrac, 'Yes')">
                <xsl:copy>
                    <xsl:apply-templates select="@*"/>
                    <xsl:attribute name="stretchy">true</xsl:attribute>
                    <xsl:apply-templates select="node()"/>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
</xsl:template>

</xsl:stylesheet>
</code>```

Required result:

```<code><article>
<math>
  <mrow>
     <mfenced open="(" close=")" stretchy="true">
          <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <mrow>
                 <mn>9999</mn>
              </mrow>
              <mrow>
                 <mfenced open="(" close=")" stretchy="true">
                    <mrow>
                       <mfrac>
                          <mi>a</mi>
                          <mi>b</mi>
                       </mfrac>
                    </mrow>
                 </mfenced>
              </mrow>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

<math>
  <mrow>
     <mfenced open="(" close=")" stretchy="true">
        <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <msub>
                 <mrow>
                    <mfenced open="(" close=")" stretchy="true">
                        <mrow>
                          <mfrac>
                             <mi>a</mi>
                             <mi>b</mi>
                          </mfrac>
                       </mrow>
                    </mfenced>
                 </mrow>
                 <mrow>
                    <mn>9999</mn>
                 </mrow>
              </msub>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

<math>
  <mrow>
     <mfenced open="(" close=")">
        <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <msub>
                 <mrow>
                    <mn>9999</mn>
                 </mrow>
                 <mrow>
                    <mfenced open="(" close=")" stretchy="true"><!-- Here stretch required -->
                        <mrow>
                          <mfrac>
                             <mi>a</mi>
                             <mi>b</mi>
                          </mfrac>
                       </mrow>
                    </mfenced>
                 </mrow>
              </msub>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>
</article>
</code>```

答:
If MFRAC found and which is not under MSUB, then attribute STRETCH
  required for MFENCED.

```<code><xsl:template match="mfenced[.//mfrac except .//msub//mfrac]">
  <xsl:copy>
   <xsl:attribute name="stretchy">true</xsl:attribute>
   <xsl:apply-templates select="@*, node()"/>
  </xsl:copy>
</xsl:template>
</code>```

If MFRAC found as descendant to MFENCED and under
  FIRST-CHILD-DESCENDANT of MSUB, then STRETCH required.

```<code><xsl:template match="mfenced[.//msub/*[1]//mfrac]">
  <xsl:copy>
    <xsl:attribute name="stretchy">true</xsl:attribute>
    <xsl:apply-templates select="@*, node()"/>
  </xsl:copy>
</xsl:template>
</code>```

In third MATH from input xml, 2nd MFENCED required STRETCH, even that
  MFRAC descendant of 2nd child descendant of MSUB, but with within that
  MFENCED, MFRAC is not having MSUB as its ancestor.

I'm sorry, I don't understand your English here.

Body:
Please suggest to identify the MFENCED, which is having MFRAC as descendant of MSUB or not.

Here some scenarios mentioned as below to stretch the MFENCED (inserting one attribute):

If MFRAC found and which is not under MSUB, then attribute STRETCH

required for MFENCED.

If MFRAC found as descendant to MFENCED and
under FIRST-CHILD-DESCENDANT of MSUB, then STRETCH required.

In third MATH from input xml, 2nd MFENCED required STRETCH, even that MFRAC descendant of 2nd child descendant of MSUB, but with within that MFENCED, MFRAC is not having MSUB as its ancestor.

Newly added further explanations:

If MFENCED under (descendant from (this) present MFENCED) any MFRAC found, then that MFENCED can stretch, where MFENCE/ancestor should not, because, with respect to main MFENCE, FRAC found under subs 2nd child-descendant. If not clear, i will give further explanations.

Input XML:

<math>
    <mrow>
        <mfenced open="(" close=")">

            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                            <mrow><mn>9999</mn></mrow>
                            <mrow>
                                <mfenced open="(" close=")">

                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

<math>
    <mrow>
        <mfenced open="(" close=")">
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                        <msub>
                            <mrow>
                                <mfenced open="(" close=")">
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                            <mrow><mn>9999</mn></mrow>
                        </msub>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

<math>
    <mrow>
        <mfenced open="(" close=")">
            <mrow>
                <mrow><mn>99999</mn></mrow>
                    <mrow>
                        <msub>
                            <mrow><mn>9999</mn></mrow>
                            <mrow>
                                <mfenced open="(" close=")">
                                    <mrow>
                                        <mfrac><mi>a</mi><mi>b</mi></mfrac>
                                    </mrow>
                                </mfenced>
                            </mrow>
                        </msub>
                    </mrow>
                </mrow>
        </mfenced>
    </mrow>
</math>

XSLT 2.0:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mfenced">
    <xsl:variable name="varFrac">
        <xsl:for-each select="descendant::mfenced">
            <xsl:for-each select="descendant::*[name()='mfrac']">
                <xsl:choose>
                    <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]
                        [generate-id(ancestor::mmlmfenced[1])=generate-id(current()/ancestor::mmlmfenced[1])])">Yes2</xsl:when>
                    <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')]
                        [generate-id(ancestor::mmlmfenced[1])=generate-id(current()/ancestor::mmlmfenced[1])])">Yes21</xsl:when>
                </xsl:choose>
            </xsl:for-each>
        </xsl:for-each>

        <xsl:for-each select="descendant::*[name()='mfrac']">
            <xsl:choose>
                <xsl:when  test="not(ancestor::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes1a</xsl:when>
                <xsl:when  test="(ancestor-or-self::*/parent::*[not(preceding-sibling::*)]/parent::*[matches(name(), '^(msubsup|msub|msup|munder|munderover|mover|msqrt|mroot)$')])">Yes11a</xsl:when>
            </xsl:choose>
        </xsl:for-each>
    </xsl:variable>

        <xsl:choose>
            <xsl:when test="contains($varFrac, 'Yes')">
                <xsl:copy>
                    <xsl:apply-templates select="@*"/>
                    <xsl:attribute name="stretchy">true</xsl:attribute>
                    <xsl:apply-templates select="node()"/>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
</xsl:template>

</xsl:stylesheet>

Required result:

<math>
  <mrow>
     <mfenced open="(" close=")" stretchy="true">
          <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <mrow>
                 <mn>9999</mn>
              </mrow>
              <mrow>
                 <mfenced open="(" close=")" stretchy="true">
                    <mrow>
                       <mfrac>
                          <mi>a</mi>
                          <mi>b</mi>
                       </mfrac>
                    </mrow>
                 </mfenced>
              </mrow>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

<math>
  <mrow>
     <mfenced open="(" close=")" stretchy="true">
        <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <msub>
                 <mrow>
                    <mfenced open="(" close=")" stretchy="true">
                        <mrow>
                          <mfrac>
                             <mi>a</mi>
                             <mi>b</mi>
                          </mfrac>
                       </mrow>
                    </mfenced>
                 </mrow>
                 <mrow>
                    <mn>9999</mn>
                 </mrow>
              </msub>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

<math>
  <mrow>
     <mfenced open="(" close=")">
        <mrow>
           <mrow>
              <mn>99999</mn>
           </mrow>
           <mrow>
              <msub>
                 <mrow>
                    <mn>9999</mn>
                 </mrow>
                 <mrow>
                    <mfenced open="(" close=")" stretchy="true">
                        <mrow>
                          <mfrac>
                             <mi>a</mi>
                             <mi>b</mi>
                          </mfrac>
                       </mrow>
                    </mfenced>
                 </mrow>
              </msub>
           </mrow>
        </mrow>
     </mfenced>
  </mrow>
</math>

Body:
If MFRAC found and which is not under MSUB, then attribute STRETCH
  required for MFENCED.

<xsl:template match="mfenced[.//mfrac except .//msub//mfrac]">
  <xsl:copy>
   <xsl:attribute name="stretchy">true</xsl:attribute>
   <xsl:apply-templates select="@*, node()"/>
  </xsl:copy>
</xsl:template>

If MFRAC found as descendant to MFENCED and under
  FIRST-CHILD-DESCENDANT of MSUB, then STRETCH required.

<xsl:template match="mfenced[.//msub/*[1]//mfrac]">
  <xsl:copy>
    <xsl:attribute name="stretchy">true</xsl:attribute>
    <xsl:apply-templates select="@*, node()"/>
  </xsl:copy>
</xsl:template>

In third MATH from input xml, 2nd MFENCED required STRETCH, even that
  MFRAC descendant of 2nd child descendant of MSUB, but with within that
  MFENCED, MFRAC is not having MSUB as its ancestor.

I'm sorry, I don't understand your English here.


问:
Moving row from bottom to the top of dataframe in pandas python
I have a dataframe like this:

```<code>      count  capacity  load  throughput
Obj1  14       34       NaN     NaN

Obj2  42       NaN       30      51

Obj3  34       NaN       20      15

Obj4  23       44        NaN     NaN

0     25       20        Nan     40
</code>```

And now I need to put the last row above the columns names.

```<code>       0     25       20       Nan     40
            count  capacity   load  throughput
    Obj1     14       34       NaN     NaN

    Obj2     42       NaN       30      51

    Obj3     34       NaN       20      15

    Obj4     23       44       NaN     NaN
</code>```

That null left-top can stay, but it's not necessary.
Is it even possible?

答:
I think you need iloc for selecting last row and also for removing:

```<code>df.columns = [df.iloc[-1],df.columns]
df = df.iloc[:-1]
#if need remove columns names
df.columns.names = (None, None)
print (df)
        25     20.0  Nan       40.0
     count capacity load throughput
Obj1    14     34.0  NaN        NaN
Obj2    42      NaN   30       51.0
Obj3    34      NaN   20       15.0
Obj4    23     44.0  NaN        NaN
</code>```

Body:
I have a dataframe like this:

      count  capacity  load  throughput
Obj1  14       34       NaN     NaN

Obj2  42       NaN       30      51

Obj3  34       NaN       20      15

Obj4  23       44        NaN     NaN

0     25       20        Nan     40

And now I need to put the last row above the columns names.

       0     25       20       Nan     40
            count  capacity   load  throughput
    Obj1     14       34       NaN     NaN

    Obj2     42       NaN       30      51

    Obj3     34       NaN       20      15

    Obj4     23       44       NaN     NaN

That null left-top can stay, but it's not necessary.
Is it even possible?

Body:
I think you need iloc for selecting last row and also for removing:

df.columns = [df.iloc[-1],df.columns]
df = df.iloc[:-1]
#if need remove columns names
df.columns.names = (None, None)
print (df)
        25     20.0  Nan       40.0
     count capacity load throughput
Obj1    14     34.0  NaN        NaN
Obj2    42      NaN   30       51.0
Obj3    34      NaN   20       15.0
Obj4    23     44.0  NaN        NaN


问:
Trying to get the element in xslt 1.0.But unable to get in response xml
Reqeust xml is attached

```<code><xsl:if test="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:id/evt0:idContext/evt0:value">
        <tns:projectIdentifier>

                        <tns:idContext>
                                                            <tns:value>
                                    <xsl:value-of
                                        select="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:id/evt0:idContext/evt0:value" />
                                </tns:value>
                                </tns:idContext>
                                                    [Response xsd attached][2]

                </tns:projectIdentifier>
</code>```

This is the xsl code that is written but not working

答:
Check this Code I think your problem solve</p>

```<code><xsl:if test="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:idContext/evt0:value">
<tns:projectIdentifier>
<tns:idContext>
<tns:value>
<xsl:value-of select="//evt0:value" />
</tns:value>
</tns:idContext>
</tns:projectIdentifier>
</code>```

Body:
Reqeust xml is attached

<xsl:if test="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:id/evt0:idContext/evt0:value">
        <tns:projectIdentifier>

                        <tns:idContext>
                                                            <tns:value>
                                    <xsl:value-of
                                        select="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:id/evt0:idContext/evt0:value" />
                                </tns:value>
                                </tns:idContext>
                                                    [Response xsd attached][2]

                </tns:projectIdentifier>

This is the xsl code that is written but not working

Body:
Check this Code I think your problem solve

<xsl:if test="../tn:notification/evt0:relationship/evt0:businessInteractionIdentifier/evt0:customerOrderIdentifier/evt0:idContext/evt0:value">
<tns:projectIdentifier>
<tns:idContext>
<tns:value>
<xsl:value-of select="//evt0:value" />
</tns:value>
</tns:idContext>
</tns:projectIdentifier>


问:
Flex IBM ILOG (Elixir 3.0) Interactive map
I develop interactive map: user can zoom some area and place labels by mouse click.
I am creating customSkin:

```<code><ibm:Scroller top="0" left="0" width="100%" height="100%" id="scroller" doubleClickEnabled="true"
skinClass="com.ibm.ilog.elixir.skins.spark.ScrollerSkin">
<ibm:MapGroup id="mapGroup">
<ibm:MapFeatureGroup id="featureGroup" featureRenderer="skins.DistrictRenderer" keyField="district"/>
<ibm:MapDataGroup id="objectsDataGroup"
zoomable="false"
itemRenderer="skins.DistrictObjectsRenderer"
keyField="district" />
</ibm:MapGroup>
</ibm:Scroller>
</code>```

In DistrictRenderer I dispatching mouse click.
But how can I place labels?
May be I must pass x,y to DistrictObjectsRenderer and there create new labels?

答:
Its a final solution:

RegionMapSkin.mxml:

```<code><ibm:Scroller top="0" left="0" width="100%" height="100%" id="scroller" skinClass="com.ibm.ilog.elixir.skins.spark.ScrollerSkin">
    <ibm:MapGroup id="mapGroup">
        <ibm:MapFeatureGroup id="featureGroup"
                             featureRenderer="com.skins.DistrictRenderer" />
    <ibm:MapDataGroup id="objectsGroup"
                          zoomable="false"
                          itemRenderer="com.skins.ObjectsRenderer"
                          dataProvider="{ObjectsModel.getInstance().items}" />
    </ibm:MapGroup>
</ibm:Scroller>
</code>```

ObjectsRenderer.mxml:

```<code><?xml version="1.0" encoding="utf-8"?>
<s:DataRenderer xmlns="http://ns.adobe.com/mxml/2009"
            xmlns:s="library://ns.adobe.com/flex/spark"
            xmlns:mx="library://ns.adobe.com/flex/mx"
            xmlns:ibm="http://www.ibm.com/xmlns/prod/ilog/elixir/2010"

            left="{data.lon}"
            top="{data.lat}">
    <s:Label text="{data.title}"
         color="#ffffff"
         backgroundColor="#AB191A"
         paddingLeft="3" paddingRight="3" paddingTop="4" paddingBottom="1"
         top="-18" left="3"/>

    <s:Ellipse width="6" height="6">
        <s:fill>
            <s:SolidColor color="#AB191A" />
        </s:fill>
    </s:Ellipse>
</s:DataRenderer>
</code>```

And onMouseClick handler in DistrictRenderer:

```<code>private function onMouseClick(e:MouseEvent):void
{
    var mapFeature:MapFeature = MapFeatureRenderer(e.currentTarget).mapFeature;
    var map:RegionMap = app.map;
    var p:Point = new Point(e.localX, e.localY);
    p = map.mapToLongLat(p);
    ObjectsModel.getInstance().items.addItem({
        'title': parameters.title,
        'lon': parameters.lon,
        'lat': parameters.lat
    });
}
</code>```

Body:
I develop interactive map: user can zoom some area and place labels by mouse click.
I am creating customSkin:

<ibm:Scroller top="0" left="0" width="100%" height="100%" id="scroller" doubleClickEnabled="true"
skinClass="com.ibm.ilog.elixir.skins.spark.ScrollerSkin">
<ibm:MapGroup id="mapGroup">
<ibm:MapFeatureGroup id="featureGroup" featureRenderer="skins.DistrictRenderer" keyField="district"/>
<ibm:MapDataGroup id="objectsDataGroup"
zoomable="false"
itemRenderer="skins.DistrictObjectsRenderer"
keyField="district" />
</ibm:MapGroup>
</ibm:Scroller>

In DistrictRenderer I dispatching mouse click.
But how can I place labels?
May be I must pass x,y to DistrictObjectsRenderer and there create new labels?

Body:
Its a final solution:

RegionMapSkin.mxml:

<ibm:Scroller top="0" left="0" width="100%" height="100%" id="scroller" skinClass="com.ibm.ilog.elixir.skins.spark.ScrollerSkin">
    <ibm:MapGroup id="mapGroup">
        <ibm:MapFeatureGroup id="featureGroup"
                             featureRenderer="com.skins.DistrictRenderer" />
    <ibm:MapDataGroup id="objectsGroup"
                          zoomable="false"
                          itemRenderer="com.skins.ObjectsRenderer"
                          dataProvider="{ObjectsModel.getInstance().items}" />
    </ibm:MapGroup>
</ibm:Scroller>

ObjectsRenderer.mxml:

<?xml version="1.0" encoding="utf-8"?>
<s:DataRenderer xmlns="http://ns.adobe.com/mxml/2009"
            xmlns:s="library://ns.adobe.com/flex/spark"
            xmlns:mx="library://ns.adobe.com/flex/mx"
            xmlns:ibm="http://www.ibm.com/xmlns/prod/ilog/elixir/2010"

            left="{data.lon}"
            top="{data.lat}">
    <s:Label text="{data.title}"
         color="#ffffff"
         backgroundColor="#AB191A"
         paddingLeft="3" paddingRight="3" paddingTop="4" paddingBottom="1"
         top="-18" left="3"/>

    <s:Ellipse width="6" height="6">
        <s:fill>
            <s:SolidColor color="#AB191A" />
        </s:fill>
    </s:Ellipse>
</s:DataRenderer>

And onMouseClick handler in DistrictRenderer:

private function onMouseClick(e:MouseEvent):void
{
    var mapFeature:MapFeature = MapFeatureRenderer(e.currentTarget).mapFeature;
    var map:RegionMap = app.map;
    var p:Point = new Point(e.localX, e.localY);
    p = map.mapToLongLat(p);
    ObjectsModel.getInstance().items.addItem({
        'title': parameters.title,
        'lon': parameters.lon,
        'lat': parameters.lat
    });
}


问:
What is the expected result when pushing onto a full (virtual) CPU stack?
Something of an irony when posting a question to a site called stackoverflow - but here goes.

I have the following specification for a virtual CPU to be implemented in software (I'm choosing Java).

Each CPU of this virtual computer contains two address registers, two numeric registers, a flags register to indicate error conditions, a stack pointer, a ten word stack, and an instruction pointer

For my ten word stack I need to define what happens when you push to it when it is full. The writer of the specification has left this as assumed knowledge.

The structure of the CPU (if it were hypothetically defined in C) - is defined as follows:

```<code>struct cpu {  /* structure for registers of virtual cpu */
int   ax;  /* address register */
int   bx;  /* address register */
int   cx;  /* numerical register */
int   dx;  /* numerical register */
char  fl;  /* flag */
char  sp;  /* stack pointer */
int   st[10];  /* stack */
int ip; /* instruction pointer */ }
</code>```

The CPU operations I have for the stack are:

```<code>case 0x0c: push_ax(ci);  break; /* push ax on stack */
case 0x0d: push_bx(ci);  break; /* push bx on stack */
case 0x0e: push_cx(ci);  break; /* push cx on stack */
case 0x0f: push_dx(ci);  break; /* push dx on stack */
case 0x10: pop_ax(ci);   break; /* pop to of stack into ax */
case 0x11: pop_bx(ci);   break; /* pop to of stack into bx */
case 0x12: pop_cx(ci);   break; /* pop to of stack into cx */
case 0x13: pop_dx(ci);   break; /* pop to of stack into dx */
</code>```

Is it normal behaviour to get a stack overflow in this situation? (Pushing to a full stack).

The other hypothetical possibility is simply to kick off the bottom of the stack. (Stack as FIFO queue with size limit).

My question is: What is the expected result when pushing onto a full (virtual) CPU stack?

答: You can treat it as a software error in the program you are running and raise some form of hardware exception. The same way you'd be doing when a division by zero is encountered.</p>

Body:
Something of an irony when posting a question to a site called stackoverflow - but here goes.

I have the following specification for a virtual CPU to be implemented in software (I'm choosing Java).

Each CPU of this virtual computer contains two address registers, two numeric registers, a flags register to indicate error conditions, a stack pointer, a ten word stack, and an instruction pointer

For my ten word stack I need to define what happens when you push to it when it is full. The writer of the specification has left this as assumed knowledge.

The structure of the CPU (if it were hypothetically defined in C) - is defined as follows:

struct cpu {  /* structure for registers of virtual cpu */
int   ax;  /* address register */
int   bx;  /* address register */
int   cx;  /* numerical register */
int   dx;  /* numerical register */
char  fl;  /* flag */
char  sp;  /* stack pointer */
int   st[10];  /* stack */
int ip; /* instruction pointer */ }

The CPU operations I have for the stack are:

case 0x0c: push_ax(ci);  break; /* push ax on stack */
case 0x0d: push_bx(ci);  break; /* push bx on stack */
case 0x0e: push_cx(ci);  break; /* push cx on stack */
case 0x0f: push_dx(ci);  break; /* push dx on stack */
case 0x10: pop_ax(ci);   break; /* pop to of stack into ax */
case 0x11: pop_bx(ci);   break; /* pop to of stack into bx */
case 0x12: pop_cx(ci);   break; /* pop to of stack into cx */
case 0x13: pop_dx(ci);   break; /* pop to of stack into dx */

Is it normal behaviour to get a stack overflow in this situation? (Pushing to a full stack).

The other hypothetical possibility is simply to kick off the bottom of the stack. (Stack as FIFO queue with size limit).

My question is: What is the expected result when pushing onto a full (virtual) CPU stack?


问:
Ucanaccess_net.ucanaccess.jdbc.DBReference@ac6b76 folder
I am using UcanAccess(net.ucanaccess.jdbc.UcanaccessDriver) Driver to connect with MS Access Database ,I am able to interact with database but every time i start my server and db is loaded ,a file folder with name "Ucanaccess_net.ucanaccess.jdbc.DBReference@194ac0b" is created on Desktop with the same size of DB(approx 250 MB).

Could any one provide solution?
Thanks

答: It sounds like you are using the memory=false connection option. In that case, the default location for the HSQLDB backing database is the same folder as the Access database file. You can use mirrorFolder=<path> to change the location where the backing database is stored.


问:
program crashing when allocating space for structures
I am having trouble allocating nodes for my graph. Here are my structures defined in my header:

```<code>typedef struct Graph {
    struct Node**  _node_list;
    int                   _sz;
} Graph;

typedef struct Node {
    char    *code;
    char    **_outgoing_arcs;
    int     _sz;
} Node;
</code>```

and here are my allocation functions:

```<code>Graph* allocGraph(int sz)
{
    Graph *g;
    g = malloc(1000);
    g->_sz = 0;
    return g;
}

Node* allocNode(char *c, Graph *g)
{
    Node *n;

    n = malloc(1000);
    strncpy(n->code,c,3);
    g->_node_list[g->_sz] = n;
    g->_sz += 1;

    return n;
}
</code>```

I can allocate graphs just fine, but when I try to allocate nodes my program crashes. Did I not do strncpy correctly? It always takes input of strings 3 long "ABC", "FOO" ...

答:
Node

There is no allocation for memory where your char points to.

Your allocation for Node has been done.
But your element *code points no-where or to undefined memory.

You have to additionally allocate memory for this, so:

```<code>g->code = malloc(4);  //Allocate memory for 3 characters + 0 at the end.
strncpy(g->code, c, 3);
</code>```

Graph

Another problem is allocation of pointers for your nodes in graph:

```<code>//Allocate memory for pointers. Array of pointers.
h->_node_list = malloc(max_number_of_nodes * sizeof(Node*))
</code>```

And for both, instead of using malloc(1000) in your cases, use:

```<code>g = malloc(sizeof Graph); //For graph
g = malloc(sizeof Node);  //For node
</code>```

Even better approach is to clear memory after you allocate it.

```<code>g = malloc(sizeof Graph); //For graph
memset(g, 0x00, sizeof Graph);

g = malloc(sizeof Node);  //For node
memset(g, 0x00, NodeGraph);
</code>```

Now your members will be reset and you can start set other pointers and allocations.

Body:
I am having trouble allocating nodes for my graph. Here are my structures defined in my header:

typedef struct Graph {
    struct Node**  _node_list;
    int                   _sz;
} Graph;

typedef struct Node {
    char    *code;
    char    **_outgoing_arcs;
    int     _sz;
} Node;

and here are my allocation functions:

Graph* allocGraph(int sz)
{
    Graph *g;
    g = malloc(1000);
    g->_sz = 0;
    return g;
}

Node* allocNode(char *c, Graph *g)
{
    Node *n;

    n = malloc(1000);
    strncpy(n->code,c,3);
    g->_node_list[g->_sz] = n;
    g->_sz += 1;

    return n;
}

I can allocate graphs just fine, but when I try to allocate nodes my program crashes. Did I not do strncpy correctly? It always takes input of strings 3 long "ABC", "FOO" ...

Body:
Node

There is no allocation for memory where your char points to.

Your allocation for Node has been done.
But your element *code points no-where or to undefined memory.

You have to additionally allocate memory for this, so:

g->code = malloc(4);  //Allocate memory for 3 characters + 0 at the end.
strncpy(g->code, c, 3);

Graph

Another problem is allocation of pointers for your nodes in graph:

//Allocate memory for pointers. Array of pointers.
h->_node_list = malloc(max_number_of_nodes * sizeof(Node*))

And for both, instead of using malloc(1000) in your cases, use:

g = malloc(sizeof Graph); //For graph
g = malloc(sizeof Node);  //For node

Even better approach is to clear memory after you allocate it.

g = malloc(sizeof Graph); //For graph
memset(g, 0x00, sizeof Graph);

g = malloc(sizeof Node);  //For node
memset(g, 0x00, NodeGraph);

Now your members will be reset and you can start set other pointers and allocations.


问:
is possible to link a DNS name to another DNS name in docker?
I'm kind of new on docker. I want to resolve DNS name into something define by the user. I mean, I have a service in docker which requires another service located in 'myEndpoint'. I want to configure that when the service asked to 'myEndpoint' returns an IP/FQN I decide, either in the containers or outside.

How I can do this?

答:
If you just want to map myEndpoing to a specific IP, you could use option --add-host when docker run ... your container. Take a look at the following example:

```<code> ~/ docker run --add-host=myEndpoint:123.124.125.126 --rm alpine:3.3 ping myEndpoint -c 4
PING myEndpoint (123.124.125.126): 56 data bytes
64 bytes from 123.124.125.126: seq=0 ttl=37 time=0.522 ms
64 bytes from 123.124.125.126: seq=1 ttl=37 time=0.391 ms
64 bytes from 123.124.125.126: seq=2 ttl=37 time=2.161 ms
64 bytes from 123.124.125.126: seq=3 ttl=37 time=0.488 ms

--- myEndpoint ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 0.391/0.890/2.161 ms
</code>```

You can refer to the docs of docker run for more details.

But if you want to map myEndpoint to other domain name, I think you need to use a FQDN and configure it as a CNAME DNS record, then configure DNS server for your container with option --dns options when you do docker run .... Hope this could be helpful :)

Body:
If you just want to map myEndpoing to a specific IP, you could use option --add-host when docker run ... your container. Take a look at the following example:

 ~/ docker run --add-host=myEndpoint:123.124.125.126 --rm alpine:3.3 ping myEndpoint -c 4
PING myEndpoint (123.124.125.126): 56 data bytes
64 bytes from 123.124.125.126: seq=0 ttl=37 time=0.522 ms
64 bytes from 123.124.125.126: seq=1 ttl=37 time=0.391 ms
64 bytes from 123.124.125.126: seq=2 ttl=37 time=2.161 ms
64 bytes from 123.124.125.126: seq=3 ttl=37 time=0.488 ms

--- myEndpoint ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 0.391/0.890/2.161 ms

You can refer to the docs of docker run for more details.

But if you want to map myEndpoint to other domain name, I think you need to use a FQDN and configure it as a CNAME DNS record, then configure DNS server for your container with option --dns options when you do docker run .... Hope this could be helpful :)


问:
Formatting a Double to a String with two numbers after the coma using Jasper
I have a jrxml file in which i have two Double values that  want to format to String with two numbers after the coma so here is my fields

```<code><field name="montantRachat" class="java.lang.Double">
        <fieldDescription><![CDATA[montantRachat]]></fieldDescription>
</field>
<variable name="total" class="java.lang.Double" calculation="Sum">
        <variableExpression><![CDATA[$F{montantRachat}]]></variableExpression>
        <initialValueExpression><![CDATA[new Double(0)]]></initialValueExpression>
</variable>
</code>```

And i want to format them to string

```<code><variable name="totalString" class="java.lang.String">
        <variableExpression><![CDATA[(new DecimalFormat("#,###,##0.00")).format($V{total})]]></variableExpression>
</variable>
<variable name="montantRachatString" class="java.lang.String">
        <variableExpression><![CDATA[(new DecimalFormat("#,###,##0.00")).format($F{montantRachat})]]></variableExpression>
</variable>
</code>```

But i get this exception

```<code>net.sf.jasperreports.engine.JRException: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
    Source text : (new DecimalFormat("#,###,##0.00")).format($V{total})

    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.fillReport(ReportControler.java:466)

    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.access$18(ReportControler.java:441)

    at com.jaspersoft.studio.editor.preview.view.control.ReportControler$4.run(ReportControler.java:333)

    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

Caused by: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
    Source text : (new DecimalFormat("#,###,##0.00")).format($V{total})

    at net.sf.jasperreports.engine.fill.JREvaluator.evaluateEstimated(JREvaluator.java:327)

    at net.sf.jasperreports.engine.fill.JRCalculator.evaluateEstimated(JRCalculator.java:602)

    at net.sf.jasperreports.engine.fill.JRCalculator.estimateVariables(JRCalculator.java:201)

    at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1261)

    at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1235)

    at net.sf.jasperreports.engine.fill.JRBaseFiller.next(JRBaseFiller.java:1614)

    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:150)

    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:963)

    at net.sf.jasperreports.engine.fill.BaseFillHandle$ReportFiller.run(BaseFillHandle.java:120)

    at java.lang.Thread.run(Unknown Source)

Caused by: java.lang.IllegalArgumentException

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

    at java.lang.reflect.Method.invoke(Unknown Source)

    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:189)

    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)

    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)

    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)

    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)

    at ORV45rapport45pdf_subreport_1490866646896_381083.evaluateEstimated(calculator_ORV45rapport45pdf_subreport_1490866646896_381083:355)

    at net.sf.jasperreports.engine.fill.JREvaluator.evaluateEstimated(JREvaluator.java:314)

    ... 9 more
</code>```

Am i missing something ?

答:
Here's an easier way of doing it. Instead of creating another variable of type String that will format and display the number, you can have a TextField and set its pattern to #,##0.00#.

```<code><textField pattern="#,##0.00#">
    <reportElement x="455" y="0" width="100" height="30"/>
    <textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
</textField>
</code>```

Body:
I have a jrxml file in which i have two Double values that  want to format to String with two numbers after the coma so here is my fields

<field name="montantRachat" class="java.lang.Double">
        <fieldDescription><![CDATA[montantRachat]]></fieldDescription>
</field>
<variable name="total" class="java.lang.Double" calculation="Sum">
        <variableExpression><![CDATA[$F{montantRachat}]]></variableExpression>
        <initialValueExpression><![CDATA[new Double(0)]]></initialValueExpression>
</variable>

And i want to format them to string

<variable name="totalString" class="java.lang.String">
        <variableExpression><![CDATA[(new DecimalFormat("#,###,##0.00")).format($V{total})]]></variableExpression>
</variable>
<variable name="montantRachatString" class="java.lang.String">
        <variableExpression><![CDATA[(new DecimalFormat("#,###,##0.00")).format($F{montantRachat})]]></variableExpression>
</variable>

But i get this exception

net.sf.jasperreports.engine.JRException: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
    Source text : (new DecimalFormat("#,###,##0.00")).format($V{total})

    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.fillReport(ReportControler.java:466)

    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.access$18(ReportControler.java:441)

    at com.jaspersoft.studio.editor.preview.view.control.ReportControler$4.run(ReportControler.java:333)

    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

Caused by: net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
    Source text : (new DecimalFormat("#,###,##0.00")).format($V{total})

    at net.sf.jasperreports.engine.fill.JREvaluator.evaluateEstimated(JREvaluator.java:327)

    at net.sf.jasperreports.engine.fill.JRCalculator.evaluateEstimated(JRCalculator.java:602)

    at net.sf.jasperreports.engine.fill.JRCalculator.estimateVariables(JRCalculator.java:201)

    at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1261)

    at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1235)

    at net.sf.jasperreports.engine.fill.JRBaseFiller.next(JRBaseFiller.java:1614)

    at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:150)

    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:963)

    at net.sf.jasperreports.engine.fill.BaseFillHandle$ReportFiller.run(BaseFillHandle.java:120)

    at java.lang.Thread.run(Unknown Source)

Caused by: java.lang.IllegalArgumentException

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

    at java.lang.reflect.Method.invoke(Unknown Source)

    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:189)

    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)

    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)

    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)

    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)

    at ORV45rapport45pdf_subreport_1490866646896_381083.evaluateEstimated(calculator_ORV45rapport45pdf_subreport_1490866646896_381083:355)

    at net.sf.jasperreports.engine.fill.JREvaluator.evaluateEstimated(JREvaluator.java:314)

    ... 9 more

Am i missing something ?

Body:
Here's an easier way of doing it. Instead of creating another variable of type String that will format and display the number, you can have a TextField and set its pattern to #,##0.00#.

<textField pattern="#,##0.00#">
    <reportElement x="455" y="0" width="100" height="30"/>
    <textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
</textField>


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答: When I first started learning programming with QBASIC the whole idea of flow control using if statements and loops was great. I think it was just a few days after I learned about the if statement that I built my first "Choose your own adventure" game. Looking back I know it must have been horribly inefficient and massive in terms of lines of code, but the fact that I could branch the story using nothing but if statements was wonderful.</p>

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: TheTXI


答: You are assigning values to g->_node_list[g->_sz] but you didn't allocate memory for it. In fact g->_node_list is undefined so it will likely crash the program if you write data to the location it points to.

Title: program crashing when allocating space for structures


问:
Apply query total for variable
I have sum query with active record, and assign with total filed.

I select one record is ok, so show as ActiveDataProvider, that total not show.

This my query:

```<code>$sumQuery = 'sum(Condition) total';
</code>```

And select sum:

```<code> $query->select(['*', $sumQuery]);
</code>```

So how can i get it's in Data Provinder.

答:
```<code>$query = $model->find()->select(['*, sum(Condition) as total']);
$dataProvider = new ActiveDataProvider([
     'query' => $query,
]);
</code>```

And, for example, in GridView columns its will be exist like this:

```<code>[
     'attribute' => 'total',
]
</code>```

Title: Apply query total for variable

Body:
I have sum query with active record, and assign with total filed.

I select one record is ok, so show as ActiveDataProvider, that total not show.

This my query:

$sumQuery = 'sum(Condition) total';

And select sum:

 $query->select(['*', $sumQuery]);

So how can i get it's in Data Provinder.

Body:
$query = $model->find()->select(['*, sum(Condition) as total']);
$dataProvider = new ActiveDataProvider([
     'query' => $query,
]);

And, for example, in GridView columns its will be exist like this:

[
     'attribute' => 'total',
]


问:
Nested query on Dynamodb with nodejs
I am working on a project where i need to perform nested query over Dynamodb tables. Please let know if it is possible if yes then please provide a sample for id not in(select id from table) in node js

答: Not supported. Select your id`s first and only then use it...</p>

Title: Nested query on Dynamodb with nodejs


问:
(iOS) dispatch_async() vs. NSOperationQueue
I learned iOS programming thanks to Stanford's CS193p course (on iTunes U) as well as the iOS programming book from Big Nerd Ranch.  In both of those, they recommend using dispatch_async(), dispatch_get_main_queue(), etc. to handle threading and concurrent operations.  However, at WWDC 2012's session on building concurrent UI, the speaker recommended the use of NSOperationQueue.

What are the differences between dispatch_*() and NSOperationQueue, and is there any reason (technical, performance, stylistic, or otherwise) that I should use one over the other?  Is NSOperationQueue just an Objective-C wrapper around dispatch_async, or is there more to it than that?

答:
Adding to above answer, the other advantage of NSOperation queue over GCD are

1)  Dependencies:-  We can set up a dependency between two NSOperations
the operation will not start until all of its dependencies return true for finished.

2) State of Operation:- We can monitor the state of an operation or operation queue. Ready, executing or finished

3) Max Number of Operation:-
We can specify the maximum number of queued operations that can run simultaneously