答:
In Java 8+ you can use java.time package.
If you date-time does not depend of Time Zone you can use LocalDateTime-class:

```<code>DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime start_date = LocalDateTime.parse("2020-02-10T11:30:00.000", dtf)
LocalDateTime end_date = LocalDateTime.of(2020,02,10,11,45,0,0);
for (int i = 0; i < 10; i++) {
    start_date = start_date.plusMinutes(15);
    end_date = end_date.plusMinutes(15);
    System.out.println("Start Date ->  " + start_date);
    System.out.println("End Date   ->  " + end_date);
    System.out.println("-----------------------------------------");
}
</code>```

Title: Increment the time by 15 mins in Java

Body:
I am able to get the time in format of 2020-02-10T11:30:00.000 as a start_time and end_time as 2020-02-10T11:45:00.000 as increment of 15 mins, now i want assign end_time into start_time, as well as end_time need to increase by 15 mins. This is where i am getting difficulty.

below is my code,

public class DateUtil {

    final static String PATTERN = "yyyy-MM-dd" +"\'T\'" +"HH:mm:00.000";
    SimpleDateFormat simpleDateFormat = null;

    DateFarmatorDemo dateFarmatorDemo = new DateFarmatorDemo();
    DateFormat dateFormat = null;

    static String start_date = null;
    static String end_date = null;
    static String temp_date = null;

    public void requiredDate() {

         Calendar start_date1 = Calendar.getInstance();
         start_date1.add(Calendar.DAY_OF_MONTH, -1);

         Calendar end_date1 = Calendar.getInstance();
         end_date1.add(Calendar.DAY_OF_MONTH, -1);
         end_date1.add(Calendar.MINUTE, +15);

         dateFormat = new SimpleDateFormat(PATTERN);
         start_date= dateFormat.format(start_date1.getTime());
         end_date= dateFormat.format(end_date1.getTime());

         for(int i=0; i <=10 ; i++) {
        //end_date= dateFormat.format(start_date1.getTime());
        //increment by 15 mins to end_date

                dateFarmatorDemo.setStart_Date(start_date);
                System.out.println("Start Date ->  "+ dateFarmatorDemo.getStart_Date());

                dateFarmatorDemo.setEnd_Date(end_date);
                System.out.println("End Date ->  " + dateFarmatorDemo.getEnd_Date());

                System.out.println("-----------------------------------------");
         }
    }
}

Body:
In Java 8+ you can use java.time package.
If you date-time does not depend of Time Zone you can use LocalDateTime-class:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime start_date = LocalDateTime.parse("2020-02-10T11:30:00.000", dtf)
LocalDateTime end_date = LocalDateTime.of(2020,02,10,11,45,0,0);
for (int i = 0; i < 10; i++) {
    start_date = start_date.plusMinutes(15);
    end_date = end_date.plusMinutes(15);
    System.out.println("Start Date ->  " + start_date);
    System.out.println("End Date   ->  " + end_date);
    System.out.println("-----------------------------------------");
}


来源: stackexchange

问:
Showing error for multiple empty inputs vuejs vuetify
I have three inputs as externalIP as External Host, externalHttpPort as Port and vendor as Vendor, I want to show error message if any of them is missing. but being specific about the name,

```<code>if (!this.externalIP || !this.externalHttpPort || !this.vendor) {
</code>```

when I do if condition, this works but I am not sure how I can tell if which input is empty. only one way which left is to add 3 multiple if

something like this

```<code>  let error;
  error = !this.externalIP
    ? "External IP Address (or URL) is incorrect"
    : "" || !this.externalHttpPort
    ? "Port is missing" : "" || !this.vendor
    ? "Please choose camera vendor or add your camera snapshot URL." : ""
  if (!error == "") {
    this.setNotification({
      text: error,
      color: "warning",
      snackbar: true
    })
    return
  }
</code>```

is there any other way of doing it? Also, Eslint show warning on indentations as well

答:
if vuetify you can use rules to check inputs

for example:
in your template:

```<code><v-text-field
    rules="[rules.required]"
    />
</code>```

and in your data:

```<code>data() {
    return {
      rules: {
        required: (value) => !!value || 'This field is required.'
      }
    }
  },
</code>```

you can add any other checking to rules array and just add it to your input by passing it to rules prop

hope it helps you!!!

ContentLicense: CC BY-SA 4.0

Body:
I have three inputs as externalIP as External Host, externalHttpPort as Port and vendor as Vendor, I want to show error message if any of them is missing. but being specific about the name,

