问:
Sorting Twitter API pages in favorites by time you favorited them not when they were created
Okay, so basically I'm trying to write a program that would go through my twitter favorite history and find pieces of media from them and then download them. I actually have a working model in Python using Tweepy that works it's just it only gets the tweets in order of when they were created. See, the thing is I don't want to download my whole favorite history every time, just up to the point of the last mass download, so at first, I set it up to stop when the tweets reached a certain date. Every time I downloaded I would record the date, but then I realized that sometimes I favorite tweets that are from a while ago, before the cut off date, but is still new to my favorites history. So I decided to try something else, I would record the tweet ID of the first tweet in the list from the last time I downloaded and then set it to stop there, and this would work fine if the api.favorites() returned it in the order it appears on your profile, but instead it auto sorts them by date, so if I fav a post form 2010, I would have to cycle threw all the back to 2010 before it would appear on one of my returned pages. When I looked threw the docs I found a little bit on sorting, but nothing on sorting the Fav Hist by when you faved the tweet. And the thing is I know it stores the order that you liked the tweets in, since that's how it displays it on your profile, even if it is just a table that they append to every time, it still works. I know I'm writing this program in python, but I'm good enough with Java and JavaScript to understand the guts of the API, it's how I got this far. Anyway if you have some suggestions or now how to do it please let me know, any help is appreciated! If all else fails I'll try using Selenium to go through my Twitter Favs from a user perspective...</p>

答: I had the same issue and I found that you can't do this with the regular Twitter API. They have an enterprise API, which requires payment to access, and that will give you the time a tweet was favorited but it doesn't look cheap so it's probably not worth it.</p>


来源: stackexchange

问:
How to disable or auto-select 'OK' on VBA dialogs using Python (Application.DisplayAlerts = False does not work)
I have a script that opens an Excel spreadsheet and then goes to a specific sheet before running a macro. The problem is that this macro brings up different dialog boxes which require user input - I am trying to automate the process. I have tried to get rid of these boxes by using the following code:

```<code>import os
impor win32com.client

xl = win32com.client.Dispatch('Excel.Application')
xl = DisplayAlerts = False #Supposed to disable alert/messages/dialog boxes
wb = xl.Workbooks.Open(os.path.abspath('Test.xlsm'), ReadOnly = 0) #Opens spreadsheet
wb.Worksheets('Assets').Activate() #Activates correct sheet
wb.Application.Run('MxRunAction') #Runs macro
wb.Clost(True)
</code>```

I have read on many threads that:

Application.DisplayAlerts = False

is supposed to fix this problem, yet this seems to do nothing if I substitue Application with xl for my case. Am I using it properly in this sense?

答:
That would be the Application need to be closed</p>

```<code>xl.DisplayAlerts = False
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a script that opens an Excel spreadsheet and then goes to a specific sheet before running a macro. The problem is that this macro brings up different dialog boxes which require user input - I am trying to automate the process. I have tried to get rid of these boxes by using the following code:

import os
impor win32com.client

xl = win32com.client.Dispatch('Excel.Application')
xl = DisplayAlerts = False #Supposed to disable alert/messages/dialog boxes
wb = xl.Workbooks.Open(os.path.abspath('Test.xlsm'), ReadOnly = 0) #Opens spreadsheet
wb.Worksheets('Assets').Activate() #Activates correct sheet
wb.Application.Run('MxRunAction') #Runs macro
wb.Clost(True)

I have read on many threads that:

Application.DisplayAlerts = False

is supposed to fix this problem, yet this seems to do nothing if I substitue Application with xl for my case. Am I using it properly in this sense?

Body:
That would be the Application need to be closed

xl.DisplayAlerts = False


问:
what is wrong in my solution? help me to impove it or any other solution?
A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:

The students must be in the order of non-decreasing height.
Two boys or two girls must not be adjacent to each other.
You have been given the heights of the boys in the array and the heights of the girls in the array. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not.
This one is mine but I am getting the wrong answer in 3 testcases.
here, a is the array of boys height and b is the array of girls.

```<code>a=sorted(a)
b=sorted(b)
i=0
n=len(a)
j=0
x=""

while i<n and j<n:
    if a[i]<b[j]:
        x+="b"
        i+=1
    elif a[i]==b[j]:
        if len(x)==0:
            x+="b"
            i+=1
        elif x[-1]=="b":
            x+="g"
            j+=1
        else:
            x+="b"
            i+=1

    else:
        x+="g"
        j+=1

while i<n:
    x+="b"
    i+=1
while j<n:
    x+="g"
    j+=1

p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)
if q or p:
    return "NO"
else:
    return "YES"
</code>```

答:
```<code>a=sorted(a)
b=sorted(b)
i=0
flag=0
n=len(a)
j=0
x=""

while i<n and j<n:
    if a[i]<b[j]:
        x+="b"
        i+=1
    elif a[i]==b[j]:
        if len(x)==0:
            x+="b"
            flag=1
            i+=1
        elif x[-1]=="b":
            x+="g"
            j+=1
        else:
            x+="b"
            i+=1

    else:
        x+="g"
        j+=1

while i<n:
    x+="b"
    i+=1
while j<n:
    x+="g"
    j+=1

w=re.findall(r"[b]{2}",x)
t=re.findall(r"[g]{2}",x)

if (w or t) and flag==1:
    i=0

    n=len(a)
    j=0
    x=""

    while i<n and j<n:

        if a[i]<b[j]:
            x+="b"
            i+=1
        elif a[i]==b[j]:
            if len(x)==0:
                x+="g"

                j+=1
            elif x[-1]=="b":
                x+="g"
                j+=1
            else:
                x+="b"
                i+=1

        else:
            x+="g"
            j+=1

    while i<n:
        x+="b"
        i+=1
    while j<n:
        x+="g"
        j+=1

    w=re.findall(r"[b]{2}",x)
    t=re.findall(r"[g]{2}",x)
    if w or t:
        return "NO"
    else:
        return 'YES'
elif w or t:
    return "NO"
else:
    return "YES"
</code>```

Body:
A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:

The students must be in the order of non-decreasing height.
Two boys or two girls must not be adjacent to each other.
You have been given the heights of the boys in the array and the heights of the girls in the array. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not.
This one is mine but I am getting the wrong answer in 3 testcases.
here, a is the array of boys height and b is the array of girls.

a=sorted(a)
b=sorted(b)
i=0
n=len(a)
j=0
x=""

while i<n and j<n:
    if a[i]<b[j]:
        x+="b"
        i+=1
    elif a[i]==b[j]:
        if len(x)==0:
            x+="b"
            i+=1
        elif x[-1]=="b":
            x+="g"
            j+=1
        else:
            x+="b"
            i+=1

    else:
        x+="g"
        j+=1

while i<n:
    x+="b"
    i+=1
while j<n:
    x+="g"
    j+=1

p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)
if q or p:
    return "NO"
else:
    return "YES"


问:
how to remove the line if it contain the "word"? in python
I have an input file looks like this

```<code>test.txt
CAT 396 NUM 59
X          Y
4.7642     28.4443
4.7643     28.3640
6.2216     29.0680
6.2217     29.2841
6.4080     28.6427
6.6484     28.6484

CAT 397 NUM 592
X          Y
7.0442     23.8320
7.0994     25.9161
7.0995     25.1801
</code>```

I only need the X and Y coordinate information.

How would I be able to only get the coordinates?

答:
```<code>line = 'some words'
if 'word' in line:
    # skip/delete the line
</code>```

If the line you want to skip is always first, you can just skip the first line, without checking the words inside it.

Body:
I have an input file looks like this

test.txt
CAT 396 NUM 59
X          Y
4.7642     28.4443
4.7643     28.3640
6.2216     29.0680
6.2217     29.2841
6.4080     28.6427
6.6484     28.6484

CAT 397 NUM 592
X          Y
7.0442     23.8320
7.0994     25.9161
7.0995     25.1801

I only need the X and Y coordinate information.

How would I be able to only get the coordinates?

Body:
line = 'some words'
if 'word' in line:
    # skip/delete the line

If the line you want to skip is always first, you can just skip the first line, without checking the words inside it.


问:
mysql syntax ERROR 1064 while creating a trigger
I am creating a trigger for my tables:-
bank
Bank(pin, deposit, withdraw, balance, accno*, sno)
and
balance
Balance(accno*,balance)

I want to update the value of balance in my balance table after insertion in the bank table.
 I am using a MySQL server (wamp64 mysql8.0.18)

```<code>mysql> create trigger update_account
    -> after insert on bank
    -> begin
    -> update balance as a
    -> set a.balance=(case
    -> when new.withdraw=1 then a.balance-new.withdraw
    -> else a.balance+new.withdraw
    -> end)
    -> where a.accno = new.accno;
</code>```

but the above code gives me the following error:-
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update balance a
set a.balance = (case
when new.withdraw=1 then a.balance - new.' at line 3

答:
Your trigger contains ONE statement. So it does NOT need in BEGIN-END block and DELIMITER re-assigning:

CREATE TRIGGER update_account
AFTER INSERT
ON bank
FOR EACH ROW
UPDATE balance
SET balance = balance + new.withdraw + new.deposit
where accno=new.accno;

```

Body:
I am creating a trigger for my tables:-
bank
Bank(pin, deposit, withdraw, balance, accno*, sno)
and
balance
Balance(accno*,balance)

I want to update the value of balance in my balance table after insertion in the bank table.
 I am using a MySQL server (wamp64 mysql8.0.18)

