问:
Statement level trigger to enforce a constraint
I am trying to implement a statement level trigger to enforce the following "An applicant cannot apply for more than two positions in one day".

I am able to enforce it using a row level trigger (as shown below) but I have no clue how to do so using a statement level trigger when I can't use :NEW or :OLD.

I know there are alternatives to using a trigger but I am revising for my exam that would have a similar question so I would appreciate any help.

```<code>CREATE TABLE APPLIES(
anumber     NUMBER(6)   NOT NULL,  /* applicant number */
pnumber     NUMBER(8)   NOT NULL, /* position number */
appDate     DATE        NOT NULL, /* application date*/
CONSTRAINT APPLIES_pkey PRIMARY KEY(anumber, pnumber)
);

CREATE OR REPLACE TRIGGER app_trigger
BEFORE INSERT ON APPLIES
FOR EACH ROW
DECLARE
  counter NUMBER;
BEGIN
  SELECT COUNT(*) INTO counter
  FROM APPLIES
  WHERE anumber = :NEW.anumber
  AND to_char(appDate, 'DD-MON-YYYY') = to_char(:NEW.appDate, 'DD-MON-YYYY');

  IF counter = 2 THEN
      RAISE_APPLICATION_ERROR(-20001, 'error msg');
  END IF;
END;
</code>```

