问:
How to download image from server and display with fade in fade out animation in swift?
I want to download 10 images from server using alamofire and animate that image in uicollectionview's imageview..in infinite loop just like photos app on window 10..does anyone know??I have googled out but didn't find suitable answer..Some says to use timer..but I think that's not feasible way.. `

```<code>if let employeeImage = employeeModelForDisplay?.employeeImageArray {
     self.animateImage(at: 0 , imageArray: employeeImage)
  }
 func animateImage(at index: Int, imageArray:[String]) {
        if index < imageArray.count {
            self.badgeImageView.alpha = 0.3
             self.badgeImageView.setImage(link: imageArray[index], imageType: .UserImage)
            UIView.animate(withDuration: 3.0, delay: 0.5, options: [.transitionCrossDissolve], animations: {
                self.badgeImageView.alpha = 1.0
            }) { (completed) in
                self.animateImage(at: index + 1, imageArray: imageArray)
            }
        } else {
               //self.animateImage(at: 0, imageArray: imageArray)
        }
    }
</code>```

`

I have coded above code in uicollectionviewcell.

答:
Approach -1:

Set animationImages on imageView, i.e.

```<code>let imagesArray = [UIImage(named: "image"), UIImage(named: "image1"), UIImage(named: "image2")]
imageView.animationImages = imagesArray.compactMap({$0})
imageView.animationDuration = 2.0
imageView.startAnimating()
</code>```

Approach-2:

You can create your own animation something like,

```<code>let imagesArray = [UIImage(named: "image"), UIImage(named: "image1"), UIImage(named: "image2")]
</code>```

Method to manage images animation,

```<code>func animateImage(at index: Int) {
    if index < imagesArray.count {
        self.imageView.image = self.imagesArray[index]
        self.imageView.alpha = 0
        UIView.animate(withDuration: 2.0, delay: 0.0, options: [.curveEaseInOut], animations: {
            self.imageView.alpha = 1.0
        }) { (completed) in
            self.animateImage(at: index + 1)
        }
    } else {
        self.animateImage(at: 0)
    }
}
</code>```

Initiate the method with index 0, i.e

```<code>self.animateImage(at: 0)
</code>```

Edit-1:

To get the images from server before animating them into the imageView,

```<code>func downloadImages() {
    let imageUrls = [String]()
    var imagesArray = [UIImage]()

    let dispatchGroup = DispatchGroup()
    dispatchGroup.notify(queue: DispatchQueue.main) {[weak self] in
        self?.imageView.animationImages = imagesArray.compactMap({$0})
        self?.imageView.animationDuration = 2.0
        self?.imageView.startAnimating()
    }

    imageUrls.forEach { (imageUrl) in
        if let url = URL(string: imageUrl) {
            dispatchGroup.enter()
            URLSession.shared.dataTask(with: url, completionHandler: { (data, urlResponse, error) in
                if let data = data, let image = UIImage(data: data) {
                    imagesArray.append(image)
                    dispatchGroup.leave()
                }
            }).resume()
        }
    }
}
</code>```

Body:
I want to download 10 images from server using alamofire and animate that image in uicollectionview's imageview..in infinite loop just like photos app on window 10..does anyone know??I have googled out but didn't find suitable answer..Some says to use timer..but I think that's not feasible way.. `

if let employeeImage = employeeModelForDisplay?.employeeImageArray {
     self.animateImage(at: 0 , imageArray: employeeImage)
  }
 func animateImage(at index: Int, imageArray:[String]) {
        if index < imageArray.count {
            self.badgeImageView.alpha = 0.3
             self.badgeImageView.setImage(link: imageArray[index], imageType: .UserImage)
            UIView.animate(withDuration: 3.0, delay: 0.5, options: [.transitionCrossDissolve], animations: {
                self.badgeImageView.alpha = 1.0
            }) { (completed) in
                self.animateImage(at: index + 1, imageArray: imageArray)
            }
        } else {
               //self.animateImage(at: 0, imageArray: imageArray)
        }
    }

`

I have coded above code in uicollectionviewcell.

Body:
Approach -1:

Set animationImages on imageView, i.e.

let imagesArray = [UIImage(named: "image"), UIImage(named: "image1"), UIImage(named: "image2")]
imageView.animationImages = imagesArray.compactMap({$0})
imageView.animationDuration = 2.0
imageView.startAnimating()

Approach-2:

You can create your own animation something like,

let imagesArray = [UIImage(named: "image"), UIImage(named: "image1"), UIImage(named: "image2")]

Method to manage images animation,

func animateImage(at index: Int) {
    if index < imagesArray.count {
        self.imageView.image = self.imagesArray[index]
        self.imageView.alpha = 0
        UIView.animate(withDuration: 2.0, delay: 0.0, options: [.curveEaseInOut], animations: {
            self.imageView.alpha = 1.0
        }) { (completed) in
            self.animateImage(at: index + 1)
        }
    } else {
        self.animateImage(at: 0)
    }
}

Initiate the method with index 0, i.e

self.animateImage(at: 0)

Edit-1:

To get the images from server before animating them into the imageView,

func downloadImages() {
    let imageUrls = [String]()
    var imagesArray = [UIImage]()

    let dispatchGroup = DispatchGroup()
    dispatchGroup.notify(queue: DispatchQueue.main) {[weak self] in
        self?.imageView.animationImages = imagesArray.compactMap({$0})
        self?.imageView.animationDuration = 2.0
        self?.imageView.startAnimating()
    }

    imageUrls.forEach { (imageUrl) in
        if let url = URL(string: imageUrl) {
            dispatchGroup.enter()
            URLSession.shared.dataTask(with: url, completionHandler: { (data, urlResponse, error) in
                if let data = data, let image = UIImage(data: data) {
                    imagesArray.append(image)
                    dispatchGroup.leave()
                }
            }).resume()
        }
    }
}


来源: stackexchange

问:
Selenium Webdriver script: Handling Browser sessions in Try and Finally Sessions
What happens if we close the driver/browser(via driver.quit() or driver.close()) in try block, then will the Finally block execute or not.

答: Finally block will be executed at any cost. But, if you try to do any operation on driver in finally block (as driver session is ended in try block), you will get NoSuchSesionException, which will fail your test scenario</p>

ContentLicense: CC BY-SA 4.0


问:
Position of text in a submit button
The position of the text on the search submit button on my blog is very low in Firefox 4, but not Chrome 10 or IE9. I've tried almost everything, and nothing works except lowering the font size of the text, which isn't an optimal solution as the text will be too small.

Screenshots

Firefox 4 on Windows 7:

Google Chrome 10.0.648.204 on Windows 7:

The relevant HTML:

```<code><form method="get" class="searchform" action="http://eligrey.com/blog">
    <input type="search" placeholder="search" name="s" />
    <input type="submit" value="🔍" title="Search" />
</form>
</code>```

The relevant CSS rule (from http://eligrey.com/blog/wp-content/themes/eligrey.com/style.css):

```<code>.searchform input[type="submit"] {
    font-family: "rfhb-lpmg";
    color: #ccc;
    font-size: 3em;
    background-color: #959595;
    text-align: center;
    border: 1px solid #888;
    height: 34px;
    width: 42px;
    line-height: 34px;
    -webkit-border-bottom-right-radius: 4px;
    -webkit-border-top-right-radius: 4px;
    -moz-border-radius-bottomright: 4px;
    -moz-border-radius-topright: 4px;
    border-bottom-right-radius: 4px;
    border-top-right-radius: 4px;
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding-box;
    background-clip: padding-box;
    -webkit-transition-property: border, background-color, box-shadow;
    -webkit-transition-duration: 0.2s;
    -moz-transition-property: border, background-color, box-shadow;
    -moz-transition-duration: 0.2s;
}
</code>```

rfhb-lpmg is just a custom font I made which implements U+2767 rotated floral heart bullet and U+1F50E right-pointing magnifying glass with simplistic glyphs.

答:
FF4 sets it's own styles on input elements. You can check all of them if you paste this in your URL field:

```<code>resource://gre-resources/forms.css
</code>```

Alternatively you can see this styles if you check Show user agent CSS from Style tab dropdown if you have Firebug instaled.

Check solution here: How to reset default button style in Firefox 4 +

ContentLicense: CC BY-SA 3.0

Title: Position of text in a submit button

Body:
The position of the text on the search submit button on my blog is very low in Firefox 4, but not Chrome 10 or IE9. I've tried almost everything, and nothing works except lowering the font size of the text, which isn't an optimal solution as the text will be too small.

Screenshots

Firefox 4 on Windows 7:

Google Chrome 10.0.648.204 on Windows 7:

The relevant HTML:

<form method="get" class="searchform" action="http://eligrey.com/blog">
    <input type="search" placeholder="search" name="s" />
    <input type="submit" value="🔍" title="Search" />
</form>

The relevant CSS rule (from http://eligrey.com/blog/wp-content/themes/eligrey.com/style.css):

.searchform input[type="submit"] {
    font-family: "rfhb-lpmg";
    color: #ccc;
    font-size: 3em;
    background-color: #959595;
    text-align: center;
    border: 1px solid #888;
    height: 34px;
    width: 42px;
    line-height: 34px;
    -webkit-border-bottom-right-radius: 4px;
    -webkit-border-top-right-radius: 4px;
    -moz-border-radius-bottomright: 4px;
    -moz-border-radius-topright: 4px;
    border-bottom-right-radius: 4px;
    border-top-right-radius: 4px;
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding-box;
    background-clip: padding-box;
    -webkit-transition-property: border, background-color, box-shadow;
    -webkit-transition-duration: 0.2s;
    -moz-transition-property: border, background-color, box-shadow;
    -moz-transition-duration: 0.2s;
}

rfhb-lpmg is just a custom font I made which implements U+2767 rotated floral heart bullet and U+1F50E right-pointing magnifying glass with simplistic glyphs.

Body:
FF4 sets it's own styles on input elements. You can check all of them if you paste this in your URL field:

resource://gre-resources/forms.css

Alternatively you can see this styles if you check Show user agent CSS from Style tab dropdown if you have Firebug instaled.

Check solution here: How to reset default button style in Firefox 4 +


问:
Configuring Elasticsearch 7 cluster
I have three server and I have installed elasticsearch on all of them.

In the elasticsearch.yml I have the following config:

first server: 172.31.1.1

```<code># /etc/elasticsearch/elasticsearch.yml
cluster.name: es-cluster
node.name: es-1
network.host: 172.31.1.1
http.port: 9200
network.host:
discovery.seed_hosts: ["172.31.1.1", "172.31.1.2", "172.31.1.3"]
cluster.initial_master_nodes:["es-1", "es-2", "es-3"]

