问:
How to move text to New line of same row when text is bigger
I am working on HTML table and i am stuck here for very long now, I have a requirement of displaying table into four columns/grid which i have done

Now when i am rendering the table i am displaying first 17 rows in one go than next 17 after five seconds

What is the issue

some ItemNames are big like BIG BANAYAN CARBINET SAUVIGNON BY GLASS

So when page is refreshing after five seconds the the column which contains this long name gets very large width which is not good to see as on UI

I am trying to make the width of each column uniform all four will have same width

So when the long ITEM NAME is coming what I am trying to do is to use word-wrap: normal; to break it after some width,but it is not working

I am dividing the four columns into equal part, which ever screen it is rendering the table it should be divided into 4 parts and when ITEMNAME is large i want to display it into same row but in new line after that exceeds the width of column

I think i have to give some sort of height to all the rows when it can accept one single small item name then it will show in single row but when the name is large it should show in same row but in two lines with same font

$(document).ready(function() {

  var tableValue = [{
    "Item Name": "MANCHOW  V SOUP",
    "SellingPrice": 100
  }, {
    "Item Name": "MANCHOW NV SOUP ",
    "SellingPrice": 125
  }, {
    "Item Name": "CEASER SALAD V",
    "SellingPrice": 175
  }, {
    "Item Name": "CEASER SALAD NV",
    "SellingPrice": 230
  }, {
    "Item Name": "GAMBUS REBOZADAS",
    "SellingPrice": 350
  }, {
    "Item Name": "PANCO FISH FINGER",
    "SellingPrice": 270
  }, {
    "Item Name": "MUSHROOM DUPLEX",
    "SellingPrice": 160
  }, {
    "Item Name": "FRENCH FRIES",
    "SellingPrice": 99
  }, {
    "Item Name": "HONEY GARLIC PRAWN",
    "SellingPrice": 350
  }, {
    "Item Name": "CHICKEN MANCHURIAN",
    "SellingPrice": 180
  }, {
    "Item Name": "MUSHROOM CHILLY",
    "SellingPrice": 120
  }, {
    "Item Name": "SALT N PEPPER BABY CORN",
    "SellingPrice": 120
  }, {
    "Item Name": "SOUTHERN STYLE CHICKEN",
    "SellingPrice": 210
  }, {
    "Item Name": "PANEER NAGGETS",
    "SellingPrice": 210
  }, {
    "Item Name": "HARA BHARA KEBAB",
    "SellingPrice": 160
  }, {
    "Item Name": "CHICKEN TIKKA",
    "SellingPrice": 210
  }, {
    "Item Name": "KALMI KEBAB",
    "SellingPrice": 250
  }, {
    "Item Name": "PIZZA MARGARITTA",
    "SellingPrice": 200
  }, {
    "Item Name": "PIZZA VEG FARMHOUSE",
    "SellingPrice": 200
  }, {
    "Item Name": "BBQ CHICKEN PIZZA",
    "SellingPrice": 225
  }, {
    "Item Name": "CHICKEN TIKKA PIZZA",
    "SellingPrice": 225
  }, {
    "Item Name": "PESTO SAUCE",
    "SellingPrice": 175
  }, {
    "Item Name": "ARABIATA",
    "SellingPrice": 160
  }, {
    "Item Name": "PINK SAUCE",
    "SellingPrice": 160
  }, {
    "Item Name": "GARBANZO BEAN SALAD",
    "SellingPrice": 90
  }, {
    "Item Name": "MASALA PAPAD",
    "SellingPrice": 50
  }, {
    "Item Name": "PEANUT MASALA",
    "SellingPrice": 60
  }, {
    "Item Name": "GAJAR KA HALWA",
    "SellingPrice": 90
  }, {
    "Item Name": "WATERMELON MARTINI",
    "SellingPrice": 281
  }, {
    "Item Name": "Kiwi martini",
    "SellingPrice": 281
  }, {
    "Item Name": " Apple gin",
    "SellingPrice": 225
  }, {
    "Item Name": "Cucumber  cooler ",
    "SellingPrice": 281
  }, {
    "Item Name": "Martini",
    "SellingPrice": 225
  }, {
    "Item Name": "Pink lady",
    "SellingPrice": 225
  }, {
    "Item Name": " Bloody marry",
    "SellingPrice": 281
  }, {
    "Item Name": "Cosmopolitan",
    "SellingPrice": 281
  }, {
    "Item Name": "Sex on the beach",
    "SellingPrice": 281
  }, {
    "Item Name": "Bull frog",
    "SellingPrice": 506
  }, {
    "Item Name": "Long  island iced tea ",
    "SellingPrice": 393
  }, {
    "Item Name": "Pinacolada",
    "SellingPrice": 225
  }, {
    "Item Name": "Daiquiri",
    "SellingPrice": 225
  }, {
    "Item Name": "Mojito ",
    "SellingPrice": 281
  }, {
    "Item Name": "Whisky sour",
    "SellingPrice": 281
  }, {
    "Item Name": "Hot toddy",
    "SellingPrice": 225
  }, {
    "Item Name": "Margarita",
    "SellingPrice": 337
  }, {
    "Item Name": "Tequila sunrise",
    "SellingPrice": 337
  }, {
    "Item Name": "Red sangria",
    "SellingPrice": 225
  }, {
    "Item Name": "White sangria",
    "SellingPrice": 247
  }, {
    "Item Name": "Rose sangria",
    "SellingPrice": 247
  }, {
    "Item Name": "By chance special ",
    "SellingPrice": 168
  }, {
    "Item Name": "Made in heaven",
    "SellingPrice": 168
  }, {
    "Item Name": "Strawberry delight",
    "SellingPrice": 168
  }, {
    "Item Name": "DRAGON",
    "SellingPrice": 168
  }, {
    "Item Name": "Mangochil ",
    "SellingPrice": 168
  }, {
    "Item Name": "Cucumber cola",
    "SellingPrice": 168
  }, {
    "Item Name": "Virgin mojito",
    "SellingPrice": 168
  }, {
    "Item Name": "Virgin mary",
    "SellingPrice": 168
  }, {
    "Item Name": "Virgin pinacolada",
    "SellingPrice": 168
  }, {
    "Item Name": "CORONA",
    "SellingPrice": 438
  }, {
    "Item Name": "CRAFT BEERS",
    "SellingPrice": 337
  }, {
    "Item Name": "BIRA WHITE 330",
    "SellingPrice": 157
  }, {
    "Item Name": "BIRA BLONDE 330",
    "SellingPrice": 135
  }, {
    "Item Name": "BIRA STRONG 650",
    "SellingPrice": 213
  }, {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123
  }, {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202
  }, {
    "Item Name": "KINGFISHER STRONG 330",
    "SellingPrice": 135
  }, {
    "Item Name": "KINGFISHER STRONG 650",
    "SellingPrice": 213
  }, {
    "Item Name": "KINGFISHER ULTRA 330",
    "SellingPrice": 146
  }, {
    "Item Name": "KINGFISHER ULTRA 650",
    "SellingPrice": 281
  }, {
    "Item Name": "KINGFISHER ULTRA MAX 330",
    "SellingPrice": 146
  }, {
    "Item Name": "KINGFISHER ULTRA MAX 650",
    "SellingPrice": 281
  }, {
    "Item Name": "BUDWIESER 330",
    "SellingPrice": 146
  }, {
    "Item Name": "BUDWIESER 650",
    "SellingPrice": 270
  }, {
    "Item Name": "BUDWIESER MAGNUM 330",
    "SellingPrice": 168
  }, {
    "Item Name": "BUDWIESER MAGNUM 650",
    "SellingPrice": 281
  }, {
    "Item Name": "TUBORG 330",
    "SellingPrice": 123
  }, {
    "Item Name": "TUBORG 650",
    "SellingPrice": 191
  }, {
    "Item Name": "TUBORG STRONG 330",
    "SellingPrice": 123
  }, {
    "Item Name": "TUBORG STRONG 650",
    "SellingPrice": 213
  }, {
    "Item Name": "CRANBERRY ",
    "SellingPrice": 157
  }, {
    "Item Name": "ORANGE",
    "SellingPrice": 157
  }, {
    "Item Name": "JAMICAN",
    "SellingPrice": 157
  }, {
    "Item Name": "BLACK BERRY",
    "SellingPrice": 157
  }, {
    "Item Name": "BLUE BERRY",
    "SellingPrice": 157
  }, {
    "Item Name": "MOET CHANDON",
    "SellingPrice": 7875
  }, {
    "Item Name": "SULA BRUT",
    "SellingPrice": 1687
  }, {
    "Item Name": "MATEUS ROSE",
    "SellingPrice": 2137
  }, {
    "Item Name": "HARDYS SIRAZ CABERNET 750",
    "SellingPrice": 1890
  }, {
    "Item Name": "HARDYS SIRAZ CABERNET BY GLASS",
    "SellingPrice": 382
  }, {
    "Item Name": "JACOB CREEK SIRAZ 750",
    "SellingPrice": 1800
  }, {
    "Item Name": "JACOB CREEK SIRAZ BY GLASS",
    "SellingPrice": 360
  }, {
    "Item Name": "BIG BANAYAN CHENNIN BLANC 750",
    "SellingPrice": 990
  }, {
    "Item Name": "BIG BANAYAN CHENNIN BLANC BY GLASS",
    "SellingPrice": 202
  }, {
    "Item Name": "SULA CHENIN BLANC 750 ",
    "SellingPrice": 1293
  }, {
    "Item Name": "SULA CHENIN BLANC BY GLASS",
    "SellingPrice": 258
  }, {
    "Item Name": "FOUR SEAZON CLASSIC CHENNIN BLANC 7",
    "SellingPrice": 1125
  }, {
    "Item Name": "FOUR SEAZON CLASSIC CHENNIN BLANC B",
    "SellingPrice": 225
  }, {
    "Item Name": "BIG BANAYAN CARBINET SAUVIGNON 750",
    "SellingPrice": 1125
  }, {
    "Item Name": "BIG BANAYAN CARBINET SAUVIGNON BY G",
    "SellingPrice": 225
  }, {
    "Item Name": "SULA SATORI MERLOT 750",
    "SellingPrice": 1237
  }, {
    "Item Name": "SULA SATORI MERLOT BY GLASS",
    "SellingPrice": 247
  }, {
    "Item Name": "GROVERS LA RESERVE 750",
    "SellingPrice": 1800
  }, {
    "Item Name": "GROVERS LA RESERVE 100",
    "SellingPrice": 360
  }, {
    "Item Name": "GLENFIDDICH 12 YEARS 700 ",
    "SellingPrice": 9225
  }, {
    "Item Name": "GLENFIDDICH 12 YEARS 30",
    "SellingPrice": 405
  }, {
    "Item Name": "TALISKER 750",
    "SellingPrice": 8775
  }, {
    "Item Name": "TALISKER 30",
    "SellingPrice": 360
  }, {
    "Item Name": "GLENNLIVET 750",
    "SellingPrice": 8887
  }, {
    "Item Name": "GLENNLIVET 30",
    "SellingPrice": 360
  }, {
    "Item Name": "THE SINGLETON 750",
    "SellingPrice": 7942
  }, {
    "Item Name": "THE SINGLETON 30",
    "SellingPrice": 326
  }, {
    "Item Name": "AMRUT FUSION 750",
    "SellingPrice": 5062
  }, {
    "Item Name": "AMRUT FUSION 30",
    "SellingPrice": 202
  }, {
    "Item Name": "JACK DANIELS 750",
    "SellingPrice": 7312
  }, {
    "Item Name": "JACK DANIELS 30",
    "SellingPrice": 292
  }, {
    "Item Name": "JIM BEAM WHITE 750",
    "SellingPrice": 4095
  }, {
    "Item Name": "JIM BEAM WHITE 30",
    "SellingPrice": 168
  }, {
    "Item Name": "JAMESON 750",
    "SellingPrice": 4950
  }, {
    "Item Name": "JAMESON 30",
    "SellingPrice": 202
  }, {
    "Item Name": "JW BLACK LABEL 750",
    "SellingPrice": 8212
  }, {
    "Item Name": "JW BLACK LABEL 200",
    "SellingPrice": 2925
  }, {
    "Item Name": "JW BLACK LABEL 30",
    "SellingPrice": 337
  }, {
    "Item Name": "JW RED LABEL 200",
    "SellingPrice": 1158
  }, {
    "Item Name": "BALLENTINSE FINEST BLENDED 750",
    "SellingPrice": 4545
  }, {
    "Item Name": "BALLENTINSE FINEST BLENDED 30",
    "SellingPrice": 180
  }, {
    "Item Name": "BLACK \u0026 WHITE 375",
    "SellingPrice": 1575
  }, {
    "Item Name": "BLACK \u0026 WHITE 180",
    "SellingPrice": 787
  }, {
    "Item Name": "BLACK \u0026 WHITE 60",
    "SellingPrice": 258
  }, {
    "Item Name": "BLACK \u0026 WHITE 30",
    "SellingPrice": 135
  }, {
    "Item Name": "100 PIPERS 180",
    "SellingPrice": 787
  }, {
    "Item Name": "100 PIPERS 60",
    "SellingPrice": 258
  }, {
    "Item Name": "100 PIPERS 30",
    "SellingPrice": 135
  }, {
    "Item Name": "VAT 69 180",
    "SellingPrice": 675
  }, {
    "Item Name": "VAT 69 60",
    "SellingPrice": 225
  }, {
    "Item Name": "VAT 69 30",
    "SellingPrice": 112
  }, {
    "Item Name": "TEACHERS HIGHLAND 180",
    "SellingPrice": 787
  }, {
    "Item Name": "TEACHERS HIGHLAND 60",
    "SellingPrice": 258
  }, {
    "Item Name": "TEACHERS HIGHLAND 30",
    "SellingPrice": 135
  }, {
    "Item Name": "TEACHERS 50 60",
    "SellingPrice": 393
  }, {
    "Item Name": "TEACHERS 50 30",
    "SellingPrice": 202
  }, {
    "Item Name": "BLACK DOG TRIPPLE GOLD 180",
    "SellingPrice": 1215
  }, {
    "Item Name": "BLACK DOG TRIPPLE GOLD 30",
    "SellingPrice": 213
  }, {
    "Item Name": "BLACK DOG 8 YEARS 180",
    "SellingPrice": 731
  }, {
    "Item Name": "BLACK DOG 8 YEARS 60",
    "SellingPrice": 247
  }, {
    "Item Name": "BLACK DOG 8 YEARS 30",
    "SellingPrice": 123
  }, {
    "Item Name": "BLENDERS PRIDE 750",
    "SellingPrice": 2283
  }, {
    "Item Name": "BLENDERS PRIDE 375",
    "SellingPrice": 1147
  }, {
    "Item Name": "BLENDERS PRIDE 180",
    "SellingPrice": 573
  }, {
    "Item Name": "BLENDERS PRIDE 60",
    "SellingPrice": 191
  }, {
    "Item Name": "BLENDERS PRIDE 30",
    "SellingPrice": 90
  }, {
    "Item Name": "SIGNATURE 180",
    "SellingPrice": 450
  }, {
    "Item Name": "SIGNATURE 60",
    "SellingPrice": 168
  }, {
    "Item Name": "SIGNATURE 30",
    "SellingPrice": 90
  }, {
    "Item Name": "GREY GOOSE 750",
    "SellingPrice": 8190
  }, {
    "Item Name": "GREY GOOSE 30",
    "SellingPrice": 326
  }, {
    "Item Name": "BELVEDERE 700",
    "SellingPrice": 8122
  }, {
    "Item Name": "BELVEDERE 30",
    "SellingPrice": 360
  }, {
    "Item Name": "CIROC 750",
    "SellingPrice": 7425
  }, {
    "Item Name": "CIROC 30",
    "SellingPrice": 303
  }, {
    "Item Name": "ABSOLUT 750",
    "SellingPrice": 4556
  }, {
    "Item Name": "ABSOLUT 30",
    "SellingPrice": 191
  }, {
    "Item Name": "SMIRNOFF RED 180",
    "SellingPrice": 551
  }, {
    "Item Name": "SMIRNOFF RED 60",
    "SellingPrice": 202
  }, {
    "Item Name": "SMIRNOFF RED30",
    "SellingPrice": 101
  }, {
    "Item Name": "SMIRNOFF ORANGE 180",
    "SellingPrice": 551
  }, {
    "Item Name": "SMIRNOFF ORANGE 60",
    "SellingPrice": 202
  }, {
    "Item Name": "SMINOFF ORANGE30",
    "SellingPrice": 101
  }, {
    "Item Name": "SMIRNOFF GREEN APPLE 180",
    "SellingPrice": 551
  }, {
    "Item Name": "SMIRNOFF GREEN APPLE 60",
    "SellingPrice": 202
  }, {
    "Item Name": "SMIRNOFF GREEN APPLE30",
    "SellingPrice": 101
  }, {
    "Item Name": "BOMBAY SAPHIRE 750",
    "SellingPrice": 4725
  }, {
    "Item Name": "BOMBAY SAPHIRE 30",
    "SellingPrice": 191
  }, {
    "Item Name": "BLUE RIBBAND 750",
    "SellingPrice": 877
  }, {
    "Item Name": "BLUE RIBBAND 60",
    "SellingPrice": 78
  }, {
    "Item Name": "BACCARDI WHITE 750",
    "SellingPrice": 2418
  }, {
    "Item Name": "BACCARDI WHITE 180",
    "SellingPrice": 585
  }, {
    "Item Name": "BACCARDI WHITE 60",
    "SellingPrice": 202
  }, {
    "Item Name": "BACCARDI WHITE 30",
    "SellingPrice": 101
  }, {
    "Item Name": "BACCARDI LEMON 180",
    "SellingPrice": 585
  }, {
    "Item Name": "BACCARDI LEMON 60",
    "SellingPrice": 202
  }, {
    "Item Name": "BACCARDI LEMON 30",
    "SellingPrice": 101
  }, {
    "Item Name": "BACCARDI ORANGE 180",
    "SellingPrice": 585
  }, {
    "Item Name": "BACCARDI ORANGE 60",
    "SellingPrice": 202
  }, {
    "Item Name": "BACCARDI LEMON 30",
    "SellingPrice": 101
  }, {
    "Item Name": "BACCARDI BLACK 180",
    "SellingPrice": 393
  }, {
    "Item Name": "BACCARDI BLACK 30",
    "SellingPrice": 67
  }, {
    "Item Name": "BACCARDI GOLD 180",
    "SellingPrice": 585
  }, {
    "Item Name": "BACCARDI GOLD30",
    "SellingPrice": 101
  }, {
    "Item Name": "OLD MONK 180",
    "SellingPrice": 225
  }, {
    "Item Name": "OLD MONK 90",
    "SellingPrice": 168
  }, {
    "Item Name": "OLD MONK 60",
    "SellingPrice": 90
  }, {
    "Item Name": "OLD MONK 30 ",
    "SellingPrice": 45
  }, {
    "Item Name": "DON ANGEL 750",
    "SellingPrice": 4668
  }, {
    "Item Name": "DON ANGEL 30",
    "SellingPrice": 191
  }, {
    "Item Name": "SAUZA SILVER 700",
    "SellingPrice": 6153
  }, {
    "Item Name": "SAUZA SILVER 30",
    "SellingPrice": 270
  }, {
    "Item Name": "JAGERBOMB",
    "SellingPrice": 506
  }, {
    "Item Name": "KAMAKAZI",
    "SellingPrice": 168
  }, {
    "Item Name": "JAGERMASTER",
    "SellingPrice": 303
  }, {
    "Item Name": "COINTTRAEU",
    "SellingPrice": 303
  }, {
    "Item Name": "SAMBUCA",
    "SellingPrice": 258
  }, {
    "Item Name": "KHALUA",
    "SellingPrice": 168
  }, {
    "Item Name": "MARTINI BLANCO",
    "SellingPrice": 90
  }, {
    "Item Name": "MARTINI ROSSO",
    "SellingPrice": 90
  }, {
    "Item Name": "HENESSY VS 700",
    "SellingPrice": 7875
  }, {
    "Item Name": "HENESSY VS 30",
    "SellingPrice": 348
  }, {
    "Item Name": "MORPHEUS 750",
    "SellingPrice": 2182
  }, {
    "Item Name": "MORPHEUS 180",
    "SellingPrice": 540
  }, {
    "Item Name": "MORPHEUS 60",
    "SellingPrice": 191
  }, {
    "Item Name": "MORPHEUS 30",
    "SellingPrice": 101
  }, {
    "Item Name": "MANSION HOUSE 180",
    "SellingPrice": 292
  }, {
    "Item Name": "MANSION HOUSE 90",
    "SellingPrice": 168
  }, {
    "Item Name": "MANSION HOUSE 60",
    "SellingPrice": 90
  }, {
    "Item Name": "MC BRANDY 60",
    "SellingPrice": 90
  }, {
    "Item Name": "RED BULL ",
    "SellingPrice": 157
  }, {
    "Item Name": "COKE",
    "SellingPrice": 45
  }, {
    "Item Name": "SPRITE",
    "SellingPrice": 45
  }, {
    "Item Name": "SODA",
    "SellingPrice": 33
  }, {
    "Item Name": "DIET COKE",
    "SellingPrice": 56
  }, {
    "Item Name": "TONIC WATER",
    "SellingPrice": 67
  }, {
    "Item Name": "GINGER ALE",
    "SellingPrice": 67
  }, {
    "Item Name": "LIME SODA",
    "SellingPrice": 45
  }, {
    "Item Name": "LIME WATER",
    "SellingPrice": 45
  }, {
    "Item Name": "PACKEGED WATER 1L",
    "SellingPrice": 39
  }, {
    "Item Name": "MANSION HOUSE 650",
    "SellingPrice": 900
  }, {
    "Item Name": "Chole Kulche",
    "SellingPrice": 80
  }, {
    "Item Name": "Butter Nan",
    "SellingPrice": 65
  }, {
    "Item Name": "Dhai",
    "SellingPrice": 20
  }, {
    "Item Name": "Rice",
    "SellingPrice": 55
  }, {
    "Item Name": "Plain rice",
    "SellingPrice": 30
  }, {
    "Item Name": "MANSION HOUSE 650",
    "SellingPrice": 900
  }, {
    "Item Name": "Chole Kulche",
    "SellingPrice": 80
  }, {
    "Item Name": "Butter Nan",
    "SellingPrice": 65
  }, {
    "Item Name": "Dhai",
    "SellingPrice": 20
  }, {
    "Item Name": "Rice",
    "SellingPrice": 55
  }, {
    "Item Name": "Plain rice",
    "SellingPrice": 30
  }]

  myFun();
  window.setInterval(showRows, 5000);
  showRows();

  function myFun() {
    addTable(tableValue);
  }

  function showRows() {
    // Any TRs that are not hidden and not already shown get "already-shown" applied
    $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
    // Then your previous code
    $(".hidden:lt(15)").removeClass("hidden"); // this one is to hide previous 5 rows and show next five
  }

  function addTable(tableValue) {
    var $tbl = $("
", {
        "class": "table"
      }),

      $tb = $("
"),
      $trh = $("
");

    var split = Math.round(tableValue.length / 4);
    for (i = 0; i < split; i++) {
      $tr = $("
", {
        class: "hidden"
      }); //ading class
      for (j = 0; j < 4; j++) {
        $.each(tableValue[split * j + i], function(key, value) {

          $("", {
            "class": "text-left color" + (j + 1)
          }).html(value).appendTo($tr);
        });
      }
      $tr.appendTo($tb);
    }
    $tbl.append($tb);
    $("#DisplayTable").html($tbl);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tbody>tr>td {
  white-space: normal;
  border-collapse: collapse;
  font-family: Verdana;
  font-weight: bold;
  white-space: nowrap;
}

td {
  word-break: break-all;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden,
.already-shown {
  display: none;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

```

答:
Use flexbox to simplify the table structure. Have a look at this fiddle

Render this HTML structure from JS:

```<code><div class="item already-show">
 <div class="col">
   <span>BIG BANAYAN CHENNIN BLANC BY GLASS</span><span>438</span>
 </div>
 <div class="col">
    <span>JAMESON 750</span><span>4950</span>
 </div>
 <div class="col">
    <span>BACCARDI WHITE 60</span><span>202</span>
 </div>
 <div class="col">
    <span>Plain rice</span><span>30</span>
 </div>
</div>
</code>```

CSS:

```<code>.item {
  display: flex;
  width:100%
}
.col {
  display: flex;
  padding: .75rem;
  vertical-align: top;
  border: 1px solid #dee2e6;
  width: 100%;
  align-items: center;
  justify-content: space-between;
}
</code>```

Body:
I am working on HTML table and i am stuck here for very long now, I have a requirement of displaying table into four columns/grid which i have done

Now when i am rendering the table i am displaying first 17 rows in one go than next 17 after five seconds

What is the issue

some ItemNames are big like BIG BANAYAN CARBINET SAUVIGNON BY GLASS

So when page is refreshing after five seconds the the column which contains this long name gets very large width which is not good to see as on UI

I am trying to make the width of each column uniform all four will have same width

So when the long ITEM NAME is coming what I am trying to do is to use word-wrap: normal; to break it after some width,but it is not working

I am dividing the four columns into equal part, which ever screen it is rendering the table it should be divided into 4 parts and when ITEMNAME is large i want to display it into same row but in new line after that exceeds the width of column

I think i have to give some sort of height to all the rows when it can accept one single small item name then it will show in single row but when the name is large it should show in same row but in two lines with same font

$(document).ready(function() {

  var tableValue = [{
    "Item Name": "MANCHOW  V SOUP",
    "SellingPrice": 100
  }, {
    "Item Name": "MANCHOW NV SOUP ",
    "SellingPrice": 125
  }, {
    "Item Name": "CEASER SALAD V",
    "SellingPrice": 175
  }, {
    "Item Name": "CEASER SALAD NV",
    "SellingPrice": 230
  }, {
    "Item Name": "GAMBUS REBOZADAS",
    "SellingPrice": 350
  }, {
    "Item Name": "PANCO FISH FINGER",
    "SellingPrice": 270
  }, {
    "Item Name": "MUSHROOM DUPLEX",
    "SellingPrice": 160
  }, {
    "Item Name": "FRENCH FRIES",
    "SellingPrice": 99
  }, {
    "Item Name": "HONEY GARLIC PRAWN",
    "SellingPrice": 350
  }, {
    "Item Name": "CHICKEN MANCHURIAN",
    "SellingPrice": 180
  }, {
    "Item Name": "MUSHROOM CHILLY",
    "SellingPrice": 120
  }, {
    "Item Name": "SALT N PEPPER BABY CORN",
    "SellingPrice": 120
  }, {
    "Item Name": "SOUTHERN STYLE CHICKEN",
    "SellingPrice": 210
  }, {
    "Item Name": "PANEER NAGGETS",
    "SellingPrice": 210
  }, {
    "Item Name": "HARA BHARA KEBAB",
    "SellingPrice": 160
  }, {
    "Item Name": "CHICKEN TIKKA",
    "SellingPrice": 210
  }, {
    "Item Name": "KALMI KEBAB",
    "SellingPrice": 250
  }, {
    "Item Name": "PIZZA MARGARITTA",
    "SellingPrice": 200
  }, {
    "Item Name": "PIZZA VEG FARMHOUSE",
    "SellingPrice": 200
  }, {
    "Item Name": "BBQ CHICKEN PIZZA",
    "SellingPrice": 225
  }, {
    "Item Name": "CHICKEN TIKKA PIZZA",
    "SellingPrice": 225
  }, {
    "Item Name": "PESTO SAUCE",
    "SellingPrice": 175
  }, {
    "Item Name": "ARABIATA",
    "SellingPrice": 160
  }, {
    "Item Name": "PINK SAUCE",
    "SellingPrice": 160
  }, {
    "Item Name": "GARBANZO BEAN SALAD",
    "SellingPrice": 90
  }, {
    "Item Name": "MASALA PAPAD",
    "SellingPrice": 50
  }, {
    "Item Name": "PEANUT MASALA",
    "SellingPrice": 60
  }, {
    "Item Name": "GAJAR KA HALWA",
    "SellingPrice": 90
  }, {
    "Item Name": "WATERMELON MARTINI",
    "SellingPrice": 281
  }, {
    "Item Name": "Kiwi martini",
    "SellingPrice": 281
  }, {
    "Item Name": " Apple gin",
    "SellingPrice": 225
  }, {
    "Item Name": "Cucumber  cooler ",
    "SellingPrice": 281
  }, {
    "Item Name": "Martini",
    "SellingPrice": 225
  }, {
    "Item Name": "Pink lady",
    "SellingPrice": 225
  }, {
    "Item Name": " Bloody marry",
    "SellingPrice": 281
  }, {
    "Item Name": "Cosmopolitan",
    "SellingPrice": 281
  }, {
    "Item Name": "Sex on the beach",
    "SellingPrice": 281
  }, {
    "Item Name": "Bull frog",
    "SellingPrice": 506
  }, {
    "Item Name": "Long  island iced tea ",
    "SellingPrice": 393
  }, {
    "Item Name": "Pinacolada",
    "SellingPrice": 225
  }, {
    "Item Name": "Daiquiri",
    "SellingPrice": 225
  }, {
    "Item Name": "Mojito ",
    "SellingPrice": 281
  }, {
    "Item Name": "Whisky sour",
    "SellingPrice": 281
  }, {
    "Item Name": "Hot toddy",
    "SellingPrice": 225
  }, {
    "Item Name": "Margarita",
    "SellingPrice": 337
  }, {
    "Item Name": "Tequila sunrise",
    "SellingPrice": 337
  }, {
    "Item Name": "Red sangria",
    "SellingPrice": 225
  }, {
    "Item Name": "White sangria",
    "SellingPrice": 247
  }, {
    "Item Name": "Rose sangria",
    "SellingPrice": 247
  }, {
    "Item Name": "By chance special ",
    "SellingPrice": 168
  }, {
    "Item Name": "Made in heaven",
    "SellingPrice": 168
  }, {
    "Item Name": "Strawberry delight",
    "SellingPrice": 168
  }, {
    "Item Name": "DRAGON",
    "SellingPrice": 168
  }, {
    "Item Name": "Mangochil ",
    "SellingPrice": 168
  }, {
    "Item Name": "Cucumber cola",
    "SellingPrice": 168
  }, {
    "Item Name": "Virgin mojito",
    "SellingPrice": 168
  }, {
    "Item Name": "Virgin mary",
    "SellingPrice": 168
  }, {
    "Item Name": "Virgin pinacolada",
    "SellingPrice": 168
  }, {
    "Item Name": "CORONA",
    "SellingPrice": 438
  }, {
    "Item Name": "CRAFT BEERS",
    "SellingPrice": 337
  }, {
    "Item Name": "BIRA WHITE 330",
    "SellingPrice": 157
  }, {
    "Item Name": "BIRA BLONDE 330",
    "SellingPrice": 135
  }, {
    "Item Name": "BIRA STRONG 650",
    "SellingPrice": 213
  }, {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123
  }, {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202
  }, {
    "Item Name": "KINGFISHER STRONG 330",
    "SellingPrice": 135
  }, {
    "Item Name": "KINGFISHER STRONG 650",
    "SellingPrice": 213
  }, {
    "Item Name": "KINGFISHER ULTRA 330",
    "SellingPrice": 146
  }, {
    "Item Name": "KINGFISHER ULTRA 650",
    "SellingPrice": 281
  }, {
    "Item Name": "KINGFISHER ULTRA MAX 330",
    "SellingPrice": 146
  }, {
    "Item Name": "KINGFISHER ULTRA MAX 650",
    "SellingPrice": 281
  }, {
    "Item Name": "BUDWIESER 330",
    "SellingPrice": 146
  }, {
    "Item Name": "BUDWIESER 650",
    "SellingPrice": 270
  }, {
    "Item Name": "BUDWIESER MAGNUM 330",
    "SellingPrice": 168
  }, {
    "Item Name": "BUDWIESER MAGNUM 650",
    "SellingPrice": 281
  }, {
    "Item Name": "TUBORG 330",
    "SellingPrice": 123
  }, {
    "Item Name": "TUBORG 650",
    "SellingPrice": 191
  }, {
    "Item Name": "TUBORG STRONG 330",
    "SellingPrice": 123
  }, {
    "Item Name": "TUBORG STRONG 650",
    "SellingPrice": 213
  }, {
    "Item Name": "CRANBERRY ",
    "SellingPrice": 157
  }, {
    "Item Name": "ORANGE",
    "SellingPrice": 157
  }, {
    "Item Name": "JAMICAN",
    "SellingPrice": 157
  }, {
    "Item Name": "BLACK BERRY",
    "SellingPrice": 157
  }, {
    "Item Name": "BLUE BERRY",
    "SellingPrice": 157
  }, {
    "Item Name": "MOET CHANDON",
    "SellingPrice": 7875
  }, {
    "Item Name": "SULA BRUT",
    "SellingPrice": 1687
  }, {
    "Item Name": "MATEUS ROSE",
    "SellingPrice": 2137
  }, {
    "Item Name": "HARDYS SIRAZ CABERNET 750",
    "SellingPrice": 1890
  }, {
    "Item Name": "HARDYS SIRAZ CABERNET BY GLASS",
    "SellingPrice": 382
  }, {
    "Item Name": "JACOB CREEK SIRAZ 750",
    "SellingPrice": 1800
  }, {
    "Item Name": "JACOB CREEK SIRAZ BY GLASS",
    "SellingPrice": 360
  }, {
    "Item Name": "BIG BANAYAN CHENNIN BLANC 750",
    "SellingPrice": 990
  }, {
    "Item Name": "BIG BANAYAN CHENNIN BLANC BY GLASS",
    "SellingPrice": 202
  }, {
    "Item Name": "SULA CHENIN BLANC 750 ",
    "SellingPrice": 1293
  }, {
    "Item Name": "SULA CHENIN BLANC BY GLASS",
    "SellingPrice": 258
  }, {
    "Item Name": "FOUR SEAZON CLASSIC CHENNIN BLANC 7",
    "SellingPrice": 1125
  }, {
    "Item Name": "FOUR SEAZON CLASSIC CHENNIN BLANC B",
    "SellingPrice": 225
  }, {
    "Item Name": "BIG BANAYAN CARBINET SAUVIGNON 750",
    "SellingPrice": 1125
  }, {
    "Item Name": "BIG BANAYAN CARBINET SAUVIGNON BY G",
    "SellingPrice": 225
  }, {
    "Item Name": "SULA SATORI MERLOT 750",
    "SellingPrice": 1237
  }, {
    "Item Name": "SULA SATORI MERLOT BY GLASS",
    "SellingPrice": 247
  }, {
    "Item Name": "GROVERS LA RESERVE 750",
    "SellingPrice": 1800
  }, {
    "Item Name": "GROVERS LA RESERVE 100",
    "SellingPrice": 360
  }, {
    "Item Name": "GLENFIDDICH 12 YEARS 700 ",
    "SellingPrice": 9225
  }, {
    "Item Name": "GLENFIDDICH 12 YEARS 30",
    "SellingPrice": 405
  }, {
    "Item Name": "TALISKER 750",
    "SellingPrice": 8775
  }, {
    "Item Name": "TALISKER 30",
    "SellingPrice": 360
  }, {
    "Item Name": "GLENNLIVET 750",
    "SellingPrice": 8887
  }, {
    "Item Name": "GLENNLIVET 30",
    "SellingPrice": 360
  }, {
    "Item Name": "THE SINGLETON 750",
    "SellingPrice": 7942
  }, {
    "Item Name": "THE SINGLETON 30",
    "SellingPrice": 326
  }, {
    "Item Name": "AMRUT FUSION 750",
    "SellingPrice": 5062
  }, {
    "Item Name": "AMRUT FUSION 30",
    "SellingPrice": 202
  }, {
    "Item Name": "JACK DANIELS 750",
    "SellingPrice": 7312
  }, {
    "Item Name": "JACK DANIELS 30",
    "SellingPrice": 292
  }, {
    "Item Name": "JIM BEAM WHITE 750",
    "SellingPrice": 4095
  }, {
    "Item Name": "JIM BEAM WHITE 30",
    "SellingPrice": 168
  }, {
    "Item Name": "JAMESON 750",
    "SellingPrice": 4950
  }, {
    "Item Name": "JAMESON 30",
    "SellingPrice": 202
  }, {
    "Item Name": "JW BLACK LABEL 750",
    "SellingPrice": 8212
  }, {
    "Item Name": "JW BLACK LABEL 200",
    "SellingPrice": 2925
  }, {
    "Item Name": "JW BLACK LABEL 30",
    "SellingPrice": 337
  }, {
    "Item Name": "JW RED LABEL 200",
    "SellingPrice": 1158
  }, {
    "Item Name": "BALLENTINSE FINEST BLENDED 750",
    "SellingPrice": 4545
  }, {
    "Item Name": "BALLENTINSE FINEST BLENDED 30",
    "SellingPrice": 180
  }, {
    "Item Name": "BLACK \u0026 WHITE 375",
    "SellingPrice": 1575
  }, {
    "Item Name": "BLACK \u0026 WHITE 180",
    "SellingPrice": 787
  }, {
    "Item Name": "BLACK \u0026 WHITE 60",
    "SellingPrice": 258
  }, {
    "Item Name": "BLACK \u0026 WHITE 30",
    "SellingPrice": 135
  }, {
    "Item Name": "100 PIPERS 180",
    "SellingPrice": 787
  }, {
    "Item Name": "100 PIPERS 60",
    "SellingPrice": 258
  }, {
    "Item Name": "100 PIPERS 30",
    "SellingPrice": 135
  }, {
    "Item Name": "VAT 69 180",
    "SellingPrice": 675
  }, {
    "Item Name": "VAT 69 60",
    "SellingPrice": 225
  }, {
    "Item Name": "VAT 69 30",
    "SellingPrice": 112
  }, {
    "Item Name": "TEACHERS HIGHLAND 180",
    "SellingPrice": 787
  }, {
    "Item Name": "TEACHERS HIGHLAND 60",
    "SellingPrice": 258
  }, {
    "Item Name": "TEACHERS HIGHLAND 30",
    "SellingPrice": 135
  }, {
    "Item Name": "TEACHERS 50 60",
    "SellingPrice": 393
  }, {
    "Item Name": "TEACHERS 50 30",
    "SellingPrice": 202
  }, {
    "Item Name": "BLACK DOG TRIPPLE GOLD 180",
    "SellingPrice": 1215
  }, {
    "Item Name": "BLACK DOG TRIPPLE GOLD 30",
    "SellingPrice": 213
  }, {
    "Item Name": "BLACK DOG 8 YEARS 180",
    "SellingPrice": 731
  }, {
    "Item Name": "BLACK DOG 8 YEARS 60",
    "SellingPrice": 247
  }, {
    "Item Name": "BLACK DOG 8 YEARS 30",
    "SellingPrice": 123
  }, {
    "Item Name": "BLENDERS PRIDE 750",
    "SellingPrice": 2283
  }, {
    "Item Name": "BLENDERS PRIDE 375",
    "SellingPrice": 1147
  }, {
    "Item Name": "BLENDERS PRIDE 180",
    "SellingPrice": 573
  }, {
    "Item Name": "BLENDERS PRIDE 60",
    "SellingPrice": 191
  }, {
    "Item Name": "BLENDERS PRIDE 30",
    "SellingPrice": 90
  }, {
    "Item Name": "SIGNATURE 180",
    "SellingPrice": 450
  }, {
    "Item Name": "SIGNATURE 60",
    "SellingPrice": 168
  }, {
    "Item Name": "SIGNATURE 30",
    "SellingPrice": 90
  }, {
    "Item Name": "GREY GOOSE 750",
    "SellingPrice": 8190
  }, {
    "Item Name": "GREY GOOSE 30",
    "SellingPrice": 326
  }, {
    "Item Name": "BELVEDERE 700",
    "SellingPrice": 8122
  }, {
    "Item Name": "BELVEDERE 30",
    "SellingPrice": 360
  }, {
    "Item Name": "CIROC 750",
    "SellingPrice": 7425
  }, {
    "Item Name": "CIROC 30",
    "SellingPrice": 303
  }, {
    "Item Name": "ABSOLUT 750",
    "SellingPrice": 4556
  }, {
    "Item Name": "ABSOLUT 30",
    "SellingPrice": 191
  }, {
    "Item Name": "SMIRNOFF RED 180",
    "SellingPrice": 551
  }, {
    "Item Name": "SMIRNOFF RED 60",
    "SellingPrice": 202
  }, {
    "Item Name": "SMIRNOFF RED30",
    "SellingPrice": 101
  }, {
    "Item Name": "SMIRNOFF ORANGE 180",
    "SellingPrice": 551
  }, {
    "Item Name": "SMIRNOFF ORANGE 60",
    "SellingPrice": 202
  }, {
    "Item Name": "SMINOFF ORANGE30",
    "SellingPrice": 101
  }, {
    "Item Name": "SMIRNOFF GREEN APPLE 180",
    "SellingPrice": 551
  }, {
    "Item Name": "SMIRNOFF GREEN APPLE 60",
    "SellingPrice": 202
  }, {
    "Item Name": "SMIRNOFF GREEN APPLE30",
    "SellingPrice": 101
  }, {
    "Item Name": "BOMBAY SAPHIRE 750",
    "SellingPrice": 4725
  }, {
    "Item Name": "BOMBAY SAPHIRE 30",
    "SellingPrice": 191
  }, {
    "Item Name": "BLUE RIBBAND 750",
    "SellingPrice": 877
  }, {
    "Item Name": "BLUE RIBBAND 60",
    "SellingPrice": 78
  }, {
    "Item Name": "BACCARDI WHITE 750",
    "SellingPrice": 2418
  }, {
    "Item Name": "BACCARDI WHITE 180",
    "SellingPrice": 585
  }, {
    "Item Name": "BACCARDI WHITE 60",
    "SellingPrice": 202
  }, {
    "Item Name": "BACCARDI WHITE 30",
    "SellingPrice": 101
  }, {
    "Item Name": "BACCARDI LEMON 180",
    "SellingPrice": 585
  }, {
    "Item Name": "BACCARDI LEMON 60",
    "SellingPrice": 202
  }, {
    "Item Name": "BACCARDI LEMON 30",
    "SellingPrice": 101
  }, {
    "Item Name": "BACCARDI ORANGE 180",
    "SellingPrice": 585
  }, {
    "Item Name": "BACCARDI ORANGE 60",
    "SellingPrice": 202
  }, {
    "Item Name": "BACCARDI LEMON 30",
    "SellingPrice": 101
  }, {
    "Item Name": "BACCARDI BLACK 180",
    "SellingPrice": 393
  }, {
    "Item Name": "BACCARDI BLACK 30",
    "SellingPrice": 67
  }, {
    "Item Name": "BACCARDI GOLD 180",
    "SellingPrice": 585
  }, {
    "Item Name": "BACCARDI GOLD30",
    "SellingPrice": 101
  }, {
    "Item Name": "OLD MONK 180",
    "SellingPrice": 225
  }, {
    "Item Name": "OLD MONK 90",
    "SellingPrice": 168
  }, {
    "Item Name": "OLD MONK 60",
    "SellingPrice": 90
  }, {
    "Item Name": "OLD MONK 30 ",
    "SellingPrice": 45
  }, {
    "Item Name": "DON ANGEL 750",
    "SellingPrice": 4668
  }, {
    "Item Name": "DON ANGEL 30",
    "SellingPrice": 191
  }, {
    "Item Name": "SAUZA SILVER 700",
    "SellingPrice": 6153
  }, {
    "Item Name": "SAUZA SILVER 30",
    "SellingPrice": 270
  }, {
    "Item Name": "JAGERBOMB",
    "SellingPrice": 506
  }, {
    "Item Name": "KAMAKAZI",
    "SellingPrice": 168
  }, {
    "Item Name": "JAGERMASTER",
    "SellingPrice": 303
  }, {
    "Item Name": "COINTTRAEU",
    "SellingPrice": 303
  }, {
    "Item Name": "SAMBUCA",
    "SellingPrice": 258
  }, {
    "Item Name": "KHALUA",
    "SellingPrice": 168
  }, {
    "Item Name": "MARTINI BLANCO",
    "SellingPrice": 90
  }, {
    "Item Name": "MARTINI ROSSO",
    "SellingPrice": 90
  }, {
    "Item Name": "HENESSY VS 700",
    "SellingPrice": 7875
  }, {
    "Item Name": "HENESSY VS 30",
    "SellingPrice": 348
  }, {
    "Item Name": "MORPHEUS 750",
    "SellingPrice": 2182
  }, {
    "Item Name": "MORPHEUS 180",
    "SellingPrice": 540
  }, {
    "Item Name": "MORPHEUS 60",
    "SellingPrice": 191
  }, {
    "Item Name": "MORPHEUS 30",
    "SellingPrice": 101
  }, {
    "Item Name": "MANSION HOUSE 180",
    "SellingPrice": 292
  }, {
    "Item Name": "MANSION HOUSE 90",
    "SellingPrice": 168
  }, {
    "Item Name": "MANSION HOUSE 60",
    "SellingPrice": 90
  }, {
    "Item Name": "MC BRANDY 60",
    "SellingPrice": 90
  }, {
    "Item Name": "RED BULL ",
    "SellingPrice": 157
  }, {
    "Item Name": "COKE",
    "SellingPrice": 45
  }, {
    "Item Name": "SPRITE",
    "SellingPrice": 45
  }, {
    "Item Name": "SODA",
    "SellingPrice": 33
  }, {
    "Item Name": "DIET COKE",
    "SellingPrice": 56
  }, {
    "Item Name": "TONIC WATER",
    "SellingPrice": 67
  }, {
    "Item Name": "GINGER ALE",
    "SellingPrice": 67
  }, {
    "Item Name": "LIME SODA",
    "SellingPrice": 45
  }, {
    "Item Name": "LIME WATER",
    "SellingPrice": 45
  }, {
    "Item Name": "PACKEGED WATER 1L",
    "SellingPrice": 39
  }, {
    "Item Name": "MANSION HOUSE 650",
    "SellingPrice": 900
  }, {
    "Item Name": "Chole Kulche",
    "SellingPrice": 80
  }, {
    "Item Name": "Butter Nan",
    "SellingPrice": 65
  }, {
    "Item Name": "Dhai",
    "SellingPrice": 20
  }, {
    "Item Name": "Rice",
    "SellingPrice": 55
  }, {
    "Item Name": "Plain rice",
    "SellingPrice": 30
  }, {
    "Item Name": "MANSION HOUSE 650",
    "SellingPrice": 900
  }, {
    "Item Name": "Chole Kulche",
    "SellingPrice": 80
  }, {
    "Item Name": "Butter Nan",
    "SellingPrice": 65
  }, {
    "Item Name": "Dhai",
    "SellingPrice": 20
  }, {
    "Item Name": "Rice",
    "SellingPrice": 55
  }, {
    "Item Name": "Plain rice",
    "SellingPrice": 30
  }]

  myFun();
  window.setInterval(showRows, 5000);
  showRows();

  function myFun() {
    addTable(tableValue);
  }

  function showRows() {
    // Any TRs that are not hidden and not already shown get "already-shown" applied
    $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
    // Then your previous code
    $(".hidden:lt(15)").removeClass("hidden"); // this one is to hide previous 5 rows and show next five
  }

  function addTable(tableValue) {
    var $tbl = $("
", {
        "class": "table"
      }),

      $tb = $("
"),
      $trh = $("
");

    var split = Math.round(tableValue.length / 4);
    for (i = 0; i < split; i++) {
      $tr = $("
", {
        class: "hidden"
      }); //ading class
      for (j = 0; j < 4; j++) {
        $.each(tableValue[split * j + i], function(key, value) {

          $("", {
            "class": "text-left color" + (j + 1)
          }).html(value).appendTo($tr);
        });
      }
      $tr.appendTo($tb);
    }
    $tbl.append($tb);
    $("#DisplayTable").html($tbl);
  }
});

tbody>tr>td {
  white-space: normal;
  border-collapse: collapse;
  font-family: Verdana;
  font-weight: bold;
  white-space: nowrap;
}

td {
  word-break: break-all;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden,
.already-shown {
  display: none;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

Body:
Use flexbox to simplify the table structure. Have a look at this fiddle

Render this HTML structure from JS:

<div class="item already-show">
 <div class="col">
   <span>BIG BANAYAN CHENNIN BLANC BY GLASS</span><span>438</span>
 </div>
 <div class="col">
    <span>JAMESON 750</span><span>4950</span>
 </div>
 <div class="col">
    <span>BACCARDI WHITE 60</span><span>202</span>
 </div>
 <div class="col">
    <span>Plain rice</span><span>30</span>
 </div>
</div>

CSS:

.item {
  display: flex;
  width:100%
}
.col {
  display: flex;
  padding: .75rem;
  vertical-align: top;
  border: 1px solid #dee2e6;
  width: 100%;
  align-items: center;
  justify-content: space-between;
}


来源: stackexchange

问:
C# late binding to com/activeX server, trouble with one method
I am fairly new to Interop/Com/ActiveX etc, so bear with me.

I am late binding into a com/activex (not sure which one) server (basically an exe not a dll). I am successfully using all the methods in that server except for one, here is the description:

VT_INT GetLastCCTError (variant
  *error_string);

Description: This function is used to retrieve the last error generated
  by the CCT. The function may be called
  at any point as long as the CCT Server
  is initialized. If no error has
  occurred when the function is called,
  the returned code is ‘0’ (zero), and
  the error string will be empty. Only
  the last error that occurred during
  the current run of the CCT Server will
  be available.

Input: None

Output: The function returns a single output parameter,
  ‘error_string’ of type VARTYPE VT_BSTR
  | VT_BYREF. The parameter contains an
  error string for the error code
  associated with the last CCT function
  failure. Return Value: This function
  returns an integer value of type
  VT_INT. This is the error code
  associated with the last CCT function
  failure

I first tried using this code:

```<code>this.LastErrorCode = (int)CCTType.InvokeMember("GetLastCCTError", BindingFlags.InvokeMethod, null, CCTObject, new object[] {this.LastErrorString});
</code>```

I got the following exception: Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)

Then after some thinking I changed the code to:

```<code>object[] Args = { "SomeString" };

this.LastErrorCode = (int)CCTType.InvokeMember("GetLastCCTError", BindingFlags.InvokeMethod, null, CCTObject, Args);
</code>```

Still the same error. After some googling, I found this article: http://www.informit.com/articles/article.aspx?p=27219&seqNum=8

If you look at section 3.3 it seems to be the solution to my problem, and thus I changed my code to:

```<code>object[] Args = { "SomeString" };

ParameterModifier ParMod = new ParameterModifier(1);
ParMod[0] = true;
ParameterModifier[] ArrParMod = { ParMod };

this.LastErrorCode = (int)CCTType.InvokeMember("GetLastCCTError", BindingFlags.InvokeMethod, null, CCTObject, Args, ArrParMod, null, null);

this.LastErrorString = (string) Args[0];
</code>```

This still results in the same exception. I am now thinking that the problem might not be the reference passing but something else. Any help will be appreciated.

答:
Is this because strings in C# are immutable.

"SomeString" will be resolved by the compiler as an unchangeable string on the managed memory (stack or heap is largely irrelevant in your case).

So, in a way you are not passing in a string reference but a literal - something that could never be an 'out' parameter as in your example ... so the marshalling won't do what it thinks (knows) would be a bad idea.

Andrew D, I suspect, is right.

Might suggest you try something like:

```<code>StringBuilder errorMessage = new StringBuilder();

this.LastErrorCode = (int)CCTType.InvokeMember("GetLastCCTError", BindingFlags.InvokeMethod, null, CCTObject, errorMessage );

this.LastErrorString = errorMessage.ToString();
</code>```

Regards,

Aidanapword

ContentLicense: CC BY-SA 2.5

Body:
I am fairly new to Interop/Com/ActiveX etc, so bear with me.

I am late binding into a com/activex (not sure which one) server (basically an exe not a dll). I am successfully using all the methods in that server except for one, here is the description:

VT_INT GetLastCCTError (variant
  *error_string);

Description: This function is used to retrieve the last error generated
  by the CCT. The function may be called
  at any point as long as the CCT Server
  is initialized. If no error has
  occurred when the function is called,
  the returned code is ‘0’ (zero), and
  the error string will be empty. Only
  the last error that occurred during
  the current run of the CCT Server will
  be available.

Input: None

Output: The function returns a single output parameter,
  ‘error_string’ of type VARTYPE VT_BSTR
  | VT_BYREF. The parameter contains an
  error string for the error code
  associated with the last CCT function
  failure. Return Value: This function
  returns an integer value of type
  VT_INT. This is the error code
  associated with the last CCT function
  failure

I first tried using this code:

this.LastErrorCode = (int)CCTType.InvokeMember("GetLastCCTError", BindingFlags.InvokeMethod, null, CCTObject, new object[] {this.LastErrorString});

I got the following exception: Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)

Then after some thinking I changed the code to:

object[] Args = { "SomeString" };

this.LastErrorCode = (int)CCTType.InvokeMember("GetLastCCTError", BindingFlags.InvokeMethod, null, CCTObject, Args);

Still the same error. After some googling, I found this article: http://www.informit.com/articles/article.aspx?p=27219&seqNum=8

If you look at section 3.3 it seems to be the solution to my problem, and thus I changed my code to:

object[] Args = { "SomeString" };

ParameterModifier ParMod = new ParameterModifier(1);
ParMod[0] = true;
ParameterModifier[] ArrParMod = { ParMod };

this.LastErrorCode = (int)CCTType.InvokeMember("GetLastCCTError", BindingFlags.InvokeMethod, null, CCTObject, Args, ArrParMod, null, null);

this.LastErrorString = (string) Args[0];

This still results in the same exception. I am now thinking that the problem might not be the reference passing but something else. Any help will be appreciated.

Body:
Is this because strings in C# are immutable.

"SomeString" will be resolved by the compiler as an unchangeable string on the managed memory (stack or heap is largely irrelevant in your case).

So, in a way you are not passing in a string reference but a literal - something that could never be an 'out' parameter as in your example ... so the marshalling won't do what it thinks (knows) would be a bad idea.

Andrew D, I suspect, is right.

Might suggest you try something like:

StringBuilder errorMessage = new StringBuilder();

this.LastErrorCode = (int)CCTType.InvokeMember("GetLastCCTError", BindingFlags.InvokeMethod, null, CCTObject, errorMessage );

this.LastErrorString = errorMessage.ToString();

Regards,

Aidanapword

ContentLicense: CC BY-SA 3.0


问:
Spring Thymeleaf with LocalDateTime problem
I have problems with localdatetime attributes using Spring and Thymeleaf.

My code:

Event.java

```<code>public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable=false)
    @NotNull(message="Name is required!")
    private String name;

    @Column(nullable=false)
    @NotNull(message="Time is required!")
    @DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm")
    private LocalDateTime time;
}
</code>```

EventController.java

```<code>...
@GetMapping("/eventEntry")
public String showForm(Model model) {

    model.addAttribute("event", new Event());

    return "eventEntry";
}

@PostMapping("/eventEntry")
public String processForm(@RequestParam("time") @DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm") LocalDateTime time,
        @Valid Event event, Errors errors, Model model) {

    if(errors.hasErrors()) {

        return "eventEntry";

    } else {

        eventList.add(event);

        eventRepository.save(event);

        model.addAttribute("event", event);
        model.addAttribute("time", time);
        model.addAttribute("listaDogadaja", listaDogadaja);

        return "output";
    }
}
</code>```

eventEntry.html

```<code><body>
    <h1>Event entry form</h1>

    <h3>New event</h3>

    <form method="POST" th:object="${event}">

        <div class="form-group">
            <label for="naziv">Name: </label>
            <input type="text" th:field="*{name}" />
            <span class="validation-error" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span>
        </div>

        <div class="form-group">
            <label for="time">Time: </label>
            <input type="datetime-local" th:field="*{time}" />
            <span class="validation-error" th:if="${#fields.hasErrors('time')}" th:errors="*{time}">Time Error</span>
        </div>

        <div class="form-group">
            <input type="submit" th:value="Save">
            <input type="reset" class="btn btn-danger" th:value="Cancel">
        </div>

    </form>
</body>
</code>```

When clicking the save button, I'm getting this exception:

```<code>Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime';
nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '05.14.2014. 1:00 PM';
nested exception is
java.lang.IllegalArgumentException: Parse attempt failed for value [05.14.2014. 1:00 PM]**
</code>```

Why is that?

答:
Have a close look at this:

```<code>java.lang.IllegalArgumentException: Parse attempt failed for value [05.14.2014. 1:00 PM]**
</code>```

The time provided is : 05.14.2014. 1:00 PM

You need to change your code accordingly to support AM/PM:
try:

```<code>...
@DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm a")
private LocalDateTime time;
</code>```

and

```<code>...
public String processForm(@RequestParam("time") @DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm a") LocalDateTime time,
</code>```

Here a means AM or PM.

for more have a look here: format-time-12-hours-pattern

ContentLicense: CC BY-SA 4.0

Body:
I have problems with localdatetime attributes using Spring and Thymeleaf.

My code:

Event.java

public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable=false)
    @NotNull(message="Name is required!")
    private String name;

    @Column(nullable=false)
    @NotNull(message="Time is required!")
    @DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm")
    private LocalDateTime time;
}

EventController.java

...
@GetMapping("/eventEntry")
public String showForm(Model model) {

    model.addAttribute("event", new Event());

    return "eventEntry";
}

@PostMapping("/eventEntry")
public String processForm(@RequestParam("time") @DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm") LocalDateTime time,
        @Valid Event event, Errors errors, Model model) {

    if(errors.hasErrors()) {

        return "eventEntry";

    } else {

        eventList.add(event);

        eventRepository.save(event);

        model.addAttribute("event", event);
        model.addAttribute("time", time);
        model.addAttribute("listaDogadaja", listaDogadaja);

        return "output";
    }
}

eventEntry.html

Event entry form

New event

    <form method="POST" th:object="${event}">

            Name:
            <input type="text" th:field="*{name}" />
            Name Error

            Time:
            <input type="datetime-local" th:field="*{time}" />
            Time Error

            <input type="submit" th:value="Save">
            <input type="reset" class="btn btn-danger" th:value="Cancel">

    </form>

When clicking the save button, I'm getting this exception:

Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime';
nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '05.14.2014. 1:00 PM';
nested exception is
java.lang.IllegalArgumentException: Parse attempt failed for value [05.14.2014. 1:00 PM]**

Why is that?

Body:
Have a close look at this:

java.lang.IllegalArgumentException: Parse attempt failed for value [05.14.2014. 1:00 PM]**

The time provided is : 05.14.2014. 1:00 PM

You need to change your code accordingly to support AM/PM:
try:

...
@DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm a")
private LocalDateTime time;

and

...
public String processForm(@RequestParam("time") @DateTimeFormat(pattern = "MM.dd.yyyy. HH:mm a") LocalDateTime time,

Here a means AM or PM.

for more have a look here: format-time-12-hours-pattern


问:
Bot responding too slow after first message
We have a bot built using Microsoft Boatbuilder and node.js, hosted on Azure. The bot works fine and responds almost instantly when a single user says "Hi". But we have observed that when multiple users are trying to chat, the bot takes anywhere between 30 sec to 1 minute to respond to the first message.

We checked the application logs but there is nothing in there that can explain the cause of this delay.

答:
We had the same issue and found turning the app service to Always On reduced our first message latency massively.

If you go to your Azure portal, then navigate to:

Dashboard --> App Services --> [name of service] --> Configuration -->
  General Settings

there's an Always On option you can check 'yes' to.


问:
Is there any way to filter all previous elements, by class?
I have a masonry gallery with ul / li elements. To make them responsive I am adding to each 'li' element it's column number as a class, so I can sort them later.

I am trying to get previous elements height in column before adding new one. So basically the column height before new 'li' element.

I am using prevAll(), to get all previous elements, but I can't combine height calculation and filtering columns. So tried to achieve it with each(), with filter, and with changing selector, I added that part of the code.

```<code>var that= this;
that.prevAll = $(this).prevAll();

that.top += $(this).prevAll('.column' + that.current_column).height();
// selector

that.top += that.prevAll.filter('.column' + that.current_column).height();
// filter

that.prevAll.each(function(){
  if(that.prevAll.hasClass('.column' + that.current_column)) {
  that.top += that.prevAll.height() + that.settings.imegesGap;
 };
});
// .each
</code>```

DOM

jQuery

```<code> $this.addClass('column' + that.current_column);
 $this.addClass('row' + that.row);
</code>```

HTML

```<code><ul class="mosaic1">
    <li ><img src="img/test.png"></li>
    <li ><img src="img/test6.jpg"></li>
    <li ><img src="img/test4.jpg"></li>
    <li ><img src="img/test.3.jpg"></li>
    <li ><img src="img/test7.jpg"></li>
    <li ><img src="img/test5.png"></li>
</ul>
</code>```

The main problem with  'each' function.It keeps summing up.

P.S. This is my first question here, so sorry if description not good enough.

答:
So the main problem was  each function, it worked wrong because I did not reset that.top  at the begging. So the  correct way is this</p>

```<code>var that= this;
that.prevAll = $(this).prevAll();
that.top = 0;

that.prevAll.each(function(){
  if(that.prevAll.hasClass('.column' + that.current_column)) {
   that.top += that.prevAll.height() + that.settings.imegesGap;
  };
enter code here
</code>```

Body:
I have a masonry gallery with ul / li elements. To make them responsive I am adding to each 'li' element it's column number as a class, so I can sort them later.

I am trying to get previous elements height in column before adding new one. So basically the column height before new 'li' element.

I am using prevAll(), to get all previous elements, but I can't combine height calculation and filtering columns. So tried to achieve it with each(), with filter, and with changing selector, I added that part of the code.

var that= this;
that.prevAll = $(this).prevAll();

that.top += $(this).prevAll('.column' + that.current_column).height();
// selector

that.top += that.prevAll.filter('.column' + that.current_column).height();
// filter

that.prevAll.each(function(){
  if(that.prevAll.hasClass('.column' + that.current_column)) {
  that.top += that.prevAll.height() + that.settings.imegesGap;
 };
});
// .each

DOM

jQuery

 $this.addClass('column' + that.current_column);
 $this.addClass('row' + that.row);

HTML

The main problem with  'each' function.It keeps summing up.

P.S. This is my first question here, so sorry if description not good enough.

Body:
So the main problem was  each function, it worked wrong because I did not reset that.top  at the begging. So the  correct way is this

var that= this;
that.prevAll = $(this).prevAll();
that.top = 0;

that.prevAll.each(function(){
  if(that.prevAll.hasClass('.column' + that.current_column)) {
   that.top += that.prevAll.height() + that.settings.imegesGap;
  };
enter code here


问:
Gradient color in CSS with percentage
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

```<code> .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }
</code>```

答:
You need to specify the points in ascending order. Just invert the values you have (you don't really need the purple but could add it if desired):

body {
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(to bottom, blue 15%, red 90%) center/cover no-repeat;
}```

Title: Gradient color in CSS with percentage

Body:
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

 .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }


问:
How do add editors but to only the unprotected cells
I have about 70 tabs that I am setting protection up for other than certain ranges which I want to be editable by all, however, if I protect them all, then share the workbook, everyone becomes an editor and can then edit the protected ranges.
Any thoughts?</p>

```<code>  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('A330'), true);
  protection = spreadsheet.getActiveSheet().protect();
  protection.setUnprotectedRanges([spreadsheet.getRange('O13:O18'),
  spreadsheet.getRange('O24:O29'), spreadsheet.getRange('O35:O45')])

  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('A340'), true);
  protection = spreadsheet.getActiveSheet().protect();
  protection.setUnprotectedRanges([spreadsheet.getRange('O13:O18'),
  spreadsheet.getRange('O24:O29'), spreadsheet.getRange('O35:O45')])
</code>```

答: you need to protect the unprotected ranges (SpreadsheetApp.ProtectionType.RANGE) and give access only to certain users.</p>

Body:
I have about 70 tabs that I am setting protection up for other than certain ranges which I want to be editable by all, however, if I protect them all, then share the workbook, everyone becomes an editor and can then edit the protected ranges.
Any thoughts?

  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('A330'), true);
  protection = spreadsheet.getActiveSheet().protect();
  protection.setUnprotectedRanges([spreadsheet.getRange('O13:O18'),
  spreadsheet.getRange('O24:O29'), spreadsheet.getRange('O35:O45')])

  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('A340'), true);
  protection = spreadsheet.getActiveSheet().protect();
  protection.setUnprotectedRanges([spreadsheet.getRange('O13:O18'),
  spreadsheet.getRange('O24:O29'), spreadsheet.getRange('O35:O45')])


问:
parse parenthesized numbers to negative numbers
How can i Parse parenthesized numbers in a list of strings  to negative numbers (or strings with negative sign).

example

```<code>input
list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']

output
['abcd',-1234,'Level-2 (2):','-31%', 'others','-3102.2%']
</code>```

strings only with numbers inside parenthesis or numbers with comma/dot inside parenthesis followed by a percentage(%) sign, should be parsed . other strings such as 'Level-2 (2):' should not be parsed.

I have tried

```<code>translator = str.maketrans(dict.fromkeys('(),'))
['-'+(x.translate(translator)) for x in list1]
</code>```

but the output is (every element has a - appended)

```<code>['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']
</code>```

Body:
How can i Parse parenthesized numbers in a list of strings  to negative numbers (or strings with negative sign).

example

input
list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']

output
['abcd',-1234,'Level-2 (2):','-31%', 'others','-3102.2%']

strings only with numbers inside parenthesis or numbers with comma/dot inside parenthesis followed by a percentage(%) sign, should be parsed . other strings such as 'Level-2 (2):' should not be parsed.

I have tried

translator = str.maketrans(dict.fromkeys('(),'))
['-'+(x.translate(translator)) for x in list1]

but the output is (every element has a - appended)

['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']

Body:
Try using re.match

Ex:

import re

list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(31.2)%']
result = []
for i in list1:
    m = re.match(r"\((\d+[.,]?\d*)\)(%?)", i)
    if m:
        result.append("-" + m.group(1)+m.group(2))
    else:
        result.append(i)
print(result)

Output:

['abcd', '-1,234', 'Level-2 (2):', '-31%', 'others', '-31.2%']

Update as per comment

import re

list1 = ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']
result = []
for i in list1:
    m = re.match(r"\((\d+(?:,\d+)*(?:\.\d+)?)\)(%?)", i)
    if m:
        result.append("-" + m.group(1).replace(",", "")+m.group(2))
    else:
        result.append(i)
print(result)

Output:

['abcd', '-1234', 'Level-2 (2):', '-31%', 'others', '-3102.2%']


问:
Numpy Zero Padding to match a certain shape
I have a file with arrays or different shapes. I want to zeropad all the array to match the largest shape. The largest shape is (93,13).

To test this I have the following code:

```<code>testarray = np.ones((41,13))
</code>```

how can I zero pad this array to match the shape of (93,13)? And ultimately, how can I do it for thousands of rows?

Edit: The solution was found in the comments:

```<code>for index, array in enumerate(mfcc):
    testarray = np.zeros((93,13))
    for index,row in enumerate(array):
        for i in range(0,len(row)-1):
            testarray[index][i]= row[i]
            mfcc[index] = testarray
</code>```

答:
You could do like this. array is your original array and in this case just for testcase. Just use your own one.

```<code>import numpy as np
array  = [[None] * 10]*10
#print(array)
testarray = np.zeros((93,13))
for index,row in enumerate(array):
    for i in range(0,len(row)-1):
        testarray[index][i]= row[i]
</code>```

Body:
I have a file with arrays or different shapes. I want to zeropad all the array to match the largest shape. The largest shape is (93,13).

To test this I have the following code:

testarray = np.ones((41,13))

how can I zero pad this array to match the shape of (93,13)? And ultimately, how can I do it for thousands of rows?

Edit: The solution was found in the comments:

for index, array in enumerate(mfcc):
    testarray = np.zeros((93,13))
    for index,row in enumerate(array):
        for i in range(0,len(row)-1):
            testarray[index][i]= row[i]
            mfcc[index] = testarray

Body:
You could do like this. array is your original array and in this case just for testcase. Just use your own one.

import numpy as np
array  = [[None] * 10]*10
#print(array)
testarray = np.zeros((93,13))
for index,row in enumerate(array):
    for i in range(0,len(row)-1):
        testarray[index][i]= row[i]


问:
Convert some database data (SQL Table) to .csv format
I want to convert some database data to .csv format.
At the beginning, I create a connection with a database then create a cursor instance, send query through that cursor instance, fetch your data & close the connection.
My problem is that I can't visualize the headers of the table, I get just the content.</p>

```<code>import pyodbc
import csv

connection = pyodbc.connect("Driver={ODBC Driver 11 for SQL Server};"
                  "Server=*****;"
                  "Database=****;"
                  "uid=****;pwd=****")

 cursor = connection.cursor()
 cursor.execute("Select * from Table")
 data=cursor.fetchall()

 with open('test.csv', 'w', newline= '') as f:
a = csv.writer(f, delimiter=',')
a.writerows(data)
cursor.close()
connection.close()
</code>```

答:
use pandas for reading data from db to export into csv </p>

```<code>import pandas as pd
sql='Select * from Table'
df= pd.read_sql(sql,sql_connection)
df.to_csv('csv_filename')
</code>```

Body:
I want to convert some database data to .csv format.
At the beginning, I create a connection with a database then create a cursor instance, send query through that cursor instance, fetch your data & close the connection.
My problem is that I can't visualize the headers of the table, I get just the content.

import pyodbc
import csv

connection = pyodbc.connect("Driver={ODBC Driver 11 for SQL Server};"
                  "Server=*****;"
                  "Database=****;"
                  "uid=****;pwd=****")

 cursor = connection.cursor()
 cursor.execute("Select * from Table")
 data=cursor.fetchall()

 with open('test.csv', 'w', newline= '') as f:
a = csv.writer(f, delimiter=',')
a.writerows(data)
cursor.close()
connection.close()

Body:
use pandas for reading data from db to export into csv

import pandas as pd
sql='Select * from Table'
df= pd.read_sql(sql,sql_connection)
df.to_csv('csv_filename')


问:
Error: Can only generate one of classes or datasets
I've copied a Dataset from one csproj to another, and the new project gets the following compile warning:
"The custom tool 'MSDataSetGenerator' failed while processing the file 'Client.xsd'."

In researching this warning I discovered that if I opened a VS cmd prompt and run XSD.exe on the xsd file directly I get more info.  It says:
"Error: Can only generate one of classes or datasets."

The command line flag that fixes this is to run:
XSD /d {xsdfilename}

If I run that on the cmd line it generates the dataset code just fine.  But I can't figure out how to make Visual Studio do that.  Anyone know?

答: If you right click on the XSD file in your project there is an option "Run Custom Tool". If the Custom Tool property of the XSD is set to MSDataSetGenerator this will regenerate the class.</p>

OwnerDisplayName: dviljoen


问:
Add arbitrary lines on seaborn jointplot
I can plot the joint distribution of two variables using jointplot. However, I can't find a way to add arbitrary lines showing specific values on both dimensions.

For example, the following code works well in displaying the joint and marginal distributions

```<code>import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

sns.set(color_codes=True)

tips = sns.load_dataset("iris")
plot = sns.jointplot(x="sepal_length", y="sepal_width", data=tips,
kind="kde")
</code>```

However, I can't find a way to include specific vertical and horizontal lines at pre-specified values. For example, including

```<code>plt.plot([6, 1.5], [6, 5], color="skyblue", lw=5, linestyle='solid', label="_not in legend")
</code>```

generates a line on one of the marginals, but nothing on the jointplot. Is there a way in which I could add, for example, a vertical and horizontal lines at specific values of sepal_length and sepal_width? (say, vertical line at 6 and horizontal line at 3) And, more in general, is it possible to make these lines based on specific statistics of the data? (mean, median of the different variables).

Thanks,

答:
You can modify the main axes of a jointplot using ax_join. Through that you can use standard matplotlib.pyplot commands such as axvline and axhline:

```<code>import seaborn as sns

sns.set(color_codes=True)

tips = sns.load_dataset("iris")
plot = sns.jointplot(x="sepal_length",y="sepal_width",data=tips,kind="kde")
plot.ax_joint.axvline(x=6)
plot.ax_joint.axhline(y=3)
plot.ax_joint.set_xlim(4,8)
plot.ax_joint.set_ylim(2,4.5)
</code>```

You could in fact also plot a general line not just a constant:

```<code>plot.ax_joint.plot([4,8], [2,5], 'b-', linewidth = 2)
</code>```

For constant lines using stats you can use the pandas dataframe properties:

```<code>plot.ax_joint.axvline(x=tips.sepal_length.median(),linestyle='--')
plot.ax_joint.axhline(y=tips.sepal_width.mean(),linestyle='--')
</code>```

You could also add lines to the marginal distribution using marg_x and marg_y:

```<code>plot.ax_marg_x.axvline(x=6)
plot.ax_marg_y.axhline(y=3)
</code>```

It looks like this:

Body:
I can plot the joint distribution of two variables using jointplot. However, I can't find a way to add arbitrary lines showing specific values on both dimensions.

For example, the following code works well in displaying the joint and marginal distributions

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

sns.set(color_codes=True)

tips = sns.load_dataset("iris")
plot = sns.jointplot(x="sepal_length", y="sepal_width", data=tips,
kind="kde")

However, I can't find a way to include specific vertical and horizontal lines at pre-specified values. For example, including

plt.plot([6, 1.5], [6, 5], color="skyblue", lw=5, linestyle='solid', label="_not in legend")

generates a line on one of the marginals, but nothing on the jointplot. Is there a way in which I could add, for example, a vertical and horizontal lines at specific values of sepal_length and sepal_width? (say, vertical line at 6 and horizontal line at 3) And, more in general, is it possible to make these lines based on specific statistics of the data? (mean, median of the different variables).

Thanks,

Body:
You can modify the main axes of a jointplot using ax_join. Through that you can use standard matplotlib.pyplot commands such as axvline and axhline:

import seaborn as sns

sns.set(color_codes=True)

tips = sns.load_dataset("iris")
plot = sns.jointplot(x="sepal_length",y="sepal_width",data=tips,kind="kde")
plot.ax_joint.axvline(x=6)
plot.ax_joint.axhline(y=3)
plot.ax_joint.set_xlim(4,8)
plot.ax_joint.set_ylim(2,4.5)

You could in fact also plot a general line not just a constant:

plot.ax_joint.plot([4,8], [2,5], 'b-', linewidth = 2)

For constant lines using stats you can use the pandas dataframe properties:

plot.ax_joint.axvline(x=tips.sepal_length.median(),linestyle='--')
plot.ax_joint.axhline(y=tips.sepal_width.mean(),linestyle='--')

You could also add lines to the marginal distribution using marg_x and marg_y:

plot.ax_marg_x.axvline(x=6)
plot.ax_marg_y.axhline(y=3)

It looks like this:


问:
Avoiding the use of worksheet.activate in order to execute code
This should be easy. I would like to reduce the usage of the code worksheets("Sheet1").activate as it is cumbersome and faulty oftentimes, however all the attempts I have tried out they do not work. So far I have used the set worksheet option and with worksheet option but unless I am strictly on the worksheet sheet 1 on Excel , the code does not execute.

I have tried some of the options listed in this link but none of them worked: How to avoid using Select in Excel VBA. I am really starting to think that I need to use activate all the time.

For example, a code like:

```<code>Sub test()
Dim Cols As integer
Cols = Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count
End sub
</code>```

I would expect that this code execute even if I am not situated on Sheet1 since I have specifically defined the worksheet in which it must be executed. However, unless I am on that worksheet, the code does not work. As background information, I run most of my codes under subroutines in the modules section of VBA.

答:
See if this helps understanding what was missing:

```<code>Option Explicit
Sub test()

    'Your code:
    Cols = Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count 'Cells inside the range are not qualified

    'Corrected code:
    Cols = Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(1, 1), Worksheets("Sheet1").Cells(1, 1).End(xlToRight)).Count

    'Above code is too long right?

    'Option 1
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Cols = ws.Range(ws.Cells(1, 1), ws.Cells(1, 1).End(xlToRight)).Count

    'Option 2
    With ThisWorkbook.Sheets("Sheet1")
        .Range(.Cells(1, 1), .Cells(1, 1).End(xlToRight)).Count
    End With

    'Changing your code works with any option:
    With ThisWorkbook.Sheets("Sheet1")
        .Cells(1, .Columns.Count).End(xlToLeft).Column 'This option goes from right to left to find the last column with data
    End With

End Sub
</code>```

Also, always qualify worksheets and workbooks might seem that with the worksheet is enough, but if you work with more than 1 workbook not qualifying it will be a problem too.

Body:
This should be easy. I would like to reduce the usage of the code worksheets("Sheet1").activate as it is cumbersome and faulty oftentimes, however all the attempts I have tried out they do not work. So far I have used the set worksheet option and with worksheet option but unless I am strictly on the worksheet sheet 1 on Excel , the code does not execute.

I have tried some of the options listed in this link but none of them worked: How to avoid using Select in Excel VBA. I am really starting to think that I need to use activate all the time.

For example, a code like:

Sub test()
Dim Cols As integer
Cols = Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count
End sub

I would expect that this code execute even if I am not situated on Sheet1 since I have specifically defined the worksheet in which it must be executed. However, unless I am on that worksheet, the code does not work. As background information, I run most of my codes under subroutines in the modules section of VBA.

Body:
See if this helps understanding what was missing:

Option Explicit
Sub test()

    'Your code:
    Cols = Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count 'Cells inside the range are not qualified

    'Corrected code:
    Cols = Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(1, 1), Worksheets("Sheet1").Cells(1, 1).End(xlToRight)).Count

    'Above code is too long right?

    'Option 1
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Cols = ws.Range(ws.Cells(1, 1), ws.Cells(1, 1).End(xlToRight)).Count

    'Option 2
    With ThisWorkbook.Sheets("Sheet1")
        .Range(.Cells(1, 1), .Cells(1, 1).End(xlToRight)).Count
    End With

    'Changing your code works with any option:
    With ThisWorkbook.Sheets("Sheet1")
        .Cells(1, .Columns.Count).End(xlToLeft).Column 'This option goes from right to left to find the last column with data
    End With

End Sub

Also, always qualify worksheets and workbooks might seem that with the worksheet is enough, but if you work with more than 1 workbook not qualifying it will be a problem too.


答:
You're quite close to doing it right.

You need to remember to refer to a WB and WS for each range object. Otherwise, VBA will refer to the active WB and WS

In Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count I count two Cells range objects that need referencing.

Additionally, your workbook is not specified for the sheet you're referring to. If there is no sheet named "Sheet1" in the active workbook, you will get a Subscript out of Range error.

To prevent such errors, it is good practice to use a With...End With statement. That way you will only have to specify the workbook and -sheet first, preventing cluttered code.

So, it would be:

```<code>With Workbooks(REF).Sheets("Sheet1")
    .Range(.Cells(1, 1), .Cells(1, 1).End(xlToRight)).Count
End With
</code>```

Title: Avoiding the use of worksheet.activate in order to execute code

Body:
You're quite close to doing it right.

You need to remember to refer to a WB and WS for each range object. Otherwise, VBA will refer to the active WB and WS

In Worksheets("Sheet1").Range(Cells(1, 1), Cells(1, 1).End(xlToRight)).Count I count two Cells range objects that need referencing.

Additionally, your workbook is not specified for the sheet you're referring to. If there is no sheet named "Sheet1" in the active workbook, you will get a Subscript out of Range error.

To prevent such errors, it is good practice to use a With...End With statement. That way you will only have to specify the workbook and -sheet first, preventing cluttered code.

So, it would be:

With Workbooks(REF).Sheets("Sheet1")
    .Range(.Cells(1, 1), .Cells(1, 1).End(xlToRight)).Count
End With


问:
Concatenate with broadcast
Consider the following arrays:

```<code>a = np.array([0,1])[:,None]
b = np.array([1,2,3])

print(a)
array([[0],
       [1]])

print(b)
b = np.array([1,2,3])
</code>```

Is there a simple way to concatenate these two arrays in a way that the latter is broadcast, in order to obtain the following?

```<code>array([[0, 1, 2, 3],
       [1, 1, 2, 3]])
</code>```

I've seen there is this closed issue with a related question. An alternative is proposed involving np.broadcast_arrays, however I cannot manage to adapt it to my example. Is there some way to do this, excluding the np.tile/np.concatenate solution?

答:
You can do it in the following way

import numpy as np
a = np.array([0,1])[:,None]
b = np.array([1,2,3])
b_new = np.broadcast_to(b,(a.shape[0],b.shape[0]))
c = np.concatenate((a,b_new),axis=1)
print(c)
```

Title: Concatenate with broadcast

Body:
Consider the following arrays:

a = np.array([0,1])[:,None]
b = np.array([1,2,3])

print(a)
array([[0],
       [1]])

print(b)
b = np.array([1,2,3])

Is there a simple way to concatenate these two arrays in a way that the latter is broadcast, in order to obtain the following?

array([[0, 1, 2, 3],
       [1, 1, 2, 3]])

I've seen there is this closed issue with a related question. An alternative is proposed involving np.broadcast_arrays, however I cannot manage to adapt it to my example. Is there some way to do this, excluding the np.tile/np.concatenate solution?


问:
Atomic write and tell for files in O_APPEND mode on linux
I am dealing with a situation where I want to save state persistently for an application that has many processes and many threads within those processes. Normally this would require a heavy use of locking to ensure
that there are no conflicts.

I wish to avoid this by saving the data into a file with the O_APPEND mode.  This way as long as I ensure that the data is <4KiB writes to the file will be atomic.  If I make use of append only data structures then I have a lock free solution.

However in order for this to work I need to know the location of the data within the file after I have written to that file. The problem that I am running into is that I am unable to find a system call that writes into
a file and then tells me the offset within that file that was written to.

I can use a write followed by a seek to discover this location.  However
this is not safe if another thread is sharing the same file descriptor so would require me to protect the write with a mutex which goes against my efforts to avoid locks.

Examining the man pages for write, writev, pwrite and prwritev has not shown anything that would carry out a write and then tell me the offset after the write as a single systems call and I'm fully aware that there may not be. Have I over looked something?

答:
If I make use of append only data structures then I have a lock free solution.

When code invokes write for a regular file, the first thing the kernel does is acquire the file read-write semaphore. All your writing threads serialize on that semaphore in the kernel.

See vfs_write, it calls file_start_write which eventually acquires the semaphore.


问:
[HTTP]how to change "www.example.com" to "localhost:3000"
hi I'm create test use cucumber in my rails apps. in my step scenario I used http basic authenticate, so far it pass the basic authenticate, but when I wanna to call method on controller and post some params, I had problem :

first I use this code in step but failed not cross to method on controller :

```<code>post some_admin_url, @params
</code>```

second I used this code, and failed also, the error is when running the URI.parse redirect to "www.example.com" I want to go "localhost:3000/admin", so I can match the data :

```<code>Net::HTTP.post_form(URI.parse(some_admin_url), {'from' => '2005-01-01','to' => '2005-03-31'}) { |i|  }
</code>```

FUTURE :

@selenium

  Scenario: Admin want to activate user

    Given one user logged in as admin

    And admin page

STEPS :

Given /^one user logged in as admin$/ do

    create_user_admin

    visit '/user_sessions/new'

    fill_in 'user_session[login]', :with=>'siadmin'

    fill_in 'user_session[password]', :with=>'12345'

    click_button 'Anmelden'

  end

Given /^admin page$/ do

    require "net/http"

    require "uri"

```<code>uri = URI.parse(user_action_admin_users_url)<br/>
http = Net::HTTP.new(uri.host, uri.port)<br/>
request = Net::HTTP::Get.new(uri.request_uri)<br/>
request.basic_auth("username", "password")<br/>
response = http.request(request)<br/>
</code>```

end

```<code>enter code here
</code>```

HELP !!!

THANKS

答:
fl00r's answer probably works, but wouldn't catch redirects.
If you want to catch redirects you have to change this in a higher level. For some test frameworks there is a way to set the default host.

Using Capybara we did that:

Capybara.default_host = "subdomain.yourapp.local"

Now we actually use a Rack middleware (in test env only :), that changes changes the env[HTTP_HOST] transparently for the application, so we don't have to care about which testframework / browser driver we use.

What framework do you use?

Body:
hi I'm create test use cucumber in my rails apps. in my step scenario I used http basic authenticate, so far it pass the basic authenticate, but when I wanna to call method on controller and post some params, I had problem :

first I use this code in step but failed not cross to method on controller :

post some_admin_url, @params

second I used this code, and failed also, the error is when running the URI.parse redirect to "www.example.com" I want to go "localhost:3000/admin", so I can match the data :

Net::HTTP.post_form(URI.parse(some_admin_url), {'from' => '2005-01-01','to' => '2005-03-31'}) { |i|  }

FUTURE :

@selenium

  Scenario: Admin want to activate user

    Given one user logged in as admin

    And admin page

STEPS :

Given /^one user logged in as admin$/ do

    create_user_admin

    visit '/user_sessions/new'

    fill_in 'user_session[login]', :with=>'siadmin'

    fill_in 'user_session[password]', :with=>'12345'

    click_button 'Anmelden'

  end

Given /^admin page$/ do

    require "net/http"

    require "uri"

uri = URI.parse(user_action_admin_users_url)

http = Net::HTTP.new(uri.host, uri.port)

request = Net::HTTP::Get.new(uri.request_uri)

request.basic_auth("username", "password")

response = http.request(request)

end

enter code here

HELP !!!

THANKS


问:
Disabled input works wrong in Firefox
I have an input which sets to disabled when some condtition implements.
For example i have input with default value 20.

<input type='number' id='main' value='20'>

And i have added to oninput event folowing code:

```<code>var input=document.getElementById('main');
input.oninput=function(){
  if(input.value>20){
  input.disabled=true;
  }
}
</code>```

Totally when you mousedown on increase button,the value will increment before you mouseup.

In Chrome the value stops at 21 as expected.

Try here:https://jsfiddle.net/u0obL5h2/3/

答: Change your function to listen to onChange rather than onInput

Title: Disabled input works wrong in Firefox

Body:
I have an input which sets to disabled when some condtition implements.
For example i have input with default value 20.

<input type='number' id='main' value='20'>

And i have added to oninput event folowing code:

var input=document.getElementById('main');
input.oninput=function(){
  if(input.value>20){
  input.disabled=true;
  }
}

Totally when you mousedown on increase button,the value will increment before you mouseup.

In Chrome the value stops at 21 as expected.

Try here:https://jsfiddle.net/u0obL5h2/3/


问:
ADMIN-DUPLICATECONFIGITEM: data base resource “hrhub-content” already content database “element- attribute-range-index
I am trying to create a script to add element- attribute-range-index and element –range-index from a config  file . please find below the script for the same.
I am able to add  element-range-index but not able to add element- attribute-range-index  via the script or through the admin console UI also .

Note: I have cross-checked and there is no duplicate index available for this . I have freshly created .Still facing the same issue.

```<code>import module namespace admin :="http://marklogic.com/xdmp/admin"
                                 at "/MarkLogic/admin.xqy"

let $dbid   := xdmp:database("hrhub-content")
let $config :=admin:get-configuration()
let $rangespec:= admin:database-range-element-attribute-index("string","www.aetna.com/hrhub/nm","plocalname","","pname","",fn:false())

return
 let $new-index  := admin:database-add-range-element-attribute-index($config,$dbid,$rangespec)
return admin:save-configuration-without-restart($new-index)
</code>```

Error message: ADMIN-DUPLICATECONFIGITEM: (ERR:FOER0000) data base
  resource “hrhub-content” already content database “element-
  attribute-range-index”

答:
Your script contains some syntax errors. I have tried with the below and it worked for me:

```<code>import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";

let $dbid   := xdmp:database("hrhub-content")
let $config := admin:get-configuration()
let $rangespec:= admin:database-range-element-attribute-index("string", "www.aetna.com/hrhub/nm", "plocalname", "", "pname", "http://marklogic.com/collation/", fn:false())

return
 let $new-index := admin:database-add-range-element-attribute-index($config,$dbid,$rangespec)
 return admin:save-configuration-without-restart($new-index)
</code>```

Things I have changed:

import changed := to only =.

import needs a ; at the end.

admin:database-range-element-attribute-index needs a collation if scalar-type is "string".

Body:
I am trying to create a script to add element- attribute-range-index and element –range-index from a config  file . please find below the script for the same.
I am able to add  element-range-index but not able to add element- attribute-range-index  via the script or through the admin console UI also .

Note: I have cross-checked and there is no duplicate index available for this . I have freshly created .Still facing the same issue.

import module namespace admin :="http://marklogic.com/xdmp/admin"
                                 at "/MarkLogic/admin.xqy"

let $dbid   := xdmp:database("hrhub-content")
let $config :=admin:get-configuration()
let $rangespec:= admin:database-range-element-attribute-index("string","www.aetna.com/hrhub/nm","plocalname","","pname","",fn:false())

return
 let $new-index  := admin:database-add-range-element-attribute-index($config,$dbid,$rangespec)
return admin:save-configuration-without-restart($new-index)

Error message: ADMIN-DUPLICATECONFIGITEM: (ERR:FOER0000) data base
  resource “hrhub-content” already content database “element-
  attribute-range-index”

Body:
Your script contains some syntax errors. I have tried with the below and it worked for me:

import module namespace admin = "http://marklogic.com/xdmp/admin" at "/MarkLogic/admin.xqy";

let $dbid   := xdmp:database("hrhub-content")
let $config := admin:get-configuration()
let $rangespec:= admin:database-range-element-attribute-index("string", "www.aetna.com/hrhub/nm", "plocalname", "", "pname", "http://marklogic.com/collation/", fn:false())

return
 let $new-index := admin:database-add-range-element-attribute-index($config,$dbid,$rangespec)
 return admin:save-configuration-without-restart($new-index)

Things I have changed:

import changed := to only =.

import needs a ; at the end.

admin:database-range-element-attribute-index needs a collation if scalar-type is "string".


问:
Cannot open (GPIO) Pin 6 in Windows 10 Iot Core
I want to let the red LED of my RainbowHAT shine. That requires that I send a high signal to the BCM 6 pin.

(Shortend) Source

Class constant:

```<code>private static readonly int GPIO_NUMBER_RED = 22;
</code>```

Called in the constructor:

```<code>    var gpioController = GpioController.GetDefault();

    redPin = gpioController.OpenPin(GPIO_NUMBER_RED);
    redPin.Write(GpioPinValue.High);
    redPin.SetDriveMode(GpioPinDriveMode.Output);
</code>```

I tried the values 6 (BCM), 31 (Pin number) and 22 (Wiring pin number) for my class global constant GPIO_NUMBER_RED but I get always the error:

```<code>    WinRT information: Pin ' is not available. It is reserved by the system or in use for another function.
</code>```

Pin layout

https://pinout.xyz/pinout/rainbow_hat

Full source

GitHub

Package Info

```<code>    <Capabilities>
        <Capability Name="internetClient" />
        <DeviceCapability Name="lowLevel"/>
    </Capabilities>
</code>```

I also restarted the Pi to "reset" maybe other application that access this Pin - without success.

答:
I have downloaded the repo and view the code. I'm not sure why you need to add the Init method in the constructor in MainPageViewModel. But it is not recommended to add the singleton instance in the constructor method of the model, since the model is used to bind to view to show the data. When you reuse the GPIO pin resource, you should release and dispose it in another page. In addition, GpioPin should be disposed manually when you needn't to use. You may try to move the Init method in the constructor of RainbowHAT, like following code.

RainbowHAT.cs(Update)

```<code>    /// <summary>
    /// Private singelton instance.
    /// </summary>
    private static RainbowHAT instance;

    /// <summary>
    /// Default instance of RainbowHAT.
    /// </summary>
    public static RainbowHAT Default
    {
        get
        {
            if (instance == null)
            {
                instance = new RainbowHAT();
            }

            return instance;
        }
    }

    private RainbowHAT()
    {
        gpioController = GpioController.GetDefault();

        // Ensure that we have a valid gpio connection
        if (gpioController == null)
        {
            throw new OperationCanceledException("Operation canceled due missing GPIO controller");
        }

        Init();
    }

    public void PerformAction(RainbowHATAction action)
    {
        switch(action)
        {
            case RainbowHATAction.TurnOnRed:
                redPin.Write(GpioPinValue.High);
                break;

            case RainbowHATAction.TurnOffRed:
                redPin.Write(GpioPinValue.Low);
                break;

            case RainbowHATAction.LEDsOn:
                apa102.TurnOn();
                break;

            case RainbowHATAction.LEDsOff:
                apa102.TurnOff();
                break;

            default:
                break;
        }
    }
</code>```

MainPageViewModel.cs

```<code>    public MainPageViewModel()
    {
        // Setup timer.
        ThreadPoolTimer.CreatePeriodicTimer
            (ClockTimer_Tick,
            TimeSpan.FromSeconds(1)
       );

        // Setup callback
        rainbowHAT.CaptiveButtonPressed += CaptiveButtonPressed;
    }
</code>```

Body:
I want to let the red LED of my RainbowHAT shine. That requires that I send a high signal to the BCM 6 pin.

(Shortend) Source

Class constant:

private static readonly int GPIO_NUMBER_RED = 22;

Called in the constructor:

    var gpioController = GpioController.GetDefault();

    redPin = gpioController.OpenPin(GPIO_NUMBER_RED);
    redPin.Write(GpioPinValue.High);
    redPin.SetDriveMode(GpioPinDriveMode.Output);

I tried the values 6 (BCM), 31 (Pin number) and 22 (Wiring pin number) for my class global constant GPIO_NUMBER_RED but I get always the error:

    WinRT information: Pin ' is not available. It is reserved by the system or in use for another function.

Pin layout

https://pinout.xyz/pinout/rainbow_hat

Full source

GitHub

Package Info

    <Capabilities>
        <Capability Name="internetClient" />
        <DeviceCapability Name="lowLevel"/>
    </Capabilities>

I also restarted the Pi to "reset" maybe other application that access this Pin - without success.

Body:
I have downloaded the repo and view the code. I'm not sure why you need to add the Init method in the constructor in MainPageViewModel. But it is not recommended to add the singleton instance in the constructor method of the model, since the model is used to bind to view to show the data. When you reuse the GPIO pin resource, you should release and dispose it in another page. In addition, GpioPin should be disposed manually when you needn't to use. You may try to move the Init method in the constructor of RainbowHAT, like following code.

RainbowHAT.cs(Update)

    /// <summary>
    /// Private singelton instance.
    /// </summary>
    private static RainbowHAT instance;

    /// <summary>
    /// Default instance of RainbowHAT.
    /// </summary>
    public static RainbowHAT Default
    {
        get
        {
            if (instance == null)
            {
                instance = new RainbowHAT();
            }

            return instance;
        }
    }

    private RainbowHAT()
    {
        gpioController = GpioController.GetDefault();

        // Ensure that we have a valid gpio connection
        if (gpioController == null)
        {
            throw new OperationCanceledException("Operation canceled due missing GPIO controller");
        }

        Init();
    }

    public void PerformAction(RainbowHATAction action)
    {
        switch(action)
        {
            case RainbowHATAction.TurnOnRed:
                redPin.Write(GpioPinValue.High);
                break;

            case RainbowHATAction.TurnOffRed:
                redPin.Write(GpioPinValue.Low);
                break;

            case RainbowHATAction.LEDsOn:
                apa102.TurnOn();
                break;

            case RainbowHATAction.LEDsOff:
                apa102.TurnOff();
                break;

            default:
                break;
        }
    }

MainPageViewModel.cs

    public MainPageViewModel()
    {
        // Setup timer.
        ThreadPoolTimer.CreatePeriodicTimer
            (ClockTimer_Tick,
            TimeSpan.FromSeconds(1)
       );

        // Setup callback
        rainbowHAT.CaptiveButtonPressed += CaptiveButtonPressed;
    }


问:
The default for KeyValuePair
I have an object of the type IEnumerable<KeyValuePair<T,U>> keyValueList, I am using

```<code> var getResult= keyValueList.SingleOrDefault();
 if(getResult==/*default */)
 {
 }
 else
 {
 }
</code>```

How can I check whether getResult is the default, in case I can't find the correct element?

I can't check whether it is null or not, because KeyValuePair is a struct.

答:
You can create a general (and generic) extension method, like this one:

```<code>public static class Extensions
{
    public static bool IsDefault<T>(this T value) where T : struct
    {
        bool isDefault = value.Equals(default(T));

        return isDefault;
    }
}
</code>```

Usage:

```<code>// We have to set explicit default value '0' to avoid build error:
// Use of unassigned local variable 'intValue'
int intValue = 0;
long longValue = 12;
KeyValuePair<String, int> kvp1 = new KeyValuePair<String, int>("string", 11);
KeyValuePair<String, int> kvp2 = new KeyValuePair<String, int>();
List<KeyValuePair<String, int>> kvps = new List<KeyValuePair<String, int>> { kvp1, kvp2 };
KeyValuePair<String, int> kvp3 = kvps.FirstOrDefault(kvp => kvp.Value == 11);
KeyValuePair<String, int> kvp4 = kvps.FirstOrDefault(kvp => kvp.Value == 15);

Console.WriteLine(intValue.IsDefault()); // results 'True'
Console.WriteLine(longValue.IsDefault()); // results 'False'
Console.WriteLine(kvp1.IsDefault()); // results 'False'
Console.WriteLine(kvp2.IsDefault()); // results 'True'
Console.WriteLine(kvp3.IsDefault()); // results 'False'
Console.WriteLine(kvp4.IsDefault()); // results 'True'
</code>```

Title: The default for KeyValuePair

Body:
I have an object of the type IEnumerable<KeyValuePair<T,U>> keyValueList, I am using

 var getResult= keyValueList.SingleOrDefault();
 if(getResult==/*default */)
 {
 }
 else
 {
 }

How can I check whether getResult is the default, in case I can't find the correct element?

I can't check whether it is null or not, because KeyValuePair is a struct.

Body:
You can create a general (and generic) extension method, like this one:

public static class Extensions
{
    public static bool IsDefault<T>(this T value) where T : struct
    {
        bool isDefault = value.Equals(default(T));

        return isDefault;
    }
}

Usage:

// We have to set explicit default value '0' to avoid build error:
// Use of unassigned local variable 'intValue'
int intValue = 0;
long longValue = 12;
KeyValuePair<String, int> kvp1 = new KeyValuePair<String, int>("string", 11);
KeyValuePair<String, int> kvp2 = new KeyValuePair<String, int>();
List<KeyValuePair<String, int>> kvps = new List<KeyValuePair<String, int>> { kvp1, kvp2 };
KeyValuePair<String, int> kvp3 = kvps.FirstOrDefault(kvp => kvp.Value == 11);
KeyValuePair<String, int> kvp4 = kvps.FirstOrDefault(kvp => kvp.Value == 15);

Console.WriteLine(intValue.IsDefault()); // results 'True'
Console.WriteLine(longValue.IsDefault()); // results 'False'
Console.WriteLine(kvp1.IsDefault()); // results 'False'
Console.WriteLine(kvp2.IsDefault()); // results 'True'
Console.WriteLine(kvp3.IsDefault()); // results 'False'
Console.WriteLine(kvp4.IsDefault()); // results 'True'