问:
JSON Array iteration using For Loop stopped at last index
I'm creating a canvas using p5.js and Marine Weather JSON file.
I'm setting for loops to iterate through the array of values from JSON file (e.g. for the length of the loop, change colour based on the values of each indices).
The for loop seems to only show the value from last index.

I have 6 things that I'm using for loop:

Change alpha value depending on air temperature & water
temperature from JSON divided by given number.

Draw random circles until loop ends for x number of times, where x = humidity value from JSON.

Change circle colour from array when index of colour array matches index of JSON array that I have created.

Draw sine wave with amplitude value from wave height & wind speed value of JSON.

At the moment, when I test using variable and for loop, everything seems to freeze at last index value. If I comment out the for loop and give the index a fixed value instead of variable, the sine waves animates (still only of last index value).
Circles form randomly if I comment out all for loop related part, however they disappear and reform too quickly.

I'll add the JSON in CSS part.

let weather;

let xspacing = 15; // Distance between each horizontal location
let waveWidth; // Width of entire wave
let theta = 0.0; // Start angle at 0
let amplitude = 25; // Height of wave
let period = 1000.0; // How many pixels before the wave repeats
let dx; // Value for incrementing x
let yvalues; // Using an array to store height values for the wave

function setup() {
  //set up a canvas that's size depends on the browser size
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB);

  waveWidth = width + 16;
  dx = (TWO_PI / period) * xspacing;
  yvalues = new Array(floor(waveWidth / xspacing));
}

function draw() {
  let warmth = color(50, 100, 100); //rgb 255, 215, 0
  let upper = color(0, 100, 65); //rgb 165, 0, 0
  let lower = color(234, 100, 31); //rgb 0, 8, 80

  let start = color(50, 2, 100); //rgb 255, 254, 249
  let mid = color(50, 100, 100); //rgb 255, 212, 0
  let end = color(49, 100, 13); //rbg 33, 27, 0

  let mixer = [];
  mixer[0] = start;
  mixer[1] = lerpColor(start, mid, 0.099);
  mixer[2] = lerpColor(start, mid, 0.198);
  mixer[3] = lerpColor(start, mid, 0.297);
  mixer[4] = lerpColor(start, mid, 0.396);
  mixer[5] = lerpColor(start, mid, 0.495);
  mixer[6] = lerpColor(start, mid, 0.594);
  mixer[7] = lerpColor(start, mid, 0.693);
  mixer[8] = lerpColor(start, mid, 0.792);
  mixer[9] = lerpColor(start, mid, 0.891);
  mixer[10] = lerpColor(start, mid, 0.99);
  mixer[11] = mid;
  mixer[12] = lerpColor(mid, end, 0.099);
  mixer[13] = lerpColor(mid, end, 0.198);
  mixer[14] = lerpColor(mid, end, 0.297);
  mixer[15] = lerpColor(mid, end, 0.396);
  mixer[16] = lerpColor(mid, end, 0.495);
  mixer[17] = lerpColor(mid, end, 0.594);
  mixer[18] = lerpColor(mid, end, 0.693);
  mixer[19] = lerpColor(mid, end, 0.792);
  mixer[20] = lerpColor(mid, end, 0.891);
  mixer[21] = lerpColor(mid, end, 0.99);
  mixer[23] = end;

  //background colour of canvas
  background(0, 28, 122);

  fill(0, 100, 65);
  noStroke();
  rect(0, 0, windowWidth, windowHeight / 2);
  //upper half of canvas representing air temperature
  for (let a = 0; a < weather.hours.length; a++) {
    fill(47, 100, 100, (weather.hours[a].airTemperature - 27) / 10);
    noStroke();
    rect(0, 0, windowWidth, windowHeight / 2);
  }

  //lower half of canvas representing water temperature
  fill(234, 100, 31);
  noStroke();
  rect(0, windowHeight / 2, windowWidth, windowHeight / 2);

  for (let w = 0; w < weather.hours.length; w++) {
    fill(47, 100, 100, (weather.hours[w].waterTemperature - 28) / 20);
    noStroke();
    rect(0, windowHeight / 2, windowWidth, windowHeight / 2);
  }

  //translucent circles with random sizes to form on random locations
  for (let h = 0; h > weather.hours.length; h++) {
    let humidityCircle = weather.hours[h].humidity;
    for (let hc = 0; hc > humidityCircle; hc++) {
      fill(255, 255, 255, 127.5);
      noStroke();
      circle(random(windowWidth), random(windowHeight / 2), random((windowWidth / 18) + 15));
    }
  }

  calcWindWave();
  renderWindWave();

  calcWaveWave();
  renderWaveWave();

  //middle large circle
  for (let t = 0; t < weather.hours.length; t++) {
    fill(mixer[weather.hours[t].time]);
    noStroke();
    circle(windowWidth / 2, windowHeight / 2, windowHeight / 3.5);
  }
}

function calcWindWave() {
  //change amplitude using windSpeed
  //Increment theta (try different values for 'angular velocity' here)
  theta += 0.02;

  //For every x value, calculate a y value with sine function
  let x = theta;
  let wsAmplitude;

  for (let ws = 0; ws < weather.hours.length; ws++) {
    wsAmplitude = weather.hours[ws].windSpeed * amplitude;
    for (i = 0; i < yvalues.length; i++) {
      yvalues[i] = sin(x) * wsAmplitude;
      x += dx;
    }
  }
}

function calcWaveWave() {
  //change amplitude using waveHeight
  //Increment theta (try different values for 'angular velocity' here)
  theta += 0.05;

  // For every x value, calculate a y value with sine function
  let x = theta;
  let whAmplitude;

  for (let wh = 0; wh < weather.hours.length; wh++) {
    whAmplitude = weather.hours[wh].waveHeight * amplitude;
    for (let i = 0; i < yvalues.length; i++) {
      yvalues[i] = sin(x) * whAmplitude;
      x += dx;
    }
  }
}

function renderWindWave() {
  noStroke();
  fill(255);
  //A simple way to draw the wave with an ellipse at each location
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 + yvalues[x], 3, 3);
  }
}

function renderWaveWave() {
  noStroke();
  fill(255);
  //A simple way to draw the wave with an ellipse at each location
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 - yvalues[x], 3, 3);
    print(yvalues.x);
  }
}