gateway.recover_after_nodes: 2
gateway.expected_nodes: 3
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
# some more default values
</code>```

second server: 172.31.1.2

```<code>node.name: es-2
network.host: 172.31.1.2
# everything else same as first server
</code>```

second server: 172.31.1.3

```<code>node.name: es-3
network.host: 172.31.1.3
# everything else same as first server
</code>```

Now when I run: curl http://es-1:9200/_cluster/stats

I notice that the cluster size is 1. if I run the same curl command on a different server, again the cluster size is 1 and the cluster_name is the same, but cluster_uuid is different...

It seems that nodes are not able to connect to each other...

I am using Ubuntu server, for node name I edited /etc/hostname and changed the host name to
es-1 and used the same name in elasticsearch.yml... but it seems that cluster nodes are not able to communicate with one another...

Update 1

```<code>curl http://es-1:9200/_cat/health
prod-es-cluster red 1 1 0 0 0 0 0 0 - NaN%

curl http://es-1/:9200/_cat/nodes
172.31.1.1 8 38 1 0.03 0.03 0.00 mdi * ip-172-31-1-1
</code>```

I just check the log and it's strange...

```<code>sudo cat /var/log/elasticsearch/elasticsearch.log
[INFO ][o.e.n.Node               ] [es-1] stopping ...
[INFO ][o.e.x.w.WatcherService   ] [es-1] stopping watch service, reason [shutdown initiated]
[INFO ][o.e.x.m.p.l.CppLogMessageHandler] [es-1] [controller/19159] [Main.cc@148] Ml controller exiting
[INFO ][o.e.x.m.p.NativeController] [es-1] Native controller process has stopped - no new native processes can be started
[INFO ][o.e.n.Node               ] [es-1] stopped
[INFO ][o.e.n.Node               ] [es-1] closing ...
[INFO ][o.e.n.Node               ] [es-1] closed
</code>```

That is all written to the log file... after restarting Elasticsearch nothing new gets added to the log file... it feels like I am either reading the wrong log file or I have put the configuration in the wrong .yml file

Update 2

This is how I start the service:

```<code>sudo /bin/systemctl enable elasticsearch.service
</code>```

Update 3

As pointed out by @hamidbayat, I think there is permission issues. Only super user have permission to /var/lib/elasticsearch

If I try to run elastic search as my ubuntu user I will get this error:

```<code>ubuntu@my-ip:~$ /usr/share/elasticsearch/bin/elasticsearch
/usr/share/elasticsearch/bin/elasticsearch-env: line 73:
/etc/default/elasticsearch: Permission denied
</code>```

If I try to run it as root, I will get this error:

```<code>ubuntu@myip:~$ sudo /usr/share/elasticsearch/bin/elasticsearch
OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
[data][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [es-1] uncaught exception in thread [main]
org.elasticsearch.bootstrap.StartupException: java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:163) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:150) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:86) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:124) ~[elasticsearch-cli-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.Command.main(Command.java:90) ~[elasticsearch-cli-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:115) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:92) ~[elasticsearch-7.1.0.jar:7.1.0]
Caused by: java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:102) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:169) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:325) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:159) ~[elasticsearch-7.1.0.jar:7.1.0]
        ... 6 more
</code>```

答:
You need to configure bootstrap check, in 6.x it throws warning

For 7.x version bootstrap configuration is must

bootstrap.system_call_filter: false add this try starting

Title: Configuring Elasticsearch 7 cluster

Body:
I have three server and I have installed elasticsearch on all of them.

In the elasticsearch.yml I have the following config:

first server: 172.31.1.1

# /etc/elasticsearch/elasticsearch.yml
cluster.name: es-cluster
node.name: es-1
network.host: 172.31.1.1
http.port: 9200
network.host:
discovery.seed_hosts: ["172.31.1.1", "172.31.1.2", "172.31.1.3"]
cluster.initial_master_nodes:["es-1", "es-2", "es-3"]

gateway.recover_after_nodes: 2
gateway.expected_nodes: 3
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
# some more default values

second server: 172.31.1.2

node.name: es-2
network.host: 172.31.1.2
# everything else same as first server

second server: 172.31.1.3

node.name: es-3
network.host: 172.31.1.3
# everything else same as first server

Now when I run: curl http://es-1:9200/_cluster/stats

I notice that the cluster size is 1. if I run the same curl command on a different server, again the cluster size is 1 and the cluster_name is the same, but cluster_uuid is different...

It seems that nodes are not able to connect to each other...

I am using Ubuntu server, for node name I edited /etc/hostname and changed the host name to
es-1 and used the same name in elasticsearch.yml... but it seems that cluster nodes are not able to communicate with one another...

Update 1

curl http://es-1:9200/_cat/health
prod-es-cluster red 1 1 0 0 0 0 0 0 - NaN%

curl http://es-1/:9200/_cat/nodes
172.31.1.1 8 38 1 0.03 0.03 0.00 mdi * ip-172-31-1-1

I just check the log and it's strange...

sudo cat /var/log/elasticsearch/elasticsearch.log
[INFO ][o.e.n.Node               ] [es-1] stopping ...
[INFO ][o.e.x.w.WatcherService   ] [es-1] stopping watch service, reason [shutdown initiated]
[INFO ][o.e.x.m.p.l.CppLogMessageHandler] [es-1] [controller/19159] [Main.cc@148] Ml controller exiting
[INFO ][o.e.x.m.p.NativeController] [es-1] Native controller process has stopped - no new native processes can be started
[INFO ][o.e.n.Node               ] [es-1] stopped
[INFO ][o.e.n.Node               ] [es-1] closing ...
[INFO ][o.e.n.Node               ] [es-1] closed

That is all written to the log file... after restarting Elasticsearch nothing new gets added to the log file... it feels like I am either reading the wrong log file or I have put the configuration in the wrong .yml file

Update 2

This is how I start the service:

sudo /bin/systemctl enable elasticsearch.service

Update 3

As pointed out by @hamidbayat, I think there is permission issues. Only super user have permission to /var/lib/elasticsearch

If I try to run elastic search as my ubuntu user I will get this error:

ubuntu@my-ip:~$ /usr/share/elasticsearch/bin/elasticsearch
/usr/share/elasticsearch/bin/elasticsearch-env: line 73:
/etc/default/elasticsearch: Permission denied

If I try to run it as root, I will get this error:

ubuntu@myip:~$ sudo /usr/share/elasticsearch/bin/elasticsearch
OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
[data][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [es-1] uncaught exception in thread [main]
org.elasticsearch.bootstrap.StartupException: java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:163) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:150) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:86) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:124) ~[elasticsearch-cli-7.1.0.jar:7.1.0]
        at org.elasticsearch.cli.Command.main(Command.java:90) ~[elasticsearch-cli-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:115) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:92) ~[elasticsearch-7.1.0.jar:7.1.0]
Caused by: java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:102) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:169) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:325) ~[elasticsearch-7.1.0.jar:7.1.0]
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:159) ~[elasticsearch-7.1.0.jar:7.1.0]
        ... 6 more


问:
How to find the number of times a string occurs in a text file?
I'm trying to count the number of times a string occurs in a file of strings.

```<code>data=open('xyz.txt')
num=[]
    while 1:
        numrow=[]
        count=0
        x=data.readline()
        if x=='':
            break
        for line in data:
            if line==x:
                count+=1
        numrow.append(x)
        numrow.append(count)
        num.append(numrow)
    print(num)
</code>```

When I try the code above, I keep getting the wrong count. Also, I'm not able to get every string and the number of times it appears. Instead, I get the string in the first line with the wrong count.

Is there a way I can print all the distinct strings along with their corresponding counts?

答:
You can use collections.Counter

Ex:

```<code>from collections import Counter

result = Counter()
with open('xyz.txt') as infile:
    for line in infile:
        result += Counter(line.strip().split())
print(result)
</code>```

Body:
I'm trying to count the number of times a string occurs in a file of strings.

data=open('xyz.txt')
num=[]
    while 1:
        numrow=[]
        count=0
        x=data.readline()
        if x=='':
            break
        for line in data:
            if line==x:
                count+=1
        numrow.append(x)
        numrow.append(count)
        num.append(numrow)
    print(num)

When I try the code above, I keep getting the wrong count. Also, I'm not able to get every string and the number of times it appears. Instead, I get the string in the first line with the wrong count.

Is there a way I can print all the distinct strings along with their corresponding counts?

Body:
You can use collections.Counter

Ex:

from collections import Counter

result = Counter()
with open('xyz.txt') as infile:
    for line in infile:
        result += Counter(line.strip().split())
print(result)


问:
How yield works in Inorder traversal with recursive generator?
I am learning about recursive generators and found this program on web.

I undertand the recursive version of In-Order traversal but i am having trouble understanding recursive generator.

Specifically i am not able to understand

why 'yield x'  is written in for loop?

Why 'yield x' is not collected in final list?

I have tried to dubug the generator and added the watch but i found that recursive call execute multiple time 'yield x' and it's not collected in final result.

```<code>class Tree:
    def __init__(self, label, left=None, right=None):
        self.label = label
        self.left = left
        self.right = right

    def __repr__(self, level=0, indent="    "):
        s = level*indent + repr(self.label)
        if self.left:
            s = s + "\\n" + self.left.__repr__(level+1, indent)
        if self.right:
            s = s + "\\n" + self.right.__repr__(level+1, indent)
        return s

    def __iter__(self):
        return inorder(self)

def tree(list):
    n = len(list)
    if n == 0:
        return []
    i = n // 2
    return Tree(list[i], tree(list[:i]), tree(list[i + 1:]))

# Recursive Generator
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x

</code>```

Role of yield x inside for loop.

答:
Not sure exactly what you're looking for, but perhaps it is something along these lines:

```<code>class Tree:
    def __init__(self, label, left=None, right=None):
        self.label = label
        self.left = left
        self.right = right

    def __repr__(self, level=0, indent="    "):
        s = level*indent + repr(self.label)
        if self.left:
            s = s + "\n" + self.left.__repr__(level+1, indent)
        if self.right:
            s = s + "\n" + self.right.__repr__(level+1, indent)
        return s

    def __iter__(self):
        return inorder(self)

def tree(list):
    n = len(list)
    if n == 0:
        return []
    i = n // 2
    return Tree(list[i], tree(list[:i]), tree(list[i + 1:]))

def inorder(t):
    if t:
        for x in t.left:
            yield x
        yield t.label
        for x in t.right:
            yield x

