问:
How to implement the Luhn alorithm in OCL
I am trying to find the Luhn algorithm in OCL to check the validity of ISIN. Can anyone provide a code example would it be great!   </p>

答:
Create a class:

```<code>   Attribute NextMult1Or2:Integer
   Method MultWith2Or1SumBiggerThan10(v:Integer):Integer
   Method GetCheckSum(input:String):Integer
</code>```

The first method MultWith2Or1SumBiggerThan10:

```<code>let res=v*self.NextMult1Or2 in
(
  if self.NextMult1Or2=2 then
    self.NextMult1Or2:=1
  else
    self.NextMult1Or2:=2
  endif;
 if res>10 then
  res-9
 else
  res
 endif
)
</code>```

And the second method GetCheckSum(input:String):Integer

```<code>self.NextMult1Or2:=2;
input.ToCharArray->collect(c|
  let i=Integer.Parse(c) in (
    self.MultWith2Or1SumBiggerThan10(i)
  )
)->sum
</code>```

To calculate the checksum - send in all but check digit to GetCheckSum - the check digit is (((res+10) / 10).Truncate*10)-res  (ie the diff from nearest 10:th above)

To check a sequence send in all including check digit to GetCheckSum - if res.Mod(10)= 0 it has passed

Body:
Create a class:

   Attribute NextMult1Or2:Integer
   Method MultWith2Or1SumBiggerThan10(v:Integer):Integer
   Method GetCheckSum(input:String):Integer

The first method MultWith2Or1SumBiggerThan10:

let res=v*self.NextMult1Or2 in
(
  if self.NextMult1Or2=2 then
    self.NextMult1Or2:=1
  else
    self.NextMult1Or2:=2
  endif;
 if res>10 then
  res-9
 else
  res
 endif
)

And the second method GetCheckSum(input:String):Integer

self.NextMult1Or2:=2;
input.ToCharArray->collect(c|
  let i=Integer.Parse(c) in (
    self.MultWith2Or1SumBiggerThan10(i)
  )
)->sum

To calculate the checksum - send in all but check digit to GetCheckSum - the check digit is (((res+10) / 10).Truncate*10)-res  (ie the diff from nearest 10:th above)

To check a sequence send in all including check digit to GetCheckSum - if res.Mod(10)= 0 it has passed


来源: stackexchange

问:
why is the address the same?

why is the address of temp (in the while loop in main) the same everytime the loop runs
  i am trying to insert into a linked list and then display and then output the middle element but initially in displaying it ran an infinite loop only displayint the first element. On printing the address after inserting and llist.add_ele_to_beg(&temp); its priting the same address each time ! why is this happening ?

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

using namespace std;

class LinkedList;
class Node
{
    private:
    Node* next;
    int value;
    friend class LinkedList;
    public:
    Node(int ele) // constructor - declared in private section
    // to prevent other classes creating objects of this class,
    // only this class can create the object
    {
        next = nullptr;
        value = ele;
    }
};

