问:
Difference between Execute Around Method and Template Pattern
I was trying to implement some of the GoF design patterns using Java 8 Lambdas. During this exercise, I came across the Execute Around Method (EAM) pattern and the Template Pattern. Both seem to have striking similarities.

I have read that the EAM is more of an idiom without inheritance and most examples seem to be around handling resources(open, doSomething,close) as compared to the Template pattern which uses inheritance.

On reading further, I see that EAM seems to have history in Smalltalk.

However, using Java 8 Lambdas, we can actually get rid of the inheritance in the Template Pattern and simply pass behavior. The solution to implement EAM idiom is very similar to Template design pattern. One could view the open,doSomething,close as a Template pattern too, open() and close() being the same steps but doSomething() being subclassed. Using Java 8 Lambdas , we could simply pass the behavior of doSomething to a function which accepts a java.util.function.Consumer. This can be seen both as a EAM and as a Template pattern.

So my question is what is the difference between the two ?

答:
EAM is more like as Strategy Pattern in GoF design patterns.
Strategy & Template Method Pattern both are Behavior Pattern base on Algorithm,but they are a little different.

Steps defined in class as Template Method Pattern you can't replace one of them at runtime, if you need you must replace the whole instance with another subclass instance, but with Strategy Pattern you can replace it with another strategy instance.

Strategy Pattern more like separate each step into an individual Strategy type, Template Method is decomposing algorithm  into steps and deferring steps to subclass. but sometimes a Strategy type implemented via Template Method. for example:

Strategy Method

```<code>Runnable step1 = ()->{};
Runnable step2 = ()->{};
Runnable step3 = ()->{};

play(step1,step2);
play(step3,step2); //replace step1 with step3
</code>```

Template Method

```<code>class TemplateMethod{
  void run(){
    step1();
    step2();
  }

  void step1(){}
  void step2(){}
}

class Foo extends TemplateMethod{
  void step1(){
      System.out.println("foo");
  }
}

class Bar extends TemplateMethod{
  void step1(){
      System.out.println("foo");
  }
}

TemplateMethod foo=new Foo();
TemplateMethod bar=new Bar();

play(foo);
play(bar);// you must replace steps with another subclass instance
</code>```

Body:
EAM is more like as Strategy Pattern in GoF design patterns.
Strategy & Template Method Pattern both are Behavior Pattern base on Algorithm,but they are a little different.

Steps defined in class as Template Method Pattern you can't replace one of them at runtime, if you need you must replace the whole instance with another subclass instance, but with Strategy Pattern you can replace it with another strategy instance.

Strategy Pattern more like separate each step into an individual Strategy type, Template Method is decomposing algorithm  into steps and deferring steps to subclass. but sometimes a Strategy type implemented via Template Method. for example:

Strategy Method

Runnable step1 = ()->{};
Runnable step2 = ()->{};
Runnable step3 = ()->{};

play(step1,step2);
play(step3,step2); //replace step1 with step3

Template Method

class TemplateMethod{
  void run(){
    step1();
    step2();
  }

  void step1(){}
  void step2(){}
}

class Foo extends TemplateMethod{
  void step1(){
      System.out.println("foo");
  }
}

class Bar extends TemplateMethod{
  void step1(){
      System.out.println("foo");
  }
}

TemplateMethod foo=new Foo();
TemplateMethod bar=new Bar();

play(foo);
play(bar);// you must replace steps with another subclass instance


来源: stackexchange

问:
Is it possible to use google reCaptcha in a form made in elm
I would like to add a contact form to my website made in elm (version 0.18).
In order to prevent abusing spamming by bots I am thinking about integrating a captcha verification plugin in it, specifically google invisible reCaptcha, or the slightly older version where you have to click "I am not a Robot"

From what I understand from the documentation, in order to use these I have either to add some attributes to the form submit button, or call it from a javascript method.

The problem is since I use the elm Http module to process the form in app

 I have no button whith a type="submit" attribute, and I don't know how to call the google plug-in API from my elm code.

Is this possible? Or is this any other method more elm friendly?

答:
Adding attributes to your buttons is actually quite easy in Elm.  Take a look at Html.Attributes.attribute.  To get a basic submit button, just do this:

```<code>button [ attribute "type" "submit" ] [ text "Submit!" ]
</code>```

Concerning the google reCaptcha in particular... I don't have the ability to actually toy with google's api right now, but I believe that you should be able to make a port that can function as the data-callback field's value.  What follows is basically idle speculation because I'm on mobile, so take it with a grain of salt...