t = tree("ABCDEFG")
[print(i.label) for i in t]
</code>```

which outputs:

```<code>A
B
C
D
E
F
G
</code>```

With that code you could instead:

```<code>[print('----------\n', i) for i in t]
</code>```

which outputs each hierarchical node in the tree, from A to G.

Edit: If you're asking how generator works, perhaps this example could be enlightening:

```<code>>>> def list2gen(lst):
...     for elem in lst:
...             yield str(elem) + '_'
...
>>> print(list2gen([1,2,'7',-4]))
<generator object list2gen at 0x000001B0DEF8B0C0>
>>> print(list(list2gen([1,2,'7',-4])))
['1_', '2_', '7_', '-4_']
</code>```

If your debugger breaks multiple times at a yield, but those elements never materialize in the resulting generator, you'd have to attribute that to bugs in the debugger. I've not used one for Python in more than a decade; they used to be notoriously bug-infested. In Python the paradigm is "test is king," and "avoid manual debugging," but I disagree with that. (The only reason I don't is lack of great IDE's and debuggers.)

Body:
I am learning about recursive generators and found this program on web.

I undertand the recursive version of In-Order traversal but i am having trouble understanding recursive generator.

Specifically i am not able to understand

why 'yield x'  is written in for loop?

Why 'yield x' is not collected in final list?

I have tried to dubug the generator and added the watch but i found that recursive call execute multiple time 'yield x' and it's not collected in final result.

class Tree:
    def __init__(self, label, left=None, right=None):
        self.label = label
        self.left = left
        self.right = right

    def __repr__(self, level=0, indent="    "):
        s = level*indent + repr(self.label)
        if self.left:
            s = s + "\\n" + self.left.__repr__(level+1, indent)
        if self.right:
            s = s + "\\n" + self.right.__repr__(level+1, indent)
        return s

    def __iter__(self):
        return inorder(self)

def tree(list):
    n = len(list)
    if n == 0:
        return []
    i = n // 2
    return Tree(list[i], tree(list[:i]), tree(list[i + 1:]))

# Recursive Generator
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x

Role of yield x inside for loop.

Body:
Not sure exactly what you're looking for, but perhaps it is something along these lines:

class Tree:
    def __init__(self, label, left=None, right=None):
        self.label = label
        self.left = left
        self.right = right

    def __repr__(self, level=0, indent="    "):
        s = level*indent + repr(self.label)
        if self.left:
            s = s + "\n" + self.left.__repr__(level+1, indent)
        if self.right:
            s = s + "\n" + self.right.__repr__(level+1, indent)
        return s

    def __iter__(self):
        return inorder(self)

def tree(list):
    n = len(list)
    if n == 0:
        return []
    i = n // 2
    return Tree(list[i], tree(list[:i]), tree(list[i + 1:]))

def inorder(t):
    if t:
        for x in t.left:
            yield x
        yield t.label
        for x in t.right:
            yield x

t = tree("ABCDEFG")
[print(i.label) for i in t]

which outputs:

A
B
C
D
E
F
G

With that code you could instead:

[print('----------\n', i) for i in t]

which outputs each hierarchical node in the tree, from A to G.

Edit: If you're asking how generator works, perhaps this example could be enlightening:

>>> def list2gen(lst):
...     for elem in lst:
...             yield str(elem) + '_'
...
>>> print(list2gen([1,2,'7',-4]))
<generator object list2gen at 0x000001B0DEF8B0C0>
>>> print(list(list2gen([1,2,'7',-4])))
['1_', '2_', '7_', '-4_']

If your debugger breaks multiple times at a yield, but those elements never materialize in the resulting generator, you'd have to attribute that to bugs in the debugger. I've not used one for Python in more than a decade; they used to be notoriously bug-infested. In Python the paradigm is "test is king," and "avoid manual debugging," but I disagree with that. (The only reason I don't is lack of great IDE's and debuggers.)


问:
NGXS: how can we pass entire collection to the actions in ngxs?
I am having a collection of object which I need to pass to ngxs actions. I am able to pass single object and it is storing the state and working fine but i do not want to iterate the object instead want to pass entire collection?

I have tried for single object it is working fine, but want to pass entire collection?

I am trying like this but it is not working:

```<code>export class AddAccounts {
  static readonly type = '[Account] Add';
  constructor(public payload: Account[]) { }
}

//this.accounts is a collection of Account[] type.
this.store.dispatch(this.accounts);

export class AccountStateModel {
  accounts: Account[][];
}

@State<AccountStateModel>({
  name: 'accounts',
  defaults: {
    accounts: []
  }
})

@Selector()
static getAccounts(state: AccountStateModel) {
  return state.accounts;
}

@Action(AddAccount)
add({ getState, patchState }: StateContext<AccountStateModel>, { payload }:
  AddAccount) {
  const state = getState();
  patchState({
    accounts: [...state.accounts, payload]
  });
}
</code>```

Is there a way we can pass entire collection to the actions?

答:
I think it's just an error in your state model.
The TutorialStateModel was defined as an array of arrays (Tutorial[][]) rather than a single array.

When I update your definition, and fix the patchState call to match it, I can see the UI updating as I'd expect.  See below:

Body:
I am having a collection of object which I need to pass to ngxs actions. I am able to pass single object and it is storing the state and working fine but i do not want to iterate the object instead want to pass entire collection?

I have tried for single object it is working fine, but want to pass entire collection?

I am trying like this but it is not working:

export class AddAccounts {
  static readonly type = '[Account] Add';
  constructor(public payload: Account[]) { }
}

//this.accounts is a collection of Account[] type.
this.store.dispatch(this.accounts);

export class AccountStateModel {
  accounts: Account[][];
}

@State<AccountStateModel>({
  name: 'accounts',
  defaults: {
    accounts: []
  }
})

@Selector()
static getAccounts(state: AccountStateModel) {
  return state.accounts;
}

@Action(AddAccount)
add({ getState, patchState }: StateContext<AccountStateModel>, { payload }:
  AddAccount) {
  const state = getState();
  patchState({
    accounts: [...state.accounts, payload]
  });
}

Is there a way we can pass entire collection to the actions?


问:
Deleting null rows from HTML table with Javascript
I have an HTML table that is pulling from a database. Some of the rows are coming in with the text null and I would like to loop through this table and delete or hide any rows that have the text null in them.

The first column will be the column to loop through and find the 'null' text and delete that row but I can't figure out how to do it.

    <col width="120">
    <col width="120">
    <col width="120">

      Item
      Price
      Sale Price

```

答:
Firstly you're using <col> tags in wrong way, you need to use <colgroup> as their parent and place them outside the
 tag. For removing empty rows you should use jQuery, then you need to loop through the rows and then remove it if the first column is empty using td:first-child selector. look at the snippet.

