问:
Modify normals after rotating a cube in WebGL
I'm trying to use normals for simple point lights on this simple scene, but I need the normals to modify correctly to the rotation of the cube.

Some notes for the code:

The reason it's so large is because it uses multiple files, which provides more organization.

The reasoning for the cube being rotated within the vertex shader but the cosine and sine operations being performed outside of it is due to performance improvements.

Instead of changing a buffer for, say, 100 cubes and rotating each and every one of them, in order to rotate the cube, we just need to input one buffer. If you just want to rotate the model view projection, that's fine, but if you want to have two cubes (side by side) rotating in different directions or have a first-person shooter with different rotating objects, that's nearly impossible.

// "shaders.js"
const vsSource = [
  `attribute vec4 aVertexPosition;`,
  `attribute vec3 aVertexNormal;`,
  `uniform mat4 uModelViewMatrix;`,
  `uniform mat4 uProjectionMatrix;`,
  `uniform mat4 uNormalMatrix;`,
  `uniform vec3 uTransform;`,
  `uniform vec2 uRotationX;`,
  `uniform vec2 uRotationY;`,
  `uniform vec2 uRotationZ;`,
  `varying highp vec3 vLighting;`,
  `void main(void) {`,
  ` vec4 p = aVertexPosition;`,
  ` float n0x = p.x * uRotationX.y + p.y * uRotationX.x;`,
  ` float n0y = p.y * uRotationX.y - p.x * uRotationX.x;`,
  ` float n0z = p.z;`,
  ` float n1x = n0x;`,
  ` float n1y = n0y * uRotationY.y + n0z * uRotationY.x;`,
  ` float n1z = n0z * uRotationY.y - n0y * uRotationY.x;`,
  ` float n2x = n1x * uRotationZ.y - n1z * uRotationZ.x;`,
  ` float n2y = n1y;`,
  ` float n2z = n1z * uRotationZ.y + n1x * uRotationZ.x;`,
  ` gl_Position = uProjectionMatrix * uModelViewMatrix * (vec4(vec3(n2x, n2y, n2z) + uTransform, p.w));`,
  ` highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);`,
  ` highp vec3 directionalLightColor = vec3(1.0, 1.0, 1.0);`,
  ` highp vec3 directionalVector = normalize(vec3(0.85, 0.8, 0.75));`,
  ` highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);`,
  ` highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);`,
  ` vLighting = ambientLight + (directionalLightColor * directional);`,
  `}`
].join(`\n`);
const fsSource = [
  `varying highp vec3 vLighting;`,
  `void main(void) {`,
  ` gl_FragColor = vec4(vec3(1.0, 0.0, 0.0) * vLighting, 1.0);`,
  `}`
].join(`\n`);