class LinkedList
{
    private:
    Node* head;
    public:
    LinkedList()
    {
        head = nullptr;
    }
    void add_ele_to_beg(Node *temp)
    {
        // Node *temp = new Node(); // dynamically alloctg Node object
        // temp->value = x;
        temp->next = this->head;
        this->head = temp;
    }
    void display()
    {
        Node *h = this->head;
        while(h)
        {
            cout << h << endl;
            cout << h->value << endl;
            h = h->next;
            cout << h << endl;
            cout << h->value << endl;
            exit(0);
        }
    }
    int findMiddle()
    {
        Node *fast, *slow = this->head;
        if(!slow)
        {
            return -1;
        }
        if(!slow->next)
        {
            return slow->value;
        }
        if(!slow->next->next)
        {
            return slow->value;
        }
        // n > 2
        fast = head->next->next;

        while(1)
        {
            slow = slow->next;
            if(!fast->next)
            {
                if(!fast->next->next)
                {
                    fast = fast->next->next;
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        return slow->value;
    }
};

int main()
{
    LinkedList llist;
    int n;
    cout << "enter n" << endl;
    cin >> n;
    // create a dummy node
    cout << "enter elements to be inserted in the beg" << endl;
    int ele;
    while(n--)
    {
        cin >> ele;
        Node temp(ele); // obj node created and ctor initialises
        llist.add_ele_to_beg(&temp); // sending address of node to make change to
        cout << &temp << endl;
        // node (passing by reference)
    }

    llist.display();

    cout << llist.findMiddle();
    cout << endl;
    return 0;
}
</code>```

答: You can create a new element using new Node() in each loop cycle.

ContentLicense: CC BY-SA 4.0

Title: why is the address the same?

Body:
why is the address of temp (in the while loop in main) the same everytime the loop runs
  i am trying to insert into a linked list and then display and then output the middle element but initially in displaying it ran an infinite loop only displayint the first element. On printing the address after inserting and llist.add_ele_to_beg(&temp); its priting the same address each time ! why is this happening ?

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

using namespace std;

class LinkedList;
class Node
{
    private:
    Node* next;
    int value;
    friend class LinkedList;
    public:
    Node(int ele) // constructor - declared in private section
    // to prevent other classes creating objects of this class,
    // only this class can create the object
    {
        next = nullptr;
        value = ele;
    }
};

class LinkedList
{
    private:
    Node* head;
    public:
    LinkedList()
    {
        head = nullptr;
    }
    void add_ele_to_beg(Node *temp)
    {
        // Node *temp = new Node(); // dynamically alloctg Node object
        // temp->value = x;
        temp->next = this->head;
        this->head = temp;
    }
    void display()
    {
        Node *h = this->head;
        while(h)
        {
            cout << h << endl;
            cout << h->value << endl;
            h = h->next;
            cout << h << endl;
            cout << h->value << endl;
            exit(0);
        }
    }
    int findMiddle()
    {
        Node *fast, *slow = this->head;
        if(!slow)
        {
            return -1;
        }
        if(!slow->next)
        {
            return slow->value;
        }
        if(!slow->next->next)
        {
            return slow->value;
        }
        // n > 2
        fast = head->next->next;

        while(1)
        {
            slow = slow->next;
            if(!fast->next)
            {
                if(!fast->next->next)
                {
                    fast = fast->next->next;
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        return slow->value;
    }
};

int main()
{
    LinkedList llist;
    int n;
    cout << "enter n" << endl;
    cin >> n;
    // create a dummy node
    cout << "enter elements to be inserted in the beg" << endl;
    int ele;
    while(n--)
    {
        cin >> ele;
        Node temp(ele); // obj node created and ctor initialises
        llist.add_ele_to_beg(&temp); // sending address of node to make change to
        cout << &temp << endl;
        // node (passing by reference)
    }

    llist.display();

    cout << llist.findMiddle();
    cout << endl;
    return 0;
}


问:
Received failure with description 'Failure' in while uploading to SFTP server with FileZilla
I faced this issue many times. While uploading or editing any file from FileZilla it its showing error message

Error: error while writing: received failure with description 'Failure'.

After the upload file the file size will be 0 byte.

My server is AWS EC2 with Minimum instance class type.

答:
I created a file (without an extension) instead of a folder by mistake. When I tried to create a folder with the same name, I had the same error as yours.

To fix issue, I removed the file and created the folder again.


问:
Checking array for a value
I have an array as below.

```<code>testgrid = [
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6]]
</code>```

On passing the testgrid into the following function it should return all indexes that do not contain a value of zero currently it returns (0, 0).  I would expect all indexes to be returned on this grid. It seems to be checking the indexes rather than the value stored at that index.  I am a noob so probably am missing something obvious here.

```<code>def not_empty_location(grid):

    # checks if current location is empty and assign location not empty
    for i in range(9):
        for j in range(9):
            if grid[i][j] != 0:
                return (i, j)
    return None
</code>```

Title: Checking array for a value

Body:
I have an array as below.

testgrid = [
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6]]

On passing the testgrid into the following function it should return all indexes that do not contain a value of zero currently it returns (0, 0).  I would expect all indexes to be returned on this grid. It seems to be checking the indexes rather than the value stored at that index.  I am a noob so probably am missing something obvious here.

def not_empty_location(grid):

    # checks if current location is empty and assign location not empty
    for i in range(9):
        for j in range(9):
            if grid[i][j] != 0:
                return (i, j)
    return None

Body:
Use yield instead of return:

def not_empty_location(grid):

    # checks if current location is empty and assign location not empty
    for i in range(9):
        for j in range(9):
            if grid[i][j] != 0:
                yield (i, j)
    return None

This would return all the values as a generator which can then simply be converted into a list.

Output:

[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7), (7, 8), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 8)]


问:
How to save PDF preview images in Rails Active Storage?
So I am using Active Storage to attach PDFs to my models, which all works perfectly fine. As part of my project, I am asked to display PDF previews on one particular resource page that lists all available PDFs on the site for download (25+). I am using the standard config - PopplerPDFPreviewer & MuPDFPreviewer.

```<code>irb(main):001:0> Rails.application.config.active_storage.previewers
=> [ActiveStorage::Previewer::PopplerPDFPreviewer, ActiveStorage::Previewer::MuPDFPreviewer, ActiveStorage::Previewer::VideoPreviewer]
</code>```

The code:

```<code>- @products.each do |product|
  - if product.installation_guide.attached?
    - if product.installation_guide.previewable?
      = image_tag product.installation_guide.preview(resize: '200x200')
</code>```

This works too, however, now and then I get a time out and too many request message since it keeps regenerating the images.

```<code>@net_http_res   #<Net::HTTPTooManyRequests 429 Too Many Requests readbody=true>
</code>```

Which is not good!

Now api.rubyonrails.org proposes to generate a stable URL (not view) with .processed.service_url that redirects to the short-lived URL that will be returned by .service_url.

```<code>blob.preview(resize_to_limit: [100, 100]).processed.service_url
</code>```

Ok, but again, it means that I have to keep regenerating the previews... Is there a way to generate a preview when uploading the PDF, and save that preview until it is deleted or replaced?

答: This only occurs on Development environment. On production (Ubuntu 18.04) it works like a charm. </p>

Body:
So I am using Active Storage to attach PDFs to my models, which all works perfectly fine. As part of my project, I am asked to display PDF previews on one particular resource page that lists all available PDFs on the site for download (25+). I am using the standard config - PopplerPDFPreviewer & MuPDFPreviewer.

irb(main):001:0> Rails.application.config.active_storage.previewers
=> [ActiveStorage::Previewer::PopplerPDFPreviewer, ActiveStorage::Previewer::MuPDFPreviewer, ActiveStorage::Previewer::VideoPreviewer]

The code:

- @products.each do |product|
  - if product.installation_guide.attached?
    - if product.installation_guide.previewable?
      = image_tag product.installation_guide.preview(resize: '200x200')

This works too, however, now and then I get a time out and too many request message since it keeps regenerating the images.

@net_http_res   #<Net::HTTPTooManyRequests 429 Too Many Requests readbody=true>

Which is not good!

Now api.rubyonrails.org proposes to generate a stable URL (not view) with .processed.service_url that redirects to the short-lived URL that will be returned by .service_url.

blob.preview(resize_to_limit: [100, 100]).processed.service_url

Ok, but again, it means that I have to keep regenerating the previews... Is there a way to generate a preview when uploading the PDF, and save that preview until it is deleted or replaced?


问:
Am i violating any NF RULE on my database design?
Good day!

I am a newbie on creating database... I need to create a db for my recruitment web application.

My database schema is as follows:

NOTE: I included the applicant_id on other tables... e.g. exam, interview, exam type.

Am i violating any normalization rule? If i do, what do you recommend to improve my design? Thank you

答:
Age and gender are generally illegal questions to ask in interviews so you may not want to record such things. You might want a separate interviewer table. You also might want a separate table that stores qualifications so you can search for people you have interviewed with C# knowledge when the next opening comes up. I'd probably do something like a Qualifications table that is the lookup for quals you want to add to the applicant qualfications table. Then you'd need the qualification id, applicantId, years, skill level in the Applicant Qualification table.

I notice results is a varchar 4 field, I assume you are planning to put Pass/fail in it. I would consider having a numeric score as well. The guy who got 80% of the questions right passed but the guy who got 100% of them right might be the better candidate. In fact for interviews I might have interview questions and results tables.  Then you can record the score and any comments about each question which can help later in evaluation of a lot of candidates. We did this manually in paper spreadsheets once when we were interviewing several hundred people (we had over a hundred openings at the time and this was way before personal computers)  and found it most helpful to be able to compare answers to questions. It's hard to remember 200 people you interviewed and who said what. It might help later when you have a new opening to find the people who were strong onthe questions most pertinent to the new job who might not have been given a job at the time of the interview(5 excellent candidates, 1 job for instance).

I might also consider a field to mark if the candidate is unaccepatble for ever hiring for some reason. Such as he committed a felony or he lied on the resume and you caught him or he was just totally clueless in the interview. This can make it easy to prevent this person from being considered repeatedly.

ContentLicense: CC BY-SA 3.0


问:
Couldn't install pylint in Python2.7 and get not matched errors even install with the local setup.py
For the developing environment constrained I have to use Python2.7 in the Windows10.

So I choose to install pylint as the linter I use in the Administrator Mode.

```<code>pip install "pylint<2.0.0"
</code>```

But it only outputs as follows:

WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None))
  after connection broken by 'ConnectTimeoutError(,
  'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

And this message repeat many times then give such output:

ERROR: Could not find a version that satisfies the requirement pylint<2.0.0 (from versions: none)
  ERROR: No matching distribution found for pylint<2.0.0

So I download a 1.9.3 version in the PyPI.

And tried to install it with setup.py in the Administrator Mode as follows:

```<code>python setup.py install
</code>```

BUT also get the same problems as before:

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

ERROR: Could not find a version that satisfies the requirement pylint==1.9.3 (from versions: none)

ERROR: No matching distribution found for pylint==1.9.3

And I also tried the older version like 1.8.4, 1.7.4 and so on.

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

ERROR: Could not find a version that satisfies the requirement pytest-runner (from versions: none)

ERROR: No matching distribution found for pytest-runner

Traceback (most recent call last):

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\installer.py", line 128, in fetch_build_egg

subprocess.check_call(cmd)

File "C:\ProgramData\Anaconda3\lib\subprocess.py", line 363, in check_call

```<code>raise CalledProcessError(retcode, cmd)
</code>```

subprocess.CalledProcessError: Command '['C:\ProgramData\Anaconda3\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\Users\EU\AppData\Local\Temp\tmpyjj78l40', '--quiet', 'pytest-runner']' returned non-zero exit status 1.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "setup.py", line 178, in

```<code>install()
</code>```

File "setup.py", line 175, in install

**kwargs)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools__init__.py", line 143, in setup

_install_setup_requires(attrs)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools__init__.py", line 138, in _install_setup_requires

dist.fetch_build_eggs(dist.setup_requires)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\dist.py", line 721, in fetch_build_eggs

replace_conflicting=True,

File "C:\ProgramData\Anaconda3\lib\site-packages\pkg_resources__init__.py", line 783, in resolve

replace_conflicting=replace_conflicting

File "C:\ProgramData\Anaconda3\lib\site-packages\pkg_resources__init__.py", line 1066, in best_match

return self.obtain(req, installer)

File "C:\ProgramData\Anaconda3\lib\site-packages\pkg_resources__init__.py", line 1078, in obtain

return installer(requirement)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\dist.py", line 777, in fetch_build_egg

return fetch_build_egg(self, req)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\installer.py", line 130, in fetch_build_egg

raise DistutilsError(str(e))

distutils.errors.DistutilsError: Command '['C:\ProgramData\Anaconda3\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\Users\EU\AppData\Local\Temp\tmpyjj78l40', '--quiet', 'pytest-runner']' returned non-zero exit status 1.

BUT it still got other problems here, which is messed with me all day.

So could anyone help me or give some hints?

Thanks in advances.

答:
First of all, you should avoid Python2.7 if possible, since it is no longer supported.

You might be behind a firewall that blocks these connections. If that's your problem, try this.

Body:
For the developing environment constrained I have to use Python2.7 in the Windows10.

So I choose to install pylint as the linter I use in the Administrator Mode.

pip install "pylint<2.0.0"

But it only outputs as follows:

WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None))
  after connection broken by 'ConnectTimeoutError(,
  'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

And this message repeat many times then give such output:

ERROR: Could not find a version that satisfies the requirement pylint<2.0.0 (from versions: none)
  ERROR: No matching distribution found for pylint<2.0.0

So I download a 1.9.3 version in the PyPI.

And tried to install it with setup.py in the Administrator Mode as follows:

python setup.py install

BUT also get the same problems as before:

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pylint/

ERROR: Could not find a version that satisfies the requirement pylint==1.9.3 (from versions: none)

ERROR: No matching distribution found for pylint==1.9.3

And I also tried the older version like 1.8.4, 1.7.4 and so on.

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/pytest-runner/

ERROR: Could not find a version that satisfies the requirement pytest-runner (from versions: none)

ERROR: No matching distribution found for pytest-runner

Traceback (most recent call last):

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\installer.py", line 128, in fetch_build_egg

subprocess.check_call(cmd)

File "C:\ProgramData\Anaconda3\lib\subprocess.py", line 363, in check_call

raise CalledProcessError(retcode, cmd)

subprocess.CalledProcessError: Command '['C:\ProgramData\Anaconda3\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\Users\EU\AppData\Local\Temp\tmpyjj78l40', '--quiet', 'pytest-runner']' returned non-zero exit status 1.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "setup.py", line 178, in

install()

File "setup.py", line 175, in install

**kwargs)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools__init__.py", line 143, in setup

_install_setup_requires(attrs)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools__init__.py", line 138, in _install_setup_requires

dist.fetch_build_eggs(dist.setup_requires)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\dist.py", line 721, in fetch_build_eggs

replace_conflicting=True,

File "C:\ProgramData\Anaconda3\lib\site-packages\pkg_resources__init__.py", line 783, in resolve

replace_conflicting=replace_conflicting

File "C:\ProgramData\Anaconda3\lib\site-packages\pkg_resources__init__.py", line 1066, in best_match

return self.obtain(req, installer)

File "C:\ProgramData\Anaconda3\lib\site-packages\pkg_resources__init__.py", line 1078, in obtain

return installer(requirement)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\dist.py", line 777, in fetch_build_egg

return fetch_build_egg(self, req)

File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\installer.py", line 130, in fetch_build_egg

raise DistutilsError(str(e))

distutils.errors.DistutilsError: Command '['C:\ProgramData\Anaconda3\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\Users\EU\AppData\Local\Temp\tmpyjj78l40', '--quiet', 'pytest-runner']' returned non-zero exit status 1.

BUT it still got other problems here, which is messed with me all day.

So could anyone help me or give some hints?

Thanks in advances.


问:
How to convert PDF to Excel on a Mac?
I have a lot of PDFs to convert to excel. I found the code below which converts PDF to excel by opening the pdf file in word but it fails at Dim fso As New FileSystemObject because mac excel does not have scripting dictionary. How do I amend the code to open the PDF files in word without having to use scripting dictionary?

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

Dim setting_sh As Worksheet
Set setting_sh = ThisWorkbook.Sheets("Setting")
Dim pdf_path As String
Dim excel_path As String

pdf_path = setting_sh.Range("E11").Value
excel_path = setting_sh.Range("E12").Value

Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File

Set fo = fso.Getfolder(pdf_path)

Dim wa As Object
Dim doc As Object
Dim wr As Object

Set wa = CreateObject("word.application")
wa.Visible = True

Dim nwb As Workbook
Dim nsh As Worksheet

For Each f In fo.Files

Set doc = wa.documents.Open(f.Path, False, Format:="PDF files")
Set wr = doc.Paragraphs(1).Range
wr.WholeStory

Set nwb = Workbooks.Add
Set nsh = nwb.Sheets(1)

wr.Copy
nsh.Paste
nwb.SaveAs (excel_path & "\" & Replace(f.Name, ".pdf", ".xlsx"))

doc.Close False
nwb.Close False
Next

wa.Quit

MsgBox "Done"

End Sub
</code>```

答: There are other ways to do this which requires no programing. One is to use the app PDFelement. This app is not cheap but if you scroll down on the linked site the is a free download option.  There are other ways given by this link. One of these is an online site that will convert your PDF to excel but the site has pretty generous restictions on the size of the PDF file.</p>

Title: How to convert PDF to Excel on a Mac?

Body:
I have a lot of PDFs to convert to excel. I found the code below which converts PDF to excel by opening the pdf file in word but it fails at Dim fso As New FileSystemObject because mac excel does not have scripting dictionary. How do I amend the code to open the PDF files in word without having to use scripting dictionary?

Option Explicit
Sub pdf_to_excel()

Dim setting_sh As Worksheet
Set setting_sh = ThisWorkbook.Sheets("Setting")
Dim pdf_path As String
Dim excel_path As String

pdf_path = setting_sh.Range("E11").Value
excel_path = setting_sh.Range("E12").Value

Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File

Set fo = fso.Getfolder(pdf_path)

Dim wa As Object
Dim doc As Object
Dim wr As Object

Set wa = CreateObject("word.application")
wa.Visible = True

Dim nwb As Workbook
Dim nsh As Worksheet

For Each f In fo.Files

Set doc = wa.documents.Open(f.Path, False, Format:="PDF files")
Set wr = doc.Paragraphs(1).Range
wr.WholeStory

Set nwb = Workbooks.Add
Set nsh = nwb.Sheets(1)

wr.Copy
nsh.Paste
nwb.SaveAs (excel_path & "\" & Replace(f.Name, ".pdf", ".xlsx"))

doc.Close False
nwb.Close False
Next

wa.Quit

MsgBox "Done"

End Sub


问:
What exactly does the timeZone option do in Intl.DateTimeFormat()
I have difficulties to understand what the timeZone option in the Intl.DateTimeFormat() method exactly does. I could not find an in-depth resource on this, yet. Any explanation would be much appreciated.

Background: We need to display the timestamp of a backend server on the frontend and had some issues with the timezone offset. At the moment, I believe the solution to display the correct time depending on the local client time is the following:

```<code>Intl.DateTimeFormat('en-GB', {
          hour: 'numeric',
          minute: 'numeric',
          second: 'numeric',
          timeZone: 'GMT'
        }).format(timestamp)}
</code>```

I do not fully understand, why I need to pass the option timeZone: 'GMT' for "Greenwich Mean Time' to get the correct time on the frontend.

答:
The time zone is used to calculate the local time:

const timeZones = [
    "GMT",
    "Europe/Madrid",
    "Asia/Tokyo"
];
const timestamp = new Date();
let displayDate;
for (timeZone of timeZones) {
    displayDate = Intl.DateTimeFormat('en-GB', {
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric',
        timeZone: timeZone
    }).format(timestamp);
    console.log("%s @ %s", displayDate, timeZone);
}```
</div>
</div>
</p>
<p>If omitted altogether, it will default to current local time zone in the JavaScript runtime where the code runs:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let displayDate = Intl.DateTimeFormat('en-GB', {
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
}).format(new Date());
console.log(displayDate);</code>```

So the property can be used to make it explicit/static or to be able to use other time zones.

Body:
I have difficulties to understand what the timeZone option in the Intl.DateTimeFormat() method exactly does. I could not find an in-depth resource on this, yet. Any explanation would be much appreciated.

Background: We need to display the timestamp of a backend server on the frontend and had some issues with the timezone offset. At the moment, I believe the solution to display the correct time depending on the local client time is the following:

Intl.DateTimeFormat('en-GB', {
          hour: 'numeric',
          minute: 'numeric',
          second: 'numeric',
          timeZone: 'GMT'
        }).format(timestamp)}

I do not fully understand, why I need to pass the option timeZone: 'GMT' for "Greenwich Mean Time' to get the correct time on the frontend.

Body:
The time zone is used to calculate the local time:

const timeZones = [
    "GMT",
    "Europe/Madrid",
    "Asia/Tokyo"
];
const timestamp = new Date();
let displayDate;
for (timeZone of timeZones) {
    displayDate = Intl.DateTimeFormat('en-GB', {
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric',
        timeZone: timeZone
    }).format(timestamp);
    console.log("%s @ %s", displayDate, timeZone);
}

If omitted altogether, it will default to current local time zone in the JavaScript runtime where the code runs:

let displayDate = Intl.DateTimeFormat('en-GB', {
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
}).format(new Date());
console.log(displayDate);

So the property can be used to make it explicit/static or to be able to use other time zones.


问:
Wix Local Settings\App Data Shortcut
How can I create a shortcut using Wix with a target of "%UserProfile%\Local Settings\Application Data\Foo\Logs"?

```<code><Shortcut Id="LogsStartMenuShortcut"
  Name="Logs"
  Target="%UserProfile%\Local Settings\Application Data\FalconMobileServer\"
  Icon="icon.ico"/>
</code>```

It doesn't like the % signs in the target.

答:
Check out this site listing all the MSI-predefined directories - I would think you should find the one you're looking for in there somewhere :-)

This one here possibly?

LocalAppDataFolder Full path to the directory that serves as a data repository for local (non-roaming) applications.

OwnerDisplayName: James Thigpen

ContentLicense: CC BY-SA 2.5

Title: Wix Local Settings\App Data Shortcut

Body:
How can I create a shortcut using Wix with a target of "%UserProfile%\Local Settings\Application Data\Foo\Logs"?

<Shortcut Id="LogsStartMenuShortcut"
  Name="Logs"
  Target="%UserProfile%\Local Settings\Application Data\FalconMobileServer\"
  Icon="icon.ico"/>

It doesn't like the % signs in the target.


问:
Does Scala achieve good performance on Android? (June 2011)
I'm very new to scala and find many of its ideas very attractive. I've just discovered the scala for android project and I'm wondering if it could be expected to run well or perhaps even better than java?

Could it even be expected do some things better than java even if the processors are mostly single core in-order execution types at the moment?

If anyone has any example or experiences to share then please do!

答: The only "lag" would be the size of the apk, but if you use something like ProGuard it would represent only around 15k/25k more, nothing significant at all. As of performance, for what i've seen is the same. I mean, it is not worse (as happens with Clojure, being dynamically typed), but i think it's the same as Java.</p>


问:
How to check if an item is in a generator in Python with less Time Complexity
```<code>gen = (i for i in range(1000))
print(555 in gen) #True
</code>```

We can check if an element exists in a generator using the in operator.

What is the time complexity?

What is the best approach to reduce time complexity while searching for an element in a generator?

答:
You can reduce time complexity by using a set:

```<code>gen = {i for i in range(1000)}
print(555 in gen) #True
</code>```

Sets are unordered, but hashed for faster lookups. Hope that helps, Happy Coding!

Body:
gen = (i for i in range(1000))
print(555 in gen) #True

We can check if an element exists in a generator using the in operator.

What is the time complexity?

What is the best approach to reduce time complexity while searching for an element in a generator?

Body:
You can reduce time complexity by using a set:

gen = {i for i in range(1000)}
print(555 in gen) #True

Sets are unordered, but hashed for faster lookups. Hope that helps, Happy Coding!


问:
Google Map API on release apk
im using google api on my app with android studio.
i added my SHA-1 keys to google cloud platform.
one is for debug version and another one is for release version ( same API key with different SHA-1 keys )
my debug version is working fine but when i make a signed apk , it doesn't work !
i checked google_maps_api.xml file and it's fine ( i have it on debug and also on main folders of the app )
i added my api key to AndroidManifestes with "com.google.android.maps.v2.API_KEY" and also tied "com.google.android.geo.API_KEY" but still not working !</p>

答:
You have to provide 2 keys in AndroidManifest.xml file for using google map and google api.

```<code><!--Google MAP API key-->
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="@string/google_map_key" />
<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="@string/google_map_api_key" />
</code>```

These 2 keys should be generated in Get an API Key.

If you use the api keys in production mode, you have to restrict the API key before using it in production.

Title: Google Map API on release apk

Body:
You have to provide 2 keys in AndroidManifest.xml file for using google map and google api.

<!--Google MAP API key-->
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="@string/google_map_key" />
<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="@string/google_map_api_key" />

These 2 keys should be generated in Get an API Key.

If you use the api keys in production mode, you have to restrict the API key before using it in production.


问:
Powershell, remove specific characters (spaces and hyphens)
I've got this string :  '  - app-name'. So that's double spaces, hyphen, space, name of the app.

I want to get rid of these double spaces, hyphen, space. So the result would be app-name

I tried '  - app-name'.Trim("  - ", " ") but that doesn't work.

How can I do this?

Thanks

答:
Use the Replace() method on the string:

```<code>$test = "  - app-name"
$test.replace(" - ", "")
</code>```

Output: appname

Body:
Use the Replace() method on the string:

$test = "  - app-name"
$test.replace(" - ", "")

Output: appname


问:
Json To Java list and verify
Hi, how I can retrieve information from my Json file to a list.
And check the information in the list

Please note that the number of servers may increase

My Json file

```<code>{
  "servers": {
    "server1": {
      "name": "Name1",
      "allowStart": true,
      "realIP": "0.0.0.0"
    },
    "server2": {
      "name": "Name2",
      "allowStart": false,
      "realIP": "0.0.0.0"
    },
    "server3": {
      "name": "Name3",
      "allowStart": true,
      "realIP": "0.0.0.0"
    }
  }
}
</code>```

i want to get something like this:

```<code>
String serverip = "0.0.0.0";

/* code for get ListServer.name ListServer.allowStart ListServer.realIP */

if (ListServer.realIP == serverip && ListServer.allowStart == true){

    System.out.print(ListServer.name + " allow to start? " + ListServer.allowStart);

}
</code>```

Ideally it would be good to recover this json file from a site.

Help me please.

答:
Unless you want to write your own parser, you can just easily add the JSON package from org.json. Either download it or just add it as a dependency. It's fairly straight forward to use and there is a good reference here: https://www.baeldung.com/java-org-json

as for recovering the json from a (I'm assuming external) site you could write something like this:

```<code>
import java.net.*;
import java.io.*;

URL yourJson = new URL(<your ip here>);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
      new InputStreamReader(new InputStreamReader(
                yourJson.openStream()), "UTF-8"));

</code>```

Title: Json To Java list and verify

Body:
Hi, how I can retrieve information from my Json file to a list.
And check the information in the list

Please note that the number of servers may increase

My Json file

{
  "servers": {
    "server1": {
      "name": "Name1",
      "allowStart": true,
      "realIP": "0.0.0.0"
    },
    "server2": {
      "name": "Name2",
      "allowStart": false,
      "realIP": "0.0.0.0"
    },
    "server3": {
      "name": "Name3",
      "allowStart": true,
      "realIP": "0.0.0.0"
    }
  }
}

i want to get something like this:

String serverip = "0.0.0.0";

/* code for get ListServer.name ListServer.allowStart ListServer.realIP */

if (ListServer.realIP == serverip && ListServer.allowStart == true){

    System.out.print(ListServer.name + " allow to start? " + ListServer.allowStart);

}

Ideally it would be good to recover this json file from a site.

Help me please.

Body:
Unless you want to write your own parser, you can just easily add the JSON package from org.json. Either download it or just add it as a dependency. It's fairly straight forward to use and there is a good reference here: https://www.baeldung.com/java-org-json

as for recovering the json from a (I'm assuming external) site you could write something like this:

import java.net.*;
import java.io.*;

URL yourJson = new URL(<your ip here>);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
      new InputStreamReader(new InputStreamReader(
                yourJson.openStream()), "UTF-8"));


问:
Accessing NSGA2 population size using pyoptsparse driver with OpenMDAO
I am attempting to modify the GA population size for when using the NSGA2 optimizer through OpenMDAO's pyoptsparse driver.

I tried accessing PopSize from pyNSGA2.py using opt_settings dictionary as follows:

```<code>prob.driver = om.pyOptSparseDriver(optimizer='NSGA2')
prob.driver.opt_settings["PopSize"] = 150
</code>```

However, this results in a segmentation error, message below:

```<code>[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: Caught signal number 11 SEGV: Segmentation Violation, probably memory access out of range
[0]PETSC ERROR: Try option -start_in_debugger or -on_error_attach_debugger
[0]PETSC ERROR: or see https://www.mcs.anl.gov/petsc/documentation/faq.html#valgrind
[0]PETSC ERROR: or try http://valgrind.org on GNU/linux and Apple Mac OS X to find memory corruption errors
[0]PETSC ERROR: configure using --with-debugging=yes, recompile, link, and run
[0]PETSC ERROR: to get more information on the crash.
--------------------------------------------------------------------------
MPI_ABORT was invoked on rank 0 in communicator MPI_COMM_WORLD
with errorcode 50152059.

NOTE: invoking MPI_ABORT causes Open MPI to kill all MPI processes.
You may or may not see output from other processes, depending on
exactly when Open MPI kills them.
</code>```

Is there a different method to access the options for the NSGA2 optimizer that should be used instead of the opt_settings dictionary?  I am relatively new to Python, so I also suspect my syntax could be incorrect as well.

Update:
For a bit more context, I attempted running without PETSC.  The optimization was successful without trying to change PopSize, however it crashed with just Segmentation fault when trying to change PopSize.  Trace the error, I believe the source of the segmentation fault is in pyoptsparse/pyNSGA2/source/crossover.c, per the message below

```<code>Program received signal SIGSEGV, Segmentation fault.
0x00007fffbc85747b in realcross (parent1=parent1@entry=0x1864bf0, parent2=parent2@entry=0x186d030,
    child1=child1@entry=0x1868280, child2=child2@entry=0x18682c0, global=..., nrealcross=<optimized out>)
    at pyoptsparse/pyNSGA2/source/crossover.c:104
104                 child2->xreal[i] = parent2->xreal[i];
</code>```

I also tried a clean installation of PETSC on a new machine, however that brings me back to the same error.

答:
In looking through the C source code for the NSGA2 optimizer, I found that the issue was not with accessing the population size option, but rather that I was specifying an invalid population size.  Per the file header comment of nsga2.c, population size must be a multiple of 4.

I was able to successfully run the optimization at population size of 160 rather than 150.

Body:
I am attempting to modify the GA population size for when using the NSGA2 optimizer through OpenMDAO's pyoptsparse driver.

I tried accessing PopSize from pyNSGA2.py using opt_settings dictionary as follows:

prob.driver = om.pyOptSparseDriver(optimizer='NSGA2')
prob.driver.opt_settings["PopSize"] = 150

However, this results in a segmentation error, message below:

[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: Caught signal number 11 SEGV: Segmentation Violation, probably memory access out of range
[0]PETSC ERROR: Try option -start_in_debugger or -on_error_attach_debugger
[0]PETSC ERROR: or see https://www.mcs.anl.gov/petsc/documentation/faq.html#valgrind
[0]PETSC ERROR: or try http://valgrind.org on GNU/linux and Apple Mac OS X to find memory corruption errors
[0]PETSC ERROR: configure using --with-debugging=yes, recompile, link, and run
[0]PETSC ERROR: to get more information on the crash.
--------------------------------------------------------------------------
MPI_ABORT was invoked on rank 0 in communicator MPI_COMM_WORLD
with errorcode 50152059.

NOTE: invoking MPI_ABORT causes Open MPI to kill all MPI processes.
You may or may not see output from other processes, depending on
exactly when Open MPI kills them.

Is there a different method to access the options for the NSGA2 optimizer that should be used instead of the opt_settings dictionary?  I am relatively new to Python, so I also suspect my syntax could be incorrect as well.

Update:
For a bit more context, I attempted running without PETSC.  The optimization was successful without trying to change PopSize, however it crashed with just Segmentation fault when trying to change PopSize.  Trace the error, I believe the source of the segmentation fault is in pyoptsparse/pyNSGA2/source/crossover.c, per the message below

Program received signal SIGSEGV, Segmentation fault.
0x00007fffbc85747b in realcross (parent1=parent1@entry=0x1864bf0, parent2=parent2@entry=0x186d030,
    child1=child1@entry=0x1868280, child2=child2@entry=0x18682c0, global=..., nrealcross=<optimized out>)
    at pyoptsparse/pyNSGA2/source/crossover.c:104
104                 child2->xreal[i] = parent2->xreal[i];

I also tried a clean installation of PETSC on a new machine, however that brings me back to the same error.


问:
Calling the variable property directly vs getter/setters - OOP Design
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

```<code>class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();
</code>```

Suggested Optimization:

```<code>$rover = new dog();
$rover->name = 'rover';
echo $rover->name;
</code>```

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?

答: This is some kind of micro-optimization. Theoretically, you can later add logic on name get/set by using magic methods (__get and __set) but practically it is not needed so much. And again, practically, this performance improvement only important only if you have everything else so optimized, that even a few microseconds add the value. In this case you can use other optimization techniques like merging all the included PHP files in one, remove type hints, decrease number of function parameters, use plain functions instead of classes. But usually adding a simple caching adds the 10-100x performance boost than all these micro-optimizations.</p>

Body:
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();

Suggested Optimization:

$rover = new dog();
$rover->name = 'rover';
echo $rover->name;

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?


问:
How do I pass a string to a GraphQL query when it's expecting an enum (Apollo Server)?
I'm trying to make a GraphQL query inside a KeystoneJS app where I need to determine if a page of a certain type exists (if a page of that type exists, I won't create it -- I'm implementing each page type as a singleton).  My thinking was to do a search for all pages with a where condition where I pass the type of the page I'm trying to create.

```<code>const PAGE_QUERY = `
    query allPages($where:PageWhereInput){
      allPages(where:$where) {
    pageType
  }
}
`;

export const doesPageTypeExist = async (query, articleType: string): Promise<boolean> => {
    const where = {
        pageType: articleType
    };
    const options = {
        skipAccessControl: false,
        variables: {
            where
        }
    };
    const { errors, data } = await query(allPages, options);
    if (errors) {
        log.error({ errors }, 'errors from GraphQL operation in Page list');
        throw new Error(errors.toString());
    } else {
        return data?.allPages.length !== 0;
    }
};
</code>```

The problem is that I get the error

Variable "$where" got invalid value { pageType: "page2" } at
"where.pageType"; Expected type PagePageTypeType.

I understand where the error is coming from: it's expecting one of these enum's

```<code>enum CondomPagePageTypeType {
 page1
 page2
 page3
 page4
}
</code>```

and I'm passing it a string, but I don't know how to pass the value I'm testing (which comes from Keystone) except as a string.

答:
Enum values are always serialized as strings when used as variables, so the problem is not with how the enum value is being submitted. According to the error, the issue is with the value of the pageType property of $where. It appears that the value of pageType is actually the object { pageType: "page2" } and not page2. In other words, your variables property looks like this:

```<code>{
  "where": {
    "pageType": {
      "pageType": "page2"
    }
  }
}
</code>```

Based on the shown code, I'd guess that maybe the articleType parameter being passed to doesPageTypeExist is not actually a string like its type would indicate.

Body:
I'm trying to make a GraphQL query inside a KeystoneJS app where I need to determine if a page of a certain type exists (if a page of that type exists, I won't create it -- I'm implementing each page type as a singleton).  My thinking was to do a search for all pages with a where condition where I pass the type of the page I'm trying to create.

const PAGE_QUERY = `
    query allPages($where:PageWhereInput){
      allPages(where:$where) {
    pageType
  }
}
`;

export const doesPageTypeExist = async (query, articleType: string): Promise<boolean> => {
    const where = {
        pageType: articleType
    };
    const options = {
        skipAccessControl: false,
        variables: {
            where
        }
    };
    const { errors, data } = await query(allPages, options);
    if (errors) {
        log.error({ errors }, 'errors from GraphQL operation in Page list');
        throw new Error(errors.toString());
    } else {
        return data?.allPages.length !== 0;
    }
};

The problem is that I get the error

Variable "$where" got invalid value { pageType: "page2" } at
"where.pageType"; Expected type PagePageTypeType.

I understand where the error is coming from: it's expecting one of these enum's

enum CondomPagePageTypeType {
 page1
 page2
 page3
 page4
}

and I'm passing it a string, but I don't know how to pass the value I'm testing (which comes from Keystone) except as a string.

Body:
Enum values are always serialized as strings when used as variables, so the problem is not with how the enum value is being submitted. According to the error, the issue is with the value of the pageType property of $where. It appears that the value of pageType is actually the object { pageType: "page2" } and not page2. In other words, your variables property looks like this:

{
  "where": {
    "pageType": {
      "pageType": "page2"
    }
  }
}

Based on the shown code, I'd guess that maybe the articleType parameter being passed to doesPageTypeExist is not actually a string like its type would indicate.


答:
While $ is the preferred route, you can also consider cbind.

First, create the numeric vector and assign it to SN:

```<code>SN <- Data[,6]/Data[,9]
</code>```

Now you use cbind to append the numeric vector as a column to the existing data frame:

```<code>Data <- cbind(Data, SN)
</code>```

Again, using the dollar operator $ is preferred, but it doesn't hurt seeing what an alternative looks like.

Title: adding new column to data frame in R

Body:
  rate   len ADT trks      sigs1 slim shld lane acpt  itg lwid hwy
1  4.58  4.99  69    8 0.20040080   55   10    8  4.6 1.20   12 FAI
2  2.86 16.11  73    8 0.06207325   60   10    4  4.4 1.43   12 FAI
3  3.02  9.75  49   10 0.10256410   60   10    4  4.7 1.54   12 FAI
4  2.29 10.65  61   13 0.09389671   65   10    6  3.8 0.94   12 FAI
5  1.61 20.01  28   12 0.04997501   70   10    4  2.2 0.65   12 FAI
6  6.87  5.97  30    6 2.00750419   55   10    4 24.8 0.34   12  PA
7  3.85  8.57  46    8 0.81668611   55    8    4 11.0 0.47   12  PA
8  6.12  5.24  25    9 0.57083969   55   10    4 18.5 0.38   12  PA
9  3.29 15.79  43   12 1.45333122   50    4    4  7.5 0.95   12  PA

I got a question in adding a new column, my data frame is called highway1,and i want to add a column named S/N, as slim divided by acpt, what can I do?

Thanks

Body:
While $ is the preferred route, you can also consider cbind.

First, create the numeric vector and assign it to SN:

SN <- Data[,6]/Data[,9]

Now you use cbind to append the numeric vector as a column to the existing data frame:

Data <- cbind(Data, SN)

Again, using the dollar operator $ is preferred, but it doesn't hurt seeing what an alternative looks like.


问:
Is there difference between creating a wrapped BigInt or Symbol with the "new" keyword in JavaScript?
I have examined the wrapped symbol objects using the following code.

```<code>const symObj = Object(sym);
const symObjNew = new Object(sym);
// I can see no difference between symObj and symObjNew

console.log(`typeof symObj === 'object' is ${typeof symObj === 'object'}`); // true
console.log(`typeof symObjNew === 'object' is ${typeof symObjNew === 'object'}`); // true
</code>```

I have also examined the symObj and symObjNew in devtools using node --inspect-brk. I don't see any difference between them. The same is true of BigInt.

答:
As specified in MDN:

When called in a non-constructor context, Object behaves identically to new Object().

I'd venture to guess this is another one of JavaScript's infamous backwards compatibility 'features', back during such a time that the new keyword didn't exist.

You can also check the ECMAScript spec for details:

When the Object function is called with optional argument value, the
  following steps are taken:

If NewTarget is neither undefined nor the active function, then

Return ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%").

If value is undefined or null, return OrdinaryObjectCreate(%Object.prototype%).

Return ! ToObject(value).

As thoroughly explained by Mike's answer, both cases in your sample snippet end up in Step 3, which performs type conversion on the argument. So there is no difference whatsoever.

Body:
I have examined the wrapped symbol objects using the following code.

const symObj = Object(sym);
const symObjNew = new Object(sym);
// I can see no difference between symObj and symObjNew

console.log(`typeof symObj === 'object' is ${typeof symObj === 'object'}`); // true
console.log(`typeof symObjNew === 'object' is ${typeof symObjNew === 'object'}`); // true

I have also examined the symObj and symObjNew in devtools using node --inspect-brk. I don't see any difference between them. The same is true of BigInt.


问:
How to set the scroll bar to my popup window?
I have threnter image description hereee images inside my popup window, and i need to set the scroll bar to be able to see all of them, but it´s not posible to scroll throw the popup window to see the images below. Hope someone can help, enter image description here
Regards. Sorry, but I can not show the code for a personal reason, hope you understand,

CSS properties below

```<code>.popup {
    background-color:  #08303a;
    box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.3);
    border-radius: 3px;
    text-align: center;
    color: #ffffff;
    font-family: 'Montserrat', sans-serif;
    padding: 10px;
    text-align: center;
    width: 400px;
    max-height: 350px;
    height: 350px;
    overflow:scroll;
    opacity: 0;
    transition: .3s ease all;
    transform:scale(0.7);

}
</code>```

答:
Without seeing your code - I believe this one will be a case of setting the following CSS property to your pop-up window:

```<code>overflow: scroll;
</code>```

For future reference - it's useful to put the code you've worked with onto Stack Overflow so people can review your code and give you a definitive answer. Without it, people will just have to guess.

Hope that helps.

Body:
I have threnter image description hereee images inside my popup window, and i need to set the scroll bar to be able to see all of them, but it´s not posible to scroll throw the popup window to see the images below. Hope someone can help, enter image description here
Regards. Sorry, but I can not show the code for a personal reason, hope you understand,

CSS properties below

.popup {
    background-color:  #08303a;
    box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.3);
    border-radius: 3px;
    text-align: center;
    color: #ffffff;
    font-family: 'Montserrat', sans-serif;
    padding: 10px;
    text-align: center;
    width: 400px;
    max-height: 350px;
    height: 350px;
    overflow:scroll;
    opacity: 0;
    transition: .3s ease all;
    transform:scale(0.7);

}

Body:
Without seeing your code - I believe this one will be a case of setting the following CSS property to your pop-up window:

overflow: scroll;

For future reference - it's useful to put the code you've worked with onto Stack Overflow so people can review your code and give you a definitive answer. Without it, people will just have to guess.

Hope that helps.


问:
How to Commit/Rollback a transaction based on the result of the previous query in Snowflake?
I have a transaction like this

```<code>BEGIN;

...

SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())); -- Returns TRUE/FALSE

+----------------+
| Result         |
|----------------|
| FALSE          |
+----------------+

-- If TRUE
COMMIT;

-- If FALSE
-- ROLLBACK;
</code>```

How do I ROLLBACK in this case based on the result of the previous query which is "FALSE"? I want to automate this script and not make a decision at runtime myself.

答:
Maybe you can create a stored procedure and execute commit or rollback based on argument:

```<code>CREATE OR REPLACE PROCEDURE commit_or_rollback( result BOOLEAN )
returns BOOLEAN
language javascript
AS
$$
    if ( RESULT ) { snowflake.execute( {sqlText: "COMMIT" }) }
    else {
        snowflake.execute( {sqlText: "ROLLBACK" }) };
    return RESULT;
$$
;
</code>```

So your script will be something like this:

```<code>BEGIN

...

CALL commit_or_rollback(  SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())) );
</code>```

A test case:

```<code>BEGIN;

SELECT CURRENT_TRANSACTION();

+-----------------------+
| CURRENT_TRANSACTION() |
+-----------------------+
| 1591113827577         |
+-----------------------+

CALL commit_or_rollback( ( SELECT TRUE ) );

+--------------------+
| COMMIT_OR_ROLLBACK |
+--------------------+
| TRUE               |
+--------------------+

SELECT CURRENT_TRANSACTION();
</code>```

The last command returns NULL. I can also see the COMMIT is executed in query history.

Body:
I have a transaction like this

BEGIN;

...

SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())); -- Returns TRUE/FALSE

+----------------+
| Result         |
|----------------|
| FALSE          |
+----------------+

-- If TRUE
COMMIT;

-- If FALSE
-- ROLLBACK;

How do I ROLLBACK in this case based on the result of the previous query which is "FALSE"? I want to automate this script and not make a decision at runtime myself.

Body:
Maybe you can create a stored procedure and execute commit or rollback based on argument:

CREATE OR REPLACE PROCEDURE commit_or_rollback( result BOOLEAN )
returns BOOLEAN
language javascript
AS
$$
    if ( RESULT ) { snowflake.execute( {sqlText: "COMMIT" }) }
    else {
        snowflake.execute( {sqlText: "ROLLBACK" }) };
    return RESULT;
$$
;

So your script will be something like this:

BEGIN

...

CALL commit_or_rollback(  SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())) );