$("#ex-table tbody tr").each(function() {
  var html = $(this).find("td:first-child").html();
  if (html === 'null') {
    $(this).remove()
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped" id="ex-table">
  <colgroup>
    <col width="120">
    <col width="120">
    <col width="120">
  </colgroup>

  <thead class="thead-inverse">
    <tr>
      <th bgcolor="#feaf3f">Item</th>
      <th bgcolor="#feaf3f">Price</th>
      <th bgcolor="#feaf3f">Sale Price</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td id="Item">null</td>
      <td id="Price">50</td>
      <td id="salePrice">60</td>
    </tr>
    <tr id="tr">
      <td id="Item">2</td>
      <td id="Price">60</td>
      <td id="salePrice">70</td>
    </tr>
  </tbody>
</table></code>```

Body:
Firstly you're using <col> tags in wrong way, you need to use <colgroup> as their parent and place them outside the <thead> tag. For removing empty rows you should use jQuery, then you need to loop through the rows and then remove it if the first column is empty using td:first-child selector. look at the snippet.

$("#ex-table tbody tr").each(function() {
  var html = $(this).find("td:first-child").html();
  if (html === 'null') {
    $(this).remove()
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped" id="ex-table">
  <colgroup>
    <col width="120">
    <col width="120">
    <col width="120">
  </colgroup>

  <thead class="thead-inverse">
    <tr>
      <th bgcolor="#feaf3f">Item</th>
      <th bgcolor="#feaf3f">Price</th>
      <th bgcolor="#feaf3f">Sale Price</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td id="Item">null</td>
      <td id="Price">50</td>
      <td id="salePrice">60</td>
    </tr>
    <tr id="tr">
      <td id="Item">2</td>
      <td id="Price">60</td>
      <td id="salePrice">70</td>
    </tr>
  </tbody>
</table>


问:
Spring Boot 1.5 to 2 migration - Flyway migration checksum mismatch
When upgrading to Spring Boot 2 from 1.5 I get the following error, although the SQL scripts haven't changed:

```<code>Migration checksum mismatch for migration version 1
-> Applied to database : 1395032327
-> Resolved locally    : -175919814
</code>```

Spring Boot recommends

To make sure that the schema upgrade goes smoothly, please follow the
  following instructions:

First upgrade your 1.5.x Spring Boot application to Flyway 4 (4.2.0 at
  the time of writing), see the instructions for Maven and Gradle.

Once your schema has been upgraded to Flyway 4, upgrade to Spring Boot
  2 and run the migration again to port your application to Flyway 5.

This is not easily possible if you don't control the deployment and you can't deploy the application twice (e.g. users download the latest version of the app).

What is the cause of the problem and what would be the solution?

答:
Probably easiest is to execute flyway.repair() before the real migration:

```<code>@Configuration
public class FlywayRepair {

    @Bean
    public FlywayMigrationStrategy repair() {
        return flyway -> {
            // repair each script checksum
            flyway.repair();
            // before migration is executed
            flyway.migrate();
        };
    }
}
</code>```

Downfall is that it also removes failed migrations. From Flyway.repair() Javadoc:

Repairs the Flyway schema history table. This will perform the
  following actions:

Remove any failed migrations on databases without DDL transactions (User objects left behind must still be cleaned up manually)

Realign the checksums, descriptions and types of the applied migrations with the ones of the available migrations

Body:
When upgrading to Spring Boot 2 from 1.5 I get the following error, although the SQL scripts haven't changed:

Migration checksum mismatch for migration version 1
-> Applied to database : 1395032327
-> Resolved locally    : -175919814

Spring Boot recommends

To make sure that the schema upgrade goes smoothly, please follow the
  following instructions:

First upgrade your 1.5.x Spring Boot application to Flyway 4 (4.2.0 at
  the time of writing), see the instructions for Maven and Gradle.

Once your schema has been upgraded to Flyway 4, upgrade to Spring Boot
  2 and run the migration again to port your application to Flyway 5.

This is not easily possible if you don't control the deployment and you can't deploy the application twice (e.g. users download the latest version of the app).

What is the cause of the problem and what would be the solution?

Body:
Probably easiest is to execute flyway.repair() before the real migration:

@Configuration
public class FlywayRepair {

    @Bean
    public FlywayMigrationStrategy repair() {
        return flyway -> {
            // repair each script checksum
            flyway.repair();
            // before migration is executed
            flyway.migrate();
        };
    }
}

Downfall is that it also removes failed migrations. From Flyway.repair() Javadoc:

Repairs the Flyway schema history table. This will perform the
  following actions:

Remove any failed migrations on databases without DDL transactions (User objects left behind must still be cleaned up manually)

Realign the checksums, descriptions and types of the applied migrations with the ones of the available migrations


问:
Does `instanceof` produce a static type qualifier?
In Typescript one can take a symbol and use its signature (and everything compiler knows about the object) as a valid type qualifier. This allows you to do this:

const foo: number = 3

const bar: typeof foo = 4
```

Is it possible in any other languages? I was told that it is possible in Java using the instanceof but I struggled to find any documentation on this keyword aside from dynamic type-checking.

答:
First of all:

Does instanceof produce a static type qualifier?

Not at all. It is just an operator that returns a boolean result. It tells you if A is an instance of B. Not more, not less.

In Java, all type information (at least at runtime) boils down to the things that java.lang.Class gives you.

In other words: when you int foo = 3 in Java, the best thing you hope for would be Class<?> bar = int.class. Also note that there is no generic way to get to the Class object of "something".

The only slightly "advanced experience" was added with the new var keyword. Which basically allows you to now write down types explicitly, but let the compiler handle them completely.

The one additional semantical element that var gives you: the ability to "name" something that otherwise has no name:

```<code>var obj = new Object() {
  private void test() {
    System.out.println("anonymous test");
  }
};
obj.test(); // works!
</code>```

( from the java specialist newsletter, issue 263 )

Body:
In Typescript one can take a symbol and use its signature (and everything compiler knows about the object) as a valid type qualifier. This allows you to do this:

const foo: number = 3

const bar: typeof foo = 4

Is it possible in any other languages? I was told that it is possible in Java using the instanceof but I struggled to find any documentation on this keyword aside from dynamic type-checking.

Body:
First of all:

Does instanceof produce a static type qualifier?

Not at all. It is just an operator that returns a boolean result. It tells you if A is an instance of B. Not more, not less.

In Java, all type information (at least at runtime) boils down to the things that java.lang.Class gives you.

In other words: when you int foo = 3 in Java, the best thing you hope for would be Class<?> bar = int.class. Also note that there is no generic way to get to the Class object of "something".

The only slightly "advanced experience" was added with the new var keyword. Which basically allows you to now write down types explicitly, but let the compiler handle them completely.

The one additional semantical element that var gives you: the ability to "name" something that otherwise has no name:

var obj = new Object() {
  private void test() {
    System.out.println("anonymous test");
  }
};
obj.test(); // works!

( from the java specialist newsletter, issue 263 )


问:
OpenPGPJS: Invalid session key for decryption
OpenPGP JS throws the following error when I attempt to decrypt some armored data with my private key:
Uncaught (in promise) Error: Error decrypting message: Invalid session key for decryption. at onError (openpgp.min.js:16057) onError @ openpgp.min.js:16057

From what I can tell from google, this means something is going wrong with the encryption, but I can't tell what it is. What makes it worse is that it seems to be inconsistent with only certain files (seemingly encrypted around the same time?) failing in this way. The encrypted messages don't seem to be malformed in any way.

If anyone has any tips for debugging this it would be appreciated. What could throw this error? Excerpts of my code are below, based primarily on the openPGPJS example code.

For extra information about what my code is doing, image files are being encrypted on the client side, uploaded to a server, downloaded elsewhere, and then being decrypted.

```<code>function encryptData(data) {
  var openpgp = window.openpgp;
  var options, encrypted;
  var pubkey = `-----BEGIN PGP PUBLIC KEY BLOCK-----...-----END PGP PUBLIC KEY BLOCK-----`;

  options = {
    data: data,
    publicKeys: openpgp.key.readArmored(pubkey).keys
  };

  return openpgp.encrypt(options);
}

function decryptPGP(encData, doneFunc) {
    var privkey = `-----BEGIN PGP PRIVATE KEY BLOCK-----...-----END PGP PRIVATE KEY BLOCK-----`;
    var pubkey = `-----BEGIN PGP PUBLIC KEY BLOCK-----...-----END PGP PUBLIC KEY BLOCK-----`;
    var passphrase = '...';
    var privKeyObj = openpgp.key.readArmored(privkey).keys[0];
    privKeyObj.decrypt(passphrase);

    options = {
        message: openpgp.message.readArmored(encData),
        publicKeys: openpgp.key.readArmored(pubkey).keys,
        privateKey: privKeyObj
    };

    openpgp.decrypt(options).then(function(plaintext) {
        doneFunc(plaintext.data);
    });
}
</code>```

答:
I have had the same issue. To resolve it, encode your result from encryption with base64. That base64 string can then be sent over the internet as you desire. When you want to decrypt, just decrypt base64 first and then

await openpgp.message.readArmored(Base64.decode(encData))

will work!

Body:
OpenPGP JS throws the following error when I attempt to decrypt some armored data with my private key:
Uncaught (in promise) Error: Error decrypting message: Invalid session key for decryption. at onError (openpgp.min.js:16057) onError @ openpgp.min.js:16057

From what I can tell from google, this means something is going wrong with the encryption, but I can't tell what it is. What makes it worse is that it seems to be inconsistent with only certain files (seemingly encrypted around the same time?) failing in this way. The encrypted messages don't seem to be malformed in any way.

If anyone has any tips for debugging this it would be appreciated. What could throw this error? Excerpts of my code are below, based primarily on the openPGPJS example code.

For extra information about what my code is doing, image files are being encrypted on the client side, uploaded to a server, downloaded elsewhere, and then being decrypted.

function encryptData(data) {
  var openpgp = window.openpgp;
  var options, encrypted;
  var pubkey = `-----BEGIN PGP PUBLIC KEY BLOCK-----...-----END PGP PUBLIC KEY BLOCK-----`;

  options = {
    data: data,
    publicKeys: openpgp.key.readArmored(pubkey).keys
  };

  return openpgp.encrypt(options);
}

function decryptPGP(encData, doneFunc) {
    var privkey = `-----BEGIN PGP PRIVATE KEY BLOCK-----...-----END PGP PRIVATE KEY BLOCK-----`;
    var pubkey = `-----BEGIN PGP PUBLIC KEY BLOCK-----...-----END PGP PUBLIC KEY BLOCK-----`;
    var passphrase = '...';
    var privKeyObj = openpgp.key.readArmored(privkey).keys[0];
    privKeyObj.decrypt(passphrase);

    options = {
        message: openpgp.message.readArmored(encData),
        publicKeys: openpgp.key.readArmored(pubkey).keys,
        privateKey: privKeyObj
    };

    openpgp.decrypt(options).then(function(plaintext) {
        doneFunc(plaintext.data);
    });
}


问:
Model State Always true even when the required field is not sent
I am simply calling an API and passing an object as a parameter and everything works fine. But then i wanted to validate the model before going any further so i simply wrote [Required] above the fields i always wanted filled.
MODEL

```<code>public class Consent
{
    public Consent()
    {

    }
    public int Id { get; set; }
    [Required]
    public int FacilityId { get; set; }
    public string Heading { get; set; }
    public string Description { get; set; }
}

</code>```

and validate the model state in controller like this

```<code>public ActionResult<int> AddConsent(Consent consent)
{
    if(!ModelState.IsValid){
        throw new CustomException("000-0000-000", "Validation failed");

    }
    //Further Code
}
</code>```

By this i expected model state to be false when i don't send the facilityId when i call the api
JSON

```<code>{
    "heading": "HeadingFromPostman5",
    "description": "DiscriptiomFromPostman5"
}
</code>```

but its still true . I know .Net core is allocating 0 to int value when null but how can i validate it then? Whats the work around for this?

答:
The Required attribute works well for nullable reference objects. For primitives, when an instance is created, the default value (in this case 0 for int) is assigned for FacilityId, and hence the Required won't work. If you make the FacilityId as nullable int then the Required attribute will work fine.</p>

```<code>[Required]
public int? FacilityId { get; set; }
</code>```

Body:
I am simply calling an API and passing an object as a parameter and everything works fine. But then i wanted to validate the model before going any further so i simply wrote [Required] above the fields i always wanted filled.
MODEL

public class Consent
{
    public Consent()
    {

    }
    public int Id { get; set; }
    [Required]
    public int FacilityId { get; set; }
    public string Heading { get; set; }
    public string Description { get; set; }
}

and validate the model state in controller like this

public ActionResult<int> AddConsent(Consent consent)
{
    if(!ModelState.IsValid){
        throw new CustomException("000-0000-000", "Validation failed");

    }
    //Further Code
}

By this i expected model state to be false when i don't send the facilityId when i call the api
JSON

{
    "heading": "HeadingFromPostman5",
    "description": "DiscriptiomFromPostman5"
}

but its still true . I know .Net core is allocating 0 to int value when null but how can i validate it then? Whats the work around for this?

Body:
The Required attribute works well for nullable reference objects. For primitives, when an instance is created, the default value (in this case 0 for int) is assigned for FacilityId, and hence the Required won't work. If you make the FacilityId as nullable int then the Required attribute will work fine.

[Required]
public int? FacilityId { get; set; }


问:
Jest throwing TyperError: Expected a function when using lodash pipe/flow
I have following code:

```<code>function sort() {
   let array1 = [{ value:1 }, { value:2 }, { value:3 }];
   let array2 = [{ code:1 }, { code:2 }, { code:3 }];
   const constructSortedArray = pipe(
     sortBy(array1, element => element.value),
     sortedArray1 => sortedArray1.concat(array2)
   );
   return constructSortedArray();
 }
</code>```

I m using lodash/fp/flow as pipe alias and lodash/sortBy. When running the code, the function works fine but when testing the code with jest I get following error on pipe:

```<code>TypeError: Expected a function

> 73 |     const constructSortedArray = pipe(
</code>```

I have tried setting the testEnviornment as jsdom and node but its not helpful. The automock is also disabled for jest.

Any help is appreciated.

答:
When you call sortBy it returns the results, and not a function. You can fix by using an arrow function, and calling the piped function with array1 as argument.

Note: lodash doesn't have a _.pipe() method (it's named _.flow()), but lodash/fp does (it's an alias of _.flow()).

const { flow, sortBy } = _;

function sort() {
  let array1 = [{ value:1 }, { value:2 }, { value:3 }];
  let array2 = [{ code:1 }, { code:2 }, { code:3 }];
  const constructSortedArray = flow(
    arr => sortBy(arr, element => element.value),
    sortedArray1 => sortedArray1.concat(array2)
  );
  return constructSortedArray(array1);
}

console.log(sort());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script></code>```

A cleaner option would be to user _.partialRight() to return a function with the right most parameter already applied:

const { flow, partialRight, sortBy, concat } = _;

function sort() {
  let array1 = [{ value:1 }, { value:2 }, { value:3 }];
  let array2 = [{ code:1 }, { code:2 }, { code:3 }];

  const constructSortedArray = flow(
    partialRight(sortBy, element => element.value),
    partialRight(concat, array2)
  );

  return constructSortedArray(array1);
}

console.log(sort());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script></code>```

And the cleanest way would be to user lodash/fp, because all functions are auto-curried, and the parameters are in the correct order:

const { pipe, partialRight, sortBy, concat } = _;

function sort() {
  let array1 = [{ value:1 }, { value:2 }, { value:3 }];
  let array2 = [{ code:1 }, { code:2 }, { code:3 }];

  const constructSortedArray = pipe(
    sortBy(element => element.value),
    partialRight(concat, [array2])
  );

  return constructSortedArray(array1);
}

console.log(sort());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script></code>```

Body:
I have following code:

function sort() {
   let array1 = [{ value:1 }, { value:2 }, { value:3 }];
   let array2 = [{ code:1 }, { code:2 }, { code:3 }];
   const constructSortedArray = pipe(
     sortBy(array1, element => element.value),
     sortedArray1 => sortedArray1.concat(array2)
   );
   return constructSortedArray();
 }

I m using lodash/fp/flow as pipe alias and lodash/sortBy. When running the code, the function works fine but when testing the code with jest I get following error on pipe:

TypeError: Expected a function

> 73 |     const constructSortedArray = pipe(

I have tried setting the testEnviornment as jsdom and node but its not helpful. The automock is also disabled for jest.

Any help is appreciated.

Body:
When you call sortBy it returns the results, and not a function. You can fix by using an arrow function, and calling the piped function with array1 as argument.

Note: lodash doesn't have a _.pipe() method (it's named _.flow()), but lodash/fp does (it's an alias of _.flow()).

const { flow, sortBy } = _;

function sort() {
  let array1 = [{ value:1 }, { value:2 }, { value:3 }];
  let array2 = [{ code:1 }, { code:2 }, { code:3 }];
  const constructSortedArray = flow(
    arr => sortBy(arr, element => element.value),
    sortedArray1 => sortedArray1.concat(array2)
  );
  return constructSortedArray(array1);
}

console.log(sort());

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

A cleaner option would be to user _.partialRight() to return a function with the right most parameter already applied:

const { flow, partialRight, sortBy, concat } = _;

function sort() {
  let array1 = [{ value:1 }, { value:2 }, { value:3 }];
  let array2 = [{ code:1 }, { code:2 }, { code:3 }];

  const constructSortedArray = flow(
    partialRight(sortBy, element => element.value),
    partialRight(concat, array2)
  );

  return constructSortedArray(array1);
}

console.log(sort());

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

And the cleanest way would be to user lodash/fp, because all functions are auto-curried, and the parameters are in the correct order:

const { pipe, partialRight, sortBy, concat } = _;

function sort() {
  let array1 = [{ value:1 }, { value:2 }, { value:3 }];
  let array2 = [{ code:1 }, { code:2 }, { code:3 }];

  const constructSortedArray = pipe(
    sortBy(element => element.value),
    partialRight(concat, [array2])
  );

  return constructSortedArray(array1);
}

console.log(sort());

<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>


问:
How to check if element exists in an Object?
How to use *ngIf to check if an element exists in an Object?

.ts file

```<code>this.data = ["cat", "dog"];

</code>```

I want to check, in my html file, if cat exists in the object this.data or not. Can I do that with an *ngIf ?

答:
```<code><div *ngIf="data.includes('cat')">hello world</div>
</code>```

I hope this will help.

Body:
How to use *ngIf to check if an element exists in an Object?

.ts file

this.data = ["cat", "dog"];

I want to check, in my html file, if cat exists in the object this.data or not. Can I do that with an *ngIf ?

Body:
<div *ngIf="data.includes('cat')">hello world</div>

I hope this will help.


答:
```<code>from collections import Counter
with open('xyz.txt') as f:
    result = Counter(f.read().split())
print(result)
</code>```

Title: How to find the number of times a string occurs in a text file?

Body:
I'm trying to count the number of times a string occurs in a file of strings.

data=open('xyz.txt')
num=[]
    while 1:
        numrow=[]
        count=0
        x=data.readline()
        if x=='':
            break
        for line in data:
            if line==x:
                count+=1
        numrow.append(x)
        numrow.append(count)
        num.append(numrow)
    print(num)

When I try the code above, I keep getting the wrong count. Also, I'm not able to get every string and the number of times it appears. Instead, I get the string in the first line with the wrong count.

Is there a way I can print all the distinct strings along with their corresponding counts?


问:
Sql select query with several subqueries optimization
I have MySql database with such tables:

```<code>PageviewEvents:
pageviewId | eventId | eventValue | eventTime

SessionPageviews:
id | sessionId | page
</code>```

PageviewEvents.pageviewId is a refers to SessionPageviews.id as foreign key.

When I need to select some data by eventId, I use this query:

```<code>SELECT
    sp.page as Page, count(*)
from PageviewEvents pe
left join SessionPageviews sp on sp.id = pe.pageviewId
where pe.eventId = 1
GROUP by sp.page
order BY 2 DESC
</code>```

And get a table like this:

```<code>page | count_of_event_1
</code>```

But now I need to select more data:

```<code>page | count_of_event_1 | count_of_event_2 ... | count_of_event_N
</code>```

I started with 2 events and tried to white something like this:

```<code>SELECT
    sp.page as Page,
    (SELECT count(*) from PageviewEvents pe1 left join SessionPageviews sp1 on sp1.id = pe1.pageviewId where pe1.eventId = 1 and sp1.page = sp.page) as count_of_event_1,
    (SELECT count(*) from PageviewEvents pe1 left join SessionPageviews sp1 on sp1.id = pe1.pageviewId where pe1.eventId = 2 and sp1.page = sp.page) as count_of_event_2
from PageviewEvents pe
left join SessionPageviews sp on sp.id = pe.pageviewId
where pe.eventId = 1 OR pe.eventId = 2
GROUP by sp.page
order BY 2 DESC
</code>```

When I run this query on remote server, it freezes.

Are there any errors in my query? How to optimize it?

答:
First, your query is suspicious.  You are using a LEFT JOIN, but you are aggregating by a column in the second table.  I doubt you really want a row with a NULL first column.

You can write the query using conditional aggregation (as Tim) points out.  I would express this as:

```<code>select sp.page as Page,
       sum( pe.eventid = 1 ) as count_of_event_1,
       sum( pe.eventid = 1 ) as count_of_event_2
from SessionPageviews sp join
     PageviewEvents pe
     on sp.id = pe.pageviewId
where pe.eventId in (1, 2)
group by sp.page
order by 2 desc;
</code>```

Then for this query, there are two indexing strategies.  If you have many types of events (or if 1 and 2 are relatively rare), then:

SessionPageviews(id, page)

PageviewEvents(eventId, pageviewId)

Otherwise:

SessionPageviews(page, id)

PageviewEvents(pageviewId, eventId)

Body:
I have MySql database with such tables:

PageviewEvents:
pageviewId | eventId | eventValue | eventTime

SessionPageviews:
id | sessionId | page

PageviewEvents.pageviewId is a refers to SessionPageviews.id as foreign key.

When I need to select some data by eventId, I use this query:

SELECT
    sp.page as Page, count(*)
from PageviewEvents pe
left join SessionPageviews sp on sp.id = pe.pageviewId
where pe.eventId = 1
GROUP by sp.page
order BY 2 DESC

And get a table like this:

page | count_of_event_1

But now I need to select more data:

page | count_of_event_1 | count_of_event_2 ... | count_of_event_N

I started with 2 events and tried to white something like this:

SELECT
    sp.page as Page,
    (SELECT count(*) from PageviewEvents pe1 left join SessionPageviews sp1 on sp1.id = pe1.pageviewId where pe1.eventId = 1 and sp1.page = sp.page) as count_of_event_1,
    (SELECT count(*) from PageviewEvents pe1 left join SessionPageviews sp1 on sp1.id = pe1.pageviewId where pe1.eventId = 2 and sp1.page = sp.page) as count_of_event_2
from PageviewEvents pe
left join SessionPageviews sp on sp.id = pe.pageviewId
where pe.eventId = 1 OR pe.eventId = 2
GROUP by sp.page
order BY 2 DESC

When I run this query on remote server, it freezes.

Are there any errors in my query? How to optimize it?

Body:
First, your query is suspicious.  You are using a LEFT JOIN, but you are aggregating by a column in the second table.  I doubt you really want a row with a NULL first column.

You can write the query using conditional aggregation (as Tim) points out.  I would express this as:

select sp.page as Page,
       sum( pe.eventid = 1 ) as count_of_event_1,
       sum( pe.eventid = 1 ) as count_of_event_2
from SessionPageviews sp join
     PageviewEvents pe
     on sp.id = pe.pageviewId
where pe.eventId in (1, 2)
group by sp.page
order by 2 desc;

Then for this query, there are two indexing strategies.  If you have many types of events (or if 1 and 2 are relatively rare), then:

SessionPageviews(id, page)

PageviewEvents(eventId, pageviewId)

Otherwise:

SessionPageviews(page, id)

PageviewEvents(pageviewId, eventId)


问:
composition. Pass a variables back
Say you had two classes A and B. If the relationship between is has-a

i.e. A has-a B

how can you pass information from B into A? Say for example in B you work out a calculation and need the answer in A.

Is there any other way of doing this besides passing a pointer to class A into class B and calling a function which takes the answer as a parameter.

Hope this makes sense,

MD.

Sorry I should have been more specific

quote from my comment below.

"well I gave a simple example. I am programming this in java and my class B runs a new thread and and will calculate the answer. Therefore I cannot just call the function from class A as I don't know when the calculation will be completed."

答:
There are basically two ways to manage "asynchronous" calls.
The first is having a callback and the other polling.
Having a callback is what , you describe. When B has finished, it needs to call A somehow that it has finished. That can been done by "giving" the adress of A to B, so it knows what to call, or by using a intermediate object C, which calls B synchronously and send the result back to A. C then needs to know about A.

Polling is when A check regularly if B has finished. This solution is usually less satisfying intellectually and more CPU consuming. You are also not notified exactly when B finished. (When B finish, nothing happend, you'll have to wait for the next poll to be aware of it). However, that way , B doesn't need no know anything about A.

I would use the first pattern with an intermediate object (and special class C). So that your model is still clean (B doesn't need to know about A or C). I suggest also you have a look at the Observer pattern.

Title: composition. Pass a variables back


问:
How to save image in project folder - reactjs
I'm working on mern project and need to find a way to store images in the project directory.
The images are originally stored in the database.
Once I obtain the images I need to save them in project folder like assets.
Is there a way to do this with just JavaScript?</p>

答:
If you are writing server-side javascript code that queries a database, then yes. React code is typically for creating client side/front end code that runs within a browser however and won't be able to interact with a server's database except through APIs.

From your edit saying you're using Express and MongoDB, it sounds like you should be able to use the following links to guide you in accomplishing what you're trying to do:

Store images in Mongodb serve them with Nodejs


问:
add a counter to lapply(do.call) - R
I have a file which includes many folders. I wrote the following code to get the address of all files, import them into R and bind them that works well. The problem is, some of the file has different number of columns, which resulted in showing an error. My question is how can add a counter to the third line of my code? I basically want to check when my counter stops, and then I manually drop that file that has different number of columns from others.
Thanks</p>

```<code>file_names <- list.files(path="D:/ABCDE", recursive=TRUE)
setwd("D:/ ABCDE ")
all_dta <- do.call(rbind, lapply(file_names, function(x) read.csv(file=x,header = FALSE)))
</code>```

答:
A simpler solution is to modify the call to skip the first row and just take all of the files with dplyr::bind_rows()

```<code>file_names <- list.files(path="D:/ABCDE", recursive=TRUE)
setwd("D:/ ABCDE ")
all_dta <- do.call(dplyr::bind_rows, lapply(file_names, function(x) read.table(file=x,header = FALSE, sep = ',', skip = 1)))
</code>```

The only thing is that you'd need to set the column names. You could either read one row to get the names or manually do it if there aren't a lot of columns.

Title: add a counter to lapply(do.call) - R

Body:
I have a file which includes many folders. I wrote the following code to get the address of all files, import them into R and bind them that works well. The problem is, some of the file has different number of columns, which resulted in showing an error. My question is how can add a counter to the third line of my code? I basically want to check when my counter stops, and then I manually drop that file that has different number of columns from others.
Thanks

file_names <- list.files(path="D:/ABCDE", recursive=TRUE)
setwd("D:/ ABCDE ")
all_dta <- do.call(rbind, lapply(file_names, function(x) read.csv(file=x,header = FALSE)))

Body:
A simpler solution is to modify the call to skip the first row and just take all of the files with dplyr::bind_rows()

file_names <- list.files(path="D:/ABCDE", recursive=TRUE)
setwd("D:/ ABCDE ")
all_dta <- do.call(dplyr::bind_rows, lapply(file_names, function(x) read.table(file=x,header = FALSE, sep = ',', skip = 1)))

The only thing is that you'd need to set the column names. You could either read one row to get the names or manually do it if there aren't a lot of columns.


问:
How to fix the "Role doesn't exist" error?
I just created a new Ruby on rails project using this, in order to deploy it with Heroku

```<code>rails new -d postgresql LG_1
</code>```

Then I used rails s to run my server and found this error :

```<code>role "esteban" does not exist.
</code>```

I've been looking for solutions for an hour, but none of them worked. Using createuser just gives me the does-not-exist error, and I'm not very comfortable with Rails.

The versions I'm using :

```<code>Ruby 2.4.4
Rails 5.2.3
Pg (gem) 1.1.4
</code>```

Here is my database.yml file (without the 75 lines of comments) :

```<code>default: &default
    adapter: postgresql
    encoding: unicode
    host: /var/run/postgresql
    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
    <<: *default
    database: LG_1_development

test:
     <<: *default
     database: LG_1_test

production:
    <<: *default
    database: LG_1_production
    username: LG_1
    password: <%= ENV['LG_1_DATABASE_PASSWORD'] %>
</code>```

I did not edit this file.

EDIT : I found the solution. I had to open the pg_hba.conf file and manually add a new user called "esteban"

答:
I guess esteban is the user name on your local machine and because you dont set specific username and password in database.yml for development mode postgres uses username of your user when trying to open connection to database.

Create role esteban in postgres:

```<code># go to psql console under default postgres user
psql postgres
# create role
create role esteban SUPERUSER LOGIN;
# exit psql
\q
</code>```

Or set correct one in database.yml if you already have it

Body:
I just created a new Ruby on rails project using this, in order to deploy it with Heroku

rails new -d postgresql LG_1

Then I used rails s to run my server and found this error :

role "esteban" does not exist.

I've been looking for solutions for an hour, but none of them worked. Using createuser just gives me the does-not-exist error, and I'm not very comfortable with Rails.

The versions I'm using :

Ruby 2.4.4
Rails 5.2.3
Pg (gem) 1.1.4

Here is my database.yml file (without the 75 lines of comments) :

default: &default
    adapter: postgresql
    encoding: unicode
    host: /var/run/postgresql
    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
    <<: *default
    database: LG_1_development

test:
     <<: *default
     database: LG_1_test

production:
    <<: *default
    database: LG_1_production
    username: LG_1
    password: <%= ENV['LG_1_DATABASE_PASSWORD'] %>

I did not edit this file.

EDIT : I found the solution. I had to open the pg_hba.conf file and manually add a new user called "esteban"

Body:
I guess esteban is the user name on your local machine and because you dont set specific username and password in database.yml for development mode postgres uses username of your user when trying to open connection to database.

Create role esteban in postgres:

# go to psql console under default postgres user
psql postgres
# create role
create role esteban SUPERUSER LOGIN;
# exit psql
\q

Or set correct one in database.yml if you already have it


问:
Using the function, how to disable and fetch the formgroupValues in angular
I need to disable the formControl and also want to fetch the data by using the function.

I used the following code for disabling the input text field

(formControlNames:- numberPrefix,numberFormat,resetNumberFormat )

```<code>onChanges() {
    this.soPreferenceFormGroup.get('numberPrefix').disable();
    this.soPreferenceFormGroup.get('numberFormat').disable();
    this.soPreferenceFormGroup.get('resetNumberFormat').disable();
 }
</code>```

Following is the result which I got.Only numberMode is fetched.

Then when I used the disabled function directly in template method like below

```<code><input pInputText type="text" formControlName="numberPrefix" class="form-control" placeholder="Required" disabled />
<input pInputText type="text" formControlName="numberFormat" class="form-control" placeholder="Required" disabled/>
<input pInputText type="text" formControlName="resetNumberFormat" class="form-control" placeholder="Required" disabled />
</code>```

Now, the all formGroup values are fetched .Below is the screenshot.

Why value is not displaying while disabling using methods??

I want to disable and fetch the value using the function instead of writing directly in html template

Can anybody help me ??

Please verify this stackBlitz: link

答:
form.value returns all active properties of your form.

If you want the disabled values with it, use myForm.getRawValue()

Body:
I need to disable the formControl and also want to fetch the data by using the function.

I used the following code for disabling the input text field

(formControlNames:- numberPrefix,numberFormat,resetNumberFormat )

onChanges() {
    this.soPreferenceFormGroup.get('numberPrefix').disable();
    this.soPreferenceFormGroup.get('numberFormat').disable();
    this.soPreferenceFormGroup.get('resetNumberFormat').disable();
 }

Following is the result which I got.Only numberMode is fetched.

Then when I used the disabled function directly in template method like below

<input pInputText type="text" formControlName="numberPrefix" class="form-control" placeholder="Required" disabled />
<input pInputText type="text" formControlName="numberFormat" class="form-control" placeholder="Required" disabled/>
<input pInputText type="text" formControlName="resetNumberFormat" class="form-control" placeholder="Required" disabled />

Now, the all formGroup values are fetched .Below is the screenshot.

Why value is not displaying while disabling using methods??

I want to disable and fetch the value using the function instead of writing directly in html template

Can anybody help me ??

Please verify this stackBlitz: link


问:
How do I create a split view where the top panel is collapsible in XCode?
I have a UINavigationController which contains several UIViewControllers. I would like to create a shared "panel" that is displayed at the top of each view. In addition, I would like to make that panel expand and collapse, overlaying the view, when tapped.

View1

-Top Panel (collapsible)

-Main Panel

View2

-Top Panel (collapsible)

-Main Panel

This would be similar to the way the toolbar or navigation panel hide/show for the camera controller, but it would be a custom view. This is an iPhone app.

As a new XCode developer I would appreciate insights as to how this should be approached from an architectural standpoint.

答:
Create a UIViewController subclass, say called PanelStyleUIViewController,
 which would be a superclass for all the views that will have the panel. The superclass implements the panel's controller logic, and the view expansion and contraction, which always happens above the children controller's regular view logic.

This is going to be a modestly difficult project for a new iOS/cocoa developer, because:

You probably will end up having to write a lot of the folding panel's view code programmatically. It is possible to design it in interface builder using more advanced techniques but IB's basic usage is to design one view controller at a time. You need to design a partial, parent view controller that then is inherited to a number of different ones.

You need to make sure that the folding view is always above (z-index wise) the regular view content of the lower level view controller classes. This is something that is probably solved by doing a bringSubviewToFront call on the panel view on, say, the viewDidAppear method.

You are going "off road" from how standard iPhone apps behave. Whenever you do this, you make headaches for yourself and might find yourself at a dead end. My recommendation would be to stay "inside the lines" for a while until you are pretty confident with objective C, cocoa touch, etc.

That said, here's some untested code I wrote here in the stack overflow editor which should give you an idea of what I mean for this superclass design:

```<code>// PanelStyleUIViewController.h
@interface PanelStyleUIViewController : UIViewController {
    UIView *panelView;
}
@property (nonatomic, retain) UIView *panelView;

// PanelStyleUIViewController.m

@implementation PanelStyleUIViewController

@synthesize panelView;

- (void)viewDidLoad {
    [super viewDidLoad];
    // setup geometry, contents, etc of panelView programmatically...
    self.panelView = [[[UIView alloc] init] autorelease];
    panelView.frame = CGRectMake(0,0,320,200);
    // set resizing mask appropriately for landscape support
    panelView.autoresizingMask = UIViewAutoresizingMaskFlexibleWidth | UIViewAutoresizingMaskFlexibleBottomMargin;
    // put a button on the panel view so it can be tapped to slide down
    UIButton *slidePanelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    slidePanelButton.frame = CGRectMake(0,160,320,40);
    [slidePanelButton addTarget:self action:@selector(slidePanel) forControlEvents:UIControlEventTouchUpInside];
    [panelView addSubview:slidePanelButton];
    // set panelView with a transform offset to slide it up under the top of the screen
    panelView.transform = CGAffineTransformMakeTranslation(0, -160);
    // add panelView to regular view controller's view
    [self.view addSubview:panelView];
}

- (void)viewWillAppear {
    // make sure the panel shows up on top, z-index wise, since subclasses might have created views that overlap it.
    [self.view bringSubviewToFront:panelView];
}

- (void)slidePanel {
    // remove the panel transform in an animated fashion (slide down).
    // TODO: some button or action needs to slide the panel back up...
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [panelView setTransform:CGAffineTransformMakeTranslation(0,0)];
    [UIView commitAnimations];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // always make sure you clean up progammatically-retained views here
    self.panelView = nil;
}

- (void)dealloc {
    // and here too
    self.panelView = nil;
    [super dealloc];
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Create a UIViewController subclass, say called PanelStyleUIViewController,
 which would be a superclass for all the views that will have the panel. The superclass implements the panel's controller logic, and the view expansion and contraction, which always happens above the children controller's regular view logic.

This is going to be a modestly difficult project for a new iOS/cocoa developer, because:

You probably will end up having to write a lot of the folding panel's view code programmatically. It is possible to design it in interface builder using more advanced techniques but IB's basic usage is to design one view controller at a time. You need to design a partial, parent view controller that then is inherited to a number of different ones.

You need to make sure that the folding view is always above (z-index wise) the regular view content of the lower level view controller classes. This is something that is probably solved by doing a bringSubviewToFront call on the panel view on, say, the viewDidAppear method.

You are going "off road" from how standard iPhone apps behave. Whenever you do this, you make headaches for yourself and might find yourself at a dead end. My recommendation would be to stay "inside the lines" for a while until you are pretty confident with objective C, cocoa touch, etc.

That said, here's some untested code I wrote here in the stack overflow editor which should give you an idea of what I mean for this superclass design:

// PanelStyleUIViewController.h
@interface PanelStyleUIViewController : UIViewController {
    UIView *panelView;
}
@property (nonatomic, retain) UIView *panelView;

// PanelStyleUIViewController.m

@implementation PanelStyleUIViewController

@synthesize panelView;

- (void)viewDidLoad {
    [super viewDidLoad];
    // setup geometry, contents, etc of panelView programmatically...
    self.panelView = [[[UIView alloc] init] autorelease];
    panelView.frame = CGRectMake(0,0,320,200);
    // set resizing mask appropriately for landscape support
    panelView.autoresizingMask = UIViewAutoresizingMaskFlexibleWidth | UIViewAutoresizingMaskFlexibleBottomMargin;
    // put a button on the panel view so it can be tapped to slide down
    UIButton *slidePanelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    slidePanelButton.frame = CGRectMake(0,160,320,40);
    [slidePanelButton addTarget:self action:@selector(slidePanel) forControlEvents:UIControlEventTouchUpInside];
    [panelView addSubview:slidePanelButton];
    // set panelView with a transform offset to slide it up under the top of the screen
    panelView.transform = CGAffineTransformMakeTranslation(0, -160);
    // add panelView to regular view controller's view
    [self.view addSubview:panelView];
}

- (void)viewWillAppear {
    // make sure the panel shows up on top, z-index wise, since subclasses might have created views that overlap it.
    [self.view bringSubviewToFront:panelView];
}

- (void)slidePanel {
    // remove the panel transform in an animated fashion (slide down).
    // TODO: some button or action needs to slide the panel back up...
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [panelView setTransform:CGAffineTransformMakeTranslation(0,0)];
    [UIView commitAnimations];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // always make sure you clean up progammatically-retained views here
    self.panelView = nil;
}

- (void)dealloc {
    // and here too
    self.panelView = nil;
    [super dealloc];
}


问:
Nginx as proxy : how to exclude specific folder under https but not under http
I can rewrite some specific http folders to https folders, but i can't rewrite all https except these specific folders from https to http; i'm stuck in a loop

Using NGinx 1.12 as a proxy, handling both http and https

i have one server section to handle http 80 and one server section to handle https (i know they can be together in the same section).

both of them are beginning that way
location / {
        proxy_pass

server {
    listen 80;
i have
location ~ ^/(xxx|yyy|zzz)/.*$ {
        rewrite ^ https://www.example.com$uri permanent;
    }
and anytime i'm in http, it is redirecting to https fine for the xxx,yyy and zzz folders. so far, so good.

but under server {
    listen 443 ssl;
, i would like to redirect everything except the xxx,yyy,zzz folder to go back to http.

I did try to do the reverse in the https section meaning :
location / {
        rewrite ^ http://www.example.com$uri permanent;
    }
and
location ~ ^/(xxx|yyy|zzz)/.*$ {
        #do nothing
    }
but it is not working, either i get a 404 error or a loop

答:
The only solution i found as Nginx is a proxy is making Apache handling the redirect on its side.

so,
a. nginx 80 is redirecting to nginx 443 specific folders.
b. all https is redirect by nginx 443 to apache 443, and then in apache 443 conf i do a test, if it the specific folders, i stop, and otherwise i redirect to nginx 80.

It's working, but i'm sure it is possible to make nginx handle it and avoid this 1 loop. if someone as a beautiful answer :-)


问:
How to pass an array from an api as props to another component
I am making an api call which returns me an array of Usernames. I am calling the api in a Navbar component and am sending the data returned by the api to another component as props. When I console.log(this.state.Name) in Navbar it gives the whole array having usernames in the console, but when i receive the array in the other SearchedUser componenet and console.log() the recieved prop it gives me undefined in the console. Can Anyone tell whats wrong.

----------------------------------Navbar Component----------------------------

```<code>     class Navbar extends Component{

     constructor(props){
    super(props);
    this.state={
        name:'',
        Name:[],
    }
     this.GetUserData=this.GetUserData.bind(this);
}

    GetUserData=()=>{
fetch(`http://localhost:4000/data/searchuser?Name=${this.state.name}`)
.then(response => response.json())
.then(data=> this.setState({Name:data.datad}))
.catch(err=>console.log(err));}

        render()
{
    console.log(this.state.Name);
    return(
        <Router>
          <Link to={'/SearchedUser'}>
                <button type="submit" onClick={this.GetUserData}><i className="fa fa-search"></i></button>
         </Link>
            <Switch>
                <Route exact path='/' component={HomeContent} />
                <Route path='/Profile' component={Profile}/>
                <Route path='/SearchedUser' render={(props)=> <SearchedUser {...props} UserName={ [this.state.Name]}/>}/>
            </Switch>
        </Router>)  }}
</code>```

--------------------------------SearchedUser Component------------------------

```<code>    import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state={
    Name: props.UserName
}
    }

    render(){
console.log(this.state.Name);
return(
    <div>
    </div>
     )
    }
    }
export default SearchedUser;
</code>```

答:
dude you need to access props by this.props.propsName in class component.

//SearchedUser component

import React from 'react'
class SearchedUser extends React.Component{
  constructor(props){
    super(props);
      this.state={
        Name: this.props.UserName
      }
   }

  render(){
    return(

     )
   }
 }

export default SearchedUser;```

Body:
I am making an api call which returns me an array of Usernames. I am calling the api in a Navbar component and am sending the data returned by the api to another component as props. When I console.log(this.state.Name) in Navbar it gives the whole array having usernames in the console, but when i receive the array in the other SearchedUser componenet and console.log() the recieved prop it gives me undefined in the console. Can Anyone tell whats wrong.

----------------------------------Navbar Component----------------------------

     class Navbar extends Component{

     constructor(props){
    super(props);
    this.state={
        name:'',
        Name:[],
    }
     this.GetUserData=this.GetUserData.bind(this);
}

    GetUserData=()=>{
fetch(`http://localhost:4000/data/searchuser?Name=${this.state.name}`)
.then(response => response.json())
.then(data=> this.setState({Name:data.datad}))
.catch(err=>console.log(err));}

        render()
{
    console.log(this.state.Name);
    return(
        <Router>
          <Link to={'/SearchedUser'}>
                <button type="submit" onClick={this.GetUserData}></button>
         </Link>
            <Switch>
                <Route exact path='/' component={HomeContent} />
                <Route path='/Profile' component={Profile}/>
                <Route path='/SearchedUser' render={(props)=> <SearchedUser {...props} UserName={ [this.state.Name]}/>}/>
            </Switch>
        </Router>)  }}

--------------------------------SearchedUser Component------------------------

    import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state={
    Name: props.UserName
}
    }

    render(){
console.log(this.state.Name);
return(

     )
    }
    }