const initShaders = (gl) => {
  const vertexShader = gl.createShader(gl.VERTEX_SHADER),
    fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(vertexShader, vsSource);
  gl.shaderSource(fragmentShader, fsSource);
  gl.compileShader(vertexShader);
  if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
    alert(`An error occurred compiling the shaders: ${gl.getShaderInfoLog(vertexShader)}`);
    gl.deleteShader(vertexShader);
    return null;
  };
  gl.compileShader(fragmentShader);
  if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
    alert(`An error occurred compiling the shaders: ${gl.getShaderInfoLog(fragmentShader)}`);
    gl.deleteShader(fragmentShader);
    return null;
  };
  return {
    'vertex': vertexShader,
    'fragment': fragmentShader
  };
};
// "object.js"
class Obj {
  #positions;
  #index;
  #normals;
  get positions() {
    return [...(this.#positions)];
  };
  get index() {
    return [...(this.#index)];
  };
  get normals() {
    return [...(this.#normals)];
  };
  constructor(positions, index, normals) {
    if (typeof positions == `object` && typeof index == `object` && typeof normals == `object`) {
      this.#positions = positions;
      this.#index = index;
      this.#normals = index;
    } else {
      console.error(`Need "object" type, got: "${typeof positions}", "${typeof index}"`)
    };
    return;
  };
};

class Object {
  static Cube = class Cube extends Obj {
    constructor() {
      super([-1.0, -1.0, 1.0,
        1.0, -1.0, 1.0,
        1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0,
        1.0, 1.0, -1.0,
        1.0, -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
        1.0, 1.0, -1.0, -1.0, -1.0, -1.0,
        1.0, -1.0, -1.0,
        1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
        1.0, -1.0, -1.0,
        1.0, 1.0, -1.0,
        1.0, 1.0, 1.0,
        1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0
      ], [
        0, 1, 2, 0, 2, 3,
        4, 5, 6, 4, 6, 7,
        8, 9, 10, 8, 10, 11,
        12, 13, 14, 12, 14, 15,
        16, 17, 18, 16, 18, 19,
        20, 21, 22, 20, 22, 23
      ], [
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, -1.0,
        0.0, 0.0, -1.0,
        0.0, 0.0, -1.0,
        0.0, 0.0, -1.0,
        0.0, 1.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, -1.0, 0.0,
        0.0, -1.0, 0.0,
        0.0, -1.0, 0.0,
        0.0, -1.0, 0.0,
        1.0, 0.0, 0.0,
        1.0, 0.0, 0.0,
        1.0, 0.0, 0.0,
        1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0
      ]);
    };
  };
};

const getBuffers = (gl, clas) => {
  if (typeof clas != `function`) {
    console.error(`Need "function" type, got: "${typeof clas}"`);
    return;
  };
  const classy = new clas();
  var positions = classy.positions,
    index = classy.index,
    normals = classy.normals;
  if (positions != undefined && positions != null && index != undefined && index != null && normals != undefined && normals != null) {
    const positionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
    const normalBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);
    const indexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(index), gl.STATIC_DRAW);
    return {
      'position': positionBuffer,
      'index': indexBuffer,
      'normal': normalBuffer
    }
  } else {
    console.error(`Need any input type, got: "${typeof positions}", "${typeof index}", "${typeof normals}"`);
  };
  return;
};
// "draw.js"
var doDraw,
  draw,
  drawRad;
(() => {
  const DTR = Math.PI / 180.0,
    RTD = 180.0 / Math.PI;
  var draws = [];
  doDraw = (gl, aVertexPosition, aVertexNormal, uProjectionMatrix, uModelViewMatrix, uNormalMatrix, uTransform, uRotationX, uRotationY, uRotationZ, projectionMatrix, modelViewMatrix) => {
    draws.forEach((e) => {
      const normalMatrix = mat4.create();
      mat4.invert(normalMatrix, normalMatrix);
      mat4.transpose(normalMatrix, normalMatrix);
      gl.bindBuffer(gl.ARRAY_BUFFER, e[`buffs`][`position`]);
      gl.vertexAttribPointer(aVertexPosition, 3, gl.FLOAT, false, 0, 0);
      gl.enableVertexAttribArray(aVertexPosition);
      gl.bindBuffer(gl.ARRAY_BUFFER, e[`buffs`][`normal`]);
      gl.vertexAttribPointer(aVertexNormal, 3, gl.FLOAT, false, 0, 0);
      gl.enableVertexAttribArray(aVertexNormal);
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, e[`buffs`][`index`]);
      gl.uniformMatrix4fv(uProjectionMatrix, false, projectionMatrix);
      gl.uniformMatrix4fv(uModelViewMatrix, false, modelViewMatrix);
      gl.uniformMatrix4fv(uNormalMatrix, false, normalMatrix);
      gl.uniform3fv(uTransform, e[`transform`]);
      gl.uniform2fv(uRotationX, e[`rotateX`]);
      gl.uniform2fv(uRotationY, e[`rotateY`]);
      gl.uniform2fv(uRotationZ, e[`rotateZ`]);
      gl.drawElements(gl.TRIANGLES, e[`count`], gl.UNSIGNED_SHORT, 0); // LINE_LOOP, TRIANGLES
      return;
    });
    draws = [];
    return;
  };
  draw = (buffs, vertexCount, x, y, z, rx, ry, rz) => {
    const rxr = rx * DTR,
      ryr = ry * DTR,
      rzr = rz * DTR;
    draws.push({
      'buffs': buffs,
      'transform': [
        x,
        y,
        z
      ],
      'rotateX': [
        Math.sin(rxr),
        Math.cos(rxr)
      ],
      'rotateY': [
        Math.sin(ryr),
        Math.cos(ryr)
      ],
      'rotateZ': [
        Math.sin(rzr),
        Math.cos(rzr)
      ],
      'rx': rxr,
      'ry': ryr,
      'rz': rzr,
      'count': vertexCount
    });
    return;
  };
  drawRad = (buffs, vertexCount, x, y, z, rx, ry, rz) => {
    draws.push({
      'buffs': buffs,
      'transform': [
        x,
        y,
        z
      ],
      'rotateX': [
        Math.sin(rx),
        Math.cos(rx)
      ],
      'rotateY': [
        Math.sin(ry),
        Math.cos(ry)
      ],
      'rotateZ': [
        Math.sin(rz),
        Math.cos(rz)
      ],
      'rx': rx,
      'ry': ry,
      'rz': rz,
      'count': vertexCount
    });
    return;
  };
  return;
})();
// "script.js"
(() => {
  const DTR = Math.PI / 180.0,
    RTD = 180.0 / Math.PI;
  var gl,
    ctx,
    canvasgl,
    canvasctx,
    width = 0,
    height = 0,
    cubeBuffs,
    shaderProgram,
    vertexShader,
    fragmentShader,
    aVertexPosition,
    aVertexNormal,
    uProjectionMatrix,
    uModelViewMatrix,
    uNormalMatrix,
    uTransform,
    uRotationX,
    uRotationY,
    uRotationZ,
    aProjectionMatrix,
    aModelViewMatrix,
    projectionMatrix,
    modelViewMatrix,
    cx = 0.0,
    cy = 0.0,
    cz = 0.0,
    crx = 0.0,
    cry = 0.0,
    crz = 0.0;
  var cubeTime = 0.0;
  var updates = [],
    updateTime = 0,
    fpsupdate = 0.0,
    fpsupdatemin = 0.0,
    fpsupdatemax = 0.0;
  const loop = (deltaTime) => {
    cubeTime += deltaTime * 90;
    updateTime += deltaTime;
    updates.push(deltaTime);
    if (updates.length > 60) {
      var n = updates.shift();
    };
    var l = updates.length,
      ftime = 0.0;
    var max = 0.0,
      min = 1000.0;
    updates.forEach((e) => {
      ftime += e;
      if (min > e) {
        min = e;
      };
      if (max < e) {
        max = e;
      };
      return;
    });
    fpsupdatemin = min;
    fpsupdatemax = max;
    fpsupdate = ftime / l;
    ctx.fillStyle = `#fff`;
    ctx.font = `12px serif`;
    var txt0 = ` 1 / deltaTime: [ FPS: ${(1 / deltaTime).toFixed(1)} ]`,
      txt1 = ` Average / deltaTime: [ FPS: ${(1 / fpsupdate).toFixed(1)} ]`,
      txt2 = ` Maximum  / deltaTime: [ FPS: ${(1 / fpsupdatemin).toFixed(1)} ]`,
      txt3 = ` Minimum / deltaTime: [ FPS: ${(1 / fpsupdatemax).toFixed(1)} ]`;
    var metrics0 = ctx.measureText(` FPS:`),
      metrics1 = ctx.measureText(txt0),
      metrics2 = ctx.measureText(txt1),
      metrics3 = ctx.measureText(txt2),
      metrics4 = ctx.measureText(txt3);
    var hmet0 = metrics0.actualBoundingBoxAscent + metrics0.actualBoundingBoxDescent + 2,
      hmet1 = metrics1.actualBoundingBoxAscent + metrics1.actualBoundingBoxDescent + 2,
      hmet2 = metrics2.actualBoundingBoxAscent + metrics2.actualBoundingBoxDescent + 2,
      hmet3 = metrics3.actualBoundingBoxAscent + metrics3.actualBoundingBoxDescent + 2,
      hmet4 = metrics4.actualBoundingBoxAscent + metrics4.actualBoundingBoxDescent + 2;
    ctx.fillText(` FPS:`, 0, hmet0);
    ctx.fillText(txt0, 0, hmet0 + hmet1);
    ctx.fillText(txt1, 0, hmet0 + hmet1 + hmet2);
    ctx.fillText(txt2, 0, hmet0 + hmet1 + hmet2 + hmet3);
    ctx.fillText(txt3, 0, hmet0 + hmet1 + hmet2 + hmet3 + hmet4);
    draw(cubeBuffs, 36, 0.0, 0.0, 0.0, cubeTime * 0.3, cubeTime * 0.7, cubeTime);
    return;
  };
  var l,
    then = 0;
  l = (now) => {
    requestAnimationFrame(l);
    now *= 0.001;
    const dT = now - then;
    then = now;
    mat4.copy(projectionMatrix, aProjectionMatrix);
    mat4.copy(modelViewMatrix, aModelViewMatrix);
    mat4.translate(modelViewMatrix, modelViewMatrix, [
      cx, -cy,
      cz
    ]);
    mat4.rotate(projectionMatrix, projectionMatrix, (-crx) * DTR, [
      1,
      0,
      0
    ]);
    mat4.rotate(projectionMatrix, projectionMatrix, cry * DTR, [
      0,
      1,
      0
    ]);
    mat4.rotate(projectionMatrix, projectionMatrix, crz * DTR, [
      0,
      0,
      1
    ]);
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clearDepth(1.0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    ctx.clearRect(0, 0, width, height);
    loop(dT);
    doDraw(gl, aVertexPosition, aVertexNormal, uProjectionMatrix, uModelViewMatrix, uNormalMatrix, uTransform, uRotationX, uRotationY, uRotationZ, projectionMatrix, modelViewMatrix);
    return;
  };
  const init = () => {
    cubeBuffs = getBuffers(gl, Object.Cube);
    cx = -6.0;
    cy = 6.0;
    cz = -6.0;
    crx = -45.0;
    cry = -45.0;
    return false;
  };
  const resize = () => {
    height = document.body.clientHeight;
    width = document.body.clientWidth;
    canvasctx.style.height = `${height}px`;
    canvasctx.style.width = `${width}px`;
    canvasctx.height = height;
    canvasctx.width = width;
    canvasgl.style.height = `${height}px`;
    canvasgl.style.width = `${width}px`;
    canvasgl.height = height;
    canvasgl.width = width;
    mat4.perspective(aProjectionMatrix, (45.0 * Math.PI) / 180.0, width / height, 0.0, 1000.0);
    gl.viewport(0, 0, width, height);
    return;
  };
  const ini = () => {
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    const shaders = initShaders(gl);
    vertexShader = shaders[`vertex`];
    fragmentShader = shaders[`fragment`];
    shaderProgram = gl.createProgram();
    gl.attachShader(shaderProgram, vertexShader);
    gl.attachShader(shaderProgram, fragmentShader);
    gl.linkProgram(shaderProgram);
    if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
      alert(`Unable to initialize the shader program: ${gl.getProgramInfoLog(shaderProgram)}`);
      return true;
    };
    gl.useProgram(shaderProgram);
    aVertexPosition = gl.getAttribLocation(shaderProgram, `aVertexPosition`);
    aVertexNormal = gl.getAttribLocation(shaderProgram, `aVertexNormal`);
    uProjectionMatrix = gl.getUniformLocation(shaderProgram, `uProjectionMatrix`);
    uModelViewMatrix = gl.getUniformLocation(shaderProgram, `uModelViewMatrix`);
    uNormalMatrix = gl.getUniformLocation(shaderProgram, `uNormalMatrix`);
    uTransform = gl.getUniformLocation(shaderProgram, `uTransform`);
    uRotationX = gl.getUniformLocation(shaderProgram, `uRotationX`);
    uRotationY = gl.getUniformLocation(shaderProgram, `uRotationY`);
    uRotationZ = gl.getUniformLocation(shaderProgram, `uRotationZ`);
    gl.disable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
    gl.enable(gl.CULL_FACE);
    gl.cullFace(gl.BACK);
    gl.enable(gl.DEPTH_TEST);
    gl.depthFunc(gl.LEQUAL);
    return init();
  };
  window.addEventListener(`load`, () => {
    canvasctx = document.createElement(`canvas`);
    canvasgl = document.createElement(`canvas`);
    canvasctx.style.imageRendering = `pixelated`;
    canvasctx.style.position = `fixed`;
    canvasctx.style.zIndex = `999`;
    canvasctx.style.left = `0px`;
    canvasctx.style.top = `0px`;
    canvasgl.style.position = `fixed`;
    canvasgl.style.zIndex = `989`;
    canvasgl.style.left = `0px`;
    canvasgl.style.top = `0px`;
    document.body.appendChild(canvasctx);
    document.body.appendChild(canvasgl);
    projectionMatrix = mat4.create();
    modelViewMatrix = mat4.create();
    aProjectionMatrix = mat4.create();
    aModelViewMatrix = mat4.create();
    ctx = canvasctx.getContext(`2d`);
    gl = canvasgl.getContext(`webgl2`, {
      'powerPreference': `high-performance`
    });
    if (ctx == null || typeof ctx == `undefined`) {
      console.error(`Unable to get 2D context`);
      alert(`Unable to get 2D context`);
      return;
    };
    if (gl == null || typeof gl == `undefined`) {
      console.error(`Unable to get WebGL2 context`);
      alert(`Unable to get WebGL2 context`);
      return;
    };
    resize();
    var cb;
    window.addEventListener(`resize`, () => {
      clearTimeout(cb);
      cb = setTimeout(resize, 150);
      return;
    });
    if (ini() == false) {
      then = performance.now() * 0.001;
      requestAnimationFrame(l);
    };
    return;
  });
  return;
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  padding: 0px;
  margin: 0px;
}

html,
body {
  height: 100%;
  width: 100%;
}</code>```

```

Body:
I'm trying to use normals for simple point lights on this simple scene, but I need the normals to modify correctly to the rotation of the cube.

Some notes for the code:

The reason it's so large is because it uses multiple files, which provides more organization.

The reasoning for the cube being rotated within the vertex shader but the cosine and sine operations being performed outside of it is due to performance improvements.

Instead of changing a buffer for, say, 100 cubes and rotating each and every one of them, in order to rotate the cube, we just need to input one buffer. If you just want to rotate the model view projection, that's fine, but if you want to have two cubes (side by side) rotating in different directions or have a first-person shooter with different rotating objects, that's nearly impossible.

// "shaders.js"
const vsSource = [
  `attribute vec4 aVertexPosition;`,
  `attribute vec3 aVertexNormal;`,
  `uniform mat4 uModelViewMatrix;`,
  `uniform mat4 uProjectionMatrix;`,
  `uniform mat4 uNormalMatrix;`,
  `uniform vec3 uTransform;`,
  `uniform vec2 uRotationX;`,
  `uniform vec2 uRotationY;`,
  `uniform vec2 uRotationZ;`,
  `varying highp vec3 vLighting;`,
  `void main(void) {`,
  ` vec4 p = aVertexPosition;`,
  ` float n0x = p.x * uRotationX.y + p.y * uRotationX.x;`,
  ` float n0y = p.y * uRotationX.y - p.x * uRotationX.x;`,
  ` float n0z = p.z;`,
  ` float n1x = n0x;`,
  ` float n1y = n0y * uRotationY.y + n0z * uRotationY.x;`,
  ` float n1z = n0z * uRotationY.y - n0y * uRotationY.x;`,
  ` float n2x = n1x * uRotationZ.y - n1z * uRotationZ.x;`,
  ` float n2y = n1y;`,
  ` float n2z = n1z * uRotationZ.y + n1x * uRotationZ.x;`,
  ` gl_Position = uProjectionMatrix * uModelViewMatrix * (vec4(vec3(n2x, n2y, n2z) + uTransform, p.w));`,
  ` highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);`,
  ` highp vec3 directionalLightColor = vec3(1.0, 1.0, 1.0);`,
  ` highp vec3 directionalVector = normalize(vec3(0.85, 0.8, 0.75));`,
  ` highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);`,
  ` highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);`,
  ` vLighting = ambientLight + (directionalLightColor * directional);`,
  `}`
].join(`\n`);
const fsSource = [
  `varying highp vec3 vLighting;`,
  `void main(void) {`,
  ` gl_FragColor = vec4(vec3(1.0, 0.0, 0.0) * vLighting, 1.0);`,
  `}`
].join(`\n`);

const initShaders = (gl) => {
  const vertexShader = gl.createShader(gl.VERTEX_SHADER),
    fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(vertexShader, vsSource);
  gl.shaderSource(fragmentShader, fsSource);
  gl.compileShader(vertexShader);
  if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
    alert(`An error occurred compiling the shaders: ${gl.getShaderInfoLog(vertexShader)}`);
    gl.deleteShader(vertexShader);
    return null;
  };
  gl.compileShader(fragmentShader);
  if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
    alert(`An error occurred compiling the shaders: ${gl.getShaderInfoLog(fragmentShader)}`);
    gl.deleteShader(fragmentShader);
    return null;
  };
  return {
    'vertex': vertexShader,
    'fragment': fragmentShader
  };
};
// "object.js"
class Obj {
  #positions;
  #index;
  #normals;
  get positions() {
    return [...(this.#positions)];
  };
  get index() {
    return [...(this.#index)];
  };
  get normals() {
    return [...(this.#normals)];
  };
  constructor(positions, index, normals) {
    if (typeof positions == `object` && typeof index == `object` && typeof normals == `object`) {
      this.#positions = positions;
      this.#index = index;
      this.#normals = index;
    } else {
      console.error(`Need "object" type, got: "${typeof positions}", "${typeof index}"`)
    };
    return;
  };
};

class Object {
  static Cube = class Cube extends Obj {
    constructor() {
      super([-1.0, -1.0, 1.0,
        1.0, -1.0, 1.0,
        1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0,
        1.0, 1.0, -1.0,
        1.0, -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
        1.0, 1.0, -1.0, -1.0, -1.0, -1.0,
        1.0, -1.0, -1.0,
        1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
        1.0, -1.0, -1.0,
        1.0, 1.0, -1.0,
        1.0, 1.0, 1.0,
        1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0
      ], [
        0, 1, 2, 0, 2, 3,
        4, 5, 6, 4, 6, 7,
        8, 9, 10, 8, 10, 11,
        12, 13, 14, 12, 14, 15,
        16, 17, 18, 16, 18, 19,
        20, 21, 22, 20, 22, 23
      ], [
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, 1.0,
        0.0, 0.0, -1.0,
        0.0, 0.0, -1.0,
        0.0, 0.0, -1.0,
        0.0, 0.0, -1.0,
        0.0, 1.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, -1.0, 0.0,
        0.0, -1.0, 0.0,
        0.0, -1.0, 0.0,
        0.0, -1.0, 0.0,
        1.0, 0.0, 0.0,
        1.0, 0.0, 0.0,
        1.0, 0.0, 0.0,
        1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0
      ]);
    };
  };
};

const getBuffers = (gl, clas) => {
  if (typeof clas != `function`) {
    console.error(`Need "function" type, got: "${typeof clas}"`);
    return;
  };
  const classy = new clas();
  var positions = classy.positions,
    index = classy.index,
    normals = classy.normals;
  if (positions != undefined && positions != null && index != undefined && index != null && normals != undefined && normals != null) {
    const positionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
    const normalBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);
    const indexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(index), gl.STATIC_DRAW);
    return {
      'position': positionBuffer,
      'index': indexBuffer,
      'normal': normalBuffer
    }
  } else {
    console.error(`Need any input type, got: "${typeof positions}", "${typeof index}", "${typeof normals}"`);
  };
  return;
};
// "draw.js"
var doDraw,
  draw,
  drawRad;
(() => {
  const DTR = Math.PI / 180.0,
    RTD = 180.0 / Math.PI;
  var draws = [];
  doDraw = (gl, aVertexPosition, aVertexNormal, uProjectionMatrix, uModelViewMatrix, uNormalMatrix, uTransform, uRotationX, uRotationY, uRotationZ, projectionMatrix, modelViewMatrix) => {
    draws.forEach((e) => {
      const normalMatrix = mat4.create();
      mat4.invert(normalMatrix, normalMatrix);
      mat4.transpose(normalMatrix, normalMatrix);
      gl.bindBuffer(gl.ARRAY_BUFFER, e[`buffs`][`position`]);
      gl.vertexAttribPointer(aVertexPosition, 3, gl.FLOAT, false, 0, 0);
      gl.enableVertexAttribArray(aVertexPosition);
      gl.bindBuffer(gl.ARRAY_BUFFER, e[`buffs`][`normal`]);
      gl.vertexAttribPointer(aVertexNormal, 3, gl.FLOAT, false, 0, 0);
      gl.enableVertexAttribArray(aVertexNormal);
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, e[`buffs`][`index`]);
      gl.uniformMatrix4fv(uProjectionMatrix, false, projectionMatrix);
      gl.uniformMatrix4fv(uModelViewMatrix, false, modelViewMatrix);
      gl.uniformMatrix4fv(uNormalMatrix, false, normalMatrix);
      gl.uniform3fv(uTransform, e[`transform`]);
      gl.uniform2fv(uRotationX, e[`rotateX`]);
      gl.uniform2fv(uRotationY, e[`rotateY`]);
      gl.uniform2fv(uRotationZ, e[`rotateZ`]);
      gl.drawElements(gl.TRIANGLES, e[`count`], gl.UNSIGNED_SHORT, 0); // LINE_LOOP, TRIANGLES
      return;
    });
    draws = [];
    return;
  };
  draw = (buffs, vertexCount, x, y, z, rx, ry, rz) => {
    const rxr = rx * DTR,
      ryr = ry * DTR,
      rzr = rz * DTR;
    draws.push({
      'buffs': buffs,
      'transform': [
        x,
        y,
        z
      ],
      'rotateX': [
        Math.sin(rxr),
        Math.cos(rxr)
      ],
      'rotateY': [
        Math.sin(ryr),
        Math.cos(ryr)
      ],
      'rotateZ': [
        Math.sin(rzr),
        Math.cos(rzr)
      ],
      'rx': rxr,
      'ry': ryr,
      'rz': rzr,
      'count': vertexCount
    });
    return;
  };
  drawRad = (buffs, vertexCount, x, y, z, rx, ry, rz) => {
    draws.push({
      'buffs': buffs,
      'transform': [
        x,
        y,
        z
      ],
      'rotateX': [
        Math.sin(rx),
        Math.cos(rx)
      ],
      'rotateY': [
        Math.sin(ry),
        Math.cos(ry)
      ],
      'rotateZ': [
        Math.sin(rz),
        Math.cos(rz)
      ],
      'rx': rx,
      'ry': ry,
      'rz': rz,
      'count': vertexCount
    });
    return;
  };
  return;
})();
// "script.js"
(() => {
  const DTR = Math.PI / 180.0,
    RTD = 180.0 / Math.PI;
  var gl,
    ctx,
    canvasgl,
    canvasctx,
    width = 0,
    height = 0,
    cubeBuffs,
    shaderProgram,
    vertexShader,
    fragmentShader,
    aVertexPosition,
    aVertexNormal,
    uProjectionMatrix,
    uModelViewMatrix,
    uNormalMatrix,
    uTransform,
    uRotationX,
    uRotationY,
    uRotationZ,
    aProjectionMatrix,
    aModelViewMatrix,
    projectionMatrix,
    modelViewMatrix,
    cx = 0.0,
    cy = 0.0,
    cz = 0.0,
    crx = 0.0,
    cry = 0.0,
    crz = 0.0;
  var cubeTime = 0.0;
  var updates = [],
    updateTime = 0,
    fpsupdate = 0.0,
    fpsupdatemin = 0.0,
    fpsupdatemax = 0.0;
  const loop = (deltaTime) => {
    cubeTime += deltaTime * 90;
    updateTime += deltaTime;
    updates.push(deltaTime);
    if (updates.length > 60) {
      var n = updates.shift();
    };
    var l = updates.length,
      ftime = 0.0;
    var max = 0.0,
      min = 1000.0;
    updates.forEach((e) => {
      ftime += e;
      if (min > e) {
        min = e;
      };
      if (max < e) {
        max = e;
      };
      return;
    });
    fpsupdatemin = min;
    fpsupdatemax = max;
    fpsupdate = ftime / l;
    ctx.fillStyle = `#fff`;
    ctx.font = `12px serif`;
    var txt0 = ` 1 / deltaTime: [ FPS: ${(1 / deltaTime).toFixed(1)} ]`,
      txt1 = ` Average / deltaTime: [ FPS: ${(1 / fpsupdate).toFixed(1)} ]`,
      txt2 = ` Maximum  / deltaTime: [ FPS: ${(1 / fpsupdatemin).toFixed(1)} ]`,
      txt3 = ` Minimum / deltaTime: [ FPS: ${(1 / fpsupdatemax).toFixed(1)} ]`;
    var metrics0 = ctx.measureText(` FPS:`),
      metrics1 = ctx.measureText(txt0),
      metrics2 = ctx.measureText(txt1),
      metrics3 = ctx.measureText(txt2),
      metrics4 = ctx.measureText(txt3);
    var hmet0 = metrics0.actualBoundingBoxAscent + metrics0.actualBoundingBoxDescent + 2,
      hmet1 = metrics1.actualBoundingBoxAscent + metrics1.actualBoundingBoxDescent + 2,
      hmet2 = metrics2.actualBoundingBoxAscent + metrics2.actualBoundingBoxDescent + 2,
      hmet3 = metrics3.actualBoundingBoxAscent + metrics3.actualBoundingBoxDescent + 2,
      hmet4 = metrics4.actualBoundingBoxAscent + metrics4.actualBoundingBoxDescent + 2;
    ctx.fillText(` FPS:`, 0, hmet0);
    ctx.fillText(txt0, 0, hmet0 + hmet1);
    ctx.fillText(txt1, 0, hmet0 + hmet1 + hmet2);
    ctx.fillText(txt2, 0, hmet0 + hmet1 + hmet2 + hmet3);
    ctx.fillText(txt3, 0, hmet0 + hmet1 + hmet2 + hmet3 + hmet4);
    draw(cubeBuffs, 36, 0.0, 0.0, 0.0, cubeTime * 0.3, cubeTime * 0.7, cubeTime);
    return;
  };
  var l,
    then = 0;
  l = (now) => {
    requestAnimationFrame(l);
    now *= 0.001;
    const dT = now - then;
    then = now;
    mat4.copy(projectionMatrix, aProjectionMatrix);
    mat4.copy(modelViewMatrix, aModelViewMatrix);
    mat4.translate(modelViewMatrix, modelViewMatrix, [
      cx, -cy,
      cz
    ]);
    mat4.rotate(projectionMatrix, projectionMatrix, (-crx) * DTR, [
      1,
      0,
      0
    ]);
    mat4.rotate(projectionMatrix, projectionMatrix, cry * DTR, [
      0,
      1,
      0
    ]);
    mat4.rotate(projectionMatrix, projectionMatrix, crz * DTR, [
      0,
      0,
      1
    ]);
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clearDepth(1.0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    ctx.clearRect(0, 0, width, height);
    loop(dT);
    doDraw(gl, aVertexPosition, aVertexNormal, uProjectionMatrix, uModelViewMatrix, uNormalMatrix, uTransform, uRotationX, uRotationY, uRotationZ, projectionMatrix, modelViewMatrix);
    return;
  };
  const init = () => {
    cubeBuffs = getBuffers(gl, Object.Cube);
    cx = -6.0;
    cy = 6.0;
    cz = -6.0;
    crx = -45.0;
    cry = -45.0;
    return false;
  };
  const resize = () => {
    height = document.body.clientHeight;
    width = document.body.clientWidth;
    canvasctx.style.height = `${height}px`;
    canvasctx.style.width = `${width}px`;
    canvasctx.height = height;
    canvasctx.width = width;
    canvasgl.style.height = `${height}px`;
    canvasgl.style.width = `${width}px`;
    canvasgl.height = height;
    canvasgl.width = width;
    mat4.perspective(aProjectionMatrix, (45.0 * Math.PI) / 180.0, width / height, 0.0, 1000.0);
    gl.viewport(0, 0, width, height);
    return;
  };
  const ini = () => {
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    const shaders = initShaders(gl);
    vertexShader = shaders[`vertex`];
    fragmentShader = shaders[`fragment`];
    shaderProgram = gl.createProgram();
    gl.attachShader(shaderProgram, vertexShader);
    gl.attachShader(shaderProgram, fragmentShader);
    gl.linkProgram(shaderProgram);
    if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
      alert(`Unable to initialize the shader program: ${gl.getProgramInfoLog(shaderProgram)}`);
      return true;
    };
    gl.useProgram(shaderProgram);
    aVertexPosition = gl.getAttribLocation(shaderProgram, `aVertexPosition`);
    aVertexNormal = gl.getAttribLocation(shaderProgram, `aVertexNormal`);
    uProjectionMatrix = gl.getUniformLocation(shaderProgram, `uProjectionMatrix`);
    uModelViewMatrix = gl.getUniformLocation(shaderProgram, `uModelViewMatrix`);
    uNormalMatrix = gl.getUniformLocation(shaderProgram, `uNormalMatrix`);
    uTransform = gl.getUniformLocation(shaderProgram, `uTransform`);
    uRotationX = gl.getUniformLocation(shaderProgram, `uRotationX`);
    uRotationY = gl.getUniformLocation(shaderProgram, `uRotationY`);
    uRotationZ = gl.getUniformLocation(shaderProgram, `uRotationZ`);
    gl.disable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
    gl.enable(gl.CULL_FACE);
    gl.cullFace(gl.BACK);
    gl.enable(gl.DEPTH_TEST);
    gl.depthFunc(gl.LEQUAL);
    return init();
  };
  window.addEventListener(`load`, () => {
    canvasctx = document.createElement(`canvas`);
    canvasgl = document.createElement(`canvas`);
    canvasctx.style.imageRendering = `pixelated`;
    canvasctx.style.position = `fixed`;
    canvasctx.style.zIndex = `999`;
    canvasctx.style.left = `0px`;
    canvasctx.style.top = `0px`;
    canvasgl.style.position = `fixed`;
    canvasgl.style.zIndex = `989`;
    canvasgl.style.left = `0px`;
    canvasgl.style.top = `0px`;
    document.body.appendChild(canvasctx);
    document.body.appendChild(canvasgl);
    projectionMatrix = mat4.create();
    modelViewMatrix = mat4.create();
    aProjectionMatrix = mat4.create();
    aModelViewMatrix = mat4.create();
    ctx = canvasctx.getContext(`2d`);
    gl = canvasgl.getContext(`webgl2`, {
      'powerPreference': `high-performance`
    });
    if (ctx == null || typeof ctx == `undefined`) {
      console.error(`Unable to get 2D context`);
      alert(`Unable to get 2D context`);
      return;
    };
    if (gl == null || typeof gl == `undefined`) {
      console.error(`Unable to get WebGL2 context`);
      alert(`Unable to get WebGL2 context`);
      return;
    };
    resize();
    var cb;
    window.addEventListener(`resize`, () => {
      clearTimeout(cb);
      cb = setTimeout(resize, 150);
      return;
    });
    if (ini() == false) {
      then = performance.now() * 0.001;
      requestAnimationFrame(l);
    };
    return;
  });
  return;
})();

* {
  padding: 0px;
  margin: 0px;
}

html,
body {
  height: 100%;
  width: 100%;
}


来源: stackexchange

问:
UISplitViewController.presentsWithGesture doesn't work when style != Unspecified
I tried to update the UISplitViewController in my old iOS project to use the newer column-based API, but noticed that when setting the Style to Double Column in IB from the currently selected Unspecified (Discouraged), the swipe gesture doesn't show and hide the master view controller anymore, even if the option Presents Primary With Gesture is selected. This also happens with a fresh project where I dragged the standard split view controller into the IB canvas as the initial view controller. Is this expected or am I missing something?

ContentLicense: CC BY-SA 4.0


问:
For loop processes one row and stop iterating through the csv file for WhatsApp/Facebook API
Hello Team Below is my code for sending WhatsApp chat messages using a CSV file it works for some time, then suddenly it stops to iterate through all and it stops at only row one or hangs to iterate through the CSV am not sure if it's the Facebook endpoint  with an issue or limit

```<code>import csv
import http.client
import json

# Open the CSV file and read it line by line
with open('chat_messages.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    # Skip the header row
    next(reader)
    for row in reader:
        chat_number = int(row[0])
        chat_message = row[1]
        chat_channel = row[2]
        chat_response = row[3]
        chat_expiry_method = row[4]
        chat_expiry_date = row[5]

        # Send Chat

        conn = http.client.HTTPSConnection("graph.facebook.com")
        payload = json.dumps({
            "messaging_product": "whatsapp",
            "to": chat_number,
            "type": "template",
            "template": {
                "name": "hello_world",
                "language": {
                    "code": "en_US"
                }
            }
        })
        headers = {
            'Authorization': 'Bearer xxxxxyyyyyyy',
            'Content-Type': 'application/json'
        }
        conn.request("POST", "/v15.0/3335355343232/messages", payload, headers)
        res = conn.getresponse()
        data = res.read()
        print(data.decode("utf-8"))
</code>```

Here is my CSV

chat_number,chat_message ,channel,response ,expiry_method,expiry_date

25677xxxxxxx,Your Message 2,whatsapp,1,Manual,08/02/2022

25471yyyyyyy,Your Message 3,whatsapp,1,Manual,06/02/2022

25575zzzzzzz,Your Message 1 ,whatsapp,1,Manual,09/02/2022

at some point when I stoped printing the repones from fakebook endpoint it worked  for all lines int he CSV but after multiple executions it failed

I comment out this code

```<code>#res = conn.getresponse()
#data = res.read()
#print(data.decode("utf-8"))
</code>```

after some time it start processing only one line and stops

Body:
Hello Team Below is my code for sending WhatsApp chat messages using a CSV file it works for some time, then suddenly it stops to iterate through all and it stops at only row one or hangs to iterate through the CSV am not sure if it's the Facebook endpoint  with an issue or limit

import csv
import http.client
import json

# Open the CSV file and read it line by line
with open('chat_messages.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    # Skip the header row
    next(reader)
    for row in reader:
        chat_number = int(row[0])
        chat_message = row[1]
        chat_channel = row[2]
        chat_response = row[3]
        chat_expiry_method = row[4]
        chat_expiry_date = row[5]

        # Send Chat

        conn = http.client.HTTPSConnection("graph.facebook.com")
        payload = json.dumps({
            "messaging_product": "whatsapp",
            "to": chat_number,
            "type": "template",
            "template": {
                "name": "hello_world",
                "language": {
                    "code": "en_US"
                }
            }
        })
        headers = {
            'Authorization': 'Bearer xxxxxyyyyyyy',
            'Content-Type': 'application/json'
        }
        conn.request("POST", "/v15.0/3335355343232/messages", payload, headers)
        res = conn.getresponse()
        data = res.read()
        print(data.decode("utf-8"))

Here is my CSV

chat_number,chat_message ,channel,response ,expiry_method,expiry_date

25677xxxxxxx,Your Message 2,whatsapp,1,Manual,08/02/2022

25471yyyyyyy,Your Message 3,whatsapp,1,Manual,06/02/2022

25575zzzzzzz,Your Message 1 ,whatsapp,1,Manual,09/02/2022

at some point when I stoped printing the repones from fakebook endpoint it worked  for all lines int he CSV but after multiple executions it failed

I comment out this code

#res = conn.getresponse()
#data = res.read()
#print(data.decode("utf-8"))

after some time it start processing only one line and stops


问:
change the architecture of a nodejs express and mongodb webapp?
hello i am working on a existing software  that runs on a local server i would like to change the architecture of that software to make it multi-tenant so that it selects the correct database according to the subdomain .
this software needs to be installed during that operation it creates the collections and documents according to the models  .
what i did is created a new route (/registernewtenant) that has a form with the client credentials and subdomain, this data gets posted to a methode index that creats the database giving it a name of tenant-"subdoùain" i tryed to run the install methode to get collections and document in the new database but i am having trouble .

this is the controller file :

```<code>const dbName  ="tenant-"+req.body.subd;

  nconf.set('Tenantmongo:tdatabase', dbName);
  nconf.save();
const url = 'mongodb://localhost:27017';
mongoClient.connect(url).then((client) => {

    // database name
    const db1 = client.db(dbName);
    db1.createCollection("test");
    // db1.addUser("admin","admin",{ roles: [ { role: "dbAdmin", db: dbName } ]})
  })
const mongoConnection={
    'mongo-server':'mongodb://localhost',
    'mongo-database':dbName,
    'mongo-port':'27017',
    'mongo-username':'admin',
    'mongo-password':'admin',
}
const adminAccount={
    'admin-username':req.body.username,
    'admin-password':req.body.pass,
    'admin-email':req.body.email,
    'admin-fullname':req.body.name,
}
const elasticConnection={
    'elasticHost':'',
    'elasticPort':'',

}
const data ={
    mongo: mongoConnection,
    account: adminAccount,
    elastic: elasticConnection
}

const roleSchema = require('../models/role')
const roleOrderSchema = require('../models/roleorder')
const UserSchema = require('../models/user')
const GroupSchema = require('../models/group')
const Counters = require('../models/counters')
const TicketTypeSchema = require('../models/tickettype')
const SettingsSchema = require('../models/setting')

// Mongo
const host = data.mongo["mongo-server"]
const port = data.mongo["mongo-port"]
const database = data.mongo["mongo-database"]
const username = data.mongo["mongo-username"]
const password = data.mongo["mongo-password"]

// ElasticSearch
let eEnabled = data['elastic[enable]']
if (typeof eEnabled === 'string') eEnabled = eEnabled.toLowerCase() === 'true'

const eHost = data['elastic[host]']
const ePort = data['elastic[port]']

// Account
const user = {
  username: data.account['admin-username'],
  password: data.account['admin-password'],
  passconfirm: data.account['admin-password'],
  email: data.account['admin-email'],
  fullname: data.account['admin-fullname']
}
console.log(user)

const dbPassword = encodeURIComponent(password)
let conuri = 'mongodb://' + username + ':' + dbPassword + '@' + host + ':' + port + '/' + database
console.log(conuri)
if (port === '---') conuri = 'mongodb+srv://' + username + ':' + dbPassword + '@' + host + '/' + database

async.waterfall(
  [function (next) {
        db.init(function (err) { // the error accurs here because of the methode init i can't call             .connect() twice to run the migrations
          return next(err)
        }, conuri)
      },
      function (next) {
        const s = new SettingsSchema({
          name: 'gen:version',
          value: require('../../package.json').version
        })

        return s.save(function (err) {
          return next(err)
        })
      },
      function (next) {
      // if (!eEnabled) return next()
      async.parallel(
        [
          function (done) {
            SettingsSchema.create(
              {
                name: 'es:enable',
                value: typeof eEnabled === 'undefined' ? false : eEnabled
              },
              done
            )
          },
          function (done) {
            if (!eHost) return done()
            SettingsSchema.create(
              {
                name: 'es:host',
                value: eHost
              },
              done
            )
          },
          function (done) {
            if (!ePort) return done()
            SettingsSchema.create(
              {
                name: 'es:port',
                value: ePort
              },
              done
            )
          }
        ],
        function (err) {
          return next(err)
        }
      )
    },
    function (next) {
      const Counter = new Counters({
        _id: 'tickets',
        next: 1001
      })

      Counter.save(function (err) {
        return next(err)
      })
    },
    function (next) {
      const Counter = new Counters({
        _id: 'reports',
        next: 1001
      })

      Counter.save(function (err) {
        return next(err)
      })
    },
    function (next) {
      const type = new TicketTypeSchema({
        name: 'Issue'
      })

      type.save(function (err) {
        return next(err)
      })
    },
    function (next) {
      const type = new TicketTypeSchema({
        name: 'Task'
      })

      type.save(function (err) {
        return next(err)
      })
    },
    function (next) {
      const defaults = require('../settings/defaults')
      const roleResults = {}
      async.parallel(
        [
          function (done) {
            roleSchema.create(
              {
                name: 'Admin',
                description: 'Default role for admins',
                grants: defaults.roleDefaults.adminGrants
              },
              function (err, role) {
                if (err) return done(err)
                roleResults.adminRole = role
                return done()
              }
            )
          },
          function (done) {
            roleSchema.create(
              {
                name: 'Support',
                description: 'Default role for agents',
                grants: defaults.roleDefaults.supportGrants
              },
              function (err, role) {
                if (err) return done(err)
                roleResults.supportRole = role
                return done()
              }
            )
          },
          function (done) {
            roleSchema.create(
              {
                name: 'User',
                description: 'Default role for users',
                grants: defaults.roleDefaults.userGrants
              },
              function (err, role) {
                if (err) return done(err)
                roleResults.userRole = role
                return done()
              }
            )
          }
        ],
        function (err) {
          return next(err, roleResults)
        }
      )
    },
    function (roleResults, next) {
      const TeamSchema = require('../models/team')
      TeamSchema.create(
        {
          name: 'Support (Default)',
          members: []
        },
        function (err, team) {
          return next(err, team, roleResults)
        }
      )
    },
    function (defaultTeam, roleResults, next) {
      UserSchema.getUserByUsername(user.username, function (err, admin) {
        if (err) {
          winston.error('Database Error: ' + err.message)
          return next('Database Error: ' + err.message)
        }

        if (!_.isNull(admin) && !_.isUndefined(admin) && !_.isEmpty(admin)) {
          return next('Username: ' + user.username + ' already exists.')
        }

        if (user.password !== user.passconfirm) {
          return next('Passwords do not match!')
        }

        const chance = new Chance()
        const adminUser = new UserSchema({
          username: user.username,
          password: user.password,
          fullname: user.fullname,
          email: user.email,
          role: roleResults.adminRole._id,
          title: 'Administrator',
          accessToken: chance.hash()
        })

        adminUser.save(function (err, savedUser) {
          if (err) {
            winston.error('Database Error: ' + err.message)
            return next('Database Error: ' + err.message)
          }

          defaultTeam.addMember(savedUser._id, function (err, success) {
            if (err) {
              winston.error('Database Error: ' + err.message)
              return next('Database Error: ' + err.message)
            }

            if (!success) {
              return next('Unable to add user to Administrator group!')
            }

            defaultTeam.save(function (err) {
              if (err) {
                winston.error('Database Error: ' + err.message)
                return next('Database Error: ' + err.message)
              }

              return next(null, defaultTeam)
            })
          })
        })
      })
    },
    function (defaultTeam, next) {
      const DepartmentSchema = require('../models/department')
      DepartmentSchema.create(
        {
          name: 'Support - All Groups (Default)',
          teams: [defaultTeam._id],
          allGroups: true,
          groups: []
        },
        function (err) {
          return next(err)
        }
      )
    },
    function (next) {
      if (!process.env.TRUDESK_DOCKER) return next()
      const S = require('../models/setting')
      const installed = new S({
        name: 'installed',
        value: true
      })

      installed.save(function (err) {
        if (err) {
          winston.error('DB Error: ' + err.message)
          return next('DB Error: ' + err.message)
        }

        return next()
      })
    },
    function (next) {
      if (process.env.TRUDESK_DOCKER) return next()
      // Write Configfile
      const fs = require('fs')
      const configFile = path.join(__dirname, '../../config.yml')
      const chance = new Chance()
      const YAML = require('yaml')

      const conf = {
        tmongo : {
          host: host,
          port: port,
          username: username,
          password: password,
          database: database,
          shard: port === '---'
        },
        tokens: {
          secret: chance.hash() + chance.md5(),
          expires: 900 // 15min
        }
      }

      fs.writeFile(configFile, YAML.stringify(conf), function (err) {
        if (err) {
          winston.error('FS Error: ' + err.message)
          return next('FS Error: ' + err.message)
        }

        return next(null)
      })
    }
  ],
  function (err) {
    if (err) {
      return res.status(400).json({ success: false, error: err })
    }

    res.json({ success: true })
  }
)``
</code>```

this the db.init methode (this connects to the tenant database successfully):
`

```<code> module.exports.init = async function (callback, connectionString, opts) {
if (connectionString) CONNECTION_URI = connectionString
if (opts) options = opts options.dbName = mongoConnectionUri.database global.CONNECTION_URI = CONNECTION_URI
mongoose.Promise = global.Promise
mongoose
.connect(CONNECTION_URI, options)
.then(function () {
  if (!process.env.FORK) {
    winston.info('Connected  to MongoDB')
  }

  db.connection = mongoose.connection
  mongoose.connection.db.admin().command({ buildInfo: 1 }, function (err, info) {
    if (err) winston.warn(err.message)
    db.version = info.version
    return callback(null, db)
  })
})
.catch(function (e) {
  winston.error('Oh no, something went wrong with DB! - ' + e.message)
  db.connection = null

  return callback(e, null)
})

module.exports.db = db
module.exports.connectionuri = CONNECTION_URI
</code>```

`

and getting this error :

{"success":false,"error":{"index":0,"code":11000,"keyPattern":{"name":1},"keyValue": {"name":"gen:version"}}}

this error indicates that an install has already been done even if i did mention the new database.
here is an example model:
`

```<code>var mongoose = require('mongoose')
var noteSchema = mongoose.Schema({
owner: { type: mongoose.Schema.Types.ObjectId, ref: 'accounts' },
date: { type: Date, required: true },
note: { type: String, required: true },
deleted: { type: Boolean, default: false, required: true }
})

module.exports = noteSchema
</code>```

`

so my question is there a way to fill database with collections and documents based on models ?

i tried using axios to send a post request to the install methode of the software but it didn't work
so i took the code from the method and put it in the controller above

i tried creating the collections and docs  manulally and it got created .

thank you !

Body:
hello i am working on a existing software  that runs on a local server i would like to change the architecture of that software to make it multi-tenant so that it selects the correct database according to the subdomain .
this software needs to be installed during that operation it creates the collections and documents according to the models  .
what i did is created a new route (/registernewtenant) that has a form with the client credentials and subdomain, this data gets posted to a methode index that creats the database giving it a name of tenant-"subdoùain" i tryed to run the install methode to get collections and document in the new database but i am having trouble .

this is the controller file :

const dbName  ="tenant-"+req.body.subd;

  nconf.set('Tenantmongo:tdatabase', dbName);
  nconf.save();
const url = 'mongodb://localhost:27017';
mongoClient.connect(url).then((client) => {

    // database name
    const db1 = client.db(dbName);
    db1.createCollection("test");
    // db1.addUser("admin","admin",{ roles: [ { role: "dbAdmin", db: dbName } ]})
  })
const mongoConnection={
    'mongo-server':'mongodb://localhost',
    'mongo-database':dbName,
    'mongo-port':'27017',
    'mongo-username':'admin',
    'mongo-password':'admin',
}
const adminAccount={
    'admin-username':req.body.username,
    'admin-password':req.body.pass,
    'admin-email':req.body.email,
    'admin-fullname':req.body.name,
}
const elasticConnection={
    'elasticHost':'',
    'elasticPort':'',

}
const data ={
    mongo: mongoConnection,
    account: adminAccount,
    elastic: elasticConnection
}

const roleSchema = require('../models/role')
const roleOrderSchema = require('../models/roleorder')
const UserSchema = require('../models/user')
const GroupSchema = require('../models/group')
const Counters = require('../models/counters')
const TicketTypeSchema = require('../models/tickettype')
const SettingsSchema = require('../models/setting')

// Mongo
const host = data.mongo["mongo-server"]
const port = data.mongo["mongo-port"]
const database = data.mongo["mongo-database"]
const username = data.mongo["mongo-username"]
const password = data.mongo["mongo-password"]

// ElasticSearch
let eEnabled = data['elastic[enable]']
if (typeof eEnabled === 'string') eEnabled = eEnabled.toLowerCase() === 'true'

const eHost = data['elastic[host]']
const ePort = data['elastic[port]']

// Account
const user = {
  username: data.account['admin-username'],
  password: data.account['admin-password'],
  passconfirm: data.account['admin-password'],
  email: data.account['admin-email'],
  fullname: data.account['admin-fullname']
}
console.log(user)

const dbPassword = encodeURIComponent(password)
let conuri = 'mongodb://' + username + ':' + dbPassword + '@' + host + ':' + port + '/' + database
console.log(conuri)
if (port === '---') conuri = 'mongodb+srv://' + username + ':' + dbPassword + '@' + host + '/' + database

async.waterfall(
  [function (next) {
        db.init(function (err) { // the error accurs here because of the methode init i can't call             .connect() twice to run the migrations
          return next(err)
        }, conuri)
      },
      function (next) {
        const s = new SettingsSchema({
          name: 'gen:version',
          value: require('../../package.json').version
        })

        return s.save(function (err) {
          return next(err)
        })
      },
      function (next) {
      // if (!eEnabled) return next()
      async.parallel(
        [
          function (done) {
            SettingsSchema.create(
              {
                name: 'es:enable',
                value: typeof eEnabled === 'undefined' ? false : eEnabled
              },
              done
            )
          },
          function (done) {
            if (!eHost) return done()
            SettingsSchema.create(
              {
                name: 'es:host',
                value: eHost
              },
              done
            )
          },
          function (done) {
            if (!ePort) return done()
            SettingsSchema.create(
              {
                name: 'es:port',
                value: ePort
              },
              done
            )
          }
        ],
        function (err) {
          return next(err)
        }
      )
    },
    function (next) {
      const Counter = new Counters({
        _id: 'tickets',
        next: 1001
      })

      Counter.save(function (err) {
        return next(err)
      })
    },
    function (next) {
      const Counter = new Counters({
        _id: 'reports',
        next: 1001
      })

      Counter.save(function (err) {
        return next(err)
      })
    },
    function (next) {
      const type = new TicketTypeSchema({
        name: 'Issue'
      })

      type.save(function (err) {
        return next(err)
      })
    },
    function (next) {
      const type = new TicketTypeSchema({
        name: 'Task'
      })

      type.save(function (err) {
        return next(err)
      })
    },
    function (next) {
      const defaults = require('../settings/defaults')
      const roleResults = {}
      async.parallel(
        [
          function (done) {
            roleSchema.create(
              {
                name: 'Admin',
                description: 'Default role for admins',
                grants: defaults.roleDefaults.adminGrants
              },
              function (err, role) {
                if (err) return done(err)
                roleResults.adminRole = role
                return done()
              }
            )
          },
          function (done) {
            roleSchema.create(
              {
                name: 'Support',
                description: 'Default role for agents',
                grants: defaults.roleDefaults.supportGrants
              },
              function (err, role) {
                if (err) return done(err)
                roleResults.supportRole = role
                return done()
              }
            )
          },
          function (done) {
            roleSchema.create(
              {
                name: 'User',
                description: 'Default role for users',
                grants: defaults.roleDefaults.userGrants
              },
              function (err, role) {
                if (err) return done(err)
                roleResults.userRole = role
                return done()
              }
            )
          }
        ],
        function (err) {
          return next(err, roleResults)
        }
      )
    },
    function (roleResults, next) {
      const TeamSchema = require('../models/team')
      TeamSchema.create(
        {
          name: 'Support (Default)',
          members: []
        },
        function (err, team) {
          return next(err, team, roleResults)
        }
      )
    },
    function (defaultTeam, roleResults, next) {
      UserSchema.getUserByUsername(user.username, function (err, admin) {
        if (err) {
          winston.error('Database Error: ' + err.message)
          return next('Database Error: ' + err.message)
        }

        if (!_.isNull(admin) && !_.isUndefined(admin) && !_.isEmpty(admin)) {
          return next('Username: ' + user.username + ' already exists.')
        }

        if (user.password !== user.passconfirm) {
          return next('Passwords do not match!')
        }

        const chance = new Chance()
        const adminUser = new UserSchema({
          username: user.username,
          password: user.password,
          fullname: user.fullname,
          email: user.email,
          role: roleResults.adminRole._id,
          title: 'Administrator',
          accessToken: chance.hash()
        })

        adminUser.save(function (err, savedUser) {
          if (err) {
            winston.error('Database Error: ' + err.message)
            return next('Database Error: ' + err.message)
          }

          defaultTeam.addMember(savedUser._id, function (err, success) {
            if (err) {
              winston.error('Database Error: ' + err.message)
              return next('Database Error: ' + err.message)
            }

            if (!success) {
              return next('Unable to add user to Administrator group!')
            }

            defaultTeam.save(function (err) {
              if (err) {
                winston.error('Database Error: ' + err.message)
                return next('Database Error: ' + err.message)
              }

              return next(null, defaultTeam)
            })
          })
        })
      })
    },
    function (defaultTeam, next) {
      const DepartmentSchema = require('../models/department')
      DepartmentSchema.create(
        {
          name: 'Support - All Groups (Default)',
          teams: [defaultTeam._id],
          allGroups: true,
          groups: []
        },
        function (err) {
          return next(err)
        }
      )
    },
    function (next) {
      if (!process.env.TRUDESK_DOCKER) return next()
      const S = require('../models/setting')
      const installed = new S({
        name: 'installed',
        value: true
      })

      installed.save(function (err) {
        if (err) {
          winston.error('DB Error: ' + err.message)
          return next('DB Error: ' + err.message)
        }

        return next()
      })
    },
    function (next) {
      if (process.env.TRUDESK_DOCKER) return next()
      // Write Configfile
      const fs = require('fs')
      const configFile = path.join(__dirname, '../../config.yml')
      const chance = new Chance()
      const YAML = require('yaml')

      const conf = {
        tmongo : {
          host: host,
          port: port,
          username: username,
          password: password,
          database: database,
          shard: port === '---'
        },
        tokens: {
          secret: chance.hash() + chance.md5(),
          expires: 900 // 15min
        }
      }

      fs.writeFile(configFile, YAML.stringify(conf), function (err) {
        if (err) {
          winston.error('FS Error: ' + err.message)
          return next('FS Error: ' + err.message)
        }

        return next(null)
      })
    }
  ],
  function (err) {
    if (err) {
      return res.status(400).json({ success: false, error: err })
    }

    res.json({ success: true })
  }
)``

this the db.init methode (this connects to the tenant database successfully):
`

 module.exports.init = async function (callback, connectionString, opts) {
if (connectionString) CONNECTION_URI = connectionString
if (opts) options = opts options.dbName = mongoConnectionUri.database global.CONNECTION_URI = CONNECTION_URI
mongoose.Promise = global.Promise
mongoose
.connect(CONNECTION_URI, options)
.then(function () {
  if (!process.env.FORK) {
    winston.info('Connected  to MongoDB')
  }

  db.connection = mongoose.connection
  mongoose.connection.db.admin().command({ buildInfo: 1 }, function (err, info) {
    if (err) winston.warn(err.message)
    db.version = info.version
    return callback(null, db)
  })
})
.catch(function (e) {
  winston.error('Oh no, something went wrong with DB! - ' + e.message)
  db.connection = null

  return callback(e, null)
})

module.exports.db = db
module.exports.connectionuri = CONNECTION_URI

`

and getting this error :

{"success":false,"error":{"index":0,"code":11000,"keyPattern":{"name":1},"keyValue": {"name":"gen:version"}}}

this error indicates that an install has already been done even if i did mention the new database.
here is an example model:
`

var mongoose = require('mongoose')
var noteSchema = mongoose.Schema({
owner: { type: mongoose.Schema.Types.ObjectId, ref: 'accounts' },
date: { type: Date, required: true },
note: { type: String, required: true },
deleted: { type: Boolean, default: false, required: true }
})

module.exports = noteSchema

`

so my question is there a way to fill database with collections and documents based on models ?

i tried using axios to send a post request to the install methode of the software but it didn't work
so i took the code from the method and put it in the controller above

i tried creating the collections and docs  manulally and it got created .

thank you !


问:
Update value printed to console
I'm attempting to update a value printed to the console in order to implement a simple REPL that supports predictive commands.

So after "->" is printed to the screen using

```<code>Console.print("->")
</code>```

and the user enters "d" followed by the "tab" key then then the existing output "->" should be converted to "-> dir"

I read the input using :

```<code>val input = scala.io.StdIn.readLine()
</code>```

I have yet to implement the listener to determine when the tab key is pressed. At this point I'm attempting to prove if command line output can be updated in place.

Title: Update value printed to console

Body:
I'm attempting to update a value printed to the console in order to implement a simple REPL that supports predictive commands.

So after "->" is printed to the screen using

Console.print("->")

and the user enters "d" followed by the "tab" key then then the existing output "->" should be converted to "-> dir"

I read the input using :

val input = scala.io.StdIn.readLine()

I have yet to implement the listener to determine when the tab key is pressed. At this point I'm attempting to prove if command line output can be updated in place.


问:
electron-packager deploy and protect source files
I have deploy my electron app with "electron-packager", but i see that the electron-packager include always "resources" folder which has asar file and app folder with all sources file of my app... how I can deploy without including including "resources" folder so user can not see my codes?

I trid to deleted the "resources" folder, but my app not opening.. and I see some third party app used electron-packager but "resources" folder not included and it's work fine. How they did that please, any suggestion is welcome?

Here is code I have used:

```<code>npx electron-packager . electron-tutorial-app --overwrite --no-asar --platform=win32 --arch=x64
</code>```

Thanks.

Body:
I have deploy my electron app with "electron-packager", but i see that the electron-packager include always "resources" folder which has asar file and app folder with all sources file of my app... how I can deploy without including including "resources" folder so user can not see my codes?

I trid to deleted the "resources" folder, but my app not opening.. and I see some third party app used electron-packager but "resources" folder not included and it's work fine. How they did that please, any suggestion is welcome?

Here is code I have used:

npx electron-packager . electron-tutorial-app --overwrite --no-asar --platform=win32 --arch=x64

Thanks.


问:
Java - Unicode input in cmd.exe doesn't match from other languages (like Node)
While reading input from the console via cmd.exe using Java, I noticed that if I input a string with Chinese characters (你好), it would always return a 65 (Char code for ?) in place of the character. The characters display correctly inside my terminal.

I have also set the encoding for the InputStreamReader and in -Dfile.encoding to UTF-8 (also tried Windows-1252, and it returns the same results).  I used both Java 8 and 17.

Here is the code I used:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
        String in = reader.readLine();
        String chars = in.codePoints()
                .mapToObj(Integer::toString)
                .collect(Collectors.joining(","));
        System.out.println(chars);
    }
}
```
<p>When I tested with another language (Node.js), it returned the correct set of bytes for the characters I input (<code>228,189,160,229,165,189</code>).</p>
<p>Here is the code I used to test in Node.js:</p>
<pre class="lang-js prettyprint-override"><code>const readline = require("readline");
const rl = readline.createInterface(process.stdin);

rl.question("", (result) => console.log(new TextEncoder().encode(result).join(",")));
</code>```

How can I get the correct string from stdin?

Body:
While reading input from the console via cmd.exe using Java, I noticed that if I input a string with Chinese characters (你好), it would always return a 65 (Char code for ?) in place of the character. The characters display correctly inside my terminal.

I have also set the encoding for the InputStreamReader and in -Dfile.encoding to UTF-8 (also tried Windows-1252, and it returns the same results).  I used both Java 8 and 17.

Here is the code I used:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
        String in = reader.readLine();
        String chars = in.codePoints()
                .mapToObj(Integer::toString)
                .collect(Collectors.joining(","));
        System.out.println(chars);
    }
}

When I tested with another language (Node.js), it returned the correct set of bytes for the characters I input (228,189,160,229,165,189).

Here is the code I used to test in Node.js:

const readline = require("readline");
const rl = readline.createInterface(process.stdin);

rl.question("", (result) => console.log(new TextEncoder().encode(result).join(",")));

How can I get the correct string from stdin?


问:
Xamarin Essentials Web Authenticator & Open Browser
For reference:

https://learn.microsoft.com/en-us/xamarin/essentials/open-browser?context=xamarin%2Fandroid&tabs=android

https://learn.microsoft.com/en-us/xamarin/essentials/web-authenticator?context=xamarin%2Fandroid&tabs=android

I am using both of these features and everything works as expected when I was on an emulator that targeted android 11. It was working without adding the recommended configurations from the documentation above.

when the app is run on an emulator that targets android 13, neither of these features works anymore.  the browser just opens and never finished loading the page.  If the browser is closed the app will recognize a cancel method was called.

from the documentation, I have tried with and without the configurations and to no avail.

```<code><queries>
        <intent>
        <action android:name="android.support.customtabs.action.CustomTabsService" />
    </intent>
        <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="http"/>
  </intent>
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="https"/>
  </intent>
    </queries>
</code>```

any suggestions?

Body:
For reference:

https://learn.microsoft.com/en-us/xamarin/essentials/open-browser?context=xamarin%2Fandroid&tabs=android

https://learn.microsoft.com/en-us/xamarin/essentials/web-authenticator?context=xamarin%2Fandroid&tabs=android

I am using both of these features and everything works as expected when I was on an emulator that targeted android 11. It was working without adding the recommended configurations from the documentation above.

when the app is run on an emulator that targets android 13, neither of these features works anymore.  the browser just opens and never finished loading the page.  If the browser is closed the app will recognize a cancel method was called.

from the documentation, I have tried with and without the configurations and to no avail.

<queries>
        <intent>
        <action android:name="android.support.customtabs.action.CustomTabsService" />
    </intent>
        <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="http"/>
  </intent>
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="https"/>
  </intent>
    </queries>

any suggestions?


问:
Missing ALTER TABLE dependency using SMO DependencyWalker
I am using powershell SMO DependencyWalker and Scripter to find the all dependencies of a table in a SQL Server database and then generating scripts to CREATE and DROP the table and those dependencies. DependencyWalker is successfully finding most of the dependencies, but does not find certain stored procedures that I believe it should.

For example, given these table definitions:

```<code>CREATE TABLE MyTable(
   [UniqueID] [uniqueidentifier] NOT NULL
)

CREATE TABLE MyOtherTable(
   [UniqueID] [uniqueidentifier] NOT NULL
)

ALTER TABLE [dbo].[MyTable]
WITH CHECK ADD CONSTRAINT [FK_MyTable_MyOtherTable] FOREIGN KEY([UniqueID])
REFERENCES [dbo].[MyOtherTable] ([UniqueID])
</code>```

And the following stored procedures that reference the table:

```<code>CREATE PROCEDURE [dbo].[MyTableResumeConstraintChecking]
AS
    ALTER TABLE dbo.MyTable CHECK CONSTRAINT FK_MyTable_MyOtherTable
    RETURN
GO
CREATE PROCEDURE [dbo].[MyTableSuspendConstraintChecking]
AS
    ALTER TABLE dbo.MyTable NOCHECK CONSTRAINT FK_MyTable_MyOtherTable
    RETURN
GO
</code>```

I would expect that the following powershell script would find the stored procedures as dependencies:

```<code>$SmoServer = New-Object ('Microsoft.SqlServer.Management.SMO.Server') $server
$dbObject = $SmoServer.Databases["MyDatabase"]
$tables = $dbObject.Tables | where { !$_.IsSystemObject }
$urns = $tables | foreach { $_.Urn }

$walker = New-Object 'Microsoft.SqlServer.Management.SMO.DependencyWalker' $SmoServer
$tree = $walker.DiscoverDependencies($urns, $false)
$depCollection = $walker.WalkDependencies($tree)

$dependencies = $depCollection | foreach { $_.Urn }
</code>```

This will find all other stored procedures that use MyTable (ones with typical INSERT, UPDATE, etc. calls). However, it will NOT find these *ConstraintChecking procedures that reference the table only via ALTER TABLE.

It should be noted that SSMS does not recognize these procedures as a dependency of the table either (when using View Dependencies).

I have tried to use other mechanisms for finding dependencies such as sp_depends and sys.dm_sql_referenced_entities, but those behave the same as DependencyWalker in this situation.

Using SMO in powershell and given a table URN, how do I find the URN of dependencies such as this?

Body:
I am using powershell SMO DependencyWalker and Scripter to find the all dependencies of a table in a SQL Server database and then generating scripts to CREATE and DROP the table and those dependencies. DependencyWalker is successfully finding most of the dependencies, but does not find certain stored procedures that I believe it should.

For example, given these table definitions:

CREATE TABLE MyTable(
   [UniqueID] [uniqueidentifier] NOT NULL
)

CREATE TABLE MyOtherTable(
   [UniqueID] [uniqueidentifier] NOT NULL
)

ALTER TABLE [dbo].[MyTable]
WITH CHECK ADD CONSTRAINT [FK_MyTable_MyOtherTable] FOREIGN KEY([UniqueID])
REFERENCES [dbo].[MyOtherTable] ([UniqueID])

And the following stored procedures that reference the table:

CREATE PROCEDURE [dbo].[MyTableResumeConstraintChecking]
AS
    ALTER TABLE dbo.MyTable CHECK CONSTRAINT FK_MyTable_MyOtherTable
    RETURN
GO
CREATE PROCEDURE [dbo].[MyTableSuspendConstraintChecking]
AS
    ALTER TABLE dbo.MyTable NOCHECK CONSTRAINT FK_MyTable_MyOtherTable
    RETURN
GO

I would expect that the following powershell script would find the stored procedures as dependencies:

$SmoServer = New-Object ('Microsoft.SqlServer.Management.SMO.Server') $server
$dbObject = $SmoServer.Databases["MyDatabase"]
$tables = $dbObject.Tables | where { !$_.IsSystemObject }
$urns = $tables | foreach { $_.Urn }

$walker = New-Object 'Microsoft.SqlServer.Management.SMO.DependencyWalker' $SmoServer
$tree = $walker.DiscoverDependencies($urns, $false)
$depCollection = $walker.WalkDependencies($tree)

$dependencies = $depCollection | foreach { $_.Urn }

This will find all other stored procedures that use MyTable (ones with typical INSERT, UPDATE, etc. calls). However, it will NOT find these *ConstraintChecking procedures that reference the table only via ALTER TABLE.

It should be noted that SSMS does not recognize these procedures as a dependency of the table either (when using View Dependencies).

I have tried to use other mechanisms for finding dependencies such as sp_depends and sys.dm_sql_referenced_entities, but those behave the same as DependencyWalker in this situation.

Using SMO in powershell and given a table URN, how do I find the URN of dependencies such as this?


问:
how to refresh recycyerview when pulldown recycyerview by user
i want refresh retrofit request when user pulldown the page .

i add an icon in option menu when click on icon refresh the data .

```<code>GlobalScope.launch {
val result = quotesApi.getQuotes()
withContext(Dispatchers.Main) {
if (result != null)
// Checking the results
prg.visibility = View.GONE
Log.d("T", result.body().toString())
}

        }

        val pullToRefresh = findViewById<SwipeRefreshLayout>(R.id.pullToRefresh)
        pullToRefresh.setOnRefreshListener {
            refreshData() // your code
            pullToRefresh.isRefreshing = false
        }

    }

    private fun refreshData() {
        val quotesApi = RetrofitHelper
</code>```

Body:
i want refresh retrofit request when user pulldown the page .

i add an icon in option menu when click on icon refresh the data .

GlobalScope.launch {
val result = quotesApi.getQuotes()
withContext(Dispatchers.Main) {
if (result != null)
// Checking the results
prg.visibility = View.GONE
Log.d("T", result.body().toString())
}

        }

        val pullToRefresh = findViewById<SwipeRefreshLayout>(R.id.pullToRefresh)
        pullToRefresh.setOnRefreshListener {
            refreshData() // your code
            pullToRefresh.isRefreshing = false
        }

    }

    private fun refreshData() {
        val quotesApi = RetrofitHelper


问:
mitmproxy save both original and forwarded request and response
What is a good way to save / write / log (request, response) pairs on both ends (client-facing, server-facing) of mitmproxy? That is, all 4 of:

c->p: original request from the client

p->c: final response to the client, possibly rewritten by the proxy

p->s: request forwarded to the server and possibly rewritten by the proxy

s->p: original response from the server

```<code>         c->p                         p->s
         original                     forwarded rewritten
         request                      request
       --------------------->        -------------->
client                         proxy                 server
       <---------------------        <--------------
         p->c                          s->p
         forwarded rewritten           original
         response                      response
</code>```

As far as I can see, the -w flag (of mitmdump) only saves single (request, response) pairs, so either the original or the forwarded request / response are not saved (and possibly neither of those, only some intermediate stage, before / after other addons that modify request / response).

Thanks for help.

Body:
What is a good way to save / write / log (request, response) pairs on both ends (client-facing, server-facing) of mitmproxy? That is, all 4 of:

c->p: original request from the client

p->c: final response to the client, possibly rewritten by the proxy

p->s: request forwarded to the server and possibly rewritten by the proxy

s->p: original response from the server

         c->p                         p->s
         original                     forwarded rewritten
         request                      request
       --------------------->        -------------->
client                         proxy                 server
       <---------------------        <--------------
         p->c                          s->p
         forwarded rewritten           original
         response                      response

As far as I can see, the -w flag (of mitmdump) only saves single (request, response) pairs, so either the original or the forwarded request / response are not saved (and possibly neither of those, only some intermediate stage, before / after other addons that modify request / response).

Thanks for help.


问:
selenium chrome NET BLOCKED BY CLIENT
selenium chrome If a page is not operated for a long time, for example, time.sleep 15 minutes, and then again, it can not open the web page, how to refresh the browser debugging found that it is blocked by client did not install any advertising plug-ins after this situation, if you enter the target URL in a new tab enter, it can be opened normally, who knows the reason? I don't think it has anything to do with cookies, thank you.

chromedriver version is also correct, I do not know if everyone's selenium chrome will not have this problem if the open page time.sleep longer time

***The reason for this is partly to do with the html http-equiv attribute of the target site. If the page does not change for a long time, any further execution of the url of the target site in the same tab will not be considered as "re-fetching from the server" but from the cache, which will cause a js exception. Any subsequent get requests of the xhr type will be directed to chrome-extension://invalid

The value after chrome-extension:// will be BLOCKED by chrome if it is unrecognisable, which will happen in any chrome speculation.

A not-so-good solution is to pywin32 simulate re-opening a new tab by typing in the url, but this causes some tab over-closing and handles switching exceptions, so I'm considering seeing if I can fix this from some chrome option parameter settings***

Also if I don't use selenium chrome but normal manual normal browsing of the target site, I don't manipulate the page for a long time and I don't have the above problem, not quite sure if this is an ISSUE with chrome, don't want to switch to firefox as there is too much code to change.

Title: selenium chrome NET BLOCKED BY CLIENT


问:
booleanPointInPolygon is returning wrong values at the border
I have the following polygon displayed on a map:

```<code>{
    "type": "Feature",
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [
                    -125.59984949809844,
                    45.262153541142055
                ],
                [
                    -64.97100463461506,
                    39.503280047917194
                ],
                [
                    -71.53494497281665,
                    25.360849581306127
                ],
                [
                    -121.81059696453559,
                    26.995032595715646
                ],
                [
                    -125.59984949809844,
                    45.262153541142055
                ]
            ]
        ]
    },
    "properties": {}
}
</code>```

Calling

```<code>console.log(booleanPointInPolygon([-98.65195, 49.42827], polygon)); //logs false
console.log(booleanPointInPolygon([-106.53965, 27.69895], polygon)); //logs true
</code>```

when the expected output should be the opposite. I'm pretty sure my data is in the right form [longitude, latitude], I am wondering what's giving me the wrong output?

Body:
I have the following polygon displayed on a map:

{
    "type": "Feature",
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [
                    -125.59984949809844,
                    45.262153541142055
                ],
                [
                    -64.97100463461506,
                    39.503280047917194
                ],
                [
                    -71.53494497281665,
                    25.360849581306127
                ],
                [
                    -121.81059696453559,
                    26.995032595715646
                ],
                [
                    -125.59984949809844,
                    45.262153541142055
                ]
            ]
        ]
    },
    "properties": {}
}