if (!this.externalIP || !this.externalHttpPort || !this.vendor) {

when I do if condition, this works but I am not sure how I can tell if which input is empty. only one way which left is to add 3 multiple if

something like this

  let error;
  error = !this.externalIP
    ? "External IP Address (or URL) is incorrect"
    : "" || !this.externalHttpPort
    ? "Port is missing" : "" || !this.vendor
    ? "Please choose camera vendor or add your camera snapshot URL." : ""
  if (!error == "") {
    this.setNotification({
      text: error,
      color: "warning",
      snackbar: true
    })
    return
  }

is there any other way of doing it? Also, Eslint show warning on indentations as well

Body:
if vuetify you can use rules to check inputs

for example:
in your template:

<v-text-field
    rules="[rules.required]"
    />

and in your data:

data() {
    return {
      rules: {
        required: (value) => !!value || 'This field is required.'
      }
    }
  },

you can add any other checking to rules array and just add it to your input by passing it to rules prop

hope it helps you!!!


问:
Launching a new window and filling form values using Javascript
I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.

Starting page HTML:

```<code><form id="memCat" methed="get" class="member_catalogue">
     <button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
      <div class="cat_block">
            <label class="cat_label" for="cat_name">Product Name:</label>
            <input class="cat_input" type="text" id="catID" value="bepot002" readonly>
       </div>
       <div class="cat_block">
             <label class="cat_label" for="cat_description">Product Description:</label>
             <input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
        </div>
        <div class="cat_block">
               <label class="cat_label" for="cat_price">Per unit price:$</label>
               <input class="cat_input" type="number" id="catVal" value="10" readonly>
        </div>
 </form>
</code>```

New page HTML:

```<code><form id="memOrder" method="post">
      <div>
           <label for="pname">Product Name:</label>
           <input type="text" id="orderID" readonly>
      </div>
      <div>
           <label for="pdescription">Product Description:</label>
           <input type="text" id="orderDesc" readonly>
      </div>
      <div>
            <label for="quantity">Quantity ordered:</label>
            <input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
      </div>
      <div>
            <label for="ind_price">Per unit price: $</label>
            <input type="number" class="quantCount" id="orderVal" readonly>
      </div>
      <div>
            <label for="tot_price">Total Price: $</label>
            <input type="number" class="quantCount" id="orderTotal" readonly>
      </div>
      <div>
            <button type="reset">Clear Order</button>
            <button type="submit" id="orderCalc">Calculate Total</button>
            <button type="submit" id="orderPlace">Place Order</button>
      </div>
</form>
</code>```

Script i have to date:

```<code>function openMemberOrder() {
    document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
    document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
    document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
    memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
</code>```

script and other meta tags in head are correct as other code is working correctly.

答:
So after much trial and error i have had success with this:

On the submission page:

 1. I created a button on the page that will capture the input form data

 2. i created the localstorage function in JS

 3. I then placed the script tag at the bottom of the page before the closing body tag

```<code>HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>

Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;

function openMemberOrder() {
    var memberOrderWindow;
    localStorage.setItem("catID", document.getElementById("catID").value);
    localStorage.setItem("catDesc", document.getElementById("catDesc").value);
    localStorage.setItem("catVal", document.getElementById("catVal").value);
    memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;

Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
</code>```

I then created the new page with the following javascript in the header loading both an image grid as well as input element values:

```<code>var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');

    for (var rowN=1; rowN<5; rowN++) {
        for (var colN = 1; colN < 6; colN++){
            urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
        }
    }

window.onload = function urlLoad(){
        document.getElementById('gridContainer').innerHTML = urlArray;
        document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
        document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
        document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
        };
</code>```

I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.

```<code>function total() {
        var Quantity = document.getElementById('orderQuant').value;
        var Value = document.getElementById('orderVal').value;
        var Total = Quantity * Value;
        document.getElementById('orderTotal').value = Total;
    }

function clearForm() {
        var i = 0;
        var j = 0;
        document.getElementById('orderQuant').value = i;
        document.getElementById('orderTotal').value = j;
    }
</code>```

Body:
I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.

Starting page HTML:

<form id="memCat" methed="get" class="member_catalogue">
     <button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"></button>

            Product Name:
            <input class="cat_input" type="text" id="catID" value="bepot002" readonly>

             Product Description:
             <input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>

               Per unit price:$
               <input class="cat_input" type="number" id="catVal" value="10" readonly>

 </form>

New page HTML:

<form id="memOrder" method="post">

           Product Name:
           <input type="text" id="orderID" readonly>

           Product Description:
           <input type="text" id="orderDesc" readonly>

            Quantity ordered:
            <input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">

            Per unit price: $
            <input type="number" class="quantCount" id="orderVal" readonly>

            Total Price: $
            <input type="number" class="quantCount" id="orderTotal" readonly>

            <button type="reset">Clear Order</button>
            <button type="submit" id="orderCalc">Calculate Total</button>
            <button type="submit" id="orderPlace">Place Order</button>

</form>

Script i have to date:

function openMemberOrder() {
    document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
    document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
    document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
    memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};

script and other meta tags in head are correct as other code is working correctly.

Body:
So after much trial and error i have had success with this:

On the submission page:

 1. I created a button on the page that will capture the input form data

 2. i created the localstorage function in JS

 3. I then placed the script tag at the bottom of the page before the closing body tag

HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>

Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;

function openMemberOrder() {
    var memberOrderWindow;
    localStorage.setItem("catID", document.getElementById("catID").value);
    localStorage.setItem("catDesc", document.getElementById("catDesc").value);
    localStorage.setItem("catVal", document.getElementById("catVal").value);
    memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;

Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>

I then created the new page with the following javascript in the header loading both an image grid as well as input element values:

var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');

    for (var rowN=1; rowN<5; rowN++) {
        for (var colN = 1; colN < 6; colN++){
            urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
        }
    }

window.onload = function urlLoad(){
        document.getElementById('gridContainer').innerHTML = urlArray;
        document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
        document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
        document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
        };

I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.

function total() {
        var Quantity = document.getElementById('orderQuant').value;
        var Value = document.getElementById('orderVal').value;
        var Total = Quantity * Value;
        document.getElementById('orderTotal').value = Total;
    }

function clearForm() {
        var i = 0;
        var j = 0;
        document.getElementById('orderQuant').value = i;
        document.getElementById('orderTotal').value = j;
    }


问:
dplyr separate with regex
I have the following dataframe. It has 1 column of text that I would like to separate into multiple columns using the separate function from dplyr.

```<code>df <- structure(list(CPT.Codes = structure(c(2L, 1L, 3L, 4L, 5L), .Label = c("28296 - CORRECTION OF BUNION...., 64445P - N BLOCK INJ, SCIATIC, SNG, 76942P - US GUIDE, NEEDLE PLACEMENT",
"36821 - AV FUSION DIRECT ANY SITE, 99100P - ANESTHESIA FOR PT OF EXTREME AGE",
"41899 - DENTAL SURGERY PROCEDURE", "50593 - PERC CRYO ABLATE RENAL TUM, 99100P - ANESTHESIA FOR PT OF EXTREME AGE",
"64721 - CARPAL TUNNEL SURGERY"), class = "factor")), class = "data.frame", row.names = c(NA,
-5L))
</code>```

My desired output is the dataframe below. Each 5-digit number or 5-digit number + letter represents the code and the text following the dash is the code's description. Sometime's the code's description has single-digit numbers and multiple commas, so the regular expression will need to recognize the 5-digit number as a new code.

```<code>dfDesired <- structure(list(CPTcode1 = c(36821L, 28296L, 41899L, 50593L, 64721L
), CPTdescrip1 = structure(c(1L, 3L, 4L, 5L, 2L), .Label = c("AV FUSION DIRECT ANY SITE",
"CARPAL TUNNEL SURGERY", "CORRECTION OF BUNION....", "DENTAL SURGERY PROCEDURE",
"PERC CRYO ABLATE RENAL TUM"), class = "factor"), CPTcode2 = structure(c(2L,
1L, NA, 2L, NA), .Label = c("64445P", "99100P"), class = "factor"),
    CPTdescrip2 = structure(c(1L, 2L, NA, 1L, NA), .Label = c("ANESTHESIA FOR PT OF EXTREME AGE",
    "N BLOCK INJ"), class = "factor"), CPTcode3 = structure(c(NA,
    1L, NA, NA, NA), .Label = "76942P", class = "factor"), CPTdescrip3 = structure(c(NA,
    1L, NA, NA, NA), .Label = "US GUIDE NEEDLE PLACEMENT", class = "factor")), class = "data.frame", row.names = c(NA,
-5L))
</code>```

I have tried variations of the code below. It is wrong. I am new to regular expressions, and cannot figure this out with existing examples.

```<code> CPT %>%
  separate(CPT.Codes,
           into = c("CPTcode1", "CPTdescrip1", "CTPcode2", "CPTdescrip2", "CPTcode3", "CPTdescrip3"),
           sep = "(?<=[A-Z]) ?(?=[0-9])", remove = F) %>%
  glimpse
</code>```

Thanks in advance.

答:
You may split with

```<code>sep = ",(?=\\s*\\d{5})\\s*|\\s+-\\s+"
</code>```

See the regex demo.

Details

,(?=\s*\d{5})\s* - a comma , that is followed with 0+ whitespaces and then any five digits, and then 0+ whitespaces

|  - or

\s+-\s+ - a - char enclosed with 1+ whitespace characters.

Title: dplyr separate with regex

Body:
I have the following dataframe. It has 1 column of text that I would like to separate into multiple columns using the separate function from dplyr.

df <- structure(list(CPT.Codes = structure(c(2L, 1L, 3L, 4L, 5L), .Label = c("28296 - CORRECTION OF BUNION...., 64445P - N BLOCK INJ, SCIATIC, SNG, 76942P - US GUIDE, NEEDLE PLACEMENT",
"36821 - AV FUSION DIRECT ANY SITE, 99100P - ANESTHESIA FOR PT OF EXTREME AGE",
"41899 - DENTAL SURGERY PROCEDURE", "50593 - PERC CRYO ABLATE RENAL TUM, 99100P - ANESTHESIA FOR PT OF EXTREME AGE",
"64721 - CARPAL TUNNEL SURGERY"), class = "factor")), class = "data.frame", row.names = c(NA,
-5L))

My desired output is the dataframe below. Each 5-digit number or 5-digit number + letter represents the code and the text following the dash is the code's description. Sometime's the code's description has single-digit numbers and multiple commas, so the regular expression will need to recognize the 5-digit number as a new code.

dfDesired <- structure(list(CPTcode1 = c(36821L, 28296L, 41899L, 50593L, 64721L
), CPTdescrip1 = structure(c(1L, 3L, 4L, 5L, 2L), .Label = c("AV FUSION DIRECT ANY SITE",
"CARPAL TUNNEL SURGERY", "CORRECTION OF BUNION....", "DENTAL SURGERY PROCEDURE",
"PERC CRYO ABLATE RENAL TUM"), class = "factor"), CPTcode2 = structure(c(2L,
1L, NA, 2L, NA), .Label = c("64445P", "99100P"), class = "factor"),
    CPTdescrip2 = structure(c(1L, 2L, NA, 1L, NA), .Label = c("ANESTHESIA FOR PT OF EXTREME AGE",
    "N BLOCK INJ"), class = "factor"), CPTcode3 = structure(c(NA,
    1L, NA, NA, NA), .Label = "76942P", class = "factor"), CPTdescrip3 = structure(c(NA,
    1L, NA, NA, NA), .Label = "US GUIDE NEEDLE PLACEMENT", class = "factor")), class = "data.frame", row.names = c(NA,
-5L))

I have tried variations of the code below. It is wrong. I am new to regular expressions, and cannot figure this out with existing examples.

 CPT %>%
  separate(CPT.Codes,
           into = c("CPTcode1", "CPTdescrip1", "CTPcode2", "CPTdescrip2", "CPTcode3", "CPTdescrip3"),
           sep = "(?<=[A-Z]) ?(?=[0-9])", remove = F) %>%
  glimpse

Thanks in advance.

Body:
You may split with

sep = ",(?=\\s*\\d{5})\\s*|\\s+-\\s+"

See the regex demo.

Details

,(?=\s*\d{5})\s* - a comma , that is followed with 0+ whitespaces and then any five digits, and then 0+ whitespaces

|  - or

\s+-\s+ - a - char enclosed with 1+ whitespace characters.


问:
How can I change the default port in react from 3000 to another port?

how to change react default port 3000 to others port ?

By default, a ReactJS app runs on port 3000. An Express.js app also runs on the same port 3000. If you were to run the two apps simultaneously, there would be conflicts. You need to change the port of one of them.
In ReactJS, the easiest way to alter the port number is by setting an environment variable named PORT to the desired number via the terminal. As an example, here we change the port number to 5000.

if you use In Linux and Mac terminals, it would be

```<code>$export PORT=5000
</code>```

or if you use In Windows, the command is slightly different

```<code>$env:PORT=5000
</code>```

and finally start npm

```<code>npm start
</code>```

NB: It is for .env file

If you want to modify your package.json
Default is

```<code>"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}
</code>```

and modify by

```<code>  "start": "PORT=2000 react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}
</code>```

and finally run again

I use this

modify your package.json Linux and MacOS :

```<code>"start": "PORT=3006 react-scripts start"
</code>```

or

```<code>"start": "export PORT=6000 react-scripts start"
</code>```

or Windows

```<code>"start": "set PORT=6000 && react-scripts start"
</code>```

and finally restart npm

I try to change default port by using this and success, So you can try

If better solution Please help me

答:
A better way would be to add a .env file to your root folder. In it, just write:

PORT=<YOUR_PORT>.

This way is better, since you don't have to account for all operating systems. It will just work for all of them because of the way create-react-app works.

Body:
how to change react default port 3000 to others port ?

By default, a ReactJS app runs on port 3000. An Express.js app also runs on the same port 3000. If you were to run the two apps simultaneously, there would be conflicts. You need to change the port of one of them.
In ReactJS, the easiest way to alter the port number is by setting an environment variable named PORT to the desired number via the terminal. As an example, here we change the port number to 5000.

if you use In Linux and Mac terminals, it would be

$export PORT=5000

or if you use In Windows, the command is slightly different

$env:PORT=5000

and finally start npm

npm start

NB: It is for .env file

If you want to modify your package.json
Default is

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}

and modify by

  "start": "PORT=2000 react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}

and finally run again

I use this

modify your package.json Linux and MacOS :

"start": "PORT=3006 react-scripts start"

or

"start": "export PORT=6000 react-scripts start"

or Windows

"start": "set PORT=6000 && react-scripts start"

and finally restart npm

I try to change default port by using this and success, So you can try

If better solution Please help me


问:
Using Hist function to build series of 1D histograms in Python 3d plot
I am using pythons hist function to generate 1d histograms each linked to a given experiment.
Now I understand that the Hist function allows one to plot multiple histograms on the same x axis for comparison. I normally use something akin to the following for this purpose and the result is a very nice plot where x1,x2 and x3 are defined as follows
x1 = lengths expt1
x2 = lengths expt2
x3 = lengths expt3

```<code>P.figure()
n, bins, patches = P.hist( [x0,x1,x2], 10, weights=[w0, w1, w2], histtype='bar')
P.show()
</code>```

I was hoping to try achieve a 3d effect however and therefore I ask dose anyone know if it is it possible to have each unique histogram offset from the other in the y plane by a given unit thus generating a 3d effect.

I would appreciate any help on this .

答: Have you tried that? http://toeholds.wordpress.com/2010/03/26/3d-bar-histogram-in-python/ </p>

ContentLicense: CC BY-SA 3.0

Body:
I am using pythons hist function to generate 1d histograms each linked to a given experiment.
Now I understand that the Hist function allows one to plot multiple histograms on the same x axis for comparison. I normally use something akin to the following for this purpose and the result is a very nice plot where x1,x2 and x3 are defined as follows
x1 = lengths expt1
x2 = lengths expt2
x3 = lengths expt3

P.figure()
n, bins, patches = P.hist( [x0,x1,x2], 10, weights=[w0, w1, w2], histtype='bar')
P.show()

I was hoping to try achieve a 3d effect however and therefore I ask dose anyone know if it is it possible to have each unique histogram offset from the other in the y plane by a given unit thus generating a 3d effect.

I would appreciate any help on this .


问:
How to submit a Thymeleaf form on text box value change?
I am working on a simple application using Spring Boot and Thymeleaf. I want to submit the form on text box value change. I am not sure whether we can call the "th:action="@{/greeting}"" through java script?

--Here is my html greeting.html

```<code><!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>Form</h1>
    <form action="#" th:action="@{/greeting}" th:object="${greeting}"
        method="post">
        <table border="1">
            <tr>
                <td>Id:</td>
                <td><input type="text" th:field="*{id}" /></td>
            </tr>
            <tr>
                <td>Message:</td>
                <td><input type="text" th:field="*{content}" /></td>
            </tr>
        </table>
        <p>
            <input type="submit" value="Submit" /> <input type="reset"
                value="Reset" />
        </p>
    </form>
</body>
</html>
</code>```

--Controller Class :: GreetingController.java

```<code>package com.example.handlingformsubmission;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class GreetingController {

    @GetMapping("/greeting")
    public String greetingForm(Model model) {
        Greeting greeting = new Greeting();
        greeting.setId(108);
        greeting.setContent("Welcome");
        model.addAttribute("greeting", greeting);
        return "greeting";
    }

    @PostMapping("/greeting")
    public String greetingSubmit(@ModelAttribute Greeting greeting) {
        greeting.setId(greeting.getId()+1);
        return "greeting";
    }

}
</code>```

答:
Javascript will not be aware of th:action="@{/greeting} since it's thymeleaf domain name.
Instead, you can simply use the /greeting URL since you are in the same domain name it will directly hit your controller. An example in jquery can be like this:

    function onChange() {
        $.ajax({
            url: '/greeting',
            type: 'POST',
            data: {attribute_of_greeting_1:'value_to_post_1',attribute_of_greeting_2:'value_to_post_2'}
        })
    }

 Ad then link this function to your event.

Body:
I am working on a simple application using Spring Boot and Thymeleaf. I want to submit the form on text box value change. I am not sure whether we can call the "th:action="@{/greeting}"" through java script?

--Here is my html greeting.html

<!DOCTYPE HTML>

<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Form

    <form action="#" th:action="@{/greeting}" th:object="${greeting}"
        method="post">

                Id:
                <input type="text" th:field="*{id}" />

                Message:
                <input type="text" th:field="*{content}" />

            <input type="submit" value="Submit" /> <input type="reset"
                value="Reset" />

    </form>

--Controller Class :: GreetingController.java

package com.example.handlingformsubmission;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class GreetingController {

    @GetMapping("/greeting")
    public String greetingForm(Model model) {
        Greeting greeting = new Greeting();
        greeting.setId(108);
        greeting.setContent("Welcome");
        model.addAttribute("greeting", greeting);
        return "greeting";
    }

    @PostMapping("/greeting")
    public String greetingSubmit(@ModelAttribute Greeting greeting) {
        greeting.setId(greeting.getId()+1);
        return "greeting";
    }

}


问:
Get func placeholder values from a snippet to appear after hitting tab at top level code level
New to swift and xcode, version 11.3.1.

If I hit func<tab> in a class, the placeholder values pop in nicely and I can tab through them to complete them.

However, when I have a simple playground file open and hit func<tab> I don't see any placeholder values. Just the keyword func appears.

How do I turn on these placeholder values for top-level functions?

答:
What you are talking about are "code snippets". You can insert them not only by typing the "magic word", but also by clicking on the plus sign on the top right, then choosing from the list:

If you search for "Function", you can find the one you're looking for.

But who wants to click a button when writing code, right? It seems like some of the snippets somehow can't be used in playgrounds, while others can. This seems like an Xcode bug. For me, things like var, varget, vargetset all worked.

As an workaround, you can create your own code snippet for a function. First, paste this code into Xcode:

```<code>func <#name#>(<#parameters#>) -> <#return type#> {
    <#function body#>
}
</code>```

Select all of it, then go to Editor -> Create Code Snippet. Give it a name, and most importantly, a "Completion".

Apparently, you can still put func as the "Completion" and it will work.

Body:
What you are talking about are "code snippets". You can insert them not only by typing the "magic word", but also by clicking on the plus sign on the top right, then choosing from the list:

If you search for "Function", you can find the one you're looking for.

But who wants to click a button when writing code, right? It seems like some of the snippets somehow can't be used in playgrounds, while others can. This seems like an Xcode bug. For me, things like var, varget, vargetset all worked.

As an workaround, you can create your own code snippet for a function. First, paste this code into Xcode:

func <#name#>(<#parameters#>) -> <#return type#> {
    <#function body#>
}