mysql> create trigger update_account
    -> after insert on bank
    -> begin
    -> update balance as a
    -> set a.balance=(case
    -> when new.withdraw=1 then a.balance-new.withdraw
    -> else a.balance+new.withdraw
    -> end)
    -> where a.accno = new.accno;

but the above code gives me the following error:-
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update balance a
set a.balance = (case
when new.withdraw=1 then a.balance - new.' at line 3


问:
Testing Number Theoretic Functions in Haskell using a recursor over natural numbers
I'm implementing some number theoretic functions as the exponentiation in Haskell using a recursor. I'm using the QuickCheck library for testing my implementation.
For simplify my tests, I'm using the Natural data type from the base library, the
Arbitrary instance for Natural defined in the quickcheck-instances library and the
following functions converting from Nat to Natural and from Natural to Nat, respectively, considering the data Nat defined by myself:

```<code>data Nat = Zero | Succ Nat

natToNatural :: Nat -> Natural
natToNatural Zero = 0
natToNatural (Succ n) = 1 + natToNatural n

naturalToNat :: Natural -> Nat
naturalToNat 0 = Zero
naturalToNat n = Succ (naturalToNat (n - 1))
</code>```

The implemetation use the following recursor over natural numbers:

```<code>recNat :: a -> (Nat -> a -> a) -> Nat -> a
recNat a _ Zero     = a
recNat a h (Succ n) = h n (recNat a h n)
</code>```

My function of exponentiation is

```<code>expR :: Nat -> Nat -> Nat
expR m n = recNat (Succ Zero) (\ _ y -> multR m y) n
</code>```

I define the prop_Exp property using the exponentiation on Natural

```<code>prop_Exp :: Natural -> Natural -> Bool
prop_Exp m n = natToNatural (expR m' n') == m ^ n
  where
    m' :: Nat
    m' = naturalToNat m

    n' :: Nat
    n' = naturalToNat n
</code>```

for testing my implementation of the expR function via QuickCheck

```<code>main :: IO ()
main = quickCheck prop_expR
</code>```

However, after running this code I get an exception:

```<code>*** Exception: stack overflow
</code>```

I want to know what it is wrong with this code

答:
As chi remarks, the Nat type represents numbers as recursive data structure. I think that it's isomorphic to [()], but I could be mistaken...

AFAICT, the conversion functions, as well as recNat, aren't tail recursive, so when working with something like 10^10, they'd be building up thunks for billions of elements. It's not too surprising that you get a stack overflow from larger numbers.

You can tell QuickCheck to limit the range of the values generated. The choose function is the general-purpose solution to this problem, but AFAICT Natural doesn't have a Random instance. Instead, you might be able to use chooseEnum, since Natural does have an Enum instance.

A few years back I was also dabbling with natural numbers (and associated ideas) in a like fashion. Here's a property I wrote of multiplication:

```<code>testProperty "Multiplication" $ do
  x <- choose @Integer (0, 25)
  y <- choose (0, 25)
  return $ x * y === toNum (multiplyF (fromNum x) (fromNum y))
</code>```

I didn't base my QuickCheck properties on Natural since I used choose. This enabled me to tell QuickCheck to only pick numbers greater than 0. For multiplication, I had to constrain my integers to be less than 25, but for other properties, I chose a larger range:

```<code>testProperty "Increment" $ do
  i <- choose @Integer (0, 1e4)
  return $ i + 1 === toNum (incF (fromNum i))
</code>```

It's been a few years, so I don't recall exactly why I chose those particular numbers. I was using an older laptop back then, but I don't recall if higher numbers caused my process to overflow, or if it was simply that the tests ran too slowly.

Body:
I'm implementing some number theoretic functions as the exponentiation in Haskell using a recursor. I'm using the QuickCheck library for testing my implementation.
For simplify my tests, I'm using the Natural data type from the base library, the
Arbitrary instance for Natural defined in the quickcheck-instances library and the
following functions converting from Nat to Natural and from Natural to Nat, respectively, considering the data Nat defined by myself:

data Nat = Zero | Succ Nat

natToNatural :: Nat -> Natural
natToNatural Zero = 0
natToNatural (Succ n) = 1 + natToNatural n

naturalToNat :: Natural -> Nat
naturalToNat 0 = Zero
naturalToNat n = Succ (naturalToNat (n - 1))

The implemetation use the following recursor over natural numbers:

recNat :: a -> (Nat -> a -> a) -> Nat -> a
recNat a _ Zero     = a
recNat a h (Succ n) = h n (recNat a h n)

My function of exponentiation is

expR :: Nat -> Nat -> Nat
expR m n = recNat (Succ Zero) (\ _ y -> multR m y) n

I define the prop_Exp property using the exponentiation on Natural

prop_Exp :: Natural -> Natural -> Bool
prop_Exp m n = natToNatural (expR m' n') == m ^ n
  where
    m' :: Nat
    m' = naturalToNat m

    n' :: Nat
    n' = naturalToNat n

for testing my implementation of the expR function via QuickCheck

main :: IO ()
main = quickCheck prop_expR

However, after running this code I get an exception:

*** Exception: stack overflow

I want to know what it is wrong with this code

Body:
As chi remarks, the Nat type represents numbers as recursive data structure. I think that it's isomorphic to [()], but I could be mistaken...

AFAICT, the conversion functions, as well as recNat, aren't tail recursive, so when working with something like 10^10, they'd be building up thunks for billions of elements. It's not too surprising that you get a stack overflow from larger numbers.

You can tell QuickCheck to limit the range of the values generated. The choose function is the general-purpose solution to this problem, but AFAICT Natural doesn't have a Random instance. Instead, you might be able to use chooseEnum, since Natural does have an Enum instance.

A few years back I was also dabbling with natural numbers (and associated ideas) in a like fashion. Here's a property I wrote of multiplication:

testProperty "Multiplication" $ do
  x <- choose @Integer (0, 25)
  y <- choose (0, 25)
  return $ x * y === toNum (multiplyF (fromNum x) (fromNum y))

I didn't base my QuickCheck properties on Natural since I used choose. This enabled me to tell QuickCheck to only pick numbers greater than 0. For multiplication, I had to constrain my integers to be less than 25, but for other properties, I chose a larger range:

testProperty "Increment" $ do
  i <- choose @Integer (0, 1e4)
  return $ i + 1 === toNum (incF (fromNum i))

It's been a few years, so I don't recall exactly why I chose those particular numbers. I was using an older laptop back then, but I don't recall if higher numbers caused my process to overflow, or if it was simply that the tests ran too slowly.


问:
How to get the focus on a textbox on a key press
We have a page which requires user to enter some input and post submission (e.g. by hitting Enter key or Submit button). The answer is shown to the end user and we provide a link which says 'Press any key to continue'.

The focus on the input box is automatically shown, either after pressing any key or by clicking on the link. Can someone provide some sample code to do this?

答:
Try this:</p>

```<code>$('#other').click(function() {
    $('#target').focus();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try this:

$('#other').click(function() {
    $('#target').focus();
});


问:
Can't parse names and phones out of different containers from a webpage
I'm trying to get name and phone from each container from a webpage's landing page using requests. My current attempt can fetch me only the names. I don't find any idea to rectify the existing loop so that it can include the phones together with names.

website address

How can I scrape the names along with phones from there?

I've tried with:

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

link = 'https://sdcds.org/dental-directory/'

r = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(r.text,"html.parser")
for item in soup.select("h3 > a"):
    print(item.text)
</code>```

This is the relevant html for one such container:

```<code><h3 class="dentist-h3"><a style="text-decoration: underline; color: #5e76a2;" href="/dental-directory/view-dentist/?ID=16835">Matthew  Osmak , DDS</a></h3>
General Practice<br>
Pomerado Dental<br>
15835 Pomerado Rd Ste 301<br>

Poway, CA 92064<br>
Tel: <a href="tel:+1(858) 487-4888">(858) 487-4888</a><br>

<a href="mailto:jarvek7@yahoo.com">jarvek7@yahoo.com</a><br>

<br>
<hr>
<br> <h3 class="dentist-h3"><a style="text-decoration: underline; color: #5e76a2;" href="/dental-directory/view-dentist/?ID=16232">Robert Ian Goldenberg , DDS</a></h3>
General Practice<br>

2602 Washington St<br>

Julian, CA 92036<br>
Tel: <a href="tel:+1(760) 765-1675">(760) 765-1675</a><br>

<a href="mailto:robertgoldenbergdds@gmail.com">robertgoldenbergdds@gmail.com</a><br>

<br>
<hr>
<br>
</code>```

答:
There are some dentists that doesn't have phone. This script will get all the names found on page + their phones (or empty string if they don't have one):

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

link = 'https://sdcds.org/dental-directory/'

r = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(r.text,"html.parser")

out, name, tel = [], '', ''
for tag in soup.select('h3.dentist-h3, a[href^="tel"]'):
    if tag.name == 'h3':
        if name:
            out.append((name, tel))
        name, tel = tag.get_text(strip=True), ''
    elif tag.name == 'a' and 'Tel:' in tag.find_previous(text=True):
        tel = tag.get_text(strip=True)

out.append((name, tel)) # append last one

for name, tel in out:
    print('{:<50} {}'.format(name, tel))