Calling

console.log(booleanPointInPolygon([-98.65195, 49.42827], polygon)); //logs false
console.log(booleanPointInPolygon([-106.53965, 27.69895], polygon)); //logs true

when the expected output should be the opposite. I'm pretty sure my data is in the right form [longitude, latitude], I am wondering what's giving me the wrong output?


问:
Applying statsforecast implementation of expanding window cross-validation to multiple time series with varying lengths
I am looking to assess the accuracy of different classical time series forecasting models by implementing expanding window cross-validation with statsforecast on a time-series dataset with many unique IDs that have varying temporal lengths that can range between 1 to 48 months. I would like to forecast the next seven months after the ending month of each window and assess the accuracy with some error metric (e.g., sMAPE). There is potentially seasonality and trend in the different time series, so I would like to capture these in the cross-validation process as well. However, I am having difficulty and not fully understanding the different parameters (step_size, n_windows, test_size) in the package's cross-validation function.

Could someone advise me in setting up the right parameters? Is what I'm looking for even feasible with the function provided in the package? How do I decide the best value for step_size, test_size and n_windows?

For reference, my data looks like this:

df =

unique_id
ds
y

0
111111
2000-01-01
9

1
111111
2000-02-01
9

2
111111
2000-03-01
10

3
111111
2000-04-01
4

