问:
Canvas generate problem with maximum call stack
I am making a script that auto generates planets see codepen for example.
But the problem I have is that i want to make it less pixelated and I am having some problems doing that if i make the tiles 70 * 70 and tile size to 10 * 10 pixels it works fine. But i want to have it set to something like tiles 360 * 360 and size to 1 or 2 pixels. But when I try to do that I get maximum call stack error. So I tried to use the requestAnimationFrame but then it take ages to load is there a way to speed up the process?

var tileNum = 0;
    var tiles;
    var colorsLand;
    var colorsWater;
    var size = 360;
    var tileSize = 2;
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    window.onload = function () {
        generatePlanet();
    }

    function generatePlanet() {
        tileNum = 0;
        tiles = [{ x: 0, y: 0, land: false }];

        //Retrive colors

        colorsLand = interpolateColors("rgb(" + getColor(true) + ")", "rgb(" + getColor(true) + ")", 6000);
        colorsWater = interpolateColors("rgb(" + getColor(false) + ")", "rgb(" + getColor(false) + ")", 6000);

        //Creates a array of my tiles and sets either water or land to them and calculates the % of being water/land
        for (var i = 0; i < (size * size); i++) {
            var currentTile = tiles[tiles.length - 1];
            if (currentTile.x <= (size - 1)) {
                var isLand = false;
                if (currentTile.land == true || tiles.length > size && tiles[tiles.length - size].land == true) {
                    isLand = (Math.floor(Math.random() * 100) + 1) > 35;
                }
                else if (currentTile.land == true || tiles.length > size &&
                    (tiles[tiles.length - 1].land == true ||
                        tiles[tiles.length - size].land == true)) {
                    isLand = (Math.floor(Math.random() * 100) + 1) > size;
                }
                else {
                    isLand = (Math.floor(Math.random() * 100) + 1) > 99;
                }
                tiles.push({ x: currentTile.x + 1, y: currentTile.y, land: isLand });
            }
            else {
                tiles.push({ x: 0, y: currentTile.y + 1, land: isLand });
            }
        }
        drawPlanet()
    }

    //retrive a random color if it's a land tile i want it dark water i want light
    function getColor(land) {
        while (true) {
            var r = Math.floor(Math.random() * 256) + 1
            var g = Math.floor(Math.random() * 256) + 1
            var b = Math.floor(Math.random() * 256) + 1
            var hsp = Math.sqrt(
                0.299 * (r * r) +
                0.587 * (g * g) +
                0.114 * (b * b)
            );
            //light color
            if (hsp > 127.5 && land == false) {
                return r + "," + g + "," + b;
            }
            //dark color
            else if (hsp < 127.5 && land == true) {
                return r + "," + g + "," + b;
            }
        }
    }

    //these 2 functions interpolateColor(s) takes 2 colors and gives me 'steps' colors between
    function interpolateColors(color1, color2, steps) {
        var stepFactor = 1 / (steps - 1),
            interpolatedColorArray = [];
        color1 = color1.match(/\d+/g).map(Number);
        color2 = color2.match(/\d+/g).map(Number);

        for (var i = 0; i < steps; i++) {
            interpolatedColorArray.push(interpolateColor(color1, color2, stepFactor * i));
        }
        return interpolatedColorArray;
    }

    function interpolateColor(color1, color2, factor) {
        if (arguments.length < 3) {
            factor = 0.5;
        }
        var result = color1.slice();
        for (var i = 0; i < 3; i++) {
            result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));
        }
        return result;
    };

    //retrives a random color for land
    function rndLandColor() {
        return 'rgb(' + colorsLand[Math.floor(Math.random() * 5999) + 1] + ')';
    }
    //retrives a random color for water
    function rndWaterColor() {
        return 'rgb(' + colorsWater[Math.floor(Math.random() * 5999) + 1] + ')';
    }

    function drawPlanet() {
        var RAF;
        var i = 0, j = 0;
        function animate() {
            ctx.beginPath();

            //fill in holes in the land that is bigger then 1
            var score = 0;
            if (tiles[tileNum - (size + 1)] !== undefined && tiles[tileNum + (size + 1)] !== undefined) {
                if (tiles[tileNum].land == false) {
                    score++;
                }
                if (tiles[tileNum - 1].land == true) {
                    score++;
                }
                if (tiles[tileNum + 1].land == true) {
                    score++;
                }
                if (tiles[tileNum + (size + 1)].land == true) {
                    score++;
                }
                if (tiles[tileNum - (size + 1)].land == true) {
                    score++;
                }
            }

            if (score >= 3) {
                ctx.fillStyle = rndLandColor();
            }

            //cover single land tiles with water (if water tile is up,down,left and right of this tile)
            else if (
                tiles[tileNum - (size + 1)] !== undefined &&
                tiles[tileNum + (size + 1)] !== undefined &&
                tiles[tileNum - 1].land == false &&
                tiles[tileNum + 1].land == false &&
                tiles[tileNum - (size + 1)].land == false &&
                tiles[tileNum + (size + 1)].land == false) {
                ctx.fillStyle = rndWaterColor();
            }

            //cover single water tiles with land (if land tile is up,down,left and right of this tile)
            else if (
                tiles[tileNum - (size + 1)] !== undefined &&
                tiles[tileNum + (size + 1)] !== undefined &&
                tiles[tileNum - 1].land == true &&
                tiles[tileNum + 1].land == true &&
                tiles[tileNum - (size + 1)].land == true &&
                tiles[tileNum + (size + 1)].land == true) {
                ctx.fillStyle = rndLandColor();
            }
            //cover tile with land
            else if (tiles[tileNum] !== undefined && tiles[tileNum].land == true) {
                ctx.fillStyle = rndLandColor();
            }

            //cover tile with water
            else if (tiles[tileNum] !== undefined && tiles[tileNum].land == false) {
                ctx.fillStyle = rndWaterColor();
            }
            tileNum++;
            ctx.fill();
            ctx.closePath();
            ctx.fillRect(tileSize * j, tileSize * i, tileSize, tileSize);

            j++;
            if (j >= (size + 1)) {
                i += 1;
                j = 0;
                if (i >= (size + 1)) {
                    cancelAnimationFrame(RAF);
                }
            }
            RAF = requestAnimationFrame(function () {
                animate();
            });
        }
        animate();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
        border: 10px solid #000000;
        border-radius: 50%;
        background-color: aquamarine;
    }

    .container {
        width: 720px;
        height: 720px;
        position: relative;
    }

    .gradient {
        position: absolute;
        height: 730px;
        width: 730px;
        top: 0;
        left: 0;
        border-radius: 50%;
        opacity: 0.8;
    }</code>```

    <canvas id="canvas" width="710" height="710"></canvas>

```

答:
Do not use canvas drawing methods to perform pixel art.

Filling a path is a relatively slow operation, to draw pixels through fillRect(), is almost never the correct way.

Instead one should prefer manipulating an ImageData object directly, and paint it on the canvas only once.

If you need to set up a scale, then use an unscaled ImageBitmap, put it on your context and then upscale it using drawImage.

Here is an updated version of your script, where I did apply some not-so minor improvements like not generating colors for out-of-screen pixels, along with this ImageData manipulation technique.

It now runs fast enough to be launched synchronously. But if you need to improve it even more, note that your getColor seems rather inneficient, but I didn't touch it.

var tileNum = 0;
var tiles;
var colorsLand;
var colorsWater;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var tileSize = 2;
canvas.width = canvas.height = 710;
// 'size' should be your grid size, not the actual pixel size painted on screen
var size = Math.ceil(canvas.width / tileSize);

function generatePlanet() {
  tileNum = 0;
  tiles = [{
    x: 0,
    y: 0,
    land: false
  }];

  //Retrive colors

  colorsLand = interpolateColors(getColor(true), getColor(true), 6000);
  colorsWater = interpolateColors(getColor(false), getColor(false), 6000);

  //Creates a array of my tiles and sets either water or land to them and calculates the % of being water/land
  for (var i = 0; i < (size * size); i++) {
    var currentTile = tiles[tiles.length - 1];
    if (currentTile.x <= (size - 1)) {
      var isLand = false;
      if (currentTile.land == true || tiles.length > size && tiles[tiles.length - size].land == true) {
        isLand = (Math.floor(Math.random() * 100) + 1) > 35;
      } else if (currentTile.land == true || tiles.length > size &&
        (tiles[tiles.length - 1].land == true ||
          tiles[tiles.length - size].land == true)) {
        isLand = (Math.floor(Math.random() * 100) + 1) > size;
      } else {
        isLand = (Math.floor(Math.random() * 100) + 1) > 99;
      }
      tiles.push({
        x: currentTile.x + 1,
        y: currentTile.y,
        land: isLand
      });
    } else {
      tiles.push({
        x: 0,
        y: currentTile.y + 1,
        land: isLand
      });
    }
  }
  drawPlanet()
}

//retrive a random color if it's a land tile i want it dark water i want light
function getColor(land) {
  while (true) {
    var r = Math.floor(Math.random() * 256) + 1
    var g = Math.floor(Math.random() * 256) + 1
    var b = Math.floor(Math.random() * 256) + 1
    var hsp = Math.sqrt(
      0.299 * (r * r) +
      0.587 * (g * g) +
      0.114 * (b * b)
    );
    //light color
    if (hsp > 127.5 && land == false) {
      return [r,g,b];
    }
    //dark color
    else if (hsp < 127.5 && land == true) {
      return [r,g,b];
    }
  }
}