</code>```

Prints:

```<code>Mina  Raffo , DDS                                  (619) 456-8973
Arthur David Santos , DDS                          (619) 334-8743
Nicholas  Dovey , DMD                              (619) 232-3774
Frederick U Soldau , DDS                           (858) 454-6124
John E Duling , DDS                                (760) 728-9558
Jimmy Igen Wang , DDS                              (858) 487-6428
,
Alexis Laine Louie , DMD                           (619) 276-0963
Karina  Scalercio , DDS
S. Roya  Sadrian , DDS                             (858) 780-9794
</code>```

Body:
I'm trying to get name and phone from each container from a webpage's landing page using requests. My current attempt can fetch me only the names. I don't find any idea to rectify the existing loop so that it can include the phones together with names.

website address

How can I scrape the names along with phones from there?

I've tried with:

import requests
from bs4 import BeautifulSoup

link = 'https://sdcds.org/dental-directory/'

r = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(r.text,"html.parser")
for item in soup.select("h3 > a"):
    print(item.text)

This is the relevant html for one such container:

Matthew  Osmak , DDS

General Practice

Pomerado Dental

15835 Pomerado Rd Ste 301

Poway, CA 92064

Tel: (858) 487-4888

jarvek7@yahoo.com

Robert Ian Goldenberg , DDS

General Practice

2602 Washington St

Julian, CA 92036

Tel: (760) 765-1675

robertgoldenbergdds@gmail.com

Body:
There are some dentists that doesn't have phone. This script will get all the names found on page + their phones (or empty string if they don't have one):

import requests
from bs4 import BeautifulSoup

link = 'https://sdcds.org/dental-directory/'

r = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(r.text,"html.parser")

out, name, tel = [], '', ''
for tag in soup.select('h3.dentist-h3, a[href^="tel"]'):
    if tag.name == 'h3':
        if name:
            out.append((name, tel))
        name, tel = tag.get_text(strip=True), ''
    elif tag.name == 'a' and 'Tel:' in tag.find_previous(text=True):
        tel = tag.get_text(strip=True)

out.append((name, tel)) # append last one

for name, tel in out:
    print('{:<50} {}'.format(name, tel))

Prints:

Mina  Raffo , DDS                                  (619) 456-8973
Arthur David Santos , DDS                          (619) 334-8743
Nicholas  Dovey , DMD                              (619) 232-3774
Frederick U Soldau , DDS                           (858) 454-6124
John E Duling , DDS                                (760) 728-9558
Jimmy Igen Wang , DDS                              (858) 487-6428
,
Alexis Laine Louie , DMD                           (619) 276-0963
Karina  Scalercio , DDS
S. Roya  Sadrian , DDS                             (858) 780-9794


问:
Saxonica - .NET API - XQuery - XPDY0002: The context item for axis step root/descendant::xxx is absent
I'm getting same error as this question, but with XQuery:
SaxonApiException: The context item for axis step ./CLIENT is absent

When running from the command line, all is good.  So I don't think there is a syntax problem with the XQuery itself.  I won't post the input file unless needed.

The XQuery is displayed with a Console.WriteLine before the error appears:

```<code>----- Start: XQUERY:
(:  FLWOR = For Let Where Order-by Return   :)
<MyFlightLegs>
{
for $flightLeg in //FlightLeg
where $flightLeg/DepartureAirport = 'OKC' or $flightLeg/ArrivalAirport = 'OKC'
order by $flightLeg/ArrivalDate[1] descending
return $flightLeg
}
</MyFlightLegs>

----- End  : XQUERY:
Error evaluating (<MyFlightLegs {for $flightLeg in root/descendant::FlightLeg[DepartureAirport = "OKC" or ArrivalAirport = "OKC"] ... return $flightLeg}/>) on line 4 column 20
  XPDY0002: The context item for axis step root/descendant::FlightLeg is absent
</code>```

I think that like the other question, maybe my input XML file is not properly specified.

I took the samples/cs/ExamplesHE.cs run method of the XQuerytoStream class.

Code there for easy reference is:

```<code>public class XQueryToStream : Example
{

    public override string testName
    {
        get { return "XQueryToStream"; }
    }

    public override void run(Uri samplesDir)
    {
        Processor processor = new Processor();
        XQueryCompiler compiler = processor.NewXQueryCompiler();
        compiler.BaseUri = samplesDir.ToString();
        compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
        XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
        XQueryEvaluator eval = exp.Load();
        Serializer qout = processor.NewSerializer();
        qout.SetOutputProperty(Serializer.METHOD, "xml");
        qout.SetOutputProperty(Serializer.INDENT, "yes");
        qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
        Console.WriteLine("Output written to testoutput.xml");
        eval.Run(qout);
    }

}
</code>```

I changed to pass the Xquery file name, the xml file name, and the output file name, and tried to make a static method out of it. (Had success doing the same with the XSLT processor.)

```<code>static void DemoXQuery(string xmlInputFilename, string xqueryInputFilename, string outFilename)
{

    // Create a Processor instance.
    Processor processor = new Processor();

    // Load the source document
    DocumentBuilder loader = processor.NewDocumentBuilder();
    loader.BaseUri = new Uri(xmlInputFilename);
    XdmNode indoc = loader.Build(loader.BaseUri);

    XQueryCompiler compiler = processor.NewXQueryCompiler();
    //BaseUri is inconsistent with Transform= Processor?
    //compiler.BaseUri = new Uri(xqueryInputFilename);
    //compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");

    string xqueryFileContents = File.ReadAllText(xqueryInputFilename);
    Console.WriteLine("----- Start: XQUERY:");
    Console.WriteLine(xqueryFileContents);
    Console.WriteLine("----- End  : XQUERY:");
    XQueryExecutable exp = compiler.Compile(xqueryFileContents);
    XQueryEvaluator eval = exp.Load();

    Serializer qout = processor.NewSerializer();
    qout.SetOutputProperty(Serializer.METHOD, "xml");
    qout.SetOutputProperty(Serializer.INDENT, "yes");
    qout.SetOutputStream(new FileStream(outFilename,
                 FileMode.Create, FileAccess.Write));

    eval.Run(qout);

}
</code>```

Also two questions regarding "BaseURI".

1. Should it be a directory name, or can it be same as the Xquery file name?
2. I get this compile error: "Cannot implicity convert to "System.Uri" to "String".

```<code>compiler.BaseUri = new Uri(xqueryInputFilename);
</code>```

It's exactly the same thing I did for XSLT which worked. But it looks like BaseUri is a string for XQuery, but a real Uri object for XSLT?  Any reason for the difference?

答:
You seem to be asking a whole series of separate questions, which are hard to disentangle.

Your C# code appears to be compiling the query

```<code><saxon:example>{static-base-uri()}</saxon:example>
</code>```

which bears no relationship to the XQuery code you supplied that involves MyFlightLegs.

The MyFlightLegs query uses //FlightLeg and is clearly designed to run against a source document containing a FlightLeg element, but your C# code makes no attempt to supply such a document. You need to add an eval.ContextItem = value statement.

Your second C# fragment creates an input document in the line

```<code>XdmNode indoc = loader.Build(loader.BaseUri);
</code>```

but it doesn't supply it to the query evaluator.

A base URI can be either a directory or a file; resolving relative.xml against file:///my/dir/ gives exactly the same result as resolving it against file:///my/dir/query.xq. By convention, though, the static base URI of the query is the URI of the resource (eg file) containing the source query text.

Yes, there's a lot of inconsistency in the use of strings versus URI objects in the API design. (There's also inconsistency about the spelling of BaseURI versus BaseUri.) Sorry about that; you're just going to have to live with it.

Body:
I'm getting same error as this question, but with XQuery:
SaxonApiException: The context item for axis step ./CLIENT is absent

When running from the command line, all is good.  So I don't think there is a syntax problem with the XQuery itself.  I won't post the input file unless needed.

The XQuery is displayed with a Console.WriteLine before the error appears:

----- Start: XQUERY:
(:  FLWOR = For Let Where Order-by Return   :)
<MyFlightLegs>
{
for $flightLeg in //FlightLeg
where $flightLeg/DepartureAirport = 'OKC' or $flightLeg/ArrivalAirport = 'OKC'
order by $flightLeg/ArrivalDate[1] descending
return $flightLeg
}
</MyFlightLegs>

----- End  : XQUERY:
Error evaluating (<MyFlightLegs {for $flightLeg in root/descendant::FlightLeg[DepartureAirport = "OKC" or ArrivalAirport = "OKC"] ... return $flightLeg}/>) on line 4 column 20
  XPDY0002: The context item for axis step root/descendant::FlightLeg is absent

I think that like the other question, maybe my input XML file is not properly specified.

I took the samples/cs/ExamplesHE.cs run method of the XQuerytoStream class.

Code there for easy reference is:

public class XQueryToStream : Example
{

    public override string testName
    {
        get { return "XQueryToStream"; }
    }

    public override void run(Uri samplesDir)
    {
        Processor processor = new Processor();
        XQueryCompiler compiler = processor.NewXQueryCompiler();
        compiler.BaseUri = samplesDir.ToString();
        compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
        XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
        XQueryEvaluator eval = exp.Load();
        Serializer qout = processor.NewSerializer();
        qout.SetOutputProperty(Serializer.METHOD, "xml");
        qout.SetOutputProperty(Serializer.INDENT, "yes");
        qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
        Console.WriteLine("Output written to testoutput.xml");
        eval.Run(qout);
    }

}

I changed to pass the Xquery file name, the xml file name, and the output file name, and tried to make a static method out of it. (Had success doing the same with the XSLT processor.)

static void DemoXQuery(string xmlInputFilename, string xqueryInputFilename, string outFilename)
{

    // Create a Processor instance.
    Processor processor = new Processor();

    // Load the source document
    DocumentBuilder loader = processor.NewDocumentBuilder();
    loader.BaseUri = new Uri(xmlInputFilename);
    XdmNode indoc = loader.Build(loader.BaseUri);

    XQueryCompiler compiler = processor.NewXQueryCompiler();
    //BaseUri is inconsistent with Transform= Processor?
    //compiler.BaseUri = new Uri(xqueryInputFilename);
    //compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");

    string xqueryFileContents = File.ReadAllText(xqueryInputFilename);
    Console.WriteLine("----- Start: XQUERY:");
    Console.WriteLine(xqueryFileContents);
    Console.WriteLine("----- End  : XQUERY:");
    XQueryExecutable exp = compiler.Compile(xqueryFileContents);
    XQueryEvaluator eval = exp.Load();

    Serializer qout = processor.NewSerializer();
    qout.SetOutputProperty(Serializer.METHOD, "xml");
    qout.SetOutputProperty(Serializer.INDENT, "yes");
    qout.SetOutputStream(new FileStream(outFilename,
                 FileMode.Create, FileAccess.Write));

    eval.Run(qout);

}

Also two questions regarding "BaseURI".

1. Should it be a directory name, or can it be same as the Xquery file name?
2. I get this compile error: "Cannot implicity convert to "System.Uri" to "String".

compiler.BaseUri = new Uri(xqueryInputFilename);

It's exactly the same thing I did for XSLT which worked. But it looks like BaseUri is a string for XQuery, but a real Uri object for XSLT?  Any reason for the difference?

Body:
You seem to be asking a whole series of separate questions, which are hard to disentangle.

Your C# code appears to be compiling the query

<saxon:example>{static-base-uri()}</saxon:example>

which bears no relationship to the XQuery code you supplied that involves MyFlightLegs.

The MyFlightLegs query uses //FlightLeg and is clearly designed to run against a source document containing a FlightLeg element, but your C# code makes no attempt to supply such a document. You need to add an eval.ContextItem = value statement.

Your second C# fragment creates an input document in the line

XdmNode indoc = loader.Build(loader.BaseUri);

but it doesn't supply it to the query evaluator.

A base URI can be either a directory or a file; resolving relative.xml against file:///my/dir/ gives exactly the same result as resolving it against file:///my/dir/query.xq. By convention, though, the static base URI of the query is the URI of the resource (eg file) containing the source query text.

Yes, there's a lot of inconsistency in the use of strings versus URI objects in the API design. (There's also inconsistency about the spelling of BaseURI versus BaseUri.) Sorry about that; you're just going to have to live with it.


问:
Download xlsx file without Headers, Vuejs
I have a download action, that it works, but in my .xlsx file I don't have the header, and I am not sure how can I get them. I'm using Vuejs / Axios with Laravel.

```<code><a type="button" class="mr-3" href="/json/persons/export" download="file.xlsx">
<button @click="exportCSV" class="btn btn-primary">
    Export CSV
