问:
Override a method in a single object instance
Am not sure how to put this, and I couldn't find the answer because of my inability to find the words to express what am looking for. (!)

In Java, I used to do something like this (I don't remember):

```<code>JPanel myButton = new JPanel("Press me"){
    public void add(JComponent component){
        //override add method
    }
};
</code>```

But, i couldn't find how to do this in Objective-C .. What I found in my search was categories and weird ^{} symbols ...

So, how can I override method(s) in a newly created object?

(For example, override -(BOOL)isEqual; in a newly created NSString* ?)

Am sorry if the question is a bit vague..

EDIT:

Obviously, without subclassing :)

EDIT:

Might as well post my problem in case someone has a better idea:

I have a few CCTransitions in COCOS2D, and I want to be notified when the transition ends .. The thing is, as soon as the transition ends, the -(void)finish; method is invoked (which is part of the CCTransition class structure)

I would really want to avoid subclassing the CCTransition class, and override the finish method to do my logic when the transition ends :)

EDIT:

-(void)onEnterTransitionDidFinish; ... I can't believe something as awesome as that existed and I haven't came across it while searching......

Which means, instead of subclassing CCTransition, override this method in my CCNode subclass :D!

答:
What you have there in Java is an anonymous subclass.  This is not possible in Objective-C (well, it sort of is but you would have to do some pretty involved contortions with the Obj-C runtime library).

But Objective-C as of iOS 4 or OS X 10.6 has "blocks", which is what the ^{} syntax is for.  This is Objective-C's notion of a closure.  This isn't going to help you directly if the APIs that you're calling don't support block callbacks, but you may be able to create wrapper classes that use blocks instead of subclassed methods to handle callbacks.

There are many resources for learning about blocks in Objective-C.

Body:
Am not sure how to put this, and I couldn't find the answer because of my inability to find the words to express what am looking for. (!)

In Java, I used to do something like this (I don't remember):

JPanel myButton = new JPanel("Press me"){
    public void add(JComponent component){
        //override add method
    }
};

But, i couldn't find how to do this in Objective-C .. What I found in my search was categories and weird ^{} symbols ...

So, how can I override method(s) in a newly created object?

(For example, override -(BOOL)isEqual; in a newly created NSString* ?)

Am sorry if the question is a bit vague..

EDIT:

Obviously, without subclassing :)

EDIT:

Might as well post my problem in case someone has a better idea:

I have a few CCTransitions in COCOS2D, and I want to be notified when the transition ends .. The thing is, as soon as the transition ends, the -(void)finish; method is invoked (which is part of the CCTransition class structure)

I would really want to avoid subclassing the CCTransition class, and override the finish method to do my logic when the transition ends :)

EDIT:

-(void)onEnterTransitionDidFinish; ... I can't believe something as awesome as that existed and I haven't came across it while searching......

Which means, instead of subclassing CCTransition, override this method in my CCNode subclass :D!


来源: stackexchange

问:
Http Status 410 in LUIS Cognitive Service
We have been getting an HTTP status of 410 in production since our deployment, not in DEV

Following the directions, I re-trained then published and I still get the error 410

The URL works if we put staging=true as shown below:

https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/APP-ID?subscription-key=Subscription-key&timezoneOffset=-360&q=lakeville,%20mn

https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/APP-ID?subscription-key=Subscription-key&staging=true&timezoneOffset=-360&q=lakeville, mn

I have followed the instructions in the link below
https://westus.dev.cognitive.microsoft.com/docs/services/5819c76f40a6350ce09de1ac/operations/5819c77140a63516d81aee78

My question is how do, I publish so not having staging=true in the query string will work?

The original owner of  Luis left the company and I had to scramble to get up to speed, When, I was granted permission I became the owner of the Luis service according to the collaborator page.  My appId is different then what is in production

Can I sync my App ID to what is in production?

How do we get into the other Luis (Original owner) application to publish?

答:
When you publish, select the correct slot when the pop-up window display, you could follow this tutorial:Publish your active, trained app to a staging or production endpoint.

About how to change LUIS ownership, ranusharao already provide the answer link:Azure LUIS Ownership change.

ContentLicense: CC BY-SA 4.0


问:
Run function before a fetch call?
I've been attempting to create a vanilla js weather app, that takes the users location with there permission and inputs it into the fetch call upon there acceptance as a template string, the weather app would than deduce there location and give the temperature back.

Im still relatively new and i've hit a roadblock, i've noticed that the fetch call runs before the user is able to click the button that allows there location to be taken.

is there anyway to pause the fetch call until after the function runs? can i run the fetch call with the onclick attached to the function?

```<code>    var latitude,longitude;
function allow() {
navigator.geolcation;
navigator.geolocation.getCurrentPosition(currentPosition);
};

function currentPosition(position) {
latitude = (position.coords.latitude);
longitude = (position.coords.longitude);
};

function onPositionReady() {
    console.log(latitude,longitude);
    // proceed
};

let api  = {
key:'456fa9bb93098fb3454b25380512d491',
};

fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
  .then(response => response.json())
  .then(data => {
    // Here's a list of repos!
    console.log(data)
  });
</code>```

答:
Try this below.

If you're successful in gaining permission to get the users location, then thats when the long/lat becomes available. At the same time as they become available, you can then run your fetch call.

If the users deny's you using the location, then it will trigger the error function.

Learn more here https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