//these 2 functions interpolateColor(s) takes 2 colors and gives me 'steps' colors between
function interpolateColors(color1, color2, steps) {
  var stepFactor = 1 / (steps - 1),
    interpolatedColorArray = [];

  for (var i = 0; i < steps; i++) {
    interpolatedColorArray.push(toUint32AARRGGBB(interpolateColor(color1, color2, stepFactor * i)));
  }
  return interpolatedColorArray;
}
function toUint32AARRGGBB(arr) {
  return Number('0xFF' + arr.map(toHexString2).join(''))
}
function toHexString2(val) {
  return val.toString(16)
    .padStart(2, '0'); // padStart may need a polyfill
}
function interpolateColor(color1, color2, factor) {
  if (arguments.length < 3) {
    factor = 0.5;
  }
  var result = color1.slice();
  for (var i = 0; i < 3; i++) {
    result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));
  }
  return result;
};

//retrives a random color for land
function rndLandColor() {
  return colorsLand[Math.floor(Math.random() * 5999) + 1];
}
//retrives a random color for water
function rndWaterColor() {
  return colorsWater[Math.floor(Math.random() * 5999) + 1];
}

// now drawing synchronously:
function drawPlanet() {

  var gridsize = size;
  var rad = gridsize / 2;

  // generate an ImageData, the size of our pixel grid
  var imgData = new ImageData(gridsize, gridsize);
  // work directly on Uint32 values (0xAARRGGBB on LittleEndian)
  var data = new Uint32Array(imgData.data.buffer);

  var score, y, x;
  for (y = 0; y < gridsize; y++) {
    for (x = 0; x < gridsize; x++) {
      score = 0;

      // if we are outside of the inner area
      if (Math.hypot(rad - x, rad - y) > rad + 2) {
        tileNum++;
        continue;
      }
      //fill in holes in the land that is bigger then 1
     if (tiles[tileNum - (gridsize + 1)] !== undefined && tiles[tileNum + (size + 1)] !== undefined) {
          if (tiles[tileNum].land == false) {
              score++;
          }
          if (tiles[tileNum - 1].land == true) {
              score++;
          }
          if (tiles[tileNum + 1].land == true) {
              score++;
          }
          if (tiles[tileNum + (gridsize + 1)].land == true) {
              score++;
          }
          if (tiles[tileNum - (gridsize + 1)].land == true) {
              score++;
          }
      }

      if (score >= 3) {
          color = rndLandColor();
      }

      //cover single land tiles with water (if water tile is up,down,left and right of this tile)
      else if (
          tiles[tileNum - (gridsize + 1)] !== undefined &&
          tiles[tileNum + (gridsize + 1)] !== undefined &&
          tiles[tileNum - 1].land == false &&
          tiles[tileNum + 1].land == false &&
          tiles[tileNum - (gridsize + 1)].land == false &&
          tiles[tileNum + (gridsize + 1)].land == false) {
          color = rndWaterColor();
      }

      //cover single water tiles with land (if land tile is up,down,left and right of this tile)
      else if (
          tiles[tileNum - (gridsize + 1)] !== undefined &&
          tiles[tileNum + (gridsize + 1)] !== undefined &&
          tiles[tileNum - 1].land == true &&
          tiles[tileNum + 1].land == true &&
          tiles[tileNum - (gridsize + 1)].land == true &&
          tiles[tileNum + (gridsize + 1)].land == true) {
          color = rndLandColor();
      }
      //cover tile with land
      else if (tiles[tileNum] !== undefined && tiles[tileNum].land == true) {
          color = rndLandColor();
      }

      //cover tile with water
      else if (tiles[tileNum] !== undefined && tiles[tileNum].land == false) {
          color = rndWaterColor();
      }
      tileNum++;
      data[(y * gridsize) + x] = color;
    }
  }
  // all done populating the ImageData
  // put it on the context at scale(1,1)
  ctx.putImageData(imgData, 0, 0);
  // remove antialiasing
  ctx.imageSmoothingEnabled = false;
  // up-scale
  ctx.scale(tileSize, tileSize);
  // draw the canvas over itself
  ctx.drawImage(ctx.canvas, 0, 0);
  ctx.setTransform(1, 0, 0, 1, 0, 0);
}

generatePlanet();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  border: 10px solid #000000;
  border-radius: 50%;
  background-color: aquamarine;
}

.container {
  width: 720px;
  height: 720px;
  position: relative;
}

.gradient {
  position: absolute;
  height: 730px;
  width: 730px;
  top: 0;
  left: 0;
  border-radius: 50%;
  opacity: 0.8;
}</code>```

  <canvas id="canvas" width="710" height="710"></canvas>

```
</div>
</div>
</p>

<p>Now, if I were in your position, I think I would even start looking somewhere else completely. For what you want to do, it seems that some noise generator could be more efficient with a more realistic output.<br>
There is one such noise generator available in SVG filters, and hence accessible to Canvas2D API, however I have to admit that controlling it is not that easy.<br>
But if you wish to take a look at it, here is a rough playground:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const controls = new Set();

function randColor() {
  return '#' + (Math.floor((Math.random()*0xFFFFFF)))
    .toString(16)
    .padStart(6, 0);
}
function makeInput(type, options) {
  return Object.assign(document.createElement('input'), {type}, options);
}
class Control {
  constructor() {
    this.color = makeInput('color', {value: randColor()});
    this.freq = makeInput('range', {min: 0.0001, max:1, step: 0.0001, value: Math.random() / 20});
    this.numOctaves = makeInput('range', {min: 1, max:10, step: 1, value: 7});
    this.opacity = makeInput('range', {min:0.01, max:1, step: 0.001, value:1});
    this.seed = Math.random() * 1000;
    const remover = document.createElement('span');
    remover.textContent = 'x';
    remover.classList.add('remover');
    const container = document.createElement('div');
    container.classList.add('control');

    container.append(
      "color: ", this.color,
      "baseFrequency: ", this.freq,
      "numOctaves: ", this.numOctaves,
      "opacity", this.opacity,
      remover
    );

    document.querySelector('.controls').append(container);

    remover.onclick = e => {
      container.remove();
      controls.delete(this);
      draw();
    };
    this.color.oninput = this.freq.oninput =  this.numOctaves.oninput = this.opacity.oninput = draw;
  }
}
for(let i=0; i<3; i++) {
  controls.add(new Control());
}

const main = c.getContext('2d');
const ctx = c.cloneNode().getContext('2d');

main.arc(c.width/2, c.height/2, Math.min(c.width, c.height)/2,0,Math.PI*2);

draw();

add_control.onclick = e => {
  controls.add(new Control());
  draw();
}

function draw() {

  main.globalCompositeOperation = 'source-over';
  main.clearRect(0,0,c.width,c.height);

  controls.forEach(control => {
    ctx.globalCompositeOperation = 'source-over';
    ctx.filter = "none";
    ctx.clearRect(0,0,c.width,c.height);

    // update <filter>
    turb.setAttribute('seed', control.seed);
    turb.setAttribute('baseFrequency', control.freq.value);
    turb.setAttribute('numOctaves', control.numOctaves.value);
    // draw black and transp

    ctx.filter = "url(#myFilter)"
    ctx.fillRect(0,0,c.width, c.width);
    // do the composition with solid color
    ctx.filter = "none"
    ctx.fillStyle = control.color.value;
    ctx.globalCompositeOperation = 'source-in'
    ctx.fillRect(0,0,c.width, c.width);
    main.globalAlpha = control.opacity.value;
    // draw on visible context
    main.drawImage(ctx.canvas, 0,0)
    main.globalAlpha = 1;
  });
  // cut-out as a circle
  main.globalCompositeOperation = 'destination-in';
  main.fill()
}</code>```

.control {
  display: inline-block;
  border: 1px solid;
  padding: 6px;
  position: relative
}
.control input {
  display: block;
}
.control span {
  position: absolute;
  top: 6px;
  right: 6px;
  cursor: pointer;
}

#canvas {
  border: 10px solid #000000;
  border-radius: 50%;
  background-color: aquamarine;
}

.container {
  width: 360px;
  height: 360px;
  position: relative;
}

.gradient {
  position: absolute;
  height: 360px;
  width: 360px;
  top: 0;
  left: 0;
  border-radius: 50%;
  opacity: 0.8;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="controls">
  <button id="add_control">add new layer</button><br>
</div>
<div class="container">
<canvas id="c" width="360" height="360"></canvas>
<svg>
  <filter id="myFilter">
    <feTurbulence type="fractalNoise" baseFrequency="0.045"
        id="turb" result="turb"/>
     <feComponentTransfer in="turb" result="contrast">
       <feFuncR type="linear" slope="1.6" intercept="-0.15"/>
       <feFuncG type="linear" slope="1.6" intercept="-0.15"/>
       <feFuncB type="linear" slope="1.6" intercept="-0.15"/>
     </feComponentTransfer>
    <feColorMatrix in="contrast"
      type="luminanceToAlpha" result="alpha"/>

  </filter>
</svg>
<img class="gradient" src="https://www.mediafire.com/convkey/1f5a/cgu50lw1ehcp4fq6g.jpg" />
</div></code>```

Body:
I am making a script that auto generates planets see codepen for example.
But the problem I have is that i want to make it less pixelated and I am having some problems doing that if i make the tiles 70 * 70 and tile size to 10 * 10 pixels it works fine. But i want to have it set to something like tiles 360 * 360 and size to 1 or 2 pixels. But when I try to do that I get maximum call stack error. So I tried to use the requestAnimationFrame but then it take ages to load is there a way to speed up the process?