</button>
</a>

exportCSV() {
    axios
    .get("/json/persons/export", {
        params: {
        sort_by: this.sortBy,
        sort_direction: this.sortDesc
        }
    })
    .then(response => {
        //
    })
    .catch(error => {
        //
    });
},
</code>```

Export Class Code

```<code>namespace App\Exports;
use App\ViewData;
use Maatwebsite\Excel\Concerns\FromCollection;
use Excel;

class DataExport implements FromCollection
{
    public function collection()
    {
        return ViewData::all();
    }

}
</code>```

答:
Well you can actually do something like

```<code>namespace App\Exports;
use App\ViewData;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Excel;

class DataExport implements FromCollection, WithHeadings
{
    public function collection()
    {
        return ViewData::all();
    }

    //Define your desired headings this way, it's just for an example
    public function headings(): array
    {
       return [
           'Name',
           'Surname',
           'Email',
           'Twitter',
       ];
    }
}
</code>```

Body:
I have a download action, that it works, but in my .xlsx file I don't have the header, and I am not sure how can I get them. I'm using Vuejs / Axios with Laravel.

<button @click="exportCSV" class="btn btn-primary">
    Export CSV
</button>

exportCSV() {
    axios
    .get("/json/persons/export", {
        params: {
        sort_by: this.sortBy,
        sort_direction: this.sortDesc
        }
    })
    .then(response => {
        //
    })
    .catch(error => {
        //
    });
},

Export Class Code

namespace App\Exports;
use App\ViewData;
use Maatwebsite\Excel\Concerns\FromCollection;
use Excel;

class DataExport implements FromCollection
{
    public function collection()
    {
        return ViewData::all();
    }

}

Body:
Well you can actually do something like

namespace App\Exports;
use App\ViewData;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Excel;

class DataExport implements FromCollection, WithHeadings
{
    public function collection()
    {
        return ViewData::all();
    }

    //Define your desired headings this way, it's just for an example
    public function headings(): array
    {
       return [
           'Name',
           'Surname',
           'Email',
           'Twitter',
       ];
    }
}


问:
Why does this wrapping allocator's constructor take in the wrong type during template substitution (perfect forwarding ctor)?
For some context, I'm writing an allocator that takes in a base allocator as a template type, and does nothing but forward the allocate() and deallocate() calls to the underlying allocator member. Creating std::vectors with this custom allocator works fine. I tried writing a make_shared wrapper that will use dummy_allocator<T, std::allocator<T>> by default but it wasn't successful. Here is a reproducible example:

```<code>#include <memory>
namespace test {

template<typename T, typename base_allocator=std::allocator<T>>
class dummy_allocator {
public:
    typedef typename std::allocator_traits<base_allocator>::size_type size_type;
    typedef typename std::allocator_traits<base_allocator>::difference_type difference_type;
    typedef typename std::allocator_traits<base_allocator>::pointer pointer;
    typedef typename std::allocator_traits<base_allocator>::const_pointer const_pointer;
    typedef typename std::allocator_traits<base_allocator>::value_type value_type;

    template<class U>
    struct rebind {
        typedef dummy_allocator<U,
                typename std::allocator_traits<base_allocator>::template rebind_alloc<U>> other;
    };

    template<typename... Args>
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator(const dummy_allocator& a) = default;

    [[nodiscard]] T *allocate(std::size_t n) {
        T *p = alloc.allocate(n);
        return p;
    }

    void deallocate(T *p, std::size_t size) noexcept {
        alloc.deallocate(p, size);
    }

private:
    base_allocator alloc;
};

/// Allocate using a wrapped version of passed in allocator
template <typename T, typename Alloc, typename... Args>
std::shared_ptr<T> allocate_shared(const Alloc& alloc, Args&&... args) {
    auto dummy_alloc = dummy_allocator<T, Alloc>(alloc);
    return std::allocate_shared<T>(dummy_alloc, std::forward<Args>(args)...);
}

/// Create a shared pointer from a default stl allocator wrapped in profile allocator.
template <typename T, typename... Args>
std::shared_ptr<T> make_shared(Args&&... args) {
    return test::allocate_shared<T>(std::allocator<T>(), std::forward<Args>(args)...);
}

} // namespace test