export default SearchedUser;

Body:
dude you need to access props by this.props.propsName in class component.

//SearchedUser component

import React from 'react'
class SearchedUser extends React.Component{
  constructor(props){
    super(props);
      this.state={
        Name: this.props.UserName
      }
   }

  render(){
    return(
      <div>
      </div>
     )
   }
 }

export default SearchedUser;


问:
Storing the result of an implicit cast to a concrete type into an interface fails
I want to implicitly cast an implementation to an interface. I know the C# specification doesn't allow this, and that is fine for my use case.

But when I implicitly cast to a type that does implement the interface, I can't store it in a variable of that interface. And that surprises me.

These are the definitions:

    public interface ISomeInterface
    {
    }

    public class SomeImplementation : ISomeInterface
    {
    }

    public class Class1
    {
        public static implicit operator SomeImplementation(Class1 class1)
        {
            return new SomeImplementation();
        }
    }

    var class1 = new Class1();

    // Works
    SomeImplementation s1 = class1;

    // Works
    ISomeInterface i1 = s1;

    // This is what I want to do
    ISomeInterface i2 = class1;
    // Cannot implicitly convert type 'Class1' to 'ISomeInterface'.
    // An explicit conversion exists (are you missing a cast?)
```

I would expect this to compile, because it is possible to implicitly cast Class1 to SomeImplementation and SomeImplementation implements ISomeInterface.

Why isn't this allowed?

答: "Well, in short, that there is no technical reason why the own conversions from / to interfaces are not allowed. The reason is because they open the door to certain scenarios that the language designers did not want to open and for that reason they prohibited them." - for full details see Conversions (explicit or implicit) and interfaces in C#</p>

Body:
I want to implicitly cast an implementation to an interface. I know the C# specification doesn't allow this, and that is fine for my use case.

But when I implicitly cast to a type that does implement the interface, I can't store it in a variable of that interface. And that surprises me.

These are the definitions:

    public interface ISomeInterface
    {
    }

    public class SomeImplementation : ISomeInterface
    {
    }

    public class Class1
    {
        public static implicit operator SomeImplementation(Class1 class1)
        {
            return new SomeImplementation();
        }
    }

    var class1 = new Class1();

    // Works
    SomeImplementation s1 = class1;

    // Works
    ISomeInterface i1 = s1;

    // This is what I want to do
    ISomeInterface i2 = class1;
    // Cannot implicitly convert type 'Class1' to 'ISomeInterface'.
    // An explicit conversion exists (are you missing a cast?)

I would expect this to compile, because it is possible to implicitly cast Class1 to SomeImplementation and SomeImplementation implements ISomeInterface.

Why isn't this allowed?


问:
Is EGit compatible with Eclipse Galileo and Eclipse Helios?
We have a product based on Eclipse. Today we support differents versions of our product: one is base on Eclipse 3.5 and another is based on Eclipse 3.6. Now, we would like to provide the EGit plugins within our product.

I've found the following comment on the EGit FAQ (http://wiki.eclipse.org/EGit/FAQ)
"EGit 0.7.1 requires Eclipse 3.5 (Galileo) or newer".

So, my questions are:

What is the compatibility of EGit 0.11.3 with Eclipse versions ?

Is EGit officially supported for Eclipse 3.6 ? With Eclipse 3.5 ?

Have someone already delivered it successfully in an Helios based product ?

Regards,
Jerome

答: Yes, it runs on Eclipse 3.5. It has been hacked by others to run on Eclipse 3.4 as well, though this isn't officially supported. Other commercial products based on Eclipse 3.5 also include EGit; you can install subsequent newer ones with the EGit release site.</p>


问:
Handle HTTP Errors globally in angular
I am working in http error handling. I have written error handling in each component which is not a good coding practice. So I have decided to write a common http error handling globally. I have searched for it, I have come across http-interceptor concept, I think there exists better way to handle the HTTP errors. What I have tried in each component is below Instead of that I need a global method. I already have http-interceptor file and the code is I am pasting below.

component.ts:

```<code>this.serviceName.methodName().catch(err => {
  console.log("Something went wrong with the request, please try again.");
  return Observable.throw(err.message.toUpperCase() || 'API_ERROR');
}).subscribe((res) => {
   console.log(res);
},
 error=>{
    this.openSnackBar('danger', "Something went wrong with the request, please try again.");
 });