```<code>function success(pos) {
  var crd = pos.coords;
  let api  = {
    key:'456fa9bb93098fb3454b25380512d491',
  };

  fetch(`https://api.openweathermap.org/data/2.5/onecall? lat=${crd.latitude}&lon=${crd.longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
  .then(response => response.json())
  .then(data => {
    // Here's a list of repos!
    console.log(data)
  });
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);
</code>```

If you don't explicitly want to have the fetch directly in the success() method for the sake of readability (under the assumption you're going to add more code to it), you could wrap it in its own function outside of the success function and call it in the success() function instead like this

```<code>function doRequest(crd) {

  let api = {
    key: '456fa9bb93098fb3454b25380512d491',
  };

  fetch(`https://api.openweathermap.org/data/2.5/onecall? lat=${crd.latitude}&lon=${crd.longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
    .then(response => response.json())
    .then(data => {
      // Here's a list of repos!
      console.log(data)
    });
}

function success(pos) {
  var crd = pos.coords;
  doRequest(crd)
}
</code>```

Title: Run function before a fetch call?

Body:
I've been attempting to create a vanilla js weather app, that takes the users location with there permission and inputs it into the fetch call upon there acceptance as a template string, the weather app would than deduce there location and give the temperature back.

Im still relatively new and i've hit a roadblock, i've noticed that the fetch call runs before the user is able to click the button that allows there location to be taken.

is there anyway to pause the fetch call until after the function runs? can i run the fetch call with the onclick attached to the function?

    var latitude,longitude;
function allow() {
navigator.geolcation;
navigator.geolocation.getCurrentPosition(currentPosition);
};

function currentPosition(position) {
latitude = (position.coords.latitude);
longitude = (position.coords.longitude);
};

function onPositionReady() {
    console.log(latitude,longitude);
    // proceed
};

let api  = {
key:'456fa9bb93098fb3454b25380512d491',
};

fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
  .then(response => response.json())
  .then(data => {
    // Here's a list of repos!
    console.log(data)
  });

Body:
Try this below.

If you're successful in gaining permission to get the users location, then thats when the long/lat becomes available. At the same time as they become available, you can then run your fetch call.

If the users deny's you using the location, then it will trigger the error function.

Learn more here https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

function success(pos) {
  var crd = pos.coords;
  let api  = {
    key:'456fa9bb93098fb3454b25380512d491',
  };

  fetch(`https://api.openweathermap.org/data/2.5/onecall? lat=${crd.latitude}&lon=${crd.longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
  .then(response => response.json())
  .then(data => {
    // Here's a list of repos!
    console.log(data)
  });
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);

If you don't explicitly want to have the fetch directly in the success() method for the sake of readability (under the assumption you're going to add more code to it), you could wrap it in its own function outside of the success function and call it in the success() function instead like this

function doRequest(crd) {

  let api = {
    key: '456fa9bb93098fb3454b25380512d491',
  };

  fetch(`https://api.openweathermap.org/data/2.5/onecall? lat=${crd.latitude}&lon=${crd.longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
    .then(response => response.json())
    .then(data => {
      // Here's a list of repos!
      console.log(data)
    });
}

function success(pos) {
  var crd = pos.coords;
  doRequest(crd)
}


问:
ILogger to blob storage is slow
I have a function that makes various LogWarning calls, using the ILogger capability from Microsoft. When deployed to Azure Services, this will write log data to blobs. It seems to be slowing down my application a lot, which I guess is the nature of having to send traffic over network to the storage unit.

I am trying to work out -- Is ILogger something I can run asynch so it is faster? How do I go about doing this?

答:
This is not a direct answer. For azure web app, we usually use Application Insights for logging. It's actually using async mode for logging.

The benefits:

1.Easy to setup and integrated with ILogger.

2.You can control the log level.

3.You can also export the logs from Application insights to blob storage.

Title: ILogger to blob storage is slow


答:
This is the changed code that worked, prevent line break, remove the ":::|" and replaced "||" with "|"br""</p>

```<code>tOut += "" //"<br>"

tOut = tOut.split(":::|").join("");
tOut = tOut.split("||").join("|<br>");
document.write(tOut)
</code>```

Title: Javascript Delete First Character on Each Line of String

Body:
I need to remove the first character of a string "|" on each line in javascript.

| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| Gbm| G| A|
| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| E| G| G A|
| D| Gbm|

end results needed:

 D| Gbm| G| A|
 D| Gbm| G| A|
 Bm| Gbm| G| D|
 Bm| Gbm| G| A|
 D| Gbm| G| A|
 D| Gbm| G| A|
 Bm| Gbm| G| D|
 Bm| E| G| G A|
 D| Gbm|

This is the page I need to edit to get just the chords.
I removed the quotes with

tOut = tOut.replace("\"", "");

http://www.lesession.co.uk/abc/abcChordsOut.htm
This is the text input in ABC Notation format:

X:1
T:Guitar
L:1/8
K:D
Q:1/4=120
R:Medium Boogie
M:4/4
| "D"D,2 A,,D, D,2 [C,A,,]_B,,/2=B,,/2 | "Gbm"_G,,3 _G,,/2E,,/2 _G,,2 _D,/2=D,/2_E,/2=E,/2 | "G"G,3 G, G,3 =G,, | "A"A,,3 A,, A,,2 B,,2 |
| "D"A,,3 =D,/2A,,/2 D,2 F,G, | "Gbm"_G,,3 _G,,/2E,,/2 _G,,2 _D,_G,, | "G"=G,,3 G,,/2E,,/2 G,,2 B,,=D, | "A"A,2 G,A, A,E, A,,2 |
| "Bm"B,,2 =C,B,,/2A,,/2 B,,2 A,,2 | "Gbm"_G,3 _G,/2=F,/2 _G,2 _D,2 | "G"=G,3 =D, G,2 A,2 | "D"[D3^G,3] D D2 B,/2C/2A,/2^C,/2=C,/2 |
| "Bm"B,,3 B,,/2A,,/2 B,,3 F,,/2E,,/2 | "Gbm"_G,,3 _G,, E,,/2_G,,3/2 A,,_D, | "G"=G,,3 G,,/2E,,/2 G,,2 B,,/2G,,/2_B,,/2^G,,/2 | "A"A,,3 A,, A,,A,,=B,,C, |
| "D"D,3 D,/2A,,/2 D,2 A,2 | "Gbm"_G,,3 _G,,/2=F,,/2 _G,,3 E,, | "G"=G,,3 G,,/2E,,/2 G,,2 B,,3/2=C,/2 | "A"A,,4  z4 |
| "D" z3/2 B,,/2 ^C,D, A,,/2D,3/2- D,3/2A,/2 | "Gbm"_G,,3 _G,, E,,/2_G,,3/2 A,,_D, | "G"=G,,3 G,,/2E,,/2 G,,2 _B,,=D, | "A"A,,3 A,, A,,2 E,,2 |
| "Bm"B,2 B,2 [B,3D,3] F, | "Gbm"_G,,3 _G,,/2E,,/2 _G,,2 _D,_G,, | "G"=G,,3 G,,/2E,,/2 G,,2 =B,,[=D,A,,-- ] | "D"[D,3A,,3] D,  z4 |
| "Bm" z4  z2  z F,/2=F,/2 | "E"E,,3 E,, E,,2 B,,E,,/2G,,/2- | "G"G,,2- G,,/2G,,E,,/2 G,,3/2B,,/2- B,,2 | "G"_A,/2G,3/2 B,G, "A"=A,2 A,,2 |
| "D" z8 | "Gbm" z8 |

after it has been formatted it is pasted into the Java app Impro-Visor to give the chords.

Body:
This is the changed code that worked, prevent line break, remove the ":::|" and replaced "||" with "|"br""

tOut += "" //"<br>"

tOut = tOut.split(":::|").join("");
tOut = tOut.split("||").join("|<br>");
document.write(tOut)


问:
Pixels eraser in Processing
I am new using Processing and this time I am trying to do like a paint program. As I chose to draw a grid in the background, I don't know how to make a eraser. If someone has any ideas....

This is my code:

```<code>
int x = 20, y = 40, w = 70, h = 50;

void setup() {
  size(600, 600);
  background(255);

  stroke(240);
  for (int linex = 0; linex < width; linex = linex+40) {
    for (int liney = 0; liney < height; liney = liney + 40) {
      line(0, liney, width, liney);
    }
    line(linex, 0, linex, height);
  }

  fill(255, 0, 0);
  rect(x, height - 250, w, h);

  fill(0, 255, 0);
  rect(x, height - 190, w, h);

  fill(0, 0, 255);
  rect(x, height - 130, w, h);

  fill(0);
  rect(x, y, w, h);
  textSize(17);
  text("Erase everything", 10, 30);
}

void draw() {
  if ((keyPressed && key == 'r') || (mousePressed && mouseX > x && mouseX < x + w && mouseY > (height - 250) && mouseY < (height - 250) + h)) {
    fill(255, 0, 0);
  }
  if (keyPressed && key == 'g'|| (mousePressed && mouseX > x && mouseX < x + w && mouseY > (height - 190) && mouseY < (height - 190) + h)) {
    fill(0, 255, 0);
  }
  if (keyPressed && key == 'b' || (mousePressed && mouseX > x && mouseX < x + w && mouseY > (height - 130) && mouseY < (height - 130) + h))  {
    fill(0, 0, 255);
  }
  if (keyPressed && key == 'n'){
    fill(0);
  }

  if (mousePressed) {
    noStroke();
    ellipse(mouseX, mouseY, 20, 20);
  }

  if (mouseX > x && mouseX < x + w && mouseY > y && mouseY < y+h && mousePressed) {
    setup();
  }
}

</code>```

Thanks in advance

答:
Just sneak the following code somewhere into the draw() function in your program.

```<code>noStroke();

ellipse(mouseX, mouseY, 8, 8); // change width and height to the diameter (in pixels) you want your eraser to have.

strokeWeight(1);
</code>```

Or, if you want a square instead of a circle:

```<code>noStroke();
rectMode(CENTER);

rect(mouseX, mouseY, 8, 8);

rectMode(CORNER);
strokeWeight(1);
</code>```

Or something in beetween:

```<code>noStroke();
rectMode(CENTER);

rect(mouseX, mouseY, 8, 8, 4); // the 5th parameter is the edge smoothness (in pixels)

rectMode(CORNER);
strokeWeight(1);
</code>```

Title: Pixels eraser in Processing

Body:
I am new using Processing and this time I am trying to do like a paint program. As I chose to draw a grid in the background, I don't know how to make a eraser. If someone has any ideas....

This is my code:

int x = 20, y = 40, w = 70, h = 50;

void setup() {
  size(600, 600);
  background(255);

  stroke(240);
  for (int linex = 0; linex < width; linex = linex+40) {
    for (int liney = 0; liney < height; liney = liney + 40) {
      line(0, liney, width, liney);
    }
    line(linex, 0, linex, height);
  }

  fill(255, 0, 0);
  rect(x, height - 250, w, h);

  fill(0, 255, 0);
  rect(x, height - 190, w, h);

  fill(0, 0, 255);
  rect(x, height - 130, w, h);

  fill(0);
  rect(x, y, w, h);
  textSize(17);
  text("Erase everything", 10, 30);
}

void draw() {
  if ((keyPressed && key == 'r') || (mousePressed && mouseX > x && mouseX < x + w && mouseY > (height - 250) && mouseY < (height - 250) + h)) {
    fill(255, 0, 0);
  }
  if (keyPressed && key == 'g'|| (mousePressed && mouseX > x && mouseX < x + w && mouseY > (height - 190) && mouseY < (height - 190) + h)) {
    fill(0, 255, 0);
  }
  if (keyPressed && key == 'b' || (mousePressed && mouseX > x && mouseX < x + w && mouseY > (height - 130) && mouseY < (height - 130) + h))  {
    fill(0, 0, 255);
  }
  if (keyPressed && key == 'n'){
    fill(0);
  }

  if (mousePressed) {
    noStroke();
    ellipse(mouseX, mouseY, 20, 20);
  }

  if (mouseX > x && mouseX < x + w && mouseY > y && mouseY < y+h && mousePressed) {
    setup();
  }
}

Thanks in advance

Body:
Just sneak the following code somewhere into the draw() function in your program.

noStroke();

ellipse(mouseX, mouseY, 8, 8); // change width and height to the diameter (in pixels) you want your eraser to have.

strokeWeight(1);

Or, if you want a square instead of a circle:

noStroke();
rectMode(CENTER);

rect(mouseX, mouseY, 8, 8);

rectMode(CORNER);
strokeWeight(1);

Or something in beetween:

noStroke();
rectMode(CENTER);

rect(mouseX, mouseY, 8, 8, 4); // the 5th parameter is the edge smoothness (in pixels)

rectMode(CORNER);
strokeWeight(1);


问:
org.json.JSONException: JSONObject["weather"] is not a string
I am currently using a weather API from https://openweathermap.org/api and I'm trying to convert a JSON page into printable strings. To be more specific. Im tryying to print out the Array of "weather" as the key but its not working:

```<code>
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class Main {

    public static void main(String[] args) throws ParseException, org.json.simple.parser.ParseException {
        String URL = "http://api.openweathermap.org/data/2.5/weather?q=miami&appid=2550e0628a9e7428e4ef85626feb1c95";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet getURL = new HttpGet(URL);
        try {
            CloseableHttpResponse response1 = httpclient.execute(getURL);
            HttpEntity entity = response1.getEntity();
            JSONObject json = new JSONObject(EntityUtils.toString(entity));
            json.getString("weather");
        } catch (IOException e) {
            System.out.println("Failed");
        }
    }

}
</code>```

The JSONObject structure is this:

```<code>    "coord": {
        "lon": -80.19,
        "lat": 25.77
    },
    "weather": [{
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04n"
    }],
    "base": "stations",
    "main": {
        "temp": 301.17,
        "feels_like": 303.16,
        "temp_min": 300.93,
        "temp_max": 301.48,
        "pressure": 1018,
        "humidity": 74
    },
    "visibility": 16093,
    "wind": {
        "speed": 4.6,
        "deg": 80
    },
    "clouds": {
        "all": 90
    },
    "dt": 1591061650,
    "sys": {
        "type": 1,
        "id": 4896,
        "country": "US",
        "sunrise": 1591007368,
        "sunset": 1591056495
    },
    "timezone": -14400,
    "id": 4164138,
    "name": "Miami",
    "cod": 200
}
</code>```

The error:

```<code>    at org.json.JSONObject.wrongValueFormatException(JSONObject.java:2590)
    at org.json.JSONObject.getString(JSONObject.java:863)
    at Main.main(Main.java:23)
</code>```

Im trying to get the "weather" section of the JSON or any sub section of the JSON. Could someone help me with my code?

答:
```<code>json.getString(key);
</code>```

Returns a string if the value of the specified key is a String.

In your case, the value of weather is a JSONArray and not a String.

You should do:

```<code>json.getJSONArray("weather");
</code>```

Ideally, you should check if the key exists, or have a default value to avoid NPE.

```<code>if (json.has("weather") && json.get("weather") instanceof JSONArray) {
    json.getJSONArray("weather");
}
</code>```

Unless you are 100% sure of the JSON structure.

Body:
I am currently using a weather API from https://openweathermap.org/api and I'm trying to convert a JSON page into printable strings. To be more specific. Im tryying to print out the Array of "weather" as the key but its not working:

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class Main {

    public static void main(String[] args) throws ParseException, org.json.simple.parser.ParseException {
        String URL = "http://api.openweathermap.org/data/2.5/weather?q=miami&appid=2550e0628a9e7428e4ef85626feb1c95";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet getURL = new HttpGet(URL);
        try {
            CloseableHttpResponse response1 = httpclient.execute(getURL);
            HttpEntity entity = response1.getEntity();
            JSONObject json = new JSONObject(EntityUtils.toString(entity));
            json.getString("weather");
        } catch (IOException e) {
            System.out.println("Failed");
        }
    }

}

The JSONObject structure is this:

    "coord": {
        "lon": -80.19,
        "lat": 25.77
    },
    "weather": [{
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04n"
    }],
    "base": "stations",
    "main": {
        "temp": 301.17,
        "feels_like": 303.16,
        "temp_min": 300.93,
        "temp_max": 301.48,
        "pressure": 1018,
        "humidity": 74
    },
    "visibility": 16093,
    "wind": {
        "speed": 4.6,
        "deg": 80
    },
    "clouds": {
        "all": 90
    },
    "dt": 1591061650,
    "sys": {
        "type": 1,
        "id": 4896,
        "country": "US",
        "sunrise": 1591007368,
        "sunset": 1591056495
    },
    "timezone": -14400,
    "id": 4164138,
    "name": "Miami",
    "cod": 200
}

The error:

    at org.json.JSONObject.wrongValueFormatException(JSONObject.java:2590)
    at org.json.JSONObject.getString(JSONObject.java:863)
    at Main.main(Main.java:23)

Im trying to get the "weather" section of the JSON or any sub section of the JSON. Could someone help me with my code?

Body:
json.getString(key);

Returns a string if the value of the specified key is a String.

In your case, the value of weather is a JSONArray and not a String.

You should do:

json.getJSONArray("weather");

Ideally, you should check if the key exists, or have a default value to avoid NPE.

if (json.has("weather") && json.get("weather") instanceof JSONArray) {
    json.getJSONArray("weather");
}

Unless you are 100% sure of the JSON structure.


问:
How to get the Builds for a project using OData in Azure Devops
I'm trying to get all the builds for a project using Odata for Azure Devops. However I found there was an endpoint for that https://analytics.dev.azure.com/{organization}/{project}/_odata/v3.0-preview/Builds but while trying the same for my Project I'm getting the below error

```<code>{"$id":"1","innerException":null,"message":"Resource not found for the segment 'Builds'.","typeName":"Microsoft.OData.UriParser.ODataUnrecognizedPathException, Microsoft.TeamFoundation.OData.Core","typeKey":"ODataUnrecognizedPathException","errorCode":0,"eventId":0}
</code>```

Is this endpoint not available anymore. Or is there something wrong with my query?

答:
Is this endpoint not available anymore. Or is there something wrong
  with my query?

The entity set Build has been renamed. You can check this post from our User Voice forum.

All entity sets and entity properties with names starting with Build will be renamed to start with PipelineRun.

For e.g. Builds entity set will be called PipelineRuns, BuildId entity property will be called PipelineRunId.

So what you should use is : https://analytics.dev.azure.com/{organization}/{project}/_odata/v3.0-preview/PipelineRuns. It works on my side :)

Body:
I'm trying to get all the builds for a project using Odata for Azure Devops. However I found there was an endpoint for that https://analytics.dev.azure.com/{organization}/{project}/_odata/v3.0-preview/Builds but while trying the same for my Project I'm getting the below error

{"$id":"1","innerException":null,"message":"Resource not found for the segment 'Builds'.","typeName":"Microsoft.OData.UriParser.ODataUnrecognizedPathException, Microsoft.TeamFoundation.OData.Core","typeKey":"ODataUnrecognizedPathException","errorCode":0,"eventId":0}

Is this endpoint not available anymore. Or is there something wrong with my query?


答:
Your success and failure callbacks don't look right either -- they're defined but never used. Depending on how the API is secured, you may not want to publish your API key publicly -- so a non-interactive example:</p>

```<code>var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);

  fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=...`)
    .then(response => response.json())
    .then(data => {
      // Here's a list of repos!
      console.log(data)
    });
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);
</code>```

Title: Run function before a fetch call?

Body:
Your success and failure callbacks don't look right either -- they're defined but never used. Depending on how the API is secured, you may not want to publish your API key publicly -- so a non-interactive example:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);

  fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=...`)
    .then(response => response.json())
    .then(data => {
      // Here's a list of repos!
      console.log(data)
    });
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);