int main() {
    auto ptr = test::make_shared<double>();
    return 0;
}
</code>```

When I ran the above code, the compiler generated some bizarre template substitution failure errors:

```<code>/usr/include/c++/10.1.0/bits/shared_ptr_base.h:679:43:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr_base.h:1371:71:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:408:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:859:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}]’
/home/ray/home/testing/src/alloc.cpp:44:35:   required from ‘std::shared_ptr<_Tp> test::allocate_shared(const Alloc&, Args&& ...) [with T = double; Alloc = std::allocator<double>; Args = {}]’
/home/ray/home/testing/src/alloc.cpp:50:36:   required from ‘std::shared_ptr<_Tp> test::make_shared(Args&& ...) [with T = double; Args = {}]’
/home/ray/home/testing/src/alloc.cpp:86:46:   required from here
/home/ray/home/testing/src/alloc.cpp:25:82: error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
   25 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/testing/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note: candidate: ‘template<class _Tp1> constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator<_Tp1>&) [with _Tp1 = _Tp1; _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  157 |  allocator(const allocator<_Tp1>&) _GLIBCXX_NOTHROW { }
      |  ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note:   template argument deduction/substitution failed:
/home/ray/home/testing/src/alloc.cpp:25:82: note:   ‘const test::dummy_allocator<double, std::allocator<double> >’ is not derived from ‘const std::allocator<_Up>’
   25 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/testing/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:147:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator< <template-parameter-1-1> >&) [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:147:34: note:   no known conversion for argument 1 from ‘const test::dummy_allocator<double, std::allocator<double> >’ to ‘const std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >&’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |                 ~~~~~~~~~~~~~~~~~^~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator() [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  144 |       allocator() _GLIBCXX_NOTHROW { }
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note:   candidate expects 0 arguments, 1 provided
... (The above error basically is repeated 2 more times)
</code>```

In particular, this error seemed representative of the problem occurring:

```<code>error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
</code>```

Where it basically says "in the constructor of dummy_allocator, you can't pass in a dummy_allocator to the std::allocator's constructor". But I'm not doing that. In allocate_shared, I'm passing in the std::allocator into the dummy_allocator.

I've really scratched my head reading the compiler error but came to no conclusions on what I'm doing wrong. Any help would be greatly appreciated!

EDIT: I think I have a hunch that whatever magic shared_ptr is doing underneath, it's trying to do a copy constructor of my dummy_allocator, and perfect forwarding is capturing the copy construction instead an actual copy constructor. However, I have no idea how to solve this as it's a variadic template and I can't use std::is_same<Args, dummy_allocator> as a requires clause in the perfect forwarding constructor.

So as Daniel Langr has pointed out, just copy constructing the dummy_allocator will fail. I fixed that issue with the following requires clause:

```<code>...
    template <typename T1, typename ...TV>
    struct is_dummy : std::is_same<typename std::decay<T1>::type, dummy_allocator<T, base_allocator>>{
    };

    template<typename... Args>
    requires (!is_dummy<Args...>::value)
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator() = default;
    dummy_allocator(const dummy_allocator& a) = default;
...

</code>```

However, that's not enough to fix the shared_ptr issue, where the error is a bit longer...*

So here is the error you get:

```<code>#include <memory>
namespace test {

template<typename T, typename base_allocator=std::allocator<T>>
class dummy_allocator {
public:
    /// Necessary for allocators, propagate exactly what the base_allocator
    /// wants.
    typedef typename std::allocator_traits<base_allocator>::size_type size_type;
    typedef typename std::allocator_traits<base_allocator>::difference_type difference_type;
    typedef typename std::allocator_traits<base_allocator>::pointer pointer;
    typedef typename std::allocator_traits<base_allocator>::const_pointer const_pointer;
    typedef typename std::allocator_traits<base_allocator>::value_type value_type;

    template<class U>
    struct rebind {
        typedef dummy_allocator<U,
                typename std::allocator_traits<base_allocator>::template rebind_alloc<U>> other;
    };

    template <typename T1, typename ...TV>
    struct is_dummy : std::is_same<typename std::decay<T1>::type, dummy_allocator<T, base_allocator>>{
    };

    template<typename... Args>
    requires (!is_dummy<Args...>::value)
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator() = default;
    dummy_allocator(const dummy_allocator& a) = default;

    [[nodiscard]] T *allocate(std::size_t n) {
        T *p = alloc.allocate(n);
        return p;
    }

    void deallocate(T *p, std::size_t size) noexcept {
        alloc.deallocate(p, size);
    }

private:
    base_allocator alloc;
};

/// Allocate using a wrapped version of passed in allocator
template <typename T, typename Alloc, typename... Args>
auto allocate_shared(const Alloc& alloc, Args&&... args) {
    auto dummy_alloc = dummy_allocator<T, Alloc>(alloc);
    return std::allocate_shared<T>(dummy_alloc, std::forward<Args>(args)...);
}

/// Create a shared pointer from a default stl allocator wrapped in profile allocator.
template <typename T, typename... Args>
auto make_shared(Args&&... args) {
    return test::allocate_shared<T>(std::allocator<T>(), std::forward<Args>(args)...);
}

} // namespace test

int main() {
    // This will fail
    auto ptr = test::make_shared<double>();

    // This will now work
    auto dummy_alloc = test::dummy_allocator<int, std::allocator<int>>();
    auto dummy_alloc2 = test::dummy_allocator<int, std::allocator<int>>(dummy_alloc);
    return 0;
}
</code>```

The associated error:

```<code>/usr/include/c++/10.1.0/bits/shared_ptr_base.h:679:43:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr_base.h:1371:71:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:408:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:859:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}]’
/home/ray/home/test/src/alloc.cpp:53:35:   required from ‘auto test::allocate_shared(const Alloc&, Args&& ...) [with T = double; Alloc = std::allocator<double>; Args = {}]’
/home/ray/home/test/src/alloc.cpp:59:36:   required from ‘auto test::make_shared(Args&& ...) [with T = double; Args = {}]’
/home/ray/home/test/src/alloc.cpp:95:46:   required from here
/home/ray/home/test/src/alloc.cpp:31:82: error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
   31 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/test/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note: candidate: ‘template<class _Tp1> constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator<_Tp1>&) [with _Tp1 = _Tp1; _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  157 |  allocator(const allocator<_Tp1>&) _GLIBCXX_NOTHROW { }
      |  ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note:   template argument deduction/substitution failed:
/home/ray/home/test/src/alloc.cpp:31:82: note:   ‘const test::dummy_allocator<double, std::allocator<double> >’ is not derived from ‘const std::allocator<_Up>’
   31 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/test/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:147:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator< <template-parameter-1-1> >&) [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:147:34: note:   no known conversion for argument 1 from ‘const test::dummy_allocator<double, std::allocator<double> >’ to ‘const std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >&’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |                 ~~~~~~~~~~~~~~~~~^~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator() [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  144 |       allocator() _GLIBCXX_NOTHROW { }
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note:   candidate expects 0 arguments, 1 provided
</code>```

答:
I think your hunch is correct. One always has to be careful with perfect forwarding constructors and the normal copy constructor. I think there are multiple solutions but I haven't tested any of them yet.

First you could provide a better match than the perfect forwarding constructor by adding dummy_allocator(dummy_allocator&) forwarding to the normal copy constructor. The perfect forwarding constructor matches better than the copy constructor, when the passed dummy_allocator is not const and hence the copy constructor has to do const conversion. But this would require also overloading the move constructor (I think) since otherwise you get the same error when someone somewhere tries to move the dummy_allocator.

A bit more tricky but probably safer is doing the following:

```<code>template<class... Args>
dummy_allocator(Args&&... args) requires (sizeof...(Args) != 1) : alloc(std::forward<Args>(args)...) {}

template<class Arg>
dummy_allocator(Arg&& arg) requires (!std::is_same_v<std::decay_t<Arg>, dummy_allocator>) : alloc(std::forward<Arg>(arg)) {}

dummy_allocator(const dummy_allocator&) = default;
</code>```

I hope I got the requires clauses right, I haven't worked much with that yet. But doing SFINAE in constructors is a royal pain in the ass.

Body:
For some context, I'm writing an allocator that takes in a base allocator as a template type, and does nothing but forward the allocate() and deallocate() calls to the underlying allocator member. Creating std::vectors with this custom allocator works fine. I tried writing a make_shared wrapper that will use dummy_allocator<T, std::allocator<T>> by default but it wasn't successful. Here is a reproducible example:

#include <memory>
namespace test {

template<typename T, typename base_allocator=std::allocator<T>>
class dummy_allocator {
public:
    typedef typename std::allocator_traits<base_allocator>::size_type size_type;
    typedef typename std::allocator_traits<base_allocator>::difference_type difference_type;
    typedef typename std::allocator_traits<base_allocator>::pointer pointer;
    typedef typename std::allocator_traits<base_allocator>::const_pointer const_pointer;
    typedef typename std::allocator_traits<base_allocator>::value_type value_type;

    template<class U>
    struct rebind {
        typedef dummy_allocator<U,
                typename std::allocator_traits<base_allocator>::template rebind_alloc> other;
    };

    template<typename... Args>
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator(const dummy_allocator& a) = default;

    [[nodiscard]] T *allocate(std::size_t n) {
        T *p = alloc.allocate(n);
        return p;
    }

    void deallocate(T *p, std::size_t size) noexcept {
        alloc.deallocate(p, size);
    }

private:
    base_allocator alloc;
};

/// Allocate using a wrapped version of passed in allocator
template <typename T, typename Alloc, typename... Args>
std::shared_ptr<T> allocate_shared(const Alloc& alloc, Args&&... args) {
    auto dummy_alloc = dummy_allocator<T, Alloc>(alloc);
    return std::allocate_shared<T>(dummy_alloc, std::forward<Args>(args)...);
}

/// Create a shared pointer from a default stl allocator wrapped in profile allocator.
template <typename T, typename... Args>
std::shared_ptr<T> make_shared(Args&&... args) {
    return test::allocate_shared<T>(std::allocator<T>(), std::forward<Args>(args)...);
}

} // namespace test

int main() {
    auto ptr = test::make_shared<double>();
    return 0;
}

When I ran the above code, the compiler generated some bizarre template substitution failure errors:

/usr/include/c++/10.1.0/bits/shared_ptr_base.h:679:43:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr_base.h:1371:71:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:408:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:859:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}]’
/home/ray/home/testing/src/alloc.cpp:44:35:   required from ‘std::shared_ptr<_Tp> test::allocate_shared(const Alloc&, Args&& ...) [with T = double; Alloc = std::allocator<double>; Args = {}]’
/home/ray/home/testing/src/alloc.cpp:50:36:   required from ‘std::shared_ptr<_Tp> test::make_shared(Args&& ...) [with T = double; Args = {}]’
/home/ray/home/testing/src/alloc.cpp:86:46:   required from here
/home/ray/home/testing/src/alloc.cpp:25:82: error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
   25 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/testing/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note: candidate: ‘template<class _Tp1> constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator<_Tp1>&) [with _Tp1 = _Tp1; _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  157 |  allocator(const allocator<_Tp1>&) _GLIBCXX_NOTHROW { }
      |  ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note:   template argument deduction/substitution failed:
/home/ray/home/testing/src/alloc.cpp:25:82: note:   ‘const test::dummy_allocator<double, std::allocator<double> >’ is not derived from ‘const std::allocator<_Up>’
   25 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/testing/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:147:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator< <template-parameter-1-1> >&) [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:147:34: note:   no known conversion for argument 1 from ‘const test::dummy_allocator<double, std::allocator<double> >’ to ‘const std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >&’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |                 ~~~~~~~~~~~~~~~~~^~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator() [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  144 |       allocator() _GLIBCXX_NOTHROW { }
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note:   candidate expects 0 arguments, 1 provided
... (The above error basically is repeated 2 more times)

In particular, this error seemed representative of the problem occurring:

error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’

Where it basically says "in the constructor of dummy_allocator, you can't pass in a dummy_allocator to the std::allocator's constructor". But I'm not doing that. In allocate_shared, I'm passing in the std::allocator into the dummy_allocator.

I've really scratched my head reading the compiler error but came to no conclusions on what I'm doing wrong. Any help would be greatly appreciated!

EDIT: I think I have a hunch that whatever magic shared_ptr is doing underneath, it's trying to do a copy constructor of my dummy_allocator, and perfect forwarding is capturing the copy construction instead an actual copy constructor. However, I have no idea how to solve this as it's a variadic template and I can't use std::is_same<Args, dummy_allocator> as a requires clause in the perfect forwarding constructor.

So as Daniel Langr has pointed out, just copy constructing the dummy_allocator will fail. I fixed that issue with the following requires clause:

...
    template <typename T1, typename ...TV>
    struct is_dummy : std::is_same<typename std::decay<T1>::type, dummy_allocator<T, base_allocator>>{
    };

    template<typename... Args>
    requires (!is_dummy<Args...>::value)
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator() = default;
    dummy_allocator(const dummy_allocator& a) = default;
...

However, that's not enough to fix the shared_ptr issue, where the error is a bit longer...*

So here is the error you get:

#include <memory>
namespace test {

template<typename T, typename base_allocator=std::allocator<T>>
class dummy_allocator {
public:
    /// Necessary for allocators, propagate exactly what the base_allocator
    /// wants.
    typedef typename std::allocator_traits<base_allocator>::size_type size_type;
    typedef typename std::allocator_traits<base_allocator>::difference_type difference_type;
    typedef typename std::allocator_traits<base_allocator>::pointer pointer;
    typedef typename std::allocator_traits<base_allocator>::const_pointer const_pointer;
    typedef typename std::allocator_traits<base_allocator>::value_type value_type;

    template<class U>
    struct rebind {
        typedef dummy_allocator<U,
                typename std::allocator_traits<base_allocator>::template rebind_alloc> other;
    };

    template <typename T1, typename ...TV>
    struct is_dummy : std::is_same<typename std::decay<T1>::type, dummy_allocator<T, base_allocator>>{
    };

    template<typename... Args>
    requires (!is_dummy<Args...>::value)
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator() = default;
    dummy_allocator(const dummy_allocator& a) = default;

    [[nodiscard]] T *allocate(std::size_t n) {
        T *p = alloc.allocate(n);
        return p;
    }

    void deallocate(T *p, std::size_t size) noexcept {
        alloc.deallocate(p, size);
    }

private:
    base_allocator alloc;
};

/// Allocate using a wrapped version of passed in allocator
template <typename T, typename Alloc, typename... Args>
auto allocate_shared(const Alloc& alloc, Args&&... args) {
    auto dummy_alloc = dummy_allocator<T, Alloc>(alloc);
    return std::allocate_shared<T>(dummy_alloc, std::forward<Args>(args)...);
}

/// Create a shared pointer from a default stl allocator wrapped in profile allocator.
template <typename T, typename... Args>
auto make_shared(Args&&... args) {
    return test::allocate_shared<T>(std::allocator<T>(), std::forward<Args>(args)...);
}

} // namespace test

int main() {
    // This will fail
    auto ptr = test::make_shared<double>();

    // This will now work
    auto dummy_alloc = test::dummy_allocator<int, std::allocator<int>>();
    auto dummy_alloc2 = test::dummy_allocator<int, std::allocator<int>>(dummy_alloc);
    return 0;
}

The associated error:

/usr/include/c++/10.1.0/bits/shared_ptr_base.h:679:43:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr_base.h:1371:71:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:408:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:859:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}]’
/home/ray/home/test/src/alloc.cpp:53:35:   required from ‘auto test::allocate_shared(const Alloc&, Args&& ...) [with T = double; Alloc = std::allocator<double>; Args = {}]’
/home/ray/home/test/src/alloc.cpp:59:36:   required from ‘auto test::make_shared(Args&& ...) [with T = double; Args = {}]’
/home/ray/home/test/src/alloc.cpp:95:46:   required from here
/home/ray/home/test/src/alloc.cpp:31:82: error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
   31 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/test/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note: candidate: ‘template<class _Tp1> constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator<_Tp1>&) [with _Tp1 = _Tp1; _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  157 |  allocator(const allocator<_Tp1>&) _GLIBCXX_NOTHROW { }
      |  ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note:   template argument deduction/substitution failed:
/home/ray/home/test/src/alloc.cpp:31:82: note:   ‘const test::dummy_allocator<double, std::allocator<double> >’ is not derived from ‘const std::allocator<_Up>’
   31 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/test/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:147:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator< <template-parameter-1-1> >&) [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:147:34: note:   no known conversion for argument 1 from ‘const test::dummy_allocator<double, std::allocator<double> >’ to ‘const std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >&’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |                 ~~~~~~~~~~~~~~~~~^~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator() [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  144 |       allocator() _GLIBCXX_NOTHROW { }
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note:   candidate expects 0 arguments, 1 provided

Body:
I think your hunch is correct. One always has to be careful with perfect forwarding constructors and the normal copy constructor. I think there are multiple solutions but I haven't tested any of them yet.

First you could provide a better match than the perfect forwarding constructor by adding dummy_allocator(dummy_allocator&) forwarding to the normal copy constructor. The perfect forwarding constructor matches better than the copy constructor, when the passed dummy_allocator is not const and hence the copy constructor has to do const conversion. But this would require also overloading the move constructor (I think) since otherwise you get the same error when someone somewhere tries to move the dummy_allocator.

A bit more tricky but probably safer is doing the following:

template<class... Args>
dummy_allocator(Args&&... args) requires (sizeof...(Args) != 1) : alloc(std::forward<Args>(args)...) {}

template<class Arg>
dummy_allocator(Arg&& arg) requires (!std::is_same_v<std::decay_t<Arg>, dummy_allocator>) : alloc(std::forward<Arg>(arg)) {}

dummy_allocator(const dummy_allocator&) = default;

I hope I got the requires clauses right, I haven't worked much with that yet. But doing SFINAE in constructors is a royal pain in the ass.


问:
Best way to migrate eclipse installtion to another computer
as I need to switch computers (hardware), I would like to migrate my Eclipse installation:
Git/Maven setup, workspace, project settings and so on.

I have read a few hints about this and what I gathered is that copying the workspace completely is the best way to do.

Now most of the threads are already a few years old.

Will this work if I install Eclipse again from scratch or should I copy my Eclipse installation as well?

Or is there actually a better way by now?

答:
So, the best way appears to be:

export the preferences

export the projects


问:
Selenium is unable to find element with data-testid attribute
Trying to find the below element tried the following nothing works can anyone help.</p>

```<code><button data-testid="addToClientBasket"
        class="sc-kfGgVZ kcCRfu">
    <span><i class="icon-Expand_Cross_30_by_30"></i>Add To Basket</span>
</button>
</code>```

```<code>By.xpath("//button[@data-testid='addToClientBasket'");

By.xpath("//div[@id='root']/div/div/div/div[4]/div/div/div[2]/button/span";

By.cssSelector("button.sc-kfGgVZ.kcCRfu.added");

By.cssSelector("button.sc-kfGgVZ.kcCR");

By.cssSelector("button[class='sc-kfGgVZ kcCRfu']");

</code>```

答:
To identify the element with text as Add To Basket using Selenium you can use either of the following Locator Strategies:

cssSelector:

```<code>driver.findElement(By.cssSelector("button[data-testid='addToClientBasket']>span>i.icon-Expand_Cross_30_by_30"));
</code>```

xpath:

```<code>driver.findElement(By.xpath("//button[@data-testid='addToClientBasket']/span[contains(., 'Add To Basket')]"));
</code>```

Presumably, moving ahead you will be invoking click()on the element and in that case ideally you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

cssSelector:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[data-testid='addToClientBasket']>span>i.icon-Expand_Cross_30_by_30"))).click();
</code>```

xpath:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@data-testid='addToClientBasket']/span[contains(., 'Add To Basket')]"))).click();
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
Trying to find the below element tried the following nothing works can anyone help.

<button data-testid="addToClientBasket"
        class="sc-kfGgVZ kcCRfu">
    Add To Basket
</button>

By.xpath("//button[@data-testid='addToClientBasket'");

By.xpath("//div[@id='root']/div/div/div/div[4]/div/div/div[2]/button/span";

By.cssSelector("button.sc-kfGgVZ.kcCRfu.added");

By.cssSelector("button.sc-kfGgVZ.kcCR");

By.cssSelector("button[class='sc-kfGgVZ kcCRfu']");

Body:
To identify the element with text as Add To Basket using Selenium you can use either of the following Locator Strategies:

cssSelector:

driver.findElement(By.cssSelector("button[data-testid='addToClientBasket']>span>i.icon-Expand_Cross_30_by_30"));

xpath:

driver.findElement(By.xpath("//button[@data-testid='addToClientBasket']/span[contains(., 'Add To Basket')]"));

Presumably, moving ahead you will be invoking click()on the element and in that case ideally you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

cssSelector:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[data-testid='addToClientBasket']>span>i.icon-Expand_Cross_30_by_30"))).click();

xpath:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@data-testid='addToClientBasket']/span[contains(., 'Add To Basket')]"))).click();

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
Kotlin, IntelliJ: math operator not working

Ubuntu Mate 20.04

IntelliJ IDEA Community 2020.2 EAP, installed through Snap

Kotlin 1.3.72, installed through Snap

JRE 1.8.0_242-8u242-b08-0ubuntu3~16.04-b08

Project set up as Kotlin: JVM|IDEA using SDK 11 (java 11.0.6)

Code:

```<code>fun main(args: Array<String>) {
    var experiencePoints: Int = 5
    experiencePoints += 5
    println(experiencePoints)
}
</code>```

has a red squiggly line under the "+=" and produces the following error:

Error:(3, 22) Kotlin: Cannot access 'java.io.Serializable' which is a supertype of 'kotlin.Int'. Check your module classpath for missing or conflicting dependencies

Changed the code to the following:

```<code>fun main(args: Array<String>) {
    var experiencePoints: Int = 5
    experiencePoints = experiencePoints + 5
    println(experiencePoints)
}
</code>```

Red squiggly line beneath the "+" character and same error.

This is Day 1 for me, following example in "Kotlin Programming, The Big Nerd Ranch Guide" by Skeen and Greenhalgh. No idea what to do about this error.

答: I discovered that I didn't have default-jdk installed. Once I did, I found that there were extra options under File -> Project Structure -> Project -> Project SDK. I added user/lib/jvm/java-11-openjdk-amd64 java version "11.0.7" and the problem resolved.</p>

Body:
Ubuntu Mate 20.04

IntelliJ IDEA Community 2020.2 EAP, installed through Snap

Kotlin 1.3.72, installed through Snap

JRE 1.8.0_242-8u242-b08-0ubuntu3~16.04-b08

Project set up as Kotlin: JVM|IDEA using SDK 11 (java 11.0.6)

Code:

fun main(args: Array<String>) {
    var experiencePoints: Int = 5
    experiencePoints += 5
    println(experiencePoints)
}

has a red squiggly line under the "+=" and produces the following error:

Error:(3, 22) Kotlin: Cannot access 'java.io.Serializable' which is a supertype of 'kotlin.Int'. Check your module classpath for missing or conflicting dependencies

Changed the code to the following:

fun main(args: Array<String>) {
    var experiencePoints: Int = 5
    experiencePoints = experiencePoints + 5
    println(experiencePoints)
}

Red squiggly line beneath the "+" character and same error.

This is Day 1 for me, following example in "Kotlin Programming, The Big Nerd Ranch Guide" by Skeen and Greenhalgh. No idea what to do about this error.


问:
How can I set an AWS lambda to be triggered 24hs after the beginning of a process?
I have the follow schema  (using AWS-IoTCore and AWS-Lambdas) that starts upon some MQTT event. At the end of the main process a flag success is saved in the database. This process takes around 5 min. I would like to call a Lambda function 24hs after the beginning of the process to check if the flag exists in the database. How can I set this timeout or delay in the Lambda function without stepfunctions?

答:
You can use CloudWatch Events (or EventBridge) to schedule a Lambda function to run once, at a set time.

To create a CloudWatch Event rule, you can use the PutRule API operation to create the rule and then add the Lambda function as the target using PutTargets. The Lambda function should also allow CloudWatch Events to invoke the function in its function policy.

I also tested this out with the following cron expression: cron(0 0 1 1 ? 2021)

This would trigger the target Lambda function once at Fri, 01 Jan 2021 00:00:00 GMT. Also note, function may be invoked more than once due to CW invoking the function asynchronously. After the Lambda function has been invoked, you can delete the rule from the same function for clean-up.


问:
How to hide soft keyboard on android after clicking outside EditText?
Ok everyone knows that to hide a keyboard you need to implement:

```<code>InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
</code>```

But the big deal here is how to hide the keyboard when the user touches or selects any other place that is not an EditText or the softKeyboard?

I tried to use the onTouchEvent() on my parent Activity but that only works if user touches outside any other view and there is no scrollview.

I tried to implement a touch, click, focus listener without any success.

I even tried to implement my own scrollview to intercept touch events but I can only get the coordinates of the event and not the view clicked.

Is there a standard way to do this?? in iPhone it was really easy.

答:
I modified the answer @navneeth-g a bit, adding null activity focus processing, avoiding multiple instance creation OnTouchListener, remove focus when keyboard is hiding, and removed hiding the keyboard when the screen scrolls, convenient on small devices.</p>
```<code>//In general, the view parameter is root layout
fun Activity.hideKeyboardOnClickOutsideEditText(view: View) {
    // Set up touch listener for non-text box views to hide keyboard.
    var previousAction = 0
    val onTouchListener = View.OnTouchListener { v, event ->
        if (currentFocus != null
            && event.action != MotionEvent.ACTION_DOWN
            && event.action != MotionEvent.ACTION_MOVE
            && previousAction != MotionEvent.ACTION_MOVE
        ) {
            currentFocus?.clearFocus()
            v?.hideKeyboard()
        }
        previousAction = event.action
        false
    }

    if (view !is EditText) {
        view.setOnTouchListener(onTouchListener)
    }

    //If a layout container, iterate over children and seed recursion.
    if (view is ViewGroup) {
        for (i in 0 until view.childCount) {
            val innerView = view.getChildAt(i)
            hideKeyboardOnClickOutsideEditText(innerView)
        }
    }
}

//in root layout.xml
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
</code>```

Body:
Ok everyone knows that to hide a keyboard you need to implement:

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

But the big deal here is how to hide the keyboard when the user touches or selects any other place that is not an EditText or the softKeyboard?

I tried to use the onTouchEvent() on my parent Activity but that only works if user touches outside any other view and there is no scrollview.

I tried to implement a touch, click, focus listener without any success.

I even tried to implement my own scrollview to intercept touch events but I can only get the coordinates of the event and not the view clicked.

Is there a standard way to do this?? in iPhone it was really easy.

Body:
I modified the answer @navneeth-g a bit, adding null activity focus processing, avoiding multiple instance creation OnTouchListener, remove focus when keyboard is hiding, and removed hiding the keyboard when the screen scrolls, convenient on small devices.

//In general, the view parameter is root layout
fun Activity.hideKeyboardOnClickOutsideEditText(view: View) {
    // Set up touch listener for non-text box views to hide keyboard.
    var previousAction = 0
    val onTouchListener = View.OnTouchListener { v, event ->
        if (currentFocus != null
            && event.action != MotionEvent.ACTION_DOWN
            && event.action != MotionEvent.ACTION_MOVE
            && previousAction != MotionEvent.ACTION_MOVE
        ) {
            currentFocus?.clearFocus()
            v?.hideKeyboard()
        }
        previousAction = event.action
        false
    }

    if (view !is EditText) {
        view.setOnTouchListener(onTouchListener)
    }

    //If a layout container, iterate over children and seed recursion.
    if (view is ViewGroup) {
        for (i in 0 until view.childCount) {
            val innerView = view.getChildAt(i)
            hideKeyboardOnClickOutsideEditText(innerView)
        }
    }
}

//in root layout.xml
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"


问:
Domain Specific Language resources
I was just listening to some older .Net Rocks! episodes, and I found #329 on DSLs to be interesting. My problem is that I can't find any good online resources for people trying to learn this technology. I get the basics of the creating new designers, but the MS docs on the T4 engine used by the DSL tools and then how to integrate the templates with the DSL models are lacking.

Does anyone know of some good introductory resources for the MS DSL tools?

答: PODCAST:  DSL Related Discussions in SE-Radio

ContentLicense: CC BY-SA 2.5

Title: Domain Specific Language resources

LastEditorDisplayName: Jeff Atwood

OwnerDisplayName: Prakash


问:
Looking for stats on popularity of JavaScript libraries
Does anyone know if there's a site that tracks the popularity of the big/various JavaScript libraries?</p>

答:
Click on the "tags" link at the top of the page.

JQuery: 1970

Prototype: 135

Dojo: 71

Mootools: 39

Those numbers line up with my intuition on the subject; JQuery is dominating.

OwnerDisplayName: magenta

OwnerDisplayName: Chase Seibert


问:
What kind of HTMLPurifier settings do you use to purify CSS?
I'm building an application which lets users input custom CSS for their own profiles (kinda like MySpace, Friendster, or Blogger).

The problem is I'm having a hard time finding a way to purify XSS attacks through CSS. I tried using HTMLPurifier, but it doesn't work. One example:

```<code>html {
    expression: alert('xss');
}

body {
    background-color: #FFF;
}
</code>```

This would be allowed by HTMLPurifier.

Are there any settings I need to use for HTMLPurifier to make this invalid?

Thanks!

Update

Is expression: the only way to push an exploit via CSS? If so, would a regular expression be more efficient than using HTMLPurifier?

答:
HTML Purifier operates on HTML input, not CSS. That being said, you can probably trick it to work on CSS style sheets by wrapping the style sheet in style tags and turning on %Filter.ExtractStyleBlocks. You'll need CSS Tidy installed.

Update. No. There are many ways to deliver CSS payloads and searching for expression is not enough.

Body:
I'm building an application which lets users input custom CSS for their own profiles (kinda like MySpace, Friendster, or Blogger).

The problem is I'm having a hard time finding a way to purify XSS attacks through CSS. I tried using HTMLPurifier, but it doesn't work. One example:

html {
    expression: alert('xss');
}

body {
    background-color: #FFF;
}

This would be allowed by HTMLPurifier.

Are there any settings I need to use for HTMLPurifier to make this invalid?

Thanks!

Update

Is expression: the only way to push an exploit via CSS? If so, would a regular expression be more efficient than using HTMLPurifier?


问:
Django model_to_dict stack overflow crash
In my app, I use a common Base model for all my models. I'v encountered a behaviour I can't explain with the Campus and Hall models:

class Base(models.Model):
    id: int = models.AutoField(primary_key=True, editable=False)

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._initial = self.as_dict

    ...
    @property
    def as_dict(self) -> dict:
        fields = [field.name for field in self._meta.fields]
        res = model_to_dict(self, fields=fields)
        return res
    ...

class Campus(Base):
    name: str = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "campuses"

    def __str__(self):
        return self.name

class Hall(Base):
    name: str = models.CharField(max_length=100)
    campus: Campus = models.ForeignKey(Campus, on_delete=models.SET_NULL, null=True)

    def save(self, *args, **kwargs):
        if self.campus is not None and isinstance(self.campus, str):
            self.campus = Campus.objects.get_or_create(name=self.campus)[0]
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.name}{f' ({self.campus})' if self.campus else ''}"
```

<p>On the admin console, when I try to delete a certain <code>Campus</code> instance, the server crashes. This is a very small part of the (very long) trace:</p>

```Fatal Python error: Cannot recover from stack overflow.
...
Current thread 0x00000bdc (most recent call first):
...
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 411 in get
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 627 in refresh_from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query_utils.py", line 139 in __get__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\fields\__init__.py", line 931 in value_from_object
  File "C:\Venvs\Coursist\lib\site-packages\django\forms\models.py", line 93 in model_to_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 411 in get
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 627 in refresh_from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query_utils.py", line 139 in __get__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\fields\__init__.py", line 931 in value_from_object
  File "C:\Venvs\Coursist\lib\site-packages\django\forms\models.py", line 93 in model_to_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
...
```

At first I thought it is some kind of circular pointing issue between Hall and Campus, but that doesn't seem to be the case (when debugging, I can't see any pointer from Campus to a Hall). The weird thing is that if I first delete all Hall instances, the deletion of the Campus goes smoothly.

I'm using python 3.7 and Django 3.0.6

答:
After some debugging, I came up with this patch:

class Base(models.Model):
    id: int = models.AutoField(primary_key=True, editable=False)
...
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if models.DEFERRED in args:
            # This means we delete it now, not interested in dict logic
            self._initial = dict()
        else:
            self._initial = self.as_dict
...
```

Not sure this is an elegant/correct solution, but it solved this bug and everything else seems to work fine.

If anyone else has any better ideas I would love to hear.

Body:
In my app, I use a common Base model for all my models. I'v encountered a behaviour I can't explain with the Campus and Hall models:

class Base(models.Model):
    id: int = models.AutoField(primary_key=True, editable=False)

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._initial = self.as_dict

    ...
    @property
    def as_dict(self) -> dict:
        fields = [field.name for field in self._meta.fields]
        res = model_to_dict(self, fields=fields)
        return res
    ...

class Campus(Base):
    name: str = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "campuses"

    def __str__(self):
        return self.name

class Hall(Base):
    name: str = models.CharField(max_length=100)
    campus: Campus = models.ForeignKey(Campus, on_delete=models.SET_NULL, null=True)

    def save(self, *args, **kwargs):
        if self.campus is not None and isinstance(self.campus, str):
            self.campus = Campus.objects.get_or_create(name=self.campus)[0]
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.name}{f' ({self.campus})' if self.campus else ''}"