A test case:

BEGIN;

SELECT CURRENT_TRANSACTION();

+-----------------------+
| CURRENT_TRANSACTION() |
+-----------------------+
| 1591113827577         |
+-----------------------+

CALL commit_or_rollback( ( SELECT TRUE ) );

+--------------------+
| COMMIT_OR_ROLLBACK |
+--------------------+
| TRUE               |
+--------------------+

SELECT CURRENT_TRANSACTION();

The last command returns NULL. I can also see the COMMIT is executed in query history.


问:
How to do time profiling of a C program in HP-UX?
I want to do a time-based profiling of an application written in C on HP-UX. I want to see which function is taking maximum amount of time, slowing down the operational duration. Is there a way to do it? I know I can use -p option in Linux and generate mon.out and then use prof command to generate the profile. But, I don't think that's the correct compiler option on HP-UX.

I would love to get some help here. I did find one similar answer here:
Is there a profiler for C (gcc) to profile code lines separately?

However, I did not quite extract the thing I need, especially for HP-UX fro this post.

答:
For hp-ux/ia64, you should be able to use Caliper (bundled with the OS)

```<code>caliper fprof -o fprof.out a.out
</code>```

For hp-ux/parisc it used to be prospect or gprof, I can't find sources right now.

Body:
For hp-ux/ia64, you should be able to use Caliper (bundled with the OS)

