问:
can not store data from api into variable with vue js
i try to store data from api in prometheus into global variable, i successfully store it from api into variable in vue js using axios, i tried to execute .then(console.log(this.infoCpu) and it worked in console, it has different value because it's from real time situation, but if i try to declare it with global variable on body html it does not work, the value if i try to console as global variable it will has null value, is it the null value comes from the value that i setup from the code on vue js? then how i store from data api into global variable that can be show if i try to show it, example code document.write("variable-that-contain-data-from-api") i need the variable because i use some library called gauge that need varibable contain data cpu real time from api

it is the code

```<code> var newCpu = new Vue({
el: '#cpuHead',
data () {
return {
  infoCpu: null
}
},
mounted () {
axios
  .get('http://172.168.20.21:9090/api/v1/query?query=prometheus_tsdb_head_series_created_total')
  .then(response => (this.infoCpu = response.data.data.result[0].value[1]))
  .then(console.log(this.infoCpu))
}
})
</code>```

that was the code that use to get data from api, and in console that is the right value of the variable this.infoCpu comes up at console.

but when i tried to show it at html body using document.write(newCpu.infoCpu), it does not has value, that just showing null default value that i set up on vue js code

but i try to show it using this code, it comes up

```<code> <div id="cpuHead>
      {{ infoCpu }}
    </div>
</code>```

image variable work

so how to correctly save data from api into variable and use it into another library that i want to use, because it looks like does not mount data from api if try to show it with document.write(newCpu.infoCpu), i need the varibale to work with my gauge library that need a variable

答:
Try to wait for response :

const newCpu = new Vue({
  el: '#cpuHead',
  data () {
    return {
      infoCpu: null
    }
  },
  async mounted () {
    await axios
      .get('http://172.168.20.21:9090/api/v1/query?query=prometheus_tsdb_head_series_created_total')
      .then(response => {
        this.infoCpu = response.data.data.result[0].value[1]
        console.log(this.infoCpu)
      })
      .catch((error) => {
        this.infoCpu = error.message
        console.log(error)
      })
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.25.0/axios.min.js" integrity="sha512-/Q6t3CASm04EliI1QyIDAA/nDo9R8FQ/BULoUFyN4n/BDdyIxeH7u++Z+eobdmr11gG5D/6nPFyDlnisDwhpYA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="cpuHead">
  <div v-if="!infoCpu">loading ...</div>
  {{ infoCpu }}
</div></code>```

Body:
i try to store data from api in prometheus into global variable, i successfully store it from api into variable in vue js using axios, i tried to execute .then(console.log(this.infoCpu) and it worked in console, it has different value because it's from real time situation, but if i try to declare it with global variable on body html it does not work, the value if i try to console as global variable it will has null value, is it the null value comes from the value that i setup from the code on vue js? then how i store from data api into global variable that can be show if i try to show it, example code document.write("variable-that-contain-data-from-api") i need the variable because i use some library called gauge that need varibable contain data cpu real time from api

it is the code

 var newCpu = new Vue({
el: '#cpuHead',
data () {
return {
  infoCpu: null
}
},
mounted () {
axios
  .get('http://172.168.20.21:9090/api/v1/query?query=prometheus_tsdb_head_series_created_total')
  .then(response => (this.infoCpu = response.data.data.result[0].value[1]))
  .then(console.log(this.infoCpu))
}
})

that was the code that use to get data from api, and in console that is the right value of the variable this.infoCpu comes up at console.

but when i tried to show it at html body using document.write(newCpu.infoCpu), it does not has value, that just showing null default value that i set up on vue js code

but i try to show it using this code, it comes up

      {{ infoCpu }}

image variable work

so how to correctly save data from api into variable and use it into another library that i want to use, because it looks like does not mount data from api if try to show it with document.write(newCpu.infoCpu), i need the varibale to work with my gauge library that need a variable

Body:
Try to wait for response :

const newCpu = new Vue({
  el: '#cpuHead',
  data () {
    return {
      infoCpu: null
    }
  },
  async mounted () {
    await axios
      .get('http://172.168.20.21:9090/api/v1/query?query=prometheus_tsdb_head_series_created_total')
      .then(response => {
        this.infoCpu = response.data.data.result[0].value[1]
        console.log(this.infoCpu)
      })
      .catch((error) => {
        this.infoCpu = error.message
        console.log(error)
      })
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.25.0/axios.min.js" integrity="sha512-/Q6t3CASm04EliI1QyIDAA/nDo9R8FQ/BULoUFyN4n/BDdyIxeH7u++Z+eobdmr11gG5D/6nPFyDlnisDwhpYA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="cpuHead">
  <div v-if="!infoCpu">loading ...</div>
  {{ infoCpu }}
</div>


来源: stackexchange

问:
ChromeOption is not working with Selenium-Java
I am using the above code with selenium-java version 4.0.0, selenium-server version 3.11.0, webdrivermanager version 5.0.3 .

Still chrome is not launching in maximised screen and not disbaling the infobars as well.

```<code>import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class chromeOptionsTest {

    public static void main(String[] args) {
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.get("http://www.google.com");
    }
}

</code>```

I am running this test on macbook m1.

答:
I did not setup WebDriverManager in my pom.xml file and used this chromrdriver.exe file instead:

```<code>System.setProperty("webdriver.chrome.driver", "C:\\Users\\panabh02\\OneDrive - CSG Systems Inc\\Desktop\\Automation\\chromedriver.exe");
</code>```

this did work for me.

Also, you can try with this options with -- and

```<code>options.addArguments("--window-size=1920, 1080");
</code>```

like below:

```<code> public static void main(String[] args) {
        //WebDriverManager.chromedriver().setup();
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\***\\****\\Desktop\\Automation\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        options.addArguments("--window-size=1920, 1080");
        options.addArguments("--disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.get("http://www.google.com");
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the above code with selenium-java version 4.0.0, selenium-server version 3.11.0, webdrivermanager version 5.0.3 .

Still chrome is not launching in maximised screen and not disbaling the infobars as well.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class chromeOptionsTest {

    public static void main(String[] args) {
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.get("http://www.google.com");
    }
}

I am running this test on macbook m1.

Body:
I did not setup WebDriverManager in my pom.xml file and used this chromrdriver.exe file instead:

System.setProperty("webdriver.chrome.driver", "C:\\Users\\panabh02\\OneDrive - CSG Systems Inc\\Desktop\\Automation\\chromedriver.exe");

this did work for me.

Also, you can try with this options with -- and

options.addArguments("--window-size=1920, 1080");

like below:

 public static void main(String[] args) {
        //WebDriverManager.chromedriver().setup();
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\***\\****\\Desktop\\Automation\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        options.addArguments("--window-size=1920, 1080");
        options.addArguments("--disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.get("http://www.google.com");
    }


问:
Seaborn Color Palette not working appropiate with lineplot
I'm having a little trouble with customizing my colors for a lineplot. I want to show an ensemble of spectras with a sequential color palette. The argument "palette="blues" works fine, but does not accept any appropriate color lists (like "Blues_d"), which do not include any bright colors.

Below you can see the code I'm using.

```<code>color = (sns.dark_palette("purple"))
sns.set()

ax = sns.lineplot(x="Wavelength", y="Absorption", hue="t (min)", lw=1, data=df1, palette=color, legend="brief")
</code>```

The problem is, that I get the following error:

ValueError: The palette list has the wrong number of colors.

So the question is: How can I use the lineplot function and using a sequential color palette of blues, reds, or whatever that do not include any bright colors?

I'm using pandas version 0.23.3, matplotlib version 2.2.2 and seaborn version 0.9.0

答:
```<code>Palette = ["#090364", "#091e75"] #define your preference
sns.set_style("whitegrid")
sns.set_palette(Palette) #use the list defined in the function
plot = sns.countplot(df['Purchased']) #Enjoy ploting
</code>```

Body:
I'm having a little trouble with customizing my colors for a lineplot. I want to show an ensemble of spectras with a sequential color palette. The argument "palette="blues" works fine, but does not accept any appropriate color lists (like "Blues_d"), which do not include any bright colors.

Below you can see the code I'm using.

color = (sns.dark_palette("purple"))
sns.set()

ax = sns.lineplot(x="Wavelength", y="Absorption", hue="t (min)", lw=1, data=df1, palette=color, legend="brief")

The problem is, that I get the following error:

ValueError: The palette list has the wrong number of colors.

So the question is: How can I use the lineplot function and using a sequential color palette of blues, reds, or whatever that do not include any bright colors?

I'm using pandas version 0.23.3, matplotlib version 2.2.2 and seaborn version 0.9.0


问:
MySQL Multi Union Shortcut
I want to have a mysql table that will list data vertically without using table values.

Just like this.

 SELECT 0 AS vertical UNION SELECT 1 UNION SELECT 2 UNION SELECT 3;

this will output

vertical

0

1

2

3

now, is there a way to do this in much lesser code? if i want to list a total of up to 50?

答:
Use recursive CTE for generating range of numbers with or without gap of any range.

Without GAP:

```<code>-- MySQL (v8.0)
-- range between 0 to 50 with no gap
WITH RECURSIVE num_range (n) AS
(
  SELECT 0 -- starting the range
  UNION ALL
  SELECT n + 1 -- increment by 1
  FROM num_range
  WHERE n < 50 -- last number
)
SELECT n
FROM num_range;
</code>```

With GAP:

```<code>-- range between 0 to 50 with gap
WITH RECURSIVE num_range (n) AS
(
  SELECT 0 -- starting the range
  UNION ALL
  SELECT n + 2  -- increment by 2
  FROM num_range
  WHERE n < 50 -- last number
)
SELECT n
FROM num_range;
</code>```

Please check this url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=30e714fbb43b0d2bf55974bea50410f9

Title: MySQL Multi Union Shortcut

Body:
Use recursive CTE for generating range of numbers with or without gap of any range.

Without GAP:

-- MySQL (v8.0)
-- range between 0 to 50 with no gap
WITH RECURSIVE num_range (n) AS
(
  SELECT 0 -- starting the range
  UNION ALL
  SELECT n + 1 -- increment by 1
  FROM num_range
  WHERE n < 50 -- last number
)
SELECT n
FROM num_range;

With GAP:

-- range between 0 to 50 with gap
WITH RECURSIVE num_range (n) AS
(
  SELECT 0 -- starting the range
  UNION ALL
  SELECT n + 2  -- increment by 2
  FROM num_range
  WHERE n < 50 -- last number
)
SELECT n
FROM num_range;

Please check this url https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=30e714fbb43b0d2bf55974bea50410f9


问:
Why won't MySQL use my index?
If I have the following table:

```<code>CREATE TABLE `mytable` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(64) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `name_first_letter` (`name`(1)),
  KEY `name_all` (`name`)
)
</code>```

Will MySQL ever choose to use the name_first_letter index over the name_all index? If so, under what conditions would this happen?

I have done some quick tests and I'm not sure if MySQL will choose the name_first_letter index even when using index hints:

```<code>-- This uses name_all
EXPLAIN SELECT name FROM mytable
WHERE SUBSTRING(name FROM 1 FOR 1) = 'T';

-- This uses no index at all
EXPLAIN SELECT name FROM mytable USE INDEX (name_first_letter)
WHERE SUBSTRING(name FROM 1 FOR 1) = 'T';
</code>```

Can any MySQL gurus shed some light on this? Is there even a point to having name_first_letter on this column?

Edit: Question title wasn't quite right.

答:
It will not make sense to use the index for your query, because you are selecting the full name column. That means that MySQL cannot use the index alone to satisfy the query.

Further, I believe that MySQL cannot understand that the SUBSTRING(name FROM 1 FOR 1) expression is equivalent to the index.

MySQL might, however, use the index if the index alone can satisfy the query. For example:

```<code>select count(*)
  from mytable
 where name like 'T%';
</code>```

But even that depends on you statistics (hinting should work).

MySQLs partial index feature is intended to save space. It does (usually) not make sense to have both, the partial and the full column index. You would typically drop the shorter one. There might be a rare case where it makes sense, but doesn't make sense in general.

ContentLicense: CC BY-SA 3.0

Title: Why won't MySQL use my index?

Body:
If I have the following table:

CREATE TABLE `mytable` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(64) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `name_first_letter` (`name`(1)),
  KEY `name_all` (`name`)
)

Will MySQL ever choose to use the name_first_letter index over the name_all index? If so, under what conditions would this happen?

I have done some quick tests and I'm not sure if MySQL will choose the name_first_letter index even when using index hints:

-- This uses name_all
EXPLAIN SELECT name FROM mytable
WHERE SUBSTRING(name FROM 1 FOR 1) = 'T';

-- This uses no index at all
EXPLAIN SELECT name FROM mytable USE INDEX (name_first_letter)
WHERE SUBSTRING(name FROM 1 FOR 1) = 'T';

Can any MySQL gurus shed some light on this? Is there even a point to having name_first_letter on this column?

Edit: Question title wasn't quite right.

Body:
It will not make sense to use the index for your query, because you are selecting the full name column. That means that MySQL cannot use the index alone to satisfy the query.

Further, I believe that MySQL cannot understand that the SUBSTRING(name FROM 1 FOR 1) expression is equivalent to the index.

MySQL might, however, use the index if the index alone can satisfy the query. For example:

select count(*)
  from mytable
 where name like 'T%';

But even that depends on you statistics (hinting should work).

MySQLs partial index feature is intended to save space. It does (usually) not make sense to have both, the partial and the full column index. You would typically drop the shorter one. There might be a rare case where it makes sense, but doesn't make sense in general.


问:
How to search for array of string in each row of another column and get the count in excel
I have a excel with a column Address and another lookup column(List) containing list of lookup strings:-

Address

List

St Dunstans Street;  Waterlooville;    PO7 5YT; United Kingdom

London

Simone Weil Avenue;  Week;    EX18 0DJ; United Kingdom

Whitehill

Greyfriars Road;  Carbrooke;    IP25 8PW; United Kingdom

Southampton

Terrick Rd;  Elham;  CT4 9GQ;   United Kingdom

Jameston

Earls Avenue;  Whitehill;    ME13 2QW; United Kingdom

United Kingdom

Cheriton Rd;  West Newton;    HU11 7LB; United Kingdom

Marlborough Crescent;  Southampton;    SO15 4JL; United Kingdom

Baldock Street;  Newton;  ML12   6PZ; United Kingdom

I want to search for all the strigns in List in Address column and return the count of strings matching
What I want to achieve :-

Address
Count_Flag

List

St Dunstans Street;  Waterlooville;    PO7 5YT; United Kingdom
1

London

Simone Weil Avenue;  Week;    EX18 0DJ; United Kingdom
1

Whitehill

Greyfriars Road;  Carbrooke;    IP25 8PW; United Kingdom
1

Southampton

Terrick Rd;  Elham;  CT4 9GQ;   United Kingdom
1

Jameston

Earls Avenue;  Whitehill;    ME13 2QW; United Kingdom
2

United Kingdom

Cheriton Rd;  West Newton;    HU11 7LB; United Kingdom
1

Marlborough Crescent;  Southampton;    SO15 4JL; United Kingdom
2

Baldock Street;  Newton;  ML12   6PZ; United Kingdom
1

I tried something like this :

```<code>=--ISNUMBER(SEARCH(@$D$2:$D$6,A2))
</code>```

答:
You may try wildcard using with COUNTIFS() function.

```<code>=COUNTIFS(A2:A9,"*"&C2&"*")
</code>```

Body:
I have a excel with a column Address and another lookup column(List) containing list of lookup strings:-

Address

List

St Dunstans Street;  Waterlooville;    PO7 5YT; United Kingdom

London

Simone Weil Avenue;  Week;    EX18 0DJ; United Kingdom

Whitehill

Greyfriars Road;  Carbrooke;    IP25 8PW; United Kingdom

Southampton

Terrick Rd;  Elham;  CT4 9GQ;   United Kingdom

Jameston

Earls Avenue;  Whitehill;    ME13 2QW; United Kingdom

United Kingdom

Cheriton Rd;  West Newton;    HU11 7LB; United Kingdom

Marlborough Crescent;  Southampton;    SO15 4JL; United Kingdom

Baldock Street;  Newton;  ML12   6PZ; United Kingdom

I want to search for all the strigns in List in Address column and return the count of strings matching
What I want to achieve :-

Address
Count_Flag

List

St Dunstans Street;  Waterlooville;    PO7 5YT; United Kingdom
1

London

Simone Weil Avenue;  Week;    EX18 0DJ; United Kingdom
1

Whitehill

Greyfriars Road;  Carbrooke;    IP25 8PW; United Kingdom
1

Southampton

Terrick Rd;  Elham;  CT4 9GQ;   United Kingdom
1

Jameston

Earls Avenue;  Whitehill;    ME13 2QW; United Kingdom
2

United Kingdom

Cheriton Rd;  West Newton;    HU11 7LB; United Kingdom
1

Marlborough Crescent;  Southampton;    SO15 4JL; United Kingdom
2

Baldock Street;  Newton;  ML12   6PZ; United Kingdom
1

I tried something like this :

=--ISNUMBER(SEARCH(@$D$2:$D$6,A2))

Body:
You may try wildcard using with COUNTIFS() function.

=COUNTIFS(A2:A9,"*"&C2&"*")


问:
How many subdomains we can create in Route 53 AWS DNS service?
In my application, I'm giving a subdomain (like user.domain.com) to each account. So, I'm planning to use AWS Route 53 for routing subdomains to my application. Is there any maximum limit of subdomains in Amazon Route 53.
Thanks in advance!</p>

答:
This might be relevant or not depending on your use case, but if you expect a large number of users and want to assign a custom subdomain per user, then the limit of 10,000 is probably not sufficient for you.

Your other option is to create a CNAME record with a wildcard subdomain, something like *.domain.com, and point the record to your application, this is now supported by AWS Route 53 and will support all possible subdomains.

The drawback is that subdomains that are not registered will also be directed to your application (like random-str.domain.com), so you'll need to do your validation outside of Route 53. Maybe call an API to validate from your frontend app


问:
python, How to find specific key value in json file then save whole line of json file？
I am a newbie and I need to export specific key value in json file,I searched a lot of sites but couldn't find the code I need, hope this helps me

my json file

```<code>
{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":26}}

</code>```

Need to export whole line json file where 'sex' is 'male' in JSON file

```<code>{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":26}}

</code>```

full code required

答:
You need to show what you have tried so that we can get an idea of the format you expect. Here is, however, one of the simplest way of tackling it -

I am assuming that you have a JSON file in which the details of all males and females are stored (with each record separated by commas, and using only double-quotes "" not single ''! your given JSON file is not valid)

From here you need to import json, then use json.load to convert to a python object (in this case it would be a list) and then iterate over it to check the key 'sex' in each dictionary and filter accordingly. Full code:

import json

filename = "<filename>.json"
with open(filename, "rt") as file:
    data = json.load(file)

new_data = []
for record in data:
    if record['person']['sex'] == 'male':
        new_data.append(record)

newfile = "<new_filename>.json"
with open(newfile, "wt") as file:
    json.dump(new_data, file)
```
<hr>
<p>For this code to work, the initial JSON file (<code>"<filename>.json"</code> above) should be of this format:</p>
<pre class="lang-json prettyprint-override"><code>[
  {"person":{"name":"Silva","sex":"female","age":21}},
  {"person":{"name":"LANA","sex":"male","age":28}},
  {"person":{"name":"Oliveira","sex":"female","age":35}},
  {"person":{"name":"KENN","sex":"male","age":26}}
]
</code>```

PS: Kindly avoid asking for full solutions to homework questions on stackoverflow. We have a lot of other work to do too.

Body:
I am a newbie and I need to export specific key value in json file,I searched a lot of sites but couldn't find the code I need, hope this helps me

my json file

{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":26}}

Need to export whole line json file where 'sex' is 'male' in JSON file

{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":26}}

full code required

Body:
You need to show what you have tried so that we can get an idea of the format you expect. Here is, however, one of the simplest way of tackling it -

I am assuming that you have a JSON file in which the details of all males and females are stored (with each record separated by commas, and using only double-quotes "" not single ''! your given JSON file is not valid)

From here you need to import json, then use json.load to convert to a python object (in this case it would be a list) and then iterate over it to check the key 'sex' in each dictionary and filter accordingly. Full code:

import json

filename = "<filename>.json"
with open(filename, "rt") as file:
    data = json.load(file)

new_data = []
for record in data:
    if record['person']['sex'] == 'male':
        new_data.append(record)

newfile = "<new_filename>.json"
with open(newfile, "wt") as file:
    json.dump(new_data, file)

For this code to work, the initial JSON file ("<filename>.json" above) should be of this format:

[
  {"person":{"name":"Silva","sex":"female","age":21}},
  {"person":{"name":"LANA","sex":"male","age":28}},
  {"person":{"name":"Oliveira","sex":"female","age":35}},
  {"person":{"name":"KENN","sex":"male","age":26}}
]

PS: Kindly avoid asking for full solutions to homework questions on stackoverflow. We have a lot of other work to do too.


问:
Vivado stops simulation on feedback circuit
I'm trying to do a circuit consisting of a 2 to 1 multiplexer (8-bit buses), an 8-bit register and an 8-bit adder. These components are all tested and work as expected.

The thing is: if I try to send the output of the Adder to one of the inputs of the
multiplexer (as seen in the image by the discontinued line), the simulation will stop rather suddenly. If I don't do that and just let ain do its thing, everything will run just as it should, but I do need the output of the adder to be the one inputted to the multiplexer.

The simulation is the following:

The code is:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity Sumitas is
    port (m   : in  STD_LOGIC;
          clk : in  STD_LOGIC;
          ain : in  STD_LOGIC_VECTOR (7 downto 0);
          Add : out STD_LOGIC_VECTOR (7 downto 0));
end Sumitas;

architecture rtl of Sumitas is
    component Adder8bit
        port (a, b : in  STD_LOGIC_VECTOR (7 downto 0);
              Cin  : in  STD_LOGIC;
              S    : out STD_LOGIC_VECTOR (7 downto 0);
              Cout : out STD_LOGIC);
    end component;

    component GenericReg
        generic (DataWidth : integer := 8);
        port (en      : in  STD_LOGIC;
              dataIn  : in  STD_LOGIC_VECTOR (DataWidth - 1 downto 0);
              dataOut : out STD_LOGIC_VECTOR (DataWidth - 1 downto 0));
    end component;

    component GenericMux2_1
        generic (DataWidth : integer := 8);
        port (a, b : in  STD_LOGIC_VECTOR (DataWidth - 1 downto 0);
              Z    : in  STD_LOGIC;
              S    : out STD_LOGIC_VECTOR (DataWidth - 1 downto 0));
    end component;

    constant DW : integer := 8;

    signal AddOut_s, MuxOut_s : STD_LOGIC_VECTOR (7 downto 0);
    signal PCOut_s            : STD_LOGIC_VECTOR (7 downto 0);

begin

    m0 : GenericMux2_1
        generic map (DataWidth => DW)
        port map (a => "00000000",
                  b => AddOut_s,
                  Z => m,
                  S => MuxOut_s);

    PC : GenericReg
        generic map (DataWidth => DW)
        port map (en      => clk,
                  dataIn  => MuxOut_s,
                  dataOut => PCOut_s);

    Add0 : Adder8bit
        port map (a    => "00000001",
                  b    => PCOut_s,
                  Cin  => '0',
                  S    => AddOut_s,
                  Cout => open);
    Add <= AddOut_s;
end rtl;
</code>```

and the testbench:

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity bm_Sumitas is
end bm_Sumitas;

architecture benchmark of bm_Sumitas is
    component Sumitas
        port (m   : in  STD_LOGIC;
              clk : in  STD_LOGIC;
              ain : in  STD_LOGIC_VECTOR (7 downto 0);
              Add : out STD_LOGIC_VECTOR (7 downto 0));
    end component;

    signal clk_s, m_s    : STD_LOGIC;
    signal Add_s, ain_s  : STD_LOGIC_VECTOR (7 downto 0);

    constant T : time := 2 ns;

begin

    benchmark : Sumitas
        port map (m   => m_s,
                  clk => clk_s,
                  ain => ain_s,
                  Add => Add_s);

    clk_proc: process
    begin
        clk_s <= '0';
            wait for T/2;
        clk_s <= '1';
            wait for T/2;
    end process;

    bm_proc : process
    begin
        m_s <= '0';
            wait for 10 ns;
        m_s <= '1';
            wait for 100 ns;
    end process;

    ains_proc : process
    begin
        ain_s <= "00001111";
        for I in 0 to 250 loop
            ain_s <= STD_LOGIC_VECTOR(TO_UNSIGNED(I, ain_s'length));
            wait for T;
        end loop;
    end process;
end benchmark;
</code>```

How can I do the thing I want? I'm ultimately trying to simulate a computer I designed. I have every component already designed and I'm coupling them together.

答:
Constructing a Minimal, Complete, and Verifiable example requires filling in the missing components:

library ieee;
use ieee.std_logic_1164.all;

entity Adder8bit is
    port (a, b : in  STD_LOGIC_VECTOR (7 downto 0);
          Cin  : in  STD_LOGIC;
          S    : out STD_LOGIC_VECTOR (7 downto 0);
          Cout : out STD_LOGIC);
end entity;

architecture foo of adder8bit is
    signal sum: std_logic_vector (9 downto 0);
    use ieee.numeric_std.all;
begin
    sum <= std_logic_vector ( unsigned ('0' & a & cin) +
                              unsigned ('0' & b & cin ));
    s <= sum(8 downto 1);
    cout <= sum(9);
end architecture;

library ieee;
use ieee.std_logic_1164.all;

entity GenericReg is
    generic (DataWidth : integer := 8);
    port (en      : in  STD_LOGIC;
          dataIn  : in  STD_LOGIC_VECTOR (DataWidth - 1 downto 0);
          dataOut : out STD_LOGIC_VECTOR (DataWidth - 1 downto 0));
end entity;

architecture fum of genericreg is
begin
    dataout <= datain when en = '1';
end architecture;
```
<p>with behavioral model substitutes.</p>
<p>(It's not that much work, copy the component declarations paste them, substitute <strong>entity</strong> for <strong>component</strong> and add the reserved word <strong>is</strong>, followed by simple behaviors in architectures.)</p>
<p>It reproduces the symptom you displayed in your simulation waveform:</p>
<p><img src="https://i.stack.imgur.com/EYm98.jpg" alt="bm_sumitas.jpg" /></p>
<p>You can see the essential point of failure occurs when the register enable (ms_s) goes high.</p>
<p>The simulator will report operation on it's STD_OUTPUT:</p>
<pre class="lang-none prettyprint-override"><code>%: make wave
/usr/local/bin/ghdl -a   bm_sumitas.vhdl
/usr/local/bin/ghdl -e   bm_sumitas
/usr/local/bin/ghdl -r  bm_sumitas --wave=bm_sumitas.ghw --stop-time=40ns
./bm_sumitas:info: simulation stopped @11ns by --stop-delta=5000
/usr/bin/open  bm_sumitas.gtkw
%:
</code>```

Note the simulation stopped at 11 ns because of a process executing repeatedly in delta cycles (simulation time doesn't advance).

This is caused by a gated relaxation oscillator formed by the enabled latch, delay (a delta cycle) and having at least one element of latch input inverting each delta cycle.

The particular simulator used has a delta cycle limitation, which will quit simulation when 5,000 delta cycles occur without simulation time advancing.

The genericreg kept generating events with no time delay in assignment, without an after clause in the waveform, after 0 fs (resolution limit) is assumed.

Essentially when the enable is true the signal will have at least one element change every simulation cycle due to the increment, and assigns the signal a new value for at least one element each simulation cycle without allowing the advancement of simulation time by not going quiescent.

You could note the simulator you used should have produced a 'console' output with a similar message if it were capable (and enabled).

So how it this problem cured?  The easiest way is to use a register (not latch) sensitive to a clock edge:

architecture foo of genericreg is
begin
    dataout <= datain when rising_edge(en);
end architecture;
```

Which gives us the full simulation:

Body:
I'm trying to do a circuit consisting of a 2 to 1 multiplexer (8-bit buses), an 8-bit register and an 8-bit adder. These components are all tested and work as expected.

The thing is: if I try to send the output of the Adder to one of the inputs of the
multiplexer (as seen in the image by the discontinued line), the simulation will stop rather suddenly. If I don't do that and just let ain do its thing, everything will run just as it should, but I do need the output of the adder to be the one inputted to the multiplexer.

The simulation is the following:

The code is:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity Sumitas is
    port (m   : in  STD_LOGIC;
          clk : in  STD_LOGIC;
          ain : in  STD_LOGIC_VECTOR (7 downto 0);
          Add : out STD_LOGIC_VECTOR (7 downto 0));
end Sumitas;

architecture rtl of Sumitas is
    component Adder8bit
        port (a, b : in  STD_LOGIC_VECTOR (7 downto 0);
              Cin  : in  STD_LOGIC;
              S    : out STD_LOGIC_VECTOR (7 downto 0);
              Cout : out STD_LOGIC);
    end component;

    component GenericReg
        generic (DataWidth : integer := 8);
        port (en      : in  STD_LOGIC;
              dataIn  : in  STD_LOGIC_VECTOR (DataWidth - 1 downto 0);
              dataOut : out STD_LOGIC_VECTOR (DataWidth - 1 downto 0));
    end component;

    component GenericMux2_1
        generic (DataWidth : integer := 8);
        port (a, b : in  STD_LOGIC_VECTOR (DataWidth - 1 downto 0);
              Z    : in  STD_LOGIC;
              S    : out STD_LOGIC_VECTOR (DataWidth - 1 downto 0));
    end component;

    constant DW : integer := 8;

    signal AddOut_s, MuxOut_s : STD_LOGIC_VECTOR (7 downto 0);
    signal PCOut_s            : STD_LOGIC_VECTOR (7 downto 0);

begin

    m0 : GenericMux2_1
        generic map (DataWidth => DW)
        port map (a => "00000000",
                  b => AddOut_s,
                  Z => m,
                  S => MuxOut_s);

    PC : GenericReg
        generic map (DataWidth => DW)
        port map (en      => clk,
                  dataIn  => MuxOut_s,
                  dataOut => PCOut_s);

    Add0 : Adder8bit
        port map (a    => "00000001",
                  b    => PCOut_s,
                  Cin  => '0',
                  S    => AddOut_s,
                  Cout => open);
    Add <= AddOut_s;
end rtl;

and the testbench:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity bm_Sumitas is
end bm_Sumitas;

architecture benchmark of bm_Sumitas is
    component Sumitas
        port (m   : in  STD_LOGIC;
              clk : in  STD_LOGIC;
              ain : in  STD_LOGIC_VECTOR (7 downto 0);
              Add : out STD_LOGIC_VECTOR (7 downto 0));
    end component;

    signal clk_s, m_s    : STD_LOGIC;
    signal Add_s, ain_s  : STD_LOGIC_VECTOR (7 downto 0);

    constant T : time := 2 ns;

begin

    benchmark : Sumitas
        port map (m   => m_s,
                  clk => clk_s,
                  ain => ain_s,
                  Add => Add_s);

    clk_proc: process
    begin
        clk_s <= '0';
            wait for T/2;
        clk_s <= '1';
            wait for T/2;
    end process;

    bm_proc : process
    begin
        m_s <= '0';
            wait for 10 ns;
        m_s <= '1';
            wait for 100 ns;
    end process;

    ains_proc : process
    begin
        ain_s <= "00001111";
        for I in 0 to 250 loop
            ain_s <= STD_LOGIC_VECTOR(TO_UNSIGNED(I, ain_s'length));
            wait for T;
        end loop;
    end process;
end benchmark;

How can I do the thing I want? I'm ultimately trying to simulate a computer I designed. I have every component already designed and I'm coupling them together.

Body:
Constructing a Minimal, Complete, and Verifiable example requires filling in the missing components:

library ieee;
use ieee.std_logic_1164.all;

entity Adder8bit is
    port (a, b : in  STD_LOGIC_VECTOR (7 downto 0);
          Cin  : in  STD_LOGIC;
          S    : out STD_LOGIC_VECTOR (7 downto 0);
          Cout : out STD_LOGIC);
end entity;

architecture foo of adder8bit is
    signal sum: std_logic_vector (9 downto 0);
    use ieee.numeric_std.all;
begin
    sum <= std_logic_vector ( unsigned ('0' & a & cin) +
                              unsigned ('0' & b & cin ));
    s <= sum(8 downto 1);
    cout <= sum(9);
end architecture;

library ieee;
use ieee.std_logic_1164.all;

entity GenericReg is
    generic (DataWidth : integer := 8);
    port (en      : in  STD_LOGIC;
          dataIn  : in  STD_LOGIC_VECTOR (DataWidth - 1 downto 0);
          dataOut : out STD_LOGIC_VECTOR (DataWidth - 1 downto 0));
end entity;

architecture fum of genericreg is
begin
    dataout <= datain when en = '1';
end architecture;

with behavioral model substitutes.

(It's not that much work, copy the component declarations paste them, substitute entity for component and add the reserved word is, followed by simple behaviors in architectures.)

It reproduces the symptom you displayed in your simulation waveform:

You can see the essential point of failure occurs when the register enable (ms_s) goes high.

The simulator will report operation on it's STD_OUTPUT:

%: make wave
/usr/local/bin/ghdl -a   bm_sumitas.vhdl
/usr/local/bin/ghdl -e   bm_sumitas
/usr/local/bin/ghdl -r  bm_sumitas --wave=bm_sumitas.ghw --stop-time=40ns
./bm_sumitas:info: simulation stopped @11ns by --stop-delta=5000
/usr/bin/open  bm_sumitas.gtkw
%:

Note the simulation stopped at 11 ns because of a process executing repeatedly in delta cycles (simulation time doesn't advance).

This is caused by a gated relaxation oscillator formed by the enabled latch, delay (a delta cycle) and having at least one element of latch input inverting each delta cycle.

The particular simulator used has a delta cycle limitation, which will quit simulation when 5,000 delta cycles occur without simulation time advancing.

The genericreg kept generating events with no time delay in assignment, without an after clause in the waveform, after 0 fs (resolution limit) is assumed.

Essentially when the enable is true the signal will have at least one element change every simulation cycle due to the increment, and assigns the signal a new value for at least one element each simulation cycle without allowing the advancement of simulation time by not going quiescent.

You could note the simulator you used should have produced a 'console' output with a similar message if it were capable (and enabled).

So how it this problem cured?  The easiest way is to use a register (not latch) sensitive to a clock edge:

architecture foo of genericreg is
begin
    dataout <= datain when rising_edge(en);
end architecture;

Which gives us the full simulation:


问:
Cannot import specific function in Jupyter notebook, however, some function in the same "~.py" can be imported
I have utils.py and there are two functions: runrealcmd, mol_with_atom_index

If I try to import the two function with the following code:

```<code>from utils import mol_with_atom_index, runrealcmd
</code>```

It fails to import runrealcmd. The error message is like below:

```<code>ImportError: cannot import name 'runrealcmd' from 'utils'
</code>```

However, if I try to import only the mol_with_atom_index with the following code:

```<code>from utils import mol_with_atom_index
</code>```

It successes. The function of mol_with_atom_index can be imported in Jupyter notebook.

However, the function of runrealcmd cannot be imported in Jupyter notebook although both of the two functions are in the same utils.py file.

```<code>ImportError: cannot import name 'runrealcmd' from 'utils'
</code>```

utils.py

```<code>from subprocess import Popen, PIPE, STDOUT
from IPython.core.magic import register_line_magic

@register_line_magic
def runrealcmd(command):
    # Display instantly: https://stackoverflow.com/questions/52545512/realtime-output-from-a-shell-command-in-jupyter-notebook
    process = Popen(command, stdout=PIPE, shell=True, stderr=STDOUT, bufsize=1, close_fds=True)
    for line in iter(process.stdout.readline, b''):
        print(line.rstrip().decode('utf-8'))
    process.stdout.close()
    process.wait()

def mol_with_atom_index(mol):
    for atom in mol.GetAtoms():
        atom.SetAtomMapNum(atom.GetIdx())
    return mol
</code>```

答: (Jupyter notebook) If you want to import the same-named function (previously imported with the same name) from the other path, you should restart the kernel first.</p>

Body:
I have utils.py and there are two functions: runrealcmd, mol_with_atom_index

If I try to import the two function with the following code:

from utils import mol_with_atom_index, runrealcmd

It fails to import runrealcmd. The error message is like below:

ImportError: cannot import name 'runrealcmd' from 'utils'

However, if I try to import only the mol_with_atom_index with the following code:

from utils import mol_with_atom_index

It successes. The function of mol_with_atom_index can be imported in Jupyter notebook.

However, the function of runrealcmd cannot be imported in Jupyter notebook although both of the two functions are in the same utils.py file.

ImportError: cannot import name 'runrealcmd' from 'utils'

utils.py

from subprocess import Popen, PIPE, STDOUT
from IPython.core.magic import register_line_magic

@register_line_magic
def runrealcmd(command):
    # Display instantly: https://stackoverflow.com/questions/52545512/realtime-output-from-a-shell-command-in-jupyter-notebook
    process = Popen(command, stdout=PIPE, shell=True, stderr=STDOUT, bufsize=1, close_fds=True)
    for line in iter(process.stdout.readline, b''):
        print(line.rstrip().decode('utf-8'))
    process.stdout.close()
    process.wait()

def mol_with_atom_index(mol):
    for atom in mol.GetAtoms():
        atom.SetAtomMapNum(atom.GetIdx())
    return mol


问:
Firefox doesn't purge DNS cache after network.dnsCacheExpiration intervall
Having the latest stable Firefox (69.0.2) on Ubuntu 19.04, I realized that FF has its own DNS cache: After applying DNS changes to the DNS server, I purged the systemd-resolved cache like described here. This worked on multiple cli-tools like dig, curl and ping, so the system-wide DNS cache should be purged. But Firefox still got the old DNS record.

This questions brings me to network.dnsCacheExpiration. According  to the Mozilla documentation, this is the duration in seconds for caching DNS entries. Default is 60 and my about:config also shows that 60 is set. However, I updated the DNS record half an hour ago and it's still the old one.

For testing purpose, I also tried it on a Windows 10 test machine with the same Firefox version. Surprisingly, the DNS changes were applied immediately and it also has network.dnsCacheExpiration set to 60.

Why is the DNS cache from Firefox not purged after 60 seconds on the Ubuntu machine? Is it a problem of the OS, altouth multiple cli-tools got the new entry?

答:
Even though this question is stale, I found very little on the topic searching the web that was helpful.  I noticed the same thing that Lion's question outlined, and tried numerous settings that were not successful, such as:

network.trr.excluded-domains,

network.dnsCacheExpiration,

network.dnsCacheExpirationGracePeriod

I found the bugzilla tickets below, which while not directly answering the question, did deal with a related issue with the hosts file not being honored:

https://bugzilla.mozilla.org/show_bug.cgi?id=1600597

https://bugzilla.mozilla.org/show_bug.cgi?id=1453207

The tickets also were not very helpful in their analysis.  I did however find three workarounds that worked for me (and hopefully it may help others as well):

To clear Firefox's DNS cache manually:

goto: about:networking#dns > Clear DNS Cache

To get the DNS cache to work decently with a particular domain:

goto: about:config > network.dns.forceResolve > list domain(s)

To disable Firefox's DNS cache (force it to always resolve without using DNS cache - has a performance impact):

goto:  about:config > network.dnsCacheEntries > set it to 0


问:
Is there a way to run IOS Simulator on Windows 10?
I want to run IOS Simulator on Windows 10.
Is there a way to do this?</p>

答:
Native testing of iOS apps is only possible on an Apple device. But there are some ways to overcome that.

Some reference to external iOS simulating platforms: https://fossbytes.com/best-ios-emulators-pc-windows-mac/


问:
Generically implementing a trait for all concrete types implementing another trait
I'm pretty new to rust, so this might be a stupid question with an obvious answer, but I don't know the answer yet. I've just read the book and then decided to implement some algorithms I'm familiar with, to get a feeling for the language. That, however, took me down a dark path to a side project that went a little deeper into the language than I had planned for...

Anyway, I'm now playing around with some code for working with indices and offsets in some algorithms in a type-safe way. I have indices into different arrays and strings and want to prevent using an index from one array to be used into another and things like that. So, I have defined new types for different kinds of indices, those with different domains, and for offsets between them. I don't allow comparisons between domains, I can subtract indices to get an offset and I can add and subtract indices and offsets and stuff like that. Further, I can define which types of objects indices can subscript, so an index into a string can only index a string and not, say, a suffix array, where another type is necessary.

This mostly works. I have a bunch of macros for defining what objects are allowed to do. For example, with this

def_offset!(Offset);
def_idx!(
    Idx
    with offset Offset
    with sub [
        Vec<T>[Idx] => T,
        [T][Idx] => T
    ]
);
```
<p>I define a generic <code>Offset</code> that you can do arithmics on but nothing else, and then an index type <code>Idx</code> that can do arithmics with <code>Offset</code> and index vectors and slices. The arithmetic for indices looks like this right now, but I'm not done experimenting with it</p>
<pre class="lang-rust prettyprint-override"><code>macro_rules! def_idx_ops {
    ($idx:ident with offset $offset:ident) => {
        // You can add an index and an offset
        def_op!($idx + $offset => $idx);
        def_op!($offset + $idx => $idx);
        def_op!($idx += $offset);

        // You can subtract an index and an offset
        def_op!($idx - $offset => $idx);
        def_op!($idx -= $offset);

        // You can subtract two indices, but you can't add
        // them (adding indices do not usually make sense)
        def_op!($idx - $idx => $offset);

        // You can add scalars to indices.
        def_op!($idx + usize => $idx);
        def_op!(usize + $idx => $idx);
        def_op!($idx += usize);

        // You can subtract scalars from indices.
        def_op!($idx - usize => $idx);
        def_op!(usize - $idx => $idx);
        def_op!($idx -= usize);
    };
}
</code>```

where the def_op! macro implements the appropriate trait for the types involved in the operator.

There is more code generation going on here than I like, but I couldn't figure out how to write generic code any other way. But maybe I will after this question.

See, now I got to implementing ranges over these types. They come out of the box if you just want a range

```<code>let r = Idx(0)..Idx(10)
</code>```

but you can't iterate over them. For that, you need to implement some traits. With the code below, it works for the type Idx:

// Trait for implementing iteration through i..j ranges for Idx.
// NB: This requires nightly; the iter::Step trait is unstable.
impl std::iter::Step for Idx {
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.0, end.0) {
            (i, j) if i > j => None,
            (i, j) => Some(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        Some(start + count) // Ignoring overflow here...
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        match start.0 {
            i if i < count => None,
            _ => Some(start - count),
        }
    }
}
```
<p>But it only works for the concrete type <code>Idx</code>. If I try to make a generic implementation, I run into all kinds of trouble.</p>
<p>This is my current attempt, but it works as little as the others I have made:</p>
<pre class="lang-rust prettyprint-override"><code>trait RangeIndex<T>: NumWrapper<T> + std::ops::Add<T> + std::ops::Sub<T>
where
    T: num::traits::NumCast,
{
}

impl<Idx> std::iter::Step for Idx
where
    Idx: RangeIndex<usize>,
{
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.wrapped(), end.wrapped()) {
            (i, j) if i > j => None,
            (i, j) => Some(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        Some(start + count) // Ignoring overflow here...
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        match start.wrapped() {
            i if i < count => None,
            _ => Some(start - count),
        }
    }
}
</code>```

The RangeIndex<T> trait puts the constraints I need on the index type, and NumWrapper is a trait for the numbers I'm wrapping in indices and offsets.

pub trait Wrapper<Wrapped> {
    fn wrapped(&self) -> Wrapped;
}

pub trait NumWrapper<Wrapped>:
    Wrapper<Wrapped> + std::cmp::PartialEq + std::cmp::PartialOrd
where
    Wrapped: num::traits::NumCast,
{
    fn cast_to_wrapped<T: num::traits::NumCast>(val: T) -> Wrapped {
        num::cast(val).unwrap()
    }
}
```
<p>(There is a little more to the wrapped objects, but this is the only relevant part for treating them as numbers).</p>
<p>This generic code does not work. The compiler suggests that I make the trait <code>dyn</code> but I assure you that I do not want to do that. I don't want any dynamic dispatch or polymorphism at all. I have concrete types; I want implementations for those. Nothing more and nothing less.</p>
<p>It is a small matter to just generate the code with macros, like I have with the operators. But I am reinventing generic code now, and that is deeply unsatisfying. I feel the same way about generating the operators instead of having code for traits and then just implementing the appropriate trait for each type.</p>
<p>Is it impossible to say "for any type that implements this particular trait, give me a concrete implementation of this trait like this"? It is really all I want. For any <code>Idx</code> that implements these traits, give me this <code>std::iter::Step</code>.</p>
<p>And if I can get that, I would love to do the same with the operators</p>
<pre class="lang-rust prettyprint-override"><code>impl<LHS, RHS, RES> std::ops::Add<RHS> for LHS {
    where //"some constraint involving both LHS and RHS and RES"
          Constraint<LHS,RHS,RES> // yeah, might not be able to do this
    type Output = RES;
    fn add(self, rhs: $rhs) -> Self::Output {
        RES(RES::cast_to_wrapped(self.wrapped()) +
            RES::cast_to_wrapped(rhs.wrapped()))
    }
}
</code>```

One can dream, at least.

Anyway, I don't mind generating the operators, but I see it as a problem if I have to give up on generic code that works with these types. If I can't even run through a range, then this project is going to die pretty soon. Using macros for every generic function just isn't an attractive idea. (Well, I can still write generic functions, I just cannot implement traits, so it is not all that bad, but it still is pretty bad).

Really, what I want to tell Rust is that "for all types that implement the following traits", "give me an instance of this generic code". Exactly what I can get with macros, I suppose, but using generics that were made for this purpose instead.

Surely there must be some well know trick to generically implementing a trait without resorting to dyn?

UPDATE

I've put a related exampled on playground. The full example where I need the ranges is a bit too long, but I think the smaller example hits the same issue. There, I have a trait for adding wrapped numbers

// Local trait for adding ... a substitute for the range code I need
trait MyAdd<Rhs> {
    type Res;
    fn my_add(self, rhs: Rhs) -> Self::Res;
}
```

I can implement std::ops::Add just from this interface, but no matter how I try, I cannot do it without explicitly implementing that trait for each type I define. There are a couple of examples of my attempts, but needless to say, they do not work.

Playground

答:
Looking at the playground example, it's not possible to do what you want. This type of impl can't work:

impl<X, RHS> std::ops::Add<RHS> for X
where
    X: MyAdd<RHS>,
{
    type Output = X::Res;
    fn add(self, rhs: RHS) -> Self::Output {
        self.my_add(rhs)
    }
}
```

It is a blanket impl, as we are implementing a trait for a bare type parameter X. But only the crate that defines the trait being impl'd (in this case std::ops::Add) is allowed to write a blanket impl for that trait.

Body:
I'm pretty new to rust, so this might be a stupid question with an obvious answer, but I don't know the answer yet. I've just read the book and then decided to implement some algorithms I'm familiar with, to get a feeling for the language. That, however, took me down a dark path to a side project that went a little deeper into the language than I had planned for...

Anyway, I'm now playing around with some code for working with indices and offsets in some algorithms in a type-safe way. I have indices into different arrays and strings and want to prevent using an index from one array to be used into another and things like that. So, I have defined new types for different kinds of indices, those with different domains, and for offsets between them. I don't allow comparisons between domains, I can subtract indices to get an offset and I can add and subtract indices and offsets and stuff like that. Further, I can define which types of objects indices can subscript, so an index into a string can only index a string and not, say, a suffix array, where another type is necessary.

This mostly works. I have a bunch of macros for defining what objects are allowed to do. For example, with this

def_offset!(Offset);
def_idx!(
    Idx
    with offset Offset
    with sub [
        Vec<T>[Idx] => T,
        [T][Idx] => T
    ]
);

I define a generic Offset that you can do arithmics on but nothing else, and then an index type Idx that can do arithmics with Offset and index vectors and slices. The arithmetic for indices looks like this right now, but I'm not done experimenting with it

macro_rules! def_idx_ops {
    ($idx:ident with offset $offset:ident) => {
        // You can add an index and an offset
        def_op!($idx + $offset => $idx);
        def_op!($offset + $idx => $idx);
        def_op!($idx += $offset);

        // You can subtract an index and an offset
        def_op!($idx - $offset => $idx);
        def_op!($idx -= $offset);

        // You can subtract two indices, but you can't add
        // them (adding indices do not usually make sense)
        def_op!($idx - $idx => $offset);

        // You can add scalars to indices.
        def_op!($idx + usize => $idx);
        def_op!(usize + $idx => $idx);
        def_op!($idx += usize);

        // You can subtract scalars from indices.
        def_op!($idx - usize => $idx);
        def_op!(usize - $idx => $idx);
        def_op!($idx -= usize);
    };
}

where the def_op! macro implements the appropriate trait for the types involved in the operator.

There is more code generation going on here than I like, but I couldn't figure out how to write generic code any other way. But maybe I will after this question.

See, now I got to implementing ranges over these types. They come out of the box if you just want a range

let r = Idx(0)..Idx(10)

but you can't iterate over them. For that, you need to implement some traits. With the code below, it works for the type Idx:

// Trait for implementing iteration through i..j ranges for Idx.
// NB: This requires nightly; the iter::Step trait is unstable.
impl std::iter::Step for Idx {
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.0, end.0) {
            (i, j) if i > j => None,
            (i, j) => Some(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        Some(start + count) // Ignoring overflow here...
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        match start.0 {
            i if i < count => None,
            _ => Some(start - count),
        }
    }
}

But it only works for the concrete type Idx. If I try to make a generic implementation, I run into all kinds of trouble.

This is my current attempt, but it works as little as the others I have made:

trait RangeIndex<T>: NumWrapper<T> + std::ops::Add<T> + std::ops::Sub<T>
where
    T: num::traits::NumCast,
{
}

impl<Idx> std::iter::Step for Idx
where
    Idx: RangeIndex<usize>,
{
    fn steps_between(start: &Self, end: &Self) -> Option<usize> {
        match (start.wrapped(), end.wrapped()) {
            (i, j) if i > j => None,
            (i, j) => Some(j - i),
        }
    }
    fn forward_checked(start: Self, count: usize) -> Option<Self> {
        Some(start + count) // Ignoring overflow here...
    }
    fn backward_checked(start: Self, count: usize) -> Option<Self> {
        match start.wrapped() {
            i if i < count => None,
            _ => Some(start - count),
        }
    }
}

The RangeIndex<T> trait puts the constraints I need on the index type, and NumWrapper is a trait for the numbers I'm wrapping in indices and offsets.

pub trait Wrapper<Wrapped> {
    fn wrapped(&self) -> Wrapped;
}

pub trait NumWrapper<Wrapped>:
    Wrapper<Wrapped> + std::cmp::PartialEq + std::cmp::PartialOrd
where
    Wrapped: num::traits::NumCast,
{
    fn cast_to_wrapped<T: num::traits::NumCast>(val: T) -> Wrapped {
        num::cast(val).unwrap()
    }
}

(There is a little more to the wrapped objects, but this is the only relevant part for treating them as numbers).

This generic code does not work. The compiler suggests that I make the trait dyn but I assure you that I do not want to do that. I don't want any dynamic dispatch or polymorphism at all. I have concrete types; I want implementations for those. Nothing more and nothing less.

It is a small matter to just generate the code with macros, like I have with the operators. But I am reinventing generic code now, and that is deeply unsatisfying. I feel the same way about generating the operators instead of having code for traits and then just implementing the appropriate trait for each type.

Is it impossible to say "for any type that implements this particular trait, give me a concrete implementation of this trait like this"? It is really all I want. For any Idx that implements these traits, give me this std::iter::Step.

And if I can get that, I would love to do the same with the operators

impl<LHS, RHS, RES> std::ops::Add<RHS> for LHS {
    where //"some constraint involving both LHS and RHS and RES"
          Constraint<LHS,RHS,RES> // yeah, might not be able to do this
    type Output = RES;
    fn add(self, rhs: $rhs) -> Self::Output {
        RES(RES::cast_to_wrapped(self.wrapped()) +
            RES::cast_to_wrapped(rhs.wrapped()))
    }
}

One can dream, at least.

Anyway, I don't mind generating the operators, but I see it as a problem if I have to give up on generic code that works with these types. If I can't even run through a range, then this project is going to die pretty soon. Using macros for every generic function just isn't an attractive idea. (Well, I can still write generic functions, I just cannot implement traits, so it is not all that bad, but it still is pretty bad).

Really, what I want to tell Rust is that "for all types that implement the following traits", "give me an instance of this generic code". Exactly what I can get with macros, I suppose, but using generics that were made for this purpose instead.

Surely there must be some well know trick to generically implementing a trait without resorting to dyn?

UPDATE

I've put a related exampled on playground. The full example where I need the ranges is a bit too long, but I think the smaller example hits the same issue. There, I have a trait for adding wrapped numbers

// Local trait for adding ... a substitute for the range code I need
trait MyAdd<Rhs> {
    type Res;
    fn my_add(self, rhs: Rhs) -> Self::Res;
}

I can implement std::ops::Add just from this interface, but no matter how I try, I cannot do it without explicitly implementing that trait for each type I define. There are a couple of examples of my attempts, but needless to say, they do not work.

Playground

Body:
Looking at the playground example, it's not possible to do what you want. This type of impl can't work:

impl<X, RHS> std::ops::Add<RHS> for X
where
    X: MyAdd<RHS>,
{
    type Output = X::Res;
    fn add(self, rhs: RHS) -> Self::Output {
        self.my_add(rhs)
    }
}

It is a blanket impl, as we are implementing a trait for a bare type parameter X. But only the crate that defines the trait being impl'd (in this case std::ops::Add) is allowed to write a blanket impl for that trait.


问:
Shopware - How to get products using App Credentials?
I created App in Shopware and able to get apiKey, secretKey, shopUrl and shopId. I want to get all my products using these credentials.

This is my code

```<code>$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "http://shopware.example.com/store-api/product",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $payload,
  CURLOPT_HTTPHEADER => [
    "Accept: application/json",
    "Content-Type: application/json",
    "sw-access-key: SW234C1LVA010CWHDD34WK1TMW"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
    $data = json_decode($response, true);
    print_r($data);
}
</code>```

and I am getting error like this

```<code>Array
(
    [errors] => Array
        (
            [0] => Array
                (
                    [status] => 412
                    [code] => FRAMEWORK__ROUTING_SALES_CHANNEL_NOT_FOUND
                    [title] => Precondition Failed
                    [detail] => No matching sales channel found.
                    [meta] => Array
                        (
                            [parameters] => Array
                                (
                                )
                        )
                )
        )
)
</code>```

When I using API key from settings page API I am able to get products.

But how to use App credentials (App key, secret key, shop URL) and get products

答:
You should have gotten the API key during App registration:

https://developer.shopware.com/docs/guides/plugins/apps/app-base-guide#confirmation-request

Did you try that one? If it does not work for the store API you might want to use the admin API.

Body:
I created App in Shopware and able to get apiKey, secretKey, shopUrl and shopId. I want to get all my products using these credentials.

This is my code

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "http://shopware.example.com/store-api/product",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $payload,
  CURLOPT_HTTPHEADER => [
    "Accept: application/json",
    "Content-Type: application/json",
    "sw-access-key: SW234C1LVA010CWHDD34WK1TMW"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
    $data = json_decode($response, true);
    print_r($data);
}

and I am getting error like this

Array
(
    [errors] => Array
        (
            [0] => Array
                (
                    [status] => 412
                    [code] => FRAMEWORK__ROUTING_SALES_CHANNEL_NOT_FOUND
                    [title] => Precondition Failed
                    [detail] => No matching sales channel found.
                    [meta] => Array
                        (
                            [parameters] => Array
                                (
                                )
                        )
                )
        )
)

When I using API key from settings page API I am able to get products.

But how to use App credentials (App key, secret key, shop URL) and get products


问:
python how to plot classification data
I'm unable to plot the data for classification algo using numpy as it throws this error ValueError: x and y must be the same size

My data in the data variable look like this:

```<code>[[ 34.62365962  78.02469282   0.        ]
 [ 30.28671077  43.89499752   0.        ]
 [ 35.84740877  72.90219803   0.        ]
 [ 60.18259939  86.3085521    1.        ]
 [ 79.03273605  75.34437644   1.        ]
 [ 45.08327748  56.31637178   0.        ]
 [ 61.10666454  96.51142588   1.        ]
 [ 75.02474557  46.55401354   1.        ]]
</code>```

Code:

```<code>data=np.loadtxt('ex2data1.txt',delimiter=',',dtype=None)
X = data[:, [0,1]]
y = data[:, 2]
pylab.scatter(X,y)
pylab.show()
</code>```

I'm trying to plot this:

答:
```<code># Visualising the Training set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, cla.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('KNN (Training set)')
plt.fig(figsize=(12,6))
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
</code>```

See the example

Title: python how to plot classification data

Body:
I'm unable to plot the data for classification algo using numpy as it throws this error ValueError: x and y must be the same size

My data in the data variable look like this:

[[ 34.62365962  78.02469282   0.        ]
 [ 30.28671077  43.89499752   0.        ]
 [ 35.84740877  72.90219803   0.        ]
 [ 60.18259939  86.3085521    1.        ]
 [ 79.03273605  75.34437644   1.        ]
 [ 45.08327748  56.31637178   0.        ]
 [ 61.10666454  96.51142588   1.        ]
 [ 75.02474557  46.55401354   1.        ]]

Code:

data=np.loadtxt('ex2data1.txt',delimiter=',',dtype=None)
X = data[:, [0,1]]
y = data[:, 2]
pylab.scatter(X,y)
pylab.show()

I'm trying to plot this:

Body:
# Visualising the Training set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, cla.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('KNN (Training set)')
plt.fig(figsize=(12,6))
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

See the example


问:
How to parse data from an extracted JSON object property using AngularJS?
I have a JSON object property that is a string and looks like this:

```<code>"&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4"
</code>```

I want to parse this property (string) to extract the numbers that have an & (ampersand) in front of them, and place each extracted &number into an array. The result would look like:

```<code>var array = ['&1', '&2', '&3', '&4', '&5', '&6', '&7', '&8'];
</code>```

I am using AngularJS.

Any suggestions on how to best accomplish this?

答:
The algorithm for this would be "split() and filter()".

A naive approach could check if the first character is an ampersand:

input = "&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4"

input.split(" ").filter(item => item.startsWith("&"))
```
<p>This works well and is fast, but makes the assumption that only numbers can come after <code>&</code>, so it will also return items like <code>&abc</code>.</p>
<p>You could also use a regex:</p>
<pre class="lang-js prettyprint-override"><code>input.split(" ").filter(item => item.match(/^&\d+$/))
</code>```

This is slower, but it's more robust. It also makes the assumption that only full-number items are allowed, so it will reject items like &12a.

Both solutions can be adapted if the full list of requirements differ, as from the question is not fully clear if:

the separator is space, or it can be other characters (e.g. comma, or newline, or tab)

items starting with & are known to contain only numbers, or can contain other characters too

negative numbers are considered valid or not

Body:
I have a JSON object property that is a string and looks like this:

"&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4"

I want to parse this property (string) to extract the numbers that have an & (ampersand) in front of them, and place each extracted &number into an array. The result would look like:

var array = ['&1', '&2', '&3', '&4', '&5', '&6', '&7', '&8'];

I am using AngularJS.

Any suggestions on how to best accomplish this?

Body:
The algorithm for this would be "split() and filter()".

A naive approach could check if the first character is an ampersand:

input = "&1 *UBIN 8 &2 *UBIN 8 &3 *UBIN 8 &4 *CHAR 10 &5 *UBIN 8 &6 *UBIN 8 &7 *UBIN 8 &8 *CCHAR *VARY 4"

input.split(" ").filter(item => item.startsWith("&"))

This works well and is fast, but makes the assumption that only numbers can come after &, so it will also return items like &abc.

You could also use a regex:

input.split(" ").filter(item => item.match(/^&\d+$/))

This is slower, but it's more robust. It also makes the assumption that only full-number items are allowed, so it will reject items like &12a.

Both solutions can be adapted if the full list of requirements differ, as from the question is not fully clear if:

the separator is space, or it can be other characters (e.g. comma, or newline, or tab)

items starting with & are known to contain only numbers, or can contain other characters too

negative numbers are considered valid or not


问:
Array with only even number
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

```<code>#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done
</code>```

but got errors like:
line 15: syntax error near unexpected token `do'

答:
If your language has a for(;;)  syntax you can

```<code>for (X = 18; X <= 2500; X += 2)
</code>```

Title: Array with only even number

Body:
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done

but got errors like:
line 15: syntax error near unexpected token `do'

Body:
If your language has a for(;;)  syntax you can

for (X = 18; X <= 2500; X += 2)


问:
How to give spacing between buttons using bootstrap
I want to give spacing between buttons is there a way to give spacing using bootstrap so that they will be consistent for different screen resolutions.

I tried using margin-left But is it the correct way to do this.??

Here is the demo

HTML:

```<code><div class="btn-toolbar text-center well">
    <button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 margin-left">
      <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> ADD PACKET
    </button>
    <button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 margin-left">
      <span class="glyphicon glyphicon-edit" aria-hidden="true"></span> EDIT CUSTOMER
    </button>
    <button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 margin-left">
      <span class="glyphicon glyphicon-time" aria-hidden="true"></span> HISTORY
    </button>
    <button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 margin-left">
      <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> DELETE CUSTOMER
    </button>
</div>
</code>```

CSS:

```<code>.margin-left{
    margin-left: 80px !important;
}
</code>```

答:
It varies according to bootstrap version

If you are using

Bootsrap 4

mr-1

for more refer the official  Bootsrap 4 margin-and-padding link

Bootstrap 5

me-1

for more refer the official Bootsrap 5 margin-and-padding link

Body:
I want to give spacing between buttons is there a way to give spacing using bootstrap so that they will be consistent for different screen resolutions.

I tried using margin-left But is it the correct way to do this.??

Here is the demo

HTML:

    <button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 margin-left">
       ADD PACKET
    </button>
    <button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 margin-left">
       EDIT CUSTOMER
    </button>
    <button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 margin-left">
       HISTORY
    </button>
    <button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 margin-left">
       DELETE CUSTOMER
    </button>

CSS:

.margin-left{
    margin-left: 80px !important;
}


问:
List sections empty after adding .id()
I have a section for each element in array. I need to use ScrollViewReader so I need to add .id() to each row. However, when I add id, list rows become empty. It works fine without id modifier. See the image below:

Here's the sample project I have made that demonstrates this problem:

import SwiftUI
import PlaygroundSupport

struct Interval: Identifiable {
    var id = UUID()
    var index: Int
    var name : String {
        "Interval \(index)"
    }
}

struct ContentView: View {

    var intervals: [Interval] = (1...9).map { index in Interval(index: index) }

    var body: some View {
        List {
            ForEach(intervals, id: \.id) { interval in
                Section {
                    Text(interval.name)
                        //.id(interval.id) // try removing this comment
                }
            }
        }
    }

}

PlaygroundPage.current.setLiveView(ContentView())
```
<p>Some debugging that I have done:</p>
<p>Having only 1 section works, but I need one section for every element.</p>
<pre class="lang-swift prettyprint-override"><code>Section {
    ForEach(intervals, id: \.id) { interval in
        Text(interval.name)
            .id(interval.id)
    }
}
</code>```

Adding each section manually also works, but this can't be done as I have lots of section in my actual project.

Section {
    Text(intervals[0].name)
        .id(intervals[0].id)
}
Section {
    Text(intervals[1].name)
        .id(intervals[1].id)
}
```

Does anyone know how to fix this? Thanks.

答:
Although @dudette's answer solved the empty cells issue in my real project, scrolling to desired cell/row wasn't working when using ScrollViewReader's scrollTo method.

I have come up with a weird fix that works for me. It is weird because I don't know how and why it works, but it works. If anyone can explain why it works, I'll be very thankful.

The solution is, I created a new ViewModifier named EmbedInSection that just embeds the content in Section.

struct EmbedInSection: ViewModifier {
    func body(content: Content) -> some View {
        Section {
            content
        }
    }
}

```
<p>And I used it like:</p>
<pre class="lang-swift prettyprint-override"><code>var body: some View {
    List {
        ForEach(intervals) { interval in
            Text(interval.name)
                .id(interval.id)
                .modifier(EmbedInSection())
        }
    }
}
</code>```

Title: List sections empty after adding .id()

Body:
I have a section for each element in array. I need to use ScrollViewReader so I need to add .id() to each row. However, when I add id, list rows become empty. It works fine without id modifier. See the image below:

Here's the sample project I have made that demonstrates this problem:

import SwiftUI
import PlaygroundSupport

struct Interval: Identifiable {
    var id = UUID()
    var index: Int
    var name : String {
        "Interval \(index)"
    }
}

struct ContentView: View {

    var intervals: [Interval] = (1...9).map { index in Interval(index: index) }

    var body: some View {
        List {
            ForEach(intervals, id: \.id) { interval in
                Section {
                    Text(interval.name)
                        //.id(interval.id) // try removing this comment
                }
            }
        }
    }

}

PlaygroundPage.current.setLiveView(ContentView())

Some debugging that I have done:

Having only 1 section works, but I need one section for every element.

Section {
    ForEach(intervals, id: \.id) { interval in
        Text(interval.name)
            .id(interval.id)
    }
}

Adding each section manually also works, but this can't be done as I have lots of section in my actual project.

Section {
    Text(intervals[0].name)
        .id(intervals[0].id)
}
Section {
    Text(intervals[1].name)
        .id(intervals[1].id)
}

Does anyone know how to fix this? Thanks.

Body:
Although @dudette's answer solved the empty cells issue in my real project, scrolling to desired cell/row wasn't working when using ScrollViewReader's scrollTo method.

I have come up with a weird fix that works for me. It is weird because I don't know how and why it works, but it works. If anyone can explain why it works, I'll be very thankful.

The solution is, I created a new ViewModifier named EmbedInSection that just embeds the content in Section.

struct EmbedInSection: ViewModifier {
    func body(content: Content) -> some View {
        Section {
            content
        }
    }
}

And I used it like:

var body: some View {
    List {
        ForEach(intervals) { interval in
            Text(interval.name)
                .id(interval.id)
                .modifier(EmbedInSection())
        }
    }
}


问:
Golang - Sending API POST Request - Not enough arguments error
The following code attempts to send a POST API request with a payload that is in RequestDetails.FormData. When I run main.go function, then I get the following errors.

```<code>go run main.go
# command-line-arguments
./main.go:53:17: not enough arguments in call to http.HandleFunc
./main.go:53:33: not enough arguments in call to reqDetails.Send
        have ()
        want (http.ResponseWriter, *http.Request)
./main.go:53:33: reqDetails.Send() used as value
</code>```

The code is available below. Anybody knows what I could do wrong here? Thanks a lot for your help.

```<code>//main.go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

// RequestDetails contains input data for Send
type RequestDetails struct {
    EndPoint string
    FormType string
    FormData map[string]string
}

// Send sends API POST request to an endpoint
func (rd RequestDetails) Send(w http.ResponseWriter, r *http.Request) {

    json_data, err := json.Marshal(rd.FormData)

    if err != nil {
        log.Fatal(err)
    }

    resp, err := http.Post(rd.EndPoint, rd.FormType, bytes.NewBuffer(json_data))

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp)

}

func main() {
    m := map[string]string{
        "AuthParamOne":   "AP0000001",
        "AuthParamTwo":   "AP0000002",
        "AuthParamThree": "AP0000003",
    }

    reqDetails := RequestDetails{
        EndPoint: "https://httpbin.org/post",
        FormType: "application/json",
        FormData: m,
    }

    http.HandleFunc(reqDetails.Send())
}
</code>```

答:
In your Send method, you don't make use of w http.ResponseWriter, r *http.Request, So it seems you don't need them:

```<code>func (rd RequestDetails) Send() {...
</code>```

Also in your last line, HandleFunc requires different arguments which once again is not necessary in your case. Just try to run the Send method:

```<code>reqDetails.Send()
</code>```

The whole main.go file:

```<code>//main.go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

// RequestDetails contains input data for Send
type RequestDetails struct {
    EndPoint string
    FormType string
    FormData map[string]string
}

// Send sends API POST request to an endpoint
func (rd RequestDetails) Send() {

    json_data, err := json.Marshal(rd.FormData)

    if err != nil {
        log.Fatal(err)
    }

    resp, err := http.Post(rd.EndPoint, rd.FormType, bytes.NewBuffer(json_data))

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp)

}

func main() {
    m := map[string]string{
        "AuthParamOne":   "AP0000001",
        "AuthParamTwo":   "AP0000002",
        "AuthParamThree": "AP0000003",
    }

    reqDetails := RequestDetails{
        EndPoint: "https://httpbin.org/post",
        FormType: "application/json",
        FormData: m,
    }

    reqDetails.Send()
}
</code>```

Body:
The following code attempts to send a POST API request with a payload that is in RequestDetails.FormData. When I run main.go function, then I get the following errors.

go run main.go
# command-line-arguments
./main.go:53:17: not enough arguments in call to http.HandleFunc
./main.go:53:33: not enough arguments in call to reqDetails.Send
        have ()
        want (http.ResponseWriter, *http.Request)
./main.go:53:33: reqDetails.Send() used as value

The code is available below. Anybody knows what I could do wrong here? Thanks a lot for your help.

//main.go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

// RequestDetails contains input data for Send
type RequestDetails struct {
    EndPoint string
    FormType string
    FormData map[string]string
}

// Send sends API POST request to an endpoint
func (rd RequestDetails) Send(w http.ResponseWriter, r *http.Request) {

    json_data, err := json.Marshal(rd.FormData)

    if err != nil {
        log.Fatal(err)
    }

    resp, err := http.Post(rd.EndPoint, rd.FormType, bytes.NewBuffer(json_data))

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp)

}

func main() {
    m := map[string]string{
        "AuthParamOne":   "AP0000001",
        "AuthParamTwo":   "AP0000002",
        "AuthParamThree": "AP0000003",
    }

    reqDetails := RequestDetails{
        EndPoint: "https://httpbin.org/post",
        FormType: "application/json",
        FormData: m,
    }

    http.HandleFunc(reqDetails.Send())
}

Body:
In your Send method, you don't make use of w http.ResponseWriter, r *http.Request, So it seems you don't need them:

func (rd RequestDetails) Send() {...

Also in your last line, HandleFunc requires different arguments which once again is not necessary in your case. Just try to run the Send method:

reqDetails.Send()

The whole main.go file:

//main.go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

// RequestDetails contains input data for Send
type RequestDetails struct {
    EndPoint string
    FormType string
    FormData map[string]string
}

// Send sends API POST request to an endpoint
func (rd RequestDetails) Send() {

    json_data, err := json.Marshal(rd.FormData)

    if err != nil {
        log.Fatal(err)
    }

    resp, err := http.Post(rd.EndPoint, rd.FormType, bytes.NewBuffer(json_data))

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp)

}

func main() {
    m := map[string]string{
        "AuthParamOne":   "AP0000001",
        "AuthParamTwo":   "AP0000002",
        "AuthParamThree": "AP0000003",
    }

    reqDetails := RequestDetails{
        EndPoint: "https://httpbin.org/post",
        FormType: "application/json",
        FormData: m,
    }

    reqDetails.Send()
}