...
...
...
...

999999
111269
2003-10-01
32532

1000000
111269
2003-11-01
0

1000001
111269
2003-12-01
984214

And to be explicit, the history for individual unique_ids can vary (i.e., the length of the time series is unequal between unique_ids.)

I have already instantiated my StatsForecast object with the requisite models:

```<code>sf = StatsForecast(
    df=df,
    models=[AutoARIMA(season_length=12), AutoETS(error_type='zzz'), Naive()],
    freq='MS',
    n_jobs=-1,
    fallback_model=Naive()
)
</code>```

Then, I call the cross_validation method:

```<code>results_cv = sf.cross_validation(
    h=7 # Predict each of the future seven months
    step_size=?,
    n_windows=?
)
</code>```

I have tried an assortment of parameter values for step_size and n_windows together, and also just for test_size alone (e.g., 7 because I want to compare the last 7 months of actuals and forecasts in each window), but I'm always left with the following error:

ValueError: could not broadcast input array from shape (y,) into shape (z,)

I expect the end result to look similar to the data-frame presented in the statsforecast tutorial:
screenshot from the GitHub example

or scroll down to 'crossvaldation_df.head()'

Any pointers would be greatly appreciated. Thank you!

Body:
I am looking to assess the accuracy of different classical time series forecasting models by implementing expanding window cross-validation with statsforecast on a time-series dataset with many unique IDs that have varying temporal lengths that can range between 1 to 48 months. I would like to forecast the next seven months after the ending month of each window and assess the accuracy with some error metric (e.g., sMAPE). There is potentially seasonality and trend in the different time series, so I would like to capture these in the cross-validation process as well. However, I am having difficulty and not fully understanding the different parameters (step_size, n_windows, test_size) in the package's cross-validation function.

