问:
Interpolate list of colors loop
I've got a list of colors and I'd like to have a method that given a list of colors it can linearly interpolate across them with an evenly distributed stops per color, so for example if there's four colors: color one to two would interpolate from 0-0.25, color two to three from 0.25-0.5 and so on.

In my rudimentary example I'm currently using an approximation of the value of the sine to trigger the next color in the array but as can be expected the index gets called more than once, causing it to skip colors. Furthermore I can't find the formula that allows me to spread the colors values evenly so I can transition them all at once from the normalized value of the cycle.

I know CSS can easily transition colors and there's libraries that can do similar things but I'd like to know the math to do this and implement in Javascript using Canvas API without any third party libraries.

const rgbColors = [
  [255, 0, 0],
  [0, 255, 0],
  [255, 0, 0],
  [0, 255, 255]
];
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

const lerp = (x, y, a) => x * (1 - a) + y * a;
let start = performance.now();
let currentIndex = 0;

function getColorLERP(colorA, colorB, progress) {
  const r = Math.round(lerp(colorA[0], colorB[0], progress) * 10) / 10;
  const g = Math.round(lerp(colorA[1], colorB[1], progress) * 10) / 10;
  const b = Math.round(lerp(colorA[2], colorB[2], progress) * 10) / 10;
  return [r, g, b];
}

const loop = (now) => {
  window.requestAnimationFrame(loop);
  const delta = Math.round(now - start);
  const yoyoRate = delta * 0.0005;
  const yoyo = Math.abs(Math.sin(yoyoRate));
  const [r, g, b] = getColorLERP(
    rgbColors[currentIndex],
    rgbColors[(currentIndex + 1) % rgbColors.length],
    yoyo
  );
  ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;

  ctx.fillRect(0, 0, 200, 200);
  ctx.fillStyle = "#000";

  if (yoyo > 0.9999) {
    currentIndex++;
    if (currentIndex > rgbColors.length - 1) {
      currentIndex = 0;
    }
  }
};

loop();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas width=200 height=200></canvas></code>```

答:
I'd just use CSS to do the math for me. You didn't mention any restrictions on technologies...

const colors = ['red', 'green', 'red', 'cyan'];
let colorIndex = 0;
setInterval(() => {
  document.querySelector('.box').classList.remove(colors[colorIndex++ % 4]);
  document.querySelector('.box').classList.add(colors[colorIndex % 4]);
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
  background-color: rgb(255,0,0);
}

.green {
  background-color: rgb(0,255,0);
}

.cyan {
  background-color: rgb(0,255,255);
}

.box {
  transition: background-color 1000ms linear;
  width: 200px;
  height: 200px;
}</code>```

```

Title: Interpolate list of colors loop

Body:
I've got a list of colors and I'd like to have a method that given a list of colors it can linearly interpolate across them with an evenly distributed stops per color, so for example if there's four colors: color one to two would interpolate from 0-0.25, color two to three from 0.25-0.5 and so on.

In my rudimentary example I'm currently using an approximation of the value of the sine to trigger the next color in the array but as can be expected the index gets called more than once, causing it to skip colors. Furthermore I can't find the formula that allows me to spread the colors values evenly so I can transition them all at once from the normalized value of the cycle.

I know CSS can easily transition colors and there's libraries that can do similar things but I'd like to know the math to do this and implement in Javascript using Canvas API without any third party libraries.

const rgbColors = [
  [255, 0, 0],
  [0, 255, 0],
  [255, 0, 0],
  [0, 255, 255]
];
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

const lerp = (x, y, a) => x * (1 - a) + y * a;
let start = performance.now();
let currentIndex = 0;

function getColorLERP(colorA, colorB, progress) {
  const r = Math.round(lerp(colorA[0], colorB[0], progress) * 10) / 10;
  const g = Math.round(lerp(colorA[1], colorB[1], progress) * 10) / 10;
  const b = Math.round(lerp(colorA[2], colorB[2], progress) * 10) / 10;
  return [r, g, b];
}

const loop = (now) => {
  window.requestAnimationFrame(loop);
  const delta = Math.round(now - start);
  const yoyoRate = delta * 0.0005;
  const yoyo = Math.abs(Math.sin(yoyoRate));
  const [r, g, b] = getColorLERP(
    rgbColors[currentIndex],
    rgbColors[(currentIndex + 1) % rgbColors.length],
    yoyo
  );
  ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;

  ctx.fillRect(0, 0, 200, 200);
  ctx.fillStyle = "#000";

  if (yoyo > 0.9999) {
    currentIndex++;
    if (currentIndex > rgbColors.length - 1) {
      currentIndex = 0;
    }
  }
};

loop();

<canvas width=200 height=200></canvas>

Body:
I'd just use CSS to do the math for me. You didn't mention any restrictions on technologies...

const colors = ['red', 'green', 'red', 'cyan'];
let colorIndex = 0;
setInterval(() => {
  document.querySelector('.box').classList.remove(colors[colorIndex++ % 4]);
  document.querySelector('.box').classList.add(colors[colorIndex % 4]);
}, 1000);

.red {
  background-color: rgb(255,0,0);
}

.green {
  background-color: rgb(0,255,0);
}

.cyan {
  background-color: rgb(0,255,255);
}

.box {
  transition: background-color 1000ms linear;
  width: 200px;
  height: 200px;
}

<div class="box red"></div>


来源: stackexchange

问:
c# equivalent for c++ vector or deque
I am almost certain this should be a duplicate but I searched for some time and could not find the answer. What should I use in C# to replace C++ vector and deque efficiently. That is I need a structure that supports direct indexing effieciently and also supports delete from one or both ends(depending on vector or deque case) again in an efficient manner.

In java I usually use ArrayList at least for vector but for C# I found this source that states:
ArrayList resizes dynamically. As elements are added, it grows in capacity to accommodate them. It is most often used in older C# programs.. So what is the new way to do this? And again what do I do for the deque case?

答:
For me, these simple extension methods were enough.</p>
```<code>using System.Linq;
using System.Collections.Generic;
-----
-----

        public static T consume<T>(this List<T> list, int index) {
            if (list.Count < index) return default(T);
            var item = list[index];
            list.RemoveAt(index);
            return item;
        }
        public static T pop<T>(this List<T> list) {
            return list.consume(list.Count - 1);
        }
        public static T dequeue<T>(this List<T> list) {
            return list.consume(0);
        }
        public static void push<T>(this List<T> list, T item) {
            list.Add(item);
        }
        public static void enqueue<T>(this List<T> list, T item) {
            list.Add(item);
        }
</code>```

ContentLicense: CC BY-SA 3.0

Title: c# equivalent for c++ vector or deque

Body:
For me, these simple extension methods were enough.

using System.Linq;
using System.Collections.Generic;
-----
-----

        public static T consume<T>(this List<T> list, int index) {
            if (list.Count < index) return default(T);
            var item = list[index];
            list.RemoveAt(index);
            return item;
        }
        public static T pop<T>(this List<T> list) {
            return list.consume(list.Count - 1);
        }
        public static T dequeue<T>(this List<T> list) {
            return list.consume(0);
        }
        public static void push<T>(this List<T> list, T item) {
            list.Add(item);
        }
        public static void enqueue<T>(this List<T> list, T item) {
            list.Add(item);
        }

ContentLicense: CC BY-SA 4.0


问:
Splitting latlong into lat and long
I'm trying to remove the square brackets from a list of latlongs called latlng, which is held in a dataframe (df) in the format as per example below:

```<code>        latlng
[-1.4253128, 52.9015902]
</code>```

I've got this but it returns NaN:

```<code>df['latitude'] = df['latlng'].str.replace('[','')
</code>```

and produces this warning:

```<code><ipython-input-59-34b588ef7f4b>:1: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will*not* be treated as literal strings when regex=True.
  df['latitude'] = df['latlng'].str.replace('[','')
</code>```

It seems that if I write the file to a csv and then use that file, the above works. But ideally, I want it all in once script.
Any help is appreciated!

答:
I think you meant to write df['latitude'] = str(df['latlng']).replace('[','').

Yet, this only removes the opening bracket and will not return long or lat alone.

You might want to use regex to split the string, something on the lines such as

```<code>import re

splitted = re.match("\[(-?\d+\.\d+),\s*(-?\d+\.\d+)\]", "[-1.4253128, 52.9015902]")
print(splitted[1])
print(splitted[2])
</code>```

Title: Splitting latlong into lat and long

Body:
I'm trying to remove the square brackets from a list of latlongs called latlng, which is held in a dataframe (df) in the format as per example below:

        latlng
[-1.4253128, 52.9015902]

I've got this but it returns NaN:

df['latitude'] = df['latlng'].str.replace('[','')

and produces this warning:

<ipython-input-59-34b588ef7f4b>:1: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will*not* be treated as literal strings when regex=True.
  df['latitude'] = df['latlng'].str.replace('[','')

It seems that if I write the file to a csv and then use that file, the above works. But ideally, I want it all in once script.
Any help is appreciated!

Body:
I think you meant to write df['latitude'] = str(df['latlng']).replace('[','').

Yet, this only removes the opening bracket and will not return long or lat alone.

You might want to use regex to split the string, something on the lines such as

import re

splitted = re.match("\[(-?\d+\.\d+),\s*(-?\d+\.\d+)\]", "[-1.4253128, 52.9015902]")
print(splitted[1])
print(splitted[2])


问:
why the bar chart code doesn't work?
the database is right:

```<code>DATABASE `poll`; TABLE `results`  CREATE TABLE `results` (
   book_type VARCHAR(50),
   num_votes INT
);