Declare an appropriate port (pretty sure the callback just gets passed a string, but perhaps you'll need to change that):

```<code>port captcha_port : ( String -> Msg ) -> Sub Msg
</code>```

Add a button with google's required attributes, including the send function of your newly created port:

```<code>button
  [ attribute "class" "g-recaptcha"
  , attribute "data-sitekey" "your_site_key"
  , attribute "data-callback" "app.ports.captcha_port.send"
  ] [ text "Sumbit All The Things!" ]
</code>```

And subscribe to the port with an appropriate Msg type somewhere in your subscriptions function:

```<code>captcha_port CaptchEvent
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Adding attributes to your buttons is actually quite easy in Elm.  Take a look at Html.Attributes.attribute.  To get a basic submit button, just do this:

button [ attribute "type" "submit" ] [ text "Submit!" ]

Concerning the google reCaptcha in particular... I don't have the ability to actually toy with google's api right now, but I believe that you should be able to make a port that can function as the data-callback field's value.  What follows is basically idle speculation because I'm on mobile, so take it with a grain of salt...

Declare an appropriate port (pretty sure the callback just gets passed a string, but perhaps you'll need to change that):

port captcha_port : ( String -> Msg ) -> Sub Msg

Add a button with google's required attributes, including the send function of your newly created port:

button
  [ attribute "class" "g-recaptcha"
  , attribute "data-sitekey" "your_site_key"
  , attribute "data-callback" "app.ports.captcha_port.send"
  ] [ text "Sumbit All The Things!" ]

And subscribe to the port with an appropriate Msg type somewhere in your subscriptions function:

captcha_port CaptchEvent


问:
How to assign client-id to a particular Kafka Producer or Topic?
I know that quotas are based on client-id. Basically I want to run the kafka-producer-perf-test with a particular client id to test whether the quotas work properly.

How can I assign a client-id for a particular producer (or) partition?

答:
When creating a producer, you can assign a unique value to client.id property

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "testclient001");
//set any additional properties.
Producer<String, GenericRecord> producer = new KafkaProducer<String, GenericRecord>(props);
```

ContentLicense: CC BY-SA 4.0


问:
CheckBoxList with a scrollbar
I know this would normally be an easy solution but in my case the situation may be a little different. I am making a control with C# client side code. This is included in a search panel. Everything I read says normally I could just wrap the CheckBoxList within a DIV tag. However, My search field automatically creates the table based upon what selectors I need. This is in a table format. You cannot have a div within a table. Is there anyway to override that table cell to allow scrolling? What are your suggestions?

I tried wrapping the checkboxlist in a div and limiting the height of the DIV and setting the overflow to auto and then scroll. First off, the scroll bars arent showing. This is because the checkboxlist still extends the table cell to fit the whole box.

答: Have you considered checking out the overflow CSS property and setting it to scroll ?

Title: CheckBoxList with a scrollbar

ContentLicense: CC BY-SA 2.5


问:
PayPal REST API billing plans & agreements (subscriptions)
I want to use the PayPal REST API to offer subscriptions on my website. According to the documentation a billing plan is required in order to create a billing agreement with a user.

While the documentation explains how to create billing plans/agreements, I still have a few questions which the documentation does not answer:

Is a billing plan used for multiple billing agreements? For example, you create a billing plan for each service on your website and let users subscribe to this.

Does each billing agreement need a new billing plan? (in contrast to the previous question)

If I delete a billing plan, does this also remove all dependent billing agreements?

答:
Pretty late answer but I am facing the same problem right now and found this link. The article is from 2014 but still can be useful because explains a little bit of what you are asking about. Reading it I think that billing plan can be used for multiple agreements. You just need to create the plan and then use the ID for agreements.

Anyway, I suggest you to use sandbox mode to test all features.

Also, if you found another answer which explains the mechanism better, please post it here.

Hope I could help.


问:
Does a es6 js export have to export a function?
I want to use the import keyword in a class. The data to import would be a simple object eg:

```<code>{
   test: 123,
   anothertest: 321
}
</code>```

I know i can write:

```<code>module.exports = {
  test: 123,
  anothertest: 321
}
</code>```

And then in the class i can just require the module

```<code>let data = require('./modulename')
</code>```

But how can i just write a simple export so in the class i can just write

```<code>import data from 'modulename'
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import demonstrates how to do this with a function but not a simple object.

答:
As simple as this:

```<code>const data = {
    test: 123,
    anothertest: 321
};

export default data;
</code>```

If you have more stuff to export, then you could export it like this:

```<code>const data = {
     test: 123,
     anothertest: 321
};

const stuff = {
     test: 464,
     another: 323
};

export { data, stuff };
</code>```

And then you can import it like this:

```<code>import { data, stuff } from './file';
</code>```

Body:
I want to use the import keyword in a class. The data to import would be a simple object eg:

{
   test: 123,
   anothertest: 321
}

I know i can write:

module.exports = {
  test: 123,
  anothertest: 321
}

And then in the class i can just require the module

let data = require('./modulename')

But how can i just write a simple export so in the class i can just write

import data from 'modulename'

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import demonstrates how to do this with a function but not a simple object.

Body:
As simple as this:

const data = {
    test: 123,
    anothertest: 321
};

export default data;

If you have more stuff to export, then you could export it like this:

const data = {
     test: 123,
     anothertest: 321
};

const stuff = {
     test: 464,
     another: 323
};

export { data, stuff };

And then you can import it like this:

import { data, stuff } from './file';


问:
Firebase - Filtering Query Data
I have a group of comments for different blog posts.

The problem now is every comment displays on every blog post.

Im calling the data with

```<code>myref= FirebaseDatabase.getInstance().getReference().child("comments");
</code>```

Which returns all comments.

This is the data JSON

```<code>    {
  "comments" : {
    "-KgnRe9d5s471yDWVYBk" : {
      "_id" : "56e35e39106a750e008c33b5",
      "_blogID" : "56ba5f6a894eeb0e008c86c0",
      "commentKey" : "-KgnRe9d5s471yDWVYBk",
      "detail" : "test comment",
      "user" : "john",
      "votes" : 0
    }
</code>```

Id like to filter all comments by "_blogID"

Thanks

答: You can use a Query like this: Query query = myref.child(commentKey).orderByChild("_blogID");

Title: Firebase - Filtering Query Data

Body:
I have a group of comments for different blog posts.

The problem now is every comment displays on every blog post.

Im calling the data with

myref= FirebaseDatabase.getInstance().getReference().child("comments");

Which returns all comments.

This is the data JSON

    {
  "comments" : {
    "-KgnRe9d5s471yDWVYBk" : {
      "_id" : "56e35e39106a750e008c33b5",
      "_blogID" : "56ba5f6a894eeb0e008c86c0",
      "commentKey" : "-KgnRe9d5s471yDWVYBk",
      "detail" : "test comment",
      "user" : "john",
      "votes" : 0
    }

Id like to filter all comments by "_blogID"

Thanks


问:
Edit existing items in a Wordpress theme
I've created a homepage, that simply has a sentence as the content

I've edited the settings so that this the front page of the website.

However, given the theme that I am using, when I go to the home page, this is what I see

I can see the content of my home page at the very bottom, but before that, there is a slider and a couple of blocks (that presumably come with the theme).

I'd like to know either how to remove these default blocks, or edit them myself to include links to other pages.

Also, as you can probably tell, I am very new to Wordpress. Are there any good documentations for beginners that would teach me how to create pages, edit and customize them so that I can have control over the whole page (as a regular website)?

答:
The html code you get above your content is inserted from the page template assigned to your homepage. Thus, if you want to modify it somehow you should go Editor Panel in Appearance Menu, then edit desired template. You can also create your own template with structure you actually want and assign it to that page.

As for a documentation, I think you're going to be good with the official one.


问:
Running a diffent code for each block of file
I have an output file from some numeric calculation. The output file looks like

aa ab ac ad ae   ┐

  ba bb bc bd be   ┘  Block of 5 strings

  0.5 1.2 0.3 aaa bbb  ┐

  0.2 8.2 3.3 ccc ddd  ┃ Block of 3 float + 2 string

  0.5 1.3 0.6 eee ggg  ┘

  0.11  0.444  0.333 0.777 0.88  ┐

  0.41  0.544  0.313 0.797 0.01 ┃

  0.11  0.447  0.333 0.777 0.88 ┃  Block of 6 float

  0.17  0.444  0.333 0.787 0.03 ┃

  0.11  0.444  0.333 0.777 0.88 ┘

which means, it forms block of some patterns. What I want to do is to read this file, and do some stuff for each block seperately.

For the simplest approach, I wrote the code like

```<code>file = open("myfile", "r")
for i, line in enumerate(file):
    if i <= 1:
        # do some stuff 1.
    elif 1< i <=4 :
        # do some stuff 2
    elif 4 < i :
        # do some stuff 3
file.close()
</code>```

and specify the line number manually whenever I run the program. The problem is that the line number of output file varies from file to file (but the pattern is same), and before I check it manually by eye, I don't know how long each block will be. What is the efficient approach handling this problem?

The size of each file is about 100~1000MB, and each contains about 500000~ 5000000 lines.

答:
```<code># -*- coding: utf-8 -*-
f = open("demo.txt","r")
data = f.readlines()
start = "┐"
end = "┘"
demo_temp_list =[]
final_list = []
for d in data:
    if start in d:
        demo_temp_list = []
        demo_temp_list.append(d)
    elif end in d:
        demo_temp_list.append(d)
        final_list.append(demo_temp_list)
    else:
        demo_temp_list.append(d)

for index,final_data in enumerate(final_list):
    print "Group ", index+1
    print final_data
    print "----------"
</code>```

output:

```<code>Group  1
['aa ab ac ad ae \xe2\x94\x90\n', 'ba bb bc bd be \xe2\x94\x98 Block of 5 strings\n']
----------
Group  2
['0.5 1.2 0.3 aaa bbb \xe2\x94\x90\n', '0.2 8.2 3.3 ccc ddd \xe2\x94\x83 Block of 3 float + 2 string\n', '0.5 1.3 0.6 eee ggg \xe2\x94\x98\n']
----------
Group  3
['0.11 0.444 0.333 0.777 0.88 \xe2\x94\x90\n', '0.41 0.544 0.313 0.797 0.01 \xe2\x94\x83\n', '0.11 0.447 0.333 0.777 0.88 \xe2\x94\x83 Block of 6 float\n', '0.17 0.444 0.333 0.787 0.03 \xe2\x94\x83\n', '0.11 0.444 0.333 0.777 0.88 \xe2\x94\x98']
----------
</code>```

Body:
I have an output file from some numeric calculation. The output file looks like

aa ab ac ad ae   ┐

  ba bb bc bd be   ┘  Block of 5 strings

  0.5 1.2 0.3 aaa bbb  ┐

  0.2 8.2 3.3 ccc ddd  ┃ Block of 3 float + 2 string

  0.5 1.3 0.6 eee ggg  ┘

  0.11  0.444  0.333 0.777 0.88  ┐

  0.41  0.544  0.313 0.797 0.01 ┃

  0.11  0.447  0.333 0.777 0.88 ┃  Block of 6 float

  0.17  0.444  0.333 0.787 0.03 ┃

  0.11  0.444  0.333 0.777 0.88 ┘

which means, it forms block of some patterns. What I want to do is to read this file, and do some stuff for each block seperately.

For the simplest approach, I wrote the code like

file = open("myfile", "r")
for i, line in enumerate(file):
    if i <= 1:
        # do some stuff 1.
    elif 1< i <=4 :
        # do some stuff 2
    elif 4 < i :
        # do some stuff 3
file.close()

and specify the line number manually whenever I run the program. The problem is that the line number of output file varies from file to file (but the pattern is same), and before I check it manually by eye, I don't know how long each block will be. What is the efficient approach handling this problem?

The size of each file is about 100~1000MB, and each contains about 500000~ 5000000 lines.

Body:
# -*- coding: utf-8 -*-
f = open("demo.txt","r")
data = f.readlines()
start = "┐"
end = "┘"
demo_temp_list =[]
final_list = []
for d in data:
    if start in d:
        demo_temp_list = []
        demo_temp_list.append(d)
    elif end in d:
        demo_temp_list.append(d)
        final_list.append(demo_temp_list)
    else:
        demo_temp_list.append(d)

for index,final_data in enumerate(final_list):
    print "Group ", index+1
    print final_data
    print "----------"

output:

Group  1
['aa ab ac ad ae \xe2\x94\x90\n', 'ba bb bc bd be \xe2\x94\x98 Block of 5 strings\n']
----------
Group  2
['0.5 1.2 0.3 aaa bbb \xe2\x94\x90\n', '0.2 8.2 3.3 ccc ddd \xe2\x94\x83 Block of 3 float + 2 string\n', '0.5 1.3 0.6 eee ggg \xe2\x94\x98\n']
----------
Group  3
['0.11 0.444 0.333 0.777 0.88 \xe2\x94\x90\n', '0.41 0.544 0.313 0.797 0.01 \xe2\x94\x83\n', '0.11 0.447 0.333 0.777 0.88 \xe2\x94\x83 Block of 6 float\n', '0.17 0.444 0.333 0.787 0.03 \xe2\x94\x83\n', '0.11 0.444 0.333 0.777 0.88 \xe2\x94\x98']
----------


问:
splitting List<Object> based on the value of a variable in that Object
I am trying to split my list into multiple smaller lists but don't know how i should do it.

```<code>List<Object> list = new List<Object>();
</code>```

This is my original list that contains the object Object. I am trying to split this list based on the variables of this Object.

example:

```<code>public class Object {
   string var1;
   int var2;
   int var3;
}
</code>```

lets say the list Object has 3 possible var1 ("yes","no","maybe") then i want 3 Lists where each list are all the objects that have "yes","no" or "maybe" as var1 (this can be a list of 100 objects long with each object being one of this string) (the amount of possibilities in var1 is not constant)

答:
Here you will have splitted list of your object. you can use group by your property of your class. something like.

```<code>var splittedList = list.GroupBy(c=>c.var1).Select(c => c.ToList()).ToList() ;
</code>```

Here splittedList is type of List<List<YourObject>>  So for your Yes, No, MayBe case it will return list of 3 List. and each of these three  will contains object with same var1 property

Body:
I am trying to split my list into multiple smaller lists but don't know how i should do it.

List<Object> list = new List<Object>();

This is my original list that contains the object Object. I am trying to split this list based on the variables of this Object.

example:

public class Object {
   string var1;
   int var2;
   int var3;
}

lets say the list Object has 3 possible var1 ("yes","no","maybe") then i want 3 Lists where each list are all the objects that have "yes","no" or "maybe" as var1 (this can be a list of 100 objects long with each object being one of this string) (the amount of possibilities in var1 is not constant)

Body:
Here you will have splitted list of your object. you can use group by your property of your class. something like.

var splittedList = list.GroupBy(c=>c.var1).Select(c => c.ToList()).ToList() ;

Here splittedList is type of List<List<YourObject>>  So for your Yes, No, MayBe case it will return list of 3 List. and each of these three  will contains object with same var1 property


问:
How to take full customer export from hybris
How can we take full hybris customer export.
i wrote an impex to export the data but there are 2 million records in database so impex is not working.Please suggest a way.</p>

答:
Maybe you can use virtualjdbc extension: https://help.hybris.com/6.3.0/hcd/8c7ec0628669101481ec9d2d8dbb3a7c.html

Also there is no limit with impex. This impex file will be smale after compression.


问:
Active Users SQL query
I'm trying to graph active users in a webapp. My database consists of two main tables, user and task. task has a user_id.

My definition of active users: is a user who has created more than 2 tasks within two weeks of a given end date.

So, I need an SQL query that gives me the number of active users between a given start and end date. I was able to do this by putting the query inside a loop, pulling the results each time, but I'd love to be able to do it in a single query.

The returned data should be something like:

```<code>Date         Count
2010-01-01   4
2010-01-02   3
2010-01-03   5
</code>```

Edit to clarify desired dataset.

答:
This is not for mysql but it could work (I am not sure of task_date + 14).

```<code>select *
from user u
where (select count(*) form task t where t.user_id = u.user_id and t.task_date + 14 > @end_date) > 2
</code>```

The inner query select count... gets the tasks for the user that have been created 14 or less days before the given end_date

Title: Active Users SQL query

Body:
I'm trying to graph active users in a webapp. My database consists of two main tables, user and task. task has a user_id.

My definition of active users: is a user who has created more than 2 tasks within two weeks of a given end date.

So, I need an SQL query that gives me the number of active users between a given start and end date. I was able to do this by putting the query inside a loop, pulling the results each time, but I'd love to be able to do it in a single query.

The returned data should be something like:

Date         Count
2010-01-01   4
2010-01-02   3
2010-01-03   5

Edit to clarify desired dataset.

Body:
This is not for mysql but it could work (I am not sure of task_date + 14).

select *
from user u
where (select count(*) form task t where t.user_id = u.user_id and t.task_date + 14 > @end_date) > 2

The inner query select count... gets the tasks for the user that have been created 14 or less days before the given end_date


问:
ServletFileUpload.parseRequest() wants RequestContext instead of HttpServletRequest request
i am writing a web app and i want to upload a file to the servlet.
i read that i can use ServletFileUpload.parseRequest(request)
it works on one computer.
but when i try to run the code on another computer i get an error that the function needs  RequestContext: ServletFileUpload.parseRequest(RequestContext)

on the computer that the function works with HttpServletRequest i see the function with RequestContext. but i don't use it

is there another way to upload files to servlet?

答:
You could try:

```<code>new ServletFileUpload().parseRequest(new ServletRequestContext(request));
</code>```

This change works on the latest apache tomcat (at least on 7.0.70, which I am using).

Body:
You could try:

new ServletFileUpload().parseRequest(new ServletRequestContext(request));

This change works on the latest apache tomcat (at least on 7.0.70, which I am using).


问:
How to add telerik RadOrgChart in wpf app
I want to know that, is it possible to add telerik's RadOrgChart control in wpf application?</p>

答:
I want to know that, is it possible to add telerik's RadOrgChart control in wpf application?

No. As far as I know RadOrgChart is an ASP.NET control

Is there any other telerik control for wpf with same functionality?

That would probably be the RadDiagram control: http://docs.telerik.com/devtools/wpf/controls/raddiagram/overview


问:
python subprocess for multiple command in one process
I am using subprocess to connect ssh session to remote host to execute multiple commands.

My current code:

```<code> import subprocess
 import sys

 HOST="admin@10.193.180.133"
 # Ports are handled in ~/.ssh/config since we use OpenSSH
 COMMAND1="network port show"
 ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND1],
                   shell=False,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
 result = ssh.stdout.readlines()
 if result == []:
     error = ssh.stderr.readlines()
     print >>sys.stderr, "ERROR: %s" % error
 else:
      resp=''.join(result)
      print(resp)
COMMAND2="network interface show"

 ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND2],
                   shell=False,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
 result = ssh.stdout.readlines()
 if result == []:
     error = ssh.stderr.readlines()
     print >>sys.stderr, "ERROR: %s" % error
 else:
     resp=''.join(result)
     print(resp)
</code>```

In above case my code asking me to enter password twice.

But what i want make is the password should be ask one time and multiple commands has to be execute.

Please help

答:
You are opening two connections in your code, so it's natural that you'll have to enter a password twice.

Instead, you can open one connection and pass multiple remote commands.

```<code>from __future__ import print_function,unicode_literals
import subprocess

sshProcess = subprocess.Popen(['ssh',
                               <remote client>],
                               stdin=subprocess.PIPE,
                               stdout = subprocess.PIPE,
                               universal_newlines=True,
                               bufsize=0)
sshProcess.stdin.write("ls .\n")
sshProcess.stdin.write("echo END\n")
sshProcess.stdin.write("uptime\n")
sshProcess.stdin.write("echo END\n")
sshProcess.stdin.close()
</code>```

see here for more details

Body:
I am using subprocess to connect ssh session to remote host to execute multiple commands.

My current code:

 import subprocess
 import sys

 HOST="admin@10.193.180.133"
 # Ports are handled in ~/.ssh/config since we use OpenSSH
 COMMAND1="network port show"
 ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND1],
                   shell=False,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
 result = ssh.stdout.readlines()
 if result == []:
     error = ssh.stderr.readlines()
     print >>sys.stderr, "ERROR: %s" % error
 else:
      resp=''.join(result)
      print(resp)
COMMAND2="network interface show"

 ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND2],
                   shell=False,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
 result = ssh.stdout.readlines()
 if result == []:
     error = ssh.stderr.readlines()
     print >>sys.stderr, "ERROR: %s" % error
 else:
     resp=''.join(result)
     print(resp)

In above case my code asking me to enter password twice.

But what i want make is the password should be ask one time and multiple commands has to be execute.

Please help

Body:
You are opening two connections in your code, so it's natural that you'll have to enter a password twice.

Instead, you can open one connection and pass multiple remote commands.

from __future__ import print_function,unicode_literals
import subprocess

sshProcess = subprocess.Popen(['ssh',
                               <remote client>],
                               stdin=subprocess.PIPE,
                               stdout = subprocess.PIPE,
                               universal_newlines=True,
                               bufsize=0)
sshProcess.stdin.write("ls .\n")
sshProcess.stdin.write("echo END\n")
sshProcess.stdin.write("uptime\n")
sshProcess.stdin.write("echo END\n")
sshProcess.stdin.close()

see here for more details


问:
Pass data from the Activity to SurfaceView
I'm not sure where the problem is. I thought if the activity would pass information to the surfaceview it implements. Basically I'm trying to make it so that when someone selects their choice of game layout from the main menu (passes it with Intent) it then goes to the PlayGame class. (I have it take the number given from the intent). That activity uses SurfaceView through a layout. Then down  in the surface view where it calls the images and assigns them I tried using an if else to determine which pictures it should be using. Didn't work. Not exactly sure what to do about it. If there is a better way to make it use the images from a previous selection on the main page. Looks like this.

Main Class (Just one of the buttons passing in intent)

```<code>Button surfButton = (Button) findViewById(R.id.play1_btn);
    surfButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View surfing)
        {
            Intent play = new Intent(Main.this, PlayGame.class);
            play.putExtra("gameType" , 1);
            startActivity(play);
        }
    });