Select all of it, then go to Editor -> Create Code Snippet. Give it a name, and most importantly, a "Completion".

Apparently, you can still put func as the "Completion" and it will work.


问:
Implementation of Dekker's algoirthm with atomic
I am reading about C++ memory model how these are applied.
I really confused when the  sequentially consistent model is necessary instead of the acquire-release model.
For example let's examine the Dekker's algorithm
Reading the following tutorial https://www.think-cell.com/en/career/talks/pdf/think-cell_talk_memorymodel.pdf , it is recommended to use sequentially consistent model for the Dekker's algorithm.

Have a look in the following example

```<code>atomic<bool> f1=false;
atomic<bool> f2=false;

//thread 1
f1.store(true, memory_order_seq_cst);
if (!f2.load(memory_order_seq_cst)) {
// critical section
}
f1.store(false);

//thread 2
f2.store(true, memory_order_seq_cst);
if (!f1.load(memory_order_seq_cst)) {
// critical section
}
f2.store(false);
</code>```

Why the release-acquire model in this case cannot quarantee that store and load operations take place without any reordering?

Thank you
George

答: Memory operations here indeed take place without reordering inside a single thread. But, there is no guarantee between threads. To achieve the desired behavior you have to use atomic compare exchange functions.</p>

Body:
I am reading about C++ memory model how these are applied.
I really confused when the  sequentially consistent model is necessary instead of the acquire-release model.
For example let's examine the Dekker's algorithm
Reading the following tutorial https://www.think-cell.com/en/career/talks/pdf/think-cell_talk_memorymodel.pdf , it is recommended to use sequentially consistent model for the Dekker's algorithm.

Have a look in the following example

atomic<bool> f1=false;
atomic<bool> f2=false;

//thread 1
f1.store(true, memory_order_seq_cst);
if (!f2.load(memory_order_seq_cst)) {
// critical section
}
f1.store(false);

//thread 2
f2.store(true, memory_order_seq_cst);
if (!f1.load(memory_order_seq_cst)) {
// critical section
}
f2.store(false);

Why the release-acquire model in this case cannot quarantee that store and load operations take place without any reordering?

Thank you
George


问:
emacs ( recompile -y )
Is it possible to pass a "-yes" flag to the 'recompile' command in emacs?

Excuse my complete lack of (e)lisp know-how. I got sick of going outside Emacs to compile my latex code, so i added the following key binding to my .emacs:

```<code>(global-set-key (kbd "<f12>") 'recompile);
</code>```

Is it possible to automatically answer 'yes' to the following prompt that might appear:
"A compilation process is running; kill it? (yes or no)."

Also, is it possible to make the window that opens and shows the output to scroll to the bottom automatically. The interesting stuff is typically down there. Maybe its possible to chain the following command after recompile: "C-x o, end-of-buffer".

Thanks!

答:
This behaviour is governed by the compilation-always-kill global variable.  Customize it via customize-variable and set it to t.

Not sure which version of emacs first had this, but 26 and newer certainly does.

ContentLicense: CC BY-SA 2.5

Title: emacs ( recompile -y )

Body:
Is it possible to pass a "-yes" flag to the 'recompile' command in emacs?

Excuse my complete lack of (e)lisp know-how. I got sick of going outside Emacs to compile my latex code, so i added the following key binding to my .emacs:

(global-set-key (kbd "<f12>") 'recompile);

Is it possible to automatically answer 'yes' to the following prompt that might appear:
"A compilation process is running; kill it? (yes or no)."

Also, is it possible to make the window that opens and shows the output to scroll to the bottom automatically. The interesting stuff is typically down there. Maybe its possible to chain the following command after recompile: "C-x o, end-of-buffer".

Thanks!


问:
Problem With ViewHolder In Androidx RecyclerView
in androidX when i make a RecyclerView Adapter i can't change ViewHolder to my private ViewHolder.
please see this code:

```<code>@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
}
</code>```

when i change that RecyclerView.ViewHolder to my advance ViewHolder  like this :

```<code>public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView name;
    ImageView image;

    public MyViewHolder(View itemView) {
        super(itemView);

        name = (TextView) itemView.findViewById(R.id.name);
        image = (ImageView) itemView.findViewById(R.id.image);
    }
}
</code>```

onBindViewHolder full broked . How can i solve this problem?

edit for put ViewHolder Code:

```<code>import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class CountryImageAdapter extends RecyclerView.Adapter {

  ArrayList personNames;
  ArrayList personImages;
  Context context;

  public CountryImageAdapter(Context context, ArrayList personNames, ArrayList personImages) {
    this.context = context;
    this.personNames = personNames;
    this.personImages = personImages;
  }

  @NonNull
  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    // infalte the item Layout
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample_gridlayout, parent, false);
    // set the view's size, margins, paddings and layout parameters
    MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
    return vh;
  }

  @Override
  public void onBindViewHolder(MyViewHolder holder, int position) {

    holder.name.setText(personNames.get(position));
    holder.image.setImageResource(personImages.get(position));
    // implement setOnClickListener event on item view.
    holder.itemView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        // open another activity on item click
        Intent intent = new Intent(context, ListOfClickActivity.class);
        intent.putExtra("TAG", "Country=" + personImages.get(position));
        context.startActivity(intent);
      }
    });

  }

  @Override
  public int getItemCount() {
    return personNames.size();
  }

  public class MyViewHolder extends RecyclerView.ViewHolder {
    // init the item view's
    TextView name;
    ImageView image;

    public MyViewHolder(View itemView) {
      super(itemView);
      // get the reference of item view's
      name = (TextView) itemView.findViewById(R.id.name);
      image = (ImageView) itemView.findViewById(R.id.image);
    }
  }

}
</code>```

答:
You have to use your advance ViewHolder  in your CountryImageAdapter to work with.

```<code>public class CountryImageAdapter extends RecyclerView.Adapter<CountryImageAdapter.MyViewHolder> {
    ....

    public CountryImageAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        ....
    }

    @Override
    public void onBindViewHolder(@NonNull CountryImageAdapter.MyViewHolder holder, int position) {

        ....
    }
}
</code>```

Body:
in androidX when i make a RecyclerView Adapter i can't change ViewHolder to my private ViewHolder.
please see this code:

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
}