INSERT INTO `results` values
    ('Classic', 15),
    ('Fantasy', 7),
    ('Humor', 32),
    ('Mystery', 12),
    ('Poetry', 25);
</code>```

the code

```<code><?php
    $dbhandle = mysql_connect("localhost","root","123") or die("unable to connect to mysql");

    $selected = mysql_select_db("poll",$dbhandle);

    $result = mysql_query("SELECT * FROM results");

    $num_poller = mysql_num_rows($result);

    $total_votes = 0;
    while($row = mysql_fetch_array($result)){
        $total_votes += $row{'num_votes'};

    }

    mysql_data_seek($result,0);
    mysql_close($dbhandle);

    putenv('GDFONTPATH=C:\WINDOWS\Fonts');
    $font = 'arial';
    $y = 50;
    $width =700;
    $bar_height =20;
    $height = $num_poller * $bar_height *1.5 + 70;
    $bar_unit = ($width - 400)/100;

    $image = imagecreate($width,$height);

    $white = imagecolorallocate($image,255,255,255);
    $black = imagecolorallocate($image,0,0,0);
    $red = imagecolorallocate($image,255,0,0);
    $blue = imagecolorallocate($image,0,0,255);

    imagefill($image,$width,$height,$white);

    imagerectangle($image,0,0,$width-1,$height-1,$black);

    imagettftext($image,16,0,$width/3+50,$y-20,$black,$font,'poll results');

    while($row = mysql_fetch_object($result)){
        if($total_votes > 0){
            $percent = intval(round(($row->num_votes/$total_votes)*100));

        }else{
            $percent =0;

    }

    imagettftext($image,12,0,10, $y+($bar_height/2), $black, $font, $row->book_type);
    //Output percentage for a particular value
    imagettftext($image, 12, 0, 170, $y + ($bar_height/2),$red,$font,$percent.'%');

    $bar_length = $percent * $bar_unit;

    //Draw a shape that corresponds to 100%
    imagerectangle($image, $bar_length+221, $y-2, (220+(100*$bar_unit)), $y+$bar_height, $black);
    //Output a bar for a particular value
    imagefilledrectangle($image,220,$y-2,220+$bar_length, $y+$bar_height, $blue);
    //Output the number of votes
    imagettftext($image, 12, 0, 250+100*$bar_unit, $y+($bar_height/2), $black, $font, $row->num_votes.' votes cast.');

    $y = $y + ($bar_height * 1.5);

    }

    header("Content-Type: image/jpeg");

    imagejpeg($image);

    imagedestroy($image);
</code>```

it shows an error: the image...cannot be displayed because it contains errors?. what's wrong with the code? thank you.

答:
To get to the actual error you seem to be running into you want to turn on error_reporting like @Wesley suggested in the comment. error_reporintg(-1); and then ether look into your php.error-log or remove the header("Content-Type: image/jpeg"); so you get the error in your browser if you have turned display_errors on.

Usually you get an "malformed" error because the response looks like this:

```<code>Warning: Some error.....
ZWW$%$%BINARY-IMAGE-STUFF
</code>```

and your browser can't get a proper jpeg header from that output.

Title: why the bar chart code doesn't work?

Body:
the database is right:

DATABASE `poll`; TABLE `results`  CREATE TABLE `results` (
   book_type VARCHAR(50),
   num_votes INT
);

INSERT INTO `results` values
    ('Classic', 15),
    ('Fantasy', 7),
    ('Humor', 32),
    ('Mystery', 12),
    ('Poetry', 25);

the code

<?php
    $dbhandle = mysql_connect("localhost","root","123") or die("unable to connect to mysql");

    $selected = mysql_select_db("poll",$dbhandle);

    $result = mysql_query("SELECT * FROM results");

    $num_poller = mysql_num_rows($result);

    $total_votes = 0;
    while($row = mysql_fetch_array($result)){
        $total_votes += $row{'num_votes'};

    }

    mysql_data_seek($result,0);
    mysql_close($dbhandle);

    putenv('GDFONTPATH=C:\WINDOWS\Fonts');
    $font = 'arial';
    $y = 50;
    $width =700;
    $bar_height =20;
    $height = $num_poller * $bar_height *1.5 + 70;
    $bar_unit = ($width - 400)/100;

    $image = imagecreate($width,$height);

    $white = imagecolorallocate($image,255,255,255);
    $black = imagecolorallocate($image,0,0,0);
    $red = imagecolorallocate($image,255,0,0);
    $blue = imagecolorallocate($image,0,0,255);

    imagefill($image,$width,$height,$white);

    imagerectangle($image,0,0,$width-1,$height-1,$black);

    imagettftext($image,16,0,$width/3+50,$y-20,$black,$font,'poll results');

    while($row = mysql_fetch_object($result)){
        if($total_votes > 0){
            $percent = intval(round(($row->num_votes/$total_votes)*100));

        }else{
            $percent =0;

    }

    imagettftext($image,12,0,10, $y+($bar_height/2), $black, $font, $row->book_type);
    //Output percentage for a particular value
    imagettftext($image, 12, 0, 170, $y + ($bar_height/2),$red,$font,$percent.'%');

    $bar_length = $percent * $bar_unit;

    //Draw a shape that corresponds to 100%
    imagerectangle($image, $bar_length+221, $y-2, (220+(100*$bar_unit)), $y+$bar_height, $black);
    //Output a bar for a particular value
    imagefilledrectangle($image,220,$y-2,220+$bar_length, $y+$bar_height, $blue);
    //Output the number of votes
    imagettftext($image, 12, 0, 250+100*$bar_unit, $y+($bar_height/2), $black, $font, $row->num_votes.' votes cast.');

    $y = $y + ($bar_height * 1.5);

    }

    header("Content-Type: image/jpeg");

    imagejpeg($image);

    imagedestroy($image);

it shows an error: the image...cannot be displayed because it contains errors?. what's wrong with the code? thank you.

Body:
To get to the actual error you seem to be running into you want to turn on error_reporting like @Wesley suggested in the comment. error_reporintg(-1); and then ether look into your php.error-log or remove the header("Content-Type: image/jpeg"); so you get the error in your browser if you have turned display_errors on.

Usually you get an "malformed" error because the response looks like this:

Warning: Some error.....
ZWW$%$%BINARY-IMAGE-STUFF

and your browser can't get a proper jpeg header from that output.


问:
TigerGraph Data Load using HEADER and INPUT_LINE_FILTER
I am trying to create a TigerGraph loading job to use column names from the header line instead of positional parameters like $1, $2 etc. In order to use files external to TigerGraph server, I believe we need to specify the HEADER and INPUT_LINE_FILTER and use them in the loading job. However, I am unable to find any examples in TigerGraph documentation. My attempt below is now working.

Any help is appreciated.

```<code>result = conn.gsql('''
USE GRAPH MyGraphCopy

BEGIN
CREATE LOADING JOB load_persons_byname FOR GRAPH MyGraphCopy {
      DEFINE FILENAME MyDataSource;
      DEFINE HEADER MyHeader = "id","name","email","username","created_at","v_id";
      DEFINE INPUT_LINE_FILTER reject_header = ( "created_at " = "created_at");
      LOAD MyDataSource TO VERTEX Person VALUES($"v_id", $"name", $"email", $"username", $"created_at") USING SEPARATOR=",", HEADER="true", USER_DEFINED_HEADER=MyHeader, REJECT_LINE_RULE=reject_header, EOL="\n", QUOTE="double";
    }
END
''')
</code>```

答:
This is how I was able to get it to work.</p>
```<code>USE GRAPH MyGraph

BEGIN
CREATE LOADING JOB load_persons_byname FOR GRAPH MyGraphCopy {
      DEFINE FILENAME MyDataSource;
      DEFINE HEADER MyHeader = "id","name","email","username","created_at","v_id";
      DEFINE INPUT_LINE_FILTER reject_header = ( $4 == "created_at");
      LOAD MyDataSource TO VERTEX Person VALUES($"v_id", $"name", $"email", $"username", $"created_at") USING SEPARATOR=",", HEADER="true", USER_DEFINED_HEADER="MyHeader", REJECT_LINE_RULE=reject_header, EOL="\n", QUOTE="double";
    }