function preload() {
  weather = {
    "hours": [{
        "airTemperature": 27.65,
        "humidity": 70.8,
        "time": 0,
        "waterTemperature": 29.28,
        "waveHeight": 1.62,
        "windSpeed": 3.26
      },
      {
        "airTemperature": 27.67,
        "humidity": 70.9,
        "time": 1,
        "waterTemperature": 29.35,
        "waveHeight": 1.7,
        "windSpeed": 3.1
      },
      {
        "airTemperature": 27.7,
        "humidity": 71,
        "time": 2,
        "waterTemperature": 29.31,
        "waveHeight": 1.78,
        "windSpeed": 2.94
      },
      {
        "airTemperature": 27.72,
        "humidity": 71.1,
        "time": 3,
        "waterTemperature": 29.14,
        "waveHeight": 1.86,
        "windSpeed": 2.78
      },
      {
        "airTemperature": 27.67,
        "humidity": 71.8,
        "time": 4,
        "waterTemperature": 28.93,
        "waveHeight": 1.86,
        "windSpeed": 2.65
      },
      {
        "airTemperature": 27.62,
        "humidity": 72.5,
        "time": 5,
        "waterTemperature": 28.8,
        "waveHeight": 1.86,
        "windSpeed": 2.53
      },
      {
        "airTemperature": 27.57,
        "humidity": 73.2,
        "time": 6,
        "waterTemperature": 28.7,
        "waveHeight": 1.86,
        "windSpeed": 2.4
      },
      {
        "airTemperature": 27.47,
        "humidity": 73.51,
        "time": 7,
        "waterTemperature": 28.63,
        "waveHeight": 1.85,
        "windSpeed": 2.24
      },
      {
        "airTemperature": 27.38,
        "humidity": 73.82,
        "time": 8,
        "waterTemperature": 28.58,
        "waveHeight": 1.83,
        "windSpeed": 2.09
      },
      {
        "airTemperature": 27.28,
        "humidity": 74.13,
        "time": 9,
        "waterTemperature": 28.54,
        "waveHeight": 1.82,
        "windSpeed": 1.93
      },
      {
        "airTemperature": 27.19,
        "humidity": 74.1,
        "time": 10,
        "waterTemperature": 28.51,
        "waveHeight": 1.8,
        "windSpeed": 1.83
      },
      {
        "airTemperature": 27.11,
        "humidity": 74.06,
        "time": 11,
        "waterTemperature": 28.48,
        "waveHeight": 1.78,
        "windSpeed": 1.74
      },
      {
        "airTemperature": 27.02,
        "humidity": 74.03,
        "time": 12,
        "waterTemperature": 28.46,
        "waveHeight": 1.76,
        "windSpeed": 1.64
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.98,
        "time": 13,
        "waterTemperature": 28.45,
        "waveHeight": 1.74,
        "windSpeed": 1.69
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.94,
        "time": 14,
        "waterTemperature": 28.43,
        "waveHeight": 1.72,
        "windSpeed": 1.74
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.89,
        "time": 15,
        "waterTemperature": 28.42,
        "waveHeight": 1.7,
        "windSpeed": 1.79
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.01,
        "time": 16,
        "waterTemperature": 28.42,
        "waveHeight": 1.69,
        "windSpeed": 1.92
      },
      {
        "airTemperature": 27.03,
        "humidity": 72.13,
        "time": 17,
        "waterTemperature": 28.42,
        "waveHeight": 1.67,
        "windSpeed": 2.04
      },
      {
        "airTemperature": 27.04,
        "humidity": 71.25,
        "time": 18,
        "waterTemperature": 28.54,
        "waveHeight": 1.66,
        "windSpeed": 2.17
      },
      {
        "airTemperature": 27.09,
        "humidity": 70.52,
        "time": 19,
        "waterTemperature": 28.74,
        "waveHeight": 1.65,
        "windSpeed": 2.35
      },
      {
        "airTemperature": 27.15,
        "humidity": 69.8,
        "time": 20,
        "waterTemperature": 29.04,
        "waveHeight": 1.65,
        "windSpeed": 2.53
      },
      {
        "airTemperature": 27.21,
        "humidity": 69.08,
        "time": 21,
        "waterTemperature": 29.39,
        "waveHeight": 1.64,
        "windSpeed": 2.71
      },
      {
        "airTemperature": 27.32,
        "humidity": 71.12,
        "time": 22,
        "waterTemperature": 29.72,
        "waveHeight": 1.63,
        "windSpeed": 3.23
      },
      {
        "airTemperature": 27.44,
        "humidity": 73.16,
        "time": 23,
        "waterTemperature": 30,
        "waveHeight": 1.63,
        "windSpeed": 3.74
      }
    ],
    "meta": {
      "cost": 1,
      "dailyQuota": 50,
      "end": "2018-07-01 23:59",
      "lat": 9.933917,
      "lng": -132.038444,
      "params": [
        "airTemperature",
        "humidity",
        "waterTemperature",
        "waveHeight",
        "windSpeed"
      ],
      "requestCount": 3,
      "source": "sg",
      "start": "2018-07-01 00:00"
    }
  };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <!-- PLEASE NO CHANGES BELOW THIS LINE (UNTIL I SAY SO) -->
  <script language="javascript" type="text/javascript" src="libraries/p5.min.js"></script>
  <script language="javascript" type="text/javascript" src="p5js-temp-Restless_Sea9110872967160478905.js"></script>
  <!-- OK, YOU CAN MAKE CHANGES BELOW THIS LINE AGAIN -->

  <!-- This line removes any default padding and style.
       You might only need one of these values set. -->
  <style>
    body {
      padding: 0;
      margin: 0;
    }
  </style>
</head>

<body>
</body>

</html></code>```

答:
You (like many others) have missed out the structural concept of p5 library. Among other structural functions draw() is looping forever (unless you stop it) so you don't want to create own loops inside of it.
Although I dont understand what the desirable result should be, i'll throw you some guidelines:

let clicked=false;  //this is for start/stop animation
let weather;

let xspacing = 15; // Distance between each horizontal location
let waveWidth; // Width of entire wave
let theta = 0.0; // Start angle at 0
let amplitude = 25; // Height of wave
let period = 1000.0; // How many pixels before the wave repeats
let dx; // Value for incrementing x
let yvalues; // Using an array to store height values for the wave

/* counters from inner loops */
let t = w = h = a = 0;

/* all the looping variables */
let warmth,
 upper,
 lower,
 start,
 mid,
 end;
/* array */
let mixer = [];

 /*******************************************************************
* P5 preload
*
* Load images, data etc. Waits for any async is ended.
********************************************************************/
function preload() {
  weather = {
    "hours": [{
        "airTemperature": 27.65,
        "humidity": 70.8,
        "time": 0,
        "waterTemperature": 29.28,
        "waveHeight": 1.62,
        "windSpeed": 3.26
      },
      {
        "airTemperature": 27.67,
        "humidity": 70.9,
        "time": 1,
        "waterTemperature": 29.35,
        "waveHeight": 1.7,
        "windSpeed": 3.1
      },
      {
        "airTemperature": 27.7,
        "humidity": 71,
        "time": 2,
        "waterTemperature": 29.31,
        "waveHeight": 1.78,
        "windSpeed": 2.94
      },
      {
        "airTemperature": 27.72,
        "humidity": 71.1,
        "time": 3,
        "waterTemperature": 29.14,
        "waveHeight": 1.86,
        "windSpeed": 2.78
      },
      {
        "airTemperature": 27.67,
        "humidity": 71.8,
        "time": 4,
        "waterTemperature": 28.93,
        "waveHeight": 1.86,
        "windSpeed": 2.65
      },
      {
        "airTemperature": 27.62,
        "humidity": 72.5,
        "time": 5,
        "waterTemperature": 28.8,
        "waveHeight": 1.86,
        "windSpeed": 2.53
      },
      {
        "airTemperature": 27.57,
        "humidity": 73.2,
        "time": 6,
        "waterTemperature": 28.7,
        "waveHeight": 1.86,
        "windSpeed": 2.4
      },
      {
        "airTemperature": 27.47,
        "humidity": 73.51,
        "time": 7,
        "waterTemperature": 28.63,
        "waveHeight": 1.85,
        "windSpeed": 2.24
      },
      {
        "airTemperature": 27.38,
        "humidity": 73.82,
        "time": 8,
        "waterTemperature": 28.58,
        "waveHeight": 1.83,
        "windSpeed": 2.09
      },
      {
        "airTemperature": 27.28,
        "humidity": 74.13,
        "time": 9,
        "waterTemperature": 28.54,
        "waveHeight": 1.82,
        "windSpeed": 1.93
      },
      {
        "airTemperature": 27.19,
        "humidity": 74.1,
        "time": 10,
        "waterTemperature": 28.51,
        "waveHeight": 1.8,
        "windSpeed": 1.83
      },
      {
        "airTemperature": 27.11,
        "humidity": 74.06,
        "time": 11,
        "waterTemperature": 28.48,
        "waveHeight": 1.78,
        "windSpeed": 1.74
      },
      {
        "airTemperature": 27.02,
        "humidity": 74.03,
        "time": 12,
        "waterTemperature": 28.46,
        "waveHeight": 1.76,
        "windSpeed": 1.64
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.98,
        "time": 13,
        "waterTemperature": 28.45,
        "waveHeight": 1.74,
        "windSpeed": 1.69
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.94,
        "time": 14,
        "waterTemperature": 28.43,
        "waveHeight": 1.72,
        "windSpeed": 1.74
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.89,
        "time": 15,
        "waterTemperature": 28.42,
        "waveHeight": 1.7,
        "windSpeed": 1.79
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.01,
        "time": 16,
        "waterTemperature": 28.42,
        "waveHeight": 1.69,
        "windSpeed": 1.92
      },
      {
        "airTemperature": 27.03,
        "humidity": 72.13,
        "time": 17,
        "waterTemperature": 28.42,
        "waveHeight": 1.67,
        "windSpeed": 2.04
      },
      {
        "airTemperature": 27.04,
        "humidity": 71.25,
        "time": 18,
        "waterTemperature": 28.54,
        "waveHeight": 1.66,
        "windSpeed": 2.17
      },
      {
        "airTemperature": 27.09,
        "humidity": 70.52,
        "time": 19,
        "waterTemperature": 28.74,
        "waveHeight": 1.65,
        "windSpeed": 2.35
      },
      {
        "airTemperature": 27.15,
        "humidity": 69.8,
        "time": 20,
        "waterTemperature": 29.04,
        "waveHeight": 1.65,
        "windSpeed": 2.53
      },
      {
        "airTemperature": 27.21,
        "humidity": 69.08,
        "time": 21,
        "waterTemperature": 29.39,
        "waveHeight": 1.64,
        "windSpeed": 2.71
      },
      {
        "airTemperature": 27.32,
        "humidity": 71.12,
        "time": 22,
        "waterTemperature": 29.72,
        "waveHeight": 1.63,
        "windSpeed": 3.23
      },
      {
        "airTemperature": 27.44,
        "humidity": 73.16,
        "time": 23,
        "waterTemperature": 30,
        "waveHeight": 1.63,
        "windSpeed": 3.74
      }
    ],
    "meta": {
      "cost": 1,
      "dailyQuota": 50,
      "end": "2018-07-01 23:59",
      "lat": 9.933917,
      "lng": -132.038444,
      "params": [
        "airTemperature",
        "humidity",
        "waterTemperature",
        "waveHeight",
        "windSpeed"
      ],
      "requestCount": 3,
      "source": "sg",
      "start": "2018-07-01 00:00"
    }
  }
}

/*******************************************************************
* P5 setup
* run once, use for initialisation.
*
* Create a canvas, show pictures, initialize arrays etc.
********************************************************************/
function setup() {
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB);

  waveWidth = width + 16;
  dx = (TWO_PI / period) * xspacing;
  yvalues = new Array(floor(waveWidth / xspacing));

 /*
  *  all the colors and mixer[] array should be
  *  initialized here as their values are not changed
  */
   warmth = color(50, 100, 100); //rgb 255, 215, 0
   upper = color(0, 100, 65); //rgb 165, 0, 0
   lower = color(234, 100, 31); //rgb 0, 8, 80

   start = color(50, 2, 100); //rgb 255, 254, 249
   mid = color(50, 100, 100); //rgb 255, 212, 0
   end = color(49, 100, 13); //rbg 33, 27, 0

  mixer[0] = start;
  mixer[1] = lerpColor(start, mid, 0.099);
  mixer[2] = lerpColor(start, mid, 0.198);
  mixer[3] = lerpColor(start, mid, 0.297);
  mixer[4] = lerpColor(start, mid, 0.396);
  mixer[5] = lerpColor(start, mid, 0.495);
  mixer[6] = lerpColor(start, mid, 0.594);
  mixer[7] = lerpColor(start, mid, 0.693);
  mixer[8] = lerpColor(start, mid, 0.792);
  mixer[9] = lerpColor(start, mid, 0.891);
  mixer[10] = lerpColor(start, mid, 0.99);
  mixer[11] = mid;
  mixer[12] = lerpColor(mid, end, 0.099);
  mixer[13] = lerpColor(mid, end, 0.198);
  mixer[14] = lerpColor(mid, end, 0.297);
  mixer[15] = lerpColor(mid, end, 0.396);
  mixer[16] = lerpColor(mid, end, 0.495);
  mixer[17] = lerpColor(mid, end, 0.594);
  mixer[18] = lerpColor(mid, end, 0.693);
  mixer[19] = lerpColor(mid, end, 0.792);
  mixer[20] = lerpColor(mid, end, 0.891);
  mixer[21] = lerpColor(mid, end, 0.95);
  mixer[22] = lerpColor(mid, end, 0.99);
  mixer[23] = end;

/* here you can change the speed of the animation */
  frameRate(3);
}

/*******************************************************************
* P5 draw
* endless loop.
*
* Do something visual with collected data.
* NB! This is already endless loop, do not create loops into it
********************************************************************/
function draw() {
  //background colour of canvas
  background(0, 28, 122);

  fill(0, 100, 65);
  noStroke();
  rect(0, 0, windowWidth, windowHeight / 2);

/* we are looping already, so you use variable a ... */
  //  for (let a = 0; a < weather.hours.length; a++) {
    fill(47, 100, 100, (weather.hours[a].airTemperature - 27) / 10);
    noStroke();
    rect(0, 0, windowWidth, windowHeight / 2);
/* ... and increase its value for the next loop */
  a++;
//  }

  fill(234, 100, 31);
  noStroke();
  rect(0, windowHeight / 2, windowWidth, windowHeight / 2);
//  for (let w = 0; w < weather.hours.length; w++) {
    fill(47, 100, 100, (weather.hours[w].waterTemperature - 28) / 20);
    noStroke();
    rect(0, windowHeight / 2, windowWidth, windowHeight / 2);
 w++;
//  }

  //translucent circles with random sizes to form on random locations

//  for (let h = 0; h > weather.hours.length; h++) {
    let humidityCircle = weather.hours[h].humidity;
    for (let hc = 0; hc < humidityCircle; hc++) {
      fill(255, 255, 255, 127.5);
      noStroke();
      ellipse(random(windowWidth), random(windowHeight / 2), random((windowWidth / 18) + 15));
    }
 h++;
//  }

  calcWindWave();
  renderWindWave();

  calcWaveWave();
  renderWaveWave();

  //middle large circle
//  for (let t = 0; t < weather.hours.length; t++) {
    fill(mixer[weather.hours[t].time]);
    noStroke();
    ellipse(windowWidth / 2, windowHeight / 2, windowHeight / 3.5);
 t++;
//  }

/* Also we have to check/change our counters
*  At this case all the counters will be initialized under same condition
*/
if(t>23)
 a = w = t = h = 0;
}

function calcWindWave() {
  //change amplitude using windSpeed
  //Increment theta (try different values for 'angular velocity' here)
  theta += 0.02;

  //For every x value, calculate a y value with sine function
  let x = theta;
  let wsAmplitude;

  for (let ws = 0; ws < weather.hours.length; ws++) {
    wsAmplitude = weather.hours[ws].windSpeed * amplitude;
    for (i = 0; i < yvalues.length; i++) {
      yvalues[i] = sin(x) * wsAmplitude;
      x += dx;
    }
  }
}

function calcWaveWave() {
  //change amplitude using waveHeight
  //Increment theta (try different values for 'angular velocity' here)
  theta += 0.05;

  // For every x value, calculate a y value with sine function
  let x = theta;
  let whAmplitude;

  for (let wh = 0; wh < weather.hours.length; wh++) {
    whAmplitude = weather.hours[wh].waveHeight * amplitude;
    for (let i = 0; i < yvalues.length; i++) {
      yvalues[i] = sin(x) * whAmplitude;
      x += dx;
    }
  }
}

function renderWindWave() {
  noStroke();
  fill(255);
  //A simple way to draw the wave with an ellipse at each location
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 + yvalues[x], 3, 3);
  }
}

function renderWaveWave() {
  noStroke();
  fill(255);
  //A simple way to draw the wave with an ellipse at each location
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 - yvalues[x], 3, 3);
//    print(yvalues.x);
  }
}
/*******************************************************************
* P5 mouseClicked
*
* P5 event. I use it to start/stop the animation
********************************************************************/
mouseClicked = function() {
    if (mouseButton === LEFT) {
  clicked = !clicked;
  if(clicked){
   noLoop();
  }else{
   loop();
  }
    }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script></code>```

Body:
I'm creating a canvas using p5.js and Marine Weather JSON file.
I'm setting for loops to iterate through the array of values from JSON file (e.g. for the length of the loop, change colour based on the values of each indices).
The for loop seems to only show the value from last index.

I have 6 things that I'm using for loop:

Change alpha value depending on air temperature & water
temperature from JSON divided by given number.

Draw random circles until loop ends for x number of times, where x = humidity value from JSON.

Change circle colour from array when index of colour array matches index of JSON array that I have created.

Draw sine wave with amplitude value from wave height & wind speed value of JSON.

At the moment, when I test using variable and for loop, everything seems to freeze at last index value. If I comment out the for loop and give the index a fixed value instead of variable, the sine waves animates (still only of last index value).
Circles form randomly if I comment out all for loop related part, however they disappear and reform too quickly.

I'll add the JSON in CSS part.

let weather;

let xspacing = 15; // Distance between each horizontal location
let waveWidth; // Width of entire wave
let theta = 0.0; // Start angle at 0
let amplitude = 25; // Height of wave
let period = 1000.0; // How many pixels before the wave repeats
let dx; // Value for incrementing x
let yvalues; // Using an array to store height values for the wave

function setup() {
  //set up a canvas that's size depends on the browser size
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB);

  waveWidth = width + 16;
  dx = (TWO_PI / period) * xspacing;
  yvalues = new Array(floor(waveWidth / xspacing));
}