Could someone advise me in setting up the right parameters? Is what I'm looking for even feasible with the function provided in the package? How do I decide the best value for step_size, test_size and n_windows?

For reference, my data looks like this:

df =

unique_id
ds
y

0
111111
2000-01-01
9

1
111111
2000-02-01
9

2
111111
2000-03-01
10

3
111111
2000-04-01
4

...
...
...
...

999999
111269
2003-10-01
32532

1000000
111269
2003-11-01
0

1000001
111269
2003-12-01
984214

And to be explicit, the history for individual unique_ids can vary (i.e., the length of the time series is unequal between unique_ids.)

I have already instantiated my StatsForecast object with the requisite models:

sf = StatsForecast(
    df=df,
    models=[AutoARIMA(season_length=12), AutoETS(error_type='zzz'), Naive()],
    freq='MS',
    n_jobs=-1,
    fallback_model=Naive()
)

Then, I call the cross_validation method:

results_cv = sf.cross_validation(
    h=7 # Predict each of the future seven months
    step_size=?,
    n_windows=?
)

I have tried an assortment of parameter values for step_size and n_windows together, and also just for test_size alone (e.g., 7 because I want to compare the last 7 months of actuals and forecasts in each window), but I'm always left with the following error:

ValueError: could not broadcast input array from shape (y,) into shape (z,)