问:
mysql group by and order by with limit query
mysql table structure is as follows

```<code>cmpid cmpname empid empname join-date
    1     xxx    21      p        18
    2     abc    13      q        10
    1     xxx    20      r         9
    2     abc    19      s        21
    2     abc    18      t        20
    1     xxx    19      u         1
</code>```

I want result as per format

```<code>cmpid cmpname empid empname join-date
    2     abc    19      s         21
    2     abc    18      t         20

    1     xxx    21      p         18
    1     xxx    20      r          9
</code>```

means which ever companies has any new emp. then it return that company first with first two joined emp info. and then other compnies with same format.

means order on join date and group on cmpname with 2 people info

If any one knows please reply

Thanks

答:
Did you mean this?</p>

```<code>select c.cmpid, c.cmpname, e.empid, e.empname, e.join-date
from company c
inner join employee e on (c.cmpid = e.cmpid)
group by c.cmpid, e.emp_id
order by e.join-date
</code>```

ContentLicense: CC BY-SA 3.0

Body:
mysql table structure is as follows

cmpid cmpname empid empname join-date
    1     xxx    21      p        18
    2     abc    13      q        10
    1     xxx    20      r         9
    2     abc    19      s        21
    2     abc    18      t        20
    1     xxx    19      u         1

I want result as per format

cmpid cmpname empid empname join-date
    2     abc    19      s         21
    2     abc    18      t         20

    1     xxx    21      p         18
    1     xxx    20      r          9

means which ever companies has any new emp. then it return that company first with first two joined emp info. and then other compnies with same format.

means order on join date and group on cmpname with 2 people info

If any one knows please reply

Thanks

Body:
Did you mean this?

select c.cmpid, c.cmpname, e.empid, e.empname, e.join-date
from company c
inner join employee e on (c.cmpid = e.cmpid)
group by c.cmpid, e.emp_id
order by e.join-date


问:
trying to create a new column that observation responds to criteria within 2 separate columns and determines output
I'm trying to create a column with if else function.
I Have a large data-set. I only need one of the columns to specify the if else function but i have multiple observations within the column which will be what the if else function is based on. I have taken the necessary observations from within the column. the original column is called lg$name. it is roughly set up like this </p>

```<code>names <- c("UK STERLING", "US DOLLARS" ,"STH AFRICAN RAND")
cash <- c("GBP", "USD", "ZDA")
id <- c(1 ,2 ,3)
df <- data.frame(names,cash,id)
#new column
df$type <- ifelse("UK Sterling", "cur" "not cur")
df$type <- ifelse("US DOLLARS", "cur", not cur")
#so on and so forth...
</code>```

<p>string contains the observations within the original data-set lg which will need to be used to determine output in new column. without having to run the multiple codes which will be inefficient in regards to data usage. I'm using data table package to do this. </p>

```<code> string <- ("AUSTRALIAN DOLLAR","BRAZILIAN REAL","CANADIAN DOLLAR","CHINESE
        YUAN","COLOMBIAN PESO","DANISH KRONER",
        "EURO, , HONG KONG DOLLAR", "HUNGARIAN FORINT", "INDIAN RUPEE",
       "INDONESIAN RUPIAH",
        "JAPANESE YEN", "KOREA (SOUTH) WON", "MEXICAN PESO","MALAYSIAN
          RINGGIT",
        "NORWEIGIAN KRONER", "NEW ZEALAND DOLLAR",  "PERUVIAN SOL",
        "POLISH ZLOTY", "Russian Rouble (new)",
        "SINGAPORE DOLLAR", "STH AFRICAN RAND",
        "SWEIDSH KRONER", "SWISS FRANC", "TAIWANESE DOLAR",
        "THAILAND BAHTS", "TURKISH LIRA","UK STERLING", "US DOLLAR")
</code>```

答:
You can use %in% :

```<code>df$type <- c('not cur', 'cur')[(df$names %in% string) + 1]
</code>```

which is similar to :

```<code>df$type <- ifelse(df$names %in% string, 'cur', 'not cur')
</code>```

Body:
I'm trying to create a column with if else function.
I Have a large data-set. I only need one of the columns to specify the if else function but i have multiple observations within the column which will be what the if else function is based on. I have taken the necessary observations from within the column. the original column is called lg$name. it is roughly set up like this

names <- c("UK STERLING", "US DOLLARS" ,"STH AFRICAN RAND")
cash <- c("GBP", "USD", "ZDA")
id <- c(1 ,2 ,3)
df <- data.frame(names,cash,id)
#new column
df$type <- ifelse("UK Sterling", "cur" "not cur")
df$type <- ifelse("US DOLLARS", "cur", not cur")
#so on and so forth...

string contains the observations within the original data-set lg which will need to be used to determine output in new column. without having to run the multiple codes which will be inefficient in regards to data usage. I'm using data table package to do this.

 string <- ("AUSTRALIAN DOLLAR","BRAZILIAN REAL","CANADIAN DOLLAR","CHINESE
        YUAN","COLOMBIAN PESO","DANISH KRONER",
        "EURO, , HONG KONG DOLLAR", "HUNGARIAN FORINT", "INDIAN RUPEE",
       "INDONESIAN RUPIAH",
        "JAPANESE YEN", "KOREA (SOUTH) WON", "MEXICAN PESO","MALAYSIAN
          RINGGIT",
        "NORWEIGIAN KRONER", "NEW ZEALAND DOLLAR",  "PERUVIAN SOL",
        "POLISH ZLOTY", "Russian Rouble (new)",
        "SINGAPORE DOLLAR", "STH AFRICAN RAND",
        "SWEIDSH KRONER", "SWISS FRANC", "TAIWANESE DOLAR",
        "THAILAND BAHTS", "TURKISH LIRA","UK STERLING", "US DOLLAR")

Body:
You can use %in% :

df$type <- c('not cur', 'cur')[(df$names %in% string) + 1]

which is similar to :

df$type <- ifelse(df$names %in% string, 'cur', 'not cur')


问:
Compare Two Arrays Of Objects and return a new array if value is true in Javascript
I need to compare 2 arrays

```<code>const inviteFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  }
]

const allFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: false
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: false
  },
]
</code>```

An if invited is true I need to return a new array.

Something like this:

```<code>const newArray = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  },
]
</code>```

Any idea how can I achieve this? Help please

答:
since you also need the !invited row, so the logic is to replace the same data from invitedFriends to allFriends (compare by id)

we loop on the allfriends then find if allfriend(n).id found on invitedFriend if found then push invitedFriend(found) if not just push the allfriend(n)

so in one line you can use

```<code>let x = allFriends.map( af =>  inviteFriends.find( x => x.userId === af.userId) || af );
</code>```

Body:
I need to compare 2 arrays

const inviteFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  }
]

const allFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: false
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: false
  },
]

An if invited is true I need to return a new array.

Something like this:

const newArray = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  },
]

Any idea how can I achieve this? Help please

Body:
since you also need the !invited row, so the logic is to replace the same data from invitedFriends to allFriends (compare by id)

we loop on the allfriends then find if allfriend(n).id found on invitedFriend if found then push invitedFriend(found) if not just push the allfriend(n)

so in one line you can use

let x = allFriends.map( af =>  inviteFriends.find( x => x.userId === af.userId) || af );


问:
Set default value to an Input field but make it editable (to be able to change it manually)?
I have an online form that takes values from some input fields and does some calculations on them. please check fiddle URL:
https://jsfiddle.net/moeadas/fv027knx/44/

I basically need to set a default value to a specific input field named (Rounded Valuation) name="B200". I want this input to take the value from another field name="B52" as default but I want users to be able to manually edit this field to enter another number (which will be used for other calculations).

Finally I want to hide the "Submit" button in the last stage as this is not really a form and its just an online form which users can play with.

I really appreciate all your kind comments and efforts. Please have a look at the fiddle link to better understand the current structure.

JAVASCRIPT CODE BELOW. CHECK THE JSFIDDLE FOR THE FULL STRUCTURE

```<code>    function milesIt(num) {
  return Math.floor(num).toString().split("").reverse().map((n, i, a) =>
    (i + 1) % 3 === 0 && i + 1 != a.length && "," + n || n).reverse().join("");
}

var inputs = document.querySelectorAll("[type='text']");
inputs.forEach(function(input) {
  //change the values to include the thousand separator each time the user changes an input
  input.onchange = function(e) {
    inputs.forEach(function(inp) {
      inp.value = inp.value.replace(/[,]/g, '');
    });
    calcule2();
    inputs.forEach(function(inp) {
      inp.value = milesIt(inp.value);
    });

  }

  input.value = milesIt(input.value);
});
////////////////////////////////////////////

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
  // ... and fix the Previous/Next buttons:
  if (n == 0) {
    document.getElementById("prevBtn").style.display = "none";
  } else {
    document.getElementById("prevBtn").style.display = "inline";
  }
  if (n == (x.length - 1)) {
    document.getElementById("nextBtn").innerHTML = "Submit";
  } else {
    document.getElementById("nextBtn").innerHTML = "Next";
  }

  // ... and run a function that displays the correct step indicator:
  fixStepIndicator(n)
}

function nextPrev(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab");
  // Exit the function if any field in the current tab is invalid:
  if (n == 1 && !validateForm()) return false;
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
  if (currentTab >= x.length) {
    //...the form gets submitted:
    document.getElementById("CreativeAcquisitions").submit();
    return false;
  }
  // Otherwise, display the correct tab:
  showTab(currentTab);
}

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false:
      valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var i, x = document.getElementsByClassName("step");
  for (i = 0; i < x.length; i++) {
    x[i].className = x[i].className.replace(" active", "");
  }
  //... and adds the "active" class to the current step:
  x[n].className += " active";
}

function calcule2() {

  var i = 0;
  for (i = 0; i <= 50; i++) {
    calcule();
  }
}

function calcule() {

  CreativeAcquisitions.B28.value = parseFloat(CreativeAcquisitions.B17.value) + parseFloat(CreativeAcquisitions.B19.value) + parseFloat(CreativeAcquisitions.B21.value) + parseFloat(CreativeAcquisitions.B23.value) + parseFloat(CreativeAcquisitions.B25.value);

  CreativeAcquisitions.B52.value = (parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value)) + parseFloat(CreativeAcquisitions.D81.value) +
    parseFloat(CreativeAcquisitions.B300.value);

  CreativeAcquisitions.B55.value = parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value);
  CreativeAcquisitions.B56.value = parseFloat(CreativeAcquisitions.B28.value);

  //CreativeAcquisitions.B200.value = CreativeAcquisitions.B52.value; //testing
  //document.getElementById("B200").value = CreativeAcquisitions.B52.value;

  CreativeAcquisitions.B66.value = parseFloat(CreativeAcquisitions.B200.value);
  CreativeAcquisitions.B67.value = parseFloat(CreativeAcquisitions.D81.value);

  CreativeAcquisitions.B68.value = parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value);

  CreativeAcquisitions.B300.value = (parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value)) * -1;

  CreativeAcquisitions.B69.value = parseFloat(CreativeAcquisitions.B41.value);
  CreativeAcquisitions.B70.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;
  CreativeAcquisitions.B71.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B47.value)) / 100;
  CreativeAcquisitions.B72.value = parseFloat(CreativeAcquisitions.B66.value) - parseFloat(CreativeAcquisitions.B67.value) - parseFloat(CreativeAcquisitions.B70.value) - parseFloat(CreativeAcquisitions.B69.value) - parseFloat(CreativeAcquisitions.B71.value);
  CreativeAcquisitions.B76.value = parseFloat(CreativeAcquisitions.B17.value);
  CreativeAcquisitions.D76.value = (parseFloat(CreativeAcquisitions.B76.value) * parseFloat(CreativeAcquisitions.C76.value)) / 100;
  CreativeAcquisitions.B77.value = parseFloat(CreativeAcquisitions.B19.value);
  CreativeAcquisitions.D77.value = (parseFloat(CreativeAcquisitions.B77.value) * parseFloat(CreativeAcquisitions.C77.value)) / 100;
  CreativeAcquisitions.B78.value = parseFloat(CreativeAcquisitions.B21.value);
  CreativeAcquisitions.D78.value = (parseFloat(CreativeAcquisitions.B78.value) * parseFloat(CreativeAcquisitions.C78.value)) / 100;
  CreativeAcquisitions.B79.value = parseFloat(CreativeAcquisitions.B23.value);
  CreativeAcquisitions.D79.value = (parseFloat(CreativeAcquisitions.B79.value) * parseFloat(CreativeAcquisitions.C79.value)) / 100;
  CreativeAcquisitions.B80.value = parseFloat(CreativeAcquisitions.B25.value);
  CreativeAcquisitions.D80.value = (parseFloat(CreativeAcquisitions.B80.value) * parseFloat(CreativeAcquisitions.C80.value)) / 100;
  CreativeAcquisitions.B81.value = parseFloat(CreativeAcquisitions.B76.value) + parseFloat(CreativeAcquisitions.B77.value) + parseFloat(CreativeAcquisitions.B78.value) + parseFloat(CreativeAcquisitions.B79.value) + parseFloat(CreativeAcquisitions.B80.value);
  CreativeAcquisitions.D81.value = parseFloat(CreativeAcquisitions.D76.value) + parseFloat(CreativeAcquisitions.D77.value) + parseFloat(CreativeAcquisitions.D78.value) + parseFloat(CreativeAcquisitions.D79.value) + parseFloat(CreativeAcquisitions.D80.value);
  CreativeAcquisitions.B91.value = parseFloat(CreativeAcquisitions.B36.value);

  CreativeAcquisitions.B92.value = parseFloat(CreativeAcquisitions.B37.value);

  CreativeAcquisitions.B93.value = parseFloat(CreativeAcquisitions.B38.value);

  CreativeAcquisitions.B94.value = parseFloat(CreativeAcquisitions.B39.value);

  CreativeAcquisitions.B95.value = parseFloat(CreativeAcquisitions.B40.value);

  CreativeAcquisitions.B96.value = (parseFloat(CreativeAcquisitions.B52.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;

  CreativeAcquisitions.B97.value = parseFloat(CreativeAcquisitions.B41.value);

  CreativeAcquisitions.B98.value = (parseFloat(CreativeAcquisitions.B91.value) + parseFloat(CreativeAcquisitions.B92.value) + parseFloat(CreativeAcquisitions.B93.value) + parseFloat(CreativeAcquisitions.B94.value) + parseFloat(CreativeAcquisitions.B95.value) + parseFloat(CreativeAcquisitions.B96.value) + parseFloat(CreativeAcquisitions.B97.value)) * -1;

  CreativeAcquisitions.C98.value = (parseFloat(CreativeAcquisitions.C91.value) + parseFloat(CreativeAcquisitions.C92.value) + parseFloat(CreativeAcquisitions.C93.value) + parseFloat(CreativeAcquisitions.C94.value) + parseFloat(CreativeAcquisitions.C95.value) + parseFloat(CreativeAcquisitions.C96.value) + parseFloat(CreativeAcquisitions.C97.value)) * -1;

  CreativeAcquisitions.B101.value = parseFloat(CreativeAcquisitions.B4.value);
  CreativeAcquisitions.B105.value = (parseFloat(CreativeAcquisitions.B101.value) * parseFloat(CreativeAcquisitions.B103.value)) / 100;
  CreativeAcquisitions.B107.value = parseFloat(CreativeAcquisitions.C98.value);
  CreativeAcquisitions.B108.value = parseFloat(CreativeAcquisitions.B101.value) - parseFloat(CreativeAcquisitions.B105.value) + parseFloat(CreativeAcquisitions.B107.value);
}
</code>```

答:
I don't know how these fields are created but following your code, this may be helpful:</p>

