问:
pip-compile raising AssertionError on its logging handler
I have a dockerfile that currently only installs pip-tools

```<code>FROM python:3.9

RUN pip install --upgrade pip && \
    pip install pip-tools

COPY ./ /root/project

WORKDIR /root/project

ENTRYPOINT ["tail", "-f", "/dev/null"]
</code>```

I build and open a shell in the container using the following commands:

```<code>docker build -t brunoapi_image .
docker run --rm -ti --name brunoapi_container --entrypoint bash brunoapi_image
</code>```

Then, when I try to run pip-compile inside the container I get this very weird error (full traceback):

```<code>root@727f1f38f095:~/project# pip-compile
Traceback (most recent call last):
  File "/usr/local/bin/pip-compile", line 8, in <module>
    sys.exit(cli())
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1128, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1053, in main
    rv = self.invoke(ctx)
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1395, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 754, in invoke
    return __callback(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/click/decorators.py", line 26, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/piptools/scripts/compile.py", line 342, in cli
    repository = PyPIRepository(pip_args, cache_dir=cache_dir)
  File "/usr/local/lib/python3.9/site-packages/piptools/repositories/pypi.py", line 106, in __init__
    self._setup_logging()
  File "/usr/local/lib/python3.9/site-packages/piptools/repositories/pypi.py", line 455, in _setup_logging
    assert isinstance(handler, logging.StreamHandler)
AssertionError
</code>```

I have no clue what's going on and I've never seen this error before. Can anyone shed some light into this?

Running on macOS Monterey

答:
```<code>pip install --upgrade pip-tools
</code>```

updating pip-tools is what fixed it for me

Body:
I have a dockerfile that currently only installs pip-tools

FROM python:3.9

RUN pip install --upgrade pip && \
    pip install pip-tools

COPY ./ /root/project

WORKDIR /root/project

ENTRYPOINT ["tail", "-f", "/dev/null"]

I build and open a shell in the container using the following commands:

docker build -t brunoapi_image .
docker run --rm -ti --name brunoapi_container --entrypoint bash brunoapi_image

Then, when I try to run pip-compile inside the container I get this very weird error (full traceback):