when i change that RecyclerView.ViewHolder to my advance ViewHolder  like this :

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView name;
    ImageView image;

    public MyViewHolder(View itemView) {
        super(itemView);

        name = (TextView) itemView.findViewById(R.id.name);
        image = (ImageView) itemView.findViewById(R.id.image);
    }
}

onBindViewHolder full broked . How can i solve this problem?

edit for put ViewHolder Code:

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class CountryImageAdapter extends RecyclerView.Adapter {

  ArrayList personNames;
  ArrayList personImages;
  Context context;

  public CountryImageAdapter(Context context, ArrayList personNames, ArrayList personImages) {
    this.context = context;
    this.personNames = personNames;
    this.personImages = personImages;
  }

  @NonNull
  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    // infalte the item Layout
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample_gridlayout, parent, false);
    // set the view's size, margins, paddings and layout parameters
    MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
    return vh;
  }

  @Override
  public void onBindViewHolder(MyViewHolder holder, int position) {

    holder.name.setText(personNames.get(position));
    holder.image.setImageResource(personImages.get(position));
    // implement setOnClickListener event on item view.
    holder.itemView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        // open another activity on item click
        Intent intent = new Intent(context, ListOfClickActivity.class);
        intent.putExtra("TAG", "Country=" + personImages.get(position));
        context.startActivity(intent);
      }
    });

  }

  @Override
  public int getItemCount() {
    return personNames.size();
  }

  public class MyViewHolder extends RecyclerView.ViewHolder {
    // init the item view's
    TextView name;
    ImageView image;

    public MyViewHolder(View itemView) {
      super(itemView);
      // get the reference of item view's
      name = (TextView) itemView.findViewById(R.id.name);
      image = (ImageView) itemView.findViewById(R.id.image);
    }
  }

}

Body:
You have to use your advance ViewHolder  in your CountryImageAdapter to work with.

public class CountryImageAdapter extends RecyclerView.Adapter<CountryImageAdapter.MyViewHolder> {
    ....

    public CountryImageAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        ....
    }

    @Override
    public void onBindViewHolder(@NonNull CountryImageAdapter.MyViewHolder holder, int position) {

        ....
    }
}


问:
How can I clear test data in Stripe via the API?
I'm familiar with the process of clearing test data via the dashboard in Stripe (as per the image).

For testing purposes, I would like to clear the test data as part of the tear down process of our unit tests - to have a clean state at the end of each test cycle.

The API documentation doesn't mention anything, so is there an undocumented way to clear the test data?

Just a note, in the new dashboard, test data deletion lives on the Developers tab:

答:
In the latest update of stripe you can find the action button for removing test data in

https://dashboard.stripe.com/test/developers


问:
Is it possible to start adb logcat without cable?
Android studio 3.6
If I want to start adb I use USB/microUSB cable. After plugin cable I start in console command:

```<code>adb logcat -vtime
</code>```

And as result I see all logs of my application.

Nice. It's work find.

Is it possible to start adb logcat  WITHOUT cable?

答:
This work for me on Windows machine:

Get phone's ip address. Settings->About device-> Status

Enable Developer options

Turn on USB Debugging

Plug In cable

adb tcpip 5555

Unplugging cable

adb connect "IP address of your phone".

Ready

adb logcat -vtime

To disconnect just type:
adb disconnect

P.S. Print device's ip address by adb

```<code>adb shell ip addr show wlan0 | grep "inet\s" | awk '{print $2}' | awk -F'/' '{print $1}'
</code>```

Body:
Android studio 3.6
If I want to start adb I use USB/microUSB cable. After plugin cable I start in console command:

adb logcat -vtime

And as result I see all logs of my application.

Nice. It's work find.

Is it possible to start adb logcat  WITHOUT cable?

Body:
This work for me on Windows machine:

Get phone's ip address. Settings->About device-> Status

Enable Developer options

Turn on USB Debugging

Plug In cable

adb tcpip 5555

Unplugging cable

adb connect "IP address of your phone".

Ready

adb logcat -vtime

To disconnect just type:
adb disconnect

P.S. Print device's ip address by adb

adb shell ip addr show wlan0 | grep "inet\s" | awk '{print $2}' | awk -F'/' '{print $1}'


问:
Azure Deserialize JSON Response C#
I try to deserialize my JSON Response which is at below, but when i print the content of each parameter, it shows error.

My JSON Resposne:

```<code>[
{
  "faceRectangle": {
     "top": 214,
     "left": 472,
     "width": 450,
     "height": 450
  },
  "faceAttributes": {
     "age": 19.0,
     "emotion": {
        "anger": 0.0,
        "contempt": 0.0,
        "disgust": 0.0,
        "fear": 0.0,
        "happiness": 0.0,
        "neutral": 0.996,
        "sadness": 0.003,
        "surprise": 0.001
     }
  }
}
]
</code>```

I able to deserialize my code with this:

```<code>public static async Task<List<RootObject>> MakeAnalysisRequest(string imageFilePath)
    {

        HttpClient client = new HttpClient();

        // Request headers.
        client.DefaultRequestHeaders.Add(
            "Ocp-Apim-Subscription-Key", subscriptionKey);

        // Request parameters. A third optional parameter is "details".
        string requestParameters = "&returnFaceId=false&returnFaceLandmarks=false&returnFaceAttributes=age,emotion";

        // Assemble the URI for the REST API Call.
        string uri = uriBase + "?" + requestParameters;

        HttpResponseMessage response;

        // Request body. Posts a locally stored JPEG image.
        byte[] byteData = GetImageAsByteArray(imageFilePath);

        using (ByteArrayContent content = new ByteArrayContent(byteData))
        {
            // This example uses content type "application/octet-stream".
            // The other content types you can use are "application/json"
            // and "multipart/form-data".
            content.Headers.ContentType =
                new MediaTypeHeaderValue("application/octet-stream");

            // Execute the REST API call.
            response = await client.PostAsync(uri, content);

            // Get the JSON response.
            string contentString = await response.Content.ReadAsStringAsync();
            // Display the JSON response.
            Console.WriteLine("\nResponse:\n");
            string format = JsonPrettyPrint(contentString);
            var deserializedJson = JsonConvert.DeserializeObject<List<RootObject>>(format);
            Console.WriteLine(format);
            Console.WriteLine(deserializedJson);
            Console.WriteLine("\nPress Enter to exit...");
            return deserializedJson;
        }
    }
</code>```

But when i try to print each parameter value, it shows error:

```<code>var output1 = MakeAnalysisRequest(imageFilePath).Result;
                var x= output1[0].FaceAttributes.Emotion.Anger;
                Console.WriteLine(x);
                var y = output1[1].FaceAttributes.Emotion.Neutral;
                Console.WriteLine(y);
                if (x >= 0.5)
                {
                    System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"D:\Degree course outline\FYP2019\soft.wav");
                    player.Play();
                }
                if (y>= 0.5)
                {
                    System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"D:\Degree course outline\FYP2019\soft.wav");
                    player.Play();
                }
</code>```

My error code is like this:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

How could i solve it?
Thanks

My class object:

```<code>class Program
{

    public class FaceRectangle
    {
        public int Top { get; set; }
        public int Left { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
    }

    public class Emotion
    {
        public double Anger { get; set; }
        public double Contempt { get; set; }
        public double Disgust { get; set; }
        public double Fear { get; set; }
        public double Happiness { get; set; }
        public double Neutral { get; set; }
        public double Sadness { get; set; }
        public double Surprise { get; set; }
    }

    public class FaceAttributes
    {
        public double Age { get; set; }
        public Emotion Emotion { get; set; }
    }

    public class RootObject
    {
        public FaceRectangle FaceRectangle { get; set; }
        public FaceAttributes FaceAttributes { get; set; }
    }
</code>```

答:
Try this code:

```<code>var output1 = await MakeAnalysisRequest(imageFilePath);
if (output1 != null && output1.Count > 0)
{
    var x= output1[0].FaceAttributes.Emotion.Anger;
     Console.WriteLine(x);
}
if (output1 != null && output1.Count > 1)
{
    var y = output1[1].FaceAttributes.Emotion.Neutral;
}
</code>```

The out of range exception is there because your deserialized output does not have enough elements to access. Please share your class object for more help.

Also try to avoid using the .Result to get the return value from asynch as it could lead to deadlocks.

Edit after providing class

With your class being like this then change your code accordingly:

```<code>var output1 = await MakeAnalysisRequest(imageFilePath);
if (output1 != null && output1.Count > 0)
{
    var x= output1[0].FaceAttributes.Emotion.Anger;
    Console.WriteLine(x);
    var y = output1[0].FaceAttributes.Emotion.Neutral;
    Console.WriteLine(y);
}
</code>```

There is only one RootObject in your jsons array that is comprised of two others.

Json array [] object {}

An array with two objects looks like this [{},{}] and not like this [{{},{}}]