I expect the end result to look similar to the data-frame presented in the statsforecast tutorial:
screenshot from the GitHub example

or scroll down to 'crossvaldation_df.head()'

Any pointers would be greatly appreciated. Thank you!


问:
Pygame inconsistent sprite speed
It could just be a product of lag, but in the Pygame import, my sprite movement is not consistent. At times it will be as expected, and then randomly speed up or jump across the screen.

I've tried both keypress loggers, the .key_get_pressed() and event.type == KEYDOWN, both have had the jumping issue.

Title: Pygame inconsistent sprite speed


问:
Proxy error: Could not proxy request /upload from localhost:3000 to http://localhost:8800/ (ECONNRESET) for axios.post in react
I've Tried uploading some file by multer.diskStorage but got an error for this by axios that it cannot proxy the frontend to backend host address. The Error Only Occurs When I'm sending the FormData to the server, else No Proxy Error...
The axios post request says that Could not proxy request ${ROUTE} from localhost:3000 (React Host) to http://localhost:8800/ (Express Host) and showing the error (ECONNRESET).

I've used a comment to show THE PROBLEM PART. Hoping for a solution...

Here is my react's package.json file

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@mui/icons-material": "^5.11.0",
    "@mui/material": "^5.11.2",
    "@mui/styled-engine": "^5.11.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.2.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router": "^5.3.4",
    "react-router-dom": "^5.3.4",
    "react-scripts": "5.0.1",
    "timeago.js": "^4.0.2",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:8800"
}