```<code>//////////Newcode///////////////////////////
function milesIt(num) {
  return Math.floor(num).toString().split("").reverse().map((n, i, a) =>
    (i + 1) % 3 === 0 && i + 1 != a.length && "," + n || n).reverse().join("");
}

var inputs = document.querySelectorAll("[type='text']");
inputs.forEach(function(input) {
  //change the values to include the thousand separator each time the user changes an input
  input.onchange = function(e) {
    inputs.forEach(function(inp) {
      inp.value = inp.value.replace(/[,]/g, '');
    });
    calcule2();
    inputs.forEach(function(inp) {
      inp.value = milesIt(inp.value);
    });
    //e.target.value = milesIt(e.target.value.replace(/[.]/g, ''));
  }
  //change the values of the inputs at the beginning, although you could write them as HTML with the thousand separator values in the source code
  input.value = milesIt(input.value);
});
////////////////////////////////////////////

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
  // ... and fix the Previous/Next buttons:
  if (n == 0) {
    document.getElementById("prevBtn").style.display = "none";
  } else {
    document.getElementById("prevBtn").style.display = "inline";
  }
  if (n == (x.length - 1)) {
    document.getElementById("nextBtn").style.display='none';
  } else {
    document.getElementById("nextBtn").innerHTML = "Next";
  }

  // ... and run a function that displays the correct step indicator:
  fixStepIndicator(n)
}

function nextPrev(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab");
  // Exit the function if any field in the current tab is invalid:
  if (n == 1 && !validateForm()) return false;
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
    if (n < (x.length - 2))
        document.getElementById("nextBtn").style.display='inline';
  // Otherwise, display the correct tab:
  showTab(currentTab);
}

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false:
      valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var i, x = document.getElementsByClassName("step");
  for (i = 0; i < x.length; i++) {
    x[i].className = x[i].className.replace(" active", "");
  }
  //... and adds the "active" class to the current step:
  x[n].className += " active";
}

function calcule2() {

  var i = 0;
  for (i = 0; i <= 50; i++) {
    calcule();
  }
}

function calcule() {

  CreativeAcquisitions.B28.value = parseFloat(CreativeAcquisitions.B17.value) + parseFloat(CreativeAcquisitions.B19.value) + parseFloat(CreativeAcquisitions.B21.value) + parseFloat(CreativeAcquisitions.B23.value) + parseFloat(CreativeAcquisitions.B25.value);

  CreativeAcquisitions.B52.value = (parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value)) + parseFloat(CreativeAcquisitions.D81.value) +
    parseFloat(CreativeAcquisitions.B300.value);

  CreativeAcquisitions.B55.value = parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value);
  CreativeAcquisitions.B56.value = parseFloat(CreativeAcquisitions.B28.value);

  CreativeAcquisitions.B200.value = Math.round(parseFloat(CreativeAcquisitions.B52.value)); //here is your field

  CreativeAcquisitions.B66.value = parseFloat(CreativeAcquisitions.B200.value);
  CreativeAcquisitions.B67.value = parseFloat(CreativeAcquisitions.D81.value);

  CreativeAcquisitions.B68.value = parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value);

  CreativeAcquisitions.B300.value = (parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value)) * -1;

  CreativeAcquisitions.B69.value = parseFloat(CreativeAcquisitions.B41.value);
  CreativeAcquisitions.B70.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;
  CreativeAcquisitions.B71.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B47.value)) / 100;
  CreativeAcquisitions.B72.value = parseFloat(CreativeAcquisitions.B66.value) - parseFloat(CreativeAcquisitions.B67.value) - parseFloat(CreativeAcquisitions.B70.value) - parseFloat(CreativeAcquisitions.B69.value) - parseFloat(CreativeAcquisitions.B71.value);
  CreativeAcquisitions.B76.value = parseFloat(CreativeAcquisitions.B17.value);
  CreativeAcquisitions.D76.value = (parseFloat(CreativeAcquisitions.B76.value) * parseFloat(CreativeAcquisitions.C76.value)) / 100;
  CreativeAcquisitions.B77.value = parseFloat(CreativeAcquisitions.B19.value);
  CreativeAcquisitions.D77.value = (parseFloat(CreativeAcquisitions.B77.value) * parseFloat(CreativeAcquisitions.C77.value)) / 100;
  CreativeAcquisitions.B78.value = parseFloat(CreativeAcquisitions.B21.value);
  CreativeAcquisitions.D78.value = (parseFloat(CreativeAcquisitions.B78.value) * parseFloat(CreativeAcquisitions.C78.value)) / 100;
  CreativeAcquisitions.B79.value = parseFloat(CreativeAcquisitions.B23.value);
  CreativeAcquisitions.D79.value = (parseFloat(CreativeAcquisitions.B79.value) * parseFloat(CreativeAcquisitions.C79.value)) / 100;
  CreativeAcquisitions.B80.value = parseFloat(CreativeAcquisitions.B25.value);
  CreativeAcquisitions.D80.value = (parseFloat(CreativeAcquisitions.B80.value) * parseFloat(CreativeAcquisitions.C80.value)) / 100;
  CreativeAcquisitions.B81.value = parseFloat(CreativeAcquisitions.B76.value) + parseFloat(CreativeAcquisitions.B77.value) + parseFloat(CreativeAcquisitions.B78.value) + parseFloat(CreativeAcquisitions.B79.value) + parseFloat(CreativeAcquisitions.B80.value);
  CreativeAcquisitions.D81.value = parseFloat(CreativeAcquisitions.D76.value) + parseFloat(CreativeAcquisitions.D77.value) + parseFloat(CreativeAcquisitions.D78.value) + parseFloat(CreativeAcquisitions.D79.value) + parseFloat(CreativeAcquisitions.D80.value);
  CreativeAcquisitions.B91.value = parseFloat(CreativeAcquisitions.B36.value);

  CreativeAcquisitions.B92.value = parseFloat(CreativeAcquisitions.B37.value);

  CreativeAcquisitions.B93.value = parseFloat(CreativeAcquisitions.B38.value);

  CreativeAcquisitions.B94.value = parseFloat(CreativeAcquisitions.B39.value);

  CreativeAcquisitions.B95.value = parseFloat(CreativeAcquisitions.B40.value);

  CreativeAcquisitions.B96.value = (parseFloat(CreativeAcquisitions.B52.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;

  CreativeAcquisitions.B97.value = parseFloat(CreativeAcquisitions.B41.value);

  CreativeAcquisitions.B98.value = (parseFloat(CreativeAcquisitions.B91.value) + parseFloat(CreativeAcquisitions.B92.value) + parseFloat(CreativeAcquisitions.B93.value) + parseFloat(CreativeAcquisitions.B94.value) + parseFloat(CreativeAcquisitions.B95.value) + parseFloat(CreativeAcquisitions.B96.value) + parseFloat(CreativeAcquisitions.B97.value)) * -1;

  CreativeAcquisitions.C98.value = (parseFloat(CreativeAcquisitions.C91.value) + parseFloat(CreativeAcquisitions.C92.value) + parseFloat(CreativeAcquisitions.C93.value) + parseFloat(CreativeAcquisitions.C94.value) + parseFloat(CreativeAcquisitions.C95.value) + parseFloat(CreativeAcquisitions.C96.value) + parseFloat(CreativeAcquisitions.C97.value)) * -1;

  CreativeAcquisitions.B101.value = parseFloat(CreativeAcquisitions.B4.value);
  CreativeAcquisitions.B105.value = (parseFloat(CreativeAcquisitions.B101.value) * parseFloat(CreativeAcquisitions.B103.value)) / 100;
  CreativeAcquisitions.B107.value = parseFloat(CreativeAcquisitions.C98.value);
  CreativeAcquisitions.B108.value = parseFloat(CreativeAcquisitions.B101.value) - parseFloat(CreativeAcquisitions.B105.value) + parseFloat(CreativeAcquisitions.B107.value);
}

</code>```

Body:
I have an online form that takes values from some input fields and does some calculations on them. please check fiddle URL:
https://jsfiddle.net/moeadas/fv027knx/44/

I basically need to set a default value to a specific input field named (Rounded Valuation) name="B200". I want this input to take the value from another field name="B52" as default but I want users to be able to manually edit this field to enter another number (which will be used for other calculations).

Finally I want to hide the "Submit" button in the last stage as this is not really a form and its just an online form which users can play with.

I really appreciate all your kind comments and efforts. Please have a look at the fiddle link to better understand the current structure.

JAVASCRIPT CODE BELOW. CHECK THE JSFIDDLE FOR THE FULL STRUCTURE

    function milesIt(num) {
  return Math.floor(num).toString().split("").reverse().map((n, i, a) =>
    (i + 1) % 3 === 0 && i + 1 != a.length && "," + n || n).reverse().join("");
}

var inputs = document.querySelectorAll("[type='text']");
inputs.forEach(function(input) {
  //change the values to include the thousand separator each time the user changes an input
  input.onchange = function(e) {
    inputs.forEach(function(inp) {
      inp.value = inp.value.replace(/[,]/g, '');
    });
    calcule2();
    inputs.forEach(function(inp) {
      inp.value = milesIt(inp.value);
    });

  }

  input.value = milesIt(input.value);
});
////////////////////////////////////////////

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
  // ... and fix the Previous/Next buttons:
  if (n == 0) {
    document.getElementById("prevBtn").style.display = "none";
  } else {
    document.getElementById("prevBtn").style.display = "inline";
  }
  if (n == (x.length - 1)) {
    document.getElementById("nextBtn").innerHTML = "Submit";
  } else {
    document.getElementById("nextBtn").innerHTML = "Next";
  }

  // ... and run a function that displays the correct step indicator:
  fixStepIndicator(n)
}

function nextPrev(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab");
  // Exit the function if any field in the current tab is invalid:
  if (n == 1 && !validateForm()) return false;
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
  if (currentTab >= x.length) {
    //...the form gets submitted:
    document.getElementById("CreativeAcquisitions").submit();
    return false;
  }
  // Otherwise, display the correct tab:
  showTab(currentTab);
}

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false:
      valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var i, x = document.getElementsByClassName("step");
  for (i = 0; i < x.length; i++) {
    x[i].className = x[i].className.replace(" active", "");
  }
  //... and adds the "active" class to the current step:
  x[n].className += " active";
}

function calcule2() {

  var i = 0;
  for (i = 0; i <= 50; i++) {
    calcule();
  }
}