On the admin console, when I try to delete a certain Campus instance, the server crashes. This is a very small part of the (very long) trace:

Fatal Python error: Cannot recover from stack overflow.
...
Current thread 0x00000bdc (most recent call first):
...
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 411 in get
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 627 in refresh_from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query_utils.py", line 139 in __get__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\fields\__init__.py", line 931 in value_from_object
  File "C:\Venvs\Coursist\lib\site-packages\django\forms\models.py", line 93 in model_to_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 411 in get
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 627 in refresh_from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query_utils.py", line 139 in __get__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\fields\__init__.py", line 931 in value_from_object
  File "C:\Venvs\Coursist\lib\site-packages\django\forms\models.py", line 93 in model_to_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
...

At first I thought it is some kind of circular pointing issue between Hall and Campus, but that doesn't seem to be the case (when debugging, I can't see any pointer from Campus to a Hall). The weird thing is that if I first delete all Hall instances, the deletion of the Campus goes smoothly.

I'm using python 3.7 and Django 3.0.6

Body:
After some debugging, I came up with this patch:

class Base(models.Model):
    id: int = models.AutoField(primary_key=True, editable=False)
...
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if models.DEFERRED in args:
            # This means we delete it now, not interested in dict logic
            self._initial = dict()
        else:
            self._initial = self.as_dict
