问:
Linked List insertion isn't working in for/while loop
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.

```<code>#include <iostream>

class Node {

public:
  int data;
  Node *next;

  Node(int &num) {
    this->data = num;
    next = NULL;
  }
};

class LinkedList {

  Node *head = NULL;

public:
  void insert(int num) {
    Node *tmp;
    if (head == NULL) {
      head = new Node(num);
      tmp = head;
    } else {
      tmp->next = new Node(num);
      tmp = tmp->next;
    }
  }

  void printList() {
    Node *tmp = head;
    while (tmp) {
      std::cout << tmp->data << "  ";
      tmp = tmp->next;
    }
    std::cout << std::endl;
  }

  void reverseList() {
    Node *curr = head, *prev = NULL, *nextNode;
    while (curr) {
      nextNode = curr->next;
      curr->next = prev;
      prev = curr;
      curr = nextNode;
    }
    head = prev;
  }
};

int main() {
  LinkedList list1;
  // This is not working
  int num;
  while (num != -1) {
    std::cin >> num;
    list1.insert(num);
  }

  // This is working
  // list1.insert(1);
  // list1.insert(2);
  // list1.insert(3);
  // list1.insert(4);
  // list1.insert(5);

  list1.printList();
  list1.reverseList();
  list1.printList();

  return 0;
}
</code>```

I expect this after insertion

Edit:
although @Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?

```<code>for (int i = 1; i <= 10; i++)
{
    list1.insert(i);
}
</code>```

答:
first of all you need to define a node for each of the tail and head of the list as follows

```<code>Node *h;
Node *t;
</code>```

you may also separate the Node from the LinkedList class so you can modify easily

```<code>class Node{
public:
    int data;
    Node *next;
    Node(int data, Node* next);
    ~Node();
};
Node::Node(int data, Node* next)
{
    this->data= data;
    this->next= next;
}
Node::~Node(){}
}
</code>```

after that you can try to add these functions to your LinkedList class
so it can deal with other special cases such empty list or full, etc..

```<code>void addToHead(int data){
Node *x = new Node(data,h);
    h=x;
    if(t==NULL){
        t=x;
    }

void addToTail(int data){
Node *x = new Node(data,NULL);
    if(isEmpty()){
        h=t=x;
    }
    else
    {
        t->next=x;
        t=x;
    }
}
</code>```

now for the insert function try this after you implemented the Node class and the other functions,

```<code>void insert(int v){
if(h==nullptr){addToHead(v); return;}
if(h->data>=v) {addToHead(v);return;}
if(t->data<=v) {addToTail(v); return;}
// In this case there is at least two nodes
Node *k=h->next;
Node *p=h;

while(k != nullptr){
if(k->data >v){
Node *z =new Node(v,k);
p->next=z;
return;
}
p=k;
k=k->next;
}

}

</code>```

the idea of making all of this is not lose the pointer when it goes through elements in the Linked List so you don't end up with a run time error.

I hope this can be useful to you.

Body:
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.

#include <iostream>

class Node {

public:
  int data;
  Node *next;

  Node(int &num) {
    this->data = num;
    next = NULL;
  }
};

class LinkedList {

  Node *head = NULL;

public:
  void insert(int num) {
    Node *tmp;
    if (head == NULL) {
      head = new Node(num);
      tmp = head;
    } else {
      tmp->next = new Node(num);
      tmp = tmp->next;
    }
  }

  void printList() {
    Node *tmp = head;
    while (tmp) {
      std::cout << tmp->data << "  ";
      tmp = tmp->next;
    }
    std::cout << std::endl;
  }

  void reverseList() {
    Node *curr = head, *prev = NULL, *nextNode;
    while (curr) {
      nextNode = curr->next;
      curr->next = prev;
      prev = curr;
      curr = nextNode;
    }
    head = prev;
  }
};

int main() {
  LinkedList list1;
  // This is not working
  int num;
  while (num != -1) {
    std::cin >> num;
    list1.insert(num);
  }

  // This is working
  // list1.insert(1);
  // list1.insert(2);
  // list1.insert(3);
  // list1.insert(4);
  // list1.insert(5);

  list1.printList();
  list1.reverseList();
  list1.printList();

  return 0;
}

I expect this after insertion

Edit:
although @Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?

for (int i = 1; i <= 10; i++)
{
    list1.insert(i);
}

Body:
first of all you need to define a node for each of the tail and head of the list as follows

Node *h;
Node *t;

you may also separate the Node from the LinkedList class so you can modify easily

class Node{
public:
    int data;
    Node *next;
    Node(int data, Node* next);
    ~Node();
};
Node::Node(int data, Node* next)
{
    this->data= data;
    this->next= next;
}
Node::~Node(){}
}

after that you can try to add these functions to your LinkedList class
so it can deal with other special cases such empty list or full, etc..