function calcule() {

  CreativeAcquisitions.B28.value = parseFloat(CreativeAcquisitions.B17.value) + parseFloat(CreativeAcquisitions.B19.value) + parseFloat(CreativeAcquisitions.B21.value) + parseFloat(CreativeAcquisitions.B23.value) + parseFloat(CreativeAcquisitions.B25.value);

  CreativeAcquisitions.B52.value = (parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value)) + parseFloat(CreativeAcquisitions.D81.value) +
    parseFloat(CreativeAcquisitions.B300.value);

  CreativeAcquisitions.B55.value = parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value);
  CreativeAcquisitions.B56.value = parseFloat(CreativeAcquisitions.B28.value);

  //CreativeAcquisitions.B200.value = CreativeAcquisitions.B52.value; //testing
  //document.getElementById("B200").value = CreativeAcquisitions.B52.value;

  CreativeAcquisitions.B66.value = parseFloat(CreativeAcquisitions.B200.value);
  CreativeAcquisitions.B67.value = parseFloat(CreativeAcquisitions.D81.value);

  CreativeAcquisitions.B68.value = parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value);

  CreativeAcquisitions.B300.value = (parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value)) * -1;

  CreativeAcquisitions.B69.value = parseFloat(CreativeAcquisitions.B41.value);
  CreativeAcquisitions.B70.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;
  CreativeAcquisitions.B71.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B47.value)) / 100;
  CreativeAcquisitions.B72.value = parseFloat(CreativeAcquisitions.B66.value) - parseFloat(CreativeAcquisitions.B67.value) - parseFloat(CreativeAcquisitions.B70.value) - parseFloat(CreativeAcquisitions.B69.value) - parseFloat(CreativeAcquisitions.B71.value);
  CreativeAcquisitions.B76.value = parseFloat(CreativeAcquisitions.B17.value);
  CreativeAcquisitions.D76.value = (parseFloat(CreativeAcquisitions.B76.value) * parseFloat(CreativeAcquisitions.C76.value)) / 100;
  CreativeAcquisitions.B77.value = parseFloat(CreativeAcquisitions.B19.value);
  CreativeAcquisitions.D77.value = (parseFloat(CreativeAcquisitions.B77.value) * parseFloat(CreativeAcquisitions.C77.value)) / 100;
  CreativeAcquisitions.B78.value = parseFloat(CreativeAcquisitions.B21.value);
  CreativeAcquisitions.D78.value = (parseFloat(CreativeAcquisitions.B78.value) * parseFloat(CreativeAcquisitions.C78.value)) / 100;
  CreativeAcquisitions.B79.value = parseFloat(CreativeAcquisitions.B23.value);
  CreativeAcquisitions.D79.value = (parseFloat(CreativeAcquisitions.B79.value) * parseFloat(CreativeAcquisitions.C79.value)) / 100;
  CreativeAcquisitions.B80.value = parseFloat(CreativeAcquisitions.B25.value);
  CreativeAcquisitions.D80.value = (parseFloat(CreativeAcquisitions.B80.value) * parseFloat(CreativeAcquisitions.C80.value)) / 100;
  CreativeAcquisitions.B81.value = parseFloat(CreativeAcquisitions.B76.value) + parseFloat(CreativeAcquisitions.B77.value) + parseFloat(CreativeAcquisitions.B78.value) + parseFloat(CreativeAcquisitions.B79.value) + parseFloat(CreativeAcquisitions.B80.value);
  CreativeAcquisitions.D81.value = parseFloat(CreativeAcquisitions.D76.value) + parseFloat(CreativeAcquisitions.D77.value) + parseFloat(CreativeAcquisitions.D78.value) + parseFloat(CreativeAcquisitions.D79.value) + parseFloat(CreativeAcquisitions.D80.value);
  CreativeAcquisitions.B91.value = parseFloat(CreativeAcquisitions.B36.value);

  CreativeAcquisitions.B92.value = parseFloat(CreativeAcquisitions.B37.value);

  CreativeAcquisitions.B93.value = parseFloat(CreativeAcquisitions.B38.value);

  CreativeAcquisitions.B94.value = parseFloat(CreativeAcquisitions.B39.value);

  CreativeAcquisitions.B95.value = parseFloat(CreativeAcquisitions.B40.value);

  CreativeAcquisitions.B96.value = (parseFloat(CreativeAcquisitions.B52.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;

  CreativeAcquisitions.B97.value = parseFloat(CreativeAcquisitions.B41.value);

  CreativeAcquisitions.B98.value = (parseFloat(CreativeAcquisitions.B91.value) + parseFloat(CreativeAcquisitions.B92.value) + parseFloat(CreativeAcquisitions.B93.value) + parseFloat(CreativeAcquisitions.B94.value) + parseFloat(CreativeAcquisitions.B95.value) + parseFloat(CreativeAcquisitions.B96.value) + parseFloat(CreativeAcquisitions.B97.value)) * -1;

  CreativeAcquisitions.C98.value = (parseFloat(CreativeAcquisitions.C91.value) + parseFloat(CreativeAcquisitions.C92.value) + parseFloat(CreativeAcquisitions.C93.value) + parseFloat(CreativeAcquisitions.C94.value) + parseFloat(CreativeAcquisitions.C95.value) + parseFloat(CreativeAcquisitions.C96.value) + parseFloat(CreativeAcquisitions.C97.value)) * -1;

  CreativeAcquisitions.B101.value = parseFloat(CreativeAcquisitions.B4.value);
  CreativeAcquisitions.B105.value = (parseFloat(CreativeAcquisitions.B101.value) * parseFloat(CreativeAcquisitions.B103.value)) / 100;
  CreativeAcquisitions.B107.value = parseFloat(CreativeAcquisitions.C98.value);
  CreativeAcquisitions.B108.value = parseFloat(CreativeAcquisitions.B101.value) - parseFloat(CreativeAcquisitions.B105.value) + parseFloat(CreativeAcquisitions.B107.value);
}

Body:
I don't know how these fields are created but following your code, this may be helpful:

//////////Newcode///////////////////////////
function milesIt(num) {
  return Math.floor(num).toString().split("").reverse().map((n, i, a) =>
    (i + 1) % 3 === 0 && i + 1 != a.length && "," + n || n).reverse().join("");
}

var inputs = document.querySelectorAll("[type='text']");
inputs.forEach(function(input) {
  //change the values to include the thousand separator each time the user changes an input
  input.onchange = function(e) {
    inputs.forEach(function(inp) {
      inp.value = inp.value.replace(/[,]/g, '');
    });
    calcule2();
    inputs.forEach(function(inp) {
      inp.value = milesIt(inp.value);
    });
    //e.target.value = milesIt(e.target.value.replace(/[.]/g, ''));
  }
  //change the values of the inputs at the beginning, although you could write them as HTML with the thousand separator values in the source code
  input.value = milesIt(input.value);
});
////////////////////////////////////////////

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
  // ... and fix the Previous/Next buttons:
  if (n == 0) {
    document.getElementById("prevBtn").style.display = "none";
  } else {
    document.getElementById("prevBtn").style.display = "inline";
  }
  if (n == (x.length - 1)) {
    document.getElementById("nextBtn").style.display='none';
  } else {
    document.getElementById("nextBtn").innerHTML = "Next";
  }

  // ... and run a function that displays the correct step indicator:
  fixStepIndicator(n)
}

function nextPrev(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab");
  // Exit the function if any field in the current tab is invalid:
  if (n == 1 && !validateForm()) return false;
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
    if (n < (x.length - 2))
        document.getElementById("nextBtn").style.display='inline';
  // Otherwise, display the correct tab:
  showTab(currentTab);
}

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false:
      valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var i, x = document.getElementsByClassName("step");
  for (i = 0; i < x.length; i++) {
    x[i].className = x[i].className.replace(" active", "");
  }
  //... and adds the "active" class to the current step:
  x[n].className += " active";
}

function calcule2() {

  var i = 0;
  for (i = 0; i <= 50; i++) {
    calcule();
  }
}