function draw() {
  let warmth = color(50, 100, 100); //rgb 255, 215, 0
  let upper = color(0, 100, 65); //rgb 165, 0, 0
  let lower = color(234, 100, 31); //rgb 0, 8, 80

  let start = color(50, 2, 100); //rgb 255, 254, 249
  let mid = color(50, 100, 100); //rgb 255, 212, 0
  let end = color(49, 100, 13); //rbg 33, 27, 0

  let mixer = [];
  mixer[0] = start;
  mixer[1] = lerpColor(start, mid, 0.099);
  mixer[2] = lerpColor(start, mid, 0.198);
  mixer[3] = lerpColor(start, mid, 0.297);
  mixer[4] = lerpColor(start, mid, 0.396);
  mixer[5] = lerpColor(start, mid, 0.495);
  mixer[6] = lerpColor(start, mid, 0.594);
  mixer[7] = lerpColor(start, mid, 0.693);
  mixer[8] = lerpColor(start, mid, 0.792);
  mixer[9] = lerpColor(start, mid, 0.891);
  mixer[10] = lerpColor(start, mid, 0.99);
  mixer[11] = mid;
  mixer[12] = lerpColor(mid, end, 0.099);
  mixer[13] = lerpColor(mid, end, 0.198);
  mixer[14] = lerpColor(mid, end, 0.297);
  mixer[15] = lerpColor(mid, end, 0.396);
  mixer[16] = lerpColor(mid, end, 0.495);
  mixer[17] = lerpColor(mid, end, 0.594);
  mixer[18] = lerpColor(mid, end, 0.693);
  mixer[19] = lerpColor(mid, end, 0.792);
  mixer[20] = lerpColor(mid, end, 0.891);
  mixer[21] = lerpColor(mid, end, 0.99);
  mixer[23] = end;

  //background colour of canvas
  background(0, 28, 122);

  fill(0, 100, 65);
  noStroke();
  rect(0, 0, windowWidth, windowHeight / 2);
  //upper half of canvas representing air temperature
  for (let a = 0; a < weather.hours.length; a++) {
    fill(47, 100, 100, (weather.hours[a].airTemperature - 27) / 10);
    noStroke();
    rect(0, 0, windowWidth, windowHeight / 2);
  }

  //lower half of canvas representing water temperature
  fill(234, 100, 31);
  noStroke();
  rect(0, windowHeight / 2, windowWidth, windowHeight / 2);

  for (let w = 0; w < weather.hours.length; w++) {
    fill(47, 100, 100, (weather.hours[w].waterTemperature - 28) / 20);
    noStroke();
    rect(0, windowHeight / 2, windowWidth, windowHeight / 2);
  }

  //translucent circles with random sizes to form on random locations
  for (let h = 0; h > weather.hours.length; h++) {
    let humidityCircle = weather.hours[h].humidity;
    for (let hc = 0; hc > humidityCircle; hc++) {
      fill(255, 255, 255, 127.5);
      noStroke();
      circle(random(windowWidth), random(windowHeight / 2), random((windowWidth / 18) + 15));
    }
  }

  calcWindWave();
  renderWindWave();

  calcWaveWave();
  renderWaveWave();

  //middle large circle
  for (let t = 0; t < weather.hours.length; t++) {
    fill(mixer[weather.hours[t].time]);
    noStroke();
    circle(windowWidth / 2, windowHeight / 2, windowHeight / 3.5);
  }
}

function calcWindWave() {
  //change amplitude using windSpeed
  //Increment theta (try different values for 'angular velocity' here)
  theta += 0.02;

  //For every x value, calculate a y value with sine function
  let x = theta;
  let wsAmplitude;

  for (let ws = 0; ws < weather.hours.length; ws++) {
    wsAmplitude = weather.hours[ws].windSpeed * amplitude;
    for (i = 0; i < yvalues.length; i++) {
      yvalues[i] = sin(x) * wsAmplitude;
      x += dx;
    }
  }
}

function calcWaveWave() {
  //change amplitude using waveHeight
  //Increment theta (try different values for 'angular velocity' here)
  theta += 0.05;

  // For every x value, calculate a y value with sine function
  let x = theta;
  let whAmplitude;

  for (let wh = 0; wh < weather.hours.length; wh++) {
    whAmplitude = weather.hours[wh].waveHeight * amplitude;
    for (let i = 0; i < yvalues.length; i++) {
      yvalues[i] = sin(x) * whAmplitude;
      x += dx;
    }
  }
}

function renderWindWave() {
  noStroke();
  fill(255);
  //A simple way to draw the wave with an ellipse at each location
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 + yvalues[x], 3, 3);
  }
}

function renderWaveWave() {
  noStroke();
  fill(255);
  //A simple way to draw the wave with an ellipse at each location
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 - yvalues[x], 3, 3);
    print(yvalues.x);
  }
}

function preload() {
  weather = {
    "hours": [{
        "airTemperature": 27.65,
        "humidity": 70.8,
        "time": 0,
        "waterTemperature": 29.28,
        "waveHeight": 1.62,
        "windSpeed": 3.26
      },
      {
        "airTemperature": 27.67,
        "humidity": 70.9,
        "time": 1,
        "waterTemperature": 29.35,
        "waveHeight": 1.7,
        "windSpeed": 3.1
      },
      {
        "airTemperature": 27.7,
        "humidity": 71,
        "time": 2,
        "waterTemperature": 29.31,
        "waveHeight": 1.78,
        "windSpeed": 2.94
      },
      {
        "airTemperature": 27.72,
        "humidity": 71.1,
        "time": 3,
        "waterTemperature": 29.14,
        "waveHeight": 1.86,
        "windSpeed": 2.78
      },
      {
        "airTemperature": 27.67,
        "humidity": 71.8,
        "time": 4,
        "waterTemperature": 28.93,
        "waveHeight": 1.86,
        "windSpeed": 2.65
      },
      {
        "airTemperature": 27.62,
        "humidity": 72.5,
        "time": 5,
        "waterTemperature": 28.8,
        "waveHeight": 1.86,
        "windSpeed": 2.53
      },
      {
        "airTemperature": 27.57,
        "humidity": 73.2,
        "time": 6,
        "waterTemperature": 28.7,
        "waveHeight": 1.86,
        "windSpeed": 2.4
      },
      {
        "airTemperature": 27.47,
        "humidity": 73.51,
        "time": 7,
        "waterTemperature": 28.63,
        "waveHeight": 1.85,
        "windSpeed": 2.24
      },
      {
        "airTemperature": 27.38,
        "humidity": 73.82,
        "time": 8,
        "waterTemperature": 28.58,
        "waveHeight": 1.83,
        "windSpeed": 2.09
      },
      {
        "airTemperature": 27.28,
        "humidity": 74.13,
        "time": 9,
        "waterTemperature": 28.54,
        "waveHeight": 1.82,
        "windSpeed": 1.93
      },
      {
        "airTemperature": 27.19,
        "humidity": 74.1,
        "time": 10,
        "waterTemperature": 28.51,
        "waveHeight": 1.8,
        "windSpeed": 1.83
      },
      {
        "airTemperature": 27.11,
        "humidity": 74.06,
        "time": 11,
        "waterTemperature": 28.48,
        "waveHeight": 1.78,
        "windSpeed": 1.74
      },
      {
        "airTemperature": 27.02,
        "humidity": 74.03,
        "time": 12,
        "waterTemperature": 28.46,
        "waveHeight": 1.76,
        "windSpeed": 1.64
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.98,
        "time": 13,
        "waterTemperature": 28.45,
        "waveHeight": 1.74,
        "windSpeed": 1.69
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.94,
        "time": 14,
        "waterTemperature": 28.43,
        "waveHeight": 1.72,
        "windSpeed": 1.74
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.89,
        "time": 15,
        "waterTemperature": 28.42,
        "waveHeight": 1.7,
        "windSpeed": 1.79
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.01,
        "time": 16,
        "waterTemperature": 28.42,
        "waveHeight": 1.69,
        "windSpeed": 1.92
      },
      {
        "airTemperature": 27.03,
        "humidity": 72.13,
        "time": 17,
        "waterTemperature": 28.42,
        "waveHeight": 1.67,
        "windSpeed": 2.04
      },
      {
        "airTemperature": 27.04,
        "humidity": 71.25,
        "time": 18,
        "waterTemperature": 28.54,
        "waveHeight": 1.66,
        "windSpeed": 2.17
      },
      {
        "airTemperature": 27.09,
        "humidity": 70.52,
        "time": 19,
        "waterTemperature": 28.74,
        "waveHeight": 1.65,
        "windSpeed": 2.35
      },
      {
        "airTemperature": 27.15,
        "humidity": 69.8,
        "time": 20,
        "waterTemperature": 29.04,
        "waveHeight": 1.65,
        "windSpeed": 2.53
      },
      {
        "airTemperature": 27.21,
        "humidity": 69.08,
        "time": 21,
        "waterTemperature": 29.39,
        "waveHeight": 1.64,
        "windSpeed": 2.71
      },
      {
        "airTemperature": 27.32,
        "humidity": 71.12,
        "time": 22,
        "waterTemperature": 29.72,
        "waveHeight": 1.63,
        "windSpeed": 3.23
      },
      {
        "airTemperature": 27.44,
        "humidity": 73.16,
        "time": 23,
        "waterTemperature": 30,
        "waveHeight": 1.63,
        "windSpeed": 3.74
      }
    ],
    "meta": {
      "cost": 1,
      "dailyQuota": 50,
      "end": "2018-07-01 23:59",
      "lat": 9.933917,
      "lng": -132.038444,
      "params": [
        "airTemperature",
        "humidity",
        "waterTemperature",
        "waveHeight",
        "windSpeed"
      ],
      "requestCount": 3,
      "source": "sg",
      "start": "2018-07-01 00:00"
    }
  };
}

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