END
</code>```

Body:
I am trying to create a TigerGraph loading job to use column names from the header line instead of positional parameters like $1, $2 etc. In order to use files external to TigerGraph server, I believe we need to specify the HEADER and INPUT_LINE_FILTER and use them in the loading job. However, I am unable to find any examples in TigerGraph documentation. My attempt below is now working.

Any help is appreciated.

result = conn.gsql('''
USE GRAPH MyGraphCopy

BEGIN
CREATE LOADING JOB load_persons_byname FOR GRAPH MyGraphCopy {
      DEFINE FILENAME MyDataSource;
      DEFINE HEADER MyHeader = "id","name","email","username","created_at","v_id";
      DEFINE INPUT_LINE_FILTER reject_header = ( "created_at " = "created_at");
      LOAD MyDataSource TO VERTEX Person VALUES($"v_id", $"name", $"email", $"username", $"created_at") USING SEPARATOR=",", HEADER="true", USER_DEFINED_HEADER=MyHeader, REJECT_LINE_RULE=reject_header, EOL="\n", QUOTE="double";
    }
END
''')

Body:
This is how I was able to get it to work.

USE GRAPH MyGraph

BEGIN
CREATE LOADING JOB load_persons_byname FOR GRAPH MyGraphCopy {
      DEFINE FILENAME MyDataSource;
      DEFINE HEADER MyHeader = "id","name","email","username","created_at","v_id";
      DEFINE INPUT_LINE_FILTER reject_header = ( $4 == "created_at");
      LOAD MyDataSource TO VERTEX Person VALUES($"v_id", $"name", $"email", $"username", $"created_at") USING SEPARATOR=",", HEADER="true", USER_DEFINED_HEADER="MyHeader", REJECT_LINE_RULE=reject_header, EOL="\n", QUOTE="double";
    }
END


问:
Filter 2d array by matching string
I have the following array below and looking to match all objects that match the string "en-GB". My current implementation results in "Cannot use 'in' operator to search for 'en' in en-GB"

Array:

```<code>const filtData = [
  [
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "es",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "dk",
        },
      },
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "sp",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "it",
        },
      },
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "en",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "uk",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
  ],
];
</code>```

JS filter:

```<code>const res = filtData.map((el) => el.filter((a) => a.descriptions.attrs.lang.some((o) => "en-GB" in o)));
console.log(filtData);
</code>```

答:
You need to compare the value.

const
    filtData = [[{ descriptions: { attrs: { lang: "en-GB" } } }, { descriptions: { attrs: { lang: "es" } } }, { descriptions: { attrs: { lang: "dk" } } }], [ { descriptions: { attrs: { lang: "sp" } } }, { descriptions: { attrs: { lang: "en-GB" } } }, { descriptions: { attrs: { lang: "it" } } }], [{ descriptions: { attrs: { lang: "en" } } }, { descriptions: { attrs: { lang: "uk" } } }, { descriptions: { attrs: { lang: "en-GB" } } }]],
    result = filtData.map(a =>
        a.filter(({ descriptions: { attrs: { lang } } }) => lang === "en-GB")
    );

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Filter 2d array by matching string

Body:
I have the following array below and looking to match all objects that match the string "en-GB". My current implementation results in "Cannot use 'in' operator to search for 'en' in en-GB"

Array:

const filtData = [
  [
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "es",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "dk",
        },
      },
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "sp",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "it",
        },
      },
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "en",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "uk",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
  ],
];

JS filter:

const res = filtData.map((el) => el.filter((a) => a.descriptions.attrs.lang.some((o) => "en-GB" in o)));
console.log(filtData);

Body:
You need to compare the value.

const
    filtData = [[{ descriptions: { attrs: { lang: "en-GB" } } }, { descriptions: { attrs: { lang: "es" } } }, { descriptions: { attrs: { lang: "dk" } } }], [ { descriptions: { attrs: { lang: "sp" } } }, { descriptions: { attrs: { lang: "en-GB" } } }, { descriptions: { attrs: { lang: "it" } } }], [{ descriptions: { attrs: { lang: "en" } } }, { descriptions: { attrs: { lang: "uk" } } }, { descriptions: { attrs: { lang: "en-GB" } } }]],
    result = filtData.map(a =>
        a.filter(({ descriptions: { attrs: { lang } } }) => lang === "en-GB")
    );

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Added non-passive event listener to a scroll-blocking 'touchmove' event. Consider marking event handler as 'passive' to make the page more responsive
So I've come across an issue on one of the sites that I've had for a while and out of the blue, it just stopped working. I'm receiving an event handler error when clicking on the blog posts in my iScroll module.

Below, I will provide screenshots (All clickable sections on there aren't clickable all of a sudden):

Browsers:

Internet Explorer: Works OK - No problem.

Edge: Works OK - No problem.

Firefox: Works OK - No problem.

Chrome: Throws Added non-passive event listener to a scroll-blocking 'touchmove' event. error - Links unclickable.

What I'm using:

/*!
 * iScroll v4.2.5 ~ Copyright (c) 2012 Matteo Spinelli, http://cubiq.org
 * Released under MIT license, http://cubiq.org/license
 */

Problem:

Throws the Added non-passive event listener to a scroll-blocking 'touchmove' event. Consider marking event handler as 'passive' to make the page more responsive. error in console - Links unclickable.

Everything worked well prior to today, so I'm not sure what could have caused it to all of a sudden stop working. It's saying that it's throwing the error from the official minimized jQuery.js file.

This is the library that the previous developer is using: https://github.com/cubiq/iscroll

All help would be greatly appreciated!

答:
The answer comes from here: Making wheel scrolling fast by default

Breakage and Guidance :
In the vast majority of cases, no breakage will
be observed. Only in rare cases (less than 0.3% of pages according to
our metrics), unintended scrolling/zooming might happen due to the
preventDefault() call getting ignored inside the listeners that are
treated as passive by default. Your application can determine whether
it may be hitting this in the wild by checking if calling
preventDefault() had any effect via the defaultPrevented property. The
fix for the affected cases is relatively easy: pass {passive: false}
to addEventListener() to override the default behavior and preserve
the event listener as blocking.

If you are getting warnings like the ones you see you need to specify the addEventListener() calls as passive.

You can do that like this :

```<code>target.addEventListener(type, listener, {passive: true});
</code>```

If you need to stop propagation or do a call to event.preventDefault() in the listener that is fired you should specify {passive: false} instead of {passive: true}.

This is mandatory because a passive option set to true prevent any call to event.preventDefault() in the related listener.

Doing so will make those warnings disappear as long as the requiring addEventListener() calls got their passive option set.

Take note that this may not work for all browsers so some changes may be required.

Body:
The answer comes from here: Making wheel scrolling fast by default

Breakage and Guidance :
In the vast majority of cases, no breakage will
be observed. Only in rare cases (less than 0.3% of pages according to
our metrics), unintended scrolling/zooming might happen due to the
preventDefault() call getting ignored inside the listeners that are
treated as passive by default. Your application can determine whether
it may be hitting this in the wild by checking if calling
preventDefault() had any effect via the defaultPrevented property. The
fix for the affected cases is relatively easy: pass {passive: false}
to addEventListener() to override the default behavior and preserve
the event listener as blocking.

If you are getting warnings like the ones you see you need to specify the addEventListener() calls as passive.

You can do that like this :

target.addEventListener(type, listener, {passive: true});

If you need to stop propagation or do a call to event.preventDefault() in the listener that is fired you should specify {passive: false} instead of {passive: true}.

This is mandatory because a passive option set to true prevent any call to event.preventDefault() in the related listener.

Doing so will make those warnings disappear as long as the requiring addEventListener() calls got their passive option set.

Take note that this may not work for all browsers so some changes may be required.


问:
TypeError: Member "length" is read-only and cannot be used to resize arrays
I am using this version of solidity, pragma solidity >=0.4.22 <0.9.0;

Whenever I compile truffle I get this TypeError: Member "length". When I change the version to 0.4.0 the error goes away, but  I can't use this version. I need to use this pragma solidity >=0.4.22 <0.9.0;

Here is the error:

```<code>     TypeError: Member "length" is read-only and cannot be used to resize arrays.
  --> project:/contracts/Ballot1.sol:23:9:
   |
23 |         proposals.length = _numProposal;
   |         ^^^^^^^^^^^^^^^^