void addToHead(int data){
Node *x = new Node(data,h);
    h=x;
    if(t==NULL){
        t=x;
    }

void addToTail(int data){
Node *x = new Node(data,NULL);
    if(isEmpty()){
        h=t=x;
    }
    else
    {
        t->next=x;
        t=x;
    }
}

now for the insert function try this after you implemented the Node class and the other functions,

void insert(int v){
if(h==nullptr){addToHead(v); return;}
if(h->data>=v) {addToHead(v);return;}
if(t->data<=v) {addToTail(v); return;}
// In this case there is at least two nodes
Node *k=h->next;
Node *p=h;

while(k != nullptr){
if(k->data >v){
Node *z =new Node(v,k);
p->next=z;
return;
}
p=k;
k=k->next;
}

}

the idea of making all of this is not lose the pointer when it goes through elements in the Linked List so you don't end up with a run time error.

I hope this can be useful to you.


来源: stackexchange

问:
Python Unittest Allow Multiple Possible Return Values
I'm writing a unittest that will be run on my class's code. For one of the functions they must write, there are two possible return values that they could return and either one is okay for my purposes.

I've been using

```<code>actual = my_function_call(arg1, arg2)
self.assertEqual(actual, expected)
</code>```

But this doesn't work for accepting one of two valid return values, so I've changed it to:

```<code>actual = my_function_call(arg1, arg2)
self.assertEqual(actual == expected1 or actual == expected2, True)
</code>```

Is there a way to do this that isn't as hacky?

答:
You can do assertTrue and in

self.assertTrue(actual in (expected1, expected2))
```

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a unittest that will be run on my class's code. For one of the functions they must write, there are two possible return values that they could return and either one is okay for my purposes.

I've been using

actual = my_function_call(arg1, arg2)
self.assertEqual(actual, expected)

But this doesn't work for accepting one of two valid return values, so I've changed it to:

actual = my_function_call(arg1, arg2)
self.assertEqual(actual == expected1 or actual == expected2, True)

Is there a way to do this that isn't as hacky?


问:
Tableau data blending how does the column from secondary data source work?
I have 2 data sources, A and B, they are linked by data blending with A.id = B.id, A.order_date = B.order_date. Both fields are linked in worksheet.

when I use A as primary data source and drag A.amount into the view, it gives me the correct sum. However when I use B as primary data source, drag [A].[amount] into the view, it gives less than the correct amount.

Does anyone here have any clue why is that? and how will I be able to use B as primary data source to retrieve A.amount?

答: Tableau Blends works same as left join, so depending on which table you set as "primary", your results may be different.</p>


问:
Find repeated words
I have this assignment where need to

Write a method that takes a String parameter. If the String has a double letter (i.e. contains the same letter twice in a row) then it should return true. Otherwise, it should return false.

This method must be named hasRepeat() and have a String parameter. This method must return a boolean.

However, when I check in my code, I am failing some tests.

It says that it isn't returning false when there are no repeated letters.

Here is my code:

public static boolean hasRepeat(String word) {
    for (int i = 0; i < word.length(); i++) {
        for (int j = i + 1; j < word.length(); j++) {
            if (word.substring(i, i + 1).equals(word.substring(i, j))) {
                return true;
            }
        }
    }
    return false;
}
```

答:
The issue is that when checking the string, the loop skips the last two string, we can fix this by adding the length of the string to 1. Here is the code.
What's also different between our code is the substring</p>

Title: Find repeated words


问:
Docker cannot push image to private registry
I created a Freestyle Project on jenkins to deploy spring boot application using Docker Build and Publish. Moreover I created a secure private registry on same machine using https://www.codeproject.com/Articles/1263817/How-to-Setup-Our-Own-Private-Docker-Registry and https://www.codeproject.com/Articles/1263831/How-to-secure-your-private-Docker-Registry.

I got the following error from Jenkins:

```<code>received unexpected HTTP status: 500 Internal Server Error
Build step 'Docker Build and Publish' marked build as failure
Finished: FAILURE
</code>```

The registry logs are as following:

```<code>{"log":"time=\"2022-02-08T13:24:35.3479554Z\" level=error msg=\"response completed with error\" err.code=unknown err.message=\"unknown error\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"xxx.xxx.xxx.xxx\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=\"999.5µs\" http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3480004Z\" level=error msg=\"response completed with error\" err.code=unknown err.message=\"invalid URL on layer\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"xxx.xxx.xxx.xxx\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.0451ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3480222Z\" level=error msg=\"response completed with error\" err.code=\"manifest blob unknown\" err.detail=sha256:4612f6d0b889cad0ed0292fae3a0b0c8a9e49aff6dea8eb049b2386d9b07986f err.message=\"blob unknown to registry\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"192.168.183.103:51762\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.0671ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3481934Z\" level=error msg=\"response completed with error\" err.code=unknown err.message=\"unknown error\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"xxx.xxx.xxx.xxx\ http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.2378ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3483014Z\" level=error msg=\"response completed with error\" err.code=unknown err.message=\"invalid URL on layer\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"xxx.xxx.xxx.xxx\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.2945ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3483546Z\" level=error msg=\"response completed with error\" err.code=\"manifest blob unknown\" err.detail=sha256:567fd00846e9a9f44eea5925b497356dda00fe89b8335d2a3b2a8b9d84b0bb69 err.message=\"blob unknown to registry\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"192.168.183.103:51762\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.3989ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"xxx.xxx.xxx.xxx - - [08/Feb/2022:13:24:35 +0000] \"PUT /v2/docker-jenkins-integration-sample/manifests/latest HTTP/1.1\" 500 523 \"\" \"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\\\(windows\\\\))\"\n","stream":"stdout","time":"2022-02-08T13:24:35.8661829Z"}
</code>```

Setting like "max-concurrent-downloads": 1 is not worked. How to solve the issue?

EDIT

I created the private registry by following command on powershell in Windows Server 2019

```<code> docker run -d -p 443:443 --name hub.local -v C:/localhub/certs:/certs -v C:/localhub/registry:/var/lib/registry -e REGISTRY_HTTP_ADDR=0.0.0.0:443 -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/localhub.crt -e REGISTRY_HTTP_TLS_KEY=/certs/localhub.key registry
</code>```

Jenkins setting are as below:

Jenkins settings

答:
Given the invalid URL error and on the "windows" in the 500, I'm guessing it's a foreign layer for windows images that's getting rejected by validation. I tried figuring out the right syntax to allow that in the past and eventually gave up and turned off the validation with REGISTRY_VALIDATION_DISABLED=true. E.g. here's a command I use to start a registry:

```<code>docker run -d --restart=unless-stopped --name registry \
  -e "REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=/var/lib/registry" \
  -e "REGISTRY_STORAGE_DELETE_ENABLED=true" \
  -e "REGISTRY_VALIDATION_DISABLED=true" \
  -v "registry-data:/var/lib/registry" \
  -p "127.0.0.1:5000:5000" \
  registry:2
</code>```

Body:
I created a Freestyle Project on jenkins to deploy spring boot application using Docker Build and Publish. Moreover I created a secure private registry on same machine using https://www.codeproject.com/Articles/1263817/How-to-Setup-Our-Own-Private-Docker-Registry and https://www.codeproject.com/Articles/1263831/How-to-secure-your-private-Docker-Registry.

I got the following error from Jenkins:

received unexpected HTTP status: 500 Internal Server Error
Build step 'Docker Build and Publish' marked build as failure
Finished: FAILURE

The registry logs are as following:

{"log":"time=\"2022-02-08T13:24:35.3479554Z\" level=error msg=\"response completed with error\" err.code=unknown err.message=\"unknown error\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"xxx.xxx.xxx.xxx\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=\"999.5µs\" http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3480004Z\" level=error msg=\"response completed with error\" err.code=unknown err.message=\"invalid URL on layer\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"xxx.xxx.xxx.xxx\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.0451ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3480222Z\" level=error msg=\"response completed with error\" err.code=\"manifest blob unknown\" err.detail=sha256:4612f6d0b889cad0ed0292fae3a0b0c8a9e49aff6dea8eb049b2386d9b07986f err.message=\"blob unknown to registry\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"192.168.183.103:51762\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.0671ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3481934Z\" level=error msg=\"response completed with error\" err.code=unknown err.message=\"unknown error\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"xxx.xxx.xxx.xxx\ http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.2378ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3483014Z\" level=error msg=\"response completed with error\" err.code=unknown err.message=\"invalid URL on layer\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"xxx.xxx.xxx.xxx\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.2945ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"time=\"2022-02-08T13:24:35.3483546Z\" level=error msg=\"response completed with error\" err.code=\"manifest blob unknown\" err.detail=sha256:567fd00846e9a9f44eea5925b497356dda00fe89b8335d2a3b2a8b9d84b0bb69 err.message=\"blob unknown to registry\" go.version=go1.16.13 http.request.contenttype=\"application/vnd.docker.distribution.manifest.v2+json\" http.request.host=hub.docker http.request.id=798ba3fb-0471-4e76-b8c6-fa04b7cd5d6a http.request.method=PUT http.request.remoteaddr=\"192.168.183.103:51762\" http.request.uri=\"/v2/docker-jenkins-integration-sample/manifests/latest\" http.request.useragent=\"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\(windows\\))\" http.response.contenttype=\"application/json; charset=utf-8\" http.response.duration=1.3989ms http.response.status=500 http.response.written=523 vars.name=docker-jenkins-integration-sample vars.reference=latest \n","stream":"stderr","time":"2022-02-08T13:24:35.8661829Z"}
{"log":"xxx.xxx.xxx.xxx - - [08/Feb/2022:13:24:35 +0000] \"PUT /v2/docker-jenkins-integration-sample/manifests/latest HTTP/1.1\" 500 523 \"\" \"docker/19.03.5 go/go1.12.12 git-commit/2ee0c57608 os/windows arch/amd64 UpstreamClient(Docker-Client/19.03.5 \\\\(windows\\\\))\"\n","stream":"stdout","time":"2022-02-08T13:24:35.8661829Z"}

Setting like "max-concurrent-downloads": 1 is not worked. How to solve the issue?

EDIT

I created the private registry by following command on powershell in Windows Server 2019

 docker run -d -p 443:443 --name hub.local -v C:/localhub/certs:/certs -v C:/localhub/registry:/var/lib/registry -e REGISTRY_HTTP_ADDR=0.0.0.0:443 -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/localhub.crt -e REGISTRY_HTTP_TLS_KEY=/certs/localhub.key registry

Jenkins setting are as below:

Jenkins settings

Body:
Given the invalid URL error and on the "windows" in the 500, I'm guessing it's a foreign layer for windows images that's getting rejected by validation. I tried figuring out the right syntax to allow that in the past and eventually gave up and turned off the validation with REGISTRY_VALIDATION_DISABLED=true. E.g. here's a command I use to start a registry:

docker run -d --restart=unless-stopped --name registry \
  -e "REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=/var/lib/registry" \
  -e "REGISTRY_STORAGE_DELETE_ENABLED=true" \
  -e "REGISTRY_VALIDATION_DISABLED=true" \
  -v "registry-data:/var/lib/registry" \
  -p "127.0.0.1:5000:5000" \
  registry:2


问:
Input value does not change after changeDetection() in Angular unit test
I use this component code:

HTML:

<app-input [model]="model" field="name"></app-input>
```
<p>TypeScript:</p>
<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'app-post-create-edit',
  templateUrl: './post-create-edit.component.html',
  styleUrls: ['./post-create-edit.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PostCreateEditComponent {
  model: new Post();
}
</code>```

In my spec.ts file:

describe('PostCreateEditComponent', () => {
  let fixture: ComponentFixture<PostCreateEditComponent>;
  let component: PostCreateEditComponent;
  const datas = POSTS_CREATE_EDIT_DATASET;
  const model: PostInterface = new Post([datas[0]);

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [...],
      providers: [...],
      declarations: [PostCreateEditComponent]
    })
    .compileComponents()
    .then(() => {
      fixture = TestBed.createComponent(PostCreateEditComponent);
      component = fixture.componentInstance;
      debugElement = fixture.debugElement;
      component.model = model;
      fixture.detectChanges();
    });
  });

  describe('general', () => {
    it('create-edit component test', () => {
      fixture.whenStable().then(() => {
        const container = context.debugElement
          .queryAll(By.css(`app-input[field="name"]`));
        const input = container[0].queryAll(By.css(context.input.type));

        expect(input[0].nativeElement.value).toEqual(model.name);
      });
    });
  });
});
```

And it says Error: "name" input element: Expected 'First post title' to equal ''.

I don't understand why doesn't changed the input field's value after call changeDetection().

How can I solve this issue? What I miss?

答:
I think the problem is backwards from what you think it is. Jasmine assertions give the "found" value first and the expected value second. It's expecting '' but finding 'First post title'.

I think. Jasmine assertion responses always get me mixed up ^^

Body:
I use this component code:

HTML:

<app-input [model]="model" field="name"></app-input>

TypeScript:

@Component({
  selector: 'app-post-create-edit',
  templateUrl: './post-create-edit.component.html',
  styleUrls: ['./post-create-edit.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PostCreateEditComponent {
  model: new Post();
}

In my spec.ts file:

describe('PostCreateEditComponent', () => {
  let fixture: ComponentFixture<PostCreateEditComponent>;
  let component: PostCreateEditComponent;
  const datas = POSTS_CREATE_EDIT_DATASET;
  const model: PostInterface = new Post([datas[0]);

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [...],
      providers: [...],
      declarations: [PostCreateEditComponent]
    })
    .compileComponents()
    .then(() => {
      fixture = TestBed.createComponent(PostCreateEditComponent);
      component = fixture.componentInstance;
      debugElement = fixture.debugElement;
      component.model = model;
      fixture.detectChanges();
    });
  });

  describe('general', () => {
    it('create-edit component test', () => {
      fixture.whenStable().then(() => {
        const container = context.debugElement
          .queryAll(By.css(`app-input[field="name"]`));
        const input = container[0].queryAll(By.css(context.input.type));

        expect(input[0].nativeElement.value).toEqual(model.name);
      });
    });
  });
});

And it says Error: "name" input element: Expected 'First post title' to equal ''.

I don't understand why doesn't changed the input field's value after call changeDetection().

How can I solve this issue? What I miss?


问:
Angular performance issues when cropping image
I'm using this component to crop images as part of an ionic/angular8 project, but I'm getting serious performance issues making the app irresponsive at some times, this is only manifesting when running from mobile, the desktop version doesn't show any issues, the crop works just fine.

Doing a performance review in some cases I see these garbage collections; I came from a java world, and GC is always a performance issue, but haven't found much about it, but I don't think its the root of the problem:

Here is another sample, seems to be a delay between the user interacting with the screen, and my inner method getting called, as you can see there's a FunctionCall, but which function.

My general code is almost the same as in the site but I'll share it here:

Html:

```<code><div class="popup-form-container ion-text-center ion-padding">
<image-cropper
      [imageChangedEvent]="imageChangedEvent"
      [maintainAspectRatio]="true"
      [aspectRatio]="4 / 4"
      format="png"
      (imageCropped)="imageCropped($event)"
      (imageLoaded)="imageLoaded()"
      (cropperReady)="cropperReady()"
      (loadImageFailed)="loadImageFailed()"
  ></image-cropper>
  <ion-button fill="clear" color="danger" (click)="close()">Cancelar</ion-button>
  <ion-button color="green" (click)="save()">Guardar</ion-button>