Body:
You (like many others) have missed out the structural concept of p5 library. Among other structural functions draw() is looping forever (unless you stop it) so you don't want to create own loops inside of it.
Although I dont understand what the desirable result should be, i'll throw you some guidelines:

let clicked=false;  //this is for start/stop animation
let weather;

let xspacing = 15; // Distance between each horizontal location
let waveWidth; // Width of entire wave
let theta = 0.0; // Start angle at 0
let amplitude = 25; // Height of wave
let period = 1000.0; // How many pixels before the wave repeats
let dx; // Value for incrementing x
let yvalues; // Using an array to store height values for the wave

/* counters from inner loops */
let t = w = h = a = 0;

/* all the looping variables */
let warmth,
 upper,
 lower,
 start,
 mid,
 end;
/* array */
let mixer = [];

 /*******************************************************************
* P5 preload
*
* Load images, data etc. Waits for any async is ended.
********************************************************************/
function preload() {
  weather = {
    "hours": [{
        "airTemperature": 27.65,
        "humidity": 70.8,
        "time": 0,
        "waterTemperature": 29.28,
        "waveHeight": 1.62,
        "windSpeed": 3.26
      },
      {
        "airTemperature": 27.67,
        "humidity": 70.9,
        "time": 1,
        "waterTemperature": 29.35,
        "waveHeight": 1.7,
        "windSpeed": 3.1
      },
      {
        "airTemperature": 27.7,
        "humidity": 71,
        "time": 2,
        "waterTemperature": 29.31,
        "waveHeight": 1.78,
        "windSpeed": 2.94
      },
      {
        "airTemperature": 27.72,
        "humidity": 71.1,
        "time": 3,
        "waterTemperature": 29.14,
        "waveHeight": 1.86,
        "windSpeed": 2.78
      },
      {
        "airTemperature": 27.67,
        "humidity": 71.8,
        "time": 4,
        "waterTemperature": 28.93,
        "waveHeight": 1.86,
        "windSpeed": 2.65
      },
      {
        "airTemperature": 27.62,
        "humidity": 72.5,
        "time": 5,
        "waterTemperature": 28.8,
        "waveHeight": 1.86,
        "windSpeed": 2.53
      },
      {
        "airTemperature": 27.57,
        "humidity": 73.2,
        "time": 6,
        "waterTemperature": 28.7,
        "waveHeight": 1.86,
        "windSpeed": 2.4
      },
      {
        "airTemperature": 27.47,
        "humidity": 73.51,
        "time": 7,
        "waterTemperature": 28.63,
        "waveHeight": 1.85,
        "windSpeed": 2.24
      },
      {
        "airTemperature": 27.38,
        "humidity": 73.82,
        "time": 8,
        "waterTemperature": 28.58,
        "waveHeight": 1.83,
        "windSpeed": 2.09
      },
      {
        "airTemperature": 27.28,
        "humidity": 74.13,
        "time": 9,
        "waterTemperature": 28.54,
        "waveHeight": 1.82,
        "windSpeed": 1.93
      },
      {
        "airTemperature": 27.19,
        "humidity": 74.1,
        "time": 10,
        "waterTemperature": 28.51,
        "waveHeight": 1.8,
        "windSpeed": 1.83
      },
      {
        "airTemperature": 27.11,
        "humidity": 74.06,
        "time": 11,
        "waterTemperature": 28.48,
        "waveHeight": 1.78,
        "windSpeed": 1.74
      },
      {
        "airTemperature": 27.02,
        "humidity": 74.03,
        "time": 12,
        "waterTemperature": 28.46,
        "waveHeight": 1.76,
        "windSpeed": 1.64
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.98,
        "time": 13,
        "waterTemperature": 28.45,
        "waveHeight": 1.74,
        "windSpeed": 1.69
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.94,
        "time": 14,
        "waterTemperature": 28.43,
        "waveHeight": 1.72,
        "windSpeed": 1.74
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.89,
        "time": 15,
        "waterTemperature": 28.42,
        "waveHeight": 1.7,
        "windSpeed": 1.79
      },
      {
        "airTemperature": 27.02,
        "humidity": 73.01,
        "time": 16,
        "waterTemperature": 28.42,
        "waveHeight": 1.69,
        "windSpeed": 1.92
      },
      {
        "airTemperature": 27.03,
        "humidity": 72.13,
        "time": 17,
        "waterTemperature": 28.42,
        "waveHeight": 1.67,
        "windSpeed": 2.04
      },
      {
        "airTemperature": 27.04,
        "humidity": 71.25,
        "time": 18,
        "waterTemperature": 28.54,
        "waveHeight": 1.66,
        "windSpeed": 2.17
      },
      {
        "airTemperature": 27.09,
        "humidity": 70.52,
        "time": 19,
        "waterTemperature": 28.74,
        "waveHeight": 1.65,
        "windSpeed": 2.35
      },
      {
        "airTemperature": 27.15,
        "humidity": 69.8,
        "time": 20,
        "waterTemperature": 29.04,
        "waveHeight": 1.65,
        "windSpeed": 2.53
      },
      {
        "airTemperature": 27.21,
        "humidity": 69.08,
        "time": 21,
        "waterTemperature": 29.39,
        "waveHeight": 1.64,
        "windSpeed": 2.71
      },
      {
        "airTemperature": 27.32,
        "humidity": 71.12,
        "time": 22,
        "waterTemperature": 29.72,
        "waveHeight": 1.63,
        "windSpeed": 3.23
      },
      {
        "airTemperature": 27.44,
        "humidity": 73.16,
        "time": 23,
        "waterTemperature": 30,
        "waveHeight": 1.63,
        "windSpeed": 3.74
      }
    ],
    "meta": {
      "cost": 1,
      "dailyQuota": 50,
      "end": "2018-07-01 23:59",
      "lat": 9.933917,
      "lng": -132.038444,
      "params": [
        "airTemperature",
        "humidity",
        "waterTemperature",
        "waveHeight",
        "windSpeed"
      ],
      "requestCount": 3,
      "source": "sg",
      "start": "2018-07-01 00:00"
    }
  }
}

/*******************************************************************
* P5 setup
* run once, use for initialisation.
*
* Create a canvas, show pictures, initialize arrays etc.
********************************************************************/
function setup() {
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB);

  waveWidth = width + 16;
  dx = (TWO_PI / period) * xspacing;
  yvalues = new Array(floor(waveWidth / xspacing));

 /*
  *  all the colors and mixer[] array should be
  *  initialized here as their values are not changed
  */
   warmth = color(50, 100, 100); //rgb 255, 215, 0
   upper = color(0, 100, 65); //rgb 165, 0, 0
   lower = color(234, 100, 31); //rgb 0, 8, 80

   start = color(50, 2, 100); //rgb 255, 254, 249
   mid = color(50, 100, 100); //rgb 255, 212, 0
   end = color(49, 100, 13); //rbg 33, 27, 0

  mixer[0] = start;
  mixer[1] = lerpColor(start, mid, 0.099);
  mixer[2] = lerpColor(start, mid, 0.198);
  mixer[3] = lerpColor(start, mid, 0.297);
  mixer[4] = lerpColor(start, mid, 0.396);
  mixer[5] = lerpColor(start, mid, 0.495);
  mixer[6] = lerpColor(start, mid, 0.594);
  mixer[7] = lerpColor(start, mid, 0.693);
  mixer[8] = lerpColor(start, mid, 0.792);
  mixer[9] = lerpColor(start, mid, 0.891);
  mixer[10] = lerpColor(start, mid, 0.99);
  mixer[11] = mid;
  mixer[12] = lerpColor(mid, end, 0.099);
  mixer[13] = lerpColor(mid, end, 0.198);
  mixer[14] = lerpColor(mid, end, 0.297);
  mixer[15] = lerpColor(mid, end, 0.396);
  mixer[16] = lerpColor(mid, end, 0.495);
  mixer[17] = lerpColor(mid, end, 0.594);
  mixer[18] = lerpColor(mid, end, 0.693);
  mixer[19] = lerpColor(mid, end, 0.792);
  mixer[20] = lerpColor(mid, end, 0.891);
  mixer[21] = lerpColor(mid, end, 0.95);
  mixer[22] = lerpColor(mid, end, 0.99);
  mixer[23] = end;

/* here you can change the speed of the animation */
  frameRate(3);
}