...

Not sure this is an elegant/correct solution, but it solved this bug and everything else seems to work fine.

If anyone else has any better ideas I would love to hear.


问:
jquery detecting div of certain class has been added to DOM
I'm using .on() to bind events of divs that get created after the page loads. It works fine for click, mouseenter... but I need to know when a new div of class MyClass has been added. I'm looking for this:

```<code>$('#MyContainer').on({

  wascreated: function () { DoSomething($(this)); }

}, '.MyClass');
</code>```

How do I do this? I've managed to write my entire app without a plugin and I want to keep it that way.

Thanks.

答:
Two additions to adeneo's answer:

(1) we can change the line

```<code>return el.classList.contains('MyClass');
</code>```

To

```<code>if( el.classList ) {
    return el.classList.contains('MyClass');
} else {
    return false;
}
</code>```

So we won't see the "Uncaught TypeError: Cannot read property 'contains' of undefined" error.

(2) add subtree: true in config to find added nodes recursively in all added elements.

Body:
I'm using .on() to bind events of divs that get created after the page loads. It works fine for click, mouseenter... but I need to know when a new div of class MyClass has been added. I'm looking for this:

$('#MyContainer').on({

  wascreated: function () { DoSomething($(this)); }

}, '.MyClass');

How do I do this? I've managed to write my entire app without a plugin and I want to keep it that way.