</code>```

PlayGame Class

```<code> @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent typ = getIntent();
    type = typ.getIntExtra("gameType", 0);

    setContentView(R.layout.game);
    gameLoopView = (GameLoopView) findViewById(R.id.gnarlyned);

}
</code>```

Game Class:

```<code>private void loadImages(Context context) {
            type = playGame.type;
    Resources res = context.getResources();

    if (type == 1){
        skyImage = BitmapFactory.decodeResource(res, R.drawable.sky);

    }
    else if (type == 2){
        skyImage = BitmapFactory.decodeResource(res, R.drawable.snowbg);

    }
</code>```

More images than just one, but to save space it's just the one. Any help would be appreciated. I'm sure I must have done something wrong there.

EDIT: Here is the log cat from the force close caused from this setup.

06-06 17:55:01.655: ERROR/AndroidRuntime(16229): FATAL EXCEPTION: main
06-06 17:55:01.655: ERROR/AndroidRuntime(16229): java.lang.RuntimeException: Unable to start activity ComponentInfo{fallacystudios.gnarlyned/fallacystudios.gnarlyned.PlayGame}: android.view.InflateException: Binary XML file line #7: Error inflating class fallacystudios.gnarlyned.GameLoopView
06-06 17:55:01.655: ERROR/AndroidRuntime(16229):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
06-06 17:55:01.655: ERROR/AndroidRuntime(16229): Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fallacystudios.gnarlyned.GameLoopView
06-06 17:55:01.655: ERROR/AndroidRuntime(16229): Caused by: java.lang.reflect.InvocationTargetException
06-06 17:55:01.655: ERROR/AndroidRuntime(16229): Caused by: java.lang.NullPointerException

Then a whole bunch of heap size overflow

All this only happens when I have the if(gameType == 1) and else if(gameType == 2) in the loadImages section. Doing this to make it so only certain images are used when that map is selected. Not sure why that doesnt work.

答: set type to public static in PlayGame Class and call intent extra before calling setContentView as Ted Hopp mentioned.

Body:
I'm not sure where the problem is. I thought if the activity would pass information to the surfaceview it implements. Basically I'm trying to make it so that when someone selects their choice of game layout from the main menu (passes it with Intent) it then goes to the PlayGame class. (I have it take the number given from the intent). That activity uses SurfaceView through a layout. Then down  in the surface view where it calls the images and assigns them I tried using an if else to determine which pictures it should be using. Didn't work. Not exactly sure what to do about it. If there is a better way to make it use the images from a previous selection on the main page. Looks like this.

Main Class (Just one of the buttons passing in intent)

Button surfButton = (Button) findViewById(R.id.play1_btn);
    surfButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View surfing)
        {
            Intent play = new Intent(Main.this, PlayGame.class);
            play.putExtra("gameType" , 1);
            startActivity(play);
        }
    });

PlayGame Class

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent typ = getIntent();
    type = typ.getIntExtra("gameType", 0);

    setContentView(R.layout.game);
    gameLoopView = (GameLoopView) findViewById(R.id.gnarlyned);

}

Game Class:

private void loadImages(Context context) {
            type = playGame.type;
    Resources res = context.getResources();

    if (type == 1){
        skyImage = BitmapFactory.decodeResource(res, R.drawable.sky);

    }
    else if (type == 2){
        skyImage = BitmapFactory.decodeResource(res, R.drawable.snowbg);

    }

More images than just one, but to save space it's just the one. Any help would be appreciated. I'm sure I must have done something wrong there.

EDIT: Here is the log cat from the force close caused from this setup.

06-06 17:55:01.655: ERROR/AndroidRuntime(16229): FATAL EXCEPTION: main
06-06 17:55:01.655: ERROR/AndroidRuntime(16229): java.lang.RuntimeException: Unable to start activity ComponentInfo{fallacystudios.gnarlyned/fallacystudios.gnarlyned.PlayGame}: android.view.InflateException: Binary XML file line #7: Error inflating class fallacystudios.gnarlyned.GameLoopView
06-06 17:55:01.655: ERROR/AndroidRuntime(16229):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
06-06 17:55:01.655: ERROR/AndroidRuntime(16229): Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fallacystudios.gnarlyned.GameLoopView
06-06 17:55:01.655: ERROR/AndroidRuntime(16229): Caused by: java.lang.reflect.InvocationTargetException
06-06 17:55:01.655: ERROR/AndroidRuntime(16229): Caused by: java.lang.NullPointerException

Then a whole bunch of heap size overflow

All this only happens when I have the if(gameType == 1) and else if(gameType == 2) in the loadImages section. Doing this to make it so only certain images are used when that map is selected. Not sure why that doesnt work.


问:
How to insert json output into mysql with node js
```<code>var express = require('express');
var fs = require('fs');
var mysql = require('mysql');
var request = require('request');
var cheerio = require('cheerio');
var bodyParser = require('body-parser');
var app     = express();

var output;
app.use(bodyParser.json())

app.get('/scrape', function(req, res){
    url = 'https://raitalumni.dypatil.edu/events/?tag=live';

    request(url, function(error, response, html){
        if(!error){
            var $ = cheerio.load(html);
            var json = {
                            title : [],
                            date  : [],
                            month : [],
                            venue : [],
                            link : []
                       };
             output = {
                            events : []
                         };

            $('p.event_name').each(function(){
                json.title.push($(this).text());
            });

            $('p.calendar_date').each(function(){
                json.date.push($(this).text());
            });

            $('span.calendar_month').each(function(){
                json.month.push($(this).text());
            });

            //var fulldate = $('p.calendar_date').concat($('p.calendar_day')).text();
            //console.log('all records: ' + fulldate);

            $('p.event_venue').each(function(){
                json.venue.push($(this).text());
            });

        // var title = $('p.event_name').each(function(){$(this).text()});

            for(var i=0; i<json.title.length; i++){
                output.events[i] = {
                    title : json.title[i],
                    date : json.date[i],
                    month : json.month[i],
                    venue : json.venue[i],
                    link : url
                }
            }

         var connection = mysql.createConnection({
        host: '127.0.0.1',
        port: 3306,
        user: 'root',
        password: '',
        database: 'raithub'
    });

connection.connect(function(error){
   if(!!error){
      console.log('Error');
   }else{
      console.log('Connected to the database!');
   }
});

       var scrape = JSON.stringify(output, null, 4);
       console.log(scrape);

       var query = connection.query("INSERT INTO scrapped ('title','date','month','venue','link') VALUES ('" + output.title + "', '" + output.date + "', '" + output.month + "', '" + output.venue + "', '" + output.link + "');", scrape, function(err, result) {
     if(err) throw err;
     console.log('data inserted');
});

            fs.writeFile('output4.json', JSON.stringify(output, null, 4), function(err){
                console.log('File successfully written! - Check your project directory for the output.json file');
            })

            res.send('Check your console!')
        }
        else {
            console.log("Network Error, please try again later")
        }
    })
})

app.listen('8000')
console.log('Server running on port 8081');
exports = module.exports = app;
</code>```

Where am I going wrong?

Getting this error,

```<code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''title','date','month','venue','li
nk') VALUES ('undefined', 'undefined', 'undefi' at line 1 error
</code>```

答:
The INSERT statement should look this:

```<code>INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
</code>```

where the column names should not be in quotes. Your specific statement would like this:

```<code>    var query = connection.query("INSERT INTO scrapped (title,date,month,venue,link) VALUES ('" + output.title + "', '" + output.date + "', '" + output.month + "', '" + output.venue + "', '" + output.link + "');", scrape, function(err, result) {
     if(err) throw err;
     console.log('data inserted');
});
</code>```

See this for the right syntax

Body:
var express = require('express');
var fs = require('fs');
var mysql = require('mysql');
var request = require('request');
var cheerio = require('cheerio');
var bodyParser = require('body-parser');
var app     = express();

var output;
app.use(bodyParser.json())

app.get('/scrape', function(req, res){
    url = 'https://raitalumni.dypatil.edu/events/?tag=live';

    request(url, function(error, response, html){
        if(!error){
            var $ = cheerio.load(html);
            var json = {
                            title : [],
                            date  : [],
                            month : [],
                            venue : [],
                            link : []
                       };
             output = {
                            events : []
                         };

            $('p.event_name').each(function(){
                json.title.push($(this).text());
            });

            $('p.calendar_date').each(function(){
                json.date.push($(this).text());
            });

            $('span.calendar_month').each(function(){
                json.month.push($(this).text());
            });

            //var fulldate = $('p.calendar_date').concat($('p.calendar_day')).text();
            //console.log('all records: ' + fulldate);

            $('p.event_venue').each(function(){
                json.venue.push($(this).text());
            });

        // var title = $('p.event_name').each(function(){$(this).text()});

            for(var i=0; i<json.title.length; i++){
                output.events[i] = {
                    title : json.title[i],
                    date : json.date[i],
                    month : json.month[i],
                    venue : json.venue[i],
                    link : url
                }
            }

         var connection = mysql.createConnection({
        host: '127.0.0.1',
        port: 3306,
        user: 'root',
        password: '',
        database: 'raithub'
    });

connection.connect(function(error){
   if(!!error){
      console.log('Error');
   }else{
      console.log('Connected to the database!');
   }
});

       var scrape = JSON.stringify(output, null, 4);
       console.log(scrape);

       var query = connection.query("INSERT INTO scrapped ('title','date','month','venue','link') VALUES ('" + output.title + "', '" + output.date + "', '" + output.month + "', '" + output.venue + "', '" + output.link + "');", scrape, function(err, result) {
     if(err) throw err;
     console.log('data inserted');
});

            fs.writeFile('output4.json', JSON.stringify(output, null, 4), function(err){
                console.log('File successfully written! - Check your project directory for the output.json file');
            })

            res.send('Check your console!')
        }
        else {
            console.log("Network Error, please try again later")
        }
    })
})

app.listen('8000')
console.log('Server running on port 8081');
exports = module.exports = app;

Where am I going wrong?

Getting this error,

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''title','date','month','venue','li
nk') VALUES ('undefined', 'undefined', 'undefi' at line 1 error

Body:
The INSERT statement should look this:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

where the column names should not be in quotes. Your specific statement would like this:

    var query = connection.query("INSERT INTO scrapped (title,date,month,venue,link) VALUES ('" + output.title + "', '" + output.date + "', '" + output.month + "', '" + output.venue + "', '" + output.link + "');", scrape, function(err, result) {
     if(err) throw err;
     console.log('data inserted');
});

See this for the right syntax


问:
Is it possible to automate excel from a java applet running in full trust?
I'm looking at all possible languages to solve a particular business case problem.

Basically need a way to allow user to browse for an excel file locally, then using Microsoft Excel COM automation, read in the cell contents and from this point on perform some actions.

I have no experience with Java, but I know this type of thing is "almost" possible using Silverlight 4.0. Here is a line of code that demonstates how you begin automation in silverlight using c#:

```<code>dynamic objExcel = AutomationFactory.CreateObject("Excel.Application");
</code>```

Problem is Silverlight only opens files from "My Documents", and it seems there is nothing you can do to allow the app full access to the file system to read in any file. So I'm investigating if Java is capable of this task?

I don't need a big explanation on how to do it, mainly I just need your experience as a Java developer to say - Yes in principle its certainly possible, or not. I need to open this xls file from any location the user specifies.

So 2 things really:

Can you browse and open any file using a trusted java applet? And get access to the files path from the open dialog?

Can you automate MS Word / Excel from a Java applet.

Thanks

答:
..Silverlight only opens files from "My Documents", ..

Java will not be able to break that security restriction.

It is for the benefit of the end user, in that if they truly want to edit the Excel file, they will save or move it to My Documents.  If they cannot do that, then perhaps they should not be altering the file.

Body:
I'm looking at all possible languages to solve a particular business case problem.

Basically need a way to allow user to browse for an excel file locally, then using Microsoft Excel COM automation, read in the cell contents and from this point on perform some actions.

I have no experience with Java, but I know this type of thing is "almost" possible using Silverlight 4.0. Here is a line of code that demonstates how you begin automation in silverlight using c#:

dynamic objExcel = AutomationFactory.CreateObject("Excel.Application");

Problem is Silverlight only opens files from "My Documents", and it seems there is nothing you can do to allow the app full access to the file system to read in any file. So I'm investigating if Java is capable of this task?

I don't need a big explanation on how to do it, mainly I just need your experience as a Java developer to say - Yes in principle its certainly possible, or not. I need to open this xls file from any location the user specifies.

So 2 things really:

Can you browse and open any file using a trusted java applet? And get access to the files path from the open dialog?

Can you automate MS Word / Excel from a Java applet.

Thanks


问:
How to measure time taken by a function to execute
I need to get execution time in milliseconds.

I originally asked this question back in 2008. The accepted answer then was to use new Date().getTime() However, we can all agree now  that using the standard performance.now() API is more appropriate. I am therefore changing the accepted answer to this one.

答:
This is a Timer function. If you want to measure the time between multiple things that aren't nested:

```<code>function timer(lap){
    if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
    timer.prev = performance.now();
}
</code>```

Similar to console.time(), but easier usage if you don't need to keep track of previous timers.

Usage:

```<code>timer()              // set the start
// do something
timer('built')       // logs 'built in: 591.815ms'
// do something
timer('copied')      // logs 'copied in: 0.065ms'
// do something
timer('compared')    // logs 'compared in: 36.41ms'
</code>```

If you like the blue color from console.time(), you can use this line instead

```<code>console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');
</code>```

OwnerDisplayName: Jangwenyi

LastEditorDisplayName: Rob

Body:
This is a Timer function. If you want to measure the time between multiple things that aren't nested:

function timer(lap){
    if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
    timer.prev = performance.now();
}

Similar to console.time(), but easier usage if you don't need to keep track of previous timers.

Usage:

timer()              // set the start
// do something
timer('built')       // logs 'built in: 591.815ms'
// do something
timer('copied')      // logs 'copied in: 0.065ms'
// do something
timer('compared')    // logs 'compared in: 36.41ms'

If you like the blue color from console.time(), you can use this line instead

console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');


问:
Collection view Cells redirecting different ViewController
I Have UICollectionView with Sections. Each Sections have variable cells which is defined by array count. I have declared array of strings for each section in viewDidLoad function.

I want each cell to open a New UIViewController on click of respective cell. How do i get the above result.

I am using Swift3 for coding.

```<code>class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectView: UICollectionView!

    var sectionHeader = [String] ()

    var sectionArr = [Any] ()
    var enquire = [String] ()
    var serviceRequest = [String] ()
    var missedCall = [String] ()
    var settings = [String] ()

    var arr = [String] ()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        sectionHeader = ["Enquire","Service Request","Missed Call Recharge","Settings"]

        enquire = ["Balance Enquiry","Mini Statement","Account Statement","Cheque Status Enquiry","Fixed Deposit Enquiry"]
        serviceRequest = ["Stop Cheque Payment","Cheque Book Request","iPIN Regeneration"]
        missedCall = ["Activate","Deactivate","Set Recharge Amount","Recharge"]
        settings = ["Change Primary Account","Register"]

        sectionArr = [enquire,serviceRequest,missedCall,settings]

        collectView.dataSource = self
        collectView.delegate = self

        collectView.reloadData()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func loadCollectionView(_ sender: Any) {
        collectView.reloadData()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionArr.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (section == 0) {
            return enquire.count
        }
        else if (section == 1) {
            return serviceRequest.count
        }
        else if (section == 2) {
            return missedCall.count
        }
        else {
            return self.settings.count
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let mycell:CustomCell = collectView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CustomCell

        arr = sectionArr[indexPath.section] as! [String]

        let imagename = arr[indexPath.row]

        let modified = imagename.replacingOccurrences(of: " ", with: "_")

        let modified_imagename = modified + ".png"

        mycell.functionalityImage.image = UIImage(named : modified_imagename)
        mycell.functionalityName.text = arr[indexPath.row]

        return mycell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        arr = sectionArr[indexPath.section] as! [String]

        showAlert(mesgTitle: "SELECTED CELL", mesgText: arr[indexPath.row])
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        var reusea:UICollectionReusableView? = nil

        if (kind == UICollectionElementKindSectionHeader) {

            let header:HeaderTextHome = collectView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header_Text", for: indexPath) as! HeaderTextHome

            header.headerText.text = sectionHeader[indexPath.section ]

            reusea = header

        }
        return reusea!
    }

    func showAlert(mesgTitle : String, mesgText : String) {

        let alertController = UIAlertController(title: mesgTitle, message: mesgText, preferredStyle: UIAlertControllerStyle.alert)

        let defaultAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)

        let cancleAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)

        alertController.addAction(defaultAction)
        alertController.addAction(cancleAction)

        present(alertController, animated: true, completion: nil)

    }

}
</code>```

Above code i display an alert on click.

答:
If you are using segue then Set up All viewController segue in storyboard then use bellow code.

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        arr = sectionArr[indexPath.section] as! [String]
        let viewControllerIdentifire = arr[indexPath.item]
        self.performSegue(withIdentifier: viewControllerIdentifire, sender: IfYouWantToPassDataThanPutHereElseNil)
        //    showAlert(mesgTitle: "SELECTED CELL", mesgText: arr[indexPath.row])
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "Enquire" {
            let vc = segue.destinationViewController as! EnquireViewController
            vc.data = sender // if you want to pass data to viewCotroller
        }
    }
</code>```