/*******************************************************************
* P5 draw
* endless loop.
*
* Do something visual with collected data.
* NB! This is already endless loop, do not create loops into it
********************************************************************/
function draw() {
  //background colour of canvas
  background(0, 28, 122);

  fill(0, 100, 65);
  noStroke();
  rect(0, 0, windowWidth, windowHeight / 2);

/* we are looping already, so you use variable a ... */
  //  for (let a = 0; a < weather.hours.length; a++) {
    fill(47, 100, 100, (weather.hours[a].airTemperature - 27) / 10);
    noStroke();
    rect(0, 0, windowWidth, windowHeight / 2);
/* ... and increase its value for the next loop */
  a++;
//  }

  fill(234, 100, 31);
  noStroke();
  rect(0, windowHeight / 2, windowWidth, windowHeight / 2);
//  for (let w = 0; w < weather.hours.length; w++) {
    fill(47, 100, 100, (weather.hours[w].waterTemperature - 28) / 20);
    noStroke();
    rect(0, windowHeight / 2, windowWidth, windowHeight / 2);
 w++;
//  }

  //translucent circles with random sizes to form on random locations

//  for (let h = 0; h > weather.hours.length; h++) {
    let humidityCircle = weather.hours[h].humidity;
    for (let hc = 0; hc < humidityCircle; hc++) {
      fill(255, 255, 255, 127.5);
      noStroke();
      ellipse(random(windowWidth), random(windowHeight / 2), random((windowWidth / 18) + 15));
    }
 h++;
//  }

  calcWindWave();
  renderWindWave();

  calcWaveWave();
  renderWaveWave();

  //middle large circle
//  for (let t = 0; t < weather.hours.length; t++) {
    fill(mixer[weather.hours[t].time]);
    noStroke();
    ellipse(windowWidth / 2, windowHeight / 2, windowHeight / 3.5);
 t++;
//  }

/* Also we have to check/change our counters
*  At this case all the counters will be initialized under same condition
*/
if(t>23)
 a = w = t = h = 0;
}

function calcWindWave() {
  //change amplitude using windSpeed
  //Increment theta (try different values for 'angular velocity' here)
  theta += 0.02;

  //For every x value, calculate a y value with sine function
  let x = theta;
  let wsAmplitude;

  for (let ws = 0; ws < weather.hours.length; ws++) {
    wsAmplitude = weather.hours[ws].windSpeed * amplitude;
    for (i = 0; i < yvalues.length; i++) {
      yvalues[i] = sin(x) * wsAmplitude;
      x += dx;
    }
  }
}

function calcWaveWave() {
  //change amplitude using waveHeight
  //Increment theta (try different values for 'angular velocity' here)
  theta += 0.05;

  // For every x value, calculate a y value with sine function
  let x = theta;
  let whAmplitude;

  for (let wh = 0; wh < weather.hours.length; wh++) {
    whAmplitude = weather.hours[wh].waveHeight * amplitude;
    for (let i = 0; i < yvalues.length; i++) {
      yvalues[i] = sin(x) * whAmplitude;
      x += dx;
    }
  }
}

function renderWindWave() {
  noStroke();
  fill(255);
  //A simple way to draw the wave with an ellipse at each location
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 + yvalues[x], 3, 3);
  }
}

function renderWaveWave() {
  noStroke();
  fill(255);
  //A simple way to draw the wave with an ellipse at each location
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 - yvalues[x], 3, 3);
//    print(yvalues.x);
  }
}
/*******************************************************************
* P5 mouseClicked
*
* P5 event. I use it to start/stop the animation
********************************************************************/
mouseClicked = function() {
    if (mouseButton === LEFT) {
  clicked = !clicked;
  if(clicked){
   noLoop();
  }else{
   loop();
  }
    }
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>


来源: stackexchange

问:
Appium desktop app test throws element could not be located exception, but passes when the app is launched before the test runs
I'm trying to learn Appium and using it for WPF application testing. Tests against Calculator or Notepad are running fine, but recently I've encountered a problem when trying to test custom WPF application.

Appium desktop app tests throw "An element could not be located on the page using the given search parameters" exception, but pass without problems when app is launched before test run. So I guess that my Setup/Init phase is somehow incorrect but I don't know why.

Error occurs when the test is run without the app launched first (so when the SetUp phase has to launch the app).
Test passes when the app is started before test run, or even when it is left open from previous failed test run.

App launch takes about 10 to 15 second, during which at first slash screen shows up, and then the main window of the application.

Appium.WebDriver nuget packege is used in the project, version 3.0.0.2

I've tried Thread.Sleep for 30 seconds, but it doesn't resolve the issue.

```<code>[TestFixture]
public class DesktopAppSession
{
    protected WindowsDriver<WindowsElement> _session;
    protected const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
    protected const string AppId = @"<path to app.exe>";

    [SetUp]
    public void TestInit()
    {
        if (_session != null)
            return;

        var appCapabilities = new DesiredCapabilities();
        appCapabilities.SetCapability("app", AppId);
        appCapabilities.SetCapability("deviceName", "WindowsPC");
        _session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);

        Assert.IsNotNull(_session);

        Thread.Sleep(TimeSpan.FromSeconds(30));

        _session.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
    }

    [TearDown]
    public void TestCleanup()
    {
        if (_session != null)
        {
            _session.Quit();
            _session = null;
        }
    }

    [Test]
    public void UserInfoModalShowsUp()
    {
        var userInfoButtonAName = "UserInfoButtonAName";
        var userInfoButtonId = "UserInfoButtonAID";

        var userInfoButton = _session.FindElementByAccessibilityId(userInfoButtonId);

        Assert.True(userInfoButton != null);

        userInfoButton.Click();

        var userDetailsTitleLabel = _session.FindElementByName("User details");

        userDetailsTitleLabel?.Click();

        Assert.True(true);
    }
}
</code>```

Exception message:

System.InvalidOperationException
  HResult=0x80131509
  Message=An element could not be located on the page using the given search parameters.
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Appium.AppiumDriver1.FindElement(String by, String value)

Log from WinAppDriver:

"POST /session/23293B57-F396-47CC-83EF-FCA491E269B0/element HTTP/1.1
Accept: application/json, image/png
Content-Length: 56
Content-Type: application/json;charset=utf-8
Host: 127.0.0.1:4723

{"using":"accessibility id","value":"UserInfoButtonAID"}
HTTP/1.1 404 Not Found
Content-Length: 139
Content-Type: application/json

{"status":7,"value":{"error":"no such element","message":"An element could not be located on the page using the given search parameters."}}"

答:
You will most likely need to switch the window handle to the correct one.

Winappdriver uses window handles for top level windows. Most likely, your splashscreen will be a top level window, and your actual application will also be a top level window.
So winappdriver will have at least 2 window handles. Your driver (_session in your case) has a property called WindowHandles which contains a list of window handles. These handles get added chronologically, so the most recent handle (the one from your application) should be the last window handle.

This example shows you how to switch window handles:

```<code>if (_session.CurrentWindowHandle != _session.WindowHandles.Last())
{
    _session.SwitchTo().Window(_session.WindowHandles.Last());
}
</code>```

You can also verify if you have the correct window handle by checking the page source property from your driver like this: _session.PageSource;. The page source is a xml representation of the current selected window handle. You can put it in the Visual Studio watch and copy over the xml to a xml formatter utility program for readability.

Additional information about the splash screen problem and alternative ways to fix it, can be found here.
Be sure to check the answers from user timotiusmargo.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to learn Appium and using it for WPF application testing. Tests against Calculator or Notepad are running fine, but recently I've encountered a problem when trying to test custom WPF application.

Appium desktop app tests throw "An element could not be located on the page using the given search parameters" exception, but pass without problems when app is launched before test run. So I guess that my Setup/Init phase is somehow incorrect but I don't know why.

Error occurs when the test is run without the app launched first (so when the SetUp phase has to launch the app).
Test passes when the app is started before test run, or even when it is left open from previous failed test run.

App launch takes about 10 to 15 second, during which at first slash screen shows up, and then the main window of the application.

Appium.WebDriver nuget packege is used in the project, version 3.0.0.2

I've tried Thread.Sleep for 30 seconds, but it doesn't resolve the issue.

[TestFixture]
public class DesktopAppSession
{
    protected WindowsDriver<WindowsElement> _session;
    protected const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
    protected const string AppId = @"<path to app.exe>";

    [SetUp]
    public void TestInit()
    {
        if (_session != null)
            return;

        var appCapabilities = new DesiredCapabilities();
        appCapabilities.SetCapability("app", AppId);
        appCapabilities.SetCapability("deviceName", "WindowsPC");
        _session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);

        Assert.IsNotNull(_session);

        Thread.Sleep(TimeSpan.FromSeconds(30));

        _session.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
    }

    [TearDown]
    public void TestCleanup()
    {
        if (_session != null)
        {
            _session.Quit();
            _session = null;
        }
    }

    [Test]
    public void UserInfoModalShowsUp()
    {
        var userInfoButtonAName = "UserInfoButtonAName";
        var userInfoButtonId = "UserInfoButtonAID";

        var userInfoButton = _session.FindElementByAccessibilityId(userInfoButtonId);

        Assert.True(userInfoButton != null);

        userInfoButton.Click();

        var userDetailsTitleLabel = _session.FindElementByName("User details");

        userDetailsTitleLabel?.Click();

        Assert.True(true);
    }
}

Exception message:

System.InvalidOperationException
  HResult=0x80131509
  Message=An element could not be located on the page using the given search parameters.
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Appium.AppiumDriver1.FindElement(String by, String value)

Log from WinAppDriver:

"POST /session/23293B57-F396-47CC-83EF-FCA491E269B0/element HTTP/1.1
Accept: application/json, image/png
Content-Length: 56
Content-Type: application/json;charset=utf-8
Host: 127.0.0.1:4723

{"using":"accessibility id","value":"UserInfoButtonAID"}
HTTP/1.1 404 Not Found
Content-Length: 139
Content-Type: application/json

{"status":7,"value":{"error":"no such element","message":"An element could not be located on the page using the given search parameters."}}"

Body:
You will most likely need to switch the window handle to the correct one.

Winappdriver uses window handles for top level windows. Most likely, your splashscreen will be a top level window, and your actual application will also be a top level window.
So winappdriver will have at least 2 window handles. Your driver (_session in your case) has a property called WindowHandles which contains a list of window handles. These handles get added chronologically, so the most recent handle (the one from your application) should be the last window handle.

This example shows you how to switch window handles:

if (_session.CurrentWindowHandle != _session.WindowHandles.Last())
{
    _session.SwitchTo().Window(_session.WindowHandles.Last());
}

You can also verify if you have the correct window handle by checking the page source property from your driver like this: _session.PageSource;. The page source is a xml representation of the current selected window handle. You can put it in the Visual Studio watch and copy over the xml to a xml formatter utility program for readability.

Additional information about the splash screen problem and alternative ways to fix it, can be found here.
Be sure to check the answers from user timotiusmargo.


问:
Read data from memory
I have an API to read data:

ROM_READ_PAGE(BLOCK_NO, PAGE_NO, *READ_BUFFER);

The Page size is 2048 and you can ONLY read WHOLE page at a time.

I know it is just about using C, but my system doesn't run using either of the methods I tried.

For example:

```<code>char *readPtr;
char readBuff[128]; //(Can not use 2048 due to stack overflow)

readPtr = readBuff;

ROM_READ_PAGE(BLOCK_NO, PAGE_NO, readPtr); // SMX doesn't like this and shows some exception
</code>```

Any other idea or if I am missing something important.

答:
You can dynamically allocate the buffer and avoid the stack overflow. you will also need to free the buffer</p>