</code>```

http-interceptor:

```<code>import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs";
import { tap } from 'rxjs/operators';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor() { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
        event => event instanceof HttpResponse ? 'succeeded' : '',
        err => 'failed'
    ))
 }
}
</code>```

Please help. Thanks.

答:
Try this:</p>

```<code>intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
      event => event instanceof HttpResponse ? 'succeeded' : '',
      err => {
        this.openSnackBar('danger', "Something went wrong with the request, please try again.");
      }
    ))
  }
</code>```

Title: Handle HTTP Errors globally in angular

Body:
I am working in http error handling. I have written error handling in each component which is not a good coding practice. So I have decided to write a common http error handling globally. I have searched for it, I have come across http-interceptor concept, I think there exists better way to handle the HTTP errors. What I have tried in each component is below Instead of that I need a global method. I already have http-interceptor file and the code is I am pasting below.

component.ts:

this.serviceName.methodName().catch(err => {
  console.log("Something went wrong with the request, please try again.");
  return Observable.throw(err.message.toUpperCase() || 'API_ERROR');
}).subscribe((res) => {
   console.log(res);
},
 error=>{
    this.openSnackBar('danger', "Something went wrong with the request, please try again.");
 });

http-interceptor:

import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs";
import { tap } from 'rxjs/operators';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor() { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
        event => event instanceof HttpResponse ? 'succeeded' : '',
        err => 'failed'
    ))
 }
}

Please help. Thanks.

Body:
Try this:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
      event => event instanceof HttpResponse ? 'succeeded' : '',
      err => {
        this.openSnackBar('danger', "Something went wrong with the request, please try again.");
      }
    ))
  }


问:
Is a parameter pack a template parameter?
cppreference writes that a template parameter pack is a template parameter:

https://en.cppreference.com/w/cpp/language/parameter_pack

Is it true? For example, is it correct to write something like this:

```<code>template<typename... Ts>
class MyClass {
    std::unique_ptr<Ts...> m_data;
};
</code>```

答:
In addition to the other answers, I would like to add an answer to this question from the perspective of the standard.

Per [temp.variadic]/1:

A template parameter pack is a template parameter that accepts zero or
  more template arguments.

So yeah, a template parameter pack is a template parameter. The code snippet you posted is correct.

Body:
cppreference writes that a template parameter pack is a template parameter:

https://en.cppreference.com/w/cpp/language/parameter_pack

Is it true? For example, is it correct to write something like this:

template<typename... Ts>
class MyClass {
    std::unique_ptr<Ts...> m_data;
};


问:
Masonite Route Parameters with slash does not work
My Routes:

```<code>Get().route('/amp/@website', 'PageController@amp_info').name('amp_info'),
Get().route('/@website', 'PageController@info').name('info')
</code>```

This works: https://websiteopedia.com/www.eventsnow.com
this does not https://websiteopedia.com/https://www.eventsnow.com/

What do I need to do differently?  the slash in params redirected to the 404 as it didn't find any matching route

答:
Yes, in order to achieve this you have two options: using inputs or creating a route compiler

Using Inputs

You can make the url simply go to the info method with nothing special in the url:

Get().route('/', 'PageController@info').name('info')
```