Body:
I Have UICollectionView with Sections. Each Sections have variable cells which is defined by array count. I have declared array of strings for each section in viewDidLoad function.

I want each cell to open a New UIViewController on click of respective cell. How do i get the above result.

I am using Swift3 for coding.

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectView: UICollectionView!

    var sectionHeader = [String] ()

    var sectionArr = [Any] ()
    var enquire = [String] ()
    var serviceRequest = [String] ()
    var missedCall = [String] ()
    var settings = [String] ()

    var arr = [String] ()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        sectionHeader = ["Enquire","Service Request","Missed Call Recharge","Settings"]

        enquire = ["Balance Enquiry","Mini Statement","Account Statement","Cheque Status Enquiry","Fixed Deposit Enquiry"]
        serviceRequest = ["Stop Cheque Payment","Cheque Book Request","iPIN Regeneration"]
        missedCall = ["Activate","Deactivate","Set Recharge Amount","Recharge"]
        settings = ["Change Primary Account","Register"]

        sectionArr = [enquire,serviceRequest,missedCall,settings]

        collectView.dataSource = self
        collectView.delegate = self

        collectView.reloadData()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func loadCollectionView(_ sender: Any) {
        collectView.reloadData()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionArr.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (section == 0) {
            return enquire.count
        }
        else if (section == 1) {
            return serviceRequest.count
        }
        else if (section == 2) {
            return missedCall.count
        }
        else {
            return self.settings.count
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let mycell:CustomCell = collectView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! CustomCell

        arr = sectionArr[indexPath.section] as! [String]

        let imagename = arr[indexPath.row]

        let modified = imagename.replacingOccurrences(of: " ", with: "_")

        let modified_imagename = modified + ".png"

        mycell.functionalityImage.image = UIImage(named : modified_imagename)
        mycell.functionalityName.text = arr[indexPath.row]

        return mycell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        arr = sectionArr[indexPath.section] as! [String]

        showAlert(mesgTitle: "SELECTED CELL", mesgText: arr[indexPath.row])
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        var reusea:UICollectionReusableView? = nil

        if (kind == UICollectionElementKindSectionHeader) {

            let header:HeaderTextHome = collectView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header_Text", for: indexPath) as! HeaderTextHome

            header.headerText.text = sectionHeader[indexPath.section ]

            reusea = header

        }
        return reusea!
    }

    func showAlert(mesgTitle : String, mesgText : String) {

        let alertController = UIAlertController(title: mesgTitle, message: mesgText, preferredStyle: UIAlertControllerStyle.alert)

        let defaultAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)

        let cancleAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)

        alertController.addAction(defaultAction)
        alertController.addAction(cancleAction)

        present(alertController, animated: true, completion: nil)

    }

}