root@727f1f38f095:~/project# pip-compile
Traceback (most recent call last):
  File "/usr/local/bin/pip-compile", line 8, in <module>
    sys.exit(cli())
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1128, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1053, in main
    rv = self.invoke(ctx)
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1395, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/lib/python3.9/site-packages/click/core.py", line 754, in invoke
    return __callback(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/click/decorators.py", line 26, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/piptools/scripts/compile.py", line 342, in cli
    repository = PyPIRepository(pip_args, cache_dir=cache_dir)
  File "/usr/local/lib/python3.9/site-packages/piptools/repositories/pypi.py", line 106, in __init__
    self._setup_logging()
  File "/usr/local/lib/python3.9/site-packages/piptools/repositories/pypi.py", line 455, in _setup_logging
    assert isinstance(handler, logging.StreamHandler)
AssertionError

I have no clue what's going on and I've never seen this error before. Can anyone shed some light into this?

Running on macOS Monterey

Body:
pip install --upgrade pip-tools

updating pip-tools is what fixed it for me


来源: stackexchange

问:
SQL Query to get the count of events in the last 30days per user based on the max date
I have an event table that looks like this.

```<code>
| id | event_id| date       |
|----|---------|------------|
| 1  | d-paiin | 28/01/2022 |
| 1  | 123gin  | 02/01/2022 |
| 1  | dhsdel  | 01/01/2022 |
| 1  | sigshwy | 31/12/2021 |
| 1  | dsiwuef | 31/12/2021 |
| 2  | shau346 | 10/02/2022 |
| 2  | akdnjsfm| 04/02/2022 |
| 2  | asjufbe | 04/02/2022 |
| 2  | jladiurn| 01/02/2022 |

</code>```

I want to write a query that finds  id and  their number of events in the last 30days using the MAX Date of each user as a reference point. i.e count of event per id where date > (MAX(Date) of each user) - 30 days.

Expected result looks like this:

```<code>
| id | count_event|
| 1  | 5          |
| 2  | 4          |

</code>```

Thanks.

答:
If by MAX(Date) of each user you mean the current date at a given time when the user accesses the system, this code works just fine:

```<code>SELECT      id,
            COUNT(id) AS count_event
FROM        tablename
WHERE       DATEDIFF(hour, SYSDATE(), tablename.date) < 30
GROUP BY    id;
</code>```

You can also use GETDATE() instead of SYSDATE() for current time.

ContentLicense: CC BY-SA 4.0

Body:
I have an event table that looks like this.

| id | event_id| date       |
|----|---------|------------|
| 1  | d-paiin | 28/01/2022 |
| 1  | 123gin  | 02/01/2022 |
| 1  | dhsdel  | 01/01/2022 |
| 1  | sigshwy | 31/12/2021 |
| 1  | dsiwuef | 31/12/2021 |
| 2  | shau346 | 10/02/2022 |
| 2  | akdnjsfm| 04/02/2022 |
| 2  | asjufbe | 04/02/2022 |
| 2  | jladiurn| 01/02/2022 |

I want to write a query that finds  id and  their number of events in the last 30days using the MAX Date of each user as a reference point. i.e count of event per id where date > (MAX(Date) of each user) - 30 days.

Expected result looks like this:

| id | count_event|
| 1  | 5          |
| 2  | 4          |

Thanks.

Body:
If by MAX(Date) of each user you mean the current date at a given time when the user accesses the system, this code works just fine:

SELECT      id,
            COUNT(id) AS count_event
FROM        tablename
WHERE       DATEDIFF(hour, SYSDATE(), tablename.date) < 30
GROUP BY    id;

You can also use GETDATE() instead of SYSDATE() for current time.


问:
get all Index on mongodb deployment
Please help me with the mongodb query, which will return all the index in the mongodb deployment .
Also , this query will exclude the views and takes only the collection . please help on the same .

below command works, but fails on dealing with "views" .

```<code>test01_rs:PRIMARY>  db.adminCommand('listDatabases').databases.forEach(function(e){ if ((e.name == "admin" || e.name == "config" || e.name == "local")) return; var database=e.name; context=db.getSiblingDB(database); context.getCollectionNames().forEach(function(collection){ records=context.getCollection(collection).aggregate( [ { $indexStats: { } }, { "$group" : { _id : { name: "$name"}, accesses:{$sum:"$accesses.ops"}, since:{$min:"$accesses.since"}, } }, { "$project": { _id:0, name:"$_id.name", since:{ $dateToString: { format: "%Y-%m-%d-%H:%M:%S", date: "$since" } }, accesses:"$accesses", } } ] ).forEach(function(index){ idx=index.name; since=index.since; accesses=index.accesses; print(database+";"+collection+";"+idx+";"+since+";"+accesses); }); }); });
</code>```

Test03;fahed;id;2022-01-10-17:31:26;0
Test04;fahed;id;2022-01-10-17:31:26;0
Test05;fahed;id;2022-01-10-17:31:26;0

thanks,
Fahed

答:
Option 1:

```<code>db.adminCommand( { listDatabases: 1 } ).databases.forEach(
    function(d){
      print('databaseName:'+d.name);
      db.getSiblingDB(d.name).getCollectionInfos({type:"collection"}).forEach(
        function(collection){ indexes =
          db.getSiblingDB(d.name).getCollection(collection.name).getIndexes();
          print("Indexes on "+d.name+"."+ collection.name + ":");
          printjson(indexes)
         })
      })
</code>```

this will provide you output like:

```<code> databaseName:x
 Indexes on x.col1:
 [ { v: 2, key: { _id: 1 }, name: '_id_' } ]
 databaseName:y
 Indexes on y.col2:
 [ { v: 2, key: { _id: 1 }, name: '_id_' } ]
</code>```

Explained:

Get array with list of database names with listDatabase:1 command.

Loop on the provided database list and getCOllectionInfos ( filtering only collections of type: collection to exclude views )

Loop on the list of provided collections and execute getIndexes() to list all indices as requested.

tested with mongosh 0.12.1 / mongod 4.4.12

Option 2:

```<code>    db.adminCommand( { listDatabases: 1 } ).databases.forEach(function(d){ print('databaseName:'+d.name);db.getSiblingDB(d.name).getCollectionInfos({type:"collection"}).forEach(function(collection){ indexes = db.getSiblingDB(d.name).getCollection(collection.name).aggregate([ {$indexStats:{}} ]); indexes.forEach(function(idx){   print("Indexes on "+d.name+"."+ collection.name + ": idx:"+idx.name+" ,since:"+idx.accesses.since+" accesses:"+idx.accesses.ops  ); } )    }) })
</code>```

for this option you will need to add some additional privilges to your user ...

Here index details taken from $indexStats containing since access

Title: get all Index on mongodb deployment

Body:
Please help me with the mongodb query, which will return all the index in the mongodb deployment .
Also , this query will exclude the views and takes only the collection . please help on the same .

below command works, but fails on dealing with "views" .

test01_rs:PRIMARY>  db.adminCommand('listDatabases').databases.forEach(function(e){ if ((e.name == "admin" || e.name == "config" || e.name == "local")) return; var database=e.name; context=db.getSiblingDB(database); context.getCollectionNames().forEach(function(collection){ records=context.getCollection(collection).aggregate( [ { $indexStats: { } }, { "$group" : { _id : { name: "$name"}, accesses:{$sum:"$accesses.ops"}, since:{$min:"$accesses.since"}, } }, { "$project": { _id:0, name:"$_id.name", since:{ $dateToString: { format: "%Y-%m-%d-%H:%M:%S", date: "$since" } }, accesses:"$accesses", } } ] ).forEach(function(index){ idx=index.name; since=index.since; accesses=index.accesses; print(database+";"+collection+";"+idx+";"+since+";"+accesses); }); }); });

Test03;fahed;id;2022-01-10-17:31:26;0
Test04;fahed;id;2022-01-10-17:31:26;0
Test05;fahed;id;2022-01-10-17:31:26;0

thanks,
Fahed

Body:
Option 1:

db.adminCommand( { listDatabases: 1 } ).databases.forEach(
    function(d){
      print('databaseName:'+d.name);
      db.getSiblingDB(d.name).getCollectionInfos({type:"collection"}).forEach(
        function(collection){ indexes =
          db.getSiblingDB(d.name).getCollection(collection.name).getIndexes();
          print("Indexes on "+d.name+"."+ collection.name + ":");
          printjson(indexes)
         })
      })

this will provide you output like:

 databaseName:x
 Indexes on x.col1:
 [ { v: 2, key: { _id: 1 }, name: '_id_' } ]
 databaseName:y
 Indexes on y.col2:
 [ { v: 2, key: { _id: 1 }, name: '_id_' } ]

Explained:

Get array with list of database names with listDatabase:1 command.

Loop on the provided database list and getCOllectionInfos ( filtering only collections of type: collection to exclude views )

Loop on the list of provided collections and execute getIndexes() to list all indices as requested.

tested with mongosh 0.12.1 / mongod 4.4.12

Option 2:

    db.adminCommand( { listDatabases: 1 } ).databases.forEach(function(d){ print('databaseName:'+d.name);db.getSiblingDB(d.name).getCollectionInfos({type:"collection"}).forEach(function(collection){ indexes = db.getSiblingDB(d.name).getCollection(collection.name).aggregate([ {$indexStats:{}} ]); indexes.forEach(function(idx){   print("Indexes on "+d.name+"."+ collection.name + ": idx:"+idx.name+" ,since:"+idx.accesses.since+" accesses:"+idx.accesses.ops  ); } )    }) })

for this option you will need to add some additional privilges to your user ...

Here index details taken from $indexStats containing since access


问:
Adding days to getDate function in JavaScript
I have this function to select the date which works fine

```<code>formatDateField(event: Date, formControl: string) {
    this.form
      .get(formControl)
      .patchValue(
        this.datePipe.transform(event.getTime(), "yyyy-MM-dd'T'HH:mm:ss")
      );
  }
</code>```

I added a button to add the days to it using this code below but says undefined in developers tool > console:

```<code>  addDaysToDateForm(formName: string, days: number) {
    let formDate: Date = this.form.get(formName).value || new Date();
    formDate.setDate(formDate.getDate() + days);
    this.form.get(formName).setValue(formDate);
  }
  setTodayForm(formName: string) {
    this.form.get(formName).setValue(new Date());
  }
</code>```

Any idea what's wrong with it?

答: We don't have Typed Forms (just yet) so values returned from form values aren't typed (as @T.J.Crowder says in the comments). You can convert the value returned from this.form.get(formName).value to a date by calling new Date() on it. i.e. new Date(this.form.get(formName).value)

Body:
I have this function to select the date which works fine

formatDateField(event: Date, formControl: string) {
    this.form
      .get(formControl)
      .patchValue(
        this.datePipe.transform(event.getTime(), "yyyy-MM-dd'T'HH:mm:ss")
      );
  }

I added a button to add the days to it using this code below but says undefined in developers tool > console:

  addDaysToDateForm(formName: string, days: number) {
    let formDate: Date = this.form.get(formName).value || new Date();
    formDate.setDate(formDate.getDate() + days);
    this.form.get(formName).setValue(formDate);
  }
  setTodayForm(formName: string) {
    this.form.get(formName).setValue(new Date());
  }

Any idea what's wrong with it?


问:
Selenium get only child elements from current parent
I'm trying to get data from an HTML like this:

...

...

 ...

```
<p>The goal is to get the <code><li></code> values from every <code><h4></code>. To get this I've tried something like this:</p>
<pre class="lang-py prettyprint-override"><code>divs = driver.find_elements_by_xpath("//div//h4[starts-with(@id,'id_')]")
for h4 in divs:
    title = h4.text
    # Get <li> from each div
    for value in h4._parent.find_elements_by_tag_name('li'): #<-- It gives me all <li> in the page
        # TODO ...
</code>```

Here I'm trying to get all
 tags and then go to the parent (the
) and find the
 tags existing only in that parent. But I retrieve all
 tags.

I've searched over the internet and I've found a couple of question in StackOverflow like Get child element using xpath selenium python or selenium find child's child elements where it says to set the context, so I've tried this:

for value in h4._parent.find_elements_by_xpath('.//li'):
                                                 ^
```

But it gives me the same numbers of elements.

So, I'm misunderstanding something?

Thanks in advance.

答:
```<code>//div[./h4[starts-with(@id,'id')]]//li
</code>```

To get all li's of all div that contains an element h4 with a certain id starting try this.

//div[./h4] basically means div with h4 element inside 1 layer deep.

Body:
I'm trying to get data from an HTML like this:

...

...

 ...

The goal is to get the
 values from every
. To get this I've tried something like this:

divs = driver.find_elements_by_xpath("//div//h4[starts-with(@id,'id_')]")
for h4 in divs:
    title = h4.text
    # Get
 from each div
    for value in h4._parent.find_elements_by_tag_name('li'): #<-- It gives me all
 in the page
        # TODO ...

Here I'm trying to get all
 tags and then go to the parent (the
) and find the
 tags existing only in that parent. But I retrieve all
 tags.

I've searched over the internet and I've found a couple of question in StackOverflow like Get child element using xpath selenium python or selenium find child's child elements where it says to set the context, so I've tried this:

for value in h4._parent.find_elements_by_xpath('.//li'):
                                                 ^

But it gives me the same numbers of elements.

So, I'm misunderstanding something?

Thanks in advance.

Body:
//div[./h4[starts-with(@id,'id')]]//li

To get all li's of all div that contains an element h4 with a certain id starting try this.

//div[./h4] basically means div with h4 element inside 1 layer deep.


问:
Get content of an element following element with some content
I have to get values from HTML document, I can't use full xpath expression because my script would be more vulnerable in case of change in original document. Here is what the html file looks like:

```<code><div id="wrapper">
    <div class="block">
        <div class="title">Kind:</div>
        <div class="value">
            <a href="http://google.com">Book</a>
        </div>

        ...
    </div>
</div>
</code>```

The idea what I need to do to get Book is to get the content of the a subnode of the node following the node with content of Kind:. Can it be done with a single xpath expression?

答:
You can use this XPath:

```<code>//div[. = 'Kind:']/following-sibling::div/a/text()
</code>```

It will select div/a/text() with preceding div with content Kind:

ContentLicense: CC BY-SA 3.0

Body:
I have to get values from HTML document, I can't use full xpath expression because my script would be more vulnerable in case of change in original document. Here is what the html file looks like:

Kind:

            Book

        ...

The idea what I need to do to get Book is to get the content of the a subnode of the node following the node with content of Kind:. Can it be done with a single xpath expression?

Body:
You can use this XPath:

//div[. = 'Kind:']/following-sibling::div/a/text()

It will select div/a/text() with preceding div with content Kind:


问:
What Postgres query can i expand the array of json column and have each field in the array as a row?

[
   {
      "id":"193",
      "duration":0,
      "count":32,
      "date":"2021-11-10T18:55:00+05:30",
      "period_end":"2022-01-11T00:00:00.000Z",
      "started_at":"2021-11-10T18:55:00+05:30",
      "ended_at":"2021-11-10T19:45:00+05:30"
   }
]
```

I'm trying to have each of those object keys as a row. can anyone help?

答:
I think each as a column would be more usable, but you asked for each as a row, so you could UNION a bunch of queries such as this:

```<code>    select 1, info ->> 'id'
    from table1
    union
    select 2, info ->> 'duration'
    from table1
    union
    select 3, info ->> 'count'
    from table1
    union
    select 4, info ->> 'date'
    from table1
    union
    select 5, info ->> 'period_end'
    from table1
    union
    select 6, info ->> 'started_at'
    from table1
    union
    select 7, info ->> 'ended_at'
    from table1
    order by 1
</code>```

Output:

```<code>    1   193
    2   0
    3   32
    4   2021-11-10T18:55:00+05:30
    5   2022-01-11T00:00:00.000Z
    6   2021-11-10T18:55:00+05:30
    7   2021-11-10T19:45:00+05:30
</code>```

Body:
[
   {
      "id":"193",
      "duration":0,
      "count":32,
      "date":"2021-11-10T18:55:00+05:30",
      "period_end":"2022-01-11T00:00:00.000Z",
      "started_at":"2021-11-10T18:55:00+05:30",
      "ended_at":"2021-11-10T19:45:00+05:30"
   }
]

I'm trying to have each of those object keys as a row. can anyone help?

Body:
I think each as a column would be more usable, but you asked for each as a row, so you could UNION a bunch of queries such as this:

    select 1, info ->> 'id'
    from table1
    union
    select 2, info ->> 'duration'
    from table1
    union
    select 3, info ->> 'count'
    from table1
    union
    select 4, info ->> 'date'
    from table1
    union
    select 5, info ->> 'period_end'
    from table1
    union
    select 6, info ->> 'started_at'
    from table1
    union
    select 7, info ->> 'ended_at'
    from table1
    order by 1

Output:

    1   193
    2   0
    3   32
    4   2021-11-10T18:55:00+05:30
    5   2022-01-11T00:00:00.000Z
    6   2021-11-10T18:55:00+05:30
    7   2021-11-10T19:45:00+05:30


问:
Adding illegal null derefernce to xv6
I am attempting to make dereferencing null pointers illegal in my build of xv6. In order to accomplish this, I have made the following changes to the source code:

changed sz = 0 to sz = PGSIZE on exec.c:42

changed i = 0 to i = PGSIZE in the function copyuvm() on vm.c:327

added i == 0 to the or conditional in function agrptr() on syscall.c:66

set entrypoint for user code 0x1000 in Makefile:149&156

When I attempt to run xv6 in qemu with these modifications, I get the warning "panic: loaduvm: address should exist" When I run the debugger, this happens the first time loaduvm() is called by the first instance of exec(). If anyone has any pointers as to what I am missing, it would be much appreciated.

答: Please add -Ttext 0x1000 in _forktest target of Makefile

Title: Adding illegal null derefernce to xv6


问:
How to make a custom exception class with multiple init args pickleable
Why does my custom Exception class below not serialize/unserialize correctly using the pickle module?

```<code>import pickle

class MyException(Exception):
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

        super(MyException, self).__init__(arg1)

e = MyException("foo", "bar")

str = pickle.dumps(e)
obj = pickle.loads(str)
</code>```

This code throws the following error:

```<code>Traceback (most recent call last):
File "test.py", line 13, in <module>
   obj = pickle.loads(str)
File "/usr/lib/python2.7/pickle.py", line 1382, in loads
   return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
   dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1133, in load_reduce
   value = func(*args)
TypeError: __init__() takes exactly 3 arguments (2 given)
</code>```

I'm sure this problem stems from a lack of knowledge on my part of how to make a class pickle-friendly. Interestingly, this problem doesn't occur when my class doesn't extend Exception.

Thanks for any help.
Kyle

EDIT: Fixing my call to super per shx2
EDIT: Cleaning up title/content

答:
I was able to get a custom exception with keyword-only arguments to work with pickling like this:

class CustomException(Exception):
    def __init__(self, arg1, *, kwonly):
        super().__init__(arg1, kwonly) # makes self.args == (arg1, kwonly)
        self.arg1 = arg1
        self.kwonly = kwonly

    def __str__(self):
        # Logic here to turn the args into the real exception message
        return f"{self.arg1} ({self.kwonly})"

    # __repr__ and __eq__ are not needed but are nice for testing
    def __repr__(self):
        return f"{self.__class__.__name__}({self.arg1!r}, kwonly={self.kwonly!r})"

    def __eq__(self, other):
        return isinstance(other, CustomException) and self.args == other.args

    # This is what makes pickling work
    @classmethod
    def _new(cls, arg1, kwonly):
        return cls(arg1, kwonly=kwonly)

    def __reduce__(self):
        return (self._new, (self.arg1, self.kwonly))
```
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>import pickle

w = CustomException('arg1', kwonly='kwonly')
w2 = pickle.loads(pickle.dumps(w))
assert w == w2
</code>```

By the way, this also works with custom warning classes, since those are also Exception subclasses.

Body:
Why does my custom Exception class below not serialize/unserialize correctly using the pickle module?

import pickle

class MyException(Exception):
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

        super(MyException, self).__init__(arg1)

e = MyException("foo", "bar")

str = pickle.dumps(e)
obj = pickle.loads(str)

This code throws the following error:

Traceback (most recent call last):
File "test.py", line 13, in <module>
   obj = pickle.loads(str)
File "/usr/lib/python2.7/pickle.py", line 1382, in loads
   return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
   dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1133, in load_reduce
   value = func(*args)
TypeError: __init__() takes exactly 3 arguments (2 given)

I'm sure this problem stems from a lack of knowledge on my part of how to make a class pickle-friendly. Interestingly, this problem doesn't occur when my class doesn't extend Exception.

Thanks for any help.
Kyle

EDIT: Fixing my call to super per shx2
EDIT: Cleaning up title/content

Body:
I was able to get a custom exception with keyword-only arguments to work with pickling like this:

class CustomException(Exception):
    def __init__(self, arg1, *, kwonly):
        super().__init__(arg1, kwonly) # makes self.args == (arg1, kwonly)
        self.arg1 = arg1
        self.kwonly = kwonly

    def __str__(self):
        # Logic here to turn the args into the real exception message
        return f"{self.arg1} ({self.kwonly})"

    # __repr__ and __eq__ are not needed but are nice for testing
    def __repr__(self):
        return f"{self.__class__.__name__}({self.arg1!r}, kwonly={self.kwonly!r})"

    def __eq__(self, other):
        return isinstance(other, CustomException) and self.args == other.args

    # This is what makes pickling work
    @classmethod
    def _new(cls, arg1, kwonly):
        return cls(arg1, kwonly=kwonly)

    def __reduce__(self):
        return (self._new, (self.arg1, self.kwonly))

Example:

import pickle

w = CustomException('arg1', kwonly='kwonly')
w2 = pickle.loads(pickle.dumps(w))
assert w == w2

By the way, this also works with custom warning classes, since those are also Exception subclasses.


问:
window.onscroll from webpage not working on react-native-webview
I'm currently using https://github.com/react-native-webview/react-native-webview for a website to load within the app. The app is essentially a glorified website so everything in implemented on webapp.

Anyway, I've bunch of stylings changes based on window.onscroll function in webapp.
Obviously they work just fine when loaded from browser, whether it be mobile or desktop.

My problem is the react native web view doesn't respond to any of those functions from window.onscroll.
I tried to do something like injectJavaScript inside  but there are many on scroll functions and that will basically mean i am replicating same thing from web to ReactNative just to inject JS. Even then, some variables are dynamic so injectJavaScript essentioally woudln't work unless that injected JS triggers on scroll function somehow.

How can I solve this issue?

TLDR; window.onscroll function on webview is not being triggered when loaded from webview.

答:
It was a bug from google.
Android System WebView was having problem this few time but it was fixed on February 1. That's what I mean.

Kindly go on playstore and search for Android System WebView and update it and try again


问:
Using chrome version is 98 and chromedriver 98.0.4758.80 . selenium version is 3.141.59. Still error
```<code>Starting ChromeDriver 98.0.4758.80 (7f0488e8ba0d8e019187c6325a16c29d9b7f4989-refs/branch-heads/4758@{#972}) on port 12326
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
[1644434934.334][SEVERE]: listen() returned an error: An attempt was made to access a socket in a way forbidden by its access permissions. (0x271D)
[1644434934.335][SEVERE]: bind() returned an error: An attempt was made to access a socket in a way forbidden by its access permissions. (0x271D)
Unable to start server with either IPv4 or IPv6. Exiting...
Feb 10, 2022 12:59:14 AM org.openqa.selenium.os.OsProcess checkForError
SEVERE: org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-UJJ98PR', ip: '192.168.45.184', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_301'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:202)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:188)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at pack1.Test.main(Test.java:9)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:12326/status] to be available after 20009 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:197)
    ... 9 more
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
    ... 10 more
</code>```

答:
This part

```<code>[1644434934.334][SEVERE]: listen() returned an error: An attempt was made to access a socket in a way forbidden by its access permissions. (0x271D)
[1644434934.335][SEVERE]: bind() returned an error: An attempt was made to access a socket in a way forbidden by its access permissions. (0x271D)
</code>```

suggests that Chrome driver cannot start listening on local port 12326 because it seems to be already taken by another process. This port should normally be selected randomly from a pool of free ports, so the question raises if you by any chance configured Chrome driver to listen on hardcoded port, and now are facing problems with multiple instances running at the same time.

Also, may be caused by security settings of the system (strict firewall/antivirus policies, etc).

Body:
This part

[1644434934.334][SEVERE]: listen() returned an error: An attempt was made to access a socket in a way forbidden by its access permissions. (0x271D)
[1644434934.335][SEVERE]: bind() returned an error: An attempt was made to access a socket in a way forbidden by its access permissions. (0x271D)

suggests that Chrome driver cannot start listening on local port 12326 because it seems to be already taken by another process. This port should normally be selected randomly from a pool of free ports, so the question raises if you by any chance configured Chrome driver to listen on hardcoded port, and now are facing problems with multiple instances running at the same time.

Also, may be caused by security settings of the system (strict firewall/antivirus policies, etc).


问:
java.sql.SQLException: Incorrect string value: '\xAC\xED\x00\x05sr...'
I have code looking like that:

```<code>    @Column(name = COLUMN_DESCRIPTION, columnDefinition = "LONGTEXT")
private Map<Locale, String> description = new HashMap<>();
</code>```

after trying to add something to column i got

```<code>java.sql.SQLException: Incorrect string value: '\xAC\xED\x00\x05sr...' for column 'description' at row 1
</code>```

Where's the problem?

答: It is not necessary a bug. You may try store this object as a blob. Which is a data type in e.g. mysql</p>

Body:
I have code looking like that:

    @Column(name = COLUMN_DESCRIPTION, columnDefinition = "LONGTEXT")
private Map<Locale, String> description = new HashMap<>();

after trying to add something to column i got

java.sql.SQLException: Incorrect string value: '\xAC\xED\x00\x05sr...' for column 'description' at row 1

Where's the problem?


问:
Apache Kafka error on windows - Couldnot find or load main class QuorumPeerMain
I just downloaded Kafka 2.8.0 from Apache website, and I am trying to setup using the instructions given on the website. But when I try to start zookeper server, I am getting below error:

Error: Could not find or load main class org.apache.zookeeper.server.quorum.QuorumPeerMain

My environment is Windows 7 64 bit. I tried to follow below e-mail chain: Apache Email Chain . But still it's having same issue. Can anyone guide me in this? As I am very new to this and couldn't find many information on Google/Apache Kafka email chain.

答:
I was facing the same issue.

Change the JAVA_HOME system variable to the shortened pathname so it contains no space.

Instead of: C:\Program Files\Java\jdk1.8.0_241

Set:  C:\Progra~1\Java\jdk1.8.0_241

This error can happen if any kafka .bat file references a malformed JAVA_HOME variable that contains space.

Setting the shortened pathname to the variable avoids the change to another path that contains no space and solves the problem.


问:
I try API request post with body type raw to get a token but need understand what is wrong
My method to get tokenKey is :

```<code>        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
        httpRequest.Method = "POST";
        httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 OPR/52.0.2871.99";

        string tokenResponse = null;

        HttpClient client = new HttpClient();

        HttpResponseMessage response = null;
        try
        {
            client.DefaultRequestHeaders.Add("x-api-key", "key");
            if (method.Equals("POST"))
            {

                httpRequest.Accept = "application/json";
                httpRequest.ContentType = "application/json";

                var data = @"{""username"":@"""+ login + @""",""password"" :@"""+ password + @"""}";

                using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
                {
                    streamWriter.Write(data);
                }

                var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                  tokenResponse = streamReader.ReadToEnd();
                }
            }
       }
catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

        return tokenResponse;
</code>```

after  var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
this error msg: The underlying connection was closed: Unexpected error on a send.

x-api-key is okay but i don't put the original as the username and password
i do it easy with postman
postman request done

Can anyone help me understand where I'm going wrong?

答:
Could this be a case of mismatch TLS versions? See this answer here:
C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Also it looks like your HttpWebRequest won't have the correct headers, because you are setting them on the HttpClient object instead. The HttpClient also doesn't seem to be being used for this call.

Body:
My method to get tokenKey is :

        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
        httpRequest.Method = "POST";
        httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 OPR/52.0.2871.99";

        string tokenResponse = null;

        HttpClient client = new HttpClient();

        HttpResponseMessage response = null;
        try
        {
            client.DefaultRequestHeaders.Add("x-api-key", "key");
            if (method.Equals("POST"))
            {

                httpRequest.Accept = "application/json";
                httpRequest.ContentType = "application/json";

                var data = @"{""username"":@"""+ login + @""",""password"" :@"""+ password + @"""}";

                using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
                {
                    streamWriter.Write(data);
                }

                var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                  tokenResponse = streamReader.ReadToEnd();
                }
            }
       }
catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

        return tokenResponse;

after  var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
this error msg: The underlying connection was closed: Unexpected error on a send.

x-api-key is okay but i don't put the original as the username and password
i do it easy with postman
postman request done

Can anyone help me understand where I'm going wrong?


问:
How can I edit web scraped text data using python?
Trying to build my first webscraper to print out how the stock market is doing on Yahoo finance. I have found out how to isolate the information I want but it returns super sloppy. How can I manipulate this data to present in an easier way?

```<code>import requests
from bs4 import BeautifulSoup

#Import your website here
html_text = requests.get('https://finance.yahoo.com/').text

soup = BeautifulSoup(html_text, 'lxml')

#Find the part of the webpage where your information is in
sp_market = soup.find('h3', class_ = 'Maw(160px)').text
print(sp_market)
</code>```

The return here is : S&P 5004,587.18+65.64(+1.45%)

I want to grab these elements such as the labels and percentages and isolate them so I can print them in a way I want. Anyone know how? Thanks so much!

edit:
((S&P 500
4,587.18+65.64(+1.45%)))

答:
For simple splitting you could use the .split(separator) method that is built-in. (f.e. First split by 'x', then split by 'y', then split by 'z' with x, y, z being seperators). Since this is not efficient and if you have bit more complex regular expressions that look the same way for different elements (here: stocks) then take a look at the python regex module.

```<code>string = "Stock +45%"
pattern = '[a-z]+[0-9][0-9]'
</code>```

Then, consider to use a function like find_all oder search.

Body:
Trying to build my first webscraper to print out how the stock market is doing on Yahoo finance. I have found out how to isolate the information I want but it returns super sloppy. How can I manipulate this data to present in an easier way?

import requests
from bs4 import BeautifulSoup

#Import your website here
html_text = requests.get('https://finance.yahoo.com/').text

soup = BeautifulSoup(html_text, 'lxml')

#Find the part of the webpage where your information is in
sp_market = soup.find('h3', class_ = 'Maw(160px)').text
print(sp_market)

The return here is : S&P 5004,587.18+65.64(+1.45%)

I want to grab these elements such as the labels and percentages and isolate them so I can print them in a way I want. Anyone know how? Thanks so much!

edit:
((S&P 500
4,587.18+65.64(+1.45%)))

Body:
For simple splitting you could use the .split(separator) method that is built-in. (f.e. First split by 'x', then split by 'y', then split by 'z' with x, y, z being seperators). Since this is not efficient and if you have bit more complex regular expressions that look the same way for different elements (here: stocks) then take a look at the python regex module.

string = "Stock +45%"
pattern = '[a-z]+[0-9][0-9]'

Then, consider to use a function like find_all oder search.


问:
Lisp: Setting element in one row results in setting that element in every row (list of lists)?
I am setting the element at row 1, column 1 of a 2D Matrix represented as a list of lists result in setting all elements at column 1 of the 2D Matrix? It is required that I rerpresent the 2D matrix as a list of lists. Below is my code:

```<code>(defvar matrix (make-list 5 :initial-element (make-list 5)))
(print (format nil "matrix (before) = ~a" matrix))
(setf (nth 1 (nth 1 matrix)) 1)
(print (format nil "matrix (after) = ~a" matrix))
</code>```

With the following output:

"matrix (before) =  ((NIL NIL NIL NIL NIL) (NIL NIL NIL NIL NIL) (NIL
NIL NIL NIL NIL)  (NIL NIL NIL NIL NIL) (NIL NIL NIL NIL NIL))"

"matrix (after) =  ((NIL 1 NIL NIL NIL) (NIL 1 NIL NIL NIL) (NIL 1 NIL
NIL NIL)  (NIL 1 NIL NIL NIL) (NIL 1 NIL NIL NIL))"

This seems strange, considering that I only set an element in the 2D matrix once.

答:
"Setting a value in one object is causing it to appear in other objects" is a problem that occurs when you have perpetrated destructive manipulation in your Lisp program, also known as mutation.

When you mutate objects, you must take great care to ensure that the objects you are not mutating are not shared in ways that will cause surprises.

Many of the cons cell and list manipulating functions in Lisp are optimized toward maximal substructure sharing.

You can see this with a simple example:

```<code>(let* ((list-one (list 2 3 4))
       (list-two (cons 1 list-one)))
  (list list-one list-two))
</code>```

This yields ((2 3 4) (1 2 3 4)). list-1 is (2 3 4) and list-2 is (1 2 3 4).  However, the cons function has allocated only one new cons cell. The (2 3 4) part of list-two is shared structure, coinciding with the list-one object. Thus if we change the code like this:

```<code>(let* ((list-one (list 2 3 4))
       (list-two (cons 1 list-one)))
  (setf (nth 1 list-one) 30)
  (list list-one list-two))
</code>```

The output is:

```<code>((2 30 4) (1 2 30 4))
</code>```

Look, we assigned 30 into the second place of list-one. But this 30 has also showed up in the third place of list-two.

The solution is: debug your code not to do that. In the above example, we can do this:

```<code>(let* ((list-one (list 2 3 4))
       (list-two (cons 1 (copy-list list-one))))
  (setf (second list-one) 30)
  (list list-one list-two))

--> ((2 30 4) (1 2 3 4))
</code>```

We inserted a call to copy-list to make a fresh copy of list-one. This object is then passed to cons, and only to cons. So then we know that list-two is brand new structure, not shared with anything else in the image. When we assign to the second position of list-one, list-two is unaffected.

How has substructure sharing occurred in your program? Let's see:

```<code> (make-list 5 :initial-element (make-list 5)))
                               ^^^^^^^^^^^^^
</code>```

The underlined expression is evaluated once, to produce an object which is passed into the make-list function. The make-list function repeats that object into the five positions of a new list. There is only one object; any change you make to one appears in the others, because there are in fact no others.

We can avoid the substructure sharing by evaluating (make-list 5) five times to create five lists, and collecting them into a list:

```<code>(loop repeat 5 collect (make-list 5))
</code>```

So that is the main strategy in dealing with mutation: to copy constituent objects in order to avoid substructure sharing.

Another strategy is to keep mutation local to a scope: mutate only those objects which did not come from anywhere else, but were just newly created in that piece of code. Then, once those objects are released for other code to use, do not mutate them. For instance, it's a common Lisp idiom to push items onto a local list (which builds up the result in reverse order), and then call nreverse to  destructively reverse the list before returning it. The list is not shared with anything, so usually that code can easily be seen to be correct by inspection.

There is no fixed recipe; in each situation where mutation provides a convenient solution, you have to think about how to best use it, while preventing unwanted effects. Any time you mutate an object, you have to worry about whether that object exists elsewhere.  Which of those elsewheres must see the mutation, which must not see the mutation.

Graphically, your object looks like this:

```<code>matrix ──┐
         │
         ▼
      ┌─────┬─────┐      ┌─────┬─────┐      ┌─────┬─────┐      ┌─────┬─────┐     ┌─────┬─────┐
      │     │     │      │     │     │      │     │     │      │     │     │     │     │     │
      │  @  │  @──┼─────►│  @  │  @──┼─────►│  @  │   @─┼─────►│  @  │  @──┼────►│  @  │ NIL │
      │  │  │     │      │  │  │     │      │  │  │     │      │  │  │     │     │  │  │     │
      └──┼──┴─────┘      └──┼──┴─────┘      └──┼──┴─────┘      └──┼──┴─────┘     └──┼──┴─────┘
         │                  │                  │                  │                 │
         │                  │                  │                  │                 │
         │                  │                  │                  │                 │
         │                  │                  │                  │                 │
         │                  │                  │                  │                 │
         │                  ▼                  ▼                  ▼                 │
         │◄─────────────────────────────────────────────────────────────────────────┘
         │
         │
      ┌──▼──┬─────┐      ┌─────┬─────┐      ┌─────┬─────┐      ┌─────┬─────┐     ┌─────┬─────┐
      │     │     │      │     │     │      │     │     │      │     │     │     │     │     │
      │ NIL │  @──┼─────►│ NIL │  @──┼─────►│ NIL │  @──┼─────►│ NIL │  @──┼────►│ NIL │ NIL │
      │     │     │      │     │     │      │     │     │      │     │     │     │     │     │
      └─────┴─────┘      └─────┴─────┘      └─────┴─────┘      └─────┴─────┘     └─────┴─────┘
</code>```

matrix is a list of five elements, which are all pointers to the same list of five NILs.

Body:
I am setting the element at row 1, column 1 of a 2D Matrix represented as a list of lists result in setting all elements at column 1 of the 2D Matrix? It is required that I rerpresent the 2D matrix as a list of lists. Below is my code:

(defvar matrix (make-list 5 :initial-element (make-list 5)))
(print (format nil "matrix (before) = ~a" matrix))
(setf (nth 1 (nth 1 matrix)) 1)
(print (format nil "matrix (after) = ~a" matrix))

With the following output:

"matrix (before) =  ((NIL NIL NIL NIL NIL) (NIL NIL NIL NIL NIL) (NIL
NIL NIL NIL NIL)  (NIL NIL NIL NIL NIL) (NIL NIL NIL NIL NIL))"

"matrix (after) =  ((NIL 1 NIL NIL NIL) (NIL 1 NIL NIL NIL) (NIL 1 NIL
NIL NIL)  (NIL 1 NIL NIL NIL) (NIL 1 NIL NIL NIL))"

This seems strange, considering that I only set an element in the 2D matrix once.

Body:
"Setting a value in one object is causing it to appear in other objects" is a problem that occurs when you have perpetrated destructive manipulation in your Lisp program, also known as mutation.

When you mutate objects, you must take great care to ensure that the objects you are not mutating are not shared in ways that will cause surprises.

Many of the cons cell and list manipulating functions in Lisp are optimized toward maximal substructure sharing.

You can see this with a simple example:

(let* ((list-one (list 2 3 4))
       (list-two (cons 1 list-one)))
  (list list-one list-two))

This yields ((2 3 4) (1 2 3 4)). list-1 is (2 3 4) and list-2 is (1 2 3 4).  However, the cons function has allocated only one new cons cell. The (2 3 4) part of list-two is shared structure, coinciding with the list-one object. Thus if we change the code like this:

(let* ((list-one (list 2 3 4))
       (list-two (cons 1 list-one)))
  (setf (nth 1 list-one) 30)
  (list list-one list-two))

The output is:

((2 30 4) (1 2 30 4))

Look, we assigned 30 into the second place of list-one. But this 30 has also showed up in the third place of list-two.

The solution is: debug your code not to do that. In the above example, we can do this:

(let* ((list-one (list 2 3 4))
       (list-two (cons 1 (copy-list list-one))))
  (setf (second list-one) 30)
  (list list-one list-two))

--> ((2 30 4) (1 2 3 4))

We inserted a call to copy-list to make a fresh copy of list-one. This object is then passed to cons, and only to cons. So then we know that list-two is brand new structure, not shared with anything else in the image. When we assign to the second position of list-one, list-two is unaffected.

How has substructure sharing occurred in your program? Let's see:

 (make-list 5 :initial-element (make-list 5)))
                               ^^^^^^^^^^^^^

The underlined expression is evaluated once, to produce an object which is passed into the make-list function. The make-list function repeats that object into the five positions of a new list. There is only one object; any change you make to one appears in the others, because there are in fact no others.

We can avoid the substructure sharing by evaluating (make-list 5) five times to create five lists, and collecting them into a list:

(loop repeat 5 collect (make-list 5))

So that is the main strategy in dealing with mutation: to copy constituent objects in order to avoid substructure sharing.

Another strategy is to keep mutation local to a scope: mutate only those objects which did not come from anywhere else, but were just newly created in that piece of code. Then, once those objects are released for other code to use, do not mutate them. For instance, it's a common Lisp idiom to push items onto a local list (which builds up the result in reverse order), and then call nreverse to  destructively reverse the list before returning it. The list is not shared with anything, so usually that code can easily be seen to be correct by inspection.

There is no fixed recipe; in each situation where mutation provides a convenient solution, you have to think about how to best use it, while preventing unwanted effects. Any time you mutate an object, you have to worry about whether that object exists elsewhere.  Which of those elsewheres must see the mutation, which must not see the mutation.

Graphically, your object looks like this:

matrix ──┐
         │
         ▼
      ┌─────┬─────┐      ┌─────┬─────┐      ┌─────┬─────┐      ┌─────┬─────┐     ┌─────┬─────┐
      │     │     │      │     │     │      │     │     │      │     │     │     │     │     │
      │  @  │  @──┼─────►│  @  │  @──┼─────►│  @  │   @─┼─────►│  @  │  @──┼────►│  @  │ NIL │
      │  │  │     │      │  │  │     │      │  │  │     │      │  │  │     │     │  │  │     │
      └──┼──┴─────┘      └──┼──┴─────┘      └──┼──┴─────┘      └──┼──┴─────┘     └──┼──┴─────┘
         │                  │                  │                  │                 │
         │                  │                  │                  │                 │
         │                  │                  │                  │                 │
         │                  │                  │                  │                 │
         │                  │                  │                  │                 │
         │                  ▼                  ▼                  ▼                 │
         │◄─────────────────────────────────────────────────────────────────────────┘
         │
         │
      ┌──▼──┬─────┐      ┌─────┬─────┐      ┌─────┬─────┐      ┌─────┬─────┐     ┌─────┬─────┐
      │     │     │      │     │     │      │     │     │      │     │     │     │     │     │
      │ NIL │  @──┼─────►│ NIL │  @──┼─────►│ NIL │  @──┼─────►│ NIL │  @──┼────►│ NIL │ NIL │
      │     │     │      │     │     │      │     │     │      │     │     │     │     │     │
      └─────┴─────┘      └─────┴─────┘      └─────┴─────┘      └─────┴─────┘     └─────┴─────┘

matrix is a list of five elements, which are all pointers to the same list of five NILs.


问:
jquery insertBefore duplication issue
Using insertBerfore to move an item above another where it appears in many nested DIVs... issue is - its duplicating the item that is being move so I have multiple versions of it... What am I doing wrong here?

I've tried using an each loop and that has the same problem...

I just need the DATE to sit above the TITLE HERE

( function($) {

   function journalIndexFeedItemMetaSwapper() {
    $(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main span.meta-date").insertBefore(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main h3.post-heading");
  }

$(window).load(function() { setTimeout(function(){ journalIndexFeedItemMetaSwapper(); },1000); });

})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE</h3>
<span class="meta-date">DATE</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE</h3>
<span class="meta-date">DATE</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE</h3>
<span class="meta-date">DATE</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE</h3>
<span class="meta-date">DATE</span>
</div>
</div>
</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script></code>```

答:
You're taking all the DATEs and put them all before all the TITLEs.

So you have to put them one-by-one before the corresponding element:

( function($) {

   function journalIndexFeedItemMetaSwapper() {
    $("span.meta-date").each(
      (i, e) => $(e).prev("h3.post-heading").before(e)
    );
  }

$(window).load(function() { setTimeout(function(){ journalIndexFeedItemMetaSwapper(); },1000); });

})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE 1</h3>
<span class="meta-date">DATE 1</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE 2</h3>
<span class="meta-date">DATE 2</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE 3</h3>
<span class="meta-date">DATE 3</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE 4</h3>
<span class="meta-date">DATE 4</span>
</div>
</div>
</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script></code>```

Title: jquery insertBefore duplication issue

Body:
Using insertBerfore to move an item above another where it appears in many nested DIVs... issue is - its duplicating the item that is being move so I have multiple versions of it... What am I doing wrong here?

I've tried using an each loop and that has the same problem...

I just need the DATE to sit above the TITLE HERE

( function($) {

   function journalIndexFeedItemMetaSwapper() {
    $(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main span.meta-date").insertBefore(".journalIndexPostGridFeed .nectar-post-grid .nectar-post-grid-item .item-main h3.post-heading");
  }

$(window).load(function() { setTimeout(function(){ journalIndexFeedItemMetaSwapper(); },1000); });

})(jQuery);

TITLE HERE

DATE

TITLE HERE

DATE

TITLE HERE

DATE

TITLE HERE

DATE

Body:
You're taking all the DATEs and put them all before all the TITLEs.

So you have to put them one-by-one before the corresponding element:

( function($) {

   function journalIndexFeedItemMetaSwapper() {
    $("span.meta-date").each(
      (i, e) => $(e).prev("h3.post-heading").before(e)
    );
  }

$(window).load(function() { setTimeout(function(){ journalIndexFeedItemMetaSwapper(); },1000); });

})(jQuery);

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE 1</h3>
<span class="meta-date">DATE 1</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE 2</h3>
<span class="meta-date">DATE 2</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE 3</h3>
<span class="meta-date">DATE 3</span>
</div>
</div>
</div>
</div>

<div class="journalIndexPostGridFeed">
<div class="nectar-post-grid">
<div class="nectar-post-grid-item">
<div class="item-main">
<h3 class="post-heading">TITLE HERE 4</h3>
<span class="meta-date">DATE 4</span>
</div>
</div>
</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>


问:
How does one modify the package contents output by WooCOmmerce on the checkout page, without modifying plugin code?
In Woocommerce, if I have several shipping methods and suppliers and someone orders several products from one or multiple suppliers, each shipping method will list the items as part of that shipping per supplier, so there is more than one shipping list, e.g. Shipping, Shipping 2 and so on. The items under each shipping block are separated by a comma.

What I want to do is make change the markup so that the items are output as a list. It could be as simple as changing the comma to a line break tag or more involved if I could actually filter the list to generate list tags and all that. Honestly, it doesn't matter, I just want to know if anyone knows what the correct way to do this is because I can't seem to find any hook or filter that even touches this.

I can see where the data is being inserted in the Woocommerce template file /plugins/woocommerce/templates/cart/cart-shipping.php

on line 76

```<code><?php echo '<p class="woocommerce-shipping-contents"><small>' . esc_html( $package_details ) . '</small></p>'; ?>
</code>```

But the section that sets the comma separation is not on a template file it is located in the file /plugins/woocommerce/includes/wc-cart-functions.php

on line 229

```<code> 'package_details'          => implode( ', ', $product_names ),
</code>```

It is part of the function

```<code>/**
* Get shipping methods.
*/

 function wc_cart_totals_shipping_html() {
 $packages = WC()->shipping()->get_packages();
 $first    = true;

 foreach ( $packages as $i => $package ) {
    $chosen_method = isset( WC()->session->chosen_shipping_methods[ $i ] ) ? WC()->session->chosen_shipping_methods[ $i ] : '';
    $product_names = array();

    if ( count( $packages ) > 1 ) {
        foreach ( $package['contents'] as $item_id => $values ) {
            $product_names[ $item_id ] = $values['data']->get_name() . ' ×' . $values['quantity'];
        }
        $product_names = apply_filters( 'woocommerce_shipping_package_details_array', $product_names, $package );
    }

    wc_get_template(
        'cart/cart-shipping.php',
        array(
            'package'                  => $package,
            'available_methods'        => $package['rates'],
            'show_package_details'     => count( $packages ) > 1,
            'show_shipping_calculator' => is_cart() && apply_filters(
            'woocommerce_shipping_show_shipping_calculator', $first, $i, $package ),
            'package_details'          => implode( ', ', $product_names ),
            /* translators: %d: shipping package number */
            'package_name'             => apply_filters( 'woocommerce_shipping_package_name', ( ( $i + 1 ) > 1 ) ? sprintf( _x( 'Shipping %d', 'shipping packages', 'woocommerce' ), ( $i + 1 ) ) : _x( 'Shipping', 'shipping packages', 'woocommerce' ), $i, $package ),
            'index'                    => $i,
            'chosen_method'            => $chosen_method,
            'formatted_destination'    => WC()->countries->get_formatted_address( $package['destination'], ', ' ),
            'has_calculated_shipping'  => WC()->customer->has_calculated_shipping(),
        )
    );

    $first = false;
 }
}
</code>```

答: I ended up following 7uc1f3r's suggestion and overrode the template. I am on mobile so I can't type all the code I used right now, but I basically set the $package_details variable equal to itself with the esc_html function, then again with a string replace to replace the commas with breaks. Then I had the original function echo the variable itself without the esc_html function to keep the breaks intact.</p>

Body:
In Woocommerce, if I have several shipping methods and suppliers and someone orders several products from one or multiple suppliers, each shipping method will list the items as part of that shipping per supplier, so there is more than one shipping list, e.g. Shipping, Shipping 2 and so on. The items under each shipping block are separated by a comma.

What I want to do is make change the markup so that the items are output as a list. It could be as simple as changing the comma to a line break tag or more involved if I could actually filter the list to generate list tags and all that. Honestly, it doesn't matter, I just want to know if anyone knows what the correct way to do this is because I can't seem to find any hook or filter that even touches this.

I can see where the data is being inserted in the Woocommerce template file /plugins/woocommerce/templates/cart/cart-shipping.php

on line 76

<?php echo '
' . esc_html( $package_details ) . '
'; ?>

But the section that sets the comma separation is not on a template file it is located in the file /plugins/woocommerce/includes/wc-cart-functions.php

on line 229

 'package_details'          => implode( ', ', $product_names ),

It is part of the function

/**
* Get shipping methods.
*/

 function wc_cart_totals_shipping_html() {
 $packages = WC()->shipping()->get_packages();
 $first    = true;

 foreach ( $packages as $i => $package ) {
    $chosen_method = isset( WC()->session->chosen_shipping_methods[ $i ] ) ? WC()->session->chosen_shipping_methods[ $i ] : '';
    $product_names = array();

    if ( count( $packages ) > 1 ) {
        foreach ( $package['contents'] as $item_id => $values ) {
            $product_names[ $item_id ] = $values['data']->get_name() . ' ×' . $values['quantity'];
        }
        $product_names = apply_filters( 'woocommerce_shipping_package_details_array', $product_names, $package );
    }

    wc_get_template(
        'cart/cart-shipping.php',
        array(
            'package'                  => $package,
            'available_methods'        => $package['rates'],
            'show_package_details'     => count( $packages ) > 1,
            'show_shipping_calculator' => is_cart() && apply_filters(
            'woocommerce_shipping_show_shipping_calculator', $first, $i, $package ),
            'package_details'          => implode( ', ', $product_names ),
            /* translators: %d: shipping package number */
            'package_name'             => apply_filters( 'woocommerce_shipping_package_name', ( ( $i + 1 ) > 1 ) ? sprintf( _x( 'Shipping %d', 'shipping packages', 'woocommerce' ), ( $i + 1 ) ) : _x( 'Shipping', 'shipping packages', 'woocommerce' ), $i, $package ),
            'index'                    => $i,
            'chosen_method'            => $chosen_method,
            'formatted_destination'    => WC()->countries->get_formatted_address( $package['destination'], ', ' ),
            'has_calculated_shipping'  => WC()->customer->has_calculated_shipping(),
        )
    );

    $first = false;
 }
}


问:
How do I set Access-Control-Allow-Origin on upstream errors in nginx?
I know there are a million answers to "how to set Access-Control-Allow-Origin in nginx" but unfortunately if there's an answer to my specific question, it's buried with all the basic answers.

I have an Angular app pointing to an nginx server with a rest service upstream - all running on my local laptop inside a docker compose.

The nginx service is configured fairly simply:

```<code>    upstream REST {
       # rest-service is mapped by docker-compose to the correct container
       server rest-service:8080;
    }

    server {
        listen 80;
        listen [::]:80;
        # This is mapped in /etc/hosts on my laptop
        server_name rest-api.mylocal.com;

        location / {
            proxy_hide_header 'Access-Control-Allow-Origin';
            # web-ui is also mapped in /etc/hosts on my laptop
            add_header "Access-Control-Allow-Origin" "http://web-ui.mylocal.com";

            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Max-Age' 1728000; # 20 days
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';

            add_header Reverse-Proxy true;
            proxy_set_header X-Real-IP       $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host            $http_host;
            proxy_pass http://REST;
        }
    }
</code>```

If I call a valid URL on the rest service, e.g. http://rest-api.mylocal.com/api/v1/auth/config (this is an unauthenticated endpoint), everything works as expected:

```<code>curl -v 'http://rest-api.mylocal.com/api/v1/auth/config'
...
< Access-Control-Allow-Origin: http://web-ui.mylocal.com
< Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
< Access-Control-Max-Age: 1728000
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: Content-Type, Authorization
< Reverse-Proxy: true
<
* Connection #0 to host rest-api.mylocal.com left intact
{"status":"OK","name":"foo",...}* Closing connection 0
</code>```

However, if I call an invalid URL, say http://rest-api.mylocal.com/api/v1/accounts (which is an authenticated endpoint, and I provide no credentials), I get back the expected error, but there are no CORS headers.  In a browser this causes everything to flake out so I don't even get the error message in Angular to display to the user:

```<code>curl -v 'http://rest-api.mylocal.com/api/v1/accounts'
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to rest-api.mylocal.com (127.0.0.1) port 80 (#0)
> GET /api/v1/accounts HTTP/1.1
> Host: rest-api.mylocal.com
> User-Agent: curl/7.64.1
> Accept: */*
>
< HTTP/1.1 403
< Server: nginx/1.21.6
< Date: Wed, 09 Feb 2022 20:57:49 GMT
< Content-Type: application/json
< Transfer-Encoding: chunked
< Connection: keep-alive
< Set-Cookie: JSESSIONID=F3B21A55841C8E5A6F838F2427A0E22B; Path=/; HttpOnly
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
<
* Connection #0 to host rest-api.mylocal.com left intact
{"timestamp":"2022-02-09T20:57:49.526+00:00","status":403,"error":"Forbidden","message":"Access Denied","path":"/api/v1/accounts"}* Closing connection 0
</code>```

Browser console:

```<code>Access to XMLHttpRequest at 'http://rest-api.mylocal.com/api/v1/accounts' from origin 'http://web-ui.mylocal.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

So... Is there a way to make sure the CORS headers are still added to the response by nginx even if the response from the upstream server is an error (401/403/404/etc)?

答: You need to add always to each header you want added to error responses.  It was added in 1.7.5: https://nginx.org/r/add_header

Body:
I know there are a million answers to "how to set Access-Control-Allow-Origin in nginx" but unfortunately if there's an answer to my specific question, it's buried with all the basic answers.

I have an Angular app pointing to an nginx server with a rest service upstream - all running on my local laptop inside a docker compose.

The nginx service is configured fairly simply:

    upstream REST {
       # rest-service is mapped by docker-compose to the correct container
       server rest-service:8080;
    }

    server {
        listen 80;
        listen [::]:80;
        # This is mapped in /etc/hosts on my laptop
        server_name rest-api.mylocal.com;

        location / {
            proxy_hide_header 'Access-Control-Allow-Origin';
            # web-ui is also mapped in /etc/hosts on my laptop
            add_header "Access-Control-Allow-Origin" "http://web-ui.mylocal.com";

            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Max-Age' 1728000; # 20 days
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';

            add_header Reverse-Proxy true;
            proxy_set_header X-Real-IP       $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host            $http_host;
            proxy_pass http://REST;
        }
    }

If I call a valid URL on the rest service, e.g. http://rest-api.mylocal.com/api/v1/auth/config (this is an unauthenticated endpoint), everything works as expected:

curl -v 'http://rest-api.mylocal.com/api/v1/auth/config'
...
< Access-Control-Allow-Origin: http://web-ui.mylocal.com
< Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
< Access-Control-Max-Age: 1728000
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: Content-Type, Authorization
< Reverse-Proxy: true
<
* Connection #0 to host rest-api.mylocal.com left intact
{"status":"OK","name":"foo",...}* Closing connection 0

However, if I call an invalid URL, say http://rest-api.mylocal.com/api/v1/accounts (which is an authenticated endpoint, and I provide no credentials), I get back the expected error, but there are no CORS headers.  In a browser this causes everything to flake out so I don't even get the error message in Angular to display to the user:

curl -v 'http://rest-api.mylocal.com/api/v1/accounts'
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to rest-api.mylocal.com (127.0.0.1) port 80 (#0)
> GET /api/v1/accounts HTTP/1.1
> Host: rest-api.mylocal.com
> User-Agent: curl/7.64.1
> Accept: */*
>
< HTTP/1.1 403
< Server: nginx/1.21.6
< Date: Wed, 09 Feb 2022 20:57:49 GMT
< Content-Type: application/json
< Transfer-Encoding: chunked
< Connection: keep-alive
< Set-Cookie: JSESSIONID=F3B21A55841C8E5A6F838F2427A0E22B; Path=/; HttpOnly
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
<
* Connection #0 to host rest-api.mylocal.com left intact
{"timestamp":"2022-02-09T20:57:49.526+00:00","status":403,"error":"Forbidden","message":"Access Denied","path":"/api/v1/accounts"}* Closing connection 0

Browser console:

Access to XMLHttpRequest at 'http://rest-api.mylocal.com/api/v1/accounts' from origin 'http://web-ui.mylocal.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

So... Is there a way to make sure the CORS headers are still added to the response by nginx even if the response from the upstream server is an error (401/403/404/etc)?


问:
Find closest elements of two lists - the best way
I have two lists(or columns of dataframe - doesn't matter) of numerical values:

```<code>L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]
</code>```

for example. I need to correlate these lists and find pairs(indexOfElementFromL1, indexOfElementFromL2) which corresponds min diff of two elements. For example, for my example it should be:
(0,1), (1,1), (2,0), (3,2), (4,4). Really what I want - find closest element L2 to each one of L1. Of course I could naive approch like:

```<code>for el1 in L1:
  for el2 in L2:
    ....
</code>```

But I'd to like to see more correct solution

答:
You can use brute force methods using for loops or taking advantage of broadcasting, as you can see in other answers.

The problem comes when the lists are large. If that's the case, for loops will  be slow and broadcasting will take a lot of memory.

The alternative is to use a search algorithm like FLANN:

```<code>>>> import numpy as np
>>> from pyflann import FLANN

>>> L1 = np.array([[1, 0.5, 3, 7, 4.7]]).T      # Data points as rows
>>> L2 = np.array([[2, 0.4, 8, 0.3, 5]]).T

>>> idx, _ = FLANN().nn(pts=L2, qpts=L1)
>>> idx
array([1, 1, 0, 2, 4], dtype=int32)

>>> list(enumerate(idx))
[(0, 1), (1, 1), (2, 0), (3, 2), (4, 4)]
</code>```

Or, if you want to perform multiple queries:

```<code>>>> flann = FLANN()
>>> flann.build_index(pts=L2)           # Build search index
>>> idx, _ = flann.nn_index(qpts=L1)    # Query
</code>```

Body:
I have two lists(or columns of dataframe - doesn't matter) of numerical values:

L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]

for example. I need to correlate these lists and find pairs(indexOfElementFromL1, indexOfElementFromL2) which corresponds min diff of two elements. For example, for my example it should be:
(0,1), (1,1), (2,0), (3,2), (4,4). Really what I want - find closest element L2 to each one of L1. Of course I could naive approch like:

for el1 in L1:
  for el2 in L2:
    ....

But I'd to like to see more correct solution

Body:
You can use brute force methods using for loops or taking advantage of broadcasting, as you can see in other answers.

The problem comes when the lists are large. If that's the case, for loops will  be slow and broadcasting will take a lot of memory.

The alternative is to use a search algorithm like FLANN:

>>> import numpy as np
>>> from pyflann import FLANN

>>> L1 = np.array([[1, 0.5, 3, 7, 4.7]]).T      # Data points as rows
>>> L2 = np.array([[2, 0.4, 8, 0.3, 5]]).T

>>> idx, _ = FLANN().nn(pts=L2, qpts=L1)
>>> idx
array([1, 1, 0, 2, 4], dtype=int32)

>>> list(enumerate(idx))
[(0, 1), (1, 1), (2, 0), (3, 2), (4, 4)]

Or, if you want to perform multiple queries:

>>> flann = FLANN()
>>> flann.build_index(pts=L2)           # Build search index
>>> idx, _ = flann.nn_index(qpts=L1)    # Query


问:
Is there a way to make a count from the child process available to parent process so that the parent process can print it?
I am trying to  use the child process to count characters in a string and then make that count available to the parent process so that the parent process can print it out. After hours of videos and reading I still cant find a way to make something from the child process available to the parent process. Can anyone show an example of something similar to what I am asking.</p>

答:
I think it is important to help ( and it makes me revise ...)

There should be numerous SO posts that can be found like How to get return value from CHILD PROCESS?.

It sounds odd to me to (re)discover that you may only retrieve only a byte from the return value of a process. After all you return only a status and 256 values are enough to express something.

Return values are not intended to retrieve high amount of information.

Even intereting hints like this answer of Return value range of the main function stating that you might get more was not successful on my side.

Return values are int. Size of std::string is size_t.

Nasty teachers may well set the exercice with such huge string of size let's say 100009.

So an easier way for this exercice is to establish a pipe (bridge) between the parent and the child, redefine standard input and output and by the way just use the cin and cout streams.

```<code>#include <iostream>
#include <unistd.h>

enum { read_end = 0, write_end, PIPE_EDGE_NB};

int main(int argc, char* argv[])
{
    int fd[PIPE_EDGE_NB];

    std::string long_str(100009,'*');

    int res = pipe(fd);
    if (0>res) {
        std::cout << "pipe failed\n" << std::flush;
        return -1;
    }

    pid_t pid = fork();
    if (0>pid) {
        std::cout << "fork failed\n" << std::flush;
        return -1;
    }

    switch(pid)
    {
        case 0: {//Child
            auto sz = long_str.size();
            std::cout << "Child says size is " << sz << "\n" << std::flush;
            dup2(fd[write_end],STDOUT_FILENO);
            close(fd[write_end]);
            std::cout << sz << "\n" << std::flush;

            }
            break;

        default:{
            dup2(fd[read_end],STDIN_FILENO);
            close(fd[read_end]);
            size_t received_size;
            try {
                std::cin >> received_size;
            }
            catch(std::exception & ex) {
                std::cout << ex.what() << "\n" << std::flush;
                return -1;
            }
            std::cout << "Parent says size is " << received_size << "\n" << std::flush;
            }
            break;
    }

    return 0;
}
</code>```

Child says size is 100009

Parent says size is 100009

Body:
I think it is important to help ( and it makes me revise ...)

There should be numerous SO posts that can be found like How to get return value from CHILD PROCESS?.

It sounds odd to me to (re)discover that you may only retrieve only a byte from the return value of a process. After all you return only a status and 256 values are enough to express something.

Return values are not intended to retrieve high amount of information.

Even intereting hints like this answer of Return value range of the main function stating that you might get more was not successful on my side.

Return values are int. Size of std::string is size_t.

Nasty teachers may well set the exercice with such huge string of size let's say 100009.

So an easier way for this exercice is to establish a pipe (bridge) between the parent and the child, redefine standard input and output and by the way just use the cin and cout streams.

#include <iostream>
#include <unistd.h>

enum { read_end = 0, write_end, PIPE_EDGE_NB};

int main(int argc, char* argv[])
{
    int fd[PIPE_EDGE_NB];

    std::string long_str(100009,'*');

    int res = pipe(fd);
    if (0>res) {
        std::cout << "pipe failed\n" << std::flush;
        return -1;
    }

    pid_t pid = fork();
    if (0>pid) {
        std::cout << "fork failed\n" << std::flush;
        return -1;
    }

    switch(pid)
    {
        case 0: {//Child
            auto sz = long_str.size();
            std::cout << "Child says size is " << sz << "\n" << std::flush;
            dup2(fd[write_end],STDOUT_FILENO);
            close(fd[write_end]);
            std::cout << sz << "\n" << std::flush;

            }
            break;

        default:{
            dup2(fd[read_end],STDIN_FILENO);
            close(fd[read_end]);
            size_t received_size;
            try {
                std::cin >> received_size;
            }
            catch(std::exception & ex) {
                std::cout << ex.what() << "\n" << std::flush;
                return -1;
            }
            std::cout << "Parent says size is " << received_size << "\n" << std::flush;
            }
            break;
    }

    return 0;
}

Child says size is 100009

Parent says size is 100009


问:
C++ loop until keystroke
If I want to loop until a keystroke there is a quite nice Windows solution:

```<code>while(!kbhit()){
    //...
}
</code>```

But this is neither an ISO-Function nor works on other Operating Systems except MS Win. I found other cross-plattform solutions but they are quite confusing and bloated - isn't there another easy way to manage this?

答: No, C++ standard doesn't define concepts like 'keyboard' and 'keystrokes', because not all systems have such things. Use a portable library, maybe ncurses should have something.</p>

Title: C++ loop until keystroke

Body:
If I want to loop until a keystroke there is a quite nice Windows solution:

while(!kbhit()){
    //...
}

But this is neither an ISO-Function nor works on other Operating Systems except MS Win. I found other cross-plattform solutions but they are quite confusing and bloated - isn't there another easy way to manage this?


问:
Click inside Loop issue - Remove dynamically created elements
The following code takes all the links onto the page that contains "https" and not "google.com" and turns them into iFrames. While that works, the close button that each is iFrame is supposed to be paired with does not work. When you click close, it only closes the last iFrame element on the page. I prefer to be able to do this in vanilla JavaScript, as opposed to jQuery.

total = []
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.href.indexOf("https") != -1 &&
 link.href.indexOf("google.com") == -1) {
    var hey = (links[i].href);
    console.log(link.href);
    total.push(links[i].href);
    var iframe = document.createElement('iframe');
    iframe.src = hey;
    document.body.appendChild(iframe);
    var close = document.createElement('button');
    document.body.appendChild(close);
    close.innerHTML = "close";
    close.addEventListener('click',function(){
      console.log("click");
      document.body.removeChild(iframe);
      document.body.removeChild(close);
    })
  }
}
```

答:
It's a Variable Hoisting issue

where the  var is hoisted to the closest scope, in your case it's window (since you don't have any other parent function wrapper), and reassigned/overridden again and again inside the loop - always leading to the last iterated element.

Quickfix:

var iframe and var close should be defined as const to remain inside the scope of that for loop body:

var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.href.indexOf("https") != -1 && link.href.indexOf("google.com") == -1) {
    const iframe = document.createElement('iframe');  // Quickfix
    iframe.src = links[i].href;
    iframe.id = Math.random();
    document.body.appendChild(iframe);
    const close = document.createElement('button');   // Quickfix
    document.body.appendChild(close);
    close.innerHTML = "close " + link.href;
    close.addEventListener('click', function() {
      document.body.removeChild(iframe);
      document.body.removeChild(close);
    })
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
</code>```

The proper way

not only it's a bad habit to use var nowadays, it's also a bad practice to assign Event handlers inside a for loop. So here's a remake which removed completely the var keyword, uses some nifty reusable DOM utility functions, and at last — the NodeList.prototype.forEach() method:

// DOM utility functions:

const EL    = (sel, par)  => (par || document).querySelector(sel);
const ELS   = (sel, par)  => (par || document).querySelectorAll(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Task:
// Convert all http/s anchors to iframes with a
// button "Delete", wrapped inside a .figure DIV Element

ELS("a").forEach(EL_anchor => {

  const href = EL_anchor.href;

  if (/^https?:\/\/(?:(?:www\.)?google.com)/.test(href)) return;

  const EL_figure = ELNew("div", {className: "figure"});
  const EL_iframe = ELNew("iframe", {src: EL_anchor.href});
  const EL_delete = ELNew("button", {type: "button", textContent: "Delete", onclick() {EL_figure.remove();}});

  EL_figure.append(EL_iframe, EL_delete);
  EL("body").append(EL_figure);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
</code>```

See the above's RegExp Example and desctription on Regex101.com

Body:
It's a Variable Hoisting issue

where the  var is hoisted to the closest scope, in your case it's window (since you don't have any other parent function wrapper), and reassigned/overridden again and again inside the loop - always leading to the last iterated element.

Quickfix:

var iframe and var close should be defined as const to remain inside the scope of that for loop body:

var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.href.indexOf("https") != -1 && link.href.indexOf("google.com") == -1) {
    const iframe = document.createElement('iframe');  // Quickfix
    iframe.src = links[i].href;
    iframe.id = Math.random();
    document.body.appendChild(iframe);
    const close = document.createElement('button');   // Quickfix
    document.body.appendChild(close);
    close.innerHTML = "close " + link.href;
    close.addEventListener('click', function() {
      document.body.removeChild(iframe);
      document.body.removeChild(close);
    })
  }
}

<a href="https://wikipedia.com"></a>
<a href="https://placekitten.com"></a>

The proper way

not only it's a bad habit to use var nowadays, it's also a bad practice to assign Event handlers inside a for loop. So here's a remake which removed completely the var keyword, uses some nifty reusable DOM utility functions, and at last — the NodeList.prototype.forEach() method:

// DOM utility functions:

const EL    = (sel, par)  => (par || document).querySelector(sel);
const ELS   = (sel, par)  => (par || document).querySelectorAll(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Task:
// Convert all http/s anchors to iframes with a
// button "Delete", wrapped inside a .figure DIV Element

ELS("a").forEach(EL_anchor => {

  const href = EL_anchor.href;

  if (/^https?:\/\/(?:(?:www\.)?google.com)/.test(href)) return;

  const EL_figure = ELNew("div", {className: "figure"});
  const EL_iframe = ELNew("iframe", {src: EL_anchor.href});
  const EL_delete = ELNew("button", {type: "button", textContent: "Delete", onclick() {EL_figure.remove();}});

  EL_figure.append(EL_iframe, EL_delete);
  EL("body").append(EL_figure);
});

<a href="https://wikipedia.com"></a>
<a href="https://placekitten.com"></a>

See the above's RegExp Example and desctription on Regex101.com