var tileNum = 0;
    var tiles;
    var colorsLand;
    var colorsWater;
    var size = 360;
    var tileSize = 2;
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    window.onload = function () {
        generatePlanet();
    }

    function generatePlanet() {
        tileNum = 0;
        tiles = [{ x: 0, y: 0, land: false }];

        //Retrive colors

        colorsLand = interpolateColors("rgb(" + getColor(true) + ")", "rgb(" + getColor(true) + ")", 6000);
        colorsWater = interpolateColors("rgb(" + getColor(false) + ")", "rgb(" + getColor(false) + ")", 6000);

        //Creates a array of my tiles and sets either water or land to them and calculates the % of being water/land
        for (var i = 0; i < (size * size); i++) {
            var currentTile = tiles[tiles.length - 1];
            if (currentTile.x <= (size - 1)) {
                var isLand = false;
                if (currentTile.land == true || tiles.length > size && tiles[tiles.length - size].land == true) {
                    isLand = (Math.floor(Math.random() * 100) + 1) > 35;
                }
                else if (currentTile.land == true || tiles.length > size &&
                    (tiles[tiles.length - 1].land == true ||
                        tiles[tiles.length - size].land == true)) {
                    isLand = (Math.floor(Math.random() * 100) + 1) > size;
                }
                else {
                    isLand = (Math.floor(Math.random() * 100) + 1) > 99;
                }
                tiles.push({ x: currentTile.x + 1, y: currentTile.y, land: isLand });
            }
            else {
                tiles.push({ x: 0, y: currentTile.y + 1, land: isLand });
            }
        }
        drawPlanet()
    }

    //retrive a random color if it's a land tile i want it dark water i want light
    function getColor(land) {
        while (true) {
            var r = Math.floor(Math.random() * 256) + 1
            var g = Math.floor(Math.random() * 256) + 1
            var b = Math.floor(Math.random() * 256) + 1
            var hsp = Math.sqrt(
                0.299 * (r * r) +
                0.587 * (g * g) +
                0.114 * (b * b)
            );
            //light color
            if (hsp > 127.5 && land == false) {
                return r + "," + g + "," + b;
            }
            //dark color
            else if (hsp < 127.5 && land == true) {
                return r + "," + g + "," + b;
            }
        }
    }

    //these 2 functions interpolateColor(s) takes 2 colors and gives me 'steps' colors between
    function interpolateColors(color1, color2, steps) {
        var stepFactor = 1 / (steps - 1),
            interpolatedColorArray = [];
        color1 = color1.match(/\d+/g).map(Number);
        color2 = color2.match(/\d+/g).map(Number);

        for (var i = 0; i < steps; i++) {
            interpolatedColorArray.push(interpolateColor(color1, color2, stepFactor * i));
        }
        return interpolatedColorArray;
    }

    function interpolateColor(color1, color2, factor) {
        if (arguments.length < 3) {
            factor = 0.5;
        }
        var result = color1.slice();
        for (var i = 0; i < 3; i++) {
            result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));
        }
        return result;
    };

    //retrives a random color for land
    function rndLandColor() {
        return 'rgb(' + colorsLand[Math.floor(Math.random() * 5999) + 1] + ')';
    }
    //retrives a random color for water
    function rndWaterColor() {
        return 'rgb(' + colorsWater[Math.floor(Math.random() * 5999) + 1] + ')';
    }

    function drawPlanet() {
        var RAF;
        var i = 0, j = 0;
        function animate() {
            ctx.beginPath();

            //fill in holes in the land that is bigger then 1
            var score = 0;
            if (tiles[tileNum - (size + 1)] !== undefined && tiles[tileNum + (size + 1)] !== undefined) {
                if (tiles[tileNum].land == false) {
                    score++;
                }
                if (tiles[tileNum - 1].land == true) {
                    score++;
                }
                if (tiles[tileNum + 1].land == true) {
                    score++;
                }
                if (tiles[tileNum + (size + 1)].land == true) {
                    score++;
                }
                if (tiles[tileNum - (size + 1)].land == true) {
                    score++;
                }
            }

            if (score >= 3) {
                ctx.fillStyle = rndLandColor();
            }

            //cover single land tiles with water (if water tile is up,down,left and right of this tile)
            else if (
                tiles[tileNum - (size + 1)] !== undefined &&
                tiles[tileNum + (size + 1)] !== undefined &&
                tiles[tileNum - 1].land == false &&
                tiles[tileNum + 1].land == false &&
                tiles[tileNum - (size + 1)].land == false &&
                tiles[tileNum + (size + 1)].land == false) {
                ctx.fillStyle = rndWaterColor();
            }

            //cover single water tiles with land (if land tile is up,down,left and right of this tile)
            else if (
                tiles[tileNum - (size + 1)] !== undefined &&
                tiles[tileNum + (size + 1)] !== undefined &&
                tiles[tileNum - 1].land == true &&
                tiles[tileNum + 1].land == true &&
                tiles[tileNum - (size + 1)].land == true &&
                tiles[tileNum + (size + 1)].land == true) {
                ctx.fillStyle = rndLandColor();
            }
            //cover tile with land
            else if (tiles[tileNum] !== undefined && tiles[tileNum].land == true) {
                ctx.fillStyle = rndLandColor();
            }

            //cover tile with water
            else if (tiles[tileNum] !== undefined && tiles[tileNum].land == false) {
                ctx.fillStyle = rndWaterColor();
            }
            tileNum++;
            ctx.fill();
            ctx.closePath();
            ctx.fillRect(tileSize * j, tileSize * i, tileSize, tileSize);

            j++;
            if (j >= (size + 1)) {
                i += 1;
                j = 0;
                if (i >= (size + 1)) {
                    cancelAnimationFrame(RAF);
                }
            }
            RAF = requestAnimationFrame(function () {
                animate();
            });
        }
        animate();
}

#canvas {
        border: 10px solid #000000;
        border-radius: 50%;
        background-color: aquamarine;
    }

    .container {
        width: 720px;
        height: 720px;
        position: relative;
    }

    .gradient {
        position: absolute;
        height: 730px;
        width: 730px;
        top: 0;
        left: 0;
        border-radius: 50%;
        opacity: 0.8;
    }

    <canvas id="canvas" width="710" height="710"></canvas>

Body:
Do not use canvas drawing methods to perform pixel art.

Filling a path is a relatively slow operation, to draw pixels through fillRect(), is almost never the correct way.

Instead one should prefer manipulating an ImageData object directly, and paint it on the canvas only once.

If you need to set up a scale, then use an unscaled ImageBitmap, put it on your context and then upscale it using drawImage.

Here is an updated version of your script, where I did apply some not-so minor improvements like not generating colors for out-of-screen pixels, along with this ImageData manipulation technique.

It now runs fast enough to be launched synchronously. But if you need to improve it even more, note that your getColor seems rather inneficient, but I didn't touch it.

var tileNum = 0;
var tiles;
var colorsLand;
var colorsWater;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var tileSize = 2;
canvas.width = canvas.height = 710;
// 'size' should be your grid size, not the actual pixel size painted on screen
var size = Math.ceil(canvas.width / tileSize);

function generatePlanet() {
  tileNum = 0;
  tiles = [{
    x: 0,
    y: 0,
    land: false
  }];

  //Retrive colors

  colorsLand = interpolateColors(getColor(true), getColor(true), 6000);
  colorsWater = interpolateColors(getColor(false), getColor(false), 6000);

  //Creates a array of my tiles and sets either water or land to them and calculates the % of being water/land
  for (var i = 0; i < (size * size); i++) {
    var currentTile = tiles[tiles.length - 1];
    if (currentTile.x <= (size - 1)) {
      var isLand = false;
      if (currentTile.land == true || tiles.length > size && tiles[tiles.length - size].land == true) {
        isLand = (Math.floor(Math.random() * 100) + 1) > 35;
      } else if (currentTile.land == true || tiles.length > size &&
        (tiles[tiles.length - 1].land == true ||
          tiles[tiles.length - size].land == true)) {
        isLand = (Math.floor(Math.random() * 100) + 1) > size;
      } else {
        isLand = (Math.floor(Math.random() * 100) + 1) > 99;
      }
      tiles.push({
        x: currentTile.x + 1,
        y: currentTile.y,
        land: isLand
      });
    } else {
      tiles.push({
        x: 0,
        y: currentTile.y + 1,
        land: isLand
      });
    }
  }
  drawPlanet()
}

//retrive a random color if it's a land tile i want it dark water i want light
function getColor(land) {
  while (true) {
    var r = Math.floor(Math.random() * 256) + 1
    var g = Math.floor(Math.random() * 256) + 1
    var b = Math.floor(Math.random() * 256) + 1
    var hsp = Math.sqrt(
      0.299 * (r * r) +
      0.587 * (g * g) +
      0.114 * (b * b)
    );
    //light color
    if (hsp > 127.5 && land == false) {
      return [r,g,b];
    }
    //dark color
    else if (hsp < 127.5 && land == true) {
      return [r,g,b];
    }
  }
}

//these 2 functions interpolateColor(s) takes 2 colors and gives me 'steps' colors between
function interpolateColors(color1, color2, steps) {
  var stepFactor = 1 / (steps - 1),
    interpolatedColorArray = [];

  for (var i = 0; i < steps; i++) {
    interpolatedColorArray.push(toUint32AARRGGBB(interpolateColor(color1, color2, stepFactor * i)));
  }
  return interpolatedColorArray;
}
function toUint32AARRGGBB(arr) {
  return Number('0xFF' + arr.map(toHexString2).join(''))
}
function toHexString2(val) {
  return val.toString(16)
    .padStart(2, '0'); // padStart may need a polyfill
}
function interpolateColor(color1, color2, factor) {
  if (arguments.length < 3) {
    factor = 0.5;
  }
  var result = color1.slice();
  for (var i = 0; i < 3; i++) {
    result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));
  }
  return result;
};