Compilation failed. See above.
</code>```

答:
From Solidity v0.6.0 and onwards, you can use an array slice such as proposals[start:end] (note: it only supports calldata array).

Otherwise, I think you might need to build a copy of the array like so:

```<code>function slice(
  uint256 start,
  uint256 end,
  uint256[] memory proposals
) public pure returns (uint256[] memory) {
  uint256[] memory result;

  uint256 idx = 0;

  for (uint256 i = start; i < end; i++) {
      result[idx] = proposals[i];
      idx++;
  }

  return result;
}
</code>```

Note this operation can be quite costly if you have a large array.

Body:
I am using this version of solidity, pragma solidity >=0.4.22 <0.9.0;

Whenever I compile truffle I get this TypeError: Member "length". When I change the version to 0.4.0 the error goes away, but  I can't use this version. I need to use this pragma solidity >=0.4.22 <0.9.0;

Here is the error:

     TypeError: Member "length" is read-only and cannot be used to resize arrays.
  --> project:/contracts/Ballot1.sol:23:9:
   |
23 |         proposals.length = _numProposal;
   |         ^^^^^^^^^^^^^^^^

Compilation failed. See above.

Body:
From Solidity v0.6.0 and onwards, you can use an array slice such as proposals[start:end] (note: it only supports calldata array).

Otherwise, I think you might need to build a copy of the array like so:

function slice(
  uint256 start,
  uint256 end,
  uint256[] memory proposals
) public pure returns (uint256[] memory) {
  uint256[] memory result;

  uint256 idx = 0;

  for (uint256 i = start; i < end; i++) {
      result[idx] = proposals[i];
      idx++;
  }

  return result;
}

Note this operation can be quite costly if you have a large array.


问:
Jetpack Compose: How to show Alert Dialog with a single item's information from LazyColumn clicked item?
I'm working on a simple project where I import a database of inventory items with room and can modify inventory according to changes. I'm struggling with the LazyColumn.

What I need: When an item from LazyColumn is clicked, show alert dialog with item info.
What happens: When an item from LazyColumn is clicked, it shows all the items alert dialog (generates 100+ alert dialogs and only the last one is visible).

Application Main page with LazyColumn:

After clicking on item shows huge shadow of 100+ Alert dialogs and only the last item is visible:

//custom alert dialog taking parameters from the database class of the inventory items

@Composable
fun ItemAlertDialog(
    onDismiss: () -> Unit,
    onNegativeClick: () -> Unit,
    onPositiveClick: () -> Unit,
    currentInventory: Int,
    itemDescription: String,
    itemNumber: String,
) {
    var incoming by remember { mutableStateOf(0f) }
    var outgoing by remember { mutableStateOf(0f) }

    Dialog(onDismissRequest = onDismiss) {
        Card(
            elevation = 8.dp,
            shape = RoundedCornerShape(12.dp)
        ) {
            Column(modifier = Modifier.padding(8.dp)) {
                Text(
                    text = itemNumber,
                    fontWeight = FontWeight.Bold,
                    fontSize = 20.sp,
                    modifier = Modifier.padding(8.dp)
                )
                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = itemDescription,
                    fontWeight = FontWeight.Normal,
                    fontSize = 15.sp,
                    modifier = Modifier.padding(8.dp)
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = currentInventory.toString(),
                    fontWeight = FontWeight.ExtraBold,
                    color = Color(0xFF0FFC107),
                    fontSize = 20.sp,
                    modifier = Modifier.padding(8.dp)
                )
                // Update Inventory
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center
                ) {
                    Column {

                        Text(text = "Incoming ${incoming.toInt()}")
                        Slider(
                            value = incoming,
                            onValueChange = { incoming = it },
                            valueRange = 0f..100f,
                            onValueChangeFinished = {}
                        )
                        Spacer(modifier = Modifier.height(8.dp))

                        Text(text = "Outgoing ${outgoing.toInt()}")
                        Slider(
                            value = outgoing,
                            onValueChange = { outgoing = it },
                            valueRange = 0f..100f,
                            onValueChangeFinished = {}
                        )
                    }
                }

                // Buttons
                Row(
                    horizontalArrangement = Arrangement.End,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    TextButton(onClick = onNegativeClick) {
                        Text(text = "CANCEL")
                    }
                    Spacer(modifier = Modifier.width(4.dp))
                    TextButton(onClick = {
                        onPositiveClick.invoke()
                    }) {
                        Text(text = "OK")
                    }
                }
            }
        }
    }
}
```
<p>Items row code with the onclick I want to fire the dialog with:</p>
<pre class="lang-kotlin prettyprint-override"><code>@Composable
fun MainScreenItemRow(
    itemNumber: String,
    itemDescription: String,
    currentInventory: Int,
    onclick: () -> Unit
) {
    Row(modifier = Modifier
        .clickable {
            onclick.invoke()
        }
        .border(width = 1.dp, color = Color.Gray, shape = RoundedCornerShape(8.dp))
        .padding(16.dp)
        .clip(shape = RoundedCornerShape(8.dp)),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = itemNumber,
            fontSize = 12.sp,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.weight(3f)
        )
        Spacer(modifier = Modifier.width(10.dp))

        Text(
            text = itemDescription,
            fontSize = 12.sp,
            maxLines = 3,
            modifier = Modifier.weight(4f)
        )
        Spacer(modifier = Modifier.width(30.dp))

        Text(
            text = currentInventory.toString(),
            fontSize = 20.sp,
            color = Color(0xFF0FFC107),
            modifier = Modifier.weight(1f)
        )
    }
}
</code>```

MainActivity code (apologies for messy code, notes annotated with //***):

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    private val mainViewModel: MainViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {

            val systemUiController = rememberSystemUiController()
            val useDarkIcons = MaterialTheme.colors.isLight
            val inventoryList by mainViewModel.getInventoryItems.collectAsState(initial = emptyList())
            val showItemDialog = remember { mutableStateOf(false)}
            val result = remember { mutableStateOf("") }
            val expanded = remember { mutableStateOf(false) }
            val randomList = listOf("")
            val selectedItem = remember{ mutableStateOf(randomList[0])}

//*** getting inventoryList from the flow, added remember to selectedItem and showItemDialog

            SimpleInventoryTheme {
                ItemModelDrawer{drawerState, drawerScopeState ->
                    SideEffect {
                        systemUiController.setSystemBarsColor(
                            color = Color.Transparent,
                            darkIcons = useDarkIcons
                        )
                    }

                    Scaffold(
                        topBar = {
                            TopAppBar(
                                title = {
                                    Text(text = "Inventory Manager")
                                },
                                actions = {
                                    IconButton(onClick = {
                                        drawerScopeState.launch {
                                            drawerState.open()
                                        }
                                    }) {
                                        Icon(Icons.Outlined.Search, contentDescription = "Search")
                                    }

                                    Box(
                                        Modifier
                                            .wrapContentSize(Alignment.TopEnd)
                                    ) {
                                        IconButton(onClick = {
                                            expanded.value = true
                                            result.value = "More icon clicked"
                                        }) {
                                            Icon(
                                                Icons.Filled.MoreVert,
                                                contentDescription = "Localized description"
                                            )
                                        }

                                        DropdownMenu(
                                            expanded = expanded.value,
                                            onDismissRequest = { expanded.value = false },
                                        ) {
                                            DropdownMenuItem(onClick = {
                                                expanded.value = false
                                                result.value = "First item clicked"
                                            }) {
                                                Text("First Item")
                                            }

                                            Divider()

                                            DropdownMenuItem(onClick = {
                                                expanded.value = false
                                                result.value = "Second item clicked"
                                            }) {
                                                Text("Second item")
                                            }

                                        }
                                    }
                                },

                                backgroundColor = Color.White,
                                elevation = AppBarDefaults.TopAppBarElevation
                            )
                        },

                        content = {
                            Column(modifier = Modifier.fillMaxSize()) {
                                MainScreenTitlesRow()
                                Divider()

//*** Showing the items in the main page and adding onclick to fire up the alert dialog

                                LazyColumn(
                                    verticalArrangement = Arrangement.spacedBy(8.dp),
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .padding(16.dp)
                                ) {

                                    itemsIndexed(inventoryList) { idx, item ->
                                        item.currentInventory?.let {
                                            MainScreenItemRow(
                                                itemNumber = item.itemNumber,
                                                itemDescription = item.itemDescription,
                                                currentInventory = it,
                                                onclick = {
//*** trying to set the clicked item into "selectedItem" val

                                                    selectedItem.value = item.itemNumber
                                                    selectedItem.value = item.itemDescription
                                                    selectedItem.value = item.currentInventory.toString()
                                                    Log.d("MainActivityItemClicked", "$selectedItem ")
                                                    showItemDialog.value = true
                                                }
                                            )
                                        }
                                    }

                                }

//*** Trying to check which item was clicked and only present its information in the alert dialog but it loads up all the items

                                if (showItemDialog.value) {

                                    LazyColumn {
                                        itemsIndexed(inventoryList) { _, item ->
                                            item.currentInventory?.let {
                                                ItemAlertDialog(
                                                    itemNumber = item.itemNumber,
                                                    itemDescription = item.itemDescription,
                                                    currentInventory = it,
                                                    onDismiss = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Dialog dismissed!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()
                                                    },
                                                    onNegativeClick = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Cancel!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()

                                                    },
                                                    onPositiveClick = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Saved!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()
                                                    }
                                                )
                                            }

                                        }
                                    }

                                }
                            }
                        }
                    )
                }
                }
        }
    }
}
```

答:
Thank you @Philip Dukhov

I've tried doing this previously and couldn't get the item.Number, item.description, item.inventory at all (val not resolved) so used the inventoryList since I could get it at least smething which was the wrong approach per your suggestion.

I learned a thing or two in the last few days struggling, so with your tip I managed to achive what I need. Not sure it's the right way but it works now. On to the next struggle!

```<code>//***Modified the selected Item from val selectedItem = remember{ mutableStateOf(randomList[0])} to separate 3:

val selectedItemNumber = remember{ mutableStateOf(randomList[0])}

val selectedItemDescription = remember{ mutableStateOf(randomList[0])}

val selectedItemInventory = remember{ mutableStateOf(randomList[0])}

 LazyColumn(
                                    verticalArrangement = Arrangement.spacedBy(8.dp),
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .padding(16.dp)
                                ) {

                                    itemsIndexed(inventoryList) { idx, item ->
                                        item.currentInventory?.let {
                                            MainScreenItemRow(
                                                itemNumber = item.itemNumber,
                                                itemDescription = item.itemDescription,
                                                currentInventory = it,
                                                onclick = {
                                                    selectedItemNumber.value = item.itemNumber
                                                    selectedItemDescription.value = item.itemDescription
                                                    selectedItemInventory.value = item.currentInventory.toString()
                                                    Log.d("MainActivityItemClicked", "$selectedItemDescription ")
                                                    showItemDialog.value = true

                                                }
                                            )
                                        }
                                    }

                                }
                                if (showItemDialog.value) {

                                                ItemAlertDialog(
                                                    itemNumber = selectedItemNumber.value,
                                                    itemDescription = selectedItemDescription.value,
                                                    currentInventory = selectedItemInventory.value.toInt(),
                                                    onDismiss = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Dialog dismissed!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()
                                                    },
                                                    onNegativeClick = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Cancel!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()

                                                    },
                                                    onPositiveClick = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Saved!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()
                                                    }
                                                )

                                        }
                                    }
</code>```

Body:
I'm working on a simple project where I import a database of inventory items with room and can modify inventory according to changes. I'm struggling with the LazyColumn.

What I need: When an item from LazyColumn is clicked, show alert dialog with item info.
What happens: When an item from LazyColumn is clicked, it shows all the items alert dialog (generates 100+ alert dialogs and only the last one is visible).