答:
You're correct that you don't have :OLD and :NEW values - so you need to check the entire table to see if the condition (let's not call it a "constraint", as that term has specific meaning in the sense of a relational database) has been violated:

```<code>CREATE OR REPLACE TRIGGER APPLIES_AIU
  AFTER INSERT OR UPDATE ON APPLIES
BEGIN
  FOR aRow IN (SELECT ANUMBER,
                      TRUNC(APPDATE) AS APPDATE,
                      COUNT(*) AS APPLICATION_COUNT
                 FROM APPLIES
                 GROUP BY ANUMBER, TRUNC(APPDATE)
                 HAVING COUNT(*) > 2)
  LOOP
    -- If we get to here it means we have at least one user who has applied
    -- for more than two jobs in a single day.

    RAISE_APPLICATION_ERROR(-20002, 'Applicant ' || aRow.ANUMBER ||
                                    ' applied for ' || aRow.APPLICATION_COUNT ||
                                    ' jobs on ' ||
                                    TO_CHAR(aRow.APPDATE, 'DD-MON-YYYY'));
  END LOOP;
END APPLIES_AIU;
</code>```

It's a good idea to add an index to support this query so it will run efficiently:

```<code>CREATE INDEX APPLIES_BIU_INDEX
  ON APPLIES(ANUMBER, TRUNC(APPDATE));
</code>```

dbfiddle here

Best of luck.

Body:
I am trying to implement a statement level trigger to enforce the following "An applicant cannot apply for more than two positions in one day".

I am able to enforce it using a row level trigger (as shown below) but I have no clue how to do so using a statement level trigger when I can't use :NEW or :OLD.

I know there are alternatives to using a trigger but I am revising for my exam that would have a similar question so I would appreciate any help.

CREATE TABLE APPLIES(
anumber     NUMBER(6)   NOT NULL,  /* applicant number */
pnumber     NUMBER(8)   NOT NULL, /* position number */
appDate     DATE        NOT NULL, /* application date*/
CONSTRAINT APPLIES_pkey PRIMARY KEY(anumber, pnumber)
);

CREATE OR REPLACE TRIGGER app_trigger
BEFORE INSERT ON APPLIES
FOR EACH ROW
DECLARE
  counter NUMBER;
BEGIN
  SELECT COUNT(*) INTO counter
  FROM APPLIES
  WHERE anumber = :NEW.anumber
  AND to_char(appDate, 'DD-MON-YYYY') = to_char(:NEW.appDate, 'DD-MON-YYYY');

  IF counter = 2 THEN
      RAISE_APPLICATION_ERROR(-20001, 'error msg');
  END IF;
END;

Body:
You're correct that you don't have :OLD and :NEW values - so you need to check the entire table to see if the condition (let's not call it a "constraint", as that term has specific meaning in the sense of a relational database) has been violated:

CREATE OR REPLACE TRIGGER APPLIES_AIU
  AFTER INSERT OR UPDATE ON APPLIES
BEGIN
  FOR aRow IN (SELECT ANUMBER,
                      TRUNC(APPDATE) AS APPDATE,
                      COUNT(*) AS APPLICATION_COUNT
                 FROM APPLIES
                 GROUP BY ANUMBER, TRUNC(APPDATE)
                 HAVING COUNT(*) > 2)
  LOOP
    -- If we get to here it means we have at least one user who has applied
    -- for more than two jobs in a single day.

    RAISE_APPLICATION_ERROR(-20002, 'Applicant ' || aRow.ANUMBER ||
                                    ' applied for ' || aRow.APPLICATION_COUNT ||
                                    ' jobs on ' ||
                                    TO_CHAR(aRow.APPDATE, 'DD-MON-YYYY'));
  END LOOP;
END APPLIES_AIU;

It's a good idea to add an index to support this query so it will run efficiently:

CREATE INDEX APPLIES_BIU_INDEX
  ON APPLIES(ANUMBER, TRUNC(APPDATE));

dbfiddle here

Best of luck.


来源: stackexchange

问:
Delphi: "Parameter object is improperly defined. Inconsistent or incomplete information was provided."
I'm trying to insert a record into a table in a 3-tier database setup, and the middle-tier server generates the error message above as an OLE exception when it tries to add the first parameter to the query.

I've Googled this error, and I find the same result consistently: it comes from having a colon in a string somewhere in your query, which b0rks ADO's SQL parser.  This is not the case here.  There are no spurious colons anywhere.  I've checked and rechecked the object definition against the schema for the table I'm trying to insert into.  Everything checks out, and this has my coworkers stumped.  Does anyone know what else could be causing this?  I'm at my wits' end here.

I'm using Delphi 2007 and SQL Server 2005.

答:
I found this thread while searching the previously mentioned Exception message.  In my case, the cause was an attempt to embed a SQL comment /* foo */ into my query.sql.text.

(I thought it would have been handy to see a comment go floating past in my profiler window.)

Anyhow - Delphi7 hated that one.

OwnerDisplayName: Mason Wheeler

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
React native app crashes for first time when downloaded from playstore when you have google referral receiver in your manifest
We have built an application and recently we have added com.google.android.gms.analytics.CampaignTrackingReceiver the default receiver in the manifest to auto capture the install sources medium etc.

We have a strange issue here. Every time we download the application, it crashes for the first time. Below is the logs.

Caused by java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.analytics.CampaignTrackingReceiver" on path: DexPathList[[zip file "/data/app/YOURPACKAGENAME--w6LGEcDlZ0B12LlUiobEQ==/base.apk"],nativeLibraryDirectories=[/data/app/YOURPACKAGENAME--w6LGEcDlZ0B12LlUiobEQ==/lib/arm, /data/app/YOURPACKAGENAME--w6LGEcDlZ0B12LlUiobEQ==/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib]]
         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
         at android.app.ActivityThread.handleReceiver(ActivityThread.java:3229)
         at android.app.ActivityThread.-wrap17(Unknown Source)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1722)
         at android.os.Handler.dispatchMessage(Handler.java:106)
         at android.os.Looper.loop(Looper.java:176)
         at android.app.ActivityThread.main(ActivityThread.java:6656)
         at java.lang.reflect.Method.invoke(Method.java)
         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

Below is the google, firebase related libraries added in build.gradle.

compile project(':react-native-firebase')

compile "com.google.android.gms:play-services-base:16.0.1"

compile "com.google.firebase:firebase-core:16.0.4"

compile "com.google.firebase:firebase-analytics:16.0.4"

apply plugin: 'com.google.gms.google-services'

All firebase events have been tracked as expected. How to solve the above crash?

答:
Most likely your production build is being stripped of some classes by your Proguard config.

Se if adding this in your proguard-pro file works:

```<code>-keep class com.google.android.gms.analytics { *; }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Most likely your production build is being stripped of some classes by your Proguard config.

Se if adding this in your proguard-pro file works:

-keep class com.google.android.gms.analytics { *; }


问:
Flatten np.ndarray in customized order
I have a np.ndarray with the shape (24, 3). I want to flatten this array but in a rathor unusual way. I would like to have [0:8, 0] then [0:8, 1] then [0:8, 2] then [8:16, 0] and so on.

Of course i could do it the brute force way but maybe there is a more elegant and efficient solution to this problem.

new_array = np.array([])
np.append(new_array, old_array[0:8, 0])
np.append(new_array, old_array[0:8, 1])
np.append(new_array, old_array[0:8, 2])

np.append(new_array, old_array[8:16, 0])
np.append(new_array, old_array[8:16, 1])
np.append(new_array, old_array[8:16, 2])

np.append(new_array, old_array[16:24, 0])
np.append(new_array, old_array[16:24, 1])
np.append(new_array, old_array[16:24, 2])
```

答:
Reshape, permute and reshape -

```<code>n = 8 # cut length along first axis
new_array = old_array.reshape(-1,n,old_array.shape[1]).swapaxes(1,2).ravel()
</code>```

Title: Flatten np.ndarray in customized order

Body:
Reshape, permute and reshape -

n = 8 # cut length along first axis
new_array = old_array.reshape(-1,n,old_array.shape[1]).swapaxes(1,2).ravel()


问:
How to convert multiple .img images to .bmp format?
I am trying to use Python to read MULTIPLE images from a folder that are currently in .img format and convert them all to .bmp format.

I've successfully done it with just one image however I am very new to Python and have trouble reading multiple images and converting them.

Here was my attempt at 1 image:

from PIL import Image, ImageFilter
import sys

img = "hand1.img"
imgOut = "hand2bmp.bmp"
image = Image.open(img).convert('RGB').convert('L').save(imgOut)
```

<p>Here was my attempt at multiple images:</p>

<pre class="lang-py prettyprint-override"><code>from PIL import Image, ImageFilter
import sys, glob, os

folder = 'C:/Users/Josep/Documents/code/test_file/BMLs/BMLs_Original'

for filename in glob.iglob(os.path.join(folder,'*.bmp')):
    Image.open(filename).convert('RGB').convert('L').save(filename)
    os.rename(filename, filename[:-4] + '.bmp').save(filename)
</code>```

I expected to convert the files to .bmp format, however, when I run the code I see no change in the images.

答:
You more-or-less just need to do what you did for one file to each file in the folder.

```<code>import glob, os, sys
from PIL import Image

folder = 'C:/Users/Josep/Documents/code/test_file/BMLs/BMLs_Original'

for filepath in glob.iglob(os.path.join(folder, '*.img')):
    image = Image.open(filepath).convert('RGB').convert('L')
    new_filepath = os.path.splitext(filepath)[0] + '.bmp'
    image.save(new_filepath)
</code>```

Note that this creates new image files, leaving the originals intact — in other words it doesn't rename the originals. If you want to get rid of the originals, you could delete them with os.remove() after saving the converted image in the loop.

Body:
I am trying to use Python to read MULTIPLE images from a folder that are currently in .img format and convert them all to .bmp format.

I've successfully done it with just one image however I am very new to Python and have trouble reading multiple images and converting them.

Here was my attempt at 1 image:

from PIL import Image, ImageFilter
import sys

img = "hand1.img"
imgOut = "hand2bmp.bmp"
image = Image.open(img).convert('RGB').convert('L').save(imgOut)

Here was my attempt at multiple images:

from PIL import Image, ImageFilter
import sys, glob, os

folder = 'C:/Users/Josep/Documents/code/test_file/BMLs/BMLs_Original'

for filename in glob.iglob(os.path.join(folder,'*.bmp')):
    Image.open(filename).convert('RGB').convert('L').save(filename)
    os.rename(filename, filename[:-4] + '.bmp').save(filename)

I expected to convert the files to .bmp format, however, when I run the code I see no change in the images.

Body:
You more-or-less just need to do what you did for one file to each file in the folder.

import glob, os, sys
from PIL import Image

folder = 'C:/Users/Josep/Documents/code/test_file/BMLs/BMLs_Original'

for filepath in glob.iglob(os.path.join(folder, '*.img')):
    image = Image.open(filepath).convert('RGB').convert('L')
    new_filepath = os.path.splitext(filepath)[0] + '.bmp'
    image.save(new_filepath)

Note that this creates new image files, leaving the originals intact — in other words it doesn't rename the originals. If you want to get rid of the originals, you could delete them with os.remove() after saving the converted image in the loop.


问:
The remove() function is deleting every element I clicked instead of the one recently clicked
I am creating a gallery web app just for fun. I am adding context menu to manipulate images. I added the functionality to delete a certain image by right clicking on it but when a right click on multiple images and click on delete option once, all the previously clicked images also gets removed.

The delete option should delete the recently clicked image only.

$(".image").on("mousedown", function(event) {
  var i = $(this);
  var c = $(".context");
  c.css("display", "none");

  if (event.which == 3) {
    c.css({
      "top": event.pageY + "px",
      "left": event.pageX + "px"
    }).slideDown();

    $("#delete").on("click", function() {
      var p = i.offset();
      i.next().css("margin-left", "290px");
      i.css({
        "position": "absolute",
        "top": p.top - 72,
        "left": p.left - 10
      });

      i.animate({
        top: "-50%",
        opacity: "0"
      });

      setTimeout(function() {
        i.next().animate({
          "marginLeft": "10px"
        });
        i.prev().animate({
          "marginRight": "10px"
        });
        i.remove();
      }, 200);

      c.css("display", "none");
    });
  } else if (event.which == 1 || event.which == 2) {
    c.css("display", "none");
  }
});
```

答:
on line 4 : I think it should be remove since it adds css attrs {display:none} in all cases.

```<code>$(".image").on("mousedown", function(event) {
  var i = $(this);
  var c = $(".context");
  // c.css("display", "none"); //should be removed
 //....
 });
</code>```

Body:
on line 4 : I think it should be remove since it adds css attrs {display:none} in all cases.

$(".image").on("mousedown", function(event) {
  var i = $(this);
  var c = $(".context");
  // c.css("display", "none"); //should be removed
 //....
 });


问:
How to add play button inside responsive slide
I have a set of images to display using a responsive slide. I found a link to create responsive slide: http://responsiveslides.com. I don't know to add pause/play button inside the slide. My code is as follows:

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
  <script src="../responsiveslides.min.js"></script>
  <script>

      $("#slider4").responsiveSlides({
        auto: true,
        pager: false,
        pauseControls:true,
        nav: true,
        pause: false,
        speed: 500,
        namespace: "callbacks",
        before: function () {
          $('.events').append("<li>before event fired.</li>");
        },
        after: function () {
          $('.events').append("<li>after event fired.</li>");
        }
      });

    });
  </script>
</head>
<body>
  <div id="wrapper">
      <a class="pause_slider" href="#">Pause Slider</a>
      <a class="play_slider" href="#">Play Slider</a>

    <div class="callbacks_container">
      <ul class="rslides" id="slider4">
        <li>
          <img src="images/1.jpg" alt="">
          <p class="caption">This is a caption</p>
        </li>
        <li>
          <img src="images/2.jpg" alt="">
          <p class="caption">This is another caption</p>
        </li>
        <li>
          <img src="images/3.jpg" alt="">
          <p class="caption">The third caption</p>
        </li>
      </ul>
    </div>
</code>```

The above is the source code. How can I add pause and play button into my slide?

答:
Do you necessarily have to use that library or can you listen to another option?

I recommend you swiper. It is a better library in my opinion. Here is the get-started link.

In this example you can change the value of the boolean autoplay with methods start() (to autoplay the slider) and stop() (to pause it).

Here you have an example. Hope it helps:

$(document).ready(function() {
 new Swiper('.swiper-container', {
  speed: 600,
  spaceBetween: 90,
  autoplay: true,
  disableOnInteraction: true,
  loop: true
 });
 const mySwiper = document.querySelector('.swiper-container').swiper;
 let isSliderActive = true;

 $("#slider-control").click(function() {
  if (isSliderActive) {
   mySwiper.autoplay.stop();
   isSliderActive = false;
   this.innerHTML = 'PLAY';
   console.log('slider stopped');
  } else {
   mySwiper.autoplay.start();
   isSliderActive = true;
   this.innerHTML = 'PAUSE';
   console.log('slider activated');
  }
 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.5/js/swiper.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.5/css/swiper.css" rel="stylesheet" />
<style>
 .swiper-slide { text-align: center; }
</style>

<div class="swiper-container">
  <!-- required wrapper -->
  <div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">
  <img src="https://place-hold.it/100x100">
  <div>Slide 1</div>
 </div>
    <div class="swiper-slide">
  <img src="https://place-hold.it/100x100">
  <div>Slide 2</div>
 </div>
    <div class="swiper-slide">
  <img src="https://place-hold.it/100x100">
  <div>Slide 3</div>
    </div>
  </div>
</div>
<button id="slider-control">PAUSE</button></code>```

Body:
I have a set of images to display using a responsive slide. I found a link to create responsive slide: http://responsiveslides.com. I don't know to add pause/play button inside the slide. My code is as follows:

      Pause Slider
      Play Slider

This is a caption

This is another caption

The third caption

The above is the source code. How can I add pause and play button into my slide?

Body:
Do you necessarily have to use that library or can you listen to another option?

I recommend you swiper. It is a better library in my opinion. Here is the get-started link.

In this example you can change the value of the boolean autoplay with methods start() (to autoplay the slider) and stop() (to pause it).

Here you have an example. Hope it helps:

$(document).ready(function() {
 new Swiper('.swiper-container', {
  speed: 600,
  spaceBetween: 90,
  autoplay: true,
  disableOnInteraction: true,
  loop: true
 });
 const mySwiper = document.querySelector('.swiper-container').swiper;
 let isSliderActive = true;

 $("#slider-control").click(function() {
  if (isSliderActive) {
   mySwiper.autoplay.stop();
   isSliderActive = false;
   this.innerHTML = 'PLAY';
   console.log('slider stopped');
  } else {
   mySwiper.autoplay.start();
   isSliderActive = true;
   this.innerHTML = 'PAUSE';
   console.log('slider activated');
  }
 });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.5/js/swiper.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.5/css/swiper.css" rel="stylesheet" />
<style>
 .swiper-slide { text-align: center; }
</style>

<div class="swiper-container">
  <!-- required wrapper -->
  <div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">
  <img src="https://place-hold.it/100x100">
  <div>Slide 1</div>
 </div>
    <div class="swiper-slide">
  <img src="https://place-hold.it/100x100">
  <div>Slide 2</div>
 </div>
    <div class="swiper-slide">
  <img src="https://place-hold.it/100x100">
  <div>Slide 3</div>
    </div>
  </div>
</div>
<button id="slider-control">PAUSE</button>


问:
Cannot read property 'length' of undefined error message in Javascript
I'm trying to solve a code challenge on code wars and don't understand why I'm getting an error message regarding the .length of a string inside of an array when I try to run it.

It's definitely the first .length in line 7.  I've tried running other arr[i].lengths and they work, I'm thinking it's a problem with scope?

function longestConsec(strarr, k) {
  var arr = [];
  if (strarr.length == 0 || k > strarr.length || k <= 0) {
    return "";
  }
  for (var i = 1; i <= strarr.length; i++) {
    if (strarr[i].length > strarr[0].length && arr.length < k) {
      arr.push(strarr[i]);
    }
  }
  arr.join('');
}

longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2);```

Should return "abigailtheta" as it's the 2 longest strings after the
first string which were the requirements.

VM304:7 Uncaught TypeError: Cannot read property 'length' of undefined

答:
As pointed out, you're iterating one time too many. Your final iteration will try to access an index that doesn't exist in your array.

That aside, your code doesn't seem to perform as you describe. It doesn't address the "longest" at any point, but rather just grabs the first two strings that are longer than the first.

If you wanted to find consecutive strings that combine for the longest length, consider something like this instead:

function longestConsec(strarr, k) {
  //invalid - exit
  if (strarr.length === 0 || k > strarr.length || k <= 0) return "";

  return strarr.reduce((out, str, idx, arr) => {
    if (idx+k > arr.length) arr.splice(1);          //exit early if at end of array

    let substring = arr.slice(idx,idx+k).join("");  //combine next k items into a string
    if (substring.length > out.length) {            //if it's the longest
      out.length = substring.length;                //save the length
      out.str = substring;                          //save the string
    }

    return out;
  }, {length: 0, str: ""});
}

var longest = longestConsec(["one", "seventeen", "four", "nineteen", "eleven", "five", "sixteen", "thirteen", "fourteen", "six"], 3);
console.log(longest);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: none !important; top: 0;}</code>```

This has room for improvements regarding efficiency, as calling .slice() each time isn't exactly necessary, but in any case I believe the result is bit more in line with your task.

Body:
I'm trying to solve a code challenge on code wars and don't understand why I'm getting an error message regarding the .length of a string inside of an array when I try to run it.

It's definitely the first .length in line 7.  I've tried running other arr[i].lengths and they work, I'm thinking it's a problem with scope?

function longestConsec(strarr, k) {
  var arr = [];
  if (strarr.length == 0 || k > strarr.length || k <= 0) {
    return "";
  }
  for (var i = 1; i <= strarr.length; i++) {
    if (strarr[i].length > strarr[0].length && arr.length < k) {
      arr.push(strarr[i]);
    }
  }
  arr.join('');
}

longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2);

Should return "abigailtheta" as it's the 2 longest strings after the
first string which were the requirements.

VM304:7 Uncaught TypeError: Cannot read property 'length' of undefined

Body:
As pointed out, you're iterating one time too many. Your final iteration will try to access an index that doesn't exist in your array.

That aside, your code doesn't seem to perform as you describe. It doesn't address the "longest" at any point, but rather just grabs the first two strings that are longer than the first.

If you wanted to find consecutive strings that combine for the longest length, consider something like this instead:

function longestConsec(strarr, k) {
  //invalid - exit
  if (strarr.length === 0 || k > strarr.length || k <= 0) return "";

  return strarr.reduce((out, str, idx, arr) => {
    if (idx+k > arr.length) arr.splice(1);          //exit early if at end of array

    let substring = arr.slice(idx,idx+k).join("");  //combine next k items into a string
    if (substring.length > out.length) {            //if it's the longest
      out.length = substring.length;                //save the length
      out.str = substring;                          //save the string
    }

    return out;
  }, {length: 0, str: ""});
}

var longest = longestConsec(["one", "seventeen", "four", "nineteen", "eleven", "five", "sixteen", "thirteen", "fourteen", "six"], 3);
console.log(longest);

.as-console-wrapper {max-height: none !important; top: 0;}

This has room for improvements regarding efficiency, as calling .slice() each time isn't exactly necessary, but in any case I believe the result is bit more in line with your task.


问:
JVM performance tuning for large applications
The default JVM parameters are not optimal for running large applications. Any insights from people who have tuned it on a real application would be helpful. We are running the application on a 32-bit windows machine, where the client JVM is used by default. We have added -server and changed the NewRatio to 1:3 (A larger young generation).

Any other parameters/tuning which you have tried and found useful?

[Update] The specific type of application I'm talking about is a server application that are rarely shutdown, taking at least -Xmx1024m. Also assume that the application is profiled already. I'm looking for general guidelines in terms of JVM performance only.

答:
Look here (or do a google search for hotspot tuning) http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html

You definitely want to profile your app before you try to tune the vm.  NetBeans has a nice profiler built into it that will let you see all sorts of things.

I once had someone tell me that the GC was broken for their app - I looked at the code and found that they never closed any of their database query results so they were retaining massive amounts of byte arrays.  Once we closed the results the time went from over 20 mins and a GB of memory to about 2 mins and a very small amount of memory.  They were able to remove the JVM tuning parameters and things were happy.

OwnerDisplayName: TofuBeer


问:
how to make this sql statment in codeigniter framework php?
how to make this sql statment in codeigniter framework php??

```<code>SELECT COUNT(`id`) AS `c` FROM `products` WHERE `valid` = 1 AND `sticky` = 2
</code>```

how to make it in the model

like this way

```<code>$this->db->get('products');
</code>```

how to do that?

答:
I know this is a late answer, but personally when using the framework, I like to build statements as general purpose as possible.  I absolutely love the ability to pass an array of conditions as the where in the query, plus I like using get_where, so... I'm submitting this because my answer's slightly different and I feel is more invasive into using the intricacies of the framework ;].</p>

```<code>$where['valid'] = 1;
$where['sticky'] = 2;

$db->select('count("id") as c');
$query = $db->get_where('products',$where);
</code>```

Body:
how to make this sql statment in codeigniter framework php??

SELECT COUNT(`id`) AS `c` FROM `products` WHERE `valid` = 1 AND `sticky` = 2

how to make it in the model

like this way

$this->db->get('products');

how to do that?

Body:
I know this is a late answer, but personally when using the framework, I like to build statements as general purpose as possible.  I absolutely love the ability to pass an array of conditions as the where in the query, plus I like using get_where, so... I'm submitting this because my answer's slightly different and I feel is more invasive into using the intricacies of the framework ;].

$where['valid'] = 1;
$where['sticky'] = 2;

$db->select('count("id") as c');
$query = $db->get_where('products',$where);


问:
Basic function call in node.js
If I write following code, I get "Hello World", but not "Hey from function". What am I doing wrong? Same if I try to write to console from called function. Seems it is not called.

This is very basic testing of node.js

```<code>const http = require('http');
const express = require('express');

const app = express();

const port = 3000;

function writetest(req, res) {
    res.send("Hey from function");
}

app.get('/nodejs/', function(req, res) {
    res.send('Hello World!');
    writetest(req,res);
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));
</code>```

No error messages, it just seems not to call he function.

答:
res.send can only be called once, once the data is sent, the users browser is not waiting for any more responses. What you are trying to achieve can be done with res.write and res.end, detailed here.
An example of how to use it is shown here.

Title: Basic function call in node.js

Body:
If I write following code, I get "Hello World", but not "Hey from function". What am I doing wrong? Same if I try to write to console from called function. Seems it is not called.

This is very basic testing of node.js

const http = require('http');
const express = require('express');

const app = express();

const port = 3000;

function writetest(req, res) {
    res.send("Hey from function");
}

app.get('/nodejs/', function(req, res) {
    res.send('Hello World!');
    writetest(req,res);
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

No error messages, it just seems not to call he function.


问:
Determine the Service.StartType in powershell 2.0
Can we get Service.StartType in PowerShell 2.0?

Service.StartType in PowerShell 5.0 works, but in PowerShell 2.0 doesn't yield result.

```<code>$Service = Get-Service WinMgmt
$Service.StartType
</code>```

I need the Service.StartType in PowerShell 2.0.  Is there any option?

答:
Query the corresponding WMI class:</p>

```<code>$winMgmtService = Get-WmiObject Win32_Service -Filter "Name = 'WinMgmt'"

# This will be either "Auto", "Manual", "Disabled" or "Unknown"
$winMgmtService.StartMode
</code>```

Body:
Can we get Service.StartType in PowerShell 2.0?

Service.StartType in PowerShell 5.0 works, but in PowerShell 2.0 doesn't yield result.

$Service = Get-Service WinMgmt
$Service.StartType

I need the Service.StartType in PowerShell 2.0.  Is there any option?

Body:
Query the corresponding WMI class:

$winMgmtService = Get-WmiObject Win32_Service -Filter "Name = 'WinMgmt'"

# This will be either "Auto", "Manual", "Disabled" or "Unknown"
$winMgmtService.StartMode


问:
Convert afterSubmit script to Worfkflow Action Script?
We have a custom script on our Sales Order that sets the Shipping Address to match the Location field in the header when the user submits the order. We're not using Cash Sales (long story) or POS. These are standard sales orders with Netsuite Basic. We have a decent amount of counter sales and our employees need the ability to quickly enter an order for a cash customer without having to add a shipping address every time. They choose "Customer Pick Up" from the Shipping Method dropdown, click Save, the script sees that option was chosen and it updates the address. This has been working great. We just installed Avatax, and it does NOT like this setup. It needs the Shipping Address selected on the order BEFORE we click Save on the order. I was hoping I could use a workflow that would trigger on field change/sourcing and run that script instead of waiting for the Save. But I can't figure out how to do it. I would be fine with a button or other mechanism as well - I just need a way to quickly set the Shipping Address to match the Location's address prior to saving the order. I started looking into converting this script to a Workflow Action Script so I can call it from a workflow, but I'm lost.. </p>

```<code>var salesOrderUE = {

    afterSubmit :function (type) {
        if (type == 'create' || type == 'edit') {
            var salesOrder = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId(), { recordmode: 'dynamic'});
            var customerPickUp = salesOrder.getFieldValue('shipmethod')
            if (customerPickUp == '16853') {
                var location = salesOrder.getFieldValue('location');
                var locationRec = nlapiLoadRecord('location', location);
                salesOrder.setFieldValue('shipaddresslist', -2);
                var subrecord = salesOrder.createSubrecord('shippingaddress');
                subrecord.setFieldValue('country', locationRec.getFieldValue('country'));
                subrecord.setFieldValue('isresidential', 'F');
                subrecord.setFieldValue('attention', locationRec.getFieldValue('attention'));
                subrecord.setFieldValue('addressee', locationRec.getFieldValue('addressee'));
                subrecord.setFieldValue('addr1', locationRec.getFieldValue('addr1'));
                subrecord.setFieldValue('addr2', locationRec.getFieldValue('addr2'));
                subrecord.setFieldValue('city', locationRec.getFieldValue('city'));
                subrecord.setFieldValue('state', locationRec.getFieldValue('state'));
                subrecord.setFieldValue('zip', locationRec.getFieldValue('zip'));
                subrecord.commit();
                salesOrder.setFieldValue('shipaddress', locationRec.getFieldValue('addr1') +
                        '\n' + locationRec.getFieldValue('city') + ' ' + locationRec.getFieldValue('state') + ' ' + locationRec.getFieldValue('zip') + '\n'+
                        locationRec.getFieldValue('country'));

                nlapiSubmitRecord(salesOrder, true, true);
            }
        }
    }
}
</code>```

答:
Huge shoutout to @battk on Slack. They walked me through the whole process of converting this to a Client script, and using the Field Changed Function to run it.

Here's the updated code: (I still need to edit the if statement to check for location == null)

```<code>function setCPUshipto(type, name, linenum) {
  if (name !== "shipmethod" || nlapiGetFieldValue("shipmethod") !== "16853")
  {
        return;
  }

  var locationId = nlapiGetFieldValue("location");
  var locationRec = nlapiLoadRecord("location", locationId);
  var subrecord = nlapiCreateSubrecord("shippingaddress") || nlapiEditSubrecord("shippingaddress")
  subrecord.setFieldValue("country", locationRec.getFieldValue("country"));
  subrecord.setFieldValue("isresidential", "F");
  subrecord.setFieldValue("attention", locationRec.getFieldValue("attention"));
  subrecord.setFieldValue("addressee", locationRec.getFieldValue("addressee"));
  subrecord.setFieldValue("addr1", locationRec.getFieldValue("addr1"));
  subrecord.setFieldValue("addr2", locationRec.getFieldValue("addr2"));
  subrecord.setFieldValue("city", locationRec.getFieldValue("city"));
  subrecord.setFieldValue("state", locationRec.getFieldValue("state"));
  subrecord.setFieldValue("zip", locationRec.getFieldValue("zip"));
  subrecord.commit();

}
</code>```

Body:
We have a custom script on our Sales Order that sets the Shipping Address to match the Location field in the header when the user submits the order. We're not using Cash Sales (long story) or POS. These are standard sales orders with Netsuite Basic. We have a decent amount of counter sales and our employees need the ability to quickly enter an order for a cash customer without having to add a shipping address every time. They choose "Customer Pick Up" from the Shipping Method dropdown, click Save, the script sees that option was chosen and it updates the address. This has been working great. We just installed Avatax, and it does NOT like this setup. It needs the Shipping Address selected on the order BEFORE we click Save on the order. I was hoping I could use a workflow that would trigger on field change/sourcing and run that script instead of waiting for the Save. But I can't figure out how to do it. I would be fine with a button or other mechanism as well - I just need a way to quickly set the Shipping Address to match the Location's address prior to saving the order. I started looking into converting this script to a Workflow Action Script so I can call it from a workflow, but I'm lost..

var salesOrderUE = {

    afterSubmit :function (type) {
        if (type == 'create' || type == 'edit') {
            var salesOrder = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId(), { recordmode: 'dynamic'});
            var customerPickUp = salesOrder.getFieldValue('shipmethod')
            if (customerPickUp == '16853') {
                var location = salesOrder.getFieldValue('location');
                var locationRec = nlapiLoadRecord('location', location);
                salesOrder.setFieldValue('shipaddresslist', -2);
                var subrecord = salesOrder.createSubrecord('shippingaddress');
                subrecord.setFieldValue('country', locationRec.getFieldValue('country'));
                subrecord.setFieldValue('isresidential', 'F');
                subrecord.setFieldValue('attention', locationRec.getFieldValue('attention'));
                subrecord.setFieldValue('addressee', locationRec.getFieldValue('addressee'));
                subrecord.setFieldValue('addr1', locationRec.getFieldValue('addr1'));
                subrecord.setFieldValue('addr2', locationRec.getFieldValue('addr2'));
                subrecord.setFieldValue('city', locationRec.getFieldValue('city'));
                subrecord.setFieldValue('state', locationRec.getFieldValue('state'));
                subrecord.setFieldValue('zip', locationRec.getFieldValue('zip'));
                subrecord.commit();
                salesOrder.setFieldValue('shipaddress', locationRec.getFieldValue('addr1') +
                        '\n' + locationRec.getFieldValue('city') + ' ' + locationRec.getFieldValue('state') + ' ' + locationRec.getFieldValue('zip') + '\n'+
                        locationRec.getFieldValue('country'));

                nlapiSubmitRecord(salesOrder, true, true);
            }
        }
    }
}

Body:
Huge shoutout to @battk on Slack. They walked me through the whole process of converting this to a Client script, and using the Field Changed Function to run it.

Here's the updated code: (I still need to edit the if statement to check for location == null)

function setCPUshipto(type, name, linenum) {
  if (name !== "shipmethod" || nlapiGetFieldValue("shipmethod") !== "16853")
  {
        return;
  }

  var locationId = nlapiGetFieldValue("location");
  var locationRec = nlapiLoadRecord("location", locationId);
  var subrecord = nlapiCreateSubrecord("shippingaddress") || nlapiEditSubrecord("shippingaddress")
  subrecord.setFieldValue("country", locationRec.getFieldValue("country"));
  subrecord.setFieldValue("isresidential", "F");
  subrecord.setFieldValue("attention", locationRec.getFieldValue("attention"));
  subrecord.setFieldValue("addressee", locationRec.getFieldValue("addressee"));
  subrecord.setFieldValue("addr1", locationRec.getFieldValue("addr1"));
  subrecord.setFieldValue("addr2", locationRec.getFieldValue("addr2"));
  subrecord.setFieldValue("city", locationRec.getFieldValue("city"));
  subrecord.setFieldValue("state", locationRec.getFieldValue("state"));
  subrecord.setFieldValue("zip", locationRec.getFieldValue("zip"));
  subrecord.commit();

}


问:
Slicing with :-1 and None - What does each of the statement mean?
I came across a code snippet where I could not understand two of the statements, though I could see the end result of each.

I will create a variable before giving the statements:

```<code>train = np.random.random((10,100))
</code>```

One of them read as :

```<code>train = train[:-1, 1:-1]
</code>```

What does this slicing mean? How to read this? I know that that -1 in slicing denotes from the back. But I cannot understand this.

Another statement read as follows:

```<code>la = [0.2**(7-j) for j in range(1,t+1)]
np.array(la)[:,None]
</code>```

What does slicing with None as in [:,None] mean?

For the above two statements, along with how each statement is read, it will be helpful to have an alternative method along, so that I understand it better.

答:
One of Python's strengths is its uniform application of straightforward principles. Numpy indexing, like all indexing in Python, passes a single argument to the indexed object's (i.e., the array's) __getitem__ method, and numpy arrays were one of the primary justifications for the slicing mechanism (or at least one of its very early uses).

When I'm trying to understand new behaviours I like to start with a concrete and comprehensible example, so rather than 10x100 random values I'll start with a one-dimensional 4-element vector and work up to 3x4, which should be big enough to understand what's going on.

```<code>simple = np.array([1, 2, 3, 4])

train = np.array([[1, 2, 3, 4],
                   [5, 6, 7, 8],
                   [9, 10, 11, 12]])
</code>```

The interpreter shows these as

```<code>array([1, 2, 3, 4])

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
</code>```

The expression simple[x] is equivalent to (which is to say the interpreter ends up executing) simple.__getitem__(x) under the hood - note this call takes a single argument.

The numpy array's __getitem__ method implements indexing with an integer very simply: it selects a single element from the first dimension. So simple[1] is 2, and train[1] is array([5, 6, 7, 8]).

When __getitem__ receives a tuple as an argument (which is how Python's syntax interprets expressions like array[x, y, z]) it applies each element of the tuple as an index to successive dimensions of the indexed object. So result = train[1, 2] is equivalent (conceptually - the code is more complex in implementation) to

```<code>temp = train[1]    # i.e. train.__getitem__(1)
result = temp[2]   # i.e. temp.__getitem__(2)
</code>```

and sure enough we find that result comes out at 7. You could think of array[x, y, z] as equivalent to array[x][y][z].

Now we can add slicing to the mix. Expressions containing a colon can be regarded as slice literals (I haven't seen a better name for them), and the interpreter creates slice objects for them. As the documentation notes, a slice object is mostly a container for three values, start, stop and slice, and it's up to each object's __getitem__ method how it interprets them. You might find this question helpful to understand slicing further.

With what you now know, you should be able to understand the answer to your first question.

```<code>result = train[:-1, 1:-1]
</code>```

will call train.__getitem__ with a two-element tuple of slices. This is equivalent to

```<code>temp = train[:-1]
result = temp[..., 1:-1]
</code>```

The first statement can be read as "set temp to all but the last row of train", and the second as "set result to all but the first and last columns of temp". train[:-1] is

```<code>array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
</code>```

and applying the [1:-1] subscripting to the second dimension of that array gives

```<code>array([[2, 3],
       [6, 7]])
</code>```

The ellipsis on the first dimension of the temp subscript says "pass everything," so the subscript expression[...]can be considered equivalent to[:]. As far as theNonevalues are concerned, a slice has a maximum of three data points: _start_, _stop_ and _step_. ANonevalue for any of these gives the default value, which is0for _start_, the length of the indexed object for _stop_, and1for _step. Sox[None:None:None]is equivalent tox[0:len(x):1]which is equivalent tox[::]`.

With this knowledge under your belt you should stand a bit more chance of understanding what's going on.

Body:
I came across a code snippet where I could not understand two of the statements, though I could see the end result of each.

I will create a variable before giving the statements:

train = np.random.random((10,100))

One of them read as :

train = train[:-1, 1:-1]

What does this slicing mean? How to read this? I know that that -1 in slicing denotes from the back. But I cannot understand this.

Another statement read as follows:

la = [0.2**(7-j) for j in range(1,t+1)]
np.array(la)[:,None]

What does slicing with None as in [:,None] mean?

For the above two statements, along with how each statement is read, it will be helpful to have an alternative method along, so that I understand it better.

Body:
One of Python's strengths is its uniform application of straightforward principles. Numpy indexing, like all indexing in Python, passes a single argument to the indexed object's (i.e., the array's) __getitem__ method, and numpy arrays were one of the primary justifications for the slicing mechanism (or at least one of its very early uses).

When I'm trying to understand new behaviours I like to start with a concrete and comprehensible example, so rather than 10x100 random values I'll start with a one-dimensional 4-element vector and work up to 3x4, which should be big enough to understand what's going on.

simple = np.array([1, 2, 3, 4])

train = np.array([[1, 2, 3, 4],
                   [5, 6, 7, 8],
                   [9, 10, 11, 12]])

The interpreter shows these as

array([1, 2, 3, 4])

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

The expression simple[x] is equivalent to (which is to say the interpreter ends up executing) simple.__getitem__(x) under the hood - note this call takes a single argument.

The numpy array's __getitem__ method implements indexing with an integer very simply: it selects a single element from the first dimension. So simple[1] is 2, and train[1] is array([5, 6, 7, 8]).

When __getitem__ receives a tuple as an argument (which is how Python's syntax interprets expressions like array[x, y, z]) it applies each element of the tuple as an index to successive dimensions of the indexed object. So result = train[1, 2] is equivalent (conceptually - the code is more complex in implementation) to

temp = train[1]    # i.e. train.__getitem__(1)
result = temp[2]   # i.e. temp.__getitem__(2)

and sure enough we find that result comes out at 7. You could think of array[x, y, z] as equivalent to array[x][y][z].

Now we can add slicing to the mix. Expressions containing a colon can be regarded as slice literals (I haven't seen a better name for them), and the interpreter creates slice objects for them. As the documentation notes, a slice object is mostly a container for three values, start, stop and slice, and it's up to each object's __getitem__ method how it interprets them. You might find this question helpful to understand slicing further.

With what you now know, you should be able to understand the answer to your first question.

result = train[:-1, 1:-1]

will call train.__getitem__ with a two-element tuple of slices. This is equivalent to

temp = train[:-1]
result = temp[..., 1:-1]

The first statement can be read as "set temp to all but the last row of train", and the second as "set result to all but the first and last columns of temp". train[:-1] is

array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

and applying the [1:-1] subscripting to the second dimension of that array gives

array([[2, 3],
       [6, 7]])

The ellipsis on the first dimension of the temp subscript says "pass everything," so the subscript expression[...]can be considered equivalent to[:]. As far as theNonevalues are concerned, a slice has a maximum of three data points: _start_, _stop_ and _step_. ANonevalue for any of these gives the default value, which is0for _start_, the length of the indexed object for _stop_, and1for _step. Sox[None:None:None]is equivalent tox[0:len(x):1]which is equivalent tox[::]`.

With this knowledge under your belt you should stand a bit more chance of understanding what's going on.


问:
Argument of type {...} is not assignable to parameter of type 'never'
I'm trying to create a type based on another one with the same keys and whose value's type is based on, but not equal to, the another type. It's similar to React's setState, where it accepts either a value or a function that get the current value and returns a new one.

After research, all issues related to this error seems related to a lack of type hinting. I already tried to specified the types for all next, current and newTheme[key] variables. It didn't work.

type Mode = "light" | "dark";

interface Theme {
  mode: Mode;
  test: number;
}

type ThemeUpdate = {
  [K in keyof Theme]: Theme[K] | ((current: Theme[K]) => Theme[K])
};

const reducer = (currentTheme: Theme, action: Partial<ThemeUpdate>): Theme => {
  const newTheme: Partial<Theme> = {};

  (Object.keys(action) as (keyof Theme)[]).forEach((key: keyof Theme) => {
    const next = action[key];
    const current = currentTheme[key];
    newTheme[key] = typeof next === "function" ? next(current) : next;
    //                                                ^^^^^^^
    // Argument of type 'number | "light" | "dark"' is not assignable to parameter of type 'never'. Type 'number' is not assignable to type 'never'
  });

  return { ...currentTheme, ...newTheme };
};

```

What I expect is that the next function will resolve the argument type according to the current key. Instead, the argument get resolved to the type never and I get the error message:

Argument of type 'number | "light" | "dark"' is not assignable to
  parameter of type 'never'. Type 'number' is not assignable to type
  'never'`

The next function should infers the current argument as Mode when key === "mode", and when key === "test" it should be inferred as number

答:
Yeah, this is one of those pain points in TypeScript that I've been calling correlated types.  The problem is that you have a set of values of union types which are not independent of each other.  next is correlated to current in a way that depends on the value of key.  But TypeScript just sees next as a union of values-or-functions-or-undefined (which is correct) and current as a union of values (which is also correct) without realizing that it is impossible for next to correspond to "mode" and for current to correspond to "test" at the same time.  The improved support for calling unions of functions only makes this problem more confusing, since the never intersection doesn't give much clue as to what's going on.

There's no great solution here.  The ways to deal with this I've found are either to walk the compiler manually through the different cases, as in:

```<code>  (Object.keys(action) as (keyof Theme)[]).forEach(key => {
    switch (key) {
      case "mode": {
        const next = action[key];
        const current = currentTheme[key];
        newTheme[key] = typeof next === "function" ? next(current) : next; // okay
        break;
      }
      case "test": {
        const next = action[key];
        const current = currentTheme[key];
        newTheme[key] = typeof next === "function" ? next(current) : next; // okay
        break;
      }
    }
  });
</code>```

which is quite type safe but is tedious...

Or, else you will need to make a type assertion somewhere to convince the compiler that what you are doing is safe (which is you taking on the responsibility for the safety; the compiler is giving up).  For this particular issue, I'd consider making the forEach() callback a generic function in the key type K and then using your assertion to tell the compiler that next is dependent on K in a way it understands:

```<code>  (Object.keys(action) as (keyof Theme)[]).forEach(
    // generic
    <K extends keyof Theme>(key: K) => {
      const next = action[key] as  // assert here
        | Theme[K]
        | ((current: Theme[K]) => Theme[K])
        | undefined;
      const current = currentTheme[key];
      newTheme[key] = typeof next === "function" ? next(current) : next; // okay
    }
  );
</code>```

which is more convenient but not as safe.

I generally recommend assertions here (link to code) and hope that one day better support for correlated types in TypeScript is introduced.

Okay, hope that helps.  Good luck!

Body:
I'm trying to create a type based on another one with the same keys and whose value's type is based on, but not equal to, the another type. It's similar to React's setState, where it accepts either a value or a function that get the current value and returns a new one.

After research, all issues related to this error seems related to a lack of type hinting. I already tried to specified the types for all next, current and newTheme[key] variables. It didn't work.

type Mode = "light" | "dark";

interface Theme {
  mode: Mode;
  test: number;
}

type ThemeUpdate = {
  [K in keyof Theme]: Theme[K] | ((current: Theme[K]) => Theme[K])
};

const reducer = (currentTheme: Theme, action: Partial<ThemeUpdate>): Theme => {
  const newTheme: Partial<Theme> = {};

  (Object.keys(action) as (keyof Theme)[]).forEach((key: keyof Theme) => {
    const next = action[key];
    const current = currentTheme[key];
    newTheme[key] = typeof next === "function" ? next(current) : next;
    //                                                ^^^^^^^
    // Argument of type 'number | "light" | "dark"' is not assignable to parameter of type 'never'. Type 'number' is not assignable to type 'never'
  });

  return { ...currentTheme, ...newTheme };
};

What I expect is that the next function will resolve the argument type according to the current key. Instead, the argument get resolved to the type never and I get the error message:

Argument of type 'number | "light" | "dark"' is not assignable to
  parameter of type 'never'. Type 'number' is not assignable to type
  'never'`

The next function should infers the current argument as Mode when key === "mode", and when key === "test" it should be inferred as number

Body:
Yeah, this is one of those pain points in TypeScript that I've been calling correlated types.  The problem is that you have a set of values of union types which are not independent of each other.  next is correlated to current in a way that depends on the value of key.  But TypeScript just sees next as a union of values-or-functions-or-undefined (which is correct) and current as a union of values (which is also correct) without realizing that it is impossible for next to correspond to "mode" and for current to correspond to "test" at the same time.  The improved support for calling unions of functions only makes this problem more confusing, since the never intersection doesn't give much clue as to what's going on.

There's no great solution here.  The ways to deal with this I've found are either to walk the compiler manually through the different cases, as in:

  (Object.keys(action) as (keyof Theme)[]).forEach(key => {
    switch (key) {
      case "mode": {
        const next = action[key];
        const current = currentTheme[key];
        newTheme[key] = typeof next === "function" ? next(current) : next; // okay
        break;
      }
      case "test": {
        const next = action[key];
        const current = currentTheme[key];
        newTheme[key] = typeof next === "function" ? next(current) : next; // okay
        break;
      }
    }
  });

which is quite type safe but is tedious...

Or, else you will need to make a type assertion somewhere to convince the compiler that what you are doing is safe (which is you taking on the responsibility for the safety; the compiler is giving up).  For this particular issue, I'd consider making the forEach() callback a generic function in the key type K and then using your assertion to tell the compiler that next is dependent on K in a way it understands:

  (Object.keys(action) as (keyof Theme)[]).forEach(
    // generic
    <K extends keyof Theme>(key: K) => {
      const next = action[key] as  // assert here
        | Theme[K]
        | ((current: Theme[K]) => Theme[K])
        | undefined;
      const current = currentTheme[key];
      newTheme[key] = typeof next === "function" ? next(current) : next; // okay
    }
  );

which is more convenient but not as safe.

I generally recommend assertions here (<a href="https://typescript-play.js.org/#code/C4TwDgpgBAsg9gE2gXigIgDYEsDmALYNKAH3QQEMAnAazQG4AoBrAO2AkoDNyBjaAFTwQAttADeDKFGGIIALlizGU9gGdgClgFdhAIw6MAvk1CQogkRACqYCuyioJUgNoBpKKyjUIIOJ3NCogC6ChaibkEkUAAU0TxalJQQbKGBEBEAlA4AfAGWmQyGjAw8cCzqUEkIWnyUDjHxicnAYfJ5ogA0ULzAWGUKAApUveQYADytNnYQ2RmpljlQTlCl5cBQLBAA7q2Dw1ijE2m5jkVMUtEA8roAVhA8wAB03iCq0T19LFnkqjEvfu0IBlnEEMo9OHBKABRXh4aKSKRQAD0SKgOGSHCwPARUjG7ggAA92CwEL9-v5Wtloi8FK4sshcstESsyhVNkT6h8ys4XpEflIUd1VKoOOshEkccyoq0IpLmaRYo0kilAZlFjLXKC5YjSFoSRBOKwIAhlFLVhUlc16pa2DLeabmZsdmkeT5IqhTBAAez1sg-ehOHqHp8iAB+DaE4BxBLK4BZTSRh1QYxSDLFKRJYAJFhLKCPfM2lppLr5x5O1rJoyMIA" rel="nofollow noreferrer">link to code) and hope that one day better support for correlated types in TypeScript is introduced.

Okay, hope that helps.  Good luck!


问:
are custom PHP logging and logging all possible errors mutually exclusive?
I've been using set_error_handler to override the default php error handling with the sole purpose to have customized errors logging. but I've come to a conclusion that one simply can't have customized error logging and log all possible errors.

1) You can use set_error_handler() - but this function, quote from php manual:

following error types cannot be
  handled with a user defined function:
  E_ERROR, E_PARSE, E_CORE_ERROR,
  E_CORE_WARNING, E_COMPILE_ERROR,
  E_COMPILE_WARNING, and most of
  E_STRICT

So - by going this route - your customized log won't have these errors logged?

2) Second way is to use register_shutdown_function() and then run error_get_last() to get the the error... But - error_get_last() ... only gets the last error ... and while you might have multiple warnings and notices during script execution - this approach will only allow you to log the most recent error, notice, warning - right?

So - IMHO - I'm not seeing any way around this. Looks like if one wants to have the most complete error log - should just stick to default php logger - right?

答:
1) Thats correct. Its because this errors will stop the whole php-process from working properly and so it doesnt make much sense to allow the software to recover itself. However, if you write software, that breaks that hard, you have other problems than the logging.

2) Seems correct so far. But you also have set_error_handler() for this.


问:
Ylim max to change dynamically with a variable, while min is set to 0 in R
I would like my graphs to start at y= 0, but I would like the maximum to change with a multiple of the data, or somehow otherwise zoom out dynamically. I have 34 charts in this set with various ymax.

I have tried scale_y_continuous and coord_cartesian but when I try to put in the expand = expand_scale(mult = 2) that works for getting my maximum to change dynamically, but then the graphs start to start at negative numbers, and I want them to start at 0.

```<code>title<- c(
  "Carangidae",
  "Atlantic cutlassfish",
  "Lizardfish",
  "Sharks",
  "Mackerel")
</code>```

```<code>#DATA#
biomass<- structure(list(timestep = structure(c(10957, 10988, 11017, 11048,
11078, 11109, 11139, 11170, 11201, 11231, 11262, 11292), class = "Date"),
    bio_pre_Carangidae = c(0.01105, 0.0199, 0.017,
    0.01018, 0.0119, 0.0101, 0.009874, 0.009507,
    0.009019, 0.00843, 0.00841, 0.00805), bio_obs_Carangidae = c(NA,
    NA, NA, NA, NA, 0.00239, NA, NA, NA, NA, NA, NA), bio_pre_Atl_cutlassfish = c(0.078,
    0.069, 0.067, 0.06872, 0.0729, 0.0769,
    0.0775, 0.075, 0.0743, 0.072, 0.071,
    0.069), bio_obs_Atl_cutlassfish = c(NA, NA, NA, NA, NA,
    0.0325, NA, NA, NA, NA, NA, NA), bio_pre_lizardfish = c(0.0635,
    0.062, 0.057, 0.0536, 0.0505, 0.0604,
    0.0627, 0.068, 0.0695, 0.066, 0.0623,
    0.0598), bio_obs_lizardfish = c(NA, NA, NA, NA, NA, 0.037,
    NA, NA, NA, NA, NA, NA), bio_pre_sharks = c(0.025, 0.0155,
    0.0148, 0.0135, 0.01379, 0.01398, 0.014,
    0.0139, 0.0136, 0.0132, 0.0126, 0.011),
    bio_obs_sharks = c(NA, NA, NA, NA, NA, 0.003, NA, NA,
    NA, NA, NA, NA), bio_pre_mackerel = c(0.0567, 0.0459,
    0.0384, 0.03, 0.0328, 0.0336, 0.0299,
    0.0296, 0.02343, 0.02713, 0.0239, 0.019
    ), bio_obs_mackerel = c(NA, NA, NA, NA, NA, 0.055, NA,
    NA, NA, NA, NA, NA)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -12L))
</code>```

This is my function:

```<code>function (biomass, .var1, .var2, .var3) {
    p <- ggplot(biomass, aes(x = timestep)) +
geom_line(aes(y = .data[[.var1]], linetype = "Predicted")) + geom_point(size = 3, aes(y = .data[[.var2]], shape = "Observed")) +
ggtitle(paste0(.var3)) +
ylab(expression("biomass" ~ (t/km^2))) +
theme_classic() +
scale_y_continuous(limits = c(0, NA), expand = expand_scale(mult = 2))+

  ###This is the portion where I cannot figure out how to set ymin = 0 and then ymax to 2* the maximum value of a dataset.##

theme(legend.position = "right") +
theme(axis.ticks = element_line(size = 1), axis.ticks.length = unit(0.25, "cm"))
    return(p)
}

## create two separate name vectors
var1_names <- colnames(biomass)[grepl("^bio_pre", colnames(biomass))]
var2_names <- colnames(biomass)[grepl("^bio_obs", colnames(biomass))]
var3_names <- title

## loop through two vectors simultaneously and save result in a list
# ..1 = var1_names, ..2 = var2_names
my_plot_b <- pmap(list(var1_names, var2_names, var3_names), ~ my_bio_plot(biomass, ..1, ..2, ..3))

## merge plots together
# https://cran.r-project.org/web/packages/cowplot/
# install.packages("cowplot", dependencies = TRUE)
dev.new(title = "Model Fit Biomass",
        width = 12,
        height = 6,
        noRStudioGD = TRUE
)
print(my_plot_b)
</code>```

I can manage to get EITHER a set ymin=0 (a) OR a dynamic ymax (b) but cannot manage to get both.

a

b

答:
Updated to add a substantially different approach from yours:

```<code>biomass %>%
  gather(species, bio, -timestep) %>%
  mutate(type = ifelse(stringr::str_detect(species, 'pre'), 'predicted', 'observed'),
         species = gsub(".*_", "", species)) %>%
  group_by(species) %>%
  mutate(ul = max(bio, na.rm = TRUE) * 2) %>%
  filter(species == "sharks") -> df

df %>%
  ggplot(aes(timestep, bio, group = type)) +
  geom_point(aes(shape = type)) +
  geom_line(aes(linetype = type)) +
  # facet_wrap(~species) +
  scale_linetype_manual(name = "",
                        values = c("blank", 'solid')) +
  scale_shape_manual(name = "",
                        values = c(19, NA))+
  scale_y_continuous(limits = c(0, max(df$ul)))
</code>```

You could remove the filter(species == "sharks") and uncomment thefacet_wrap(~species) and you will get all the species plotted at the same time.

Body:
I would like my graphs to start at y= 0, but I would like the maximum to change with a multiple of the data, or somehow otherwise zoom out dynamically. I have 34 charts in this set with various ymax.

I have tried scale_y_continuous and coord_cartesian but when I try to put in the expand = expand_scale(mult = 2) that works for getting my maximum to change dynamically, but then the graphs start to start at negative numbers, and I want them to start at 0.

title<- c(
  "Carangidae",
  "Atlantic cutlassfish",
  "Lizardfish",
  "Sharks",
  "Mackerel")

#DATA#
biomass<- structure(list(timestep = structure(c(10957, 10988, 11017, 11048,
11078, 11109, 11139, 11170, 11201, 11231, 11262, 11292), class = "Date"),
    bio_pre_Carangidae = c(0.01105, 0.0199, 0.017,
    0.01018, 0.0119, 0.0101, 0.009874, 0.009507,
    0.009019, 0.00843, 0.00841, 0.00805), bio_obs_Carangidae = c(NA,
    NA, NA, NA, NA, 0.00239, NA, NA, NA, NA, NA, NA), bio_pre_Atl_cutlassfish = c(0.078,
    0.069, 0.067, 0.06872, 0.0729, 0.0769,
    0.0775, 0.075, 0.0743, 0.072, 0.071,
    0.069), bio_obs_Atl_cutlassfish = c(NA, NA, NA, NA, NA,
    0.0325, NA, NA, NA, NA, NA, NA), bio_pre_lizardfish = c(0.0635,
    0.062, 0.057, 0.0536, 0.0505, 0.0604,
    0.0627, 0.068, 0.0695, 0.066, 0.0623,
    0.0598), bio_obs_lizardfish = c(NA, NA, NA, NA, NA, 0.037,
    NA, NA, NA, NA, NA, NA), bio_pre_sharks = c(0.025, 0.0155,
    0.0148, 0.0135, 0.01379, 0.01398, 0.014,
    0.0139, 0.0136, 0.0132, 0.0126, 0.011),
    bio_obs_sharks = c(NA, NA, NA, NA, NA, 0.003, NA, NA,
    NA, NA, NA, NA), bio_pre_mackerel = c(0.0567, 0.0459,
    0.0384, 0.03, 0.0328, 0.0336, 0.0299,
    0.0296, 0.02343, 0.02713, 0.0239, 0.019
    ), bio_obs_mackerel = c(NA, NA, NA, NA, NA, 0.055, NA,
    NA, NA, NA, NA, NA)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -12L))

This is my function:

function (biomass, .var1, .var2, .var3) {
    p <- ggplot(biomass, aes(x = timestep)) +
geom_line(aes(y = .data[[.var1]], linetype = "Predicted")) + geom_point(size = 3, aes(y = .data[[.var2]], shape = "Observed")) +
ggtitle(paste0(.var3)) +
ylab(expression("biomass" ~ (t/km^2))) +
theme_classic() +
scale_y_continuous(limits = c(0, NA), expand = expand_scale(mult = 2))+

  ###This is the portion where I cannot figure out how to set ymin = 0 and then ymax to 2* the maximum value of a dataset.##

theme(legend.position = "right") +
theme(axis.ticks = element_line(size = 1), axis.ticks.length = unit(0.25, "cm"))
    return(p)
}

## create two separate name vectors
var1_names <- colnames(biomass)[grepl("^bio_pre", colnames(biomass))]
var2_names <- colnames(biomass)[grepl("^bio_obs", colnames(biomass))]
var3_names <- title

## loop through two vectors simultaneously and save result in a list
# ..1 = var1_names, ..2 = var2_names
my_plot_b <- pmap(list(var1_names, var2_names, var3_names), ~ my_bio_plot(biomass, ..1, ..2, ..3))

## merge plots together
# https://cran.r-project.org/web/packages/cowplot/
# install.packages("cowplot", dependencies = TRUE)
dev.new(title = "Model Fit Biomass",
        width = 12,
        height = 6,
        noRStudioGD = TRUE
)
print(my_plot_b)

I can manage to get EITHER a set ymin=0 (a) OR a dynamic ymax (b) but cannot manage to get both.

a

b

Body:
Updated to add a substantially different approach from yours:

biomass %>%
  gather(species, bio, -timestep) %>%
  mutate(type = ifelse(stringr::str_detect(species, 'pre'), 'predicted', 'observed'),
         species = gsub(".*_", "", species)) %>%
  group_by(species) %>%
  mutate(ul = max(bio, na.rm = TRUE) * 2) %>%
  filter(species == "sharks") -> df

df %>%
  ggplot(aes(timestep, bio, group = type)) +
  geom_point(aes(shape = type)) +
  geom_line(aes(linetype = type)) +
  # facet_wrap(~species) +
  scale_linetype_manual(name = "",
                        values = c("blank", 'solid')) +
  scale_shape_manual(name = "",
                        values = c(19, NA))+
  scale_y_continuous(limits = c(0, max(df$ul)))

You could remove the filter(species == "sharks") and uncomment thefacet_wrap(~species) and you will get all the species plotted at the same time.


问:
Why does Java compile to assembly twice?
I compiled a simple Java file to assembly using Java 8 on Mac OS X. This is Test.java:

```<code>public class Test {

    static volatile int a = 1;

    public static void main(String[] args) {
        a++;
    }
}
</code>```

I output the assembly code using:

```<code>java -server -Xcomp -XX:+UnlockDiagnosticVMOptions -XX:-Inline -XX:CompileCommand=print,*Test.main Test>Test.asm
</code>```

This is the Test.asm output:

```<code>CompilerOracle: print *Test.main
Compiled method (c1)    1733 1750       3       Test::main (9 bytes)
 total in heap  [0x0000000111848650,0x0000000111848970] = 800
 relocation     [0x0000000111848778,0x00000001118487a0] = 40
 main code      [0x00000001118487a0,0x0000000111848860] = 192
 stub code      [0x0000000111848860,0x00000001118488f0] = 144
 oops           [0x00000001118488f0,0x00000001118488f8] = 8
 metadata       [0x00000001118488f8,0x0000000111848900] = 8
 scopes data    [0x0000000111848900,0x0000000111848918] = 24
 scopes pcs     [0x0000000111848918,0x0000000111848968] = 80
 dependencies   [0x0000000111848968,0x0000000111848970] = 8
Loaded disassembler from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/hsdis-amd64.dylib
Decoding compiled method 0x0000000111848650:
Code:
[Disassembling for mach='i386:x86-64']
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000010e40e240} 'main' '([Ljava/lang/String;)V' in 'Test'
  # parm0:    rsi:rsi   = '[Ljava/lang/String;'
  #           [sp+0x40]  (sp of caller)
  0x00000001118487a0: mov    %eax,-0x14000(%rsp)
  0x00000001118487a7: push   %rbp
  0x00000001118487a8: sub    $0x30,%rsp
  0x00000001118487ac: movabs $0x10e40e4d0,%rdi  ;   {metadata(method data for {method} {0x000000010e40e240} 'main' '([Ljava/lang/String;)V' in 'Test')}
  0x00000001118487b6: mov    0xdc(%rdi),%ebx
  0x00000001118487bc: add    $0x8,%ebx
  0x00000001118487bf: mov    %ebx,0xdc(%rdi)
  0x00000001118487c5: movabs $0x10e40e240,%rdi  ;   {metadata({method} {0x000000010e40e240} 'main' '([Ljava/lang/String;)V' in 'Test')}
  0x00000001118487cf: and    $0x0,%ebx
  0x00000001118487d2: cmp    $0x0,%ebx
  0x00000001118487d5: je     0x00000001118487fe
  0x00000001118487db: movabs $0x7955fd1e8,%rsi  ;   {oop(a 'java/lang/Class' = 'Test')}
  0x00000001118487e5: mov    0x68(%rsi),%edi    ;*getstatic a
                                                ; - Test::main@0 (line 6)

  0x00000001118487e8: inc    %edi
  0x00000001118487ea: mov    %edi,0x68(%rsi)
  0x00000001118487ed: lock addl $0x0,(%rsp)     ;*putstatic a
                                                ; - Test::main@5 (line 6)

  0x00000001118487f2: add    $0x30,%rsp
  0x00000001118487f6: pop    %rbp
  0x00000001118487f7: test   %eax,-0x5f7f6fd(%rip)        # 0x000000010b8c9100
                                                ;   {poll_return}
  0x00000001118487fd: retq
  0x00000001118487fe: mov    %rdi,0x8(%rsp)
  0x0000000111848803: movq   $0xffffffffffffffff,(%rsp)
  0x000000011184880b: callq  0x0000000111543f60  ; OopMap{rsi=Oop off=112}
                                                ;*synchronization entry
                                                ; - Test::main@-1 (line 6)
                                                ;   {runtime_call}
  0x0000000111848810: jmp    0x00000001118487db
  0x0000000111848812: nop
  0x0000000111848813: nop
  0x0000000111848814: mov    0x2a8(%r15),%rax
  0x000000011184881b: movabs $0x0,%r10
  0x0000000111848825: mov    %r10,0x2a8(%r15)
  0x000000011184882c: movabs $0x0,%r10
  0x0000000111848836: mov    %r10,0x2b0(%r15)
  0x000000011184883d: add    $0x30,%rsp
  0x0000000111848841: pop    %rbp
  0x0000000111848842: jmpq   0x00000001114b24a0  ;   {runtime_call}
  0x0000000111848847: hlt
  0x0000000111848848: hlt
  0x0000000111848849: hlt
  0x000000011184884a: hlt
  0x000000011184884b: hlt
  0x000000011184884c: hlt
  0x000000011184884d: hlt
  0x000000011184884e: hlt
  0x000000011184884f: hlt
  0x0000000111848850: hlt
  0x0000000111848851: hlt
  0x0000000111848852: hlt
  0x0000000111848853: hlt
  0x0000000111848854: hlt
  0x0000000111848855: hlt
  0x0000000111848856: hlt
  0x0000000111848857: hlt
  0x0000000111848858: hlt
  0x0000000111848859: hlt
  0x000000011184885a: hlt
  0x000000011184885b: hlt
  0x000000011184885c: hlt
  0x000000011184885d: hlt
  0x000000011184885e: hlt
  0x000000011184885f: hlt
[Exception Handler]
[Stub Code]
  0x0000000111848860: callq  0x00000001115418e0  ;   {no_reloc}
  0x0000000111848865: mov    %rsp,-0x28(%rsp)
  0x000000011184886a: sub    $0x80,%rsp
  0x0000000111848871: mov    %rax,0x78(%rsp)
  0x0000000111848876: mov    %rcx,0x70(%rsp)
  0x000000011184887b: mov    %rdx,0x68(%rsp)
  0x0000000111848880: mov    %rbx,0x60(%rsp)
  0x0000000111848885: mov    %rbp,0x50(%rsp)
  0x000000011184888a: mov    %rsi,0x48(%rsp)
  0x000000011184888f: mov    %rdi,0x40(%rsp)
  0x0000000111848894: mov    %r8,0x38(%rsp)
  0x0000000111848899: mov    %r9,0x30(%rsp)
  0x000000011184889e: mov    %r10,0x28(%rsp)
  0x00000001118488a3: mov    %r11,0x20(%rsp)
  0x00000001118488a8: mov    %r12,0x18(%rsp)
  0x00000001118488ad: mov    %r13,0x10(%rsp)
  0x00000001118488b2: mov    %r14,0x8(%rsp)
  0x00000001118488b7: mov    %r15,(%rsp)
  0x00000001118488bb: movabs $0x10c7d8060,%rdi  ;   {external_word}
  0x00000001118488c5: movabs $0x111848865,%rsi  ;   {internal_word}
  0x00000001118488cf: mov    %rsp,%rdx
  0x00000001118488d2: and    $0xfffffffffffffff0,%rsp
  0x00000001118488d6: callq  0x000000010c60361a  ;   {runtime_call}
  0x00000001118488db: hlt
[Deopt Handler Code]
  0x00000001118488dc: movabs $0x1118488dc,%r10  ;   {section_word}
  0x00000001118488e6: push   %r10
  0x00000001118488e8: jmpq   0x000000011148d3c0  ;   {runtime_call}
  0x00000001118488ed: hlt
  0x00000001118488ee: hlt
  0x00000001118488ef: hlt
OopMapSet contains 1 OopMaps

#0
OopMap{rsi=Oop off=112}
Compiled method (c1)    1747 1751       1       Test::main (9 bytes)
 total in heap  [0x0000000111847250,0x0000000111847518] = 712
 relocation     [0x0000000111847378,0x00000001118473a0] = 40
 main code      [0x00000001118473a0,0x0000000111847420] = 128
 stub code      [0x0000000111847420,0x00000001118474b0] = 144
 oops           [0x00000001118474b0,0x00000001118474b8] = 8
 metadata       [0x00000001118474b8,0x00000001118474c0] = 8
 scopes data    [0x00000001118474c0,0x00000001118474d0] = 16
 scopes pcs     [0x00000001118474d0,0x0000000111847510] = 64
 dependencies   [0x0000000111847510,0x0000000111847518] = 8
Decoding compiled method 0x0000000111847250:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000010e40e240} 'main' '([Ljava/lang/String;)V' in 'Test'
  # parm0:    rsi:rsi   = '[Ljava/lang/String;'
  #           [sp+0x40]  (sp of caller)
  0x00000001118473a0: mov    %eax,-0x14000(%rsp)
  0x00000001118473a7: push   %rbp
  0x00000001118473a8: sub    $0x30,%rsp
  0x00000001118473ac: movabs $0x7955fd1e8,%rsi  ;   {oop(a 'java/lang/Class' = 'Test')}
  0x00000001118473b6: mov    0x68(%rsi),%edi    ;*getstatic a
                                                ; - Test::main@0 (line 6)

  0x00000001118473b9: inc    %edi
  0x00000001118473bb: mov    %edi,0x68(%rsi)
  0x00000001118473be: lock addl $0x0,(%rsp)     ;*putstatic a
                                                ; - Test::main@5 (line 6)

  0x00000001118473c3: add    $0x30,%rsp
  0x00000001118473c7: pop    %rbp
  0x00000001118473c8: test   %eax,-0x5f7e2ce(%rip)        # 0x000000010b8c9100
                                                ;   {poll_return}
  0x00000001118473ce: retq
  0x00000001118473cf: nop
  0x00000001118473d0: nop
  0x00000001118473d1: mov    0x2a8(%r15),%rax
  0x00000001118473d8: movabs $0x0,%r10
  0x00000001118473e2: mov    %r10,0x2a8(%r15)
  0x00000001118473e9: movabs $0x0,%r10
  0x00000001118473f3: mov    %r10,0x2b0(%r15)
  0x00000001118473fa: add    $0x30,%rsp
  0x00000001118473fe: pop    %rbp
  0x00000001118473ff: jmpq   0x00000001114b24a0  ;   {runtime_call}
  0x0000000111847404: hlt
  0x0000000111847405: hlt
  0x0000000111847406: hlt
  0x0000000111847407: hlt
  0x0000000111847408: hlt
  0x0000000111847409: hlt
  0x000000011184740a: hlt
  0x000000011184740b: hlt
  0x000000011184740c: hlt
  0x000000011184740d: hlt
  0x000000011184740e: hlt
  0x000000011184740f: hlt
  0x0000000111847410: hlt
  0x0000000111847411: hlt
  0x0000000111847412: hlt
  0x0000000111847413: hlt
  0x0000000111847414: hlt
  0x0000000111847415: hlt
  0x0000000111847416: hlt
  0x0000000111847417: hlt
  0x0000000111847418: hlt
  0x0000000111847419: hlt
  0x000000011184741a: hlt
  0x000000011184741b: hlt
  0x000000011184741c: hlt
  0x000000011184741d: hlt
  0x000000011184741e: hlt
  0x000000011184741f: hlt
[Exception Handler]
[Stub Code]
  0x0000000111847420: callq  0x00000001115418e0  ;   {no_reloc}
  0x0000000111847425: mov    %rsp,-0x28(%rsp)
  0x000000011184742a: sub    $0x80,%rsp
  0x0000000111847431: mov    %rax,0x78(%rsp)
  0x0000000111847436: mov    %rcx,0x70(%rsp)
  0x000000011184743b: mov    %rdx,0x68(%rsp)
  0x0000000111847440: mov    %rbx,0x60(%rsp)
  0x0000000111847445: mov    %rbp,0x50(%rsp)
  0x000000011184744a: mov    %rsi,0x48(%rsp)
  0x000000011184744f: mov    %rdi,0x40(%rsp)
  0x0000000111847454: mov    %r8,0x38(%rsp)
  0x0000000111847459: mov    %r9,0x30(%rsp)
  0x000000011184745e: mov    %r10,0x28(%rsp)
  0x0000000111847463: mov    %r11,0x20(%rsp)
  0x0000000111847468: mov    %r12,0x18(%rsp)
  0x000000011184746d: mov    %r13,0x10(%rsp)
  0x0000000111847472: mov    %r14,0x8(%rsp)
  0x0000000111847477: mov    %r15,(%rsp)
  0x000000011184747b: movabs $0x10c7d8060,%rdi  ;   {external_word}
  0x0000000111847485: movabs $0x111847425,%rsi  ;   {internal_word}
  0x000000011184748f: mov    %rsp,%rdx
  0x0000000111847492: and    $0xfffffffffffffff0,%rsp
  0x0000000111847496: callq  0x000000010c60361a  ;   {runtime_call}
  0x000000011184749b: hlt
[Deopt Handler Code]
  0x000000011184749c: movabs $0x11184749c,%r10  ;   {section_word}
  0x00000001118474a6: push   %r10
  0x00000001118474a8: jmpq   0x000000011148d3c0  ;   {runtime_call}
  0x00000001118474ad: hlt
  0x00000001118474ae: hlt
  0x00000001118474af: hlt
OopMapSet contains 0 OopMaps
</code>```

The question is: why does the generated assembly code have two main methods and how do I make it have only one?

答:
Why does the generated assembly code have two main methods?

The Assembly contains the result of the work of the C1 compiler at different compilation levels:

```<code>C1 / Level 3

C1 / Level 1
</code>```

The appropriate information is present in the Test.asm output:

```<code>Compiled method (c1)    1733 1750       3       Test::main (9 bytes)

Compiled method (c1)    1747 1751       1       Test::main (9 bytes)
</code>```

In order to remove an extra compilation overhead, you can set -XX:TieredStopAtLevel=1 - check this answer for more details.

Body:
I compiled a simple Java file to assembly using Java 8 on Mac OS X. This is Test.java:

public class Test {

    static volatile int a = 1;

    public static void main(String[] args) {
        a++;
    }
}

I output the assembly code using:

java -server -Xcomp -XX:+UnlockDiagnosticVMOptions -XX:-Inline -XX:CompileCommand=print,*Test.main Test>Test.asm

This is the Test.asm output:

CompilerOracle: print *Test.main
Compiled method (c1)    1733 1750       3       Test::main (9 bytes)
 total in heap  [0x0000000111848650,0x0000000111848970] = 800
 relocation     [0x0000000111848778,0x00000001118487a0] = 40
 main code      [0x00000001118487a0,0x0000000111848860] = 192
 stub code      [0x0000000111848860,0x00000001118488f0] = 144
 oops           [0x00000001118488f0,0x00000001118488f8] = 8
 metadata       [0x00000001118488f8,0x0000000111848900] = 8
 scopes data    [0x0000000111848900,0x0000000111848918] = 24
 scopes pcs     [0x0000000111848918,0x0000000111848968] = 80
 dependencies   [0x0000000111848968,0x0000000111848970] = 8
Loaded disassembler from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/hsdis-amd64.dylib
Decoding compiled method 0x0000000111848650:
Code:
[Disassembling for mach='i386:x86-64']
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000010e40e240} 'main' '([Ljava/lang/String;)V' in 'Test'
  # parm0:    rsi:rsi   = '[Ljava/lang/String;'
  #           [sp+0x40]  (sp of caller)
  0x00000001118487a0: mov    %eax,-0x14000(%rsp)
  0x00000001118487a7: push   %rbp
  0x00000001118487a8: sub    $0x30,%rsp
  0x00000001118487ac: movabs $0x10e40e4d0,%rdi  ;   {metadata(method data for {method} {0x000000010e40e240} 'main' '([Ljava/lang/String;)V' in 'Test')}
  0x00000001118487b6: mov    0xdc(%rdi),%ebx
  0x00000001118487bc: add    $0x8,%ebx
  0x00000001118487bf: mov    %ebx,0xdc(%rdi)
  0x00000001118487c5: movabs $0x10e40e240,%rdi  ;   {metadata({method} {0x000000010e40e240} 'main' '([Ljava/lang/String;)V' in 'Test')}
  0x00000001118487cf: and    $0x0,%ebx
  0x00000001118487d2: cmp    $0x0,%ebx
  0x00000001118487d5: je     0x00000001118487fe
  0x00000001118487db: movabs $0x7955fd1e8,%rsi  ;   {oop(a 'java/lang/Class' = 'Test')}
  0x00000001118487e5: mov    0x68(%rsi),%edi    ;*getstatic a
                                                ; - Test::main@0 (line 6)

  0x00000001118487e8: inc    %edi
  0x00000001118487ea: mov    %edi,0x68(%rsi)
  0x00000001118487ed: lock addl $0x0,(%rsp)     ;*putstatic a
                                                ; - Test::main@5 (line 6)

  0x00000001118487f2: add    $0x30,%rsp
  0x00000001118487f6: pop    %rbp
  0x00000001118487f7: test   %eax,-0x5f7f6fd(%rip)        # 0x000000010b8c9100
                                                ;   {poll_return}
  0x00000001118487fd: retq
  0x00000001118487fe: mov    %rdi,0x8(%rsp)
  0x0000000111848803: movq   $0xffffffffffffffff,(%rsp)
  0x000000011184880b: callq  0x0000000111543f60  ; OopMap{rsi=Oop off=112}
                                                ;*synchronization entry
                                                ; - Test::main@-1 (line 6)
                                                ;   {runtime_call}
  0x0000000111848810: jmp    0x00000001118487db
  0x0000000111848812: nop
  0x0000000111848813: nop
  0x0000000111848814: mov    0x2a8(%r15),%rax
  0x000000011184881b: movabs $0x0,%r10
  0x0000000111848825: mov    %r10,0x2a8(%r15)
  0x000000011184882c: movabs $0x0,%r10
  0x0000000111848836: mov    %r10,0x2b0(%r15)
  0x000000011184883d: add    $0x30,%rsp
  0x0000000111848841: pop    %rbp
  0x0000000111848842: jmpq   0x00000001114b24a0  ;   {runtime_call}
  0x0000000111848847: hlt
  0x0000000111848848: hlt
  0x0000000111848849: hlt
  0x000000011184884a: hlt
  0x000000011184884b: hlt
  0x000000011184884c: hlt
  0x000000011184884d: hlt
  0x000000011184884e: hlt
  0x000000011184884f: hlt
  0x0000000111848850: hlt
  0x0000000111848851: hlt
  0x0000000111848852: hlt
  0x0000000111848853: hlt
  0x0000000111848854: hlt
  0x0000000111848855: hlt
  0x0000000111848856: hlt
  0x0000000111848857: hlt
  0x0000000111848858: hlt
  0x0000000111848859: hlt
  0x000000011184885a: hlt
  0x000000011184885b: hlt
  0x000000011184885c: hlt
  0x000000011184885d: hlt
  0x000000011184885e: hlt
  0x000000011184885f: hlt
[Exception Handler]
[Stub Code]
  0x0000000111848860: callq  0x00000001115418e0  ;   {no_reloc}
  0x0000000111848865: mov    %rsp,-0x28(%rsp)
  0x000000011184886a: sub    $0x80,%rsp
  0x0000000111848871: mov    %rax,0x78(%rsp)
  0x0000000111848876: mov    %rcx,0x70(%rsp)
  0x000000011184887b: mov    %rdx,0x68(%rsp)
  0x0000000111848880: mov    %rbx,0x60(%rsp)
  0x0000000111848885: mov    %rbp,0x50(%rsp)
  0x000000011184888a: mov    %rsi,0x48(%rsp)
  0x000000011184888f: mov    %rdi,0x40(%rsp)
  0x0000000111848894: mov    %r8,0x38(%rsp)
  0x0000000111848899: mov    %r9,0x30(%rsp)
  0x000000011184889e: mov    %r10,0x28(%rsp)
  0x00000001118488a3: mov    %r11,0x20(%rsp)
  0x00000001118488a8: mov    %r12,0x18(%rsp)
  0x00000001118488ad: mov    %r13,0x10(%rsp)
  0x00000001118488b2: mov    %r14,0x8(%rsp)
  0x00000001118488b7: mov    %r15,(%rsp)
  0x00000001118488bb: movabs $0x10c7d8060,%rdi  ;   {external_word}
  0x00000001118488c5: movabs $0x111848865,%rsi  ;   {internal_word}
  0x00000001118488cf: mov    %rsp,%rdx
  0x00000001118488d2: and    $0xfffffffffffffff0,%rsp
  0x00000001118488d6: callq  0x000000010c60361a  ;   {runtime_call}
  0x00000001118488db: hlt
[Deopt Handler Code]
  0x00000001118488dc: movabs $0x1118488dc,%r10  ;   {section_word}
  0x00000001118488e6: push   %r10
  0x00000001118488e8: jmpq   0x000000011148d3c0  ;   {runtime_call}
  0x00000001118488ed: hlt
  0x00000001118488ee: hlt
  0x00000001118488ef: hlt
OopMapSet contains 1 OopMaps

#0
OopMap{rsi=Oop off=112}
Compiled method (c1)    1747 1751       1       Test::main (9 bytes)
 total in heap  [0x0000000111847250,0x0000000111847518] = 712
 relocation     [0x0000000111847378,0x00000001118473a0] = 40
 main code      [0x00000001118473a0,0x0000000111847420] = 128
 stub code      [0x0000000111847420,0x00000001118474b0] = 144
 oops           [0x00000001118474b0,0x00000001118474b8] = 8
 metadata       [0x00000001118474b8,0x00000001118474c0] = 8
 scopes data    [0x00000001118474c0,0x00000001118474d0] = 16
 scopes pcs     [0x00000001118474d0,0x0000000111847510] = 64
 dependencies   [0x0000000111847510,0x0000000111847518] = 8
Decoding compiled method 0x0000000111847250:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000010e40e240} 'main' '([Ljava/lang/String;)V' in 'Test'
  # parm0:    rsi:rsi   = '[Ljava/lang/String;'
  #           [sp+0x40]  (sp of caller)
  0x00000001118473a0: mov    %eax,-0x14000(%rsp)
  0x00000001118473a7: push   %rbp
  0x00000001118473a8: sub    $0x30,%rsp
  0x00000001118473ac: movabs $0x7955fd1e8,%rsi  ;   {oop(a 'java/lang/Class' = 'Test')}
  0x00000001118473b6: mov    0x68(%rsi),%edi    ;*getstatic a
                                                ; - Test::main@0 (line 6)

  0x00000001118473b9: inc    %edi
  0x00000001118473bb: mov    %edi,0x68(%rsi)
  0x00000001118473be: lock addl $0x0,(%rsp)     ;*putstatic a
                                                ; - Test::main@5 (line 6)

  0x00000001118473c3: add    $0x30,%rsp
  0x00000001118473c7: pop    %rbp
  0x00000001118473c8: test   %eax,-0x5f7e2ce(%rip)        # 0x000000010b8c9100
                                                ;   {poll_return}
  0x00000001118473ce: retq
  0x00000001118473cf: nop
  0x00000001118473d0: nop
  0x00000001118473d1: mov    0x2a8(%r15),%rax
  0x00000001118473d8: movabs $0x0,%r10
  0x00000001118473e2: mov    %r10,0x2a8(%r15)
  0x00000001118473e9: movabs $0x0,%r10
  0x00000001118473f3: mov    %r10,0x2b0(%r15)
  0x00000001118473fa: add    $0x30,%rsp
  0x00000001118473fe: pop    %rbp
  0x00000001118473ff: jmpq   0x00000001114b24a0  ;   {runtime_call}
  0x0000000111847404: hlt
  0x0000000111847405: hlt
  0x0000000111847406: hlt
  0x0000000111847407: hlt
  0x0000000111847408: hlt
  0x0000000111847409: hlt
  0x000000011184740a: hlt
  0x000000011184740b: hlt
  0x000000011184740c: hlt
  0x000000011184740d: hlt
  0x000000011184740e: hlt
  0x000000011184740f: hlt
  0x0000000111847410: hlt
  0x0000000111847411: hlt
  0x0000000111847412: hlt
  0x0000000111847413: hlt
  0x0000000111847414: hlt
  0x0000000111847415: hlt
  0x0000000111847416: hlt
  0x0000000111847417: hlt
  0x0000000111847418: hlt
  0x0000000111847419: hlt
  0x000000011184741a: hlt
  0x000000011184741b: hlt
  0x000000011184741c: hlt
  0x000000011184741d: hlt
  0x000000011184741e: hlt
  0x000000011184741f: hlt
[Exception Handler]
[Stub Code]
  0x0000000111847420: callq  0x00000001115418e0  ;   {no_reloc}
  0x0000000111847425: mov    %rsp,-0x28(%rsp)
  0x000000011184742a: sub    $0x80,%rsp
  0x0000000111847431: mov    %rax,0x78(%rsp)
  0x0000000111847436: mov    %rcx,0x70(%rsp)
  0x000000011184743b: mov    %rdx,0x68(%rsp)
  0x0000000111847440: mov    %rbx,0x60(%rsp)
  0x0000000111847445: mov    %rbp,0x50(%rsp)
  0x000000011184744a: mov    %rsi,0x48(%rsp)
  0x000000011184744f: mov    %rdi,0x40(%rsp)
  0x0000000111847454: mov    %r8,0x38(%rsp)
  0x0000000111847459: mov    %r9,0x30(%rsp)
  0x000000011184745e: mov    %r10,0x28(%rsp)
  0x0000000111847463: mov    %r11,0x20(%rsp)
  0x0000000111847468: mov    %r12,0x18(%rsp)
  0x000000011184746d: mov    %r13,0x10(%rsp)
  0x0000000111847472: mov    %r14,0x8(%rsp)
  0x0000000111847477: mov    %r15,(%rsp)
  0x000000011184747b: movabs $0x10c7d8060,%rdi  ;   {external_word}
  0x0000000111847485: movabs $0x111847425,%rsi  ;   {internal_word}
  0x000000011184748f: mov    %rsp,%rdx
  0x0000000111847492: and    $0xfffffffffffffff0,%rsp
  0x0000000111847496: callq  0x000000010c60361a  ;   {runtime_call}
  0x000000011184749b: hlt
[Deopt Handler Code]
  0x000000011184749c: movabs $0x11184749c,%r10  ;   {section_word}
  0x00000001118474a6: push   %r10
  0x00000001118474a8: jmpq   0x000000011148d3c0  ;   {runtime_call}
  0x00000001118474ad: hlt
  0x00000001118474ae: hlt
  0x00000001118474af: hlt
OopMapSet contains 0 OopMaps

The question is: why does the generated assembly code have two main methods and how do I make it have only one?

Body:
Why does the generated assembly code have two main methods?

The Assembly contains the result of the work of the C1 compiler at different compilation levels:

C1 / Level 3

C1 / Level 1

The appropriate information is present in the Test.asm output:

Compiled method (c1)    1733 1750       3       Test::main (9 bytes)

Compiled method (c1)    1747 1751       1       Test::main (9 bytes)

In order to remove an extra compilation overhead, you can set -XX:TieredStopAtLevel=1 - check this answer for more details.