//retrives a random color for land
function rndLandColor() {
  return colorsLand[Math.floor(Math.random() * 5999) + 1];
}
//retrives a random color for water
function rndWaterColor() {
  return colorsWater[Math.floor(Math.random() * 5999) + 1];
}

// now drawing synchronously:
function drawPlanet() {

  var gridsize = size;
  var rad = gridsize / 2;

  // generate an ImageData, the size of our pixel grid
  var imgData = new ImageData(gridsize, gridsize);
  // work directly on Uint32 values (0xAARRGGBB on LittleEndian)
  var data = new Uint32Array(imgData.data.buffer);

  var score, y, x;
  for (y = 0; y < gridsize; y++) {
    for (x = 0; x < gridsize; x++) {
      score = 0;

      // if we are outside of the inner area
      if (Math.hypot(rad - x, rad - y) > rad + 2) {
        tileNum++;
        continue;
      }
      //fill in holes in the land that is bigger then 1
     if (tiles[tileNum - (gridsize + 1)] !== undefined && tiles[tileNum + (size + 1)] !== undefined) {
          if (tiles[tileNum].land == false) {
              score++;
          }
          if (tiles[tileNum - 1].land == true) {
              score++;
          }
          if (tiles[tileNum + 1].land == true) {
              score++;
          }
          if (tiles[tileNum + (gridsize + 1)].land == true) {
              score++;
          }
          if (tiles[tileNum - (gridsize + 1)].land == true) {
              score++;
          }
      }

      if (score >= 3) {
          color = rndLandColor();
      }

      //cover single land tiles with water (if water tile is up,down,left and right of this tile)
      else if (
          tiles[tileNum - (gridsize + 1)] !== undefined &&
          tiles[tileNum + (gridsize + 1)] !== undefined &&
          tiles[tileNum - 1].land == false &&
          tiles[tileNum + 1].land == false &&
          tiles[tileNum - (gridsize + 1)].land == false &&
          tiles[tileNum + (gridsize + 1)].land == false) {
          color = rndWaterColor();
      }

      //cover single water tiles with land (if land tile is up,down,left and right of this tile)
      else if (
          tiles[tileNum - (gridsize + 1)] !== undefined &&
          tiles[tileNum + (gridsize + 1)] !== undefined &&
          tiles[tileNum - 1].land == true &&
          tiles[tileNum + 1].land == true &&
          tiles[tileNum - (gridsize + 1)].land == true &&
          tiles[tileNum + (gridsize + 1)].land == true) {
          color = rndLandColor();
      }
      //cover tile with land
      else if (tiles[tileNum] !== undefined && tiles[tileNum].land == true) {
          color = rndLandColor();
      }

      //cover tile with water
      else if (tiles[tileNum] !== undefined && tiles[tileNum].land == false) {
          color = rndWaterColor();
      }
      tileNum++;
      data[(y * gridsize) + x] = color;
    }
  }
  // all done populating the ImageData
  // put it on the context at scale(1,1)
  ctx.putImageData(imgData, 0, 0);
  // remove antialiasing
  ctx.imageSmoothingEnabled = false;
  // up-scale
  ctx.scale(tileSize, tileSize);
  // draw the canvas over itself
  ctx.drawImage(ctx.canvas, 0, 0);
  ctx.setTransform(1, 0, 0, 1, 0, 0);
}

generatePlanet();

#canvas {
  border: 10px solid #000000;
  border-radius: 50%;
  background-color: aquamarine;
}

.container {
  width: 720px;
  height: 720px;
  position: relative;
}

.gradient {
  position: absolute;
  height: 730px;
  width: 730px;
  top: 0;
  left: 0;
  border-radius: 50%;
  opacity: 0.8;
}

<div class="container">
  <img class="gradient" src="https://www.mediafire.com/convkey/1f5a/cgu50lw1ehcp4fq6g.jpg" />
  <canvas id="canvas" width="710" height="710"></canvas>
</div>

Now, if I were in your position, I think I would even start looking somewhere else completely. For what you want to do, it seems that some noise generator could be more efficient with a more realistic output.

There is one such noise generator available in SVG filters, and hence accessible to Canvas2D API, however I have to admit that controlling it is not that easy.

But if you wish to take a look at it, here is a rough playground:

const controls = new Set();

function randColor() {
  return '#' + (Math.floor((Math.random()*0xFFFFFF)))
    .toString(16)
    .padStart(6, 0);
}
function makeInput(type, options) {
  return Object.assign(document.createElement('input'), {type}, options);
}
class Control {
  constructor() {
    this.color = makeInput('color', {value: randColor()});
    this.freq = makeInput('range', {min: 0.0001, max:1, step: 0.0001, value: Math.random() / 20});
    this.numOctaves = makeInput('range', {min: 1, max:10, step: 1, value: 7});
    this.opacity = makeInput('range', {min:0.01, max:1, step: 0.001, value:1});
    this.seed = Math.random() * 1000;
    const remover = document.createElement('span');
    remover.textContent = 'x';
    remover.classList.add('remover');
    const container = document.createElement('div');
    container.classList.add('control');

    container.append(
      "color: ", this.color,
      "baseFrequency: ", this.freq,
      "numOctaves: ", this.numOctaves,
      "opacity", this.opacity,
      remover
    );

    document.querySelector('.controls').append(container);

    remover.onclick = e => {
      container.remove();
      controls.delete(this);
      draw();
    };
    this.color.oninput = this.freq.oninput =  this.numOctaves.oninput = this.opacity.oninput = draw;
  }
}
for(let i=0; i<3; i++) {
  controls.add(new Control());
}

const main = c.getContext('2d');
const ctx = c.cloneNode().getContext('2d');

main.arc(c.width/2, c.height/2, Math.min(c.width, c.height)/2,0,Math.PI*2);

draw();

add_control.onclick = e => {
  controls.add(new Control());
  draw();
}

function draw() {

  main.globalCompositeOperation = 'source-over';
  main.clearRect(0,0,c.width,c.height);

  controls.forEach(control => {
    ctx.globalCompositeOperation = 'source-over';
    ctx.filter = "none";
    ctx.clearRect(0,0,c.width,c.height);

    // update <filter>
    turb.setAttribute('seed', control.seed);
    turb.setAttribute('baseFrequency', control.freq.value);
    turb.setAttribute('numOctaves', control.numOctaves.value);
    // draw black and transp

    ctx.filter = "url(#myFilter)"
    ctx.fillRect(0,0,c.width, c.width);
    // do the composition with solid color
    ctx.filter = "none"
    ctx.fillStyle = control.color.value;
    ctx.globalCompositeOperation = 'source-in'
    ctx.fillRect(0,0,c.width, c.width);
    main.globalAlpha = control.opacity.value;
    // draw on visible context
    main.drawImage(ctx.canvas, 0,0)
    main.globalAlpha = 1;
  });
  // cut-out as a circle
  main.globalCompositeOperation = 'destination-in';
  main.fill()
}

.control {
  display: inline-block;
  border: 1px solid;
  padding: 6px;
  position: relative
}
.control input {
  display: block;
}
.control span {
  position: absolute;
  top: 6px;
  right: 6px;
  cursor: pointer;
}

#canvas {
  border: 10px solid #000000;
  border-radius: 50%;
  background-color: aquamarine;
}

.container {
  width: 360px;
  height: 360px;
  position: relative;
}

.gradient {
  position: absolute;
  height: 360px;
  width: 360px;
  top: 0;
  left: 0;
  border-radius: 50%;
  opacity: 0.8;
}

<div class="controls">
  <button id="add_control">add new layer</button><br>
</div>
<div class="container">
<canvas id="c" width="360" height="360"></canvas>
<svg>
  <filter id="myFilter">
    <feTurbulence type="fractalNoise" baseFrequency="0.045"
        id="turb" result="turb"/>
     <feComponentTransfer in="turb" result="contrast">
       <feFuncR type="linear" slope="1.6" intercept="-0.15"/>
       <feFuncG type="linear" slope="1.6" intercept="-0.15"/>
       <feFuncB type="linear" slope="1.6" intercept="-0.15"/>
     </feComponentTransfer>
    <feColorMatrix in="contrast"
      type="luminanceToAlpha" result="alpha"/>

  </filter>
</svg>
<img class="gradient" src="https://www.mediafire.com/convkey/1f5a/cgu50lw1ehcp4fq6g.jpg" />
</div>


来源: stackexchange

问:
How to get a reference to current DropTarget, upon drop failure with YUI 2.8.1 DragDrop?
I'm using the DragDrop component - its basically the 'grouped drop objects' example - but I cannot for the life of me obtain a reference to the DropTarget object at the time I dropped my drag object... when the DropTarget is "incorrect".

I tried intercepting onInvalidDrop, can't seem to catch references to a DropTarget there, 'this' default scopes to the Dragged object.

I tried putting a conditional within onDragDrop for whether a drop result was a legal target, hoping to see some result... nothing.

I then tried to do the same with onDragEnd as with onDragDrop, no cigar.

I simply want to deactivate the DropTarget the user failed on. I have the styles ready, I have isTarget ready to be applied... but nothing to apply it to?

URL: http://codefinger.co.nz/_testing/yui_dragdrop/dragdrop_test.html

答:
Beware! Dav Glass of the YUI team advised that the reference I'm after is not available in Y2.8.1 DragDrop - though it is in YUI3.