Application Main page with LazyColumn:

After clicking on item shows huge shadow of 100+ Alert dialogs and only the last item is visible:

//custom alert dialog taking parameters from the database class of the inventory items

@Composable
fun ItemAlertDialog(
    onDismiss: () -> Unit,
    onNegativeClick: () -> Unit,
    onPositiveClick: () -> Unit,
    currentInventory: Int,
    itemDescription: String,
    itemNumber: String,
) {
    var incoming by remember { mutableStateOf(0f) }
    var outgoing by remember { mutableStateOf(0f) }

    Dialog(onDismissRequest = onDismiss) {
        Card(
            elevation = 8.dp,
            shape = RoundedCornerShape(12.dp)
        ) {
            Column(modifier = Modifier.padding(8.dp)) {
                Text(
                    text = itemNumber,
                    fontWeight = FontWeight.Bold,
                    fontSize = 20.sp,
                    modifier = Modifier.padding(8.dp)
                )
                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = itemDescription,
                    fontWeight = FontWeight.Normal,
                    fontSize = 15.sp,
                    modifier = Modifier.padding(8.dp)
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = currentInventory.toString(),
                    fontWeight = FontWeight.ExtraBold,
                    color = Color(0xFF0FFC107),
                    fontSize = 20.sp,
                    modifier = Modifier.padding(8.dp)
                )
                // Update Inventory
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center
                ) {
                    Column {

                        Text(text = "Incoming ${incoming.toInt()}")
                        Slider(
                            value = incoming,
                            onValueChange = { incoming = it },
                            valueRange = 0f..100f,
                            onValueChangeFinished = {}
                        )
                        Spacer(modifier = Modifier.height(8.dp))

                        Text(text = "Outgoing ${outgoing.toInt()}")
                        Slider(
                            value = outgoing,
                            onValueChange = { outgoing = it },
                            valueRange = 0f..100f,
                            onValueChangeFinished = {}
                        )
                    }
                }

                // Buttons
                Row(
                    horizontalArrangement = Arrangement.End,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    TextButton(onClick = onNegativeClick) {
                        Text(text = "CANCEL")
                    }
                    Spacer(modifier = Modifier.width(4.dp))
                    TextButton(onClick = {
                        onPositiveClick.invoke()
                    }) {
                        Text(text = "OK")
                    }
                }
            }
        }
    }
}

Items row code with the onclick I want to fire the dialog with:

@Composable
fun MainScreenItemRow(
    itemNumber: String,
    itemDescription: String,
    currentInventory: Int,
    onclick: () -> Unit
) {
    Row(modifier = Modifier
        .clickable {
            onclick.invoke()
        }
        .border(width = 1.dp, color = Color.Gray, shape = RoundedCornerShape(8.dp))
        .padding(16.dp)
        .clip(shape = RoundedCornerShape(8.dp)),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = itemNumber,
            fontSize = 12.sp,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.weight(3f)
        )
        Spacer(modifier = Modifier.width(10.dp))

        Text(
            text = itemDescription,
            fontSize = 12.sp,
            maxLines = 3,
            modifier = Modifier.weight(4f)
        )
        Spacer(modifier = Modifier.width(30.dp))

        Text(
            text = currentInventory.toString(),
            fontSize = 20.sp,
            color = Color(0xFF0FFC107),
            modifier = Modifier.weight(1f)
        )
    }
}

MainActivity code (apologies for messy code, notes annotated with //***):

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    private val mainViewModel: MainViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {

            val systemUiController = rememberSystemUiController()
            val useDarkIcons = MaterialTheme.colors.isLight
            val inventoryList by mainViewModel.getInventoryItems.collectAsState(initial = emptyList())
            val showItemDialog = remember { mutableStateOf(false)}
            val result = remember { mutableStateOf("") }
            val expanded = remember { mutableStateOf(false) }
            val randomList = listOf("")
            val selectedItem = remember{ mutableStateOf(randomList[0])}

//*** getting inventoryList from the flow, added remember to selectedItem and showItemDialog

            SimpleInventoryTheme {
                ItemModelDrawer{drawerState, drawerScopeState ->
                    SideEffect {
                        systemUiController.setSystemBarsColor(
                            color = Color.Transparent,
                            darkIcons = useDarkIcons
                        )
                    }

                    Scaffold(
                        topBar = {
                            TopAppBar(
                                title = {
                                    Text(text = "Inventory Manager")
                                },
                                actions = {
                                    IconButton(onClick = {
                                        drawerScopeState.launch {
                                            drawerState.open()
                                        }
                                    }) {
                                        Icon(Icons.Outlined.Search, contentDescription = "Search")
                                    }

                                    Box(
                                        Modifier
                                            .wrapContentSize(Alignment.TopEnd)
                                    ) {
                                        IconButton(onClick = {
                                            expanded.value = true
                                            result.value = "More icon clicked"
                                        }) {
                                            Icon(
                                                Icons.Filled.MoreVert,
                                                contentDescription = "Localized description"
                                            )
                                        }

                                        DropdownMenu(
                                            expanded = expanded.value,
                                            onDismissRequest = { expanded.value = false },
                                        ) {
                                            DropdownMenuItem(onClick = {
                                                expanded.value = false
                                                result.value = "First item clicked"
                                            }) {
                                                Text("First Item")
                                            }

                                            Divider()

                                            DropdownMenuItem(onClick = {
                                                expanded.value = false
                                                result.value = "Second item clicked"
                                            }) {
                                                Text("Second item")
                                            }

                                        }
                                    }
                                },

                                backgroundColor = Color.White,
                                elevation = AppBarDefaults.TopAppBarElevation
                            )
                        },

                        content = {
                            Column(modifier = Modifier.fillMaxSize()) {
                                MainScreenTitlesRow()
                                Divider()

//*** Showing the items in the main page and adding onclick to fire up the alert dialog

                                LazyColumn(
                                    verticalArrangement = Arrangement.spacedBy(8.dp),
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .padding(16.dp)
                                ) {

                                    itemsIndexed(inventoryList) { idx, item ->
                                        item.currentInventory?.let {
                                            MainScreenItemRow(
                                                itemNumber = item.itemNumber,
                                                itemDescription = item.itemDescription,
                                                currentInventory = it,
                                                onclick = {
//*** trying to set the clicked item into "selectedItem" val

                                                    selectedItem.value = item.itemNumber
                                                    selectedItem.value = item.itemDescription
                                                    selectedItem.value = item.currentInventory.toString()
                                                    Log.d("MainActivityItemClicked", "$selectedItem ")
                                                    showItemDialog.value = true
                                                }
                                            )
                                        }
                                    }

                                }

//*** Trying to check which item was clicked and only present its information in the alert dialog but it loads up all the items

                                if (showItemDialog.value) {

                                    LazyColumn {
                                        itemsIndexed(inventoryList) { _, item ->
                                            item.currentInventory?.let {
                                                ItemAlertDialog(
                                                    itemNumber = item.itemNumber,
                                                    itemDescription = item.itemDescription,
                                                    currentInventory = it,
                                                    onDismiss = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Dialog dismissed!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()
                                                    },
                                                    onNegativeClick = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Cancel!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()

                                                    },
                                                    onPositiveClick = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Saved!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()
                                                    }
                                                )
                                            }

                                        }
                                    }

                                }
                            }
                        }
                    )
                }
                }
        }
    }
}

Body:
Thank you @Philip Dukhov

I've tried doing this previously and couldn't get the item.Number, item.description, item.inventory at all (val not resolved) so used the inventoryList since I could get it at least smething which was the wrong approach per your suggestion.

I learned a thing or two in the last few days struggling, so with your tip I managed to achive what I need. Not sure it's the right way but it works now. On to the next struggle!

//***Modified the selected Item from val selectedItem = remember{ mutableStateOf(randomList[0])} to separate 3:

val selectedItemNumber = remember{ mutableStateOf(randomList[0])}

val selectedItemDescription = remember{ mutableStateOf(randomList[0])}

val selectedItemInventory = remember{ mutableStateOf(randomList[0])}

 LazyColumn(
                                    verticalArrangement = Arrangement.spacedBy(8.dp),
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .padding(16.dp)
                                ) {

                                    itemsIndexed(inventoryList) { idx, item ->
                                        item.currentInventory?.let {
                                            MainScreenItemRow(
                                                itemNumber = item.itemNumber,
                                                itemDescription = item.itemDescription,
                                                currentInventory = it,
                                                onclick = {
                                                    selectedItemNumber.value = item.itemNumber
                                                    selectedItemDescription.value = item.itemDescription
                                                    selectedItemInventory.value = item.currentInventory.toString()
                                                    Log.d("MainActivityItemClicked", "$selectedItemDescription ")
                                                    showItemDialog.value = true

                                                }
                                            )
                                        }
                                    }

                                }
                                if (showItemDialog.value) {

                                                ItemAlertDialog(
                                                    itemNumber = selectedItemNumber.value,
                                                    itemDescription = selectedItemDescription.value,
                                                    currentInventory = selectedItemInventory.value.toInt(),
                                                    onDismiss = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Dialog dismissed!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()
                                                    },
                                                    onNegativeClick = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Cancel!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()

                                                    },
                                                    onPositiveClick = {
                                                        showItemDialog.value = !showItemDialog.value
                                                        Toast.makeText(
                                                            this@MainActivity,
                                                            "Saved!",
                                                            Toast.LENGTH_SHORT
                                                        )
                                                            .show()
                                                    }
                                                )

                                        }
                                    }