```<code>char *readBuff;
readBuff = (char *) malloc(2048);
free(readBuff);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Read data from memory

Body:
I have an API to read data:

ROM_READ_PAGE(BLOCK_NO, PAGE_NO, *READ_BUFFER);

The Page size is 2048 and you can ONLY read WHOLE page at a time.

I know it is just about using C, but my system doesn't run using either of the methods I tried.

For example:

char *readPtr;
char readBuff[128]; //(Can not use 2048 due to stack overflow)

readPtr = readBuff;

ROM_READ_PAGE(BLOCK_NO, PAGE_NO, readPtr); // SMX doesn't like this and shows some exception

Any other idea or if I am missing something important.

Body:
You can dynamically allocate the buffer and avoid the stack overflow. you will also need to free the buffer

char *readBuff;
readBuff = (char *) malloc(2048);
free(readBuff);


问:
How to find iOS elements with a Appium Java Client?
Can't seem to either find the right element or I am trying to coerce the returned element into the wrong type. Looking for the correct syntax to find a button to tap it. I am working with an iOS simulator build, Appium, running test with a Java Client.

AppTest.Java

  @Test (enabled=true) public void myFirstTest() throws InterruptedException {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

**IOSElement button = driver.findElement(MobileBy.AccessibilityId("UIA_upsellPage_third_button"));**
```

<h1>Output</h1>

```org.openqa.selenium.WebDriverException: Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=28000000-0000-0000-61D4-000000000000, ELEMENT=28000000-0000-0000-61D4-000000000000}
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'C02R91M5G8WLMBP', ip: '2601:645:8002:1391:0:0:0:5d42%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.6', java.version: '12.0.1'
Driver info: driver.version: IOSDriver
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:378)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:62)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at io.appium.java_client.FindsByAccessibilityId.findElementByAccessibilityId(FindsByAccessibilityId.java:31)
    at io.appium.java_client.MobileBy$ByAccessibilityId.findElement(MobileBy.java:288)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:58)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at com.media.automation.iphone_automation_1.AppTest.myFirstTest(AppTest.java:70)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.ClassCastException: class java.util.HashMap cannot be cast to class org.openqa.selenium.WebElement (java.util.HashMap is in module java.base of loader 'bootstrap'; org.openqa.selenium.WebElement is in unnamed module of loader 'app')
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:376)
    ... 35 more
```

Expected Result:
Should return an element that can be tapped with a method to mimic a button press.

Actual Result: org.openqa.selenium.WebDriverException: Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=28000000-0000-0000-61D4-000000000000, ELEMENT=28000000-0000-0000-61D4-000000000000}

答:
Most likely your client is out of date.

Make sure you use the latest stable appium-java-client library, which is 7.0.0

And do not include selenium-java dependency explicitly, it is already coming in Appium.

And double check the Appium server version, 1.13.0 has been recently released.

Body:
Can't seem to either find the right element or I am trying to coerce the returned element into the wrong type. Looking for the correct syntax to find a button to tap it. I am working with an iOS simulator build, Appium, running test with a Java Client.

AppTest.Java

  @Test (enabled=true) public void myFirstTest() throws InterruptedException {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

**IOSElement button = driver.findElement(MobileBy.AccessibilityId("UIA_upsellPage_third_button"));**

Output

org.openqa.selenium.WebDriverException: Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=28000000-0000-0000-61D4-000000000000, ELEMENT=28000000-0000-0000-61D4-000000000000}
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: 'C02R91M5G8WLMBP', ip: '2601:645:8002:1391:0:0:0:5d42%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.6', java.version: '12.0.1'
Driver info: driver.version: IOSDriver
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:378)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:62)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at io.appium.java_client.FindsByAccessibilityId.findElementByAccessibilityId(FindsByAccessibilityId.java:31)
    at io.appium.java_client.MobileBy$ByAccessibilityId.findElement(MobileBy.java:288)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:58)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at com.media.automation.iphone_automation_1.AppTest.myFirstTest(AppTest.java:70)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.ClassCastException: class java.util.HashMap cannot be cast to class org.openqa.selenium.WebElement (java.util.HashMap is in module java.base of loader 'bootstrap'; org.openqa.selenium.WebElement is in unnamed module of loader 'app')
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:376)
    ... 35 more

Expected Result:
Should return an element that can be tapped with a method to mimic a button press.

Actual Result: org.openqa.selenium.WebDriverException: Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=28000000-0000-0000-61D4-000000000000, ELEMENT=28000000-0000-0000-61D4-000000000000}


问:
Compare two files and create a new one with the differences
I need to compare two files and create a new one with the differences of this two, i just know compare the files to show if they are equal or not, but i dont know how can i solve my problem.

I search so much info on how to compare files, but i didnt found the way of display the differences between this two files. This is my actual code.

Edit: The file can contain more than 1 line of data, usually like 30.

The text cannot be deleted, and the similarity just appear in the end of the text. I mean, the final line of a file text will be always the start of the other file text.

This is for homework and the instruction are: "Read the host file and check if any line is already present in the ip url file, and in case they are not, it is necessary to write them in a temporary file."

```<code>#include <stdio.h>
void main()
{
FILE *f1, *f2;
int a, b;

f1 = fopen("D:\\product3\\test.txt","r");
f2 = fopen("D:\\product3\\test2.txt", "r");

if(f1 == NULL || f2 == NULL)
{
    printf("Cannot read the files");
}
else
{
    a = getc(f1);
    b = getc(f2);

    while (a != EOF && b != EOF)
    {
        a = getc(f1);
        b = getc(f2);

        if(a != b)
        {
            printf("");
        }
    }
    if (a == b)
    {
        printf("\n The files are equal \n");
    }
    else if (a!=b)
    {
        printf("\n The files aren't equal \n");
    }
    else
    {
        printf("\n Error \n");
    }
}

fclose(f1);
fclose(f2);
}
</code>```

The content of the files are:

```
>Test.txt
AAA
aaa
bbb
BBB
111

>Test2.txt
AAA
aaa
bbb
BBB
111
333
444
555
6666
777
CCC
```

so the output must be:

```
>333
444
555
6666
777
CCC
```

答:
This is the code that i finally used.</p>

```<code>void CheckContent(char dir[100])
{

FILE *f1, *f2,*f3;
int a, b;
char dir2[100];
char temporal[100];

strcpy (temporal,"D:\\producto3\\temporal.txt");

printf("\nIntroduce la ruta del archivo donde estan los pares a leer.\n");
scanf("%s", &dir2);

f1 = fopen(dir, "r");
f2 = fopen(dir2, "r");
f3 = fopen(temporal, "w");

if (f1 == NULL || f2 == NULL)
{
    printf("No se puede leer alguno de los ficheros");
}

else
{
    char pairLine[256];
    f2 = fopen("D:\\producto3\\pares.txt", "r");

    while (fgets(pairLine, sizeof(pairLine), f2))
    {
        char hostLine[256];
        f1 = fopen("D:\\producto3\\hosts", "r");
        int counter = 0;
        while (fgets(hostLine, sizeof(hostLine), f1))
        {
            if (hostLine[0] != '#')
            {
                if (strcmp(pairLine, hostLine) == 0)
                {
                    counter++;
                }
            }
        }
        fclose(f1);
        if (counter == 0)
        {
            fputs(pairLine,f3);
        }
    }
    fclose(f3);
    fclose(f2);
}
FilePares(dir,temporal);
}
</code>```

Body:
I need to compare two files and create a new one with the differences of this two, i just know compare the files to show if they are equal or not, but i dont know how can i solve my problem.

I search so much info on how to compare files, but i didnt found the way of display the differences between this two files. This is my actual code.

Edit: The file can contain more than 1 line of data, usually like 30.

The text cannot be deleted, and the similarity just appear in the end of the text. I mean, the final line of a file text will be always the start of the other file text.

This is for homework and the instruction are: "Read the host file and check if any line is already present in the ip url file, and in case they are not, it is necessary to write them in a temporary file."

#include <stdio.h>
void main()
{
FILE *f1, *f2;
int a, b;

f1 = fopen("D:\\product3\\test.txt","r");
f2 = fopen("D:\\product3\\test2.txt", "r");

if(f1 == NULL || f2 == NULL)
{
    printf("Cannot read the files");
}
else
{
    a = getc(f1);
    b = getc(f2);

    while (a != EOF && b != EOF)
    {
        a = getc(f1);
        b = getc(f2);

        if(a != b)
        {
            printf("");
        }
    }
    if (a == b)
    {
        printf("\n The files are equal \n");
    }
    else if (a!=b)
    {
        printf("\n The files aren't equal \n");
    }
    else
    {
        printf("\n Error \n");
    }
}

fclose(f1);
fclose(f2);
}

The content of the files are:

>Test.txt
AAA
aaa
bbb
BBB
111

>Test2.txt
AAA
aaa
bbb
BBB
111
333
444
555
6666
777
CCC

so the output must be:

>333
444
555
6666
777
CCC

Body:
This is the code that i finally used.

void CheckContent(char dir[100])
{

FILE *f1, *f2,*f3;
int a, b;
char dir2[100];
char temporal[100];

strcpy (temporal,"D:\\producto3\\temporal.txt");

printf("\nIntroduce la ruta del archivo donde estan los pares a leer.\n");
scanf("%s", &dir2);

f1 = fopen(dir, "r");
f2 = fopen(dir2, "r");
f3 = fopen(temporal, "w");

if (f1 == NULL || f2 == NULL)
{
    printf("No se puede leer alguno de los ficheros");
}

else
{
    char pairLine[256];
    f2 = fopen("D:\\producto3\\pares.txt", "r");

    while (fgets(pairLine, sizeof(pairLine), f2))
    {
        char hostLine[256];
        f1 = fopen("D:\\producto3\\hosts", "r");
        int counter = 0;
        while (fgets(hostLine, sizeof(hostLine), f1))
        {
            if (hostLine[0] != '#')
            {
                if (strcmp(pairLine, hostLine) == 0)
                {
                    counter++;
                }
            }
        }
        fclose(f1);
        if (counter == 0)
        {
            fputs(pairLine,f3);
        }
    }
    fclose(f3);
    fclose(f2);
}
FilePares(dir,temporal);
}


问:
How to know length of the drop-down list using protractor webdriver?
I am working on a task where I am automating the front end pages. There I need to get the length of the drop-down list but I haven't found any suggestions regarding the same in protractor type script.

My xpath is:

//*[@id=intrestmethod'].

I am getting the drop-down value with below code but I need to know the total drop-down values present in it .

```<code>browser.driver.findelement(xpathvalue).getAttribute('value').then((function(attributevalue){
Console.log(attributevalue);
}):
</code>```

答:
You can use count() method on all available drop-down elements.

Remember that it returns a promise.Promise<number>.

See the documentation:

https://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.count

Body:
I am working on a task where I am automating the front end pages. There I need to get the length of the drop-down list but I haven't found any suggestions regarding the same in protractor type script.

My xpath is:

//*[@id=intrestmethod'].

I am getting the drop-down value with below code but I need to know the total drop-down values present in it .