Though its not feasible in my case to switch to YUI3, a suitable (if hacky) solution was to add all droppables to a single group (instead of many groups) so that they all trigger onDragDrop. From there, its possible to qualify in/valid drop targets based on things like the drop targets' id, classNames, or in my case some custom object props.

Problem... solved.

ContentLicense: CC BY-SA 3.0


问:
Can't load context for Test
For some tests, I need to use prod-context and test-context. But Spring can't find my context.

I've tried to put context in a different location, also tried to upload context with various loader.

I have my context in the resources classpath.

```<code>Entities-src-test-java-Dao-test1
                -resources-META-INF-spring
</code>```

My full path is
C:\Git\Application\Entities\src\test\resources\META-INF\spring

When I try, for example

```<code>public class test1{
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("test-beans.xml");
...
</code>```

or

```<code>@ContextConfiguration("file:/C://Git/Application/Entities/src/test/resources/META-INF/spring/test-beans.xml")
public class test1{
...
</code>```

Or other various... I got error

```<code>org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [test-beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [test-beans.xml] cannot be opened because it does not exist
</code>```

If I start that class in debugger and check
System.getProperty("user.dir") I will see C:\Git\Application or new File(".").getAbsolutePath(); shows me C:\Git\Application\.

How to solve that?

答:
Well ,it is not so good to make the location of the configuration file to depend on the file path. Are you sure other teammate will also put the project source codes in the folder C:\Git\Application\Entities? If not , your teammate most probably cannot run your test case out of the box , not to mention the build server.

Instead , you can try to refer the configuration file using classpath to prevent such file issues :

```<code>@ContextConfiguration("classpath:spring/test-beans.xml")
public class Test{

}
</code>```

And put the test-beans.xml inside the folder C:\Git\Application\Entities\src\test\resources\spring

ContentLicense: CC BY-SA 4.0

Title: Can't load context for Test

Body:
For some tests, I need to use prod-context and test-context. But Spring can't find my context.

I've tried to put context in a different location, also tried to upload context with various loader.

I have my context in the resources classpath.

Entities-src-test-java-Dao-test1
                -resources-META-INF-spring

My full path is
C:\Git\Application\Entities\src\test\resources\META-INF\spring

When I try, for example