Above code i display an alert on click.

Body:
If you are using segue then Set up All viewController segue in storyboard then use bellow code.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        arr = sectionArr[indexPath.section] as! [String]
        let viewControllerIdentifire = arr[indexPath.item]
        self.performSegue(withIdentifier: viewControllerIdentifire, sender: IfYouWantToPassDataThanPutHereElseNil)
        //    showAlert(mesgTitle: "SELECTED CELL", mesgText: arr[indexPath.row])
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "Enquire" {
            let vc = segue.destinationViewController as! EnquireViewController
            vc.data = sender // if you want to pass data to viewCotroller
        }
    }


问:
Return sub-document from nested list based on multiple match criteria
Hi I have the following document, I want to extract message from messagelist based on multiple criteria.

```<code>{
"_id" : ObjectId("58df770371043e7087cdaadd"),
"prospectemailid" : "abc@gmail.com",
"prospectid" : "1491038545032",
"useremail" : "xyz@gmail.com",
"threadidslist" : [
    {
        "threadid" : "15b28e8e711f71b0",
        "subject" : "sub",
        "campaignid" : "1491460056589",
        "messagelist" : [
            {
                "emailuniqueid" : "1492376430400",
                "messageid" : "15b28e8e711f71b0",
                "timestamp" : "Sat Apr 01 15:16:43 IST 2017",
                "from" : "utsavanand.work@gmail.com",
                "body" : "Hello",
                "labelid" : "SENT",
                "to" : "anuragkv10@gmail.com",
                "messageidpayload" : ""
            },
            {
                "emailuniqueid" : "1492376430400",
                "messageid" : "15b28ecbcbe5b32d",
                "timestamp" : "Sat Apr 01 15:20:54 IST 2017",
                "from" : "anuragkv10@gmail.com",
                "body" : "Hi",
                "labelid" : "RECEIVED",
                "to" : "utsavanand.work@gmail.com",
                "messageidpayload" : "<CAL_CU77Rc27peuGde=WTC7waW3gfvS2Wr_t2A+7KBjjxsKW8Sw@mail.gmail.com>"
            }
        ]
    }
]
</code>```

}

Expected output based on
Criteria : prospectemailid=1491038545032,useremail=xyz@gmail.com,threadidslist.campaignid=1491460056589 and messagelist.emailuniqueid= 1492376430400 is

```<code>{
               "emailuniqueid" : "1492376430400",
                "messageid" : "15b28ecbcbe5b32d",
                "timestamp" : "Sat Apr 01 15:20:54 IST 2017",
                "from" : "sad@gmail.com",
                "body" : "Hi",
                "labelid" : "RECEIVED",
                "to" : asd@gmail.com",
                "messageidpayload" : "<CAL_CU77Rc27peuGde=WTC7waW3gfvS2Wr_t2A+7KBjjxsKW8Sw@mail.gmail.com>"
 }
</code>```

Thanks..!

So far i have tried:

```<code>db.getCollection('GD').aggregate(
[

   { $match:{
        "prospectid" : "1491038545032",
        "useremail" : "xyz@gmail.com",
        "threadidslist.campaignid" : "1491460056589",
        "threadidslist.messagelist.emailuniqueid" : "1492376430400"
    }

}
])
</code>```

答:
Use the $arrayElemAt and $filter operators in a $project pipeline to get the filtered nested array. The $replaceRoot pipeline will promote the filtered subdocument to the top level and replaces all other fields.

Consider running the following pipeline to get the desired result:

```<code>db.GD.aggregate([
    { "$match": {
        "prospectid" : "1491038545032",
        "useremail" : "xyz@gmail.com",
        "threadidslist.campaignid" : "1491460056589",
        "threadidslist.messagelist.emailuniqueid" : "1492376430400"
    } },
    { "$project": {
        "threadidslist": {
            "$arrayElemAt": [
                {
                    "$filter": {
                        "input": "$threadidslist",
                        "as": "thread",
                        "cond": { "$eq": ["$$thread.campaignid", "1491460056589"] }
                    }
                },
                0
            ]
        }
    } },
    { "$project": {
        "messagelist": {
            "$arrayElemAt": [
                {
                    "$filter": {
                        "input": "$threadidslist.messagelist",
                        "as": "msg",
                        "cond": { "$eq": ["$$msg.emailuniqueid", "1492376430400"] }
                    }
                },
                0
            ]
        }
    } },
    { "$replaceRoot": { "newRoot": "$messagelist" } }
])
</code>```

Body:
Hi I have the following document, I want to extract message from messagelist based on multiple criteria.