Thanks.

Body:
Two additions to adeneo's answer:

(1) we can change the line

return el.classList.contains('MyClass');

To

if( el.classList ) {
    return el.classList.contains('MyClass');
} else {
    return false;
}

So we won't see the "Uncaught TypeError: Cannot read property 'contains' of undefined" error.

(2) add subtree: true in config to find added nodes recursively in all added elements.


问:
Double header guards in Visual Studio stl numeric implementation
In the stl implementation that comes along with Visual Studio 12.0 the numeric header looks like this

```<code>#pragma once
#ifndef _NUMERIC_
#define _NUMERIC_

// shortened for the sake of readibility
.
.
.

#endif /* _NUMERIC_ */
</code>```

I know that #pragma once is not standard conform.

Nevertheless, why did they implement a double header guard?

答:
#pragma once: The same file will not be included multiple times
include guard idiom：uses preprocessor macro definitions to prevent multiple inclusions of the contents of the file.

According to the Doc

There's no advantage to use of both the include guard idiom and
  #pragma once in the same file. The compiler recognizes the include guard idiom, and implements the multiple-include optimization the same
  way as the #pragma once directive if no non-comment code or
  preprocessor directive comes before or after the standard form of the
  idiom

I suggest you could refer to the link:https://stackoverflow.com/a/13339535/11872808

Body:
In the stl implementation that comes along with Visual Studio 12.0 the numeric header looks like this

#pragma once
#ifndef _NUMERIC_
#define _NUMERIC_

// shortened for the sake of readibility
.
.
.

#endif /* _NUMERIC_ */

I know that #pragma once is not standard conform.

Nevertheless, why did they implement a double header guard?


问:
how to remove the line if it contain the "word"? in python
I have an input file looks like this

```<code>test.txt
CAT 396 NUM 59
X          Y
4.7642     28.4443
4.7643     28.3640
6.2216     29.0680
6.2217     29.2841
6.4080     28.6427
6.6484     28.6484

CAT 397 NUM 592
X          Y
7.0442     23.8320
7.0994     25.9161
7.0995     25.1801
</code>```

I only need the X and Y coordinate information.

How would I be able to only get the coordinates?

答:
You may try this:</p>

```<code>with open('test.txt') as fin :
    lines = fin.readlines()

coords = []
for line in lines :
    try :
        x, y = map( float, line.split())
        coords.append( (x,y) )
    except ValueError:
        pass  # ignore other lines
</code>```

Body:
I have an input file looks like this

test.txt
CAT 396 NUM 59
X          Y
4.7642     28.4443
4.7643     28.3640
6.2216     29.0680
6.2217     29.2841
6.4080     28.6427
6.6484     28.6484

CAT 397 NUM 592
X          Y
7.0442     23.8320
7.0994     25.9161
7.0995     25.1801

I only need the X and Y coordinate information.

How would I be able to only get the coordinates?

Body:
You may try this:

with open('test.txt') as fin :
    lines = fin.readlines()

coords = []
for line in lines :
    try :
        x, y = map( float, line.split())
        coords.append( (x,y) )
    except ValueError:
        pass  # ignore other lines