Title: Azure Deserialize JSON Response C#

Body:
I try to deserialize my JSON Response which is at below, but when i print the content of each parameter, it shows error.

My JSON Resposne:

[
{
  "faceRectangle": {
     "top": 214,
     "left": 472,
     "width": 450,
     "height": 450
  },
  "faceAttributes": {
     "age": 19.0,
     "emotion": {
        "anger": 0.0,
        "contempt": 0.0,
        "disgust": 0.0,
        "fear": 0.0,
        "happiness": 0.0,
        "neutral": 0.996,
        "sadness": 0.003,
        "surprise": 0.001
     }
  }
}
]

I able to deserialize my code with this:

public static async Task<List<RootObject>> MakeAnalysisRequest(string imageFilePath)
    {

        HttpClient client = new HttpClient();

        // Request headers.
        client.DefaultRequestHeaders.Add(
            "Ocp-Apim-Subscription-Key", subscriptionKey);

        // Request parameters. A third optional parameter is "details".
        string requestParameters = "&returnFaceId=false&returnFaceLandmarks=false&returnFaceAttributes=age,emotion";

        // Assemble the URI for the REST API Call.
        string uri = uriBase + "?" + requestParameters;

        HttpResponseMessage response;

        // Request body. Posts a locally stored JPEG image.
        byte[] byteData = GetImageAsByteArray(imageFilePath);

        using (ByteArrayContent content = new ByteArrayContent(byteData))
        {
            // This example uses content type "application/octet-stream".
            // The other content types you can use are "application/json"
            // and "multipart/form-data".
            content.Headers.ContentType =
                new MediaTypeHeaderValue("application/octet-stream");

            // Execute the REST API call.
            response = await client.PostAsync(uri, content);

            // Get the JSON response.
            string contentString = await response.Content.ReadAsStringAsync();
            // Display the JSON response.
            Console.WriteLine("\nResponse:\n");
            string format = JsonPrettyPrint(contentString);
            var deserializedJson = JsonConvert.DeserializeObject<List<RootObject>>(format);
            Console.WriteLine(format);
            Console.WriteLine(deserializedJson);
            Console.WriteLine("\nPress Enter to exit...");
            return deserializedJson;
        }
    }

But when i try to print each parameter value, it shows error:

var output1 = MakeAnalysisRequest(imageFilePath).Result;
                var x= output1[0].FaceAttributes.Emotion.Anger;
                Console.WriteLine(x);
                var y = output1[1].FaceAttributes.Emotion.Neutral;
                Console.WriteLine(y);
                if (x >= 0.5)
                {
                    System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"D:\Degree course outline\FYP2019\soft.wav");
                    player.Play();
                }
                if (y>= 0.5)
                {
                    System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"D:\Degree course outline\FYP2019\soft.wav");
                    player.Play();
                }

My error code is like this:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

How could i solve it?
Thanks

My class object:

class Program
{

    public class FaceRectangle
    {
        public int Top { get; set; }
        public int Left { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
    }

    public class Emotion
    {
        public double Anger { get; set; }
        public double Contempt { get; set; }
        public double Disgust { get; set; }
        public double Fear { get; set; }
        public double Happiness { get; set; }
        public double Neutral { get; set; }
        public double Sadness { get; set; }
        public double Surprise { get; set; }
    }

    public class FaceAttributes
    {
        public double Age { get; set; }
        public Emotion Emotion { get; set; }
    }

    public class RootObject
    {
        public FaceRectangle FaceRectangle { get; set; }
        public FaceAttributes FaceAttributes { get; set; }
    }

Body:
Try this code:

var output1 = await MakeAnalysisRequest(imageFilePath);
if (output1 != null && output1.Count > 0)
{
    var x= output1[0].FaceAttributes.Emotion.Anger;
     Console.WriteLine(x);
}
if (output1 != null && output1.Count > 1)
{
    var y = output1[1].FaceAttributes.Emotion.Neutral;
}

The out of range exception is there because your deserialized output does not have enough elements to access. Please share your class object for more help.

Also try to avoid using the .Result to get the return value from asynch as it could lead to deadlocks.

Edit after providing class

With your class being like this then change your code accordingly:

var output1 = await MakeAnalysisRequest(imageFilePath);
if (output1 != null && output1.Count > 0)
{
    var x= output1[0].FaceAttributes.Emotion.Anger;
    Console.WriteLine(x);
    var y = output1[0].FaceAttributes.Emotion.Neutral;
    Console.WriteLine(y);
}

There is only one RootObject in your jsons array that is comprised of two others.

Json array [] object {}

An array with two objects looks like this [{},{}] and not like this [{{},{}}]


问:
Did not find handler method
I am trying to invoke a rest endpoint, but getting this info when i call it, resulting in a 404 error in UI

```<code>2016-08-07 13:43:42.611 DEBUG 27834 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /api/v1/operations
2016-08-07 13:43:42.614 DEBUG 27834 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/api/v1/operations]
2016-08-07 13:43:42.615 DEBUG 27834 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/api/v1/operations] are [/**]
2016-08-07 13:43:42.616 DEBUG 27834 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/api/v1/operations] are {}
2016-08-07 13:43:42.617 DEBUG 27834 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/api/v1/operations] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39ead1b7]]] and 1 interceptor
</code>```

There are 2 controller class in the same package with different endpoint

```<code>@RestController
public class OperationRetrievalController {

    @Autowired
    OperationRetrievalManager operationRetrievalManager;

    private static Logger logger = Logger.getLogger(OperationRetrievalController.class);

    @RequestMapping("/api/v1/operations")
    public ResponseEntity<List<OperationView>> requestUserOperations() {
        String ssoId = "xxxxxx";
        logger.info("Inside request operationRetrivel Manager +++++++++>>>>>>>>");
        return new ResponseEntity<List<OperationView>>(operationRetrievalManager.retrieveOperations(ssoId), HttpStatus.OK);
    }

}
</code>```

I have another class in the same package :

```<code>@RestController
public class ComponentRetrievalController {

    @Autowired
    ComponentRetrievalManager componentRetrievalManager;

    @RequestMapping(value = "api/v1/component/{sso_id}" , method=RequestMethod.GET)
    public ResponseEntity<List<Component>> requestUserComponent(@PathVariable("sso_id") String ssoId) {

        return new ResponseEntity<List<Component>>(componentRetrievalManager.retrieveComponents(ssoId), HttpStatus.OK);
    }

}
</code>```

Here is the Spring boot app class :

```<code>@SpringBootApplication
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages="com.ge.power.bis.repositories")
@ComponentScan(basePackages="com.ge.power.bis.managers")
public class Application {

    private static Logger logger = Logger.getLogger(Application.class);

    public static void main(String[] args) {

        SpringApplication springApplication = new SpringApplication(Application.class);

        ApplicationContext ctx = springApplication.run(args);

        logger.info("Let's inspect the beans provided by Spring Boot:");
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames)
        {
            logger.info(beanName);
        }
    }
}
</code>```

Here is the structure of my package

When I remove all the annotations in Application.java and just keeping the  @SpringBootApplication, It gives the following error:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'componentRetrievalController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.ge.power.bis.managers.ComponentRetrievalManager com.ge.power.bis.controllers.ComponentRetrievalController.componentRetrievalManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ge.power.bis.managers.ComponentRetrievalManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapable
</code>```

答:
You need to mark the service class as "Available to make beans" so the Spring's component-scan will be able to make bean and inject values.

This can be done by @Component annotation. As mentioned in the answer by @sromit, adding @Service annotation will also work, as it already inherits the @Component. @Repository and @Controller also inherit the @Component annotation.

Title: Did not find handler method

Body:
I am trying to invoke a rest endpoint, but getting this info when i call it, resulting in a 404 error in UI

2016-08-07 13:43:42.611 DEBUG 27834 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /api/v1/operations
2016-08-07 13:43:42.614 DEBUG 27834 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/api/v1/operations]
2016-08-07 13:43:42.615 DEBUG 27834 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/api/v1/operations] are [/**]
2016-08-07 13:43:42.616 DEBUG 27834 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/api/v1/operations] are {}
2016-08-07 13:43:42.617 DEBUG 27834 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/api/v1/operations] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39ead1b7]]] and 1 interceptor

There are 2 controller class in the same package with different endpoint

@RestController
public class OperationRetrievalController {

    @Autowired
    OperationRetrievalManager operationRetrievalManager;

    private static Logger logger = Logger.getLogger(OperationRetrievalController.class);

    @RequestMapping("/api/v1/operations")
    public ResponseEntity<List<OperationView>> requestUserOperations() {
        String ssoId = "xxxxxx";
        logger.info("Inside request operationRetrivel Manager +++++++++>>>>>>>>");
        return new ResponseEntity<List<OperationView>>(operationRetrievalManager.retrieveOperations(ssoId), HttpStatus.OK);
    }

}

I have another class in the same package :

@RestController
public class ComponentRetrievalController {

    @Autowired
    ComponentRetrievalManager componentRetrievalManager;

    @RequestMapping(value = "api/v1/component/{sso_id}" , method=RequestMethod.GET)
    public ResponseEntity<List<Component>> requestUserComponent(@PathVariable("sso_id") String ssoId) {

        return new ResponseEntity<List<Component>>(componentRetrievalManager.retrieveComponents(ssoId), HttpStatus.OK);
    }

}

Here is the Spring boot app class :

@SpringBootApplication
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages="com.ge.power.bis.repositories")
@ComponentScan(basePackages="com.ge.power.bis.managers")
public class Application {

    private static Logger logger = Logger.getLogger(Application.class);

    public static void main(String[] args) {

        SpringApplication springApplication = new SpringApplication(Application.class);

        ApplicationContext ctx = springApplication.run(args);

        logger.info("Let's inspect the beans provided by Spring Boot:");
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames)
        {
            logger.info(beanName);
        }
    }
}

Here is the structure of my package

When I remove all the annotations in Application.java and just keeping the  @SpringBootApplication, It gives the following error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'componentRetrievalController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.ge.power.bis.managers.ComponentRetrievalManager com.ge.power.bis.controllers.ComponentRetrievalController.componentRetrievalManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ge.power.bis.managers.ComponentRetrievalManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapable


问:
Unable to get value from JSON by Javascript
I am trying to load a JSON data value, which stored on the Google Sheet, into my HTML page.

By now, I am frustrated how to get the value of "12345678" which is under the "gsx$date" and "$t".

However, I am not able to receive the specific value and only the text of "} //]]>" was received.

Could someone help me please? Thanks!

For HTML part, I typed the following code for showing the specific json data:

```<code><table id="dataTable">
  <tbody>