</div>
</code>```

And here you can see my class, I added a bunch of console logs in the process of finding the issue, and something I've seen is that when the app freezes and stays in the long call, there's no outpu, then out of the souden, lots in a row:

```<code>    @Component({
  selector: 'app-crop-image-popover',
  templateUrl: './crop-image-popover.component.html',
  styleUrls: ['./crop-image-popover.component.scss',
              '../../text-area/text-edit-popover/text-edit-popover.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CropImagePopoverComponent implements OnInit {

  @Input()
  imageChangedEvent: any;

  private croppedImage: any = '';
  private uploader: FileUploader;
  private imageUrl: any;
  private errors: any;

  constructor(private modalCtrl: ModalController,
              private commonSrv: CommonService,
              protected cloudinary: Cloudinary,
              private alertCtrl: AlertController,
              private sysParamsSrv: SystemParamsService,
              private base64: Base64,
              private domSanitizer: DomSanitizer,
              private imageCompress: NgxImageCompressService,
              private changeDetector: ChangeDetectorRef) {
    // Inicializamos el compoente de carga de archivos

  }

  ngOnInit() {}

  imageCropped(event: ImageCroppedEvent) {
    console.log('cropped');
    this.croppedImage = event.base64;
  }
  imageLoaded() {
    console.log('loaded');
    // show cropper
//     this.commonSrv.hideSpinner();
  }
  cropperReady() {
    // cropper ready
    console.log('ready');
    this.commonSrv.hideSpinner();
  }
  loadImageFailed() {
    // show message
    console.log('failed');
  }

  close() {
    this.modalCtrl.dismiss();
  }
}
</code>```

I've already tried updating the changeDetection strategy, removed some function calls I had in other pages, and most of the performance recommendations, but I don't seem to find the reason for my current problem

答:
ngx-image-cropper, when you change the crop size/position it actually crops the image and is very resource intensive. If you can get away with it, you can only do the crop once by setting autoCrop to false like so:

```<code><image-cropper
    [imageChangedEvent]="imageChangedEvent"
    [maintainAspectRatio]="true"
    [aspectRatio]="1"
    [autoCrop]="false"
    format="png"
    (imageLoaded)="imageLoaded()"
    (cropperReady)="cropperReady()"
    (loadImageFailed)="loadImageFailed()"
></image-cropper>
<ion-button fill="clear" color="danger" (click)="close()">Cancelar</ion-button>
<ion-button color="green" (click)="save()">Guardar</ion-button>
</code>```

Then use the @ViewChild to get access to the cropper and thus the cropping methods. Here is what that looks like within the typescript file:

```<code>@ViewChild(ImageCropperComponent) imageCropper: ImageCropperComponent;
</code>```

Then, when the user selects to keep the crop, you will need to do something like this:

```<code>function save(): void {
  const event = this.imageCropper.crop();
  this.croppedImage = event.base64;
}
</code>```

This will fix some performance issues. But do note that it appears that iDevices struggle with handling cropping in the way that ngx-image-cropper does it. Specifically, if the user uses the camera while uploading an image, the image may require too much memory to convert to a base64 string in the Safari thread - as a result, iDevices can freeze when used normally. Here is one place where this is discussed: https://github.com/Mawi137/ngx-image-cropper/issues/481

Body:
I'm using this component to crop images as part of an ionic/angular8 project, but I'm getting serious performance issues making the app irresponsive at some times, this is only manifesting when running from mobile, the desktop version doesn't show any issues, the crop works just fine.

Doing a performance review in some cases I see these garbage collections; I came from a java world, and GC is always a performance issue, but haven't found much about it, but I don't think its the root of the problem:

Here is another sample, seems to be a delay between the user interacting with the screen, and my inner method getting called, as you can see there's a FunctionCall, but which function.

My general code is almost the same as in the site but I'll share it here:

Html:

<image-cropper
      [imageChangedEvent]="imageChangedEvent"
      [maintainAspectRatio]="true"
      [aspectRatio]="4 / 4"
      format="png"
      (imageCropped)="imageCropped($event)"
      (imageLoaded)="imageLoaded()"
      (cropperReady)="cropperReady()"
      (loadImageFailed)="loadImageFailed()"
  ></image-cropper>
  <ion-button fill="clear" color="danger" (click)="close()">Cancelar</ion-button>
  <ion-button color="green" (click)="save()">Guardar</ion-button>

And here you can see my class, I added a bunch of console logs in the process of finding the issue, and something I've seen is that when the app freezes and stays in the long call, there's no outpu, then out of the souden, lots in a row:

    @Component({
  selector: 'app-crop-image-popover',
  templateUrl: './crop-image-popover.component.html',
  styleUrls: ['./crop-image-popover.component.scss',
              '../../text-area/text-edit-popover/text-edit-popover.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CropImagePopoverComponent implements OnInit {

  @Input()
  imageChangedEvent: any;

  private croppedImage: any = '';
  private uploader: FileUploader;
  private imageUrl: any;
  private errors: any;

  constructor(private modalCtrl: ModalController,
              private commonSrv: CommonService,
              protected cloudinary: Cloudinary,
              private alertCtrl: AlertController,
              private sysParamsSrv: SystemParamsService,
              private base64: Base64,
              private domSanitizer: DomSanitizer,
              private imageCompress: NgxImageCompressService,
              private changeDetector: ChangeDetectorRef) {
    // Inicializamos el compoente de carga de archivos

  }

  ngOnInit() {}

  imageCropped(event: ImageCroppedEvent) {
    console.log('cropped');
    this.croppedImage = event.base64;
  }
  imageLoaded() {
    console.log('loaded');
    // show cropper
//     this.commonSrv.hideSpinner();
  }
  cropperReady() {
    // cropper ready
    console.log('ready');
    this.commonSrv.hideSpinner();
  }
  loadImageFailed() {
    // show message
    console.log('failed');
  }

  close() {
    this.modalCtrl.dismiss();
  }
}

I've already tried updating the changeDetection strategy, removed some function calls I had in other pages, and most of the performance recommendations, but I don't seem to find the reason for my current problem

Body:
ngx-image-cropper, when you change the crop size/position it actually crops the image and is very resource intensive. If you can get away with it, you can only do the crop once by setting autoCrop to false like so:

<image-cropper
    [imageChangedEvent]="imageChangedEvent"
    [maintainAspectRatio]="true"
    [aspectRatio]="1"
    [autoCrop]="false"
    format="png"
    (imageLoaded)="imageLoaded()"
    (cropperReady)="cropperReady()"
    (loadImageFailed)="loadImageFailed()"
></image-cropper>
<ion-button fill="clear" color="danger" (click)="close()">Cancelar</ion-button>
<ion-button color="green" (click)="save()">Guardar</ion-button>

Then use the @ViewChild to get access to the cropper and thus the cropping methods. Here is what that looks like within the typescript file:

@ViewChild(ImageCropperComponent) imageCropper: ImageCropperComponent;

Then, when the user selects to keep the crop, you will need to do something like this:

function save(): void {
  const event = this.imageCropper.crop();
  this.croppedImage = event.base64;
}

This will fix some performance issues. But do note that it appears that iDevices struggle with handling cropping in the way that ngx-image-cropper does it. Specifically, if the user uses the camera while uploading an image, the image may require too much memory to convert to a base64 string in the Safari thread - as a result, iDevices can freeze when used normally. Here is one place where this is discussed: https://github.com/Mawi137/ngx-image-cropper/issues/481


问:
Why is the cursor shaking?
My marker has a problem that when I do mouse:hover the cursor is shaking.

I put my component into codesandbox with the same code I'm using on my application.

You may notice when you bring the mouse closer to the edge of the marker, the cursor starts to shaking.

.marker {
  transition: all 0.5s ease;
  border: 2px solid #fff;
  background-color: #61ba9e;
  border-radius: 100%;
  width: 20px;
  height: 20px;
}

.marker:hover {
  height: 12.5px;
  width: 12.5px;
  box-shadow: 0 0 0 4px rgb(97 186 158 / 60%);
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="marker"></div></code>```

I don't know why this is happening, can you help me?

Thanks in advance.

答:
The shaking is caused by your element shrinking and therefore your cursor not hovering anymore (and then re-growing as you aren't hovering, causing your cursor to change again)

Instead of changing the size of your marker, why not use a pseudo element, then your hand won't "shake" as it will always hover the marker (but the pseudo element will change size instead).

.marker {
  width: 20px;
  height: 20px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
}

.marker:hover {
  cursor: pointer;
}

.marker:after {
  content: '';
  display: block;
  transition: all 0.5s ease;
  border: 2px solid #fff;
  background-color: #61ba9e;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  box-sizing:border-box;
}

.marker:hover:after {
  height: 12.5px;
  width: 12.5px;
  box-shadow: 0 0 0 4px rgb(97 186 158 / 60%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="marker"></div></code>```

Title: Why is the cursor shaking?

Body:
My marker has a problem that when I do mouse:hover the cursor is shaking.

I put my component into codesandbox with the same code I'm using on my application.

You may notice when you bring the mouse closer to the edge of the marker, the cursor starts to shaking.

.marker {
  transition: all 0.5s ease;
  border: 2px solid #fff;
  background-color: #61ba9e;
  border-radius: 100%;
  width: 20px;
  height: 20px;
}

.marker:hover {
  height: 12.5px;
  width: 12.5px;
  box-shadow: 0 0 0 4px rgb(97 186 158 / 60%);
  cursor: pointer;
}

I don't know why this is happening, can you help me?

Thanks in advance.

Body:
The shaking is caused by your element shrinking and therefore your cursor not hovering anymore (and then re-growing as you aren't hovering, causing your cursor to change again)

Instead of changing the size of your marker, why not use a pseudo element, then your hand won't "shake" as it will always hover the marker (but the pseudo element will change size instead).

.marker {
  width: 20px;
  height: 20px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
}

.marker:hover {
  cursor: pointer;
}

.marker:after {
  content: '';
  display: block;
  transition: all 0.5s ease;
  border: 2px solid #fff;
  background-color: #61ba9e;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  box-sizing:border-box;
}

.marker:hover:after {
  height: 12.5px;
  width: 12.5px;
  box-shadow: 0 0 0 4px rgb(97 186 158 / 60%);
}

<div class="marker"></div>


问:
How to get the part of a file after the first line that matches a regular expression
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

```<code>cat file | grep 'TERMINATE'     # It is found on line 534
</code>```

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

答:
Use Bash parameter expansion like the following:</p>
```<code>content=$(cat file)
echo "${content#*TERMINATE}"
</code>```

Body:
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

cat file | grep 'TERMINATE'     # It is found on line 534

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

Body:
Use Bash parameter expansion like the following:

content=$(cat file)
echo "${content#*TERMINATE}"


问:
How to create python kafka producer with multiple bootstrap servers?
I'm trying to use send messages to a Kafka topic which is supported by multiple brokers. Below is my method, where self.bootstrap_servers = "[b-1.dev-stg-kafka.wjiw3s.c1.kafka.us-east-1.amazonaws.com:9092, b-2.dev-stg-kafka.wjiw3s.c1.kafka.us-east-1.amazonaws.com:9092]"

```<code>from kafka import KafkaProducer
from time import sleep
    def send(self):
        try:
            producer = KafkaProducer(bootstrap_servers=self.bootstrap_server, api_version=(0, 10, 1))
            message = self.prepare_message()
            producer.send(self.topic, self.encoded_payload)
            sleep(2)
        except:
            print("Exception sending message to kafka")
</code>```

when I try to test this I get in the exception block and the line that fails is when I create my producer. How can I publish a Kafka message with this KafkaProducer, which has multiple kafka bootstrap_servers supporting it? Is there another way to do this?

Error:

```<code>  File "C:\Users\ENV\datareplayer\venv\lib\site-packages\kafka\client_async.py", line 216, in __init__
    self._bootstrap(collect_hosts(self.config['bootstrap_servers']))
  File "C:\Users\ENV\datareplayer\venv\lib\site-packages\kafka\conn.py", line 1236, in collect_hosts
    host, port, afi = get_ip_port_afi(host_port)
  File "C:\Users\ENV\datareplayer\venv\lib\site-packages\kafka\conn.py", line 1192, in get_ip_port_afi
    host, rest = host_and_port_str[1:].split(']')
ValueError: not enough values to unpack (expected 2, got 1)
</code>```

答:
ast.literal_eval(bootstrap_servers) can help.

It takes a stringified list as input, and converts it to a list. For example:

```<code>input_str = "['broker1', 'broker2', 'broker3']"

type(input_str)
str
</code>```

If you do

```<code>input_list = ast.literal_eval(input_str)
</code>```

input_list is now a list

```<code>type(input_list)
list
</code>```

Body:
I'm trying to use send messages to a Kafka topic which is supported by multiple brokers. Below is my method, where self.bootstrap_servers = "[b-1.dev-stg-kafka.wjiw3s.c1.kafka.us-east-1.amazonaws.com:9092, b-2.dev-stg-kafka.wjiw3s.c1.kafka.us-east-1.amazonaws.com:9092]"

from kafka import KafkaProducer
from time import sleep
    def send(self):
        try:
            producer = KafkaProducer(bootstrap_servers=self.bootstrap_server, api_version=(0, 10, 1))
            message = self.prepare_message()
            producer.send(self.topic, self.encoded_payload)
            sleep(2)
        except:
            print("Exception sending message to kafka")

when I try to test this I get in the exception block and the line that fails is when I create my producer. How can I publish a Kafka message with this KafkaProducer, which has multiple kafka bootstrap_servers supporting it? Is there another way to do this?

Error:

  File "C:\Users\ENV\datareplayer\venv\lib\site-packages\kafka\client_async.py", line 216, in __init__
    self._bootstrap(collect_hosts(self.config['bootstrap_servers']))
  File "C:\Users\ENV\datareplayer\venv\lib\site-packages\kafka\conn.py", line 1236, in collect_hosts
    host, port, afi = get_ip_port_afi(host_port)
  File "C:\Users\ENV\datareplayer\venv\lib\site-packages\kafka\conn.py", line 1192, in get_ip_port_afi
    host, rest = host_and_port_str[1:].split(']')
ValueError: not enough values to unpack (expected 2, got 1)

Body:
ast.literal_eval(bootstrap_servers) can help.

It takes a stringified list as input, and converts it to a list. For example:

input_str = "['broker1', 'broker2', 'broker3']"

type(input_str)
str

If you do

input_list = ast.literal_eval(input_str)

input_list is now a list

type(input_list)
list


问:
How can I have all references of a method in Roslyn (method is called by other classes)?
Thanks to Roslyn, having access to .Net compiler, in our project Gcop  we need to have list of references where are calling a method.

VS IDE shows the reference places very suitable like this:

Actually I want to understand which class/name space and even assembly is calling my method by Roslyn C# syntax.

Currently I have access to MethodSymbol here :

```<code>var methodSymbol = semanticModel.GetSymbolInfo(invocation).Symbol as IMethodSymbol;
</code>```

what should I write to get access to references of this method?

//added recently for double check

```<code> var solutionPath = Utilities.DteExtensions.SolutionFullPath;
 var msWorkspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create();
 var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result;

 var result = new List<ReferenceLocation>();
 var refrences = SymbolFinder.FindReferencesAsync(methodSymbol, solution).Result;

 foreach (var refernc in refrences)
  {
    foreach (var location in refernc.Locations)
     {
         result.Add(location);
     }
  }
///???????? why the result is empty ?
</code>```

答:
I prefer to change following to make it work:

```<code> var nodes = methodInvocation.DescendantNodes().OfType<InvocationExpressionSyntax>()
   .Where(x => x.Expression.ToString().Contains(methodName));
</code>```

To:

```<code>var nodes = new List<InvocationExpressionSyntax>();
foreach (var methodInvocationExpression in methodInvocation.DescendantNodes().OfType<InvocationExpressionSyntax>())
{
    if(methodInvocationExpression.DescendantNodes().OfType<MemberAccessExpressionSyntax>().Any(x => x.Name.Identifier.ValueText == methodName))
    {
        nodes.Add(methodInvocationExpression);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Thanks to Roslyn, having access to .Net compiler, in our project Gcop  we need to have list of references where are calling a method.

VS IDE shows the reference places very suitable like this:

Actually I want to understand which class/name space and even assembly is calling my method by Roslyn C# syntax.

Currently I have access to MethodSymbol here :

var methodSymbol = semanticModel.GetSymbolInfo(invocation).Symbol as IMethodSymbol;

what should I write to get access to references of this method?

//added recently for double check

 var solutionPath = Utilities.DteExtensions.SolutionFullPath;
 var msWorkspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create();
 var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result;

 var result = new List<ReferenceLocation>();
 var refrences = SymbolFinder.FindReferencesAsync(methodSymbol, solution).Result;

 foreach (var refernc in refrences)
  {
    foreach (var location in refernc.Locations)
     {
         result.Add(location);
     }
  }
///???????? why the result is empty ?

Body:
I prefer to change following to make it work:

 var nodes = methodInvocation.DescendantNodes().OfType<InvocationExpressionSyntax>()
   .Where(x => x.Expression.ToString().Contains(methodName));

To:

var nodes = new List<InvocationExpressionSyntax>();
foreach (var methodInvocationExpression in methodInvocation.DescendantNodes().OfType<InvocationExpressionSyntax>())
{
    if(methodInvocationExpression.DescendantNodes().OfType<MemberAccessExpressionSyntax>().Any(x => x.Name.Identifier.ValueText == methodName))
    {
        nodes.Add(methodInvocationExpression);
    }
}


问:
Highlight DT diagonal in R Shiny
I have a large datatable in a Shiny app and would like to highlight the diagonal, using logic something like if rowNum == colNum then 'blue' else 'white'.

The rowCallback DT option would let me style by row number, but I can't find anything in the docs that would do the equivalent for column number at the same time.

The best idea I have is to create ~200 extra boolean columns in the table just to determine whether each cell is highlighted or not, hiding them, and using formatStyle(valueColumns = 201:400) to style the others. But that seems like massive overkill here. Any bright ideas?

答:
@danloo's answer gives the desired rendering but you should avoid HTML in cells, because it disturbs the sorting. Here is a way with rowCallback:

```<code>library(DT)

js <- c(
  "function(row, data, displayNum, displayIndex, dataIndex){",
  "  $('td:eq(' + dataIndex + ')', row).css('background-color', 'yellow');",
  "}"
)

dat <- as.data.frame(matrix(1:9, nrow = 3))

datatable(
  dat,
  rownames = FALSE,
  options = list(
    rowCallback = JS(js)
  )
)
</code>```

Title: Highlight DT diagonal in R Shiny

Body:
@danloo's answer gives the desired rendering but you should avoid HTML in cells, because it disturbs the sorting. Here is a way with rowCallback:

library(DT)

js <- c(
  "function(row, data, displayNum, displayIndex, dataIndex){",
  "  $('td:eq(' + dataIndex + ')', row).css('background-color', 'yellow');",
  "}"
)

dat <- as.data.frame(matrix(1:9, nrow = 3))

datatable(
  dat,
  rownames = FALSE,
  options = list(
    rowCallback = JS(js)
  )
)


问:
Try to offline exporting to Highcharts
I want to make offline exporting with highcharts.
Here is my code

```<code>import {Chart} from 'highcharts-vue'
import Highcharts from 'highcharts'
import offlineExporting from "highcharts/modules/offline-exporting"
offlineExporting(Highcharts)
</code>```

I tried  to use exporting.js and offline-exporting.js together and it worked.
Is this solution of the problem? If it'not, is there any another solution?

答:
For offline-exporting you have to make client side export implementation

```<code>import { withHighcharts } from 'react-jsx-highcharts';
import Highcharts from 'highcharts';
import exportingOption from 'highcharts/modules/exporting';
import offlineOption from 'highcharts/modules/offline-exporting';

exportingOption(Highcharts);
offlineOption(Highcharts);

withHighcharts(Component, Highcharts);
</code>```

Additionally you have to add exporting object as Highcharts option

```<code>exporting: {
    buttons: {
        contextButton: {
            menuItems: ['downloadPNG', 'downloadJPEG', 'downloadPDF', 'downloadSVG']
        }
    }
}
</code>```

Title: Try to offline exporting to Highcharts

Body:
I want to make offline exporting with highcharts.
Here is my code

import {Chart} from 'highcharts-vue'
import Highcharts from 'highcharts'
import offlineExporting from "highcharts/modules/offline-exporting"
offlineExporting(Highcharts)

I tried  to use exporting.js and offline-exporting.js together and it worked.
Is this solution of the problem? If it'not, is there any another solution?

Body:
For offline-exporting you have to make client side export implementation

import { withHighcharts } from 'react-jsx-highcharts';
import Highcharts from 'highcharts';
import exportingOption from 'highcharts/modules/exporting';
import offlineOption from 'highcharts/modules/offline-exporting';

exportingOption(Highcharts);
offlineOption(Highcharts);

withHighcharts(Component, Highcharts);

Additionally you have to add exporting object as Highcharts option

exporting: {
    buttons: {
        contextButton: {
            menuItems: ['downloadPNG', 'downloadJPEG', 'downloadPDF', 'downloadSVG']
        }
    }
}


问:
Flutter signedapk build error in android studio
Task :app:compileFlutterBuildRelease
Can't load Kernel binary: Invalid kernel binary format version.
Dart snapshot generator failed with exit code 254
Can't load Kernel binary: Invalid kernel binary format version.
Dart snapshot generator failed with exit code 254

Task :app:compileFlutterBuildRelease FAILED

答:
Try this commands to clear all your project and rebuild</p>
```<code>flutter create .
flutter clean
flutter pub get
</code>```

Body:
Try this commands to clear all your project and rebuild

flutter create .
flutter clean
flutter pub get


问:
How to avoid many database round trips and a lot of irrelevant data?
I have worked with various applications and encountered this situation many times. Until now I have not figured out what is the best approach.

Here's the scenario:

I have an application either desktop or web

I need to retrieve simple documents from the database. The document has a general details and item details so the database:

GeneralDetails table:

```<code>| DocumentID | DateCreated | Owner     |
| 1          | 07/07/07    | Naruto    |
| 2          | 08/08/08    | Goku      |
| 3          | 09/09/09    | Taguro    |
</code>```

ItemDetails table

```<code>| DocumentID | Item        | Quantity  |
| 1          | Marbles     | 20        |
| 1          | Cards       | 56        |
| 2          | Yo-yo       | 1         |
| 2          | Chess board | 3         |
| 2          | GI Joe      | 12        |
| 3          | Rubber Duck | 1         |
</code>```

As you can see, the tables have a one-to-many relationship. Now, in order to retrieve all the documents and their respective items, I always do either of the two:

Method 1 - Many round trips (pseudo-code):

```<code> Documents = GetFromDB("select DocumentID, Owner " +
                       "from GeneralDetails")
 For Each Document in Documents
{
    Display(Document["CreatedBy"])
    DocumentItems = GetFromDB("select Item, Quantity " +
                              "from ItemDetails " +
                              "where DocumentID = " + Document["DocumentID"] + "")
    For Each DocumentItem in DocumentItems
    {
        Display(DocumentItem["Item"] + " " + DocumentItem["Quantity"])
    }
}
</code>```

Method 2 - Much irrelevant data (pseudo-code):

```<code>DocumentsAndItems = GetFromDB("select g.DocumentID, g.Owner, i.Item, i.Quantity " +
                              "from GeneralDetails as g " +
                              "inner join ItemDetails as i " +
                              "on g.DocumentID = i.DocumentID")
//Display...
</code>```

I used the first method when I was in college for desktop applications, the performance was not bad so I realized it was okay.

Until one day, I saw an article "Make the web faster", it says that many round trips to the database is bad; so ever since then I have used the second method.

On the second method, I avoided round trips by using inner join to retrieve the first and the second table at once, but it produces unecessary or redundant data. See the result set.

```<code>| DocumentID | Owner     | Item        | Quantity  |
| 1          | Naruto    | Marbles     | 20        |
| 1          | Naruto    | Cards       | 56        |
| 2          | Goku      | Yo-yo       | 1         |
| 2          | Goku      | Chess board | 3         |
| 2          | Goku      | GI Joe      | 12        |
| 3          | Taguro    | Rubber Duck | 1         |
</code>```

The result set has redundant DocumentID and Owner. It looks like an unnormalized database.

Now, the question is, how do I avoid round trips and at the same time avoid redundant data?

答:
The inner join is better because the database has more possibilities to optimize.

In general you can not create a query like this which does not produce redundant results. For that, the relational model is too restrictive. I would just live with it: the database is responsible to optimize these cases.

If you really encounter performance problems (mainly because of a network bottleneck) you could write a stored procedure, that makes the query and denormalizes it. In your example you create create a result like:

```<code>| DocumentID | Owner     | Items                                   | Quantity    |
| 1          | Naruto    | Marbles, Cards                          | 20, 56      |
| 2          | Goku      | Yo-yo, Chess board, GI Joe, Rubber Duck | 1, 3, 12, 1 |
</code>```

But this of course does not conform to the first normal form - so you will need to parse it on the client.
If you use a database with XML support (like Oracle or MS SQL Server) you could even create an XML file on the server and send this to the client.

But whatever you do, remember: premature optimization is the root of all evil. Don't do this kind of stuff before you are not 100% sure, that you are really facing a problem you can solve like this.

Body:
I have worked with various applications and encountered this situation many times. Until now I have not figured out what is the best approach.

Here's the scenario:

I have an application either desktop or web

I need to retrieve simple documents from the database. The document has a general details and item details so the database:

GeneralDetails table:

| DocumentID | DateCreated | Owner     |
| 1          | 07/07/07    | Naruto    |
| 2          | 08/08/08    | Goku      |
| 3          | 09/09/09    | Taguro    |

ItemDetails table

| DocumentID | Item        | Quantity  |
| 1          | Marbles     | 20        |
| 1          | Cards       | 56        |
| 2          | Yo-yo       | 1         |
| 2          | Chess board | 3         |
| 2          | GI Joe      | 12        |
| 3          | Rubber Duck | 1         |

As you can see, the tables have a one-to-many relationship. Now, in order to retrieve all the documents and their respective items, I always do either of the two:

Method 1 - Many round trips (pseudo-code):

 Documents = GetFromDB("select DocumentID, Owner " +
                       "from GeneralDetails")
 For Each Document in Documents
{
    Display(Document["CreatedBy"])
    DocumentItems = GetFromDB("select Item, Quantity " +
                              "from ItemDetails " +
                              "where DocumentID = " + Document["DocumentID"] + "")
    For Each DocumentItem in DocumentItems
    {
        Display(DocumentItem["Item"] + " " + DocumentItem["Quantity"])
    }
}

Method 2 - Much irrelevant data (pseudo-code):

DocumentsAndItems = GetFromDB("select g.DocumentID, g.Owner, i.Item, i.Quantity " +
                              "from GeneralDetails as g " +
                              "inner join ItemDetails as i " +
                              "on g.DocumentID = i.DocumentID")
//Display...

I used the first method when I was in college for desktop applications, the performance was not bad so I realized it was okay.

Until one day, I saw an article "Make the web faster", it says that many round trips to the database is bad; so ever since then I have used the second method.

On the second method, I avoided round trips by using inner join to retrieve the first and the second table at once, but it produces unecessary or redundant data. See the result set.

| DocumentID | Owner     | Item        | Quantity  |
| 1          | Naruto    | Marbles     | 20        |
| 1          | Naruto    | Cards       | 56        |
| 2          | Goku      | Yo-yo       | 1         |
| 2          | Goku      | Chess board | 3         |
| 2          | Goku      | GI Joe      | 12        |
| 3          | Taguro    | Rubber Duck | 1         |

The result set has redundant DocumentID and Owner. It looks like an unnormalized database.

Now, the question is, how do I avoid round trips and at the same time avoid redundant data?

Body:
The inner join is better because the database has more possibilities to optimize.

In general you can not create a query like this which does not produce redundant results. For that, the relational model is too restrictive. I would just live with it: the database is responsible to optimize these cases.

If you really encounter performance problems (mainly because of a network bottleneck) you could write a stored procedure, that makes the query and denormalizes it. In your example you create create a result like:

| DocumentID | Owner     | Items                                   | Quantity    |
| 1          | Naruto    | Marbles, Cards                          | 20, 56      |
| 2          | Goku      | Yo-yo, Chess board, GI Joe, Rubber Duck | 1, 3, 12, 1 |

But this of course does not conform to the first normal form - so you will need to parse it on the client.
If you use a database with XML support (like Oracle or MS SQL Server) you could even create an XML file on the server and send this to the client.

But whatever you do, remember: premature optimization is the root of all evil. Don't do this kind of stuff before you are not 100% sure, that you are really facing a problem you can solve like this.


问:
Futter: Cannot find 'kGADAdSizeBanner' in scope
Error on iOS:

```<code>Cannot find 'kGADAdSizeBanner' in scope
</code>```

Line:

```<code>private var adSize: GADAdSize = kGADAdSizeBanner
</code>```

Package:

```<code>native_admob_flutter
</code>```

Extra info:

```<code>Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.10.0, on macOS 11.6.2 20G314 darwin-x64, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] VS Code (version 1.62.0)
[✓] Connected device (2 available)
[✓] HTTP Host Availability

• No issues found!
</code>```

Android works.
Official Flutter package for ads (google_mobile_ads) is totally dead so changing to that one is not an option anymore.

答:
Not sure if this will help but I faced this same issue. So I looked at the Banner-Ad size section from their documentation, and just made a custom GADAdsize var.

For example if you wanted a Large Banner(kGADAdSizeLargeBanner), then the documentation shows that the size in points (Width x Height) is 320x100.

Size for whatever reason we can't access the variable kGADAdSizeLargeBanner (or kGADAdSizeBanner in your case) we can just create our own.

```<code>let adSize = GADAdSizeFromCGSize(CGSize(width: 320, height: 100))
</code>```

Then using this adSize variable we can initialize a banner view.

```<code>let bannerView: GADBannerView = GADBannerView(adSize: adSize)
</code>```

More detailed info about GADAdSizeFromCGSize can be found at this link.

Body:
Error on iOS:

Cannot find 'kGADAdSizeBanner' in scope

Line:

private var adSize: GADAdSize = kGADAdSizeBanner

Package:

native_admob_flutter

Extra info:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.10.0, on macOS 11.6.2 20G314 darwin-x64, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] VS Code (version 1.62.0)
[✓] Connected device (2 available)
[✓] HTTP Host Availability

• No issues found!

Android works.
Official Flutter package for ads (google_mobile_ads) is totally dead so changing to that one is not an option anymore.

Body:
Not sure if this will help but I faced this same issue. So I looked at the Banner-Ad size section from their documentation, and just made a custom GADAdsize var.

For example if you wanted a Large Banner(kGADAdSizeLargeBanner), then the documentation shows that the size in points (Width x Height) is 320x100.

Size for whatever reason we can't access the variable kGADAdSizeLargeBanner (or kGADAdSizeBanner in your case) we can just create our own.

let adSize = GADAdSizeFromCGSize(CGSize(width: 320, height: 100))

Then using this adSize variable we can initialize a banner view.

let bannerView: GADBannerView = GADBannerView(adSize: adSize)

More detailed info about GADAdSizeFromCGSize can be found at this link.


问:
Build deep learning model for non-image data
Can you please tell me how to build an autoencoder using CNN and pooling layers, with a single matrix(4,4) with integer numbers?
e.g,
input data = array([[ 4,  3,  8,  6], [ 1,  1,  2,  2], [24, 18, 32, 24], [ 6,  6,  8,  8]])

autoencoder(data)

output data= array([[ 4,  3,  8,  6], [ 1,  1,  2,  2], [24, 18, 32, 24], [ 6,  6,  8,  8]])

Explanation:
https://medium.com/machine-learning-researcher/auto-encoder-d942a29c9807

答:
The article you quoted is already well detailed, all you need to do is replaced linear units by convolution and max pool in the encoding part and deconvolution and upsampling in the decoding part.

Here is in example using Keras of a convolutional autoencoder.

But if you're new to Deep Learning I would not advise you to start here. Autoencoder are tricky, the expected output you described above could easily be obtained by setting:

```<code>def autoencoder(x):
    return x
</code>```

Which is not something you want.

People commonly design "undercomplete" autoencoders, with internal layer of smaller dimension to induce some compression. But "overcomplete" autoencoders with larger internal dimension are also valid architecture combined with regularization.

Body:
The article you quoted is already well detailed, all you need to do is replaced linear units by convolution and max pool in the encoding part and deconvolution and upsampling in the decoding part.

Here is in example using Keras of a convolutional autoencoder.

But if you're new to Deep Learning I would not advise you to start here. Autoencoder are tricky, the expected output you described above could easily be obtained by setting:

def autoencoder(x):
    return x

Which is not something you want.

People commonly design "undercomplete" autoencoders, with internal layer of smaller dimension to induce some compression. But "overcomplete" autoencoders with larger internal dimension are also valid architecture combined with regularization.


问:
Theorem euclid_gcd , proving that forall a b z, euclid a b z -> gcd a b z. using coq
i am trying to prove euclid_gcd Theorem but i get stack in the first case !! some help please  :)</p>
```<code>Inductive euclid : nat -> nat -> nat -> Prop :=
| stop : forall z, euclid z z z
| step_a : forall a b z, a > b -> euclid (a - b) b z -> euclid a b z
| step_b : forall a b z, a < b -> euclid a (b - a) z -> euclid a b z.

Inductive gcd : nat -> nat -> nat -> Prop :=
| base : forall z, gcd z z z
| step_a' : forall a b z, gcd a b z -> gcd (a + b) b z
| step_b' : forall a b z, gcd a b z -> gcd a (a + b) z.

Theorem euclid_gcd : forall a b z, euclid a b z -> gcd a b z.
Proof.
intros a b z H.
induction a.
....`
</code>```

答:
I suggest you write euclid as a function and gcd as a bunch of properties about that function.

As you may expect these basic concepts are already part of many Coq libraries. Here how "step_a'" looks like in Mathematical Components:
https://math-comp.github.io/htmldoc/mathcomp.ssreflect.div.html#gcdnDl

The key property of gcd (the function computing Euclidian division) is a showcase proof in this book, page 110:
https://zenodo.org/record/4457887#.YgKCdvso8RA

Body:
i am trying to prove euclid_gcd Theorem but i get stack in the first case !! some help please  :)

Inductive euclid : nat -> nat -> nat -> Prop :=
| stop : forall z, euclid z z z
| step_a : forall a b z, a > b -> euclid (a - b) b z -> euclid a b z
| step_b : forall a b z, a  euclid a (b - a) z -> euclid a b z.

Inductive gcd : nat -> nat -> nat -> Prop :=
| base : forall z, gcd z z z
| step_a' : forall a b z, gcd a b z -> gcd (a + b) b z
| step_b' : forall a b z, gcd a b z -> gcd a (a + b) z.

Theorem euclid_gcd : forall a b z, euclid a b z -> gcd a b z.
Proof.
intros a b z H.
induction a.
....`


问:
Android Studio: "The emulator process for AVD Pixel_2_API_30 has terminated." on MacBook Pro M1 (Apple Silicon)
I have a problem to start an Android Emulator on my MacBook Pro M1 (Apple Silicon). When I try to start an emulator (API 30, CPU/ABI arm64), I get this error: "The emulator process for AVD Pixel_2_API_30 has terminiated."

I'm using 2020.3.1 Beta 5 of Android Studio.

Does anyone know how to solve this problem?

答:
I think this will helps. uninstall "Intel x86 Emulator Accelerator (HAXM installer)" and reinstall it.

Tools ->  SDK Manager -> SDK Tools

credit https://www.youtube.com/watch?v=PFNDx2wdO4A&t=77s


问:
UISearchBar background while searching

How do you change the background when using the UISearchBar.

When I start the search the background behind by UITableView changes to white.
 How do I change that?

Thanks

答:
i have one great example of UITableview with Search bar and its operation.

I think this blog should help you..

http://www.xcode-tutorials.com/uitableview-%E2%80%93-4-searching-table-view/

in this example they used tableview with search bar and with layer view when you touch on searchbar
enjoy it...

Title: UISearchBar background while searching


问:
Text inside bars dynamic and responsive
I want to achieve something like this:

Im trying to have the bars dynamic in addition to the length of the text and it should be fully responsive. Im interested in your approaches.

答:
I think something like this would do the trick.

The background for inline-elements (such as span) renders exactly the way you need it.
You just should add some padding for the span itself and set a bigger line-height for spacing the lines.

.wrapper {
  line-height: 2;
  font-family: sans-serif;
}

span {
  padding-block: 6px;
  background: lightgray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="wrapper">
  <span>Hello World<br>This is my task For you<br>guys, hope you enjoy it</span>
</p></code>```

Title: Text inside bars dynamic and responsive

Body:
I think something like this would do the trick.

The background for inline-elements (such as span) renders exactly the way you need it.
You just should add some padding for the span itself and set a bigger line-height for spacing the lines.

.wrapper {
  line-height: 2;
  font-family: sans-serif;
}

span {
  padding-block: 6px;
  background: lightgray;
}

<p class="wrapper">
  <span>Hello World<br>This is my task For you<br>guys, hope you enjoy it</span>
</p>


问:
VBA Find if an array (made up of range) contains a specific value
I'm trying to write a code which takes a specific predefined, hardcoded value and a range made up of values from 3rd to last column with value (just one row) and sees if my array contains that specific item. The code I have:

```<code>Dim LastColumn As Long
LastColumn = Cells(Cells.Find("Parameters", lookat:=xlWhole).Row, Columns.Count).End(xlToLeft).Column

Dim Environment
Environment = ThisWorkbook.Worksheets("Specification").Range(Cells(Cells.Find("Environment").Row, 3), Cells(Cells.Find("Environment").Row, LastColumn)).Value

If ItemIsInArray(Environment , "SKIN") Then
'do stuff
End if
</code>```

And the function

```<code>Function ItemIsInArray(arr As Variant, arrX As Variant) As Boolean

'Declare variables
Dim i As Long, j As Long, boolFound As Boolean, mtch

'Main function
If Not IsArray(arrX) Then
    For j = LBound(arr) To UBound(arr)
        If CStr(arr(j)) = CStr(arrX) Then ItemIsInArray = True: Exit For
    Next j
    Exit Function
End If

For i = LBound(arrX) To UBound(arrX, 2)
    For j = LBound(arr) To UBound(arr)
        If CStr(arr(j)) = CStr(arrX(1, i)) Then
            boolFound = True: Exit For
        End If
    Next j

If boolFound Then ItemIsInArray = True: Exit Function
    boolFound = False
Next i

ItemIsInArray = False

End Function
</code>```

Problem is that it returns "subscript out of range" on
"CStr(arr(j))" in "If CStr(arr(j)) = CStr(arrX) Then ItemIsInArray = True: Exit For".

I guess the problem is the way how I convert the range to an array, but I can't seem to figure it out. Could someone help me solve this?

答:
Your array is 2-dimensional and you're only passing a single dimension in your indexer: arr(j).

You need to loop over both dimensions and use the LBound(array, dimension) and UBound(array, dimension) overloads.

Something like the following:

```<code>For i = LBound(arr, 1) To UBound(arr, 1)
    For j = LBound(arr, 2) To UBound(arr, 2)
        If CStr(arr(i, j)) = CStr(arrX) Then ItemIsInArray = True: Exit For
    Next j
Next i
</code>```

Body:
I'm trying to write a code which takes a specific predefined, hardcoded value and a range made up of values from 3rd to last column with value (just one row) and sees if my array contains that specific item. The code I have:

Dim LastColumn As Long
LastColumn = Cells(Cells.Find("Parameters", lookat:=xlWhole).Row, Columns.Count).End(xlToLeft).Column

Dim Environment
Environment = ThisWorkbook.Worksheets("Specification").Range(Cells(Cells.Find("Environment").Row, 3), Cells(Cells.Find("Environment").Row, LastColumn)).Value

If ItemIsInArray(Environment , "SKIN") Then
'do stuff
End if

And the function

Function ItemIsInArray(arr As Variant, arrX As Variant) As Boolean

'Declare variables
Dim i As Long, j As Long, boolFound As Boolean, mtch

'Main function
If Not IsArray(arrX) Then
    For j = LBound(arr) To UBound(arr)
        If CStr(arr(j)) = CStr(arrX) Then ItemIsInArray = True: Exit For
    Next j
    Exit Function
End If

For i = LBound(arrX) To UBound(arrX, 2)
    For j = LBound(arr) To UBound(arr)
        If CStr(arr(j)) = CStr(arrX(1, i)) Then
            boolFound = True: Exit For
        End If
    Next j

If boolFound Then ItemIsInArray = True: Exit Function
    boolFound = False
Next i

ItemIsInArray = False

End Function

Problem is that it returns "subscript out of range" on
"CStr(arr(j))" in "If CStr(arr(j)) = CStr(arrX) Then ItemIsInArray = True: Exit For".

I guess the problem is the way how I convert the range to an array, but I can't seem to figure it out. Could someone help me solve this?

Body:
Your array is 2-dimensional and you're only passing a single dimension in your indexer: arr(j).

You need to loop over both dimensions and use the LBound(array, dimension) and UBound(array, dimension) overloads.

Something like the following:

For i = LBound(arr, 1) To UBound(arr, 1)
    For j = LBound(arr, 2) To UBound(arr, 2)
        If CStr(arr(i, j)) = CStr(arrX) Then ItemIsInArray = True: Exit For
    Next j
Next i


问:
Is there any tool to create dependency graphs for GitHub private repositories mainly written in Python -only showing the private dependencies?
I'm working in a company that has a couple of private repositories - all of them mainly written in Python.

Each repo has at its root a requirements.txt file.

We are interested in listing the dependencies and dependents for each repository, not the public ones but just our private dependencies and dependents.

Assume for example the requirements.txt file for our_private_package1 looks like this:

```<code>public_package1
public_package2
public_package3
our_private_package2
our_private_package3
</code>```

Also assume there is another package our_private_package4 which has the following requirements.txt file:

```<code>public_package2
public_package4
our_private_package1
</code>```

So we would like to build a dependency graph in which we could see the following for our_private_package1:

Dependencies:

our_private_package2

our_private_package3

Dependents:

our_private_package4

Ideally, we would like to visualize the dependencies with a graph.

2 notes:

GitHub's solution is not suitable here for 2 reasons. First, it
only shows public dependencies. Also it does not determine the
dependents of private repositories (whether the dependents are public
or private).

Dependencies should no be transitive. With the example above, our_private_package2 should not be listed as dependent for our_private_package4 (although we
should see in a visual representation a path from
our_private_package2 to our_private_package4, with a directed branch from our_private_package2 to our_private_package1 and
another branch from our_private_package1 to our_private_package4).

If there is no available tool for such kind of problem, I would like at least some guidance how to do it with some Python code (almost sure it's feasible).

答:
As previously mentionned in the comments, I had a similar need. I solved it using a similar approach than this one :

```<code>from collections import defaultdict
from typing import List, Tuple, Dict

def main():
    requirements_file_content_per_package = {
        "our_private_package1": """\
public_package1
public_package2
public_package3
our_private_package2
our_private_package3
        """,

        "our_private_package2": """\
public_package2
public_package4
our_private_package1
        """
    }

    private_packages_names = ["our_private_package1",
                              "our_private_package2",
                              "our_private_package3",
                              "our_private_package4"]

    # process descending dependency
    private_packages_dependencies: Dict[str, Tuple[List[str], List[str]]] = {}
    for private_package_name in private_packages_names:
        requirements_file_content = requirements_file_content_per_package.get(private_package_name, "")
        private_packages_dependencies[private_package_name] = classify_dependencies(requirements_file_content, private_packages_names)

    # display
    for private_package_name, (package_private_dependencies_names, _) in private_packages_dependencies.items():
        print(f"package {private_package_name!r} depends on private {package_private_dependencies_names!r}")

    # process ascending dependencies
    private_packages_dependents: Dict[str, List[str]] = defaultdict(list)
    for private_package_name, (package_private_dependencies_names, _) in private_packages_dependencies.items():
        for package_private_dependency_name in package_private_dependencies_names:
            private_packages_dependents[package_private_dependency_name].append(private_package_name)

    # display
    for private_package_name, package_private_dependents_names in private_packages_dependents.items():
        print(f"package {private_package_name!r} is depended on by private {package_private_dependents_names!r}")

def classify_dependencies(requirements_file_content: str, private_packages_names: List[str]) -> Tuple[List[str], List[str]]:
    private_dependencies: List[str] = []
    public_dependencies: List[str] = []
    for dependency_name in requirements_file_content.splitlines():
        is_private = dependency_name in private_packages_names
        if is_private:
            private_dependencies.append(dependency_name)
        else:
            public_dependencies.append(dependency_name)
    return private_dependencies, public_dependencies

main()
</code>```

It's a bit crude, and I am using very basic Python (strings, lists and sets) but it could be possible to use a directed colored graph instead. Also, the names get very long because I wanted to be descriptive, but I think using a concise defined vocabulary would be better.

As for visualization :

    import graphviz  # installed with pip

    dot = graphviz.Digraph()
    # at first, create all the nodes
    for private_package_name in private_packages_names:
        dot.node(private_package_name)
    # then create the edges
    for private_package_name, package_private_dependents_names in private_packages_dependents.items():
        for package_private_dependent_name in package_private_dependents_names:
            dot.edge(package_private_dependent_name, private_package_name)
    dot.render("deps.gv", format="png")
```

produced deps.gv.png :

Body:
I'm working in a company that has a couple of private repositories - all of them mainly written in Python.

Each repo has at its root a requirements.txt file.

We are interested in listing the dependencies and dependents for each repository, not the public ones but just our private dependencies and dependents.

Assume for example the requirements.txt file for our_private_package1 looks like this:

public_package1
public_package2
public_package3
our_private_package2
our_private_package3

Also assume there is another package our_private_package4 which has the following requirements.txt file:

public_package2
public_package4
our_private_package1

So we would like to build a dependency graph in which we could see the following for our_private_package1:

Dependencies:

our_private_package2

our_private_package3

Dependents:

our_private_package4

Ideally, we would like to visualize the dependencies with a graph.

2 notes:

GitHub's solution is not suitable here for 2 reasons. First, it
only shows public dependencies. Also it does not determine the
dependents of private repositories (whether the dependents are public
or private).

Dependencies should no be transitive. With the example above, our_private_package2 should not be listed as dependent for our_private_package4 (although we
should see in a visual representation a path from
our_private_package2 to our_private_package4, with a directed branch from our_private_package2 to our_private_package1 and
another branch from our_private_package1 to our_private_package4).

If there is no available tool for such kind of problem, I would like at least some guidance how to do it with some Python code (almost sure it's feasible).

Body:
As previously mentionned in the comments, I had a similar need. I solved it using a similar approach than this one :

from collections import defaultdict
from typing import List, Tuple, Dict

def main():
    requirements_file_content_per_package = {
        "our_private_package1": """\
public_package1
public_package2
public_package3
our_private_package2
our_private_package3
        """,

        "our_private_package2": """\
public_package2
public_package4
our_private_package1
        """
    }

    private_packages_names = ["our_private_package1",
                              "our_private_package2",
                              "our_private_package3",
                              "our_private_package4"]

    # process descending dependency
    private_packages_dependencies: Dict[str, Tuple[List[str], List[str]]] = {}
    for private_package_name in private_packages_names:
        requirements_file_content = requirements_file_content_per_package.get(private_package_name, "")
        private_packages_dependencies[private_package_name] = classify_dependencies(requirements_file_content, private_packages_names)

    # display
    for private_package_name, (package_private_dependencies_names, _) in private_packages_dependencies.items():
        print(f"package {private_package_name!r} depends on private {package_private_dependencies_names!r}")

    # process ascending dependencies
    private_packages_dependents: Dict[str, List[str]] = defaultdict(list)
    for private_package_name, (package_private_dependencies_names, _) in private_packages_dependencies.items():
        for package_private_dependency_name in package_private_dependencies_names:
            private_packages_dependents[package_private_dependency_name].append(private_package_name)

    # display
    for private_package_name, package_private_dependents_names in private_packages_dependents.items():
        print(f"package {private_package_name!r} is depended on by private {package_private_dependents_names!r}")

def classify_dependencies(requirements_file_content: str, private_packages_names: List[str]) -> Tuple[List[str], List[str]]:
    private_dependencies: List[str] = []
    public_dependencies: List[str] = []
    for dependency_name in requirements_file_content.splitlines():
        is_private = dependency_name in private_packages_names
        if is_private:
            private_dependencies.append(dependency_name)
        else:
            public_dependencies.append(dependency_name)
    return private_dependencies, public_dependencies

main()

It's a bit crude, and I am using very basic Python (strings, lists and sets) but it could be possible to use a directed colored graph instead. Also, the names get very long because I wanted to be descriptive, but I think using a concise defined vocabulary would be better.

As for visualization :

    import graphviz  # installed with pip

    dot = graphviz.Digraph()
    # at first, create all the nodes
    for private_package_name in private_packages_names:
        dot.node(private_package_name)
    # then create the edges
    for private_package_name, package_private_dependents_names in private_packages_dependents.items():
        for package_private_dependent_name in package_private_dependents_names:
            dot.edge(package_private_dependent_name, private_package_name)
    dot.render("deps.gv", format="png")

produced deps.gv.png :


问:
Profile Entire Java Program Execution in VisualVM
In Java profiling, it seems like all (free) roads nowadays lead to the VisualVM profiler included with JDK6.   It looks like a fine program, and everyone touts how you can "attach it to a running process" as a major feature.  The problem is, that seems to be the only way to use it on a local process.  I want to be able to start my program in the profiler, and track its entire execution.

I have tried using the -Xrunjdwp option described in how to profile application startup with visualvm, but between the two transport methods (shared memory and server), neither is useful for me.  VisualVM doesn't seem to have any integration with the former, and VisualVM refuses to connect to localhost or 127.0.0.1, so the latter is no good either.  I also tried inserting a simple read of System.in into my program to insert a pause in execution, but in that case VisualVM blocks until the read completes, and doesn't allow you to start profiling until after execution is under way.  <s>I have also tried looking into the Eclipse plugin but the website is full of dead links and the launcher just crashes with a NullPointerException when I try to use it</s> (this may no longer be accurate).

Coming from C, this doesn't seem like a particularly difficult task to me.  Am I just missing something or is this really an impossible request?  I'm open to any kinds of suggestions, including using a different (also free) profiler, and I'm not averse to the command line.

答: The advice with -Xrunjdwp is incorrect. It just enables debugger and with suspend=y it waits for debugger to attach. Since VisualVM is not debugger, it does not help you. However inserting System.in or Thread.sleep() will pause the startup and allows VisualVM to attach to your application. Be sure to read Profiling with VisualVM 1 and Profiling with VisualVM 2 to better understand profiler settings. Note also that instead of profiling, you can use 'Sampler' tab in VisualVM, which is more suitable for profiling entire java program execution. As other mentioned you can also use NetBeans Profiler, which directly support profiling of the application startup.


问:
Zip multiple arrays in PHP based on their identical keys and not their indices or their positions in array
I have two arrays:

```<code>$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5, 'six' => 6];
$b = ['one'=>'uno', 'three'=>'tres','two'=> 'dos', 'four'=>'cuatro', 'five'=>'cinco'];
</code>```

note that in $b Array 'three' and 'two' keys are not in same order as $a. also 'six' key is not available in $b Array.

I want this result as output:

```<code>Array
(
    [0] => Array
        (
            [0] => 1
            [1] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => cinco
        )

)
</code>```

I tried to use array_map but it don't detect keys and just zip them based of their indices:

```<code>$d = array_map(null, $a, $b);
</code>```

答: Can't you just use ksort(). Then, create a new array using `foreach'?</p>

Body:
I have two arrays:

$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5, 'six' => 6];
$b = ['one'=>'uno', 'three'=>'tres','two'=> 'dos', 'four'=>'cuatro', 'five'=>'cinco'];

note that in $b Array 'three' and 'two' keys are not in same order as $a. also 'six' key is not available in $b Array.

I want this result as output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => cinco
        )

)

I tried to use array_map but it don't detect keys and just zip them based of their indices:

$d = array_map(null, $a, $b);


问:
Convert regular lat/lon grid to polygons using R sf
I'm trying to convert a regular 1-degree by 1-degree geographic grid to polygons while maintaining the data associated with each grid point using the R sf package.

Example code:

```<code>library(tidyverse)
library(sf)
library(sfheaders)
library(sfheaders)

# latitude
lldata <- tibble(lat=as.numeric(rep(seq(40,49.5),10)))

# Longitude + add data
lldata <- lldata %>%
          group_by(lat) %>%
          mutate(lon = -90 + row_number()-1,
                 data = runif(1))

#Plot the grid as points
lldata %>%
  ggplot() +
  geom_point(aes(x=lon,y=lat,color=data))
</code>```

This yields:

```<code># Attempt #1
#https://stackoverflow.com/questions/48383990/convert-sequence-of-longitude-and-latitude-to-polygon-via-sf-in-r

lldata %>% arrange(lat,-lon)  %>%
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  summarise(geometry = st_combine(geometry)) %>%
  st_cast("POLYGON") %>%
  ggplot() +
  geom_sf()
</code>```

Which yields

```<code># Also tried
poly <- st_sf(st_sfc(st_make_valid(st_polygon(list(as.matrix(lldata))))), crs = 4326)
# error that the polygon is not closed

# Attempt #2
# https://stackoverflow.com/questions/52669779/convert-sets-of-spatial-coordinates-to-polygons-in-r-using-sf/52671103

sf <- sfheaders::sf_polygon(
  obj = lldata
  , x = "lon"
  , y = "lat"
)

# Same result as above
sf %>%
  ggplot() +
  geom_sf()
</code>```

I'm expecting a polygon whose boundaries are defined by the regular grid but the boundaries of each polygon are not being closed.   Is there a simple solution in the SF package I'm missing?

Also, when creating the polygon, I'd like for the variable "data" to be associated with each polygon.  I have not made it that far, however.

答:
Using sf::st_make_grid :

```<code>library(tidyverse)
library(sf)

lldata <- tibble(lat = as.numeric(rep(seq(40, 49.5), 10))) %>%
  group_by(lat) %>%
  mutate(lon = -90 + row_number() - 1,
         data = runif(1)) %>%
  ungroup() %>%
  st_as_sf(coords = c("lon", "lat"))

lldata_poly <- lldata %>%
  st_make_grid(cellsize = 1, offset = c(-90.5, 39.5)) %>%
  st_as_sf() %>%
  st_join(lldata)

# plot
ggplot() +
  geom_sf(data = lldata_poly, aes(fill = data)) +
  geom_sf(data = lldata)

# export
write_sf(lldata_poly, "~/grid.shp")
</code>```

You can adjust the offset depending of what you want (centers or corners)

Body:
I'm trying to convert a regular 1-degree by 1-degree geographic grid to polygons while maintaining the data associated with each grid point using the R sf package.

Example code:

library(tidyverse)
library(sf)
library(sfheaders)
library(sfheaders)

# latitude
lldata <- tibble(lat=as.numeric(rep(seq(40,49.5),10)))

# Longitude + add data
lldata <- lldata %>%
          group_by(lat) %>%
          mutate(lon = -90 + row_number()-1,
                 data = runif(1))

#Plot the grid as points
lldata %>%
  ggplot() +
  geom_point(aes(x=lon,y=lat,color=data))

This yields:

# Attempt #1
#https://stackoverflow.com/questions/48383990/convert-sequence-of-longitude-and-latitude-to-polygon-via-sf-in-r

lldata %>% arrange(lat,-lon)  %>%
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  summarise(geometry = st_combine(geometry)) %>%
  st_cast("POLYGON") %>%
  ggplot() +
  geom_sf()

Which yields

# Also tried
poly <- st_sf(st_sfc(st_make_valid(st_polygon(list(as.matrix(lldata))))), crs = 4326)
# error that the polygon is not closed

# Attempt #2
# https://stackoverflow.com/questions/52669779/convert-sets-of-spatial-coordinates-to-polygons-in-r-using-sf/52671103

sf <- sfheaders::sf_polygon(
  obj = lldata
  , x = "lon"
  , y = "lat"
)

# Same result as above
sf %>%
  ggplot() +
  geom_sf()

I'm expecting a polygon whose boundaries are defined by the regular grid but the boundaries of each polygon are not being closed.   Is there a simple solution in the SF package I'm missing?

Also, when creating the polygon, I'd like for the variable "data" to be associated with each polygon.  I have not made it that far, however.

Body:
Using sf::st_make_grid :

library(tidyverse)
library(sf)

lldata <- tibble(lat = as.numeric(rep(seq(40, 49.5), 10))) %>%
  group_by(lat) %>%
  mutate(lon = -90 + row_number() - 1,
         data = runif(1)) %>%
  ungroup() %>%
  st_as_sf(coords = c("lon", "lat"))

lldata_poly <- lldata %>%
  st_make_grid(cellsize = 1, offset = c(-90.5, 39.5)) %>%
  st_as_sf() %>%
  st_join(lldata)

# plot
ggplot() +
  geom_sf(data = lldata_poly, aes(fill = data)) +
  geom_sf(data = lldata)

# export
write_sf(lldata_poly, "~/grid.shp")

You can adjust the offset depending of what you want (centers or corners)


答:
This should do it:</p>
```<code>OUTPUT = data.frame(
  YEAR = INPUT$year,
  MAX = apply(INPUT[-1], 1, max)
)
</code>```

Title: how to get max from multiple columns in R

Body:
INPUT:-
 year max1 max2 max3
2001   10  101   87
2002  103   19   88
2003   21   23   89
2004   27   28   91

OUTPUT:-

YEAR    MAX

2001     101

2002     103

2003      89

2004      91

Body:
This should do it:

OUTPUT = data.frame(
  YEAR = INPUT$year,
  MAX = apply(INPUT[-1], 1, max)
)


问:
Running a stored procedure using a resultset as the parameter and insert into a table
I have the question below,

I do have a query which returns 10 rows for example.

```<code>SELECT CarId FROM Car

EXEC spQ_GetCar (@CarId)
</code>```

Also, I have a stored procedure that uses an id from the table above.

My question is, how can I run the stored procedure and use the output of the table as the parameter and then insert that into another temp table.

Would it be possible by using a cursor and dynamic SQL ?, has anyone faced this before ?

NOTES: I cannot create a table type to use it

答:
I achieved this by following approach below:

```<code>CREATE TABLE #TEMP (CarId INT)

DECLARE @CarId INT

DECLARE Car CURSOR
    ,CarId INT SET Car = CURSOR STATIC
FOR
SELECT CarId
FROM Car

OPEN Car

WHILE 1 = 1
BEGIN
    FETCH Car
    INTO @CarId

    IF @@FETCH_STATUS <> 0
        BREAK

    INSERT INTO #TEMP
    EXEC spQ_GetCar(@CarId)
END

CLOSE @ServiceAgreements

DEALLOCATE @ServiceAgreements

DROP TABLE #TEMP
</code>```

Notes: Performance was not relevant as it was a one off script.

Body:
I have the question below,

I do have a query which returns 10 rows for example.

SELECT CarId FROM Car

EXEC spQ_GetCar (@CarId)

Also, I have a stored procedure that uses an id from the table above.

My question is, how can I run the stored procedure and use the output of the table as the parameter and then insert that into another temp table.

Would it be possible by using a cursor and dynamic SQL ?, has anyone faced this before ?

NOTES: I cannot create a table type to use it

Body:
I achieved this by following approach below:

CREATE TABLE #TEMP (CarId INT)

DECLARE @CarId INT

DECLARE Car CURSOR
    ,CarId INT SET Car = CURSOR STATIC
FOR
SELECT CarId
FROM Car

OPEN Car

WHILE 1 = 1
BEGIN
    FETCH Car
    INTO @CarId

    IF @@FETCH_STATUS <> 0
        BREAK

    INSERT INTO #TEMP
    EXEC spQ_GetCar(@CarId)
END

CLOSE @ServiceAgreements

DEALLOCATE @ServiceAgreements

DROP TABLE #TEMP

Notes: Performance was not relevant as it was a one off script.