<p>Then you can hit routes like <code>https://websiteopedia.com/?website=https://www.eventsnow.com/</code> </p>

<p>Then inside the <code>info</code> method, you would get the input as normal:</p>

<pre class="lang-py prettyprint-override"><code>def info(self, request: Request):
    request.input('website') #== 'https://www.eventsnow.com/'
</code>```

Route Compiler

A route compiler is simply a way to compile regex in the URL. You can make a new compiler in one of the boot methods in your service providers.

This new compiler would look like this:

def boot(self, view: View):
    view.compile('url', r'([^\s]+)')
```

<p>Then you can construct the route like this:</p>

<pre class="lang-py prettyprint-override"><code>Get().route('/@website:url', 'PageController@info').name('info')
</code>```

This will now compile that into the regex you provided and you can now hit the routes like you were previously.

Body:
My Routes:

Get().route('/amp/@website', 'PageController@amp_info').name('amp_info'),
Get().route('/@website', 'PageController@info').name('info')

This works: https://websiteopedia.com/www.eventsnow.com
this does not https://websiteopedia.com/https://www.eventsnow.com/

What do I need to do differently?  the slash in params redirected to the 404 as it didn't find any matching route

Body:
Yes, in order to achieve this you have two options: using inputs or creating a route compiler

Using Inputs

You can make the url simply go to the info method with nothing special in the url:

Get().route('/', 'PageController@info').name('info')

Then you can hit routes like https://websiteopedia.com/?website=https://www.eventsnow.com/

Then inside the info method, you would get the input as normal:

def info(self, request: Request):
    request.input('website') #== 'https://www.eventsnow.com/'

Route Compiler

A route compiler is simply a way to compile regex in the URL. You can make a new compiler in one of the boot methods in your service providers.

This new compiler would look like this:

def boot(self, view: View):
    view.compile('url', r'([^\s]+)')

Then you can construct the route like this:

Get().route('/@website:url', 'PageController@info').name('info')

This will now compile that into the regex you provided and you can now hit the routes like you were previously.


问:
invalid operands of types 'const char [35]' and 'double' to binary 'operator+'
I have a problem with a string in arduino. I know that I can not put together different types like that. I have tried several conversions but don't get it working.

The following line is where I get the message "invalid operands of types 'const char [35]' and 'double' to binary 'operator +'"

```<code>sendString("Time: " + (micros () - PingTimer) * 0.001, 3 + " ms");
</code>```

答:
Disclaimer: This question is pretty similar but on a different stack exchange site (and the answer is questionable).

The problem can be reduced to the following snippet:

void setup() {
  "hello" + 3.0;
}
```