  </tbody>
</table>
</code>```

For Javascript part:

```<code><script type="text/javascript" language="javascript>
let xhr = new XMLHttpRequest;
xhr.open('GET', 'url', true);
xhr.onload = function()
{
  if (this.status === 200)
  {
    let data = JSON.parse(this.responseText).entry,
            tbodyHtml = '';

    data.map(function(d) {
        tbodyHtml =+ `
        <tr>
            <td>${d.gsx$date.$t}</td>
        </tr>
      `;
    });

    document.querySelector('#dataTable tbody').innerHTML = tbodyHtml;
  }
}
xhr.send();
</script>
</code>```

This is my JSON data from a Google Sheet

```<code>    {
   "version":"1.0",
   "encoding":"UTF-8",
   "feed":{
      "xmlns":"http://www.w3.org/2005/Atom",
      "xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/",
      "xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended"
      },
      "updated":{
         "$t":"2020-02-16T06:28:44.692Z"
      },
      "category":[
         {
            "scheme":"http://schemas.google.com/spreadsheets/2006",
            "term":"http://schemas.google.com/spreadsheets/2006#list"
         }
      ],
      "title":{
         "type":"text",
         "$t":"Today"
      },
      "openSearch$totalResults":{
         "$t":"1"
      },
      "openSearch$startIndex":{
         "$t":"1"
      },
      "entry":[
         {
            "updated":{
               "$t":"2020-02-16T06:28:44.692Z"
            },
            "category":[
               {
                  "scheme":"http://schemas.google.com/spreadsheets/2006",
                  "term":"http://schemas.google.com/spreadsheets/2006#list"
               }
            ],
            "title":{
               "type":"text",
               "$t":"1"
            },
            "content":{
               "type":"text",
               "$t":"time: 2, todayhightemp: 3, todayhightemptime: 4"
            },
            "link":[
               {
                  "rel":"self",
                  "type":"application/atom+xml",
                  "href":"https://spreadsheets.google.com/feeds/list/133WezZS498sLEDZ-2ZM_2lvxwcMYwXTiGZPBC0Do0p8/od6/public/full/cokwr"
               }
            ],
            "gsx$date":{
               "$t":"12345678"
            },
            "gsx$time":{
               "$t":"23456789"
            },
            "gsx$todayhightemp":{
               "$t":"34567890"
            },
            "gsx$todayhightemptime":{
               "$t":"45678901"
            },
            "gsx$todaylowtemp":{
               "$t":""
            },
            "gsx$todaylowtemptime":{
               "$t":""
            },
            "gsx$todayhighrh":{
               "$t":""
            },
            "gsx$todayhighrhtime":{
               "$t":""
            },
            "gsx$todaylowrh":{
               "$t":""
            },
            "gsx$todaylowrhtime":{
               "$t":""
            },
            "gsx$todayhighbar":{
               "$t":""
            },
            "gsx$todayhighbartime":{
               "$t":""
            },
            "gsx$todaylowbar":{
               "$t":""
            },
            "gsx$todaylowbartime":{
               "$t":""
            },
            "gsx$todayhighwindspeed":{
               "$t":""
            },
            "gsx$todayhighwindspeedtime":{
               "$t":""
            },
            "gsx$todayrainrate":{
               "$t":""
            },
            "gsx$todayhighrainrate":{
               "$t":""
            },
            "gsx$todayhighrainratetime":{
               "$t":""
            },
            "gsx$todayet":{
               "$t":""
            },
            "gsx$todayhighsolarradiation":{
               "$t":""
            },
            "gsx$todayhighsolarradationtime":{
               "$t":""
            },
            "gsx$todayhighuv":{
               "$t":""
            },
            "gsx$todayhighuvtime":{
               "$t":""
            },
            "gsx$todayhighdewpoint":{
               "$t":""
            },
            "gsx$todayhighdewpointtime":{
               "$t":""
            },
            "gsx$todaylowdewpoint":{
               "$t":""
            },
            "gsx$todaylowdewpointtime":{
               "$t":""
            },
            "gsx$todayhighheatindex":{
               "$t":""
            },
            "gsx$todayhighheatindextime":{
               "$t":""
            }
         }
      ]
   }
}
</code>```

答:
1) Load everything as JSON.
So to achieve it please follow this tutorial to retrieve all of the sheet as JSON. When I was following the tutorial, my GOOGLESHEETCODE was the code, generated from shared button on the top right corner.

2) Use fetch or axios to make the request.

Here is an example with fetch:

```<code>const url = 'YOUJSONENDPOINTURL';

fetch(url)
    .then(data=> data.json())
    .then(result => {
        let firstCell = result['feed']['entry'][0]['gsx$date']['$t'];

        result['feed']['entry'].forEach((b) => { // loop through all cells
           console.log(b.gsx$date.$t);
        })
    })

</code>```

You can use XMLHttpRequest as it is from your request.
The issue in your example is that the JSON that you've attached is invalid and that is not the same JSON structure that we are retrieving from sheets.

Body:
I am trying to load a JSON data value, which stored on the Google Sheet, into my HTML page.

By now, I am frustrated how to get the value of "12345678" which is under the "gsx$date" and "$t".

However, I am not able to receive the specific value and only the text of "} //]]>" was received.

Could someone help me please? Thanks!

For HTML part, I typed the following code for showing the specific json data:

For Javascript part:

This is my JSON data from a Google Sheet

    {
   "version":"1.0",
   "encoding":"UTF-8",
   "feed":{
      "xmlns":"http://www.w3.org/2005/Atom",
      "xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/",
      "xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended"
      },
      "updated":{
         "$t":"2020-02-16T06:28:44.692Z"
      },
      "category":[
         {
            "scheme":"http://schemas.google.com/spreadsheets/2006",
            "term":"http://schemas.google.com/spreadsheets/2006#list"
         }
      ],
      "title":{
         "type":"text",
         "$t":"Today"
      },
      "openSearch$totalResults":{
         "$t":"1"
      },
      "openSearch$startIndex":{
         "$t":"1"
      },
      "entry":[
         {
            "updated":{
               "$t":"2020-02-16T06:28:44.692Z"
            },
            "category":[
               {
                  "scheme":"http://schemas.google.com/spreadsheets/2006",
                  "term":"http://schemas.google.com/spreadsheets/2006#list"
               }
            ],
            "title":{
               "type":"text",
               "$t":"1"
            },
            "content":{
               "type":"text",
               "$t":"time: 2, todayhightemp: 3, todayhightemptime: 4"
            },
            "link":[
               {
                  "rel":"self",
                  "type":"application/atom+xml",
                  "href":"https://spreadsheets.google.com/feeds/list/133WezZS498sLEDZ-2ZM_2lvxwcMYwXTiGZPBC0Do0p8/od6/public/full/cokwr"
               }
            ],
            "gsx$date":{
               "$t":"12345678"
            },
            "gsx$time":{
               "$t":"23456789"
            },
            "gsx$todayhightemp":{
               "$t":"34567890"
            },
            "gsx$todayhightemptime":{
               "$t":"45678901"
            },
            "gsx$todaylowtemp":{
               "$t":""
            },
            "gsx$todaylowtemptime":{
               "$t":""
            },
            "gsx$todayhighrh":{
               "$t":""
            },
            "gsx$todayhighrhtime":{
               "$t":""
            },
            "gsx$todaylowrh":{
               "$t":""
            },
            "gsx$todaylowrhtime":{
               "$t":""
            },
            "gsx$todayhighbar":{
               "$t":""
            },
            "gsx$todayhighbartime":{
               "$t":""
            },
            "gsx$todaylowbar":{
               "$t":""
            },
            "gsx$todaylowbartime":{
               "$t":""
            },
            "gsx$todayhighwindspeed":{
               "$t":""
            },
            "gsx$todayhighwindspeedtime":{
               "$t":""
            },
            "gsx$todayrainrate":{
               "$t":""
            },
            "gsx$todayhighrainrate":{
               "$t":""
            },
            "gsx$todayhighrainratetime":{
               "$t":""
            },
            "gsx$todayet":{
               "$t":""
            },
            "gsx$todayhighsolarradiation":{
               "$t":""
            },
            "gsx$todayhighsolarradationtime":{
               "$t":""
            },
            "gsx$todayhighuv":{
               "$t":""
            },
            "gsx$todayhighuvtime":{
               "$t":""
            },
            "gsx$todayhighdewpoint":{
               "$t":""
            },
            "gsx$todayhighdewpointtime":{
               "$t":""
            },
            "gsx$todaylowdewpoint":{
               "$t":""
            },
            "gsx$todaylowdewpointtime":{
               "$t":""
            },
            "gsx$todayhighheatindex":{
               "$t":""
            },
            "gsx$todayhighheatindextime":{
               "$t":""
            }
         }
      ]
   }
}

Body:
1) Load everything as JSON.
So to achieve it please follow this tutorial to retrieve all of the sheet as JSON. When I was following the tutorial, my GOOGLESHEETCODE was the code, generated from shared button on the top right corner.

2) Use fetch or axios to make the request.

Here is an example with fetch:

const url = 'YOUJSONENDPOINTURL';

fetch(url)
    .then(data=> data.json())
    .then(result => {
        let firstCell = result['feed']['entry'][0]['gsx$date']['$t'];

        result['feed']['entry'].forEach((b) => { // loop through all cells
           console.log(b.gsx$date.$t);
        })
    })

You can use XMLHttpRequest as it is from your request.
The issue in your example is that the JSON that you've attached is invalid and that is not the same JSON structure that we are retrieving from sheets.


问:
OpenGl writting wrong data to image
im tryn to write an wpf like ui. im using sharpfont, freeimage c# binding and opengl.
my problem is at fonthandling and creating textures for my fonts.
This is what i get...

This is my font code

```<code>    int IGlyphAtlas.Width => SIZE;
    int IGlyphAtlas.Height => SIZE;