caliper fprof -o fprof.out a.out

For hp-ux/parisc it used to be prospect or gprof, I can't find sources right now.


问:
Unable to save TensorFlow Keras LSTM model to SavedModel format
System information:

OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Windows 10

TensorFlow installed from (source or binary): pip installed

TensorFlow version (use command below): v2.0.0-rc2-26-g64c3d382ca 2.0.0

Python version: 3.7.1

Error:

Unable to save TensorFlow Keras LSTM model to SavedModel format for exporting to Google Cloud bucket.

Error Message:

ValueError: Attempted to save a function b'__inference_lstm_2_layer_call_fn_36083' which references a symbolic Tensor Tensor("dropout/mul_1:0", shape=(None, 1280), dtype=float32) that is not a simple constant. This is not supported.

Code:

```<code>import tensorflow as tf
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tqdm
import datetime
from sklearn.preprocessing import LabelBinarizer

model = tf.keras.Sequential([
    tf.keras.layers.Masking(mask_value=0.),
    tf.keras.layers.LSTM(512, dropout=0.5, recurrent_dropout=0.5),
    tf.keras.layers.Dense(256, activation='relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(len(LABELS), activation='softmax')
])

model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy', 'top_k_categorical_accuracy'])

test_file = 'C:/.../testlist01.txt'
train_file = 'C:/.../trainlist01.txt'

with open(test_file) as f:
    test_list = [row.strip() for row in list(f)]

with open(train_file) as f:
    train_list = [row.strip() for row in list(f)]
    train_list = [row.split(' ')[0] for row in train_list]

def make_generator(file_list):
    def generator():
        np.random.shuffle(file_list)
        for path in file_list:
            full_path = os.path.join(BASE_PATH, path).replace('.avi', '.npy')

            label = os.path.basename(os.path.dirname(path))
            features = np.load(full_path)

            padded_sequence = np.zeros((SEQUENCE_LENGTH, 1280))
            padded_sequence[0:len(features)] = np.array(features)

            transformed_label = encoder.transform([label])
            yield padded_sequence, transformed_label[0]
    return generator

train_dataset = tf.data.Dataset.from_generator(make_generator(train_list),
                 output_types=(tf.float32, tf.int16),
                 output_shapes=((SEQUENCE_LENGTH, 1280), (len(LABELS))))
train_dataset = train_dataset.batch(16).prefetch(tf.data.experimental.AUTOTUNE)

valid_dataset = tf.data.Dataset.from_generator(make_generator(test_list),
                 output_types=(tf.float32, tf.int16),
                 output_shapes=((SEQUENCE_LENGTH, 1280), (len(LABELS))))
valid_dataset = valid_dataset.batch(16).prefetch(tf.data.experimental.AUTOTUNE)

model.fit(train_dataset, epochs=17, validation_data=valid_dataset)

BASE_DIRECTORY = 'C:\\...\\saved_model\\LSTM\\1\\';
tf.saved_model.save(model, BASE_DIRECTORY)
</code>```