function calcule() {

  CreativeAcquisitions.B28.value = parseFloat(CreativeAcquisitions.B17.value) + parseFloat(CreativeAcquisitions.B19.value) + parseFloat(CreativeAcquisitions.B21.value) + parseFloat(CreativeAcquisitions.B23.value) + parseFloat(CreativeAcquisitions.B25.value);

  CreativeAcquisitions.B52.value = (parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value)) + parseFloat(CreativeAcquisitions.D81.value) +
    parseFloat(CreativeAcquisitions.B300.value);

  CreativeAcquisitions.B55.value = parseFloat(CreativeAcquisitions.B4.value) * parseFloat(CreativeAcquisitions.B6.value);
  CreativeAcquisitions.B56.value = parseFloat(CreativeAcquisitions.B28.value);

  CreativeAcquisitions.B200.value = Math.round(parseFloat(CreativeAcquisitions.B52.value)); //here is your field

  CreativeAcquisitions.B66.value = parseFloat(CreativeAcquisitions.B200.value);
  CreativeAcquisitions.B67.value = parseFloat(CreativeAcquisitions.D81.value);

  CreativeAcquisitions.B68.value = parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value);

  CreativeAcquisitions.B300.value = (parseFloat(CreativeAcquisitions.B36.value) + parseFloat(CreativeAcquisitions.B37.value) + parseFloat(CreativeAcquisitions.B38.value) + parseFloat(CreativeAcquisitions.B39.value) + parseFloat(CreativeAcquisitions.B40.value)) * -1;

  CreativeAcquisitions.B69.value = parseFloat(CreativeAcquisitions.B41.value);
  CreativeAcquisitions.B70.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;
  CreativeAcquisitions.B71.value = (parseFloat(CreativeAcquisitions.B200.value) * parseFloat(CreativeAcquisitions.B47.value)) / 100;
  CreativeAcquisitions.B72.value = parseFloat(CreativeAcquisitions.B66.value) - parseFloat(CreativeAcquisitions.B67.value) - parseFloat(CreativeAcquisitions.B70.value) - parseFloat(CreativeAcquisitions.B69.value) - parseFloat(CreativeAcquisitions.B71.value);
  CreativeAcquisitions.B76.value = parseFloat(CreativeAcquisitions.B17.value);
  CreativeAcquisitions.D76.value = (parseFloat(CreativeAcquisitions.B76.value) * parseFloat(CreativeAcquisitions.C76.value)) / 100;
  CreativeAcquisitions.B77.value = parseFloat(CreativeAcquisitions.B19.value);
  CreativeAcquisitions.D77.value = (parseFloat(CreativeAcquisitions.B77.value) * parseFloat(CreativeAcquisitions.C77.value)) / 100;
  CreativeAcquisitions.B78.value = parseFloat(CreativeAcquisitions.B21.value);
  CreativeAcquisitions.D78.value = (parseFloat(CreativeAcquisitions.B78.value) * parseFloat(CreativeAcquisitions.C78.value)) / 100;
  CreativeAcquisitions.B79.value = parseFloat(CreativeAcquisitions.B23.value);
  CreativeAcquisitions.D79.value = (parseFloat(CreativeAcquisitions.B79.value) * parseFloat(CreativeAcquisitions.C79.value)) / 100;
  CreativeAcquisitions.B80.value = parseFloat(CreativeAcquisitions.B25.value);
  CreativeAcquisitions.D80.value = (parseFloat(CreativeAcquisitions.B80.value) * parseFloat(CreativeAcquisitions.C80.value)) / 100;
  CreativeAcquisitions.B81.value = parseFloat(CreativeAcquisitions.B76.value) + parseFloat(CreativeAcquisitions.B77.value) + parseFloat(CreativeAcquisitions.B78.value) + parseFloat(CreativeAcquisitions.B79.value) + parseFloat(CreativeAcquisitions.B80.value);
  CreativeAcquisitions.D81.value = parseFloat(CreativeAcquisitions.D76.value) + parseFloat(CreativeAcquisitions.D77.value) + parseFloat(CreativeAcquisitions.D78.value) + parseFloat(CreativeAcquisitions.D79.value) + parseFloat(CreativeAcquisitions.D80.value);
  CreativeAcquisitions.B91.value = parseFloat(CreativeAcquisitions.B36.value);

  CreativeAcquisitions.B92.value = parseFloat(CreativeAcquisitions.B37.value);

  CreativeAcquisitions.B93.value = parseFloat(CreativeAcquisitions.B38.value);

  CreativeAcquisitions.B94.value = parseFloat(CreativeAcquisitions.B39.value);

  CreativeAcquisitions.B95.value = parseFloat(CreativeAcquisitions.B40.value);

  CreativeAcquisitions.B96.value = (parseFloat(CreativeAcquisitions.B52.value) * parseFloat(CreativeAcquisitions.B46.value)) / 100;

  CreativeAcquisitions.B97.value = parseFloat(CreativeAcquisitions.B41.value);

  CreativeAcquisitions.B98.value = (parseFloat(CreativeAcquisitions.B91.value) + parseFloat(CreativeAcquisitions.B92.value) + parseFloat(CreativeAcquisitions.B93.value) + parseFloat(CreativeAcquisitions.B94.value) + parseFloat(CreativeAcquisitions.B95.value) + parseFloat(CreativeAcquisitions.B96.value) + parseFloat(CreativeAcquisitions.B97.value)) * -1;

  CreativeAcquisitions.C98.value = (parseFloat(CreativeAcquisitions.C91.value) + parseFloat(CreativeAcquisitions.C92.value) + parseFloat(CreativeAcquisitions.C93.value) + parseFloat(CreativeAcquisitions.C94.value) + parseFloat(CreativeAcquisitions.C95.value) + parseFloat(CreativeAcquisitions.C96.value) + parseFloat(CreativeAcquisitions.C97.value)) * -1;

  CreativeAcquisitions.B101.value = parseFloat(CreativeAcquisitions.B4.value);
  CreativeAcquisitions.B105.value = (parseFloat(CreativeAcquisitions.B101.value) * parseFloat(CreativeAcquisitions.B103.value)) / 100;
  CreativeAcquisitions.B107.value = parseFloat(CreativeAcquisitions.C98.value);
  CreativeAcquisitions.B108.value = parseFloat(CreativeAcquisitions.B101.value) - parseFloat(CreativeAcquisitions.B105.value) + parseFloat(CreativeAcquisitions.B107.value);
}


问:
AWS Appsync implementation using GraphQL-client library in .Net
I am trying to implement an app sync subscription similar to this python example but in .net https://aws.amazon.com/blogs/mobile/appsync-websockets-python/

I started this using the nuget package GraphQL.Client https://www.nuget.org/packages/GraphQL.Client
The execution of Query/Mutation is working fine like given in the readme of https://github.com/graphql-dotnet/graphql-client
But subscription is not working.

My code using the GraphQL.Client:

```<code>using var graphQLClient = new GraphQLHttpClient("https://<MY-API-PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql", new NewtonsoftJsonSerializer());

 graphQLClient.HttpClient.DefaultRequestHeaders.Add("host", "<API HOST without https or absolute path and 'realtime-' text in the api address>"); //As given in the python example

graphQLClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", "<API KEY>");
var req= new GraphQLRequest
{
    Query = @"subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){  content }}",
    Variables = new{}
};

IObservable<GraphQLResponse<Response>> subscriptionStream = graphQLClient.CreateSubscriptionStream<Response>(req, (Exception ex) =>
{
      Console.WriteLine("Error: {0}", ex.ToString());
});

var subscription = subscriptionStream.Subscribe(response =>
{
                Console.WriteLine($"Response'{Newtonsoft.Json.JsonConvert.SerializeObject(response)}' ");
},
ex =>
{
Console.WriteLine("Error{0}", ex.ToString());
});
</code>```

Its giving the exception "The remote party closed the WebSocket connection without completing the close handshake."

stack trace:

at System.Net.WebSockets.ManagedWebSocket.d__662.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at GraphQL.Client.Http.Websocket.GraphQLHttpWebSocket.d__40.MoveNext() in C:\Users\UserName\Source\repos\graphql-client\src\GraphQL.Client\Websocket\GraphQLHttpWebSocket.cs:line 546

Then I tried without this nuget and using standard websocket

Code without nuget:

```<code>static public async Task CallWebsocket()
        {
            try
            {
                _client = new ClientWebSocket();
                _client.Options.AddSubProtocol("graphql-ws");
                _client.Options.SetRequestHeader("host", "<HOST URL without wss but now with 'realtime' text in api url because otherwise we are getting SSL error>");
                _client.Options.SetRequestHeader("x-api-key", "<API KEY>");

                await _client.ConnectAsync(new Uri("https://<MY-APPSYNC_API_PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql"), CancellationToken.None);
                await SendCommand();
                var docList = await Receive();
            }
            catch(Exception ex)
            {

            }
        }

       static  private async Task SendCommand()
        {
            ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("'query' : 'subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){  content }}'"));
            await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
        }
        static private async Task<string> Receive()
        {
            var receiveBufferSize = 1536;
            byte[] buffer = new byte[receiveBufferSize];
            var result = await _client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            var resultJson = (new UTF8Encoding()).GetString(buffer);
            return resultJson;
        }
</code>```

I am getting below exception:

Inner exception: "An established connection was aborted by the software in your host machine."

Inner exception message: "Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.."

Message: "The remote party closed the WebSocket connection without completing the close handshake."

Could anyone please help with the correct implementation.

答:
Nuget won't work out of the box with AppSync subscriptions, so you will need to write your own client code for that, like you attempted in the second (non-nuget) example.

Now, for the second example, take a second look at the python example referenced in your question. There are several steps that are not included in your code. I will enumerate the required steps and try to port them to C# from the python code (note that I don't have a C# environment at hand so there might be syntax errors, but this code should be pretty close to what you need)

Step 0 - AppSync Endpoints

Assume the result of invoking aws appsync get-graphql-api --api-id example123456 for your API is:

{
    "graphqlApi": {
        "name": "myNewRealTimeGraphQL-API",
        "authenticationType": "<API_KEY>",
        "tags": {},
        "apiId": "example123456",
        "uris": {
            "GRAPHQL": "https://abc.appsync-api.us-west-2.amazonaws.com/graphql",
            "REALTIME": "wss://abc.appsync-realtime-api.us-west-2.amazonaws.com/graphql"
        },
        "arn": "arn:aws:appsync:us-west-2: xxxxxxxxxxxx:apis/xxxxxxxxxxxx"
    }
}
```
<h2>Step 1 - Build the connection URL</h2>
<h2>Step 2 - Connect to WebSocket Endpoint</h2>
<p>This includes sending a connection_init message as per the protocol mentioned in the python article</p>
<h2>Step 3 - Wait for connection_ack as per protocol</h2>
<p>Again, this is as per protocol</p>
<h2>Step 4 - Register subscription</h2>
<h2>Step 5 - Send mutation</h2>
<p>This step is not in this response, but can be done through the AWS console</p>
<h2>Step 6 - Wait for "data" messages</h2>
<p>These are the real-time events sent by AppSync</p>
<h2>Step 7 - Deregister subscription</h2>
<h2>Step 8 - Disconnect</h2>
<pre class="lang-cs prettyprint-override"><code>// These are declared at the same level as your _client

// This comes from the graphqlApi.uris.GRAPHQL in step 0, set as a var here for clarity
_gqlHost  = "abc.appsync-api.us-west-2.amazonaws.com";

// This comes from the graphqlApi.uris.REALTIME in step 0, set as a var here for clarity
_realtimeUri = "wss://abc.appsync-realtime-api.us-west-2.amazonaws.com/graphql";

_apiKey = "<API KEY>";

static public async Task CallWebsocket()
{

    // Step 1
    // This is JSON needed by the server, it will be converted to base64
    // (note: might be better to use something like Json.NET for this task)
    var header = var test = $@"{{
        ""host"":""{_gqlHost}"",
        ""x-api-key"": ""{_apiKey}""
    }}";

    // Now we need to encode the previous JSON to base64
    var headerB64 = System.Convert.ToBase64String(
        System.Text.Encoding.UTF8.GetBytes(header));

    UriBuilder connectionUriBuilder = new UriBuilder(_realtimeUri);
    connectionUriBuilder.Query = $"header={headerB64}&payload=e30=";

    try
    {
        _client = new ClientWebSocket();
        _client.Options.AddSubProtocol("graphql-ws");

        // Step 2
        await _client.ConnectAsync(connectionUriBuilder.Uri), CancellationToken.None);
        // Step 3
        await SendConnectionInit();
        await Receive();
    }
    catch(Exception ex)
    {

    }
}

static  private async Task SendConnectionInit()
{
    ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(@"{""type"": ""connection_init""}"));
    await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}

static  private async Task SendSubscription()
{
    // This detail is important, note that the subscription is a stringified JSON that will be embeded in the "data" field below
    var subscription = $@"{{\""query\"": \""subscription SubscribeToEventComments{{ subscribeToEventComments{{ content }} }}\"", \""variables\"": {{}} }}";

    var register = $@"{{
            ""id"": ""<SUB_ID>"",
            ""payload"": {{
                ""data"": ""{subscription}"",
                ""extensions"": {{
                    ""authorization"": {{
                        ""host"": ""{_gqlHost}"",
                        ""x-api-key"":""{_apiKey}""
                    }}
                }}
            }},
            ""type"": ""start""
        }}";

    // The output should look like below, note again the "data" field contains a stringified JSON that represents the subscription
    /*
    {
        "id": "<SUB_ID>",
        "payload": {
            "data": "{\"query\": \"subscription SubscribeToEventComments{ subscribeToEventComments{ content}}\", \"variables\": {} }",
            "extensions": {
                "authorization": {
                    "host": "abc.appsync-api.us-west-2.amazonaws.com",
                    "x-api-key":"<API KEY>"
                }
            }
        },
        "type": "start"
    }
    */

    ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(register));
    await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}

static  private async Task Deregister()
{
    var deregister = $@"{{
                            ""type"": ""stop"",
                            ""id"": ""<SUB_ID>""
                        }}"
    ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(deregister));
    await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}

static private async Task Receive()
{
    while (_socket.State == WebSocketState.Open)
    {
        ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);
        WebSocketReceiveResult result= null;
        using (var ms = new MemoryStream())
        {
            // This loop is needed because the server might send chunks of data that need to be assembled by the client
            // see: https://stackoverflow.com/questions/23773407/a-websockets-receiveasync-method-does-not-await-the-entire-message
            do
            {
                result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                ms.Write(buffer.Array, buffer.Offset, result.Count);
            }
            while (!result.EndOfMessage);

            ms.Seek(0, SeekOrigin.Begin);

            using (var reader = new StreamReader(ms, Encoding.UTF8))
            {
                // convert stream to string
                var message = reader.ReadToEnd();
                Console.WriteLine(message)
                // quick and dirty way to check response
                if (message.Contains("connection_ack"))
                {
                    // Step 4
                    await SendSubscription();
                } else if (message.Contains("data"))  // Step 6
                {
                    // Step 7
                    await Deregister();
                    // Step 8
                    await _client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }
            }
        }
    }
}

</code>```