browser.driver.findelement(xpathvalue).getAttribute('value').then((function(attributevalue){
Console.log(attributevalue);
}):


问:
Expo command is not found ubuntu
I have installed expo with this command - npm install expo-cli -g
but when I am writing expo in command line, is writing that expo in not found.

I have tried to install with yarn and it was installed successful but is writing that expo in not found.

I have tried to export PATH to ~/.profile but this did not help me.

What do I need to do to make my expo project?

答:
If it is installed, expo might not be in your PATH.

Check if npm global is in your path. $ echo $PATH,

if not in your path add npm global to your path.

get the path of your global npm npm config get prefix

add the output of the above command to your .bashrc or .zshrc file.

```<code># replace npm-global-path with the output of npm config get prefix
export PATH=npm-global-path/bin:$PATH
</code>```

then

```<code># source your .bashrc, .zshr or *.profile
source ~/.bashrc or source ~/.zshrc
</code>```

Environment variables in bash_profile or bashrc?

Title: Expo command is not found ubuntu

Body:
If it is installed, expo might not be in your PATH.

Check if npm global is in your path. $ echo $PATH,

if not in your path add npm global to your path.

get the path of your global npm npm config get prefix

add the output of the above command to your .bashrc or .zshrc file.

# replace npm-global-path with the output of npm config get prefix
export PATH=npm-global-path/bin:$PATH

then

# source your .bashrc, .zshr or *.profile
source ~/.bashrc or source ~/.zshrc

Environment variables in bash_profile or bashrc?


问:
Incorrect syntax near 'as' when added calculated column
I need to add a calculated column from 2 other columns in the same table but I have this error "Incorrect syntax near 'as'."

```<code>alter table [test].[S937] add [new col] as ([col a] * [col b])
</code>```

I have full rights on the database.

When I try to add the column "empty" it works, values are all NULL :

```<code>alter table [test].[S937] add [new col] varchar(9)
</code>```

The table was created by multiple joins and works absolutely fine.

```<code>SELECT table1.col1 AS [namecol1], table2[col2] as [namecol2], table3[col3] as [namecol3] into test.S937 FROM table1 INNER JOIN (SELECT...) LEFT JOIN (SELECT...) UNION
</code>```

答:
It's working. Here.

But you can also create the column first, and update it next.

Body:
I need to add a calculated column from 2 other columns in the same table but I have this error "Incorrect syntax near 'as'."

alter table [test].[S937] add [new col] as ([col a] * [col b])

I have full rights on the database.

When I try to add the column "empty" it works, values are all NULL :

alter table [test].[S937] add [new col] varchar(9)

The table was created by multiple joins and works absolutely fine.

SELECT table1.col1 AS [namecol1], table2[col2] as [namecol2], table3[col3] as [namecol3] into test.S937 FROM table1 INNER JOIN (SELECT...) LEFT JOIN (SELECT...) UNION


问:
Amazon SimpleDB & DynamoDB for storing blog posts
Consider a simple blog post schema has the following columns

```<code>ID
Author
Category
Status
CreatedDateTime
UpdatedDateTime
</code>```

So assume the following queries

query by ID

query by Author, paginated

query by (Author, Status), sorted by CreatedDateTime, paginated

query by (Category, Status), sorted by CreatedDateTime, paginated

So seems without doing much works, SimpleDB would be more easy to implement the codes?

答:
You should use DynamoDB because it has a lot of useful features such as Point in Time Recovery, transactions, encryption-at-rest, and activity streams that SimpleDB does not have.

If you're operating on a small scale, DynamoDB has the advantage that it allows you to set a maximum capacity for your table, which means you can make sure you stay in the free tier.

If you're operating at a larger scale, DynamoDB automatically handles all of the partitioning of your data (and has, for all practical purposes, limitless capacity), whereas SimpleDB has a limit of 10 GB per domain (aka "table") and you are required to manage any horizontal partitioning across domains that you might need.

Finally, there are signs that SimpleDB is already on a deprecation path. For example, if you look at the SimpleDB release notes, you will see that the last update was in 2011, whereas DynamoDB had several new features announced at the last re:Invent conference. Also, there are a number of reddit posts (such as here, here, and here) where the general consensus is that SimpleDB is already deprecated, and in some of the threads, Jeff Barr even commented and did not contradict any of the assertions that SimpleDB is deprecated.

That being said, in DynamoDB, you can support your desired queries.
You will need two Global Secondary Indexes, which use a composite sort key. Your queries can be supported with the following schema:

ID — hash key of your table

Author — hash key of the Author-Status-CreatedDateTime-index

Category — hash key of the Category-Status-CreatedDateTime-index

Status

CreatedDateTime

UpdatedDateTime

Status-CreatedDateTime — sort key of Author-Status-CreatedDateTime-index and Category-Status-CreatedDateTime-index. This is a composite attribute that exists to enable some of your queries. It is simply the value of Status with a separator character (I'll assume it's # for the rest of this answer), and CreatedDateTime appended to the end. (Personal opinion here: use ISO-8601 timestamps instead of unix timestamps. It will make troubleshooting a lot easier.)

Using this schema, you can satisfy all of your queries.

query by ID:
Simply perform a GetItem request on the main table using the blog post Id.

query by Author, paginated:
Perform a Query on the Author-Status-CreatedDateTime-index with a key condition expression of Author = :author.

query by (Author, Status), sorted by CreatedDateTime, paginated:
Perform a Query on the Author-Status-CreatedDateTime-index with a key condition expression of Author = :author and begins_with(Status-CreatedDateTime, :status). The results will be returned in order of ascending CreatedDateTime.

query by (Category, Status), sorted by CreatedDateTime, paginated:
Perform a Query on the Category-Status-CreatedDateTime-index with a key condition expression of Author = :author and begins_with(Status-CreatedDateTime, :status). The results will be returned in order of ascending CreatedDateTime. (Additionally, if you wanted to get all the blog posts in the "technology" category that have the status published and were created in 2019, you could use a key condition expression of Category = "technology" and begins_with(Status-CreatedDateTime, "published#2019").

The sort order of the results can be controlled using the ScanIndexForward field of the Query request. The default is true (sort ascending); but by setting it to false DynamoDB will return results in descending order.

DynamoDB has built in support for paginating the results of a Query operation. Basically, any time that there are more results that were not returned, the query response will contain a lastEvaluatedKey which you can pass into your next query request to pick up where you left off. (See Query Pagination for more details about how it works.)

On the other hand, if you're already familiar with SQL, and you want to make this as easy for yourself as possible, consider just using the Aurora Serverless Data API.

Body:
Consider a simple blog post schema has the following columns

ID
Author
Category
Status
CreatedDateTime
UpdatedDateTime

So assume the following queries

query by ID

query by Author, paginated

query by (Author, Status), sorted by CreatedDateTime, paginated

query by (Category, Status), sorted by CreatedDateTime, paginated

So seems without doing much works, SimpleDB would be more easy to implement the codes?


问:
Responsiveness - iPad in Chrome vs iPad in Mozilla Firefox
I am developing a website in a Windows system. I have Firefox and Chrome browsers installed. When I checked the responsiveness of my webpage by setting the device as iPad(768 X 1024) using 'inspect element' feature in these browsers, I could get different resultant UI for same device. Why is it so? On which browser can I rely on as I don't have any Mac/Apple devices with me to test? I am concerned of using other online web tools due to security issues. Please help. Thanks in advance.</p>

答: There's a tool for checking responsiveness called browserstack. You can try it from here: https://www.browserstack.com. They're offering free trial.</p>


问:
Fastest method to find a complex type in a list (Vector, Array, Dictionary, whatever is faster)
Hail, Stack!

I need to know the best method to find an item inside a list (Vector, Array, Dictionary, whatever is faster) of complex type (extensions of Objects and Sprites).

I've used "Needle in Haystack" method, but it seems that it isn't fast enough.

E.g.
Suppose that I have a collection of Sprites (a pool, in fact).

Each sprite will be added to the stage and perform some action. After that, it will die.

I don't want to pay the cost to dispose it (garbage collect) and create another (new) one every time so I'll keep the dead sprites in a collection.

Sometimes times I'll call a method that will add a sprite to the stage.

This sprite can be a old one, if it is already dead, or a new one, if the pool don't have any free sprite.

One of the scenarios that pushed me to this question was a Particle System.

A "head" particle leaving a "trail" of particles every frame and exploding into a flashy multitude of particles... Every frame...

Some times this counts up to 50.000 PNGs with motion, rotation, alpha, event dispatching, scale, etc...

But, this is JUST ONE scenario...

At the moment I'm trying to use a Object Pool with a Linked List...

Hopes that it will be faster that running a whole Array/Vector or create new instances every frame an let them dye with Garbage Collection.

Someone knows a better/faster way to do it?

答:
Do you have any sort of key that can be attributed to the objects?(or possibly use the object as a key)

I believe that a Dictionary look up would probably be the fastest since it is done similar to Java's HashMap.

In that case you could have the object as the key and just do

myDictionary[complexObject] != null
(it will be null if there is no entry of that object)

Although if you could specify further what it is you need to lookup I might be able to offer further application of this


问:
How to get average time from list of times
Hi I have a problem with average time from list of times to each test.

output:

test1 ['0:02:30.000000', '0:02:28.000000', '0:02:31.000000', '0:02:33.000000', '0:02:34.000000', '0:02:37.000000', '0:02:30.000000', '0:02:30.000000']

test2 ['0:23:25.789000', '0:23:04.653000']

test3 ['0:32:21.873000', '0:32:33.752000', '0:33:30.383000', '0:32:29.835000']

expected result:

test_name = average time
on example:

test2 = 0:23:15:442000

I tried to convert str to time:

time == dt.strptime(str(time), '%H:%M:%S.%f')

but then i cannot sum all times and then divide to length of list.

Could you please help me with this issue?

def average_time(file_path):
    df = pd.DataFrame(pd.read_excel(file_path))
    test_names_list = collections.Counter(df.iloc[:, 0])
    times_list = {}
    for test_name in test_names_list:
        times_list[test_name] = []
        for row in range(df.shape[0]):
            if str(df.iloc[row, 0]) == test_name:
                times_list[test_name].append(str(df.iloc[row, 5]))
        print(test_name, times_list[test_name])
```

答:
Resolved.

def average_time(file_path):
    df = pd.DataFrame(pd.read_excel(file_path))
    test_names_list = collections.Counter(df.iloc[:, 0])
    times_list = {}
    for test_name in test_names_list:
        times_list[test_name] = []
        for row in range(df.shape[0]):
            if str(df.iloc[row, 0]) == test_name:
                times_list[test_name].append(get_sec(str(df.iloc[row, 5])))
        print(test_name, str(dt.timedelta(seconds=mean(times_list[test_name]))))
```


问:
Jupyter notebook: how to run python shell command on current kernel?
I'm trying to run a simple

!python script.py

command within a Jupyter notebook running on a custom kernel (virtual environment) where I installed a number of modules. When I run the above command, I am getting some errors related to missing modules, meaning it is not running that code on the same virtual environment as the jupyter notebook.

Is there any way to solve this?

答:
First activate the virtual env then start your notebook.Then it will have your activated virtual env packages</p>

```<code>source stackpy/bin/activate

sudo jupyter notebook --allow-root
</code>```

Body:
First activate the virtual env then start your notebook.Then it will have your activated virtual env packages

source stackpy/bin/activate

sudo jupyter notebook --allow-root


问:
How to conditionally apply CSS classes in React JS
I've been musing on how best to conditionally apply a CSS class in React JS. I've seen some answers banding around but there aren't many out there or they're just not as elaborative as I'd like.</p>

答:
If you need to add a conditional class to an existing class, this one may give you an idea

```<code><span className={'fa ' + (this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down')}></span>
</code>```

in this example, I am showing an arrow icon for a dropdown depending on the state of the dropdown. I need to keep the class fa for any case to set the font-family of the span, and I only need to switch between fa-angle-up and fa-angle-down.

Same example with template literals

```<code><span className={`fa ${this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down'}`}></span>
</code>```

Body:
If you need to add a conditional class to an existing class, this one may give you an idea

<span className={'fa ' + (this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down')}></span>

in this example, I am showing an arrow icon for a dropdown depending on the state of the dropdown. I need to keep the class fa for any case to set the font-family of the span, and I only need to switch between fa-angle-up and fa-angle-down.

Same example with template literals

<span className={`fa ${this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down'}`}></span>


问:
For statement and range function with indexes
For my assignment, I have to use a for loop and a range function for a program to print out the following, each on a separate line so it looks like a list.

```<code>Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
</code>```

I know that you have to create two variables, one that keeps track of the number of indexes and another that prints that, because the question states:
 (the number corresponds to the accumulated summation over the successive indexes). My problem is creating the function that does so keeping track of the indexes. Any guidance would be great. Thanks again in advance.

```<code>count_indexes = ?
print_statement = count_indexes + 1
for i in range(0,11,count_indexes):
    print("Hello",print_statement)
</code>```

The expected result should print hello 5 times, each on different lines, each with different numbers on them, and the numbers should be 0,1,3,6,10.

答:
you would need to increment step manually which can be done using a while loop. checkout difference between while and for loop.

The for statement iterates through a collection or iterable object or generator function.

The while statement simply loops until a condition is False.

if you use a while loop your code would look something like this:

```<code>count_indexes = 0
step = 1
while count_indexes < 11:
    print("Hello", count_indexes)
    count_indexes = count_indexes + step
    step = step + 1
</code>```

output:

```<code>Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
</code>```

Body:
For my assignment, I have to use a for loop and a range function for a program to print out the following, each on a separate line so it looks like a list.

Hello 0
Hello 1
Hello 3
Hello 6
Hello 10

I know that you have to create two variables, one that keeps track of the number of indexes and another that prints that, because the question states:
 (the number corresponds to the accumulated summation over the successive indexes). My problem is creating the function that does so keeping track of the indexes. Any guidance would be great. Thanks again in advance.

count_indexes = ?
print_statement = count_indexes + 1
for i in range(0,11,count_indexes):
    print("Hello",print_statement)

The expected result should print hello 5 times, each on different lines, each with different numbers on them, and the numbers should be 0,1,3,6,10.

Body:
you would need to increment step manually which can be done using a while loop. checkout difference between while and for loop.

The for statement iterates through a collection or iterable object or generator function.

The while statement simply loops until a condition is False.

if you use a while loop your code would look something like this:

count_indexes = 0
step = 1
while count_indexes < 11:
    print("Hello", count_indexes)
    count_indexes = count_indexes + step
    step = step + 1

output:

Hello 0
Hello 1
Hello 3
Hello 6
Hello 10


问:
Extending the attributes inspector in interface builder
Is it possible to extend the interface builder's attribute inspector with additional attributes for custom classes inheriting from UIView?</p>

答:
Not at the moment.

Interface Builder allows you to implement custom inspectors for your objects by means of an Interface Builder Plugin. However, IB Kit doesn't currently support making plugins for iPhone OS. Only plugin development for Mac OS is currently supported.

OwnerDisplayName: Cristian Libardo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Cristian Libardo

OwnerDisplayName: Brandon Walkin


问:
How to get FxCop for WinXP?
I have Windows XP and Visual Studio 2010 installed.

Intended to use FxCop to check if the solution corresponds to the Microsoft Code Guides.

Now found out that FxCop is part of "Microsoft Windows SDK for Windows 7 and .NET Framework 4"

Should I install this thing, even if I have Windows XP?

答: FxCop 10 can be run on WindowsXP (I have installed it on my XP box at work.) Having said that, I agree with Anuraj's comment - if you are using a version of VisualStudio 2010 that includes code analysis, using that is an easy place to start.  With a few exceptions, both VS and FxCop use the same rule set, so knowing one will help with the other.</p>

Title: How to get FxCop for WinXP?


问:
Corrupt XLSX file after download via axios
I try to create an XLSX file in a Vue application with axios. I do this:

First I send a post call to the backend controller:

```<code>return axios({
            url: '/backend/article/exportApi',
            method: 'POST',
            reponseType: 'blob',
            headers: {
                'Accept': 'vnd.ms-excel'
            },
            data: {headers: headers, articles: articles}
        });
</code>```

Then on the backend I do some things, create a xlsx file and save it on the server. This file is good and I when I check it, I can open it in excel. Now I want that this file is automatically downloaded by the browser, so in my controller I do this ($file is the path to the created xlsx file on the server):

```<code>$response = $this->Response();
$response->setHeader('Cache-Control', 'public');
$response->setHeader('Content-Description', 'File Transfer');
$response->setHeader('Content-disposition', 'attachment; filename="export.xlsx"');
$response->setHeader('Content-Type', 'application/vnd.ms-excel');
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Content-Length', filesize($file));
$response->sendHeaders();

echo readfile($file);
</code>```

The response looks like this: https://d.pr/i/UndMRn On the JS side I do this with the response:

```<code>let blob = new Blob([response.data], {type: 'vnd.ms-excel;charset=utf-8'});
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'export.xlsx';
link.click();
</code>```

The file which is downloaded is corrupted and can not be opened by Excel. I tried several things, including changing the type from vnd.ms-excel to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet and the responseType from blob to arraybuffer. None with success.

Anybody has a solution?

答: The reason was that POST does not accept a responseType. So I needed to make a POST call first and a GET request afterwards to retrieve and create the file.</p>

Body:
I try to create an XLSX file in a Vue application with axios. I do this:

First I send a post call to the backend controller:

return axios({
            url: '/backend/article/exportApi',
            method: 'POST',
            reponseType: 'blob',
            headers: {
                'Accept': 'vnd.ms-excel'
            },
            data: {headers: headers, articles: articles}
        });

Then on the backend I do some things, create a xlsx file and save it on the server. This file is good and I when I check it, I can open it in excel. Now I want that this file is automatically downloaded by the browser, so in my controller I do this ($file is the path to the created xlsx file on the server):

$response = $this->Response();
$response->setHeader('Cache-Control', 'public');
$response->setHeader('Content-Description', 'File Transfer');
$response->setHeader('Content-disposition', 'attachment; filename="export.xlsx"');
$response->setHeader('Content-Type', 'application/vnd.ms-excel');
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Content-Length', filesize($file));
$response->sendHeaders();

echo readfile($file);

The response looks like this: https://d.pr/i/UndMRn On the JS side I do this with the response:

let blob = new Blob([response.data], {type: 'vnd.ms-excel;charset=utf-8'});
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'export.xlsx';
link.click();

The file which is downloaded is corrupted and can not be opened by Excel. I tried several things, including changing the type from vnd.ms-excel to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet and the responseType from blob to arraybuffer. None with success.

Anybody has a solution?


问:
Angular component are not getting destroyed
In angular application, every time I route to a new page, my earlier page's component is staying in memory. It's not getting destroyed and when I route back to that page it creates a new instance.

Application is not created through angular CLI. It's a custom build application using the webpack configuration provided on angular website. Actually, I am doing performance improvement of the existing angular application and this demo app I created for isolation of issue.

Github
https://github.com/bytesofdhiren/angular-memory-issue

Basically, every time I route to home or register page, the application creates a new instance of the register component and home component. It's not destroying the earlier created component.

答: Actually, I tried running the above Github application in production mode and the issue got resolved. But the actual issue in my production application still exists. But that is related to something else. I will post a new question for that.</p>


问:
MySQL UNION does not work consistently. If I switch the posision of two clause, the results are different each other
According to the position of clauses, mysql results differently.

```<code>SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'
union all
SELECT qty as qty FROM tstock_txn_temp WHERE company_id='003490'
</code>```

result: correct

```<code>-290
290
</code>```

changed query

```<code>SELECT qty as qty
FROM tstock_txn_temp
WHERE company_id='003490'
union ALL
SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'
</code>```

result: not correct

```<code>290
0
</code>```

the result should be

```<code>290
-290
</code>```

答:
I am unable to reproduce your issue. </p>

```<code>drop table if exists tstock_txn,tstock_txn_temp;
create table tstock_txn_temp
(company_id int,qty int);
insert into tstock_txn_temp values (003490,200);

create table tstock_txn
(company_id int, txn_date date,bos varchar(1), txn_qty int);

insert into tstock_txn values
(003490,'2019-05-01','b',100),
(003490,'2019-05-01','b',100);

SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'
union all
SELECT qty as qty FROM tstock_txn_temp WHERE company_id=003490;

+------+
| qty  |
+------+
| -200 |
|  200 |
+------+
2 rows in set (0.02 sec)

SELECT qty as qty FROM tstock_txn_temp WHERE company_id='003490'
union ALL
SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490' ;

+------+
| qty  |
+------+
|  200 |
| -200 |
+------+
2 rows in set (0.00 sec)
</code>```

Body:
According to the position of clauses, mysql results differently.

SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'
union all
SELECT qty as qty FROM tstock_txn_temp WHERE company_id='003490'

result: correct

-290
290

changed query

SELECT qty as qty
FROM tstock_txn_temp
WHERE company_id='003490'
union ALL
SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'

result: not correct

290
0

the result should be

290
-290

Body:
I am unable to reproduce your issue.

drop table if exists tstock_txn,tstock_txn_temp;
create table tstock_txn_temp
(company_id int,qty int);
insert into tstock_txn_temp values (003490,200);

create table tstock_txn
(company_id int, txn_date date,bos varchar(1), txn_qty int);

insert into tstock_txn values
(003490,'2019-05-01','b',100),
(003490,'2019-05-01','b',100);

SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'
union all
SELECT qty as qty FROM tstock_txn_temp WHERE company_id=003490;

+------+
| qty  |
+------+
| -200 |
|  200 |
+------+
2 rows in set (0.02 sec)

SELECT qty as qty FROM tstock_txn_temp WHERE company_id='003490'
union ALL
SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490' ;

+------+
| qty  |
+------+
|  200 |
| -200 |
+------+
2 rows in set (0.00 sec)