答: This seems to be a bug with both TensorFlow 2.0 and 2.1, after upgrading my TensorFlow to v2.2, it's working fine. </p>

Body:
System information:

OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Windows 10

TensorFlow installed from (source or binary): pip installed

TensorFlow version (use command below): v2.0.0-rc2-26-g64c3d382ca 2.0.0

Python version: 3.7.1

Error:

Unable to save TensorFlow Keras LSTM model to SavedModel format for exporting to Google Cloud bucket.

Error Message:

ValueError: Attempted to save a function b'__inference_lstm_2_layer_call_fn_36083' which references a symbolic Tensor Tensor("dropout/mul_1:0", shape=(None, 1280), dtype=float32) that is not a simple constant. This is not supported.

Code:

import tensorflow as tf
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tqdm
import datetime
from sklearn.preprocessing import LabelBinarizer

model = tf.keras.Sequential([
    tf.keras.layers.Masking(mask_value=0.),
    tf.keras.layers.LSTM(512, dropout=0.5, recurrent_dropout=0.5),
    tf.keras.layers.Dense(256, activation='relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(len(LABELS), activation='softmax')
])

model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy', 'top_k_categorical_accuracy'])

test_file = 'C:/.../testlist01.txt'
train_file = 'C:/.../trainlist01.txt'

with open(test_file) as f:
    test_list = [row.strip() for row in list(f)]

with open(train_file) as f:
    train_list = [row.strip() for row in list(f)]
    train_list = [row.split(' ')[0] for row in train_list]

def make_generator(file_list):
    def generator():
        np.random.shuffle(file_list)
        for path in file_list:
            full_path = os.path.join(BASE_PATH, path).replace('.avi', '.npy')

            label = os.path.basename(os.path.dirname(path))
            features = np.load(full_path)

            padded_sequence = np.zeros((SEQUENCE_LENGTH, 1280))
            padded_sequence[0:len(features)] = np.array(features)

            transformed_label = encoder.transform([label])
            yield padded_sequence, transformed_label[0]
    return generator

train_dataset = tf.data.Dataset.from_generator(make_generator(train_list),
                 output_types=(tf.float32, tf.int16),
                 output_shapes=((SEQUENCE_LENGTH, 1280), (len(LABELS))))
train_dataset = train_dataset.batch(16).prefetch(tf.data.experimental.AUTOTUNE)

valid_dataset = tf.data.Dataset.from_generator(make_generator(test_list),
                 output_types=(tf.float32, tf.int16),
                 output_shapes=((SEQUENCE_LENGTH, 1280), (len(LABELS))))
valid_dataset = valid_dataset.batch(16).prefetch(tf.data.experimental.AUTOTUNE)

model.fit(train_dataset, epochs=17, validation_data=valid_dataset)

BASE_DIRECTORY = 'C:\\...\\saved_model\\LSTM\\1\\';
tf.saved_model.save(model, BASE_DIRECTORY)


问:
How to create and use a map in ReactJS
I have a Spring-Boot app with a ReactJS front-end, and I'm trying to figure out how to use Semantic UI to use a value selected from one input field to populate another input field.

I think I have most of the pieces in place, but I'm trying to figure out how to select a value from an array of name/value objects based on the name. I haven't quite gotten how the "map" function works, and the examples I've seen so far choose based on an index rather than a value. How to code it so it chooses the entry based on the value?

For example, here's the array:

```<code>const productMap = [
  {key: 'template_key1', value: 'Product 1'},
  {key: 'template_key2', value: 'Product 2'},
  {key: 'template_key3', value: 'Product 3'}
}
</code>```

I have a method that gets called when the user selects the key:

```<code> handleSelectTemplateChange=(event,{value})=>{
    let item = {...this.state.item};
    item.template = value;

    // how should this be coded?
    item.product = productMap.getValue(item.template);

    this.setState({item});
  }
</code>```

答:
I found a good description at this site.

Here's the code that seems to work:

```<code>   item.template = value;
    productMap.map(entry =>{
      if (value === entry.key){
        item.product = entry.value;
      }
    })
</code>```

Title: How to create and use a map in ReactJS

Body:
I have a Spring-Boot app with a ReactJS front-end, and I'm trying to figure out how to use Semantic UI to use a value selected from one input field to populate another input field.

I think I have most of the pieces in place, but I'm trying to figure out how to select a value from an array of name/value objects based on the name. I haven't quite gotten how the "map" function works, and the examples I've seen so far choose based on an index rather than a value. How to code it so it chooses the entry based on the value?

For example, here's the array:

const productMap = [
  {key: 'template_key1', value: 'Product 1'},
  {key: 'template_key2', value: 'Product 2'},
  {key: 'template_key3', value: 'Product 3'}
}

I have a method that gets called when the user selects the key:

 handleSelectTemplateChange=(event,{value})=>{
    let item = {...this.state.item};
    item.template = value;

    // how should this be coded?
    item.product = productMap.getValue(item.template);

    this.setState({item});
  }

Body:
I found a good description at this site.

Here's the code that seems to work:

   item.template = value;
    productMap.map(entry =>{
      if (value === entry.key){
        item.product = entry.value;
      }
    })


问:
T-SQL query to show table definition?
What is a query that will show me the full definition, including indexes and keys for a SQL Server table?  I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio.  But SQLCMD is always an option.

UPDATE:  I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime.  Is there something else I am missing with sp_help?

Here is what I call:

sp_help airports

Note that I really do want the DDL that defines the table.

答:
Try the sp_help stored procedure.

sp_help <>

Title: T-SQL query to show table definition?


问:
Pandas-profiling error AttributeError: 'DataFrame' object has no attribute 'profile_report'
I wanted to use pandas-profiling to do some eda on a dataset but I'm getting an error : AttributeError: 'DataFrame' object has no attribute 'profile_report'

I have created a python script on spyder with the following code :

import pandas as pd
import pandas_profiling
data_abc = pd.read_csv('abc.csv')
profile = data_abc.profile_report(title='Pandas Profiling Report')
profile.to_file(output_file="abc_pandas_profiling.html")

AttributeError: 'DataFrame' object has no attribute 'profile_report'

答:
Try in conda environment</p>

```<code>!pip install --user pandas-profiling
import pandas_profiling
data.profile_report()
</code>```

Body:
Try in conda environment

!pip install --user pandas-profiling
import pandas_profiling
data.profile_report()


问:
AWS - Accessing private website hosted on an external AWS account
Background

My company has bought a SaaS product which is hosted on vendor's AWS environment. The product has a website dashboard which is currently only accessible within the vendor's AWS environment. The access to the vendor's AWS environment is tightly controlled by the vendor.

Right now my users are able to access that dashboard by using Amazon Workspaces provisioned by the vendor. However, the Workspaces have limited number of accounts for my company. My company would like to make this dashboard widely accessible within my company and not restricted by the number of Workspaces accounts.

Question

My company has our own AWS account as well but currently not linked to vendor's VPC/AWS environment at all. Can we build something in our own AWS (probably with a PrivateLink to vendor's VPC?) such that my users can securely access the vendor's dashboard via our own AWS environment? If there's a possible way to do this, what are the AWS services required on both sides?