    public int ID { get; } = id++;
    public float Size { get; }
    public string Family => fontface.Family;
    public bool IsLoaded => fontface != null;
    public FontWeight Weight => fontface.Weight;
    public FontStyle Style => fontface.Style;
    public FontStretch Stretch => fontface.Stretch;
    public Texture Texture => internaltexture;

    private bool isdisposed;
    private readonly FontFace fontface;
    private readonly TextAnalyzer analyzer;
    private readonly Texture2D internaltexture;
    private readonly List<PixelData> pixeldata = new List<PixelData>();
    public Font(FontFace face, float size)
    {
        TextureAttributes attributes = new TextureAttributes()
        {
            filter = OpenGL.GlFilter.LINEAR,
            format = OpenGL.GLPixelFormat.RED,
            type = OpenGL.GLPixelDataType.UNSIGNED_BYTE,
            wrap = OpenGL.GLTextureWrapMode.CLAMP_TO_BORDER,
            internalformat = OpenGL.GLInternalFormat.R8,
        };

        Size = size;
        fontface = face;
        analyzer = new TextAnalyzer(this);
        internaltexture = new Texture2D(attributes, SIZE, SIZE);
    }
    public TextLayout Layout(string text, TextFormat format, Rect rect, bool direct)
    {
        TextLayout layout = new TextLayout();

        format.Font = fontface;
        format.Size = Size;

        analyzer.Clear();
        analyzer.AppendText(text, format);
        analyzer.PerformLayout((float)rect.x, (float)rect.y, (float)rect.width, (float)rect.height, layout);

        return layout;
    }
    public Texture CopyInternalTexture()
    {
        TextureAttributes attributes = new TextureAttributes()
        {
            filter = OpenGL.GlFilter.LINEAR,
            format = OpenGL.GLPixelFormat.RED,
            type = OpenGL.GLPixelDataType.UNSIGNED_BYTE,
            wrap = OpenGL.GLTextureWrapMode.CLAMP_TO_BORDER,
            internalformat = OpenGL.GLInternalFormat.R8,
        };
        return new Texture2D(attributes, SIZE, SIZE, internaltexture.Read());
    }

    public void Dispose() => Dispose(true);
    private void Dispose(bool dispose)
    {
        if (isdisposed) return;
        if (dispose)
        {
            isdisposed = true;
        }
    }

    void IGlyphAtlas.Insert(char glyph, int page, int x, int y, int width, int height, IntPtr data)
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Font));
        if (page > 0) throw new InvalidOperationException("the texture of the font is to small for more glyphs");

        //byte[] pixels = new byte[width * height];
        //Marshal.Copy(data, pixels, 0, pixels.Length);
        internaltexture.Write(0, x, y, width, height, data);

        //pixeldata.Add(new PixelData(glyph, x, y, width, height, pixels));
    }
</code>```

this is my texture code

```<code>    public int Width { get; }
    public int Height { get; }

    public GLTextureTarget Target { get; }
    public GLPixelDataType Type => textureattributes.type;
    public GLPixelFormat Format => textureattributes.format;
    public GLInternalFormat InternalFormat => textureattributes.internalformat;
    public GLTextureWrapMode Wrap => textureattributes.wrap;
    public GlFilter Filter => textureattributes.filter;

    private bool isdisposed;
    private readonly uint textureindex;
    private readonly TextureAttributes textureattributes;

    public Texture(GLTextureTarget target, TextureAttributes attributes, int width, int height)
    {
        Target = target;
        Width = width;
        Height = height;

        textureattributes = attributes;
        textureindex = GL.GenTexture();

        GL.BindTexture(Target, textureindex);
        Initialize(IntPtr.Zero);
        GL.BindTexture(Target, 0);
    }
    public Texture(GLTextureTarget target, TextureAttributes attributes, int width, int height, IntPtr dataptr)
    {
        Target = target;
        Width = width;
        Height = height;

        textureattributes = attributes;
        textureindex = GL.GenTexture();
        GL.BindTexture(Target, textureindex);
        Initialize(dataptr);
        GL.BindTexture(Target, 0);
    }
    public Texture(GLTextureTarget target, TextureAttributes attributes, int width, int height, byte[] dataarray)
    {
        Target = target;
        Width = width;
        Height = height;

        textureattributes = attributes;
        textureindex = GL.GenTexture();

        GCHandle pinnedArray = GCHandle.Alloc(dataarray, GCHandleType.Pinned);
        IntPtr pointer = pinnedArray.AddrOfPinnedObject();

        GL.BindTexture(Target, textureindex);
        Initialize(pointer);
        GL.BindTexture(Target, 0);

        pinnedArray.Free();
    }

    internal void Bind()
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));
        GL.BindTexture(Target, textureindex);
    }
    internal void Release() => GL.BindTexture(Target, 0);

    public void Write(int level, int xoffset, int yoffset, int width, int height, IntPtr data)
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));

        GL.BindTexture(Target, textureindex);
        WriteOverride(level, xoffset, yoffset, width, height, data);
        GL.BindTexture(Target, 0);
    }
    public void Write(int level, int xoffset, int yoffset, int width, int height, byte[] data)
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));

        GL.BindTexture(Target, textureindex);
        WriteOverride(level, xoffset, yoffset, width, height, data);
        GL.BindTexture(Target, 0);
    }
    public byte[] Read()
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));

        int size = Width * Height * GetBPP();
        GL.BindTexture(Target, textureindex);

        byte[] dataarray = new byte[size];
        GL.GetTextureImage(textureindex, 0, Format, Type, size, dataarray);

        GL.BindTexture(Target, 0);
        return dataarray;
    }
    public byte[] Read(int level, int xoffset, int yoffset, int width, int height)
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));

        int size = width * height * GetBPP();
        byte[] dataarray = new byte[size];

        GL.BindTexture(Target, textureindex);
        GL.GetTextureSubImage(textureindex, 0, xoffset, yoffset, 0, width, height, 0, Format, Type, size, dataarray);
        GL.BindTexture(Target, 0);
        return dataarray;
    }
    public void Dispose() => Dispose(true);

    protected abstract void Initialize(IntPtr dataptr);
    protected abstract void WriteOverride(int level, int x, int y, int width, int height, byte[] data);
    protected abstract void WriteOverride(int level, int x, int y, int width, int height, IntPtr data);

    private void Dispose(bool dispose)
    {
        if (isdisposed) return;
        if (dispose)
        {
            isdisposed = true;
            GL.DeleteTextures(1, new[] { textureindex });
        }
    }
    private int GetBPP()
    {
        switch (Format)
        {
            case GLPixelFormat.STENCIL_INDEX:
            case GLPixelFormat.DEPTH_COMPONENT:
            case GLPixelFormat.RED:
            case GLPixelFormat.GREEN:
            case GLPixelFormat.BLUE: return 1;
            case GLPixelFormat.RG: return 2;
            case GLPixelFormat.BGR:
            case GLPixelFormat.RGB: return 3;
            case GLPixelFormat.BGRA:
            case GLPixelFormat.RGBA: return 4;
            case GLPixelFormat.RED_INTEGER:
            case GLPixelFormat.GREEN_INTEGER:
            case GLPixelFormat.BLUE_INTEGER: return 4;
            case GLPixelFormat.RG_INTEGER: return 8;
            case GLPixelFormat.BGR_INTEGER:
            case GLPixelFormat.RGB_INTEGER: return 12;
            case GLPixelFormat.BGRA_INTEGER:
            case GLPixelFormat.RGBA_INTEGER: return 16;
            case GLPixelFormat.NONE:
            default: return 0;
        }
    }
</code>```

and texture2D

```<code>    public Texture2D(TextureAttributes attributes, int width, int height) :
        base(GLTextureTarget.TEXTURE_2D, attributes, width, height)
    {
    }
    public Texture2D(TextureAttributes attributes, int width, int height, IntPtr dataptr) :
        base(GLTextureTarget.TEXTURE_2D, attributes, width, height, dataptr)
    {
    }
    public Texture2D(TextureAttributes attributes, int width, int height, byte[] dataarray) :
        base(GLTextureTarget.TEXTURE_2D, attributes, width, height, dataarray)
    {
    }

    protected override void Initialize(IntPtr dataptr)
    {
        GL.TexParameteri(Target, GLTextureParameter.TEXTURE_MIN_FILTER, Filter);
        GL.TexParameteri(Target, GLTextureParameter.TEXTURE_MAG_FILTER, Filter);
        GL.TexParameteri(Target, GLTextureParameter.TEXTURE_WRAP_S, Wrap);
        GL.TexParameteri(Target, GLTextureParameter.TEXTURE_WRAP_T, Wrap);
        GL.GenerateMipmap(Target);

        GL.TexImage2D(GLTexture2DProxyTarget.TEXTURE_2D, 0, InternalFormat, Width, Height, 0, Format, Type, dataptr);
    }

    protected override void WriteOverride(int level, int x, int y, int width, int height, byte[] data)
        => GL.TexSubImage2D(GLTexture2DTarget.TEXTURE_2D, level, x, y, width, height, Format, Type, data);

    protected override void WriteOverride(int level, int x, int y, int width, int height, IntPtr data)
        => GL.TexSubImage2D(GLTexture2DTarget.TEXTURE_2D, level, x, y, width, height, Format, Type, data);
</code>```

im using a single channel (red) for the texture data. sharpfont is working correctly (validated). do i miss somthing by writing to the texture?

答:
By default OpenGL assumes that the start of each row of an image is aligned 4 bytes. This is because the GL_UNPACK_ALIGNMENT parameter by default is 4.

Since the image has 1 (RED) color channel and is tightly packed, loading of a glyph with a width that is divisible by 4 works, but it fails if the width is not divisible by 4.

Change the the GL_UNPACK_ALIGNMENT parameter to 1, before specifying the two-dimensional texture image (glTexImage2D):

Gl.PixelStorei(GL.UNPACK_ALIGNMENT, 1);
GL.TexImage2D(GLTexture2DProxyTarget.TEXTURE_2D, 0, InternalFormat, Width, Height, 0, Format, Type, dataptr);
Gl.PixelStorei(GL.UNPACK_ALIGNMENT, 4);
```