{
"_id" : ObjectId("58df770371043e7087cdaadd"),
"prospectemailid" : "abc@gmail.com",
"prospectid" : "1491038545032",
"useremail" : "xyz@gmail.com",
"threadidslist" : [
    {
        "threadid" : "15b28e8e711f71b0",
        "subject" : "sub",
        "campaignid" : "1491460056589",
        "messagelist" : [
            {
                "emailuniqueid" : "1492376430400",
                "messageid" : "15b28e8e711f71b0",
                "timestamp" : "Sat Apr 01 15:16:43 IST 2017",
                "from" : "utsavanand.work@gmail.com",
                "body" : "Hello",
                "labelid" : "SENT",
                "to" : "anuragkv10@gmail.com",
                "messageidpayload" : ""
            },
            {
                "emailuniqueid" : "1492376430400",
                "messageid" : "15b28ecbcbe5b32d",
                "timestamp" : "Sat Apr 01 15:20:54 IST 2017",
                "from" : "anuragkv10@gmail.com",
                "body" : "Hi",
                "labelid" : "RECEIVED",
                "to" : "utsavanand.work@gmail.com",
                "messageidpayload" : "<CAL_CU77Rc27peuGde=WTC7waW3gfvS2Wr_t2A+7KBjjxsKW8Sw@mail.gmail.com>"
            }
        ]
    }
]

}

Expected output based on
Criteria : prospectemailid=1491038545032,useremail=xyz@gmail.com,threadidslist.campaignid=1491460056589 and messagelist.emailuniqueid= 1492376430400 is

{
               "emailuniqueid" : "1492376430400",
                "messageid" : "15b28ecbcbe5b32d",
                "timestamp" : "Sat Apr 01 15:20:54 IST 2017",
                "from" : "sad@gmail.com",
                "body" : "Hi",
                "labelid" : "RECEIVED",
                "to" : asd@gmail.com",
                "messageidpayload" : "<CAL_CU77Rc27peuGde=WTC7waW3gfvS2Wr_t2A+7KBjjxsKW8Sw@mail.gmail.com>"
 }

Thanks..!

So far i have tried:

db.getCollection('GD').aggregate(
[

   { $match:{
        "prospectid" : "1491038545032",
        "useremail" : "xyz@gmail.com",
        "threadidslist.campaignid" : "1491460056589",
        "threadidslist.messagelist.emailuniqueid" : "1492376430400"
    }

}
])

Body:
Use the $arrayElemAt and $filter operators in a $project pipeline to get the filtered nested array. The $replaceRoot pipeline will promote the filtered subdocument to the top level and replaces all other fields.

Consider running the following pipeline to get the desired result:

db.GD.aggregate([
    { "$match": {
        "prospectid" : "1491038545032",
        "useremail" : "xyz@gmail.com",
        "threadidslist.campaignid" : "1491460056589",
        "threadidslist.messagelist.emailuniqueid" : "1492376430400"
    } },
    { "$project": {
        "threadidslist": {
            "$arrayElemAt": [
                {
                    "$filter": {
                        "input": "$threadidslist",
                        "as": "thread",
                        "cond": { "$eq": ["$$thread.campaignid", "1491460056589"] }
                    }
                },
                0
            ]
        }
    } },
    { "$project": {
        "messagelist": {
            "$arrayElemAt": [
                {
                    "$filter": {
                        "input": "$threadidslist.messagelist",
                        "as": "msg",
                        "cond": { "$eq": ["$$msg.emailuniqueid", "1492376430400"] }
                    }
                },
                0
            ]
        }
    } },
    { "$replaceRoot": { "newRoot": "$messagelist" } }
])


问:
XPATH required for an input text field?
i have a text box in my web application,Where i need to give input. I am trying to find the xpath of the text box. the following error is thrown.