My objective is to ensure this dashboard is not exposed to the Internet and yet all my company's users can view it without having Workspace credentials.

答:
If I understood your question correctly, what you are looking for looks a lot like How can I access an API Gateway private REST API in another AWS account using an interface VPC endpoint?. The link includes the steps to get access to a private REST endpoint in another account.

It uses VPC interface endpoints which are themselves built on top of PrivateLink.

You may also have a look at Endpoint Service that contains some more scenarios.


问:
How to use MotionLayout like TransitionManager?
Tutoiral I see with MotionLayout have things in common and that is it focused on either an onClick or onSwipe to trigger MotionLayout Transition. I was wondering how to Transition from something like State A to State B with other trigger like instead of onClick it would trigger onNavDestinationChanged something like:

```<code>navController.addNavigationChangeListener { motionLayout.transtionToAnotherState() }
</code>```

Something similar to TransitionManager where if I want to go from Scene A to Scene B I just do:

```<code>TransitionManager.beginDelayedTransition(rootLayout)
// Do someLayout changes
</code>```

1) Is something similar doable with MotionLayout?
2) If yes can anyone guide me?

Thank you very much.

答:
So apparently, it was really easy to do this and for anyone else who needs to know simply call:</p>

```<code>motionLayout.transitionToState(constraintSetId)
</code>```