<p>It produces the following error message:</p>

<pre class="lang-none prettyprint-override"><code>error: invalid operands of types 'const char [6]' and 'double' to binary 'operator+'
</code>```

Many programming languages support "adding" character sequences together, C++ doesn't. Which means that you will need to use a class which represents a character sequence and implements the + operator.

Luckily there is already such a class which you can use: String. Example:

void setup() {
  String("hello") + 3.0;
}
```

<p>The expression is evaluates from left to right which means that the left most type has to be a <code>String</code>, in other words:</p>

<pre class="lang-cpp prettyprint-override"><code>String("a") + 1 + 2 + 3
</code>```

Is understood as:

((String("a") + 1) + 2) + 3
```

Where String("a") + 1 is a String and therefore (String("a") + 1) + 2 is, and so on...

Body:
I have a problem with a string in arduino. I know that I can not put together different types like that. I have tried several conversions but don't get it working.

The following line is where I get the message "invalid operands of types 'const char [35]' and 'double' to binary 'operator +'"

sendString("Time: " + (micros () - PingTimer) * 0.001, 3 + " ms");

Body:
Disclaimer: This question is pretty similar but on a different stack exchange site (and the answer is questionable).

The problem can be reduced to the following snippet:

void setup() {
  "hello" + 3.0;
}

It produces the following error message:

error: invalid operands of types 'const char [6]' and 'double' to binary 'operator+'

Many programming languages support "adding" character sequences together, C++ doesn't. Which means that you will need to use a class which represents a character sequence and implements the + operator.

Luckily there is already such a class which you can use: String. Example:

void setup() {
  String("hello") + 3.0;
}

The expression is evaluates from left to right which means that the left most type has to be a String, in other words:

String("a") + 1 + 2 + 3

Is understood as:

((String("a") + 1) + 2) + 3

Where String("a") + 1 is a String and therefore (String("a") + 1) + 2 is, and so on...