Unable to locate element: {"method":"xpath","selector":"

HTML code:

```<code><div class="input">
<input id="firstName" class="long" type="text" maxlength="50" value="" name="firstName
</code>```

I want the xpath for firstName textbox.

答:
```<code>//*[text()[contains(.,'firstName')]]
</code>```

finding by text would always work.

Title: XPATH required for an input text field?

Body:
i have a text box in my web application,Where i need to give input. I am trying to find the xpath of the text box. the following error is thrown.

Unable to locate element: {"method":"xpath","selector":"

HTML code:

<input id="firstName" class="long" type="text" maxlength="50" value="" name="firstName

I want the xpath for firstName textbox.

Body:
//*[text()[contains(.,'firstName')]]

finding by text would always work.


问:
How to check if node is empty
I'm trying to make a variable, which tells me, whether node1 has something in it or not. node1 can be an empty element  or it may contain an attribute. But right now I would like to know how achieve answer "false" when the node1 is empty .</p>

```<code><xsl:variable name="elementHasData">
    <xsl:choose>
        <xsl:when test="node1 != ''">
            <xsl:value-of select="true()"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="false()"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:variable>
</code>```

答:
You can try this in XSLT 2.0:

```<code><xsl:variable name="elementHasData" select="if (node1[node()]) then 'true()' else 'false()'"/>
</code>```

Title: How to check if node is empty

Body:
I'm trying to make a variable, which tells me, whether node1 has something in it or not. node1 can be an empty element  or it may contain an attribute. But right now I would like to know how achieve answer "false" when the node1 is empty .

<xsl:variable name="elementHasData">
    <xsl:choose>
        <xsl:when test="node1 != ''">
            <xsl:value-of select="true()"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="false()"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:variable>

Body:
You can try this in XSLT 2.0:

<xsl:variable name="elementHasData" select="if (node1[node()]) then 'true()' else 'false()'"/>


问:
Is string.ElementAt() O(1)?
Under remarks, it says

If the type of source implements IList, that implementation is used to obtain the element at the specified index. Otherwise, this method obtains the specified element.

String does not implement IList<T>. Does that mean this will be an O(n) operation if I declare something like,

```<code>IEnumerable<char> myString = "stringy";
</code>```

?

答: ElementAt when applied to a type which is a string will be an O(N) operation.  It does not implement IList<char> and hence ElementAt won't do any optimizations on it and instead enumerates through the IEnumerable<char> until it reaches the specified index.

Title: Is string.ElementAt() O(1)?

Body:
Under remarks, it says

If the type of source implements IList, that implementation is used to obtain the element at the specified index. Otherwise, this method obtains the specified element.

String does not implement IList<T>. Does that mean this will be an O(n) operation if I declare something like,

IEnumerable<char> myString = "stringy";

?


问:
Using ClickOnce API without installation
I have a Winforms application. I have published it using ClickOnce. But my requirement is to use the ClickOnce API in the forms application without installing the published installer on the client side. I found that ApplicationDeployment.IsNetworkDeployedproperty has to be used for this. But every time I run the application, this property returns false. I am not able to use any ClickOnce APIs.

Am I missing something? What should I do to use the ClickOnce APIs without installing the application?

Please share your thoughts.

Thanks in Advance.

答:
ApplicationDeployment.IsNetworkDeployed will be true when the application has been installed on the machine and has been started using the .appref-ms reference created by ClickOnce during the installation. Otherwise it is false.

There is no way to use the API (i.e. ApplicationDeployment.CurrentDeployment) without installing the application as there simply is no current deployment available.


问:
Firebase adapter populateViewHolder() is never called
activity layout :

android:layout_height="match_parent"

```<code>    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_list_tasks2"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_list_tasks"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

   ... something else...

    </RelativeLayout>
</code>```

activity class :

rv.setHasFixedSize(true);

```<code>public class AdminActivity2 extends AppCompatActivity {

    RecyclerView rv;

    private DatabaseReference myRef;

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admin_activity);

        rv = (RecyclerView) findViewById(R.id.rv_list_tasks);

        myRef = FirebaseDatabase.getInstance().getReference();

        FirebaseRecyclerAdapter<Machinist, AdminActivity2.MachinistsViewHolder2> adapter;
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(llm);
        rv.setHasFixedSize(true);
        rv.post(this::supportStartPostponedEnterTransition);
        Query query = myRef.child("Машинисты").orderByChild("points/itogo");

        adapter = new FirebaseRecyclerAdapter<Machinist, MachinistsViewHolder2>(
                Machinist.class,
                R.layout.machinist_item,
                MachinistsViewHolder2.class,
                query){

            @Override
            public void onBindViewHolder(MachinistsViewHolder2 viewHolder, int position) {

            }

            @Override
            protected void populateViewHolder(MachinistsViewHolder2 viewHolder, Machinist model, int position) {

                Log.d("djuyf", "populate");

                Typeface mTypeface;
                mTypeface = Typeface.create("sans-serif-regular", Typeface.NORMAL);

                DatabaseReference itemRef = getRef(position);

                viewHolder.cvRemove.setOnClickListener(view -> {
                    AlertDialog diaBox = askOption(itemRef);
                    diaBox.show();
                });
                viewHolder.cvArchive.setOnClickListener(view -> {
                    Intent startArchiveActivity = new Intent(AdminActivity2.this, Archive.class);
                    startArchiveActivity.putExtra("Name", viewHolder.tvName.getText().toString());
                    Gson gson = new Gson();
                    String myJson = gson.toJson(model);
                    startArchiveActivity.putExtra("myjson", myJson);
                    startActivity(startArchiveActivity);
                });

                viewHolder.tvPosition.setText(String.format(Locale.getDefault(), "%02d", position + 1));
                viewHolder.tvName.setText(model.getLastName() + " " + model.getFirstName().charAt(0) + model.getMiddleName().charAt(0));
                viewHolder.tvName.setTypeface(mTypeface);

                viewHolder.cvTo.setTitleText(pointCount(model.getArchive(), Constants.header.to, false));
                viewHolder.cvTo.setOnClickListener(view -> showDialog("Цикл ТО-1", itemRef, model, TO, viewHolder.cvItogo));

                viewHolder.cvKs.setTitleText(pointCount(model.getArchive(), Constants.header.ks, false));
                viewHolder.cvKs.setOnClickListener(view -> showDialog("Культурное состояние локомотива", itemRef, model, KS, viewHolder.cvItogo));

                viewHolder.cvTz.setTitleText(pointCount(model.getArchive(), Constants.header.tz, false));
                viewHolder.cvTz.setOnClickListener(view -> showDialog("Посещение технических занятий", itemRef, model, TZ, viewHolder.cvItogo));

                viewHolder.cvRl.setTitleText(pointCount(model.getArchive(), Constants.header.rl, false));
                viewHolder.cvRl.setOnClickListener(view -> showDialog("Расшифровка лент", itemRef, model, RL, viewHolder.cvItogo));

                viewHolder.cvOt.setTitleText(pointCount(model.getArchive(), Constants.header.ot, false));
                viewHolder.cvOt.setOnClickListener(view -> showDialog("Охрана труда", itemRef, model, OT, viewHolder.cvItogo));

                viewHolder.cvOtk.setTitleText(pointCount(model.getArchive(), Constants.header.oz, false));
                viewHolder.cvOtk.setOnClickListener(view -> showDialog("Отказы", itemRef, model, OTK, viewHolder.cvItogo));

                viewHolder.cvItogo.setTitleText(pointCount(model.getArchive(), null, true));
                viewHolder.cvItogo.setOnClickListener(view -> setSelected(true, true, viewHolder));

            }
        };

        rv.setAdapter(adapter);

    }

    public static class MachinistsViewHolder2 extends RecyclerView.ViewHolder {

        SwipeLayout sl;

        RelativeLayout rlDataContainer;

        TextView tvPosition;
        TextView tvName;
        CircleView cvTo;
        CircleView cvKs;
        CircleView cvTz;
        CircleView cvRl;
        CircleView cvOt;
        CircleView cvOtk;
        CircleView cvItogo;

        CircleImageView cvRemove;
        CircleImageView cvArchive;

        public MachinistsViewHolder2(View itemView) {
            super(itemView);

            rlDataContainer = (RelativeLayout)itemView.findViewById(R.id.rlDataContainer);

            sl = (SwipeLayout) itemView.findViewById(R.id.sl);
            sl.setShowMode(SwipeLayout.ShowMode.LayDown);
            sl.addDrag(SwipeLayout.DragEdge.Left, itemView.findViewById(R.id.bottom_wrapper));

            tvPosition = (TextView) itemView.findViewById(R.id.tvPosition);
            tvName = (TextView) itemView.findViewById(R.id.tvName);

            cvTo = (CircleView) itemView.findViewById(R.id.cvTo);
            cvKs = (CircleView) itemView.findViewById(R.id.cvKs);
            cvTz = (CircleView) itemView.findViewById(R.id.cvTz);
            cvRl = (CircleView) itemView.findViewById(R.id.cvRl);
            cvOt = (CircleView) itemView.findViewById(R.id.cvOt);
            cvOtk = (CircleView) itemView.findViewById(R.id.cvOtk);
            cvItogo = (CircleView) itemView.findViewById(R.id.cvItogo);

            cvRemove = (CircleImageView) itemView.findViewById(R.id.cvRemove);
            cvArchive = (CircleImageView) itemView.findViewById(R.id.cvArchive);
        }
    }
}
</code>```

As a result, I see the list. But I can not call the setText () method on TextView. Because populateViewHolder is never called.
Where did I make a mistake?

答:
I forget about this:

super.onBindViewHolder(viewHolder, position);

inside method onBindViewHolder(MachinistsViewHolder viewHolder, int position);

Body:
activity layout :

android:layout_height="match_parent"

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_list_tasks2"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_list_tasks"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

   ... something else...

    </RelativeLayout>

activity class :

rv.setHasFixedSize(true);

public class AdminActivity2 extends AppCompatActivity {

    RecyclerView rv;

    private DatabaseReference myRef;

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admin_activity);

        rv = (RecyclerView) findViewById(R.id.rv_list_tasks);

        myRef = FirebaseDatabase.getInstance().getReference();

        FirebaseRecyclerAdapter<Machinist, AdminActivity2.MachinistsViewHolder2> adapter;
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(llm);
        rv.setHasFixedSize(true);
        rv.post(this::supportStartPostponedEnterTransition);
        Query query = myRef.child("Машинисты").orderByChild("points/itogo");

        adapter = new FirebaseRecyclerAdapter<Machinist, MachinistsViewHolder2>(
                Machinist.class,
                R.layout.machinist_item,
                MachinistsViewHolder2.class,
                query){

            @Override
            public void onBindViewHolder(MachinistsViewHolder2 viewHolder, int position) {

            }

            @Override
            protected void populateViewHolder(MachinistsViewHolder2 viewHolder, Machinist model, int position) {

                Log.d("djuyf", "populate");

                Typeface mTypeface;
                mTypeface = Typeface.create("sans-serif-regular", Typeface.NORMAL);

                DatabaseReference itemRef = getRef(position);

                viewHolder.cvRemove.setOnClickListener(view -> {
                    AlertDialog diaBox = askOption(itemRef);
                    diaBox.show();
                });
                viewHolder.cvArchive.setOnClickListener(view -> {
                    Intent startArchiveActivity = new Intent(AdminActivity2.this, Archive.class);
                    startArchiveActivity.putExtra("Name", viewHolder.tvName.getText().toString());
                    Gson gson = new Gson();
                    String myJson = gson.toJson(model);
                    startArchiveActivity.putExtra("myjson", myJson);
                    startActivity(startArchiveActivity);
                });

                viewHolder.tvPosition.setText(String.format(Locale.getDefault(), "%02d", position + 1));
                viewHolder.tvName.setText(model.getLastName() + " " + model.getFirstName().charAt(0) + model.getMiddleName().charAt(0));
                viewHolder.tvName.setTypeface(mTypeface);

                viewHolder.cvTo.setTitleText(pointCount(model.getArchive(), Constants.header.to, false));
                viewHolder.cvTo.setOnClickListener(view -> showDialog("Цикл ТО-1", itemRef, model, TO, viewHolder.cvItogo));

                viewHolder.cvKs.setTitleText(pointCount(model.getArchive(), Constants.header.ks, false));
                viewHolder.cvKs.setOnClickListener(view -> showDialog("Культурное состояние локомотива", itemRef, model, KS, viewHolder.cvItogo));

                viewHolder.cvTz.setTitleText(pointCount(model.getArchive(), Constants.header.tz, false));
                viewHolder.cvTz.setOnClickListener(view -> showDialog("Посещение технических занятий", itemRef, model, TZ, viewHolder.cvItogo));

                viewHolder.cvRl.setTitleText(pointCount(model.getArchive(), Constants.header.rl, false));
                viewHolder.cvRl.setOnClickListener(view -> showDialog("Расшифровка лент", itemRef, model, RL, viewHolder.cvItogo));

                viewHolder.cvOt.setTitleText(pointCount(model.getArchive(), Constants.header.ot, false));
                viewHolder.cvOt.setOnClickListener(view -> showDialog("Охрана труда", itemRef, model, OT, viewHolder.cvItogo));

                viewHolder.cvOtk.setTitleText(pointCount(model.getArchive(), Constants.header.oz, false));
                viewHolder.cvOtk.setOnClickListener(view -> showDialog("Отказы", itemRef, model, OTK, viewHolder.cvItogo));

                viewHolder.cvItogo.setTitleText(pointCount(model.getArchive(), null, true));
                viewHolder.cvItogo.setOnClickListener(view -> setSelected(true, true, viewHolder));

            }
        };

        rv.setAdapter(adapter);

    }

    public static class MachinistsViewHolder2 extends RecyclerView.ViewHolder {

        SwipeLayout sl;

        RelativeLayout rlDataContainer;

        TextView tvPosition;
        TextView tvName;
        CircleView cvTo;
        CircleView cvKs;
        CircleView cvTz;
        CircleView cvRl;
        CircleView cvOt;
        CircleView cvOtk;
        CircleView cvItogo;

        CircleImageView cvRemove;
        CircleImageView cvArchive;

        public MachinistsViewHolder2(View itemView) {
            super(itemView);

            rlDataContainer = (RelativeLayout)itemView.findViewById(R.id.rlDataContainer);

            sl = (SwipeLayout) itemView.findViewById(R.id.sl);
            sl.setShowMode(SwipeLayout.ShowMode.LayDown);
            sl.addDrag(SwipeLayout.DragEdge.Left, itemView.findViewById(R.id.bottom_wrapper));

            tvPosition = (TextView) itemView.findViewById(R.id.tvPosition);
            tvName = (TextView) itemView.findViewById(R.id.tvName);

            cvTo = (CircleView) itemView.findViewById(R.id.cvTo);
            cvKs = (CircleView) itemView.findViewById(R.id.cvKs);
            cvTz = (CircleView) itemView.findViewById(R.id.cvTz);
            cvRl = (CircleView) itemView.findViewById(R.id.cvRl);
            cvOt = (CircleView) itemView.findViewById(R.id.cvOt);
            cvOtk = (CircleView) itemView.findViewById(R.id.cvOtk);
            cvItogo = (CircleView) itemView.findViewById(R.id.cvItogo);

            cvRemove = (CircleImageView) itemView.findViewById(R.id.cvRemove);
            cvArchive = (CircleImageView) itemView.findViewById(R.id.cvArchive);
        }
    }
}

As a result, I see the list. But I can not call the setText () method on TextView. Because populateViewHolder is never called.
Where did I make a mistake?


问:
Protractor randomly crashing with ECONNREFUSED
Since a few days, protractor crashes randomly during execution with the following exception:

```<code>Error: connect ECONNREFUSED
  at errnoException (net.js:905:11)
  at Object.afterConnect [as oncomplete] (net.js:896:19)
</code>```

There is no further information given. Catching uncaught errors does not yield any more information as well:

```<code>{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }
</code>```

This happens regardless of running through the webdriver-manager or with directConnect, and regardless of browser (tried chrome and firefox). The console of the webdriver-manager also does not give any indication what could be wrong (output just ends, but is not hung - i.e. I can just start protractor again and connect to the same session).

Tried protractor versions 1.2 and 1.5, as well as node 0.10.31 and 0.10.34 with no change. So I am really at a loss whats going on and how I could debug this problem.

Thanks in advance for any help.

答:
I could see from execution error log, The issue is with connection is not established between webdriver server and the browser you use, just follow the below steps, I hope it will work fine,

Step 1: Open Command Prompt type - Webdriver-manager update (To update drivers)

Step 2: Then type - Webdriver-manager start (To Start driver Server)

and make sure, all the configuration details are properly defined in the Configuration file.

I hope this will solve the issue.

Body:
Since a few days, protractor crashes randomly during execution with the following exception:

Error: connect ECONNREFUSED
  at errnoException (net.js:905:11)
  at Object.afterConnect [as oncomplete] (net.js:896:19)

There is no further information given. Catching uncaught errors does not yield any more information as well:

{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

This happens regardless of running through the webdriver-manager or with directConnect, and regardless of browser (tried chrome and firefox). The console of the webdriver-manager also does not give any indication what could be wrong (output just ends, but is not hung - i.e. I can just start protractor again and connect to the same session).

Tried protractor versions 1.2 and 1.5, as well as node 0.10.31 and 0.10.34 with no change. So I am really at a loss whats going on and how I could debug this problem.

Thanks in advance for any help.


问:
Inconsistent updating of Meteor template
Using Meteor with blaze templates and flow router, I find that if I create a new element then the page doesn't update to show it, but if I delete the same element it disappears immediately. Here's the template code:

```<code><template name="EditProject">
    ...
    {{#each currentCounts }}
        <div class="count-box">{{> CountDelete }}</div>
    {{/each}}
    ...
    <btn class="btn waves-effect waves-light h-button" id="add-count">Add Count</btn>
    ...
</template>

<template name="CountDelete">
    <div class="card blue-grey lighten-2 count-box">
        <div class="card-content white-text">
            <span class="card-title">
                {{ name }}
            </span>
            {{ notes }}
        </div>
        <div class="card-action">
            <btn class="btn waves-effect waves-light delete-count">
                <i class="mdi mdi-delete"></i>
            </btn>
            <a class="btn waves-effect waves-light" href="/edit_count/{{ _id }}">
                <i class="mdi mdi-pencil"></i>
            </a>
        </div>
    </div>
</template>
</code>```

The source of currentCounts is this:

```<code>Template.EditProject.helpers({
    currentCounts: function() {
        var projectId = FlowRouter.getParam('projectId');
        const project = Projects.findOne(projectId);
        var counts = Counts.find({
            _id: { $in: project.counts }
            },
            {
                sort: { sort_order: -1 }
            }
        );
        return counts;
    }
})
</code>```

As mentioned, clicking on a .delete-count button deletes the associated count and also causes the UI to update to show that it has gone. Adding a count (from a click on #add-count) creates the count correctly but the page does not update. There's a brief flicker, but that's all, and refreshing the page causes the new count to show up. Could anyone suggest what's going on?

Edit: Here's the subscription, as requested in a comment:

```<code>Template.EditProject.onCreated(function() {
    var self = this;
    self.autorun(function() {
        var projectId = FlowRouter.getParam('projectId');
        self.subscribe('single-project',projectId);
        self.subscribe('project-counts',projectId);
    })
})
</code>```

Further edit:

When first accessing this route the page renders as it should, showing a list of several counts via the {{#each currentCounts}}. If I delete one of those counts it instantly disappears from the screen but if I add a new one it doesn't show up until I refresh the page.

Another edit:

Listeners and server publication code (in server/main.js) added as requested. Oddly, when starting the application again everything started behaving as it should, but within a few minutes the same behaviour I've been describing reasserted itself.

```<code>Meteor.publish('project-counts', function projectPublication(projectId) {
    let project = Projects.findOne({_id: projectId, knitter: this.userId});
    return Counts.find({_id: { $in: project.counts }});
});
Meteor.publish('single-project', function projectPublication(projectId) {
    return Projects.find({_id: projectId, knitter: this.userId});
});

'click #add-count'(event) {
    //TODO: Check for duplicate count name
    var projectId = FlowRouter.getParam('projectId');
    var countName = $('#new-count').val();
    var countNotes = $('#new-count-notes').val();

    if (!countName) {
        $("#errors-go-here").empty();
        Blaze.renderWithData(Template.EditProjectErrors, {
            errors: ['You must supply a name for the new count.']
        }, $("#errors-go-here")[0])
        $('.modal').modal();
        $('#validation-errors').modal('open');
        return;
    }

Template.EditProject.events({
    ...
    Meteor.call('projects.add-count',projectId,countName,countNotes, function(error) {
            if (error) {
                console.log("Count add error: " + error);
                Materialize.toast('Failed to add count \'' + countName + '\'!', 3000, 'orange darken-4');
                return false;
            } else {
                Materialize.toast('Count \'' + countName + '\' added!', 3000, 'blue-grey');
                $('#new-count').val(null);
                $('#new-count-notes').val(null);
                // Running this makes the missing count show up, but this is clearly not the right way to do it...
                //location.reload();
            }
        });
    },
    ...
)}

Template.CountDelete.events({
    'click .delete-count'(event) {
        var self = this;
        var projectId = FlowRouter.getParam('projectId');
        var countId = self._id;
        const count = Counts.findOne(countId);
        const name = count.name;

        Meteor.call('projects.delete-count',projectId,countId, function(error) {
            if (error) {
                console.log("Count add error: " + error);
                Materialize.toast('Failed to delete count \'' + name + '\'!', 3000, 'orange darken-4');
                return false;
            } else {
                Materialize.toast('Count \'' + count.name + '\' deleted!', 3000, 'blue-grey');
            }
        });

    },

})
</code>```

Further information: I found that once the page is loaded it behaves as it should. However, if it is reloaded then it starts misbehaving. So, I'd originally not noticed the correct behaviour happening as the page had been refreshed by Meteor due to changes to the code.

答:
To be complete, you should probably have also shared the methods code (i.e. 'projects.add-count' and 'projects.delete-count').

That being said, I suspect they update the counts array field of document with _id equal to projectId in Projects collection.

In that case, looking at your 'project-counts' publication, we see that it depends on a Projects.findOne query, which is not reactive on server-side with standard Meteor.

Therefore what happens when you add a "count" is that a new document is added into Counts collection, and its _id is very probably correctly recorded in the project's counts field, but this does not re-execute your publication code. Therefore the cursor selector query is unchanged, and your client does not receive any modification in its Counts collection.

Assuming your method code is loaded in both client and server, the client performs a stub / simulation that inserts this new document and locally updates the project's counts, triggering a UI update.

But then your server executes the method as well, which leads to no change in the publication, therefore the new document in Counts is not sent to the client, which hides it back. This creates the flicker that you observe.

Now when you delete a document from Counts, we can assume that in particular you remove it from Counts collection, which then updates the publication cursor, that is why your UI correctly reflects the deletion, even though the publication query selector was not changed.

Finally, when you refresh the page, your publication code is entirely re-evaluated, using the latest version of your document in Projects collection, which leads to a correct query selector, hence your new cursor now includes the newly added document in Counts.

Then to solve your issue, you should try to use reactive joins or publish composite packages.

E.g. see https://stackoverflow.com/a/32920733/5108796 (Meteor.publish: publish collection which depends on other collection)

Body:
Using Meteor with blaze templates and flow router, I find that if I create a new element then the page doesn't update to show it, but if I delete the same element it disappears immediately. Here's the template code:

<template name="EditProject">
    ...
    {{#each currentCounts }}

{{> CountDelete }}

    {{/each}}
    ...
    <btn class="btn waves-effect waves-light h-button" id="add-count">Add Count</btn>
    ...
</template>

<template name="CountDelete">

                {{ name }}

            {{ notes }}

            <btn class="btn waves-effect waves-light delete-count">

            </btn>

</template>

The source of currentCounts is this:

Template.EditProject.helpers({
    currentCounts: function() {
        var projectId = FlowRouter.getParam('projectId');
        const project = Projects.findOne(projectId);
        var counts = Counts.find({
            _id: { $in: project.counts }
            },
            {
                sort: { sort_order: -1 }
            }
        );
        return counts;
    }
})

As mentioned, clicking on a .delete-count button deletes the associated count and also causes the UI to update to show that it has gone. Adding a count (from a click on #add-count) creates the count correctly but the page does not update. There's a brief flicker, but that's all, and refreshing the page causes the new count to show up. Could anyone suggest what's going on?

Edit: Here's the subscription, as requested in a comment:

Template.EditProject.onCreated(function() {
    var self = this;
    self.autorun(function() {
        var projectId = FlowRouter.getParam('projectId');
        self.subscribe('single-project',projectId);
        self.subscribe('project-counts',projectId);
    })
})

Further edit:

When first accessing this route the page renders as it should, showing a list of several counts via the {{#each currentCounts}}. If I delete one of those counts it instantly disappears from the screen but if I add a new one it doesn't show up until I refresh the page.

Another edit:

Listeners and server publication code (in server/main.js) added as requested. Oddly, when starting the application again everything started behaving as it should, but within a few minutes the same behaviour I've been describing reasserted itself.

Meteor.publish('project-counts', function projectPublication(projectId) {
    let project = Projects.findOne({_id: projectId, knitter: this.userId});
    return Counts.find({_id: { $in: project.counts }});
});
Meteor.publish('single-project', function projectPublication(projectId) {
    return Projects.find({_id: projectId, knitter: this.userId});
});

'click #add-count'(event) {
    //TODO: Check for duplicate count name
    var projectId = FlowRouter.getParam('projectId');
    var countName = $('#new-count').val();
    var countNotes = $('#new-count-notes').val();

    if (!countName) {
        $("#errors-go-here").empty();
        Blaze.renderWithData(Template.EditProjectErrors, {
            errors: ['You must supply a name for the new count.']
        }, $("#errors-go-here")[0])
        $('.modal').modal();
        $('#validation-errors').modal('open');
        return;
    }

Template.EditProject.events({
    ...
    Meteor.call('projects.add-count',projectId,countName,countNotes, function(error) {
            if (error) {
                console.log("Count add error: " + error);
                Materialize.toast('Failed to add count \'' + countName + '\'!', 3000, 'orange darken-4');
                return false;
            } else {
                Materialize.toast('Count \'' + countName + '\' added!', 3000, 'blue-grey');
                $('#new-count').val(null);
                $('#new-count-notes').val(null);
                // Running this makes the missing count show up, but this is clearly not the right way to do it...
                //location.reload();
            }
        });
    },
    ...
)}

Template.CountDelete.events({
    'click .delete-count'(event) {
        var self = this;
        var projectId = FlowRouter.getParam('projectId');
        var countId = self._id;
        const count = Counts.findOne(countId);
        const name = count.name;

        Meteor.call('projects.delete-count',projectId,countId, function(error) {
            if (error) {
                console.log("Count add error: " + error);
                Materialize.toast('Failed to delete count \'' + name + '\'!', 3000, 'orange darken-4');
                return false;
            } else {
                Materialize.toast('Count \'' + count.name + '\' deleted!', 3000, 'blue-grey');
            }
        });

    },

})

Further information: I found that once the page is loaded it behaves as it should. However, if it is reloaded then it starts misbehaving. So, I'd originally not noticed the correct behaviour happening as the page had been refreshed by Meteor due to changes to the code.