Body:
I am trying to implement an app sync subscription similar to this python example but in .net https://aws.amazon.com/blogs/mobile/appsync-websockets-python/

I started this using the nuget package GraphQL.Client https://www.nuget.org/packages/GraphQL.Client
The execution of Query/Mutation is working fine like given in the readme of https://github.com/graphql-dotnet/graphql-client
But subscription is not working.

My code using the GraphQL.Client:

using var graphQLClient = new GraphQLHttpClient("https://<MY-API-PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql", new NewtonsoftJsonSerializer());

 graphQLClient.HttpClient.DefaultRequestHeaders.Add("host", "<API HOST without https or absolute path and 'realtime-' text in the api address>"); //As given in the python example

graphQLClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", "<API KEY>");
var req= new GraphQLRequest
{
    Query = @"subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){  content }}",
    Variables = new{}
};

IObservable<GraphQLResponse<Response>> subscriptionStream = graphQLClient.CreateSubscriptionStream<Response>(req, (Exception ex) =>
{
      Console.WriteLine("Error: {0}", ex.ToString());
});

var subscription = subscriptionStream.Subscribe(response =>
{
                Console.WriteLine($"Response'{Newtonsoft.Json.JsonConvert.SerializeObject(response)}' ");
},
ex =>
{
Console.WriteLine("Error{0}", ex.ToString());
});

Its giving the exception "The remote party closed the WebSocket connection without completing the close handshake."

stack trace:

at System.Net.WebSockets.ManagedWebSocket.d__662.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at GraphQL.Client.Http.Websocket.GraphQLHttpWebSocket.d__40.MoveNext() in C:\Users\UserName\Source\repos\graphql-client\src\GraphQL.Client\Websocket\GraphQLHttpWebSocket.cs:line 546

Then I tried without this nuget and using standard websocket

Code without nuget:

static public async Task CallWebsocket()
        {
            try
            {
                _client = new ClientWebSocket();
                _client.Options.AddSubProtocol("graphql-ws");
                _client.Options.SetRequestHeader("host", "<HOST URL without wss but now with 'realtime' text in api url because otherwise we are getting SSL error>");
                _client.Options.SetRequestHeader("x-api-key", "<API KEY>");

                await _client.ConnectAsync(new Uri("https://<MY-APPSYNC_API_PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql"), CancellationToken.None);
                await SendCommand();
                var docList = await Receive();
            }
            catch(Exception ex)
            {

            }
        }

       static  private async Task SendCommand()
        {
            ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("'query' : 'subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){  content }}'"));
            await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
        }
        static private async Task<string> Receive()
        {
            var receiveBufferSize = 1536;
            byte[] buffer = new byte[receiveBufferSize];
            var result = await _client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            var resultJson = (new UTF8Encoding()).GetString(buffer);
            return resultJson;
        }

I am getting below exception:

Inner exception: "An established connection was aborted by the software in your host machine."

Inner exception message: "Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.."

Message: "The remote party closed the WebSocket connection without completing the close handshake."

Could anyone please help with the correct implementation.

Body:
Nuget won't work out of the box with AppSync subscriptions, so you will need to write your own client code for that, like you attempted in the second (non-nuget) example.

Now, for the second example, take a second look at the python example referenced in your question. There are several steps that are not included in your code. I will enumerate the required steps and try to port them to C# from the python code (note that I don't have a C# environment at hand so there might be syntax errors, but this code should be pretty close to what you need)

Step 0 - AppSync Endpoints

Assume the result of invoking aws appsync get-graphql-api --api-id example123456 for your API is:

{
    "graphqlApi": {
        "name": "myNewRealTimeGraphQL-API",
        "authenticationType": "<API_KEY>",
        "tags": {},
        "apiId": "example123456",
        "uris": {
            "GRAPHQL": "https://abc.appsync-api.us-west-2.amazonaws.com/graphql",
            "REALTIME": "wss://abc.appsync-realtime-api.us-west-2.amazonaws.com/graphql"
        },
        "arn": "arn:aws:appsync:us-west-2: xxxxxxxxxxxx:apis/xxxxxxxxxxxx"
    }
}

Step 1 - Build the connection URL

Step 2 - Connect to WebSocket Endpoint

This includes sending a connection_init message as per the protocol mentioned in the python article

Step 3 - Wait for connection_ack as per protocol

Again, this is as per protocol

Step 4 - Register subscription

Step 5 - Send mutation

This step is not in this response, but can be done through the AWS console

Step 6 - Wait for "data" messages

These are the real-time events sent by AppSync

Step 7 - Deregister subscription

Step 8 - Disconnect

// These are declared at the same level as your _client

// This comes from the graphqlApi.uris.GRAPHQL in step 0, set as a var here for clarity
_gqlHost  = "abc.appsync-api.us-west-2.amazonaws.com";

// This comes from the graphqlApi.uris.REALTIME in step 0, set as a var here for clarity
_realtimeUri = "wss://abc.appsync-realtime-api.us-west-2.amazonaws.com/graphql";

_apiKey = "<API KEY>";

static public async Task CallWebsocket()
{

    // Step 1
    // This is JSON needed by the server, it will be converted to base64
    // (note: might be better to use something like Json.NET for this task)
    var header = var test = $@"{{
        ""host"":""{_gqlHost}"",
        ""x-api-key"": ""{_apiKey}""
    }}";

    // Now we need to encode the previous JSON to base64
    var headerB64 = System.Convert.ToBase64String(
        System.Text.Encoding.UTF8.GetBytes(header));

    UriBuilder connectionUriBuilder = new UriBuilder(_realtimeUri);
    connectionUriBuilder.Query = $"header={headerB64}&payload=e30=";

    try
    {
        _client = new ClientWebSocket();
        _client.Options.AddSubProtocol("graphql-ws");

        // Step 2
        await _client.ConnectAsync(connectionUriBuilder.Uri), CancellationToken.None);
        // Step 3
        await SendConnectionInit();
        await Receive();
    }
    catch(Exception ex)
    {

    }
}

static  private async Task SendConnectionInit()
{
    ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(@"{""type"": ""connection_init""}"));
    await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}

static  private async Task SendSubscription()
{
    // This detail is important, note that the subscription is a stringified JSON that will be embeded in the "data" field below
    var subscription = $@"{{\""query\"": \""subscription SubscribeToEventComments{{ subscribeToEventComments{{ content }} }}\"", \""variables\"": {{}} }}";

    var register = $@"{{
            ""id"": ""<SUB_ID>"",
            ""payload"": {{
                ""data"": ""{subscription}"",
                ""extensions"": {{
                    ""authorization"": {{
                        ""host"": ""{_gqlHost}"",
                        ""x-api-key"":""{_apiKey}""
                    }}
                }}
            }},
            ""type"": ""start""
        }}";

    // The output should look like below, note again the "data" field contains a stringified JSON that represents the subscription
    /*
    {
        "id": "<SUB_ID>",
        "payload": {
            "data": "{\"query\": \"subscription SubscribeToEventComments{ subscribeToEventComments{ content}}\", \"variables\": {} }",
            "extensions": {
                "authorization": {
                    "host": "abc.appsync-api.us-west-2.amazonaws.com",
                    "x-api-key":"<API KEY>"
                }
            }
        },
        "type": "start"
    }
    */

    ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(register));
    await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}

static  private async Task Deregister()
{
    var deregister = $@"{{
                            ""type"": ""stop"",
                            ""id"": ""<SUB_ID>""
                        }}"
    ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(deregister));
    await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}

static private async Task Receive()
{
    while (_socket.State == WebSocketState.Open)
    {
        ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);
        WebSocketReceiveResult result= null;
        using (var ms = new MemoryStream())
        {
            // This loop is needed because the server might send chunks of data that need to be assembled by the client
            // see: https://stackoverflow.com/questions/23773407/a-websockets-receiveasync-method-does-not-await-the-entire-message
            do
            {
                result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                ms.Write(buffer.Array, buffer.Offset, result.Count);
            }
            while (!result.EndOfMessage);

            ms.Seek(0, SeekOrigin.Begin);

            using (var reader = new StreamReader(ms, Encoding.UTF8))
            {
                // convert stream to string
                var message = reader.ReadToEnd();
                Console.WriteLine(message)
                // quick and dirty way to check response
                if (message.Contains("connection_ack"))
                {
                    // Step 4
                    await SendSubscription();
                } else if (message.Contains("data"))  // Step 6
                {
                    // Step 7
                    await Deregister();
                    // Step 8
                    await _client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }
            }
        }
    }
}