问:
Iterator provided by the Hibernate Interceptor post flush method throws ConcurrentModificationException
I have extended the EmptyInterceptor provided by hibernate to perform some logic on post flush. The overwritten post flush method is provided with an iterator. When I tried to iterate, I received ConcurrentModificationException.

Below is my code snippet,

```<code>@Override
public void postFlush(Iterator entities) throws CallbackException
{
    while (entities.hasNext())
    {
        Object entity;

        try
        {
            entity = entities.next();
        }
        catch(ConcurrentModificationException e)
        {
            // I get concurrent modification exception while iterating.

            return;
        }

    }
}
</code>```

I am getting the below exception,

java.util.ConcurrentModificationException
      at java.util.HashMap$HashIterator.nextEntry(HashMap.java:922)
      at java.util.HashMap$ValueIterator.next(HashMap.java:950)
      at org.hibernate.internal.util.collections.LazyIterator.next(LazyIterator.java:51)
      at com.mycompany.MyInterceptor.postFlush(MyInterceptor.java:55)
      at org.hibernate.event.internal.AbstractFlushingEventListener.postPostFlush(AbstractFlushingEventListener.java:401)
      at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:70)
      at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1130)
      at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1580)
      at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)

From Hibernate Forum we can understand that the iterator passed to the postFlush() method is not thread safe causing ConcurrentModificationException.

Suggestions and solution to avoid the exception is appreciated.

答:
If you look at the implementation of IteratorUtils.toList, it just does:

```<code>    List list = new ArrayList(estimatedSize);
    while (iterator.hasNext()) {
        list.add(iterator.next());
    }
</code>```

which isn't any faster than doing it that way, except... perhaps by allocating the list with an estimated size of 10, it is faster because it isn't necessarily having to re-allocate...

Body:
I have extended the EmptyInterceptor provided by hibernate to perform some logic on post flush. The overwritten post flush method is provided with an iterator. When I tried to iterate, I received ConcurrentModificationException.

Below is my code snippet,

@Override
public void postFlush(Iterator entities) throws CallbackException
{
    while (entities.hasNext())
    {
        Object entity;

        try
        {
            entity = entities.next();
        }
        catch(ConcurrentModificationException e)
        {
            // I get concurrent modification exception while iterating.

            return;
        }

    }
}

I am getting the below exception,

java.util.ConcurrentModificationException
      at java.util.HashMap$HashIterator.nextEntry(HashMap.java:922)
      at java.util.HashMap$ValueIterator.next(HashMap.java:950)
      at org.hibernate.internal.util.collections.LazyIterator.next(LazyIterator.java:51)
      at com.mycompany.MyInterceptor.postFlush(MyInterceptor.java:55)
      at org.hibernate.event.internal.AbstractFlushingEventListener.postPostFlush(AbstractFlushingEventListener.java:401)
      at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:70)
      at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1130)
      at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1580)
      at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)

From Hibernate Forum we can understand that the iterator passed to the postFlush() method is not thread safe causing ConcurrentModificationException.

Suggestions and solution to avoid the exception is appreciated.

Body:
If you look at the implementation of IteratorUtils.toList, it just does:

    List list = new ArrayList(estimatedSize);
    while (iterator.hasNext()) {
        list.add(iterator.next());
    }

which isn't any faster than doing it that way, except... perhaps by allocating the list with an estimated size of 10, it is faster because it isn't necessarily having to re-allocate...


问:
Azure ServiceBusQueue function not firing locally
I just cannot seem to figure out why this function will not fire.

There is an active message in my service bus queue.

My local.settings.json file has the correct queue name and bus connection string which are referenced correctly in the main function class.

I've checked my code agaisn't the example in the MS docs and it looks correct.

When I run it in debug, the CLI picks up the correct function then logs host lock acquired, but does nothing else.

I have tried...

Adding ;TransportType=AmqpWebSockets to the connection string

Explicitly typing the queue name in the main function class instead of the json settings file

Sending a new message onto the queue

Refreshing the queue

But it just will not work and I'm wondering what else to try?

Running the following...

.NET core - 3.1

Azure core tools - 3.0

Function version - 3.3.1

Nugets...

Azure.Messaging.ServiceBus - 7.5.1