</code>```

This is my React Component (like FaceBook Share)

```<code>import './share.css'
import { Mood, CameraAlt, LocationOn, Label, ArrowDropDown } from '@mui/icons-material';
import { useContext, useRef, useState } from 'react';
import { AuthContext } from '../../context/AuthContext'
import axios from 'axios';

const Share = () => {
    const { user } = useContext(AuthContext);
    const [file, setFile] = useState(null);
    const desc = useRef();

    const submitHandler = async (e) => {
        console.log("..............................");
        e.preventDefault();
        const newPost = {
                userId: user._id,
                desc: desc.current.value
            }
        if (file) {    // THIS IS THE PROBLEM PART
            const data = new FormData();
            const fileName = file.name + Date.now();
            data.append('file', file);
            data.append('name', fileName);
            newPost.img = fileName;
            try {
                axios.post('/upload', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                    transformRequest: formData => formData,
                })
                .then((res) => {
                    console.log(res.data);
                });
            } catch (err) {
                console.log(err);
            }
        }
        try {
           await axios.post('/posts/', newPost);
        }catch(err){}
    }

    const PF = process.env.REACT_APP_PUBLIC_FOLDER;

    return (
        <div className='share'>
            <div className="shareTop">
                <div className='shareProfileContainer'>
                    <img src={user.profilePicture || PF+'content/noAvatar.png'} alt="Profile" className="shareProfile" />
                    <div className='shareDetails'>
                        <span className='shareProfileText'>{user.username}</span>
                        < ArrowDropDown className='shareProfileOption' />
                        <span className='shareProfileOptionText'>Public</span>
                    </div>
                </div>
                <input placeholder={"What's on your mind, " + user.username + '?'} className='shareInput' ref={desc}/>
            </div>
            <hr className='shareHr' />
            <div className="shareBottom">
                <form className="shareOptions" onSubmit={submitHandler} enctype="multipart/form-data" name="file">
                    <label htmlFor='photosNvideos' className="shareOption">
                        < CameraAlt color='success' />
                        <input id='photosNvideos' type="file" accept='.png, .jpg, .jpeg, .heif, .mp4, .hevc' onChange={(e) => (setFile(e.target.files[0]))} />
                        <span className='shareOptionText'>Photo/Video</span>
                    </label>
                    <div className="shareOption">
                        < LocationOn color='error' />
                        <span className='shareOptionText'>Location</span>
                    </div>
                    <div className="shareOption">
                        < Label color='primary' />
                        <span className='shareOptionText'>Tag</span>
                    </div>
                    <div className="shareOption">
                        < Mood color='warning' />
                        <span className='shareOptionText'>Feeling</span>
                    </div>
                    <button type="submit" className="shareButton">Post</button>
                </form>
            </div>
        </div>
    );
}