Body:
Tutoiral I see with MotionLayout have things in common and that is it focused on either an onClick or onSwipe to trigger MotionLayout Transition. I was wondering how to Transition from something like State A to State B with other trigger like instead of onClick it would trigger onNavDestinationChanged something like:

navController.addNavigationChangeListener { motionLayout.transtionToAnotherState() }

Something similar to TransitionManager where if I want to go from Scene A to Scene B I just do:

TransitionManager.beginDelayedTransition(rootLayout)
// Do someLayout changes

1) Is something similar doable with MotionLayout?
2) If yes can anyone guide me?

Thank you very much.

Body:
So apparently, it was really easy to do this and for anyone else who needs to know simply call:

motionLayout.transitionToState(constraintSetId)


问:
Search in belongsToMany-relation for item by pivot value
I got these models:

Order

Invoice

An Order can have many Invoices and an Invoice can belong to many Orders.

Example:

Orders:

Order #1

Order #2

Order #3

Invoices:

Invoice #1 -> belongs To Order #1 and Order #2 (so this Invoice contains both Orders)

Invoice #2 -> belongsTo  Order #2 and Order #3

Each belongsTo-relation saves a date as pivot, which defines the last date this order has been invoiced.

Now I'd like to create a isInvoiceable() getter for my Order-Model, which returns, whether the order has been invoiced within the last month or not. If the latest date is older than one month, return true, as this Order should create a new invoice.

So now I need your help: I need to check all invoices, whether there's an Order (belongsToMany) with the order_id of the current Order, and a date-pivot that's older than now - one month. I need to check the order_id because the Invoice could possibly contain information about other Orders, too.

And this is the missing link for me: How can I check the belongsToMany-relation in Invoice for date and order_id?

答:
you have two choices:

1- like  Remul said in his answer: using wherePivot();

2- using  newPivotQuery()

witch give you more space to work with ...

when you use this method, the query will be on pivot table directly ...

```<code>class Order extends Model {

public function isInvoiceable()
{

   return $this->invoices()-> newPivotQuery()->firstWhere('date', '>=', Carbon::now()->subMonth())!=null;
}
</code>```

the advantage of using newPivotQuery() that you can insert,update, make overall queries ...

Body:
you have two choices:

1- like  Remul said in his answer: using wherePivot();

2- using  newPivotQuery()

witch give you more space to work with ...

when you use this method, the query will be on pivot table directly ...

class Order extends Model {

public function isInvoiceable()
{

   return $this->invoices()-> newPivotQuery()->firstWhere('date', '>=', Carbon::now()->subMonth())!=null;
}

the advantage of using newPivotQuery() that you can insert,update, make overall queries ...


问:
How to trigger a anynomous function with parameters Javascript
Today I was at job interview - and I had been presented with a task.
I have never encoutered such a function, so there it is:

Write down a function which after triggering like this:

```<code>console.log('hello'.repeatify(3))
</code>```

returns

```<code>hellohellohello
</code>```

I was trying to create an empty object and append a method repeatify, however i just don't know how to trigger it just with 'hello'.

Maybe i should change console.log method?

Thanks for the help :)

答:
ES6 version

repeatify

String.prototype.repeatify = String.prototype.repeatify || function (times = 1) {
  // ES5 this
  return [...``.padStart(times, ` `)].map((item, i) => item = this).join(``);
};

`abx`.repeatify(3);
// "abxabxabx"

```

Body:
Today I was at job interview - and I had been presented with a task.
I have never encoutered such a function, so there it is:

Write down a function which after triggering like this:

console.log('hello'.repeatify(3))

returns

hellohellohello

I was trying to create an empty object and append a method repeatify, however i just don't know how to trigger it just with 'hello'.

Maybe i should change console.log method?

Thanks for the help :)


问:
Xero-Api and Vapor 3 unable to connect to recive token
I have a vapor3 app within which I am trying to connect to the Xero Api, the process is fairly simple. We send the user to a xero web page where they login with the details and authorise our connection, it then redirects back to my vapor 3 app. In the app we then connect to the xero server with the code provided in the redirect, and then xero should be issue an access token to be used going forward. The process is described here

The issue is I can't connect to xero to get the access token. I have tried 2 approaches, the first is to use HTTPClient, with this code:

 let m = try decoder.decode(Master.self, from: masterDoc!)
 let ci = m.xeroAppKey.data(using: .utf8)?.base64EncodedString() //convert from string to base encoded
 let xs = m.xeroAppSec.data(using: .utf8)?.base64EncodedString() //convert from string to base encoded
 let authorization = "Basic " + ci! + ":" + xs!
 print("authorisation is \(authorization)")
 return HTTPClient.connect(hostname: "identity.xero.com", on: req).flatMap{client in
       var httpReq = HTTPRequest(method: .POST, url: "https://identity.xero.com/connect/token")
       httpReq.headers.add(name: "authorization", value: authorization)
       httpReq.headers.add(name: "Content-Type", value: "x-www-form-urlencoded")
       httpReq.body = HTTPBody(string: "grant_type=authorization_code&code=\(code)&redirect_uri=http://localhost:8080/XeroAuthRedirect")

       return client.send(httpReq).flatMap{resp in
         print("response is \(resp) with status \(resp.status)")
         return req.future().map{
           return .ok
         }
      }
    }
```

<p>With this I get the following response: </p>

```HTTP/1.1 301 Moved Permanently
Server: AkamaiGHost
Content-Length: 0
Location: https://identity.xero.com/connect/token
Expires: Tue, 02 Jun 2020 07:59:59 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Tue, 02 Jun 2020 07:59:59 GMT
Connection: keep-alive
```

<p>Which suggests the end point has moved but the location suggested is the same one that I am trying to connect to. I can't find anywhere in the docs which suggested the end point has changed. It also seems HTTPClient wont follow redirects. </p>

<p>So I tried to connect using URLSession instead using this code: </p>