Microsoft.Azure.WebJobs.Extensions.ServiceBus - 5.2.0 (I'm using the new ServiceBusReceivedMessage type)

Microsoft.NET.Sdk.Functions - 3.0.13

I haven't reached the stage to publish yet, still just getting it running locally first.

Thanks

```<code> public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task Run([ServiceBusTrigger("MessageQueueName", Connection = "ServiceBusConnectionString")] ServiceBusReceivedMessage message, ILogger logger)
        {
            var bus = new AzureBus(Environment.GetEnvironmentVariable("ServiceBusConnectionString", EnvironmentVariableTarget.Process)).SendOnly();
            var endpoint = new Endpoint(bus, logger);

            logger.LogInformation($"Message received from bus - {message}");

            await endpoint.Start();
            await bus.Handle(message);
        }
    }
</code>```

答:
TransportType is not a valid token for the connection string and will be ignored by the Service Bus client library.  To use the web socket transport, the easiest way is to specify it in your host.json:

{
  "extensions": {
    "serviceBus": {
      "transportType" : "amqpWebSockets"
  }
}
```

Body:
I just cannot seem to figure out why this function will not fire.

There is an active message in my service bus queue.

My local.settings.json file has the correct queue name and bus connection string which are referenced correctly in the main function class.

I've checked my code agaisn't the example in the MS docs and it looks correct.

When I run it in debug, the CLI picks up the correct function then logs host lock acquired, but does nothing else.

I have tried...

Adding ;TransportType=AmqpWebSockets to the connection string

Explicitly typing the queue name in the main function class instead of the json settings file

Sending a new message onto the queue

Refreshing the queue

But it just will not work and I'm wondering what else to try?

Running the following...

.NET core - 3.1

Azure core tools - 3.0

Function version - 3.3.1

Nugets...

Azure.Messaging.ServiceBus - 7.5.1

Microsoft.Azure.WebJobs.Extensions.ServiceBus - 5.2.0 (I'm using the new ServiceBusReceivedMessage type)

Microsoft.NET.Sdk.Functions - 3.0.13

I haven't reached the stage to publish yet, still just getting it running locally first.

Thanks

 public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task Run([ServiceBusTrigger("MessageQueueName", Connection = "ServiceBusConnectionString")] ServiceBusReceivedMessage message, ILogger logger)
        {
            var bus = new AzureBus(Environment.GetEnvironmentVariable("ServiceBusConnectionString", EnvironmentVariableTarget.Process)).SendOnly();
            var endpoint = new Endpoint(bus, logger);

            logger.LogInformation($"Message received from bus - {message}");

            await endpoint.Start();
            await bus.Handle(message);
        }
    }


问:
iPhone: IB, switching between iPhone and iPad
I have a project. When I choose some xib file, iPhone simulator shows in IB. Is there any whey to change it to iPad simulator ? Thanks in advance...</p>

答:
When you begin your app, you will be asked for its platform, eg. iphone or ipad or Universal. Select Universal. This will give you three delegates for your project.

YourAppDelegate

YourAppDelegate_iPad

YourAppDelegate_iPhone

Now for ipad, when you add a nib, do not forget to checkmark "Targeted For Ipad".
Then in the file YourAppDelegate_ipad.m file,

```<code>     // In YourAppDelegate_iPad.m
     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:           (NSDictionary *)launchOptions
     {
         NSLog(@"iPad App Delegate");
         //insert your controller over here with the specified xib fileName...
         return [super application:application didFinishLaunchingWithOptions:launchOptions];
     }
</code>```

Body:
When you begin your app, you will be asked for its platform, eg. iphone or ipad or Universal. Select Universal. This will give you three delegates for your project.

YourAppDelegate

YourAppDelegate_iPad

YourAppDelegate_iPhone

Now for ipad, when you add a nib, do not forget to checkmark "Targeted For Ipad".
Then in the file YourAppDelegate_ipad.m file,

     // In YourAppDelegate_iPad.m
     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:           (NSDictionary *)launchOptions
     {
         NSLog(@"iPad App Delegate");
         //insert your controller over here with the specified xib fileName...
         return [super application:application didFinishLaunchingWithOptions:launchOptions];
     }


问:
Extract json key/value pairs with postgresql/snowflake, where value is not null/blank
I have a field called "filter" with json array like:

[
   {
      "after":"2021-10-14T00:00:00",
      "column":"createddate",
      "from":null,
      "gt":null,
      "gte":null,
      "id":"928d57b0",
      "lt":null,
      "lte":null,
      "not":null,
      "prior":null,
      "to":null,
      "value":null
   },
   {
      "after":null,
      "column":"last_coach_date",
      "from":"",
      "gt":null,
      "gte":null,
      "id":"01704cdd",
      "lt":null,
      "lte":null,
      "not":null,
      "prior":null,
      "to":"",
      "value":null
   }
]
```

I'm trying to extract key/value pairs where value is not null/blank and create another field for it.

Maybe to something like this or one long string:

 { "after": "2021-10-14T00:00:00", "column": "createddate", "id": "928d57b0"}, {"column": "last_coach_date","id": "01704cdd"} AS filter_value

答:
So very similar to Lukasz solution, but OBJECT_AGG will filter out any NULL values, so if you cast to ::text the nulls become real nulls, and are filtered out, so the WHERE clause is not required:

```<code>WITH data_table AS(
  SELECT parse_json('[ { "after": "2021-10-14T00:00:00", "column": "createddate", "from": null, "gt": null, "gte": null, "id": "928d57b0", "lt": null, "lte": null, "not": null, "prior": null, "to": null, "value": null }, { "after": null, "column": "last_coach_date", "from": "", "gt": null, "gte": null, "id": "01704cdd", "lt": null, "lte": null, "not": null, "prior": null, "to": "", "value": null } ]') as json
)
SELECT f.index as batch_id,
    OBJECT_AGG(p.key, NULLIF(p.value::text,'')::variant) as obj
FROM data_table t,
  TABLE(FLATTEN(input=>t.json)) as f,
  TABLE(FLATTEN(input=>f.value)) as p
GROUP BY 1
ORDER BY 1
;
</code>```

gives:

BATCH_ID
OBJ

0
{    "after": "2021-10-14T00:00:00",    "column": "createddate",    "id": "928d57b0"  }

1
{    "column": "last_coach_date",    "id": "01704cdd"  }

It's not clear from the question if you want 2 rows, or a single value, the latter can be had by adding another layer of aggregation via ARRAY_AGG:

```<code>WITH data_table AS(
  SELECT parse_json('[ { "after": "2021-10-14T00:00:00", "column": "createddate", "from": null, "gt": null, "gte": null, "id": "928d57b0", "lt": null, "lte": null, "not": null, "prior": null, "to": null, "value": null }, { "after": null, "column": "last_coach_date", "from": "", "gt": null, "gte": null, "id": "01704cdd", "lt": null, "lte": null, "not": null, "prior": null, "to": "", "value": null } ]') as json
)
SELECT array_agg(obj) as single_answer
FROM (
  SELECT f.index as batch_id,
      OBJECT_AGG(p.key, NULLIF(p.value::text,'')::variant) as obj
  FROM data_table t,
    TABLE(FLATTEN(input=>t.json)) as f,
    TABLE(FLATTEN(input=>f.value)) as p
  GROUP BY 1
)
;
</code>```

gives:

SINGLE_ANSWER

[    {      "after": "2021-10-14T00:00:00",      "column": "createddate",      "id": "928d57b0"    },    {      "column": "last_coach_date",      "id": "01704cdd"    }  ]

Body:
I have a field called "filter" with json array like:

[
   {
      "after":"2021-10-14T00:00:00",
      "column":"createddate",
      "from":null,
      "gt":null,
      "gte":null,
      "id":"928d57b0",
      "lt":null,
      "lte":null,
      "not":null,
      "prior":null,
      "to":null,
      "value":null
   },
   {
      "after":null,
      "column":"last_coach_date",
      "from":"",
      "gt":null,
      "gte":null,
      "id":"01704cdd",
      "lt":null,
      "lte":null,
      "not":null,
      "prior":null,
      "to":"",
      "value":null
   }
]

I'm trying to extract key/value pairs where value is not null/blank and create another field for it.

Maybe to something like this or one long string:

 { "after": "2021-10-14T00:00:00", "column": "createddate", "id": "928d57b0"}, {"column": "last_coach_date","id": "01704cdd"} AS filter_value

Body:
So very similar to Lukasz solution, but OBJECT_AGG will filter out any NULL values, so if you cast to ::text the nulls become real nulls, and are filtered out, so the WHERE clause is not required:

WITH data_table AS(
  SELECT parse_json('[ { "after": "2021-10-14T00:00:00", "column": "createddate", "from": null, "gt": null, "gte": null, "id": "928d57b0", "lt": null, "lte": null, "not": null, "prior": null, "to": null, "value": null }, { "after": null, "column": "last_coach_date", "from": "", "gt": null, "gte": null, "id": "01704cdd", "lt": null, "lte": null, "not": null, "prior": null, "to": "", "value": null } ]') as json
)
SELECT f.index as batch_id,
    OBJECT_AGG(p.key, NULLIF(p.value::text,'')::variant) as obj
FROM data_table t,
  TABLE(FLATTEN(input=>t.json)) as f,
  TABLE(FLATTEN(input=>f.value)) as p
GROUP BY 1
ORDER BY 1
;

gives:

BATCH_ID
OBJ

0
{    "after": "2021-10-14T00:00:00",    "column": "createddate",    "id": "928d57b0"  }

1
{    "column": "last_coach_date",    "id": "01704cdd"  }

It's not clear from the question if you want 2 rows, or a single value, the latter can be had by adding another layer of aggregation via ARRAY_AGG:

WITH data_table AS(
  SELECT parse_json('[ { "after": "2021-10-14T00:00:00", "column": "createddate", "from": null, "gt": null, "gte": null, "id": "928d57b0", "lt": null, "lte": null, "not": null, "prior": null, "to": null, "value": null }, { "after": null, "column": "last_coach_date", "from": "", "gt": null, "gte": null, "id": "01704cdd", "lt": null, "lte": null, "not": null, "prior": null, "to": "", "value": null } ]') as json
)
SELECT array_agg(obj) as single_answer
FROM (
  SELECT f.index as batch_id,
      OBJECT_AGG(p.key, NULLIF(p.value::text,'')::variant) as obj
  FROM data_table t,
    TABLE(FLATTEN(input=>t.json)) as f,
    TABLE(FLATTEN(input=>f.value)) as p
  GROUP BY 1
)
;

gives:

SINGLE_ANSWER

[    {      "after": "2021-10-14T00:00:00",      "column": "createddate",      "id": "928d57b0"    },    {      "column": "last_coach_date",      "id": "01704cdd"    }  ]


问:
APScheduler ID not found?
Can date scheduled jobs have IDS? I don't know what I am doing wrong but whenever I run this code, I get the error:

apscheduler.jobstores.base.JobLookupError: 'No job by the id of item_last_run was found'

```<code>from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta

scheduler = BackgroundScheduler(timezone="America/New_York")

message = "test"
def display_message():
    print(message)
    scheduler.remove_job('item_last_run')

scheduler_date = datetime.now() + timedelta(seconds = 3 )

print(f"\n\n***********SCHEDULED JOB FOR {scheduler_date}")
scheduler.add_job(display_message, 'date', run_date=scheduler_date, id='item_last_run')
scheduler.start()
</code>```

答: Try to put a time.sleep() before calling the remove_job() function. I had the same issue and added a time.sleep(1) before it actually worked.

Title: APScheduler ID not found?

Body:
Can date scheduled jobs have IDS? I don't know what I am doing wrong but whenever I run this code, I get the error:

apscheduler.jobstores.base.JobLookupError: 'No job by the id of item_last_run was found'

from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta

scheduler = BackgroundScheduler(timezone="America/New_York")

message = "test"
def display_message():
    print(message)
    scheduler.remove_job('item_last_run')

scheduler_date = datetime.now() + timedelta(seconds = 3 )

print(f"\n\n***********SCHEDULED JOB FOR {scheduler_date}")
scheduler.add_job(display_message, 'date', run_date=scheduler_date, id='item_last_run')
scheduler.start()


问:
Store slope, intercept, and R2 for multiple regressions in one batch calculation in R
I have a data frame that has a long list of data:

```<code>Well.ID | Year | Ave.GWE
1       | 2005 | 525
1       | 2006 | 524
1       | 2004 | 523
2       | 2005 | 552
2       | 2006 | 551
2       | 2007 | 550
.
.
.
10       | 2005 | 582
10       | 2006 | 581
10       | 2007 | 580

</code>```

I've been able to make a batch plot of the linear regression of Years vs GWE for each Well.ID using ggplot, facet_rep_wrap, geom_smooth, and stat_regline_equation. Now i'd like to create a data frame with the following for each regression:

```<code>
Well.ID | m (slope) | b (intercept) | R2

</code>```

Does anyone know if i can run the lm function through a forloop and store all this information automatically?

Thanks

答:
a human readable solution;

```<code>modelfun <- function(x){
    model <- lm(Ave.GWE ~ Year,x)
    coefs <- coefficients(model)

    intercept <- coefs[1]
    slope <- coefs[2]
    rsq <- summary(model)$r.squared

    list(intercept = intercept,slope = slope,rsq = rsq)
}

newdf <- data.frame()

for(i in unique(df[['Well.ID']])){
    subset_df <- subset(df,Well.ID == i)

    modelstored <- modelfun(subset_df)

    newrow <- data.frame(Well.ID = i,
                         m = modelstored$slope,
                         b = modelstored$intercept,
                         R2 = modelstored$rsq)
    rownames(newrow) <- NULL
    newdf <- rbind(newdf,newrow)
}

newdf
</code>```

output ;

```<code>  Well.ID      m     b    R2
    <dbl>  <dbl> <dbl> <dbl>
1       1  0.500 -479. 0.250
2       2 -1.00  2557. 1
3      10 -1.00  2587. 1
</code>```

Body:
I have a data frame that has a long list of data:

Well.ID | Year | Ave.GWE
1       | 2005 | 525
1       | 2006 | 524
1       | 2004 | 523
2       | 2005 | 552
2       | 2006 | 551
2       | 2007 | 550
.
.
.
10       | 2005 | 582
10       | 2006 | 581
10       | 2007 | 580

I've been able to make a batch plot of the linear regression of Years vs GWE for each Well.ID using ggplot, facet_rep_wrap, geom_smooth, and stat_regline_equation. Now i'd like to create a data frame with the following for each regression:

Well.ID | m (slope) | b (intercept) | R2

Does anyone know if i can run the lm function through a forloop and store all this information automatically?

Thanks

Body:
a human readable solution;

modelfun <- function(x){
    model <- lm(Ave.GWE ~ Year,x)
    coefs <- coefficients(model)

    intercept <- coefs[1]
    slope <- coefs[2]
    rsq <- summary(model)$r.squared

    list(intercept = intercept,slope = slope,rsq = rsq)
}

newdf <- data.frame()

for(i in unique(df[['Well.ID']])){
    subset_df <- subset(df,Well.ID == i)

    modelstored <- modelfun(subset_df)

    newrow <- data.frame(Well.ID = i,
                         m = modelstored$slope,
                         b = modelstored$intercept,
                         R2 = modelstored$rsq)
    rownames(newrow) <- NULL
    newdf <- rbind(newdf,newrow)
}

newdf

output ;

  Well.ID      m     b    R2
    <dbl>  <dbl> <dbl> <dbl>
1       1  0.500 -479. 0.250
2       2 -1.00  2557. 1
3      10 -1.00  2587. 1


问:
Can I change a component I downloaded in react-native project from node_modules?
I want to use a kinda outdated module react-native-numbers-please (last update 2 years ago), but it doesn't work. I think it's because it uses a Picker from react-native. I've changed that in the module's NumbersPlease.tsx which is the main file from which the component is exported.

So I've updated it to use Picker from @react-native-picker/picker as react suggested in a warning message, but I don't think its changed anything since I still get the exact same warning (Picker has been extracted from react-native core and will be removed in a future release...).

I've tried restarting the npm server, but It hasn't changed anything.

Is there something else I need to do for react-native to recognize that I've changed the module, or does it just simply not work?

Thanks in advance!

答:
You can start editing it inside node_modules folder and then patching the package. Then you need to run the following command to patch the package:

npm install -g patch-package
patch-package <module name>
```
<p>This will create a folder at the root of the project called <code>patches</code>. Then in your <code>package.json</code> file under scripts add the following script:</p>
<pre class="lang-json prettyprint-override"><code>"scripts": {
    ....
   "postinstall": "patch-package"
}
</code>```

From now on, when you run install, it will also apply patches on original files.

Body:
You can start editing it inside node_modules folder and then patching the package. Then you need to run the following command to patch the package:

npm install -g patch-package
patch-package <module name>

This will create a folder at the root of the project called patches. Then in your package.json file under scripts add the following script:

"scripts": {
    ....
   "postinstall": "patch-package"
}

From now on, when you run install, it will also apply patches on original files.


问:
Sql exception in winforms form handling best practice
using c# vs2008 winforms.

My standard forms have a typical usage pattern of

Form load

Sqlconnection object open.

read/write datasets using sqldataadaptors

read many things using sql readers

write many data using stored procedures to write

close sql connection

close form

So whats best practice in handling exceptions in this type of usage pattern
I enclose all read and write code to the sql server in try catch clauses to trap exceptions.

So what do i do when i trap an exception ?

Should i close and dispose all sql objects ?

Should i close the form and dispose the form.

Should i try to let the user continue on

Should i try to re-open my sqlconnection if the exception is that the sql connection broken ?

Given that i open and close connections on form load and close, as that it only in theory opens once and closes once with many reads and writes inbetween.

I'm just not sure what action i should be taking when i trap an exception, to prevent memory and resource leaks.

any advice appreciated

thanks

答:
You may want to consider not keeping the SqlConnection open for the lifetime of your form. The form's lifetime is controlled by the user, therefore at the moment the lifetime of SqlConnections are also controlled by the user, which is not a good idea; locks on the database may be kept open until the SqlConnection closes. In a multi-user system this can increase contention for the locked records--you will potentially be blocking out other users whilst your forms have the connection open.

It is better to open and close the connection for particular actions on the form, e.g., when the user clicks a button. Because connection pooling is implemented automatically under the covers, you should not worry about the overhead in repeatedly opening and closing connections--this will be minimised by the connection pooling.


问:
forJoin for dynamic amount of requests not printing when done
So I'm using forkJoin to complete a dynamic amount of requests. It's working great, but I'm not getting my console log when subscribing to the forkJoin? All the examples I've seen just do a basic subscribe like I am, so I'm not really understanding why it isn't working.

I've added the DataService calls also for more clarity. Perhaps I'm doing something wrong there and that's why the forkJoin isn't working?

Here is my code:

```<code>let requests = [];
newAdds.forEach(ele => {
    requests.push(this._dataService.add(ID1, ID2));
});

forkJoin(requests).subscribe(ret => {
    console.log(ret);
  }
);

 add(id1, id2) {
    class Add{
      ID1: number;
      ID2: string;
    };
    let data = new Add();
    data.ID1 = id1;
    data.ID2 = id2;

    let cmd = "Add";
    return this.put(this.urlAdmin() + cmd, data);
  }

protected put(cmd: string, body: any) {
 let headers = new HttpHeaders();
 headers.append('Content-Type', 'application/json');

 return this._http.put(cmd, body, {
   headers: headers
 });
}
</code>```

答:
forkJoin will only emit if and only if all observables have completed.

This one example will never emit (interval never ends)

```<code>forkJoin([interval(1000), interval(2000)]).subscribe(console.log); // won't emit
</code>```

This example will emit [0, 0] value after 2000ms.

```<code>forkJoin([timer(1000), timer(2000)]).subscribe(console.log); // emit [0,0]
</code>```

If one observable does't emit a single value but completes, forkJoin won't emit

```<code>forkJoin(of()).subscribe(console.log) // won't emit
</code>```

If at least 1 observable throws an error, forkJoin will never complete.

```<code>forkJoin([of(1), throwError(1)]).subscribe(console.log); // will never emit
</code>```

ForkJoin doc

Body:
So I'm using forkJoin to complete a dynamic amount of requests. It's working great, but I'm not getting my console log when subscribing to the forkJoin? All the examples I've seen just do a basic subscribe like I am, so I'm not really understanding why it isn't working.

I've added the DataService calls also for more clarity. Perhaps I'm doing something wrong there and that's why the forkJoin isn't working?

Here is my code:

let requests = [];
newAdds.forEach(ele => {
    requests.push(this._dataService.add(ID1, ID2));
});

forkJoin(requests).subscribe(ret => {
    console.log(ret);
  }
);

 add(id1, id2) {
    class Add{
      ID1: number;
      ID2: string;
    };
    let data = new Add();
    data.ID1 = id1;
    data.ID2 = id2;

    let cmd = "Add";
    return this.put(this.urlAdmin() + cmd, data);
  }

protected put(cmd: string, body: any) {
 let headers = new HttpHeaders();
 headers.append('Content-Type', 'application/json');

 return this._http.put(cmd, body, {
   headers: headers
 });
}

Body:
forkJoin will only emit if and only if all observables have completed.

This one example will never emit (interval never ends)

forkJoin([interval(1000), interval(2000)]).subscribe(console.log); // won't emit

This example will emit [0, 0] value after 2000ms.

forkJoin([timer(1000), timer(2000)]).subscribe(console.log); // emit [0,0]

If one observable does't emit a single value but completes, forkJoin won't emit

forkJoin(of()).subscribe(console.log) // won't emit

If at least 1 observable throws an error, forkJoin will never complete.

forkJoin([of(1), throwError(1)]).subscribe(console.log); // will never emit

ForkJoin doc


问:
add commas using String.Format for number and
Using String.Format how can i ensure all numbers have commas after every 3 digits
eg 23000 = "23,000" and that 0 returns "0".

String.Format("{0:n}", 0); //gives 0.00 which i dont want.
I dont want any decimal places, all numbers will be integers.

答:
relatively american number to ordinal.

```<code>using static System.Threading.Thread;

public static string NumberToOrdinal(int number, CultureInfo? culture = null)
{
    var numberString = number.ToString(
        format: "#,0",
        provider: culture ?? CurrentThread.CurrentCulture);
    // Examine the last 2 digits.
    var lastDigits = number % 100;
    // If the last digits are 11, 12, or 13, use th. Otherwise:
    if (lastDigits is >= 11 and <= 13) return $"{numberString}th";
    // Check the last digit.
    return (lastDigits % 10) switch
    {
        1 => $"{numberString}st",
        2 => $"{numberString}nd",
        3 => $"{numberString}rd",
        _ => $"{numberString}th",
    };
}
</code>```

ps i never comment on these things because stack overflow won't let me and sometimes its not worth upstaging everyone with a new answer for a slight improvement. Screw stackoverflow. I've been here for years and still can't comment- which is why i still don't post.

ContentLicense: CC BY-SA 2.5

Body:
relatively american number to ordinal.

using static System.Threading.Thread;

public static string NumberToOrdinal(int number, CultureInfo? culture = null)
{
    var numberString = number.ToString(
        format: "#,0",
        provider: culture ?? CurrentThread.CurrentCulture);
    // Examine the last 2 digits.
    var lastDigits = number % 100;
    // If the last digits are 11, 12, or 13, use th. Otherwise:
    if (lastDigits is >= 11 and <= 13) return $"{numberString}th";
    // Check the last digit.
    return (lastDigits % 10) switch
    {
        1 => $"{numberString}st",
        2 => $"{numberString}nd",
        3 => $"{numberString}rd",
        _ => $"{numberString}th",
    };
}

ps i never comment on these things because stack overflow won't let me and sometimes its not worth upstaging everyone with a new answer for a slight improvement. Screw stackoverflow. I've been here for years and still can't comment- which is why i still don't post.