export default Share;
</code>```

And This is my backend code

```<code>const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const multer = require('multer');
const path = require('path');

dotenv.config();

mongoose.set('strictQuery', true);
mongoose.connect(process.env.DB_URL, () => {
    console.log('Connected to MongoDB');
});

app.use('/images', express.static(path.join(__dirname, './public/images')));

//middleware
app.use(express.json());
app.use(morgan('common'));

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images');
    },
    filename: function (req, file, cb) {
        cb(null, req.body.name);
    }
});

const upload = multer({ storage });
app.post('/upload', upload.single("file"), (req, res) => {
    try {
        return res.status(200).json("Upload Success");
    } catch (err) {
        console.log(err);
    }
});

app.use('/users', userRoute);
app.use('/posts', postRoute);
app.use('/auth', authRoute);

app.listen(8800, () => {
    console.log('Backend server is running!');
});
</code>```

I've Tried uploading some file by multer.diskStorage but got an error for this by axios that it cannot proxy the frontend to backend host address.

Body:
I've Tried uploading some file by multer.diskStorage but got an error for this by axios that it cannot proxy the frontend to backend host address. The Error Only Occurs When I'm sending the FormData to the server, else No Proxy Error...
The axios post request says that Could not proxy request ${ROUTE} from localhost:3000 (React Host) to http://localhost:8800/ (Express Host) and showing the error (ECONNRESET).

I've used a comment to show THE PROBLEM PART. Hoping for a solution...

Here is my react's package.json file

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@mui/icons-material": "^5.11.0",
    "@mui/material": "^5.11.2",
    "@mui/styled-engine": "^5.11.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.2.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router": "^5.3.4",
    "react-router-dom": "^5.3.4",
    "react-scripts": "5.0.1",
    "timeago.js": "^4.0.2",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:8800"
}

This is my React Component (like FaceBook Share)

import './share.css'
import { Mood, CameraAlt, LocationOn, Label, ArrowDropDown } from '@mui/icons-material';
import { useContext, useRef, useState } from 'react';
import { AuthContext } from '../../context/AuthContext'
import axios from 'axios';

const Share = () => {
    const { user } = useContext(AuthContext);
    const [file, setFile] = useState(null);
    const desc = useRef();

    const submitHandler = async (e) => {
        console.log("..............................");
        e.preventDefault();
        const newPost = {
                userId: user._id,
                desc: desc.current.value
            }
        if (file) {    // THIS IS THE PROBLEM PART
            const data = new FormData();
            const fileName = file.name + Date.now();
            data.append('file', file);
            data.append('name', fileName);
            newPost.img = fileName;
            try {
                axios.post('/upload', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                    transformRequest: formData => formData,
                })
                .then((res) => {
                    console.log(res.data);
                });
            } catch (err) {
                console.log(err);
            }
        }
        try {
           await axios.post('/posts/', newPost);
        }catch(err){}
    }

    const PF = process.env.REACT_APP_PUBLIC_FOLDER;

    return (

                        {user.username}
                        < ArrowDropDown className='shareProfileOption' />
                        Public

                <input placeholder={"What's on your mind, " + user.username + '?'} className='shareInput' ref={desc}/>

                <form className="shareOptions" onSubmit={submitHandler} enctype="multipart/form-data" name="file">

                        < CameraAlt color='success' />
                        <input id='photosNvideos' type="file" accept='.png, .jpg, .jpeg, .heif, .mp4, .hevc' onChange={(e) => (setFile(e.target.files[0]))} />
                        Photo/Video

                        < LocationOn color='error' />
                        Location

                        Tag

                        < Mood color='warning' />
                        Feeling

                    <button type="submit" className="shareButton">Post</button>
                </form>

    );
}

export default Share;

And This is my backend code

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const multer = require('multer');
const path = require('path');

dotenv.config();

mongoose.set('strictQuery', true);
mongoose.connect(process.env.DB_URL, () => {
    console.log('Connected to MongoDB');
});

app.use('/images', express.static(path.join(__dirname, './public/images')));

//middleware
app.use(express.json());
app.use(morgan('common'));

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images');
    },
    filename: function (req, file, cb) {
        cb(null, req.body.name);
    }
});

const upload = multer({ storage });
app.post('/upload', upload.single("file"), (req, res) => {
    try {
        return res.status(200).json("Upload Success");
    } catch (err) {
        console.log(err);
    }
});

app.use('/users', userRoute);
app.use('/posts', postRoute);
app.use('/auth', authRoute);

app.listen(8800, () => {
    console.log('Backend server is running!');
});

I've Tried uploading some file by multer.diskStorage but got an error for this by axios that it cannot proxy the frontend to backend host address.