<pre class="lang-swift prettyprint-override"><code>let url = URL(string:"https://identity.xero.com/connect/token")!
                let payload = "grant_type=authorization_code&code=\(code)&redirect_uri=http://localhost:8080/XeroAuthRedirect".data(using: .utf8)

                let promise = req.eventLoop.newPromise(HTTPStatus.self)

                var request = URLRequest(url: url)
                request.httpMethod = "POST"
                request.addValue(authorization, forHTTPHeaderField: "authorization")
                request.addValue("x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
                request.httpBody = payload

                URLSession.shared.dataTask(with: request) {(data, response, error) in

                    if let error = error {
                        print(error.localizedDescription)
                        promise.fail(error: error) // (!)
                        return
                    }

                    guard let data = data else {
                        print("empty data")
                        promise.fail(error: SumUpError.invalidResponse) // (!)
                        return
                    }

                    guard let str = String(data: data, encoding: .utf8) else {
                        print("invalid data")
                        promise.fail(error: SumUpError.invalidResponse) // (!)
                        return
                    }

                    print(str)

                    print("response is \(String(describing: response))")

                }.resume()
</code>```

Where i get the following error message.

```<code>{"error":"invalid_request"}
</code>```

Any ideas what is going on here or how I can get this connection up and running are greatly apprecitated.

答:
Ok so the answer in the end was to use the vapor client service found at req.client()

I used the following code. I also made a rookie error of encodeing the client id and client secret and then combing them, rather then cobining them first then encoding them. The docs do show this but I guess not clear enough.
Anyway here is the code that worked to connect to the Xero Api with Vapor 3.

    let toBase = "\(clientId):\(clientSecret)".data(using: .utf8)?.base64EncodedString()
    let authorization = "Basic " + toBase!
    let payload = "grant_type=authorization_code&code=\(code)&redirect_uri=http://localhost:8080/XeroAuthRedirect".data(using: .utf8)!
    let request = Request( using: req)
    request.http.url = URL(string:"https://identity.xero.com/connect/token")!
    request.http.body = payload.convertToHTTPBody()
    request.http.method = HTTPMethod.POST
    request.http.headers.add(name: "authorization", value: authorization)
    request.http.headers.add(name: "Content-Type", value: "application/x-www-form-urlencoded")
 return try req.client().send(request).flatMap{resp in

}
```

Hopefully this is helpful to anyone trying to add xero with Vapor.

Body:
I have a vapor3 app within which I am trying to connect to the Xero Api, the process is fairly simple. We send the user to a xero web page where they login with the details and authorise our connection, it then redirects back to my vapor 3 app. In the app we then connect to the xero server with the code provided in the redirect, and then xero should be issue an access token to be used going forward. The process is described here

The issue is I can't connect to xero to get the access token. I have tried 2 approaches, the first is to use HTTPClient, with this code:

 let m = try decoder.decode(Master.self, from: masterDoc!)
 let ci = m.xeroAppKey.data(using: .utf8)?.base64EncodedString() //convert from string to base encoded
 let xs = m.xeroAppSec.data(using: .utf8)?.base64EncodedString() //convert from string to base encoded
 let authorization = "Basic " + ci! + ":" + xs!
 print("authorisation is \(authorization)")
 return HTTPClient.connect(hostname: "identity.xero.com", on: req).flatMap{client in
       var httpReq = HTTPRequest(method: .POST, url: "https://identity.xero.com/connect/token")
       httpReq.headers.add(name: "authorization", value: authorization)
       httpReq.headers.add(name: "Content-Type", value: "x-www-form-urlencoded")
       httpReq.body = HTTPBody(string: "grant_type=authorization_code&code=\(code)&redirect_uri=http://localhost:8080/XeroAuthRedirect")

       return client.send(httpReq).flatMap{resp in
         print("response is \(resp) with status \(resp.status)")
         return req.future().map{
           return .ok
         }
      }
    }

With this I get the following response:

HTTP/1.1 301 Moved Permanently
Server: AkamaiGHost
Content-Length: 0
Location: https://identity.xero.com/connect/token
Expires: Tue, 02 Jun 2020 07:59:59 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Tue, 02 Jun 2020 07:59:59 GMT
Connection: keep-alive

Which suggests the end point has moved but the location suggested is the same one that I am trying to connect to. I can't find anywhere in the docs which suggested the end point has changed. It also seems HTTPClient wont follow redirects.

So I tried to connect using URLSession instead using this code:

let url = URL(string:"https://identity.xero.com/connect/token")!
                let payload = "grant_type=authorization_code&code=\(code)&redirect_uri=http://localhost:8080/XeroAuthRedirect".data(using: .utf8)

                let promise = req.eventLoop.newPromise(HTTPStatus.self)

                var request = URLRequest(url: url)
                request.httpMethod = "POST"
                request.addValue(authorization, forHTTPHeaderField: "authorization")
                request.addValue("x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
                request.httpBody = payload

                URLSession.shared.dataTask(with: request) {(data, response, error) in

                    if let error = error {
                        print(error.localizedDescription)
                        promise.fail(error: error) // (!)
                        return
                    }

                    guard let data = data else {
                        print("empty data")
                        promise.fail(error: SumUpError.invalidResponse) // (!)
                        return
                    }

                    guard let str = String(data: data, encoding: .utf8) else {
                        print("invalid data")
                        promise.fail(error: SumUpError.invalidResponse) // (!)
                        return
                    }

                    print(str)

                    print("response is \(String(describing: response))")

                }.resume()

Where i get the following error message.

{"error":"invalid_request"}

Any ideas what is going on here or how I can get this connection up and running are greatly apprecitated.

Body:
Ok so the answer in the end was to use the vapor client service found at req.client()

I used the following code. I also made a rookie error of encodeing the client id and client secret and then combing them, rather then cobining them first then encoding them. The docs do show this but I guess not clear enough.
Anyway here is the code that worked to connect to the Xero Api with Vapor 3.

    let toBase = "\(clientId):\(clientSecret)".data(using: .utf8)?.base64EncodedString()
    let authorization = "Basic " + toBase!
    let payload = "grant_type=authorization_code&code=\(code)&redirect_uri=http://localhost:8080/XeroAuthRedirect".data(using: .utf8)!
    let request = Request( using: req)
    request.http.url = URL(string:"https://identity.xero.com/connect/token")!
    request.http.body = payload.convertToHTTPBody()
    request.http.method = HTTPMethod.POST
    request.http.headers.add(name: "authorization", value: authorization)
    request.http.headers.add(name: "Content-Type", value: "application/x-www-form-urlencoded")
 return try req.client().send(request).flatMap{resp in

}

Hopefully this is helpful to anyone trying to add xero with Vapor.


问:
AZCopy: Set the file Content-Type
We are trying to use AZCopy in our deployment script to upload some assets directly into our storage which is exposed via a CDN on Azure.

When we upload the files, the Content-Type is application/octet-stream but we would need to be able to specify by example text/javascript

Is there a way to achieve this? We don't bother having to call AZCopy several times for each file types.

答:
I found a way of doing this using Azure Pipelines:

```<code>
- task: AzureFileCopy@4
  displayName: "Azure Storage - copy new files"
  inputs:
    SourcePath: '$(System.DefaultWorkingDirectory)/dist/*'
    azureSubscription: 'johnykes-PAYG(xxxxx-b455-4c4d-a8f8-c2a5fd479f10)'
    Destination: 'AzureBlob'
    storage: 'johnykeschatfrontend'
    ContainerName: '$web'

- task: AzureFileCopy@4
  displayName: "Azure Storage - overwrite .js files with correct Content Type"
  inputs:
    SourcePath: '$(System.DefaultWorkingDirectory)/dist/*.js'
    azureSubscription: 'johnykes-PAYG(xxxxx-b455-4c4d-a8f8-c2a5fd479f10)'
    Destination: 'AzureBlob'
    storage: 'johnykeschatfrontend'
    ContainerName: '$web'
    AdditionalArgumentsForBlobCopy: '--content-type "application/javascript"'
</code>```

Please let me know if you find a way of doing this using the Azure CLI or in my way but recursively (for all .js files).

Title: AZCopy: Set the file Content-Type

Body:
I found a way of doing this using Azure Pipelines:

- task: AzureFileCopy@4
  displayName: "Azure Storage - copy new files"
  inputs:
    SourcePath: '$(System.DefaultWorkingDirectory)/dist/*'
    azureSubscription: 'johnykes-PAYG(xxxxx-b455-4c4d-a8f8-c2a5fd479f10)'
    Destination: 'AzureBlob'
    storage: 'johnykeschatfrontend'
    ContainerName: '$web'

- task: AzureFileCopy@4
  displayName: "Azure Storage - overwrite .js files with correct Content Type"
  inputs:
    SourcePath: '$(System.DefaultWorkingDirectory)/dist/*.js'
    azureSubscription: 'johnykes-PAYG(xxxxx-b455-4c4d-a8f8-c2a5fd479f10)'
    Destination: 'AzureBlob'
    storage: 'johnykeschatfrontend'
    ContainerName: '$web'
    AdditionalArgumentsForBlobCopy: '--content-type "application/javascript"'

Please let me know if you find a way of doing this using the Azure CLI or in my way but recursively (for all .js files).


问:
What is the meaning of XML tags "see "and "seealso" in C# in Visual Studio 2010?
When you work in Visual Studio 2010 and write a comment on a method and click enter
Visual Studio 2010 allows you to create "see" and "see also" XML comments.

If you type in comment "see" and press TAB then it looks like

```<code>/// <see cref=""/>
/// <seealso cref=""/>
</code>```

What is meaning of it in C#?

答:
After so much time I'm surprised nobody has responded with the most important parts of the answer.

Microsoft's standard documentation system, is fueled by special comments tagged with /// or ''' or --- etc depending on language.

By default, the system only feeds intellisense. The XML output created during compilation from these special comments and any supported tags within them can be used as input to other systems such as SandCastle and DocFX but you must install these tools and configure them to benefit from them.  If you use such tools, the difference between the two tags is determined by the tool and perhaps how you configure it, not by Microsoft.  So read the documentation for the tool in question to understand if the tags are treated differently and, if so, in what way.

Having said that, if you aren't using an external tool you may not see the point of using either tag since there is no obvious reason to do so and no obvious difference between them if you choose to use one or the other.

The truth is, there is currently no difference between them from an intellisense point of view.  However there is a very good reason to use one them even if you don't use tools that read the XML output.  That reason is REFACTORING!

By tagging an identifier (with see or seealso) as opposed to just typing it's name as literal text, Visual Studio's refactoring tools are informed that the label is a legal identifier.  This causes any renaming of the identifier to include the tag content.  This has a huge advantage over the often ambiguous string searches that are otherwise necessary to keep documentation in sync with source code when identifiers are renamed.

In a way, it serves a similar function as the nameof() operator, which is useful in building strings.  The difference is, this works within ANY specially marked COMMENT rather than in code.

OwnerDisplayName: Steven Spielberg

Body:
When you work in Visual Studio 2010 and write a comment on a method and click enter
Visual Studio 2010 allows you to create "see" and "see also" XML comments.

If you type in comment "see" and press TAB then it looks like

/// <see cref=""/>
/// <seealso cref=""/>

What is meaning of it in C#?


问:
cmath header confusion
What is the namespace for math functions? Global or std?

Consider cos function. It has 3 overloads. But there is also legacy cos from math.h. C doesn't know anything about function overloading. Therefore cos(x) can't be resolved to cos(float). The solution is to call the single precision version explicitly cosf(x). Did I miss anything?

答: They are in the std namespace.  But, for backwards compatibility reasons the cmath header also shows them in the global namespace with a using std::cos;.

Title: cmath header confusion