Title: OpenGl writting wrong data to image

Body:
im tryn to write an wpf like ui. im using sharpfont, freeimage c# binding and opengl.
my problem is at fonthandling and creating textures for my fonts.
This is what i get...

This is my font code

    int IGlyphAtlas.Width => SIZE;
    int IGlyphAtlas.Height => SIZE;

    public int ID { get; } = id++;
    public float Size { get; }
    public string Family => fontface.Family;
    public bool IsLoaded => fontface != null;
    public FontWeight Weight => fontface.Weight;
    public FontStyle Style => fontface.Style;
    public FontStretch Stretch => fontface.Stretch;
    public Texture Texture => internaltexture;

    private bool isdisposed;
    private readonly FontFace fontface;
    private readonly TextAnalyzer analyzer;
    private readonly Texture2D internaltexture;
    private readonly List<PixelData> pixeldata = new List<PixelData>();
    public Font(FontFace face, float size)
    {
        TextureAttributes attributes = new TextureAttributes()
        {
            filter = OpenGL.GlFilter.LINEAR,
            format = OpenGL.GLPixelFormat.RED,
            type = OpenGL.GLPixelDataType.UNSIGNED_BYTE,
            wrap = OpenGL.GLTextureWrapMode.CLAMP_TO_BORDER,
            internalformat = OpenGL.GLInternalFormat.R8,
        };

        Size = size;
        fontface = face;
        analyzer = new TextAnalyzer(this);
        internaltexture = new Texture2D(attributes, SIZE, SIZE);
    }
    public TextLayout Layout(string text, TextFormat format, Rect rect, bool direct)
    {
        TextLayout layout = new TextLayout();

        format.Font = fontface;
        format.Size = Size;

        analyzer.Clear();
        analyzer.AppendText(text, format);
        analyzer.PerformLayout((float)rect.x, (float)rect.y, (float)rect.width, (float)rect.height, layout);

        return layout;
    }
    public Texture CopyInternalTexture()
    {
        TextureAttributes attributes = new TextureAttributes()
        {
            filter = OpenGL.GlFilter.LINEAR,
            format = OpenGL.GLPixelFormat.RED,
            type = OpenGL.GLPixelDataType.UNSIGNED_BYTE,
            wrap = OpenGL.GLTextureWrapMode.CLAMP_TO_BORDER,
            internalformat = OpenGL.GLInternalFormat.R8,
        };
        return new Texture2D(attributes, SIZE, SIZE, internaltexture.Read());
    }

    public void Dispose() => Dispose(true);
    private void Dispose(bool dispose)
    {
        if (isdisposed) return;
        if (dispose)
        {
            isdisposed = true;
        }
    }

    void IGlyphAtlas.Insert(char glyph, int page, int x, int y, int width, int height, IntPtr data)
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Font));
        if (page > 0) throw new InvalidOperationException("the texture of the font is to small for more glyphs");

        //byte[] pixels = new byte[width * height];
        //Marshal.Copy(data, pixels, 0, pixels.Length);
        internaltexture.Write(0, x, y, width, height, data);

        //pixeldata.Add(new PixelData(glyph, x, y, width, height, pixels));
    }

this is my texture code

    public int Width { get; }
    public int Height { get; }

    public GLTextureTarget Target { get; }
    public GLPixelDataType Type => textureattributes.type;
    public GLPixelFormat Format => textureattributes.format;
    public GLInternalFormat InternalFormat => textureattributes.internalformat;
    public GLTextureWrapMode Wrap => textureattributes.wrap;
    public GlFilter Filter => textureattributes.filter;

    private bool isdisposed;
    private readonly uint textureindex;
    private readonly TextureAttributes textureattributes;

    public Texture(GLTextureTarget target, TextureAttributes attributes, int width, int height)
    {
        Target = target;
        Width = width;
        Height = height;

        textureattributes = attributes;
        textureindex = GL.GenTexture();

        GL.BindTexture(Target, textureindex);
        Initialize(IntPtr.Zero);
        GL.BindTexture(Target, 0);
    }
    public Texture(GLTextureTarget target, TextureAttributes attributes, int width, int height, IntPtr dataptr)
    {
        Target = target;
        Width = width;
        Height = height;

        textureattributes = attributes;
        textureindex = GL.GenTexture();
        GL.BindTexture(Target, textureindex);
        Initialize(dataptr);
        GL.BindTexture(Target, 0);
    }
    public Texture(GLTextureTarget target, TextureAttributes attributes, int width, int height, byte[] dataarray)
    {
        Target = target;
        Width = width;
        Height = height;

        textureattributes = attributes;
        textureindex = GL.GenTexture();

        GCHandle pinnedArray = GCHandle.Alloc(dataarray, GCHandleType.Pinned);
        IntPtr pointer = pinnedArray.AddrOfPinnedObject();

        GL.BindTexture(Target, textureindex);
        Initialize(pointer);
        GL.BindTexture(Target, 0);

        pinnedArray.Free();
    }

    internal void Bind()
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));
        GL.BindTexture(Target, textureindex);
    }
    internal void Release() => GL.BindTexture(Target, 0);

    public void Write(int level, int xoffset, int yoffset, int width, int height, IntPtr data)
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));

        GL.BindTexture(Target, textureindex);
        WriteOverride(level, xoffset, yoffset, width, height, data);
        GL.BindTexture(Target, 0);
    }
    public void Write(int level, int xoffset, int yoffset, int width, int height, byte[] data)
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));

        GL.BindTexture(Target, textureindex);
        WriteOverride(level, xoffset, yoffset, width, height, data);
        GL.BindTexture(Target, 0);
    }
    public byte[] Read()
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));

        int size = Width * Height * GetBPP();
        GL.BindTexture(Target, textureindex);

        byte[] dataarray = new byte[size];
        GL.GetTextureImage(textureindex, 0, Format, Type, size, dataarray);

        GL.BindTexture(Target, 0);
        return dataarray;
    }
    public byte[] Read(int level, int xoffset, int yoffset, int width, int height)
    {
        if (isdisposed) throw new ObjectDisposedException(nameof(Texture));

        int size = width * height * GetBPP();
        byte[] dataarray = new byte[size];

        GL.BindTexture(Target, textureindex);
        GL.GetTextureSubImage(textureindex, 0, xoffset, yoffset, 0, width, height, 0, Format, Type, size, dataarray);
        GL.BindTexture(Target, 0);
        return dataarray;
    }
    public void Dispose() => Dispose(true);

    protected abstract void Initialize(IntPtr dataptr);
    protected abstract void WriteOverride(int level, int x, int y, int width, int height, byte[] data);
    protected abstract void WriteOverride(int level, int x, int y, int width, int height, IntPtr data);

    private void Dispose(bool dispose)
    {
        if (isdisposed) return;
        if (dispose)
        {
            isdisposed = true;
            GL.DeleteTextures(1, new[] { textureindex });
        }
    }
    private int GetBPP()
    {
        switch (Format)
        {
            case GLPixelFormat.STENCIL_INDEX:
            case GLPixelFormat.DEPTH_COMPONENT:
            case GLPixelFormat.RED:
            case GLPixelFormat.GREEN:
            case GLPixelFormat.BLUE: return 1;
            case GLPixelFormat.RG: return 2;
            case GLPixelFormat.BGR:
            case GLPixelFormat.RGB: return 3;
            case GLPixelFormat.BGRA:
            case GLPixelFormat.RGBA: return 4;
            case GLPixelFormat.RED_INTEGER:
            case GLPixelFormat.GREEN_INTEGER:
            case GLPixelFormat.BLUE_INTEGER: return 4;
            case GLPixelFormat.RG_INTEGER: return 8;
            case GLPixelFormat.BGR_INTEGER:
            case GLPixelFormat.RGB_INTEGER: return 12;
            case GLPixelFormat.BGRA_INTEGER:
            case GLPixelFormat.RGBA_INTEGER: return 16;
            case GLPixelFormat.NONE:
            default: return 0;
        }
    }

and texture2D

    public Texture2D(TextureAttributes attributes, int width, int height) :
        base(GLTextureTarget.TEXTURE_2D, attributes, width, height)
    {
    }
    public Texture2D(TextureAttributes attributes, int width, int height, IntPtr dataptr) :
        base(GLTextureTarget.TEXTURE_2D, attributes, width, height, dataptr)
    {
    }
    public Texture2D(TextureAttributes attributes, int width, int height, byte[] dataarray) :
        base(GLTextureTarget.TEXTURE_2D, attributes, width, height, dataarray)
    {
    }

    protected override void Initialize(IntPtr dataptr)
    {
        GL.TexParameteri(Target, GLTextureParameter.TEXTURE_MIN_FILTER, Filter);
        GL.TexParameteri(Target, GLTextureParameter.TEXTURE_MAG_FILTER, Filter);
        GL.TexParameteri(Target, GLTextureParameter.TEXTURE_WRAP_S, Wrap);
        GL.TexParameteri(Target, GLTextureParameter.TEXTURE_WRAP_T, Wrap);
        GL.GenerateMipmap(Target);

        GL.TexImage2D(GLTexture2DProxyTarget.TEXTURE_2D, 0, InternalFormat, Width, Height, 0, Format, Type, dataptr);
    }

    protected override void WriteOverride(int level, int x, int y, int width, int height, byte[] data)
        => GL.TexSubImage2D(GLTexture2DTarget.TEXTURE_2D, level, x, y, width, height, Format, Type, data);

    protected override void WriteOverride(int level, int x, int y, int width, int height, IntPtr data)
        => GL.TexSubImage2D(GLTexture2DTarget.TEXTURE_2D, level, x, y, width, height, Format, Type, data);

im using a single channel (red) for the texture data. sharpfont is working correctly (validated). do i miss somthing by writing to the texture?