public class test1{
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("test-beans.xml");
...

or

@ContextConfiguration("file:/C://Git/Application/Entities/src/test/resources/META-INF/spring/test-beans.xml")
public class test1{
...

Or other various... I got error

org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [test-beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [test-beans.xml] cannot be opened because it does not exist

If I start that class in debugger and check
System.getProperty("user.dir") I will see C:\Git\Application or new File(".").getAbsolutePath(); shows me C:\Git\Application\.

How to solve that?

Body:
Well ,it is not so good to make the location of the configuration file to depend on the file path. Are you sure other teammate will also put the project source codes in the folder C:\Git\Application\Entities? If not , your teammate most probably cannot run your test case out of the box , not to mention the build server.

Instead , you can try to refer the configuration file using classpath to prevent such file issues :

@ContextConfiguration("classpath:spring/test-beans.xml")
public class Test{

}

And put the test-beans.xml inside the folder C:\Git\Application\Entities\src\test\resources\spring


问:
Spring conditional yaml property value
That's how one line of my .yaml properties file looks like:

```<code>profiles.active: rabbit-${CLUSTER_ENV}, mongo-${CLUSTER_ENV} ...
</code>```

I want to put the below logic only for rabbit- property:

```<code>if(CLUSTER_ENV == "local") {
   return "dev";
} else {
   return CLUSTER_ENV;
}
</code>```

Other properties should be filled with local but only in this place the property value should be conditionally filled. Can I somehow add this logic in Spring yaml properties?

答:
It does not look pretty, but you can use something like:

```<code> #this can be added on startup
mykey: key1

#a map with your condition
mymap:
  key1: val1
  key2: val2

#your value based on the condition
conditional: con-${mymap.${mykey}}
</code>```

regards,
WiPU

UPDATE based on comment:

```<code> #this can be added on startup as variable
mykey: local

#a map with your condition
mymap:
  local: dev
  xyz: test

# your value based on the condition or the key as fallback if the key is not
# present in mymap.
conditional: con-${mymap.${mykey}:${mykey}}
</code>```

Title: Spring conditional yaml property value

Body:
That's how one line of my .yaml properties file looks like:

profiles.active: rabbit-${CLUSTER_ENV}, mongo-${CLUSTER_ENV} ...

I want to put the below logic only for rabbit- property:

if(CLUSTER_ENV == "local") {
   return "dev";
} else {
   return CLUSTER_ENV;
}

Other properties should be filled with local but only in this place the property value should be conditionally filled. Can I somehow add this logic in Spring yaml properties?

Body:
It does not look pretty, but you can use something like:

 #this can be added on startup
mykey: key1

#a map with your condition
mymap:
  key1: val1
  key2: val2

#your value based on the condition
conditional: con-${mymap.${mykey}}

regards,
WiPU

UPDATE based on comment:

 #this can be added on startup as variable
mykey: local

#a map with your condition
mymap:
  local: dev
  xyz: test

# your value based on the condition or the key as fallback if the key is not
# present in mymap.
conditional: con-${mymap.${mykey}:${mykey}}


问:
Rewrite Mathematica output in Python
I want to convert the piecewise-function output of a calculation in Mathematica into Python. Taking inspiration from this page for the Mathematica->Python conversion and this page for writing piecewise functions, I have

```<code>from numpy import linspace, vectorize, array
from numpy import arctan, log
import matplotlib.pyplot as plt
from sympy.parsing.mathematica import parse

def fun(x,a,b,c):
    # string inside parse('') is my mathematica output
    if a == 0:
        out = parse('a (-I b + x) ArcTan[(b - a)/c]')
    else:
        out = parse('4 c a^2 Log[c^2 + (x - a)^2]')
    return out

a = 0.17
b = 0.44
c = 0.29
x = linspace(0,50,int(1e3))

vfun = vectorize(fun)
y = vfun(x,a,b,c)
yp = 4*c*a**2*log(c**2 + (x - a)**2)

plt.figure()
plt.plot(x,y,'.-')
plt.title('mathematica -> python conversion')

plt.figure()
plt.plot(x,yp,'.-')
plt.title('expected')

plt.show()
</code>```

The plot looks like:

whereas it should be:

Have I done something wrong when converting Mathematica to Python? Or is there a problem when assigning numerical values to a, b, and c? (Note that this is a MWE, and the Mathematica code that I want to convert is much longer and complicated than what is shown above.)

答:
This is a dirty solution:

import numpy as np
import matplotlib.pyplot as plt
from sympy.parsing.mathematica import mathematica
from sympy import symbols

def fun(x, a, b, c):
    # string inside parse('') is my mathematica output
    if a == 0:
        out = mathematica('a (-I b + x) ArcTan[(b - a)/c]')
    else:
        out = mathematica('4 c a^2 Log[c^2 + (x - a)^2]')
    return out

aa = 0.17
bb = 0.44
cc = 0.29
II = 1
xx = np.linspace(0, 50, int(1e3))

x, a, b, c, I = symbols('x, a, b, c, I')

fun1 = fun(x, a, b, c)
fun2 = fun1.subs({a: aa, c: cc})
print(fun2.evalf())

y_list = []

for item in xx:
    y_list.append(fun2.subs({x:item}).evalf())

print(y_list[:10])

plt.figure()
plt.plot(xx, y_list,'.-')
plt.title('mathematica -> python conversion')
plt.show()

```

<p>I will explain it later how all of this works.</p>

<h3>Update</h3>

<p>As you may see, when <code>a == 0</code>, the function is <code>0</code>, you need to check that.</p>

<p>When you use <code>mathematica</code>, the type of <code>fun1</code> is a <code>sympy</code> function (<code>sympy.core.mul.Mul</code>), that's why you have to use <code>symbols</code> and <code>fun1.subs()</code> and <code>fun2.evalf()</code>, in other words, you need to know who to use the basic functions of <code>sympy</code>.</p>

<p>The way you evaluate a function in order to plot it, well, you use a list:</p>

<pre class="lang-py prettyprint-override"><code>y_list = []

for item in xx:
    y_list.append(fun2.subs({x:item}).evalf())
</code>```

By the way, I am using sympy version 1.4.

Title: Rewrite Mathematica output in Python

Body:
I want to convert the piecewise-function output of a calculation in Mathematica into Python. Taking inspiration from this page for the Mathematica->Python conversion and this page for writing piecewise functions, I have

from numpy import linspace, vectorize, array
from numpy import arctan, log
import matplotlib.pyplot as plt
from sympy.parsing.mathematica import parse

def fun(x,a,b,c):
    # string inside parse('') is my mathematica output
    if a == 0:
        out = parse('a (-I b + x) ArcTan[(b - a)/c]')
    else:
        out = parse('4 c a^2 Log[c^2 + (x - a)^2]')
    return out

a = 0.17
b = 0.44
c = 0.29
x = linspace(0,50,int(1e3))

vfun = vectorize(fun)
y = vfun(x,a,b,c)
yp = 4*c*a**2*log(c**2 + (x - a)**2)

plt.figure()
plt.plot(x,y,'.-')
plt.title('mathematica -> python conversion')

plt.figure()
plt.plot(x,yp,'.-')
plt.title('expected')

plt.show()

The plot looks like:

whereas it should be:

Have I done something wrong when converting Mathematica to Python? Or is there a problem when assigning numerical values to a, b, and c? (Note that this is a MWE, and the Mathematica code that I want to convert is much longer and complicated than what is shown above.)

Body:
This is a dirty solution:

import numpy as np
import matplotlib.pyplot as plt
from sympy.parsing.mathematica import mathematica
from sympy import symbols

def fun(x, a, b, c):
    # string inside parse('') is my mathematica output
    if a == 0:
        out = mathematica('a (-I b + x) ArcTan[(b - a)/c]')
    else:
        out = mathematica('4 c a^2 Log[c^2 + (x - a)^2]')
    return out

aa = 0.17
bb = 0.44
cc = 0.29
II = 1
xx = np.linspace(0, 50, int(1e3))

x, a, b, c, I = symbols('x, a, b, c, I')

fun1 = fun(x, a, b, c)
fun2 = fun1.subs({a: aa, c: cc})
print(fun2.evalf())

y_list = []

for item in xx:
    y_list.append(fun2.subs({x:item}).evalf())

print(y_list[:10])

plt.figure()
plt.plot(xx, y_list,'.-')
plt.title('mathematica -> python conversion')
plt.show()

I will explain it later how all of this works.

Update

As you may see, when a == 0, the function is 0, you need to check that.

When you use mathematica, the type of fun1 is a sympy function (sympy.core.mul.Mul), that's why you have to use symbols and fun1.subs() and fun2.evalf(), in other words, you need to know who to use the basic functions of sympy.

The way you evaluate a function in order to plot it, well, you use a list:

y_list = []

for item in xx:
    y_list.append(fun2.subs({x:item}).evalf())

By the way, I am using sympy version 1.4.


问:
Oracle SQL query Optimization with multiple filters and create table
My select query is running for 15 hours and still running so I cancelled it. How can I optimize my query?

```<code>CREATE TABLE W_PURCH_RCPT_FS_tmp
AS

    SELECT RCV.TRANSACTION_ID,
           PO.RELEASE_DATE,
           NVL (ASL.PROCESSING_LEAD_TIME, MTL.FULL_LEAD_TIME)
               AS PROCESSING_LEAD_TIME
      FROM obia_ui.PO_ASL_ATTRIBUTES@betsy.world@dsn_310      ASL,
           obia_ui.MTL_SYSTEM_ITEMS_B@betsy.world@dsn_310      MTL,
           obia_ui.RCV_TRANSACTIONS@betsy.world@dsn_310       RCV,
           obia_ui.PO_RELEASES_ALL@betsy.world@dsn_310         PO,
           obia_ui.PO_LINES_ALL@betsy.world@dsn_310           LINES,
           obia_ui.PO_LINE_LOCATIONS_ALL@betsy.world@dsn_310   LOC,
           obia_ui.PO_HEADERS_ALL@betsy.world@dsn_310          HEAD
     WHERE  RCV.CREATION_DATE > '30-JUN-2016'
            AND MTL.INVENTORY_ITEM_ID = LINES.ITEM_ID
           AND MTL.ORGANIZATION_ID = LOC.SHIP_TO_ORGANIZATION_ID
           AND LINES.PO_LINE_ID = LOC.PO_LINE_ID
           AND ASL.USING_ORGANIZATION_ID = LOC.SHIP_TO_ORGANIZATION_ID
           AND ASL.ITEM_ID = LINES.ITEM_ID
           AND ASL.VENDOR_ID = HEAD.VENDOR_ID
           AND ASL.VENDOR_SITE_ID = HEAD.VENDOR_SITE_ID
           AND RCV.TRANSACTION_ID = PO.PO_RELEASE_ID
           ;
</code>```

I expect that query to finish shorter.

答: First of all you have to master explain plan concept to optimize a query in Oracle. After understanding explain plans I would suggest to go for table by table. Starting from the first table check how it performs on an explain plan. By this way you can figure out the indexes that need to be created. Sometimes there's no way to create a useful index. In that case splitting the data into smaller chunks (tables) may help. Also Oracle has a parallel query running capabilities. You can take advantage of this feature too. </p>

Body:
My select query is running for 15 hours and still running so I cancelled it. How can I optimize my query?

CREATE TABLE W_PURCH_RCPT_FS_tmp
AS

    SELECT RCV.TRANSACTION_ID,
           PO.RELEASE_DATE,
           NVL (ASL.PROCESSING_LEAD_TIME, MTL.FULL_LEAD_TIME)
               AS PROCESSING_LEAD_TIME
      FROM obia_ui.PO_ASL_ATTRIBUTES@betsy.world@dsn_310      ASL,
           obia_ui.MTL_SYSTEM_ITEMS_B@betsy.world@dsn_310      MTL,
           obia_ui.RCV_TRANSACTIONS@betsy.world@dsn_310       RCV,
           obia_ui.PO_RELEASES_ALL@betsy.world@dsn_310         PO,
           obia_ui.PO_LINES_ALL@betsy.world@dsn_310           LINES,
           obia_ui.PO_LINE_LOCATIONS_ALL@betsy.world@dsn_310   LOC,
           obia_ui.PO_HEADERS_ALL@betsy.world@dsn_310          HEAD
     WHERE  RCV.CREATION_DATE > '30-JUN-2016'
            AND MTL.INVENTORY_ITEM_ID = LINES.ITEM_ID
           AND MTL.ORGANIZATION_ID = LOC.SHIP_TO_ORGANIZATION_ID
           AND LINES.PO_LINE_ID = LOC.PO_LINE_ID
           AND ASL.USING_ORGANIZATION_ID = LOC.SHIP_TO_ORGANIZATION_ID
           AND ASL.ITEM_ID = LINES.ITEM_ID
           AND ASL.VENDOR_ID = HEAD.VENDOR_ID
           AND ASL.VENDOR_SITE_ID = HEAD.VENDOR_SITE_ID
           AND RCV.TRANSACTION_ID = PO.PO_RELEASE_ID
           ;

I expect that query to finish shorter.


问:
Use Python command line argument as function names and function values
Related to this question Command line arguments in python.

With the SYS module, how can I use a command line argument as a function name and function value, within my code - without importing some other module?

I'd like a solution that uses sys only. Also, please no variable-length params answers. Those are confusing. Assume that just the function name and one function variable are specified at the command line.

```<code>import sys

def reversal(aaa): return aaa[::-1]

a = sys.argv[1]
b = sys.argv[2]

print a(b)
</code>```

At the command line

```<code>cpu_location$ python blah.py reversal 'abcdefg'

Traceback (most recent call last):
File "blah.py", line 8, in <module>
print a(b)
TypeError: 'str' object is not callable
</code>```

I want to know how to make sys.argv[1] be considered a function name, thereby calling the function I have defined.

The other posts I see on this are a mash up of:
- dealing with C/C++ and adding some other module
- not using sys at all
- using the argv items as values for functions, and names of other files, instead of names of functions

答:
use google module: fire

```<code>pip install fire
</code>```

Here's a simple example:

```<code>import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':
  fire.Fire(Calculator)
</code>```

Then, from the command line, you can run:

```<code>python calculator.py double 10  # 20
python calculator.py double --number=15  # 30
</code>```

Body:
Related to this question Command line arguments in python.

With the SYS module, how can I use a command line argument as a function name and function value, within my code - without importing some other module?

I'd like a solution that uses sys only. Also, please no variable-length params answers. Those are confusing. Assume that just the function name and one function variable are specified at the command line.

import sys

def reversal(aaa): return aaa[::-1]

a = sys.argv[1]
b = sys.argv[2]

print a(b)

At the command line

cpu_location$ python blah.py reversal 'abcdefg'

Traceback (most recent call last):
File "blah.py", line 8, in <module>
print a(b)
TypeError: 'str' object is not callable

I want to know how to make sys.argv[1] be considered a function name, thereby calling the function I have defined.

The other posts I see on this are a mash up of:
- dealing with C/C++ and adding some other module
- not using sys at all
- using the argv items as values for functions, and names of other files, instead of names of functions

Body:
use google module: fire

pip install fire

Here's a simple example:

import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':
  fire.Fire(Calculator)

Then, from the command line, you can run:

python calculator.py double 10  # 20
python calculator.py double --number=15  # 30


问:
Heroku is giving me 404 error, only renders "Unkown path"?
I'm trying to deploy my application to heroku, however when I try to open the link to it, the only thing being rendered is "unkown path", erros being "Failed to load resource: the server responded with a status of 404 (Not Found)".

I kept checking the routes files as much as I could and I can't see what doesn't work here. This is how the index.js file looks like

```<code>import route from './router.js';

import Login from '../ui/pages/user/Login';
import Home from '../ui/Home';
import Register from '../ui/pages/user/Register';
import PostCreate from '../ui/pages/post/PostCreate';
import PostList from '../ui/pages/post/PostList';
import PostEdit from '../ui/pages/post/PostEdit';

route('/', Home, {}, {
    name: 'home'
  });
  route('/login', Login, {}, {
    name: 'login'
  });
  route('/register', Register, {}, {
    name: 'register'
  });
  route('/post/create', PostCreate, {}, {
    name: 'post.create'
  });
  route('/post/list', PostList, {}, {
    name: 'post.list'
  });
  route('/post/edit/:_id', PostEdit, {}, {
    name:'post.edit'
  });
</code>```

And this is the router.js file

```<code>import { createRouter } from 'meteor/cultofcoders:meteor-react-routing';
import App from '/imports/ui/App.jsx';

export default createRouter(App);
</code>```

Could it just be an issue regarding the routing package I'm using?

答:
I feel you are using the "wrong" router. cultofcoders:meteor-react-routing seems to not have been maintained in the past 2 years which is huge in terms of react routing. Would you be interested to try "react-router": "^5.0.0" with "react-router-dom": "^5.0.0" then you have something like:

```<code>import React from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import Component1 from '.....'
import Component2 from '.....'

const Main = location => {
  return (
      <Switch location={location.location}>
        <Route exact path='/' component={Component1} />
        <Route exact path='/something' component={Component2} />
        <Route exact path='/something/:id' component={Component2} /> // route with param
        <Route path='*' component={NotFoundPage} />
        ...........
      </Switch>)
}

</code>```

Body:
I'm trying to deploy my application to heroku, however when I try to open the link to it, the only thing being rendered is "unkown path", erros being "Failed to load resource: the server responded with a status of 404 (Not Found)".

I kept checking the routes files as much as I could and I can't see what doesn't work here. This is how the index.js file looks like

import route from './router.js';

import Login from '../ui/pages/user/Login';
import Home from '../ui/Home';
import Register from '../ui/pages/user/Register';
import PostCreate from '../ui/pages/post/PostCreate';
import PostList from '../ui/pages/post/PostList';
import PostEdit from '../ui/pages/post/PostEdit';

route('/', Home, {}, {
    name: 'home'
  });
  route('/login', Login, {}, {
    name: 'login'
  });
  route('/register', Register, {}, {
    name: 'register'
  });
  route('/post/create', PostCreate, {}, {
    name: 'post.create'
  });
  route('/post/list', PostList, {}, {
    name: 'post.list'
  });
  route('/post/edit/:_id', PostEdit, {}, {
    name:'post.edit'
  });

And this is the router.js file

import { createRouter } from 'meteor/cultofcoders:meteor-react-routing';
import App from '/imports/ui/App.jsx';

export default createRouter(App);

Could it just be an issue regarding the routing package I'm using?

Body:
I feel you are using the "wrong" router. cultofcoders:meteor-react-routing seems to not have been maintained in the past 2 years which is huge in terms of react routing. Would you be interested to try "react-router": "^5.0.0" with "react-router-dom": "^5.0.0" then you have something like:

import React from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import Component1 from '.....'
import Component2 from '.....'

const Main = location => {
  return (
      <Switch location={location.location}>
        <Route exact path='/' component={Component1} />
        <Route exact path='/something' component={Component2} />
        <Route exact path='/something/:id' component={Component2} /> // route with param
        <Route path='*' component={NotFoundPage} />
        ...........
      </Switch>)
}


问:
Remove comment markup generated by a v-if condition
want to remove the conditional comment markup (  ) from the HTML

I am using a condition for example

```<code><sidebar v-if="showSidebarTrigger"> ... </sidebar>
</code>```

when the condition is false in dom  generated i wanted that to remove

答:
This is what I found said by Evan You on related Github issue

v-if is usually used for elements in a relatively stable node structure, rendering it to empty comment tags makes vnode lists diffing more efficient as the lists are more "stable", and it avoids some edge cases when elements are not keyed.

As stated in the statement further- a related workaround will work here - you can usev-for as an alternative if you don't want lots of such comment tags in DOM.

Make computed property say displaySideBar and push your showSidebarTrigger conditionally in array and return it.

```<code>displaySideBar() {
let showSideBar = []
  if(showSidebarTrigger) {
    showSideBar.push(showSidebarTrigger)
  }
}
</code>```

Now in your html section

```<code><div v-for="(sideBar, index) in displaySideBar" :key="`sideBar-${index}`">
   <h1> Hey </h1>
</div>
</code>```

Body:
want to remove the conditional comment markup (  ) from the HTML

I am using a condition for example

<sidebar v-if="showSidebarTrigger"> ... </sidebar>

when the condition is false in dom  generated i wanted that to remove

Body:
This is what I found said by Evan You on related Github issue

v-if is usually used for elements in a relatively stable node structure, rendering it to empty comment tags makes vnode lists diffing more efficient as the lists are more "stable", and it avoids some edge cases when elements are not keyed.

As stated in the statement further- a related workaround will work here - you can usev-for as an alternative if you don't want lots of such comment tags in DOM.

Make computed property say displaySideBar and push your showSidebarTrigger conditionally in array and return it.

displaySideBar() {
let showSideBar = []
  if(showSidebarTrigger) {
    showSideBar.push(showSidebarTrigger)
  }
}

Now in your html section

<div v-for="(sideBar, index) in displaySideBar" :key="`sideBar-${index}`">
   <h1> Hey </h1>
</div>


问:
Why my form only work in chrome when Js is active?
To submit my form, the user need choice the price of your ticket by html droplist.

Here is JS the code:

```<code>var ticket = document.getElementById('ticket-box');
var member = document.getElementById('member');
var form = document.getElementById('form');

form.style.display = 'none';
ticket.style.display = 'none';

member.addEventListener('change', function() {
  var chosen = member.options[member.selectedIndex].index;

  if(chosen == 1) {
    form.style.display = 'inline-block';
    ticket.style.display = 'inline-block';
    form.selectedIndex = 2;
    form.options[0].style.display = 'none';
    form.options[1].style.display = 'none';
    form.options[2].style.display = 'inline-block';
    form.options[3].style.display = 'inline-block';
    form.options[4].style.display = 'none';
    form.options[5].style.display = 'none';

$(function() {
   $('#btnget').click(function(e) {

      let formValido =  document
    .getElementById("formulario")
    .checkValidity();

      if(formValido){
         $("#formulario")
         .attr("action", $('#form').val())
         .submit();
      }
   })
});
  }
  });
</code>```

This only works in chrome (email is comming only in chrome).

Why is this happening?

form link: http://www.congressoprotecaodados.com.br/inscricao/form22.html

答: maybe you are using some javascript function or keyword which is only support to chrome .Please refer mozilla develope netword to check browser support for any javascript built in function .</p>

Body:
To submit my form, the user need choice the price of your ticket by html droplist.

Here is JS the code:

var ticket = document.getElementById('ticket-box');
var member = document.getElementById('member');
var form = document.getElementById('form');

form.style.display = 'none';
ticket.style.display = 'none';

member.addEventListener('change', function() {
  var chosen = member.options[member.selectedIndex].index;

  if(chosen == 1) {
    form.style.display = 'inline-block';
    ticket.style.display = 'inline-block';
    form.selectedIndex = 2;
    form.options[0].style.display = 'none';
    form.options[1].style.display = 'none';
    form.options[2].style.display = 'inline-block';
    form.options[3].style.display = 'inline-block';
    form.options[4].style.display = 'none';
    form.options[5].style.display = 'none';

$(function() {
   $('#btnget').click(function(e) {

      let formValido =  document
    .getElementById("formulario")
    .checkValidity();

      if(formValido){
         $("#formulario")
         .attr("action", $('#form').val())
         .submit();
      }
   })
});
  }
  });

This only works in chrome (email is comming only in chrome).

Why is this happening?

form link: http://www.congressoprotecaodados.com.br/inscricao/form22.html


问:
iPhone Safari browser, change # hash URL and then Javascript alert message box stop working
I run a web page in iPhone Safari. The page has a button. on clicking it, will show an alert message box. This is OK. Then, I change or add # hash URL by typing in the address bar, then, alert message box stop working. I click the button, and nothing happens. No javascript error but no alert message box.

Is this iOS Safari known issue?

Please share your thoughts and the solution you have come up with. Many Thanks!

$(".button").click(function () {
  alert('Hello');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input class="button" type="button" value="alert" /></code>```

Note:

This is not quite due to my code. I have also tested at
Here

I have tested in the most recent iOS versions.

Javascript itself is working

Not JQuery issue, plain JS code also does not work

An alert box is working in iPhone Chrome or other browsers

答:
Could be related to Alert, confirm, and prompt not working after using History API on Safari, iOS and https://forums.developer.apple.com/thread/65054

It seems that alert() becomes undefined. A suggested workaround is to use custom popups instead.

Body:
I run a web page in iPhone Safari. The page has a button. on clicking it, will show an alert message box. This is OK. Then, I change or add # hash URL by typing in the address bar, then, alert message box stop working. I click the button, and nothing happens. No javascript error but no alert message box.

Is this iOS Safari known issue?

Please share your thoughts and the solution you have come up with. Many Thanks!

$(".button").click(function () {
  alert('Hello');
});

<input class="button" type="button" value="alert" />

Note:

This is not quite due to my code. I have also tested at
Here

I have tested in the most recent iOS versions.

Javascript itself is working

Not JQuery issue, plain JS code also does not work

An alert box is working in iPhone Chrome or other browsers


问:
Cannot install SDK Tools 28.0.3
I have Android Studio 3.4.1.
When I go to SDK Manager, under SDK Tools, it only shows me 26.1.1.
I cannot see SDK Tools 28.0.3
It does show me Android SDK Platform-Tools 28.0.3

Any idea how do I get SDK Tools 28.0.3?

Here are the platforms I have selected and installed:

Thanks

答:
Try to download it from the official android developers page:
https://developer.android.com/sdk/older_releases.html</p>

Title: Cannot install SDK Tools 28.0.3


问:
How to change file template XIB from NS to UI?
I'm attempting to create a file template that generates a View.swift file (subclass of a UIView) and a XIB connected to said View.swift file.

I can connect the two just fine, but for some reason, my XIB is not... er... UIKit friendly? I'm not sure how exactly to describe it. I expect my XIB file to load like so:

However, it instead loads like this:

Here is the relevant View.swift file, the configuration for the XIB file, and the TemplateInfo.plist

View.swift

```<code>import UIKit

class ___VARIABLE_sceneName___View: ___VARIABLE_cocoaSubclass___ {
    //MARK: XIB Outlets
    @IBOutlet var contentView: ___VARIABLE_cocoaSubclass___!

 // MARK: Object lifecycle
override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

// MARK: Setup

private func setup() {
Bundle.main.loadNibNamed("___VARIABLE_sceneName___", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds
        contentView.autoresizingMask = [.flexibleHeight, .flexibleHeight]
}
</code>```

XIB

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="11134" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="11134"/>
    </dependencies>
    <objects>
        <customObject id="-2" userLabel="File's Owner" customClass="___VARIABLE_sceneName___View" customModuleProvider="target">
            <connections>
                <outlet property="contentView" destination="Hz6-mo-xeY" id="0bl-1N-x8E"/>
            </connections>
        </customObject>
        <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
        <customObject id="-3" userLabel="Application" customClass="NSObject"/>
        <customView id="Hz6-mo-xeY">
            <rect key="frame" x="0.0" y="0.0" width="480" height="272"/>
            <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
        </customView>
    </objects>
</document>
</code>```

TemplateInfo.plist

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>DefaultCompletionName</key>
    <string>MyScene</string>
    <key>Description</key>
    <string>This generates a new View for a View Controller.</string>
    <key>Kind</key>
    <string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
    <key>Options</key>
    <array>
        <dict>
            <key>Name</key>
            <string>Subclass Of</string>
            <key>Values</key>
            <array>
                <string>NSView</string>
            </array>
            <key>FallbackHeader</key>
            <string>#import <Cocoa/Cocoa.h></string>
            <key>Default</key>
            <string>NSView</string>
            <key>Type</key>
            <string>class</string>
            <key>Identifier</key>
            <string>cocoaSubclass</string>
        </dict>
        <dict>
            <key>Description</key>
            <string>The name of the scene to create</string>
            <key>Identifier</key>
            <string>sceneName</string>
            <key>Name</key>
            <string>New Scene Name:</string>
            <key>NotPersisted</key>
            <true/>
            <key>Required</key>
            <true/>
            <key>Type</key>
            <string>text</string>
        </dict>
        <dict>
            <key>Default</key>
            <string>___VARIABLE_sceneName:identifier___</string>
            <key>Identifier</key>
            <string>productName</string>
            <key>Type</key>
            <string>static</string>
        </dict>
        <dict>
            <key>Default</key>
            <string>___VARIABLE_sceneName:identifier___View</string>
            <key>Description</key>
            <string>The view controller name</string>
            <key>Identifier</key>
            <string>viewControllerName</string>
            <key>Name</key>
            <string>View Controller Name:</string>
            <key>Required</key>
            <true/>
            <key>Type</key>
            <string>static</string>
        </dict>
        <dict>
            <key>Default</key>
            <string>___VARIABLE_sceneName:identifier___Components</string>
            <key>Description</key>
            <string>The components name</string>
            <key>Identifier</key>
            <string>componentsName</string>
            <key>Name</key>
            <string>Components Name:</string>
            <key>Required</key>
            <true/>
            <key>Type</key>
            <string>static</string>
        </dict>
        <dict>
            <key>Identifier</key>
            <string>XIB</string>
            <key>Name</key>
            <string>Also create a XIB file</string>
            <key>Description</key>
            <string>Use a Xib?</string>
            <key>Type</key>
            <string>checkbox</string>
            <key>Required</key>
            <true/>
            <key>Default</key>
            <false/>
            <key>NotPersisted</key>
            <true/>
        </dict>
        <dict>
            <key>Identifier</key>
            <string>languageChoice</string>
            <key>Required</key>
            <true/>
            <key>Name</key>
            <string>Language:</string>
            <key>Description</key>
            <string>The implementation language</string>
            <key>Type</key>
            <string>popup</string>
            <key>Default</key>
            <string>Swift</string>
            <key>Values</key>
            <array>
                <string>Swift</string>
            </array>
            <key>MainTemplateFiles</key>
            <dict>
                <key>Swift</key>
                <string>___FILEBASENAME___View.swift</string>
            </dict>
            <key>AllowedTypes</key>
            <dict>
                <key>Swift</key>
                <array>
                    <string>public.swift-source</string>
                </array>
            </dict>
        </dict>
    </array>
    <key>Platforms</key>
    <array>
        <string>com.apple.platform.iphoneos</string>
    </array>
    <key>SortOrder</key>
    <string>1</string>
    <key>Summary</key>
    <string>This generates a new View for the View Controller of the same name.</string>
</dict>
</plist>
</code>```

The template container folder name is NSViewXIBSwift.

答:
When you create your xib, distinguish an iOS xib:

from a macOS xib:

Body:
I'm attempting to create a file template that generates a View.swift file (subclass of a UIView) and a XIB connected to said View.swift file.

I can connect the two just fine, but for some reason, my XIB is not... er... UIKit friendly? I'm not sure how exactly to describe it. I expect my XIB file to load like so:

However, it instead loads like this:

Here is the relevant View.swift file, the configuration for the XIB file, and the TemplateInfo.plist

View.swift

import UIKit

class ___VARIABLE_sceneName___View: ___VARIABLE_cocoaSubclass___ {
    //MARK: XIB Outlets
    @IBOutlet var contentView: ___VARIABLE_cocoaSubclass___!

 // MARK: Object lifecycle
override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

// MARK: Setup

private func setup() {
Bundle.main.loadNibNamed("___VARIABLE_sceneName___", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds
        contentView.autoresizingMask = [.flexibleHeight, .flexibleHeight]
}

XIB

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="11134" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="11134"/>
    </dependencies>
    <objects>
        <customObject id="-2" userLabel="File's Owner" customClass="___VARIABLE_sceneName___View" customModuleProvider="target">
            <connections>
                <outlet property="contentView" destination="Hz6-mo-xeY" id="0bl-1N-x8E"/>
            </connections>
        </customObject>
        <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
        <customObject id="-3" userLabel="Application" customClass="NSObject"/>
        <customView id="Hz6-mo-xeY">
            <rect key="frame" x="0.0" y="0.0" width="480" height="272"/>
            <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
        </customView>
    </objects>
</document>

TemplateInfo.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>DefaultCompletionName</key>
    <string>MyScene</string>
    <key>Description</key>
    <string>This generates a new View for a View Controller.</string>
    <key>Kind</key>
    <string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
    <key>Options</key>
    <array>
        <dict>
            <key>Name</key>
            <string>Subclass Of</string>
            <key>Values</key>
            <array>
                <string>NSView</string>
            </array>
            <key>FallbackHeader</key>
            <string>#import <Cocoa/Cocoa.h></string>
            <key>Default</key>
            <string>NSView</string>
            <key>Type</key>
            <string>class</string>
            <key>Identifier</key>
            <string>cocoaSubclass</string>
        </dict>
        <dict>
            <key>Description</key>
            <string>The name of the scene to create</string>
            <key>Identifier</key>
            <string>sceneName</string>
            <key>Name</key>
            <string>New Scene Name:</string>
            <key>NotPersisted</key>
            <true/>
            <key>Required</key>
            <true/>
            <key>Type</key>
            <string>text</string>
        </dict>
        <dict>
            <key>Default</key>
            <string>___VARIABLE_sceneName:identifier___</string>
            <key>Identifier</key>
            <string>productName</string>
            <key>Type</key>
            <string>static</string>
        </dict>
        <dict>
            <key>Default</key>
            <string>___VARIABLE_sceneName:identifier___View</string>
            <key>Description</key>
            <string>The view controller name</string>
            <key>Identifier</key>
            <string>viewControllerName</string>
            <key>Name</key>
            <string>View Controller Name:</string>
            <key>Required</key>
            <true/>
            <key>Type</key>
            <string>static</string>
        </dict>
        <dict>
            <key>Default</key>
            <string>___VARIABLE_sceneName:identifier___Components</string>
            <key>Description</key>
            <string>The components name</string>
            <key>Identifier</key>
            <string>componentsName</string>
            <key>Name</key>
            <string>Components Name:</string>
            <key>Required</key>
            <true/>
            <key>Type</key>
            <string>static</string>
        </dict>
        <dict>
            <key>Identifier</key>
            <string>XIB</string>
            <key>Name</key>
            <string>Also create a XIB file</string>
            <key>Description</key>
            <string>Use a Xib?</string>
            <key>Type</key>
            <string>checkbox</string>
            <key>Required</key>
            <true/>
            <key>Default</key>
            <false/>
            <key>NotPersisted</key>
            <true/>
        </dict>
        <dict>
            <key>Identifier</key>
            <string>languageChoice</string>
            <key>Required</key>
            <true/>
            <key>Name</key>
            <string>Language:</string>
            <key>Description</key>
            <string>The implementation language</string>
            <key>Type</key>
            <string>popup</string>
            <key>Default</key>
            <string>Swift</string>
            <key>Values</key>
            <array>
                <string>Swift</string>
            </array>
            <key>MainTemplateFiles</key>
            <dict>
                <key>Swift</key>
                <string>___FILEBASENAME___View.swift</string>
            </dict>
            <key>AllowedTypes</key>
            <dict>
                <key>Swift</key>
                <array>
                    <string>public.swift-source</string>
                </array>
            </dict>
        </dict>
    </array>
    <key>Platforms</key>
    <array>
        <string>com.apple.platform.iphoneos</string>
    </array>
    <key>SortOrder</key>
    <string>1</string>
    <key>Summary</key>
    <string>This generates a new View for the View Controller of the same name.</string>
</dict>
</plist>

The template container folder name is NSViewXIBSwift.