问:
Vue Change state in forEach loop and if condition to update replies of any comment
I have a State with editedIndex i want to change it in forEach loop but i am not able to call it in that loop.

i have done this code so far

```<code>data() {
return {
    dialog: false,
      comments: [],
      editedReply: {
        reply: null,
        comment_id: null,
        name: JSON.parse(localStorage.getItem("user")).name,
        email: JSON.parse(localStorage.getItem("user")).email
      },
      editedIndex: -1
    };
  },
</code>```

in above code i have added the initial state of comments which contains index of all comments
I am trying to update the replies of each comment.

```<code>handleEdit(reply) {
      let commentArray = this.comments;
      commentArray.forEach(function(comment) {
        comment.reply.forEach(function(item) {
          if (reply.id === item.id) {
            this.editedIndex = comment.reply.indexOf(item);
            this.editedReply = Object.assign({}, item);
          }
        });
      });
     this.dialog = true;
    },
</code>```

from i have the list of comments in this.comments and reply represents the reply on which i have clicked to update.

my problem here is i am not able to call this.editedIndex and this.editedReply in if condition as i have mentioned above.
I have used comment.reply every comment contains a array of reply which you can see in below json data for comment i want to update the this json reply

json data for my comments is

```<code>    {
        "comments": [
            {
                "id": 5,
                "comment": "nice blog",
                "name": "test user",
                "email": "dhruvil@gkmit.co",
                "status": true,
                "created_at": "2020-05-28T04:36:46.797Z",
                "article": {
                    "id": 308,
                    "title": "test for comment article"
                },
                "reply": [
                    {
                        "id": 99,
                        "reply": "abcbc",
                        "name": "test2",
                        "email": "test2@mailinator.com",
                        "created_at": "2020-05-29T13:23:31.358Z"
                    },
                    {
                        "id": 100,
                        "reply": "abcbc",
                        "name": "test2",
                        "email": "test2@mailinator.com",
                        "created_at": "2020-05-29T13:23:31.521Z"
                    },
               ]
         },
         {
            .......... and so on
         },
    ]
}
</code>```

答:
Try using this snippet for handleEdit method:

```<code>handleEdit(reply) {
    let commentArray = this.comments;
    commentArray.forEach(comment => {
      comment.reply.forEach(item => {
        if (reply.id === item.id) {
          this.editedIndex = comment.reply.indexOf(item);
          this.editedReply = Object.assign({}, item);
        }
      });
    });
   this.dialog = true;
},
</code>```

What's different here is I used arrow functions for the callbacks of forEach operations.

Body:
I have a State with editedIndex i want to change it in forEach loop but i am not able to call it in that loop.

i have done this code so far

data() {
return {
    dialog: false,
      comments: [],
      editedReply: {
        reply: null,
        comment_id: null,
        name: JSON.parse(localStorage.getItem("user")).name,
        email: JSON.parse(localStorage.getItem("user")).email
      },
      editedIndex: -1
    };
  },

in above code i have added the initial state of comments which contains index of all comments
I am trying to update the replies of each comment.

handleEdit(reply) {
      let commentArray = this.comments;
      commentArray.forEach(function(comment) {
        comment.reply.forEach(function(item) {
          if (reply.id === item.id) {
            this.editedIndex = comment.reply.indexOf(item);
            this.editedReply = Object.assign({}, item);
          }
        });
      });
     this.dialog = true;
    },

from i have the list of comments in this.comments and reply represents the reply on which i have clicked to update.

my problem here is i am not able to call this.editedIndex and this.editedReply in if condition as i have mentioned above.
I have used comment.reply every comment contains a array of reply which you can see in below json data for comment i want to update the this json reply

json data for my comments is

    {
        "comments": [
            {
                "id": 5,
                "comment": "nice blog",
                "name": "test user",
                "email": "dhruvil@gkmit.co",
                "status": true,
                "created_at": "2020-05-28T04:36:46.797Z",
                "article": {
                    "id": 308,
                    "title": "test for comment article"
                },
                "reply": [
                    {
                        "id": 99,
                        "reply": "abcbc",
                        "name": "test2",
                        "email": "test2@mailinator.com",
                        "created_at": "2020-05-29T13:23:31.358Z"
                    },
                    {
                        "id": 100,
                        "reply": "abcbc",
                        "name": "test2",
                        "email": "test2@mailinator.com",
                        "created_at": "2020-05-29T13:23:31.521Z"
                    },
               ]
         },
         {
            .......... and so on
         },
    ]
}

Body:
Try using this snippet for handleEdit method:

handleEdit(reply) {
    let commentArray = this.comments;
    commentArray.forEach(comment => {
      comment.reply.forEach(item => {
        if (reply.id === item.id) {
          this.editedIndex = comment.reply.indexOf(item);
          this.editedReply = Object.assign({}, item);
        }
      });
    });
   this.dialog = true;
},

What's different here is I used arrow functions for the callbacks of forEach operations.


来源: stackexchange

问:
JAVA inheritance constructor order of call
When I run the following program

```<code>public class Example {
    static class A {
        A()
        {
            f();
        }
        public void f(){
            System.out.println("A ctor");
        }
    }
    static class B extends A {
        B()
        {
            f();
        }
        public void f() {
            System.out.println("B ctor");
        }
    }
    public static void main(String[] args) {
        B b = new B();
        b.f();
        A a = new A();
        a.f();
    }
}
</code>```

I expect the following

```<code>A ctor
B ctor
B ctor
A ctor
A ctor
</code>```

But instead I get

```<code>B ctor
B ctor
B ctor
A ctor
A ctor
</code>```

I'm confused as to why this is. The first call to the constructor of B should call A.f() (thru the automatic call to A's constructor) but looks like its calling B.f()

Why?

答:
When you compile B.java, the compiler inserts some code.  While you typed.

```<code>    B() {
        f();
    }
</code>```

If you reverse the Java Bytecode, you will clearly see instructions like

```<code>    B() {
        super();
        f();
    }
</code>```

But while that might explain the inheritence question, there's a massive problem with your code.

It is not safe to call functions on a class that's not constructed.

So calling f() inside of A() is not safe.  This is because A() isn't full constructed until the constructor of A() completes.  Again, calling f() inside of B() is not safe, for the same reasons.

If you convert f() to static members, which don't use the this references, then you will have safe code; however, you won't get polymorphisim in your f() calls.

Remember, that a f() call is a call on the object.  In the middle of wiring the object's dynamic methods, a call to f() might refer to either A's or B's implementation, and at the time of construction, it's not always possible to know which one should be invoked, as A()'s constructor is called in an identical manner both inside and outside of the B() constructor.

Now that the general rule has been stated, here's the exceptions:

You can safely call some function g() within a constructor if g() is a final member function, which refers to variables that have been properly assigned and final in that class level.

You can safely call some function h() in a parent class, if h() is written to only mutate variables that are effectively private to the parent class.

You can call some function j() in a parent class, if all the variables used by j() have a sensible assignment, but you might not see the desired results if the variables are leaked for mutation to lower sub-classes.

Basically, if you know enough about how classes are constructed, you can write your code to work with the construction order because you're programming your functions around the failure cases.  The first two approaches are considered "good design" and the last approach is considered "bad design, but we do it when it works" quality code.

ContentLicense: CC BY-SA 4.0

Body:
When I run the following program

public class Example {
    static class A {
        A()
        {
            f();
        }
        public void f(){
            System.out.println("A ctor");
        }
    }
    static class B extends A {
        B()
        {
            f();
        }
        public void f() {
            System.out.println("B ctor");
        }
    }
    public static void main(String[] args) {
        B b = new B();
        b.f();
        A a = new A();
        a.f();
    }
}

I expect the following

A ctor
B ctor
B ctor
A ctor
A ctor

But instead I get

B ctor
B ctor
B ctor
A ctor
A ctor

I'm confused as to why this is. The first call to the constructor of B should call A.f() (thru the automatic call to A's constructor) but looks like its calling B.f()

Why?

Body:
When you compile B.java, the compiler inserts some code.  While you typed.

    B() {
        f();
    }

If you reverse the Java Bytecode, you will clearly see instructions like

    B() {
        super();
        f();
    }

But while that might explain the inheritence question, there's a massive problem with your code.

It is not safe to call functions on a class that's not constructed.

So calling f() inside of A() is not safe.  This is because A() isn't full constructed until the constructor of A() completes.  Again, calling f() inside of B() is not safe, for the same reasons.

If you convert f() to static members, which don't use the this references, then you will have safe code; however, you won't get polymorphisim in your f() calls.

Remember, that a f() call is a call on the object.  In the middle of wiring the object's dynamic methods, a call to f() might refer to either A's or B's implementation, and at the time of construction, it's not always possible to know which one should be invoked, as A()'s constructor is called in an identical manner both inside and outside of the B() constructor.

Now that the general rule has been stated, here's the exceptions:

You can safely call some function g() within a constructor if g() is a final member function, which refers to variables that have been properly assigned and final in that class level.

You can safely call some function h() in a parent class, if h() is written to only mutate variables that are effectively private to the parent class.

You can call some function j() in a parent class, if all the variables used by j() have a sensible assignment, but you might not see the desired results if the variables are leaked for mutation to lower sub-classes.

Basically, if you know enough about how classes are constructed, you can write your code to work with the construction order because you're programming your functions around the failure cases.  The first two approaches are considered "good design" and the last approach is considered "bad design, but we do it when it works" quality code.


问:
Not enough values to unpack expected two got one
i was following the tutorials on the django official documentation on a polling app, in part 4 of the tutorial i used same code as in the tutorials but i keep getting an error
ValueError: Not enough values to unpack (expected 2, got 1)
here is the code for my views.py

from django.shortcuts import render, get_object_or_404

from django.http import HttpResponse, HttpResponseRedirect

from django.urls import reverse

from django.views import generic

from .models import Choice, Question

class IndexView(generic.ListView):

    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):

        return Question.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView):

    model = Question
    template_name = 'polls/detail.html'

class ResultView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

def votes(request, question_id):

    question = get_object_or_404(Question, pk=question_id)

    try:

        selected_choice = question.choice_set.get(request.POST['choice'])

    except (KeyError, Choice.DoesNotExist):

        return render(request, 'polls/detail.html',
        {'question':question, 'error_message': "You didn't select a choice",})

    else:

        selected_choice.votes += 1
        selected_choice.save()

    return HttpResponseRedirect(reverse('polls:resullts', args=(question_id,)))
```

<p>and the html code for detail.html is below</p>

<pre class="lang-html prettyprint-override"><code><p>{{question.question_text}}</p>

{% if error_message %}<p>{{error_message}}</p>{% endif %}

<form action="{% url 'polls:votes' question.id %}" method="POST">
{% csrf_token %}

{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}" >
    <label for="choice{{forloop.counter}}">{{choice.choice_text}}</label><br>
{% endfor %}

<input type="submit" value="Vote">
</form>
</code>```

```<code>Internal Server Error: /polls/1/votes/
Traceback (most recent call last):
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\polls\views.py", line 45, in votes
    selected_choice = question.choice_set.get(kii)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 404, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1351, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1378, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1248, in build_filter
    arg, value = filter_expr
ValueError: not enough values to unpack (expected 2, got 1)
</code>```

This is the error message i keep getting

答:
Try this code here, I think what you are trying to do is get a choice related to the Question and that also has the choice from the form</p>

```<code>def votes(request, question_id):

    question = get_object_or_404(Question, pk=question_id)

    try:
        selected_choice = Choice.objects.get(
           question=question,
           id=request.POST['choice']
        ) # UPDATED CODE

    except (KeyError, Choice.DoesNotExist):

        return render(request, 'polls/detail.html',
        {'question':question, 'error_message': "You didn't select a choice",})
....
</code>```

Body:
i was following the tutorials on the django official documentation on a polling app, in part 4 of the tutorial i used same code as in the tutorials but i keep getting an error
ValueError: Not enough values to unpack (expected 2, got 1)
here is the code for my views.py

from django.shortcuts import render, get_object_or_404

from django.http import HttpResponse, HttpResponseRedirect

from django.urls import reverse

from django.views import generic

from .models import Choice, Question

class IndexView(generic.ListView):

    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):

        return Question.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView):

    model = Question
    template_name = 'polls/detail.html'

class ResultView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

def votes(request, question_id):

    question = get_object_or_404(Question, pk=question_id)

    try:

        selected_choice = question.choice_set.get(request.POST['choice'])

    except (KeyError, Choice.DoesNotExist):

        return render(request, 'polls/detail.html',
        {'question':question, 'error_message': "You didn't select a choice",})

    else:

        selected_choice.votes += 1
        selected_choice.save()

    return HttpResponseRedirect(reverse('polls:resullts', args=(question_id,)))

and the html code for detail.html is below

{{question.question_text}}

{% if error_message %}
{{error_message}}
{% endif %}

<form action="{% url 'polls:votes' question.id %}" method="POST">
{% csrf_token %}

{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}" >
    {{choice.choice_text}}

{% endfor %}

<input type="submit" value="Vote">
</form>

Internal Server Error: /polls/1/votes/
Traceback (most recent call last):
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\polls\views.py", line 45, in votes
    selected_choice = question.choice_set.get(kii)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 404, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1351, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1378, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\Oj Philz\Desktop\hello\env\lib\site-packages\django\db\models\sql\query.py", line 1248, in build_filter
    arg, value = filter_expr
ValueError: not enough values to unpack (expected 2, got 1)

This is the error message i keep getting

Body:
Try this code here, I think what you are trying to do is get a choice related to the Question and that also has the choice from the form

def votes(request, question_id):

    question = get_object_or_404(Question, pk=question_id)

    try:
        selected_choice = Choice.objects.get(
           question=question,
           id=request.POST['choice']
        ) # UPDATED CODE

    except (KeyError, Choice.DoesNotExist):

        return render(request, 'polls/detail.html',
        {'question':question, 'error_message': "You didn't select a choice",})
....


问:
How to parse nested parenthesis only in first level in C#
I would like to write C# code that parses nested parenthesis to array elements, but only on first level. An example is needed for sure:

I want this string:

```<code>"(example (to (parsing nested paren) but) (first lvl only))"
</code>```

tp be parsed into:

```<code>["example", "(to (parsing nested paren) but)", "(first lvl only)"]
</code>```

I was thinking about using regex but can't figure out how to properly use them without implementing this behaviour from scratch.

In the case of malformed inputs I would like to return an empty array, or an array ["error"]

答:
well, regex will do the job:

var text = @"(example (to (parsing nested paren) but) (first lvl only))";
var pattern = @"\(([\w\s]+) (\([\w\s]+ \([\w\s]+\) [\w\s]+\)) (\([\w\s]+\))\)*";

try
{
    Regex r = new Regex(pattern, RegexOptions.IgnoreCase);

    Match m = r.Match(text);

    string group_1 = m.Groups[1].Value; //example
    string group_2 = m.Groups[2].Value; //(to (parsing nested paren) but)
    string group_3 = m.Groups[3].Value; //(first lvl only)

    return new string[]{group_1,group_2,group_3};

}
catch(Exception ex){

    return new string[]{"error"};
}
```

hopefully this helps, tested here in dotnetfiddle

Edit:

this might get you started into building the right expression according to whatever patterns you are falling into and maybe build a recursive function to parse the rest into the desired output :)

Body:
I would like to write C# code that parses nested parenthesis to array elements, but only on first level. An example is needed for sure:

I want this string:

"(example (to (parsing nested paren) but) (first lvl only))"

tp be parsed into:

["example", "(to (parsing nested paren) but)", "(first lvl only)"]

I was thinking about using regex but can't figure out how to properly use them without implementing this behaviour from scratch.

In the case of malformed inputs I would like to return an empty array, or an array ["error"]

Body:
well, regex will do the job:

var text = @"(example (to (parsing nested paren) but) (first lvl only))";
var pattern = @"\(([\w\s]+) (\([\w\s]+ \([\w\s]+\) [\w\s]+\)) (\([\w\s]+\))\)*";

try
{
    Regex r = new Regex(pattern, RegexOptions.IgnoreCase);

    Match m = r.Match(text);

    string group_1 = m.Groups[1].Value; //example
    string group_2 = m.Groups[2].Value; //(to (parsing nested paren) but)
    string group_3 = m.Groups[3].Value; //(first lvl only)

    return new string[]{group_1,group_2,group_3};

}
catch(Exception ex){

    return new string[]{"error"};
}

hopefully this helps, tested here in dotnetfiddle

Edit:

this might get you started into building the right expression according to whatever patterns you are falling into and maybe build a recursive function to parse the rest into the desired output :)


问:
How to launch html using Chrome at "--allow-file-access-from-files" mode?
I have the same situation with HERE

And to solve this problem I have to launch html file using Chrome at "--allow-file-access-from-files" mode.
I tried next steps many times, but it doesn't work.

start cmd under windows 7

direct to chrome.exe folder

do this chrome --allow-file-access-from-files file:///C:/test%20-%203.html

答:
Well there is quick to run a html which needs permission or blocked by CORS
Just simply open the folder using VSCODE and install an extension called "live server"

And then just click on the bottom which says go live, thats it.
Screenshot

ContentLicense: CC BY-SA 3.0


问:
Implement strategy pattern with enum
I'm trying to create a service to handle different payment methods. I want to implement strategy pattern. I'd like to have an enum with the different payment methods. This is an example of what I have:

```<code>public enum Pay {
    CREDITCARD(1) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }

    },
    OTHERMETHOD(2) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }
    };

    private int id;

    Payment(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public abstract void pay();
}
</code>```

somewhere in the client:

```<code>user.setPay(Pay.CREDITCARD);
user.pay();
</code>```

The problem with this approach is that method "pay" could be have a lot of logic so I'd like to have it in a different class. I could define an interface like this:

```<code>public interface Pay {
    void pay();
}

public class CreditCard implements Pay {
    @Override
    public void pay() {
    }
}

public class OtherMethod implements Pay {
    @Override
    public void pay() {
    }
}
</code>```

somewhere in the client:

```<code>if (method.equals("creditcard")) {
    user.setPay(new CreditCard());
    user.pay();
}
else {
    user.setPay(new OtherMethod());
    user.pay();
}
</code>```

but I like much more how it looks with Enum and that the reason to keep that way. Thanks

答:
It can be developed like this</p>

```<code>public enum PayType {
   CREDITCARD(new CreditCard()),
   OTHER(new OtherMethod();

   private Pay pay;
   PayType(Pay pay) {
      this.pay = pay;
   }

}
</code>```

Title: Implement strategy pattern with enum

Body:
I'm trying to create a service to handle different payment methods. I want to implement strategy pattern. I'd like to have an enum with the different payment methods. This is an example of what I have:

public enum Pay {
    CREDITCARD(1) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }

    },
    OTHERMETHOD(2) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }
    };

    private int id;

    Payment(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public abstract void pay();
}

somewhere in the client:

user.setPay(Pay.CREDITCARD);
user.pay();

The problem with this approach is that method "pay" could be have a lot of logic so I'd like to have it in a different class. I could define an interface like this:

public interface Pay {
    void pay();
}

public class CreditCard implements Pay {
    @Override
    public void pay() {
    }
}

public class OtherMethod implements Pay {
    @Override
    public void pay() {
    }
}

somewhere in the client:

if (method.equals("creditcard")) {
    user.setPay(new CreditCard());
    user.pay();
}
else {
    user.setPay(new OtherMethod());
    user.pay();
}

but I like much more how it looks with Enum and that the reason to keep that way. Thanks

Body:
It can be developed like this

public enum PayType {
   CREDITCARD(new CreditCard()),
   OTHER(new OtherMethod();

   private Pay pay;
   PayType(Pay pay) {
      this.pay = pay;
   }

}


问:
How can I get all the tree graphs given a certain numbers of nodes? Networkx
I was wondering is there a way to obtain all the different trees using Networkx? It's a known fact that the number of trees with n  nodes is n^(n-2) (using Cayley's Formula) so if there is 3 nodes, then it has 3 tree graphs, if it has 4 nodes then it has 16 trees and so on. What I want is to code all the trees using the prufer sequence, I know that Networkx has a function to create random trees, but there is a chance I can get duplicates, all I can think of is use Numpy so I can find all the unique elements in a list, here is my code:

```<code>import numpy as np
import networkx as nx

n = 3  #Number of nodes
aux = []
prufer = []

for i in range(10):
    aux.append(nx.random_tree(n))

for j in aux:
    prufer.append(nx.to_prufer_sequence(j))

arr = np.array(prufer)
newarr = np.unique(arr, axis = 0)
</code>```

The problem here it's that I generated 10 random trees, but in the end I only want 3 but when I want to find all the trees using 4 nodes I don't want to generate 50 if I'm only going to use 16. Is there a way I can do this more efficiently? Thank you!

答:
This  might be a bit bruteforcy, and there might be built-in functionality or a more elegant approach that I am missing, but it certainly is better than randomly generating the trees: You can use itertools to generate pairwise combinations and filter out duplicates and self-pointing loops:

```<code>import itertools

def make_all_trees(nodes):
    # generate all pairwise combinations of nodes
    edges =  [a for a in itertools.product(range(nodes), range(nodes))]

    # use sets to lose..
    # ..symmetric edges: (0,1), (1,0) => keep only (0,1)
    edges = list(set([tuple(set(e)) for e in edges]))
    # ..and self-loops: (0,0)
    edges = [e for e in edges if len(e)>1]

    trees = []
    # generate all graphs that have nodes-1 edges
    for o in itertools.combinations(edges, nodes-1):
        #make sure that all nodes are in the edgelist:
        flattened = [item for sublist in o for item in sublist]

        if len(set(flattened)) == nodes:
            G = nx.Graph()
            G.add_edges_from(o)
            # make sure all nodes are connected
            if len(list(nx.connected_components(G)))==1:
                trees.append(G)

    return trees
</code>```

testcases:

```<code> len(make_all_trees(3)): 3
 len(make_all_trees(4)): 16
 len(make_all_trees(5)): 125
</code>```

all 4 node trees:

trees = make_all_trees(4)

```<code>for p, tree in enumerate(trees):
    plt.subplot(4,4,p+1)
    nx.draw_networkx(tree)
plt.show()
</code>```

Body:
I was wondering is there a way to obtain all the different trees using Networkx? It's a known fact that the number of trees with n  nodes is n^(n-2) (using Cayley's Formula) so if there is 3 nodes, then it has 3 tree graphs, if it has 4 nodes then it has 16 trees and so on. What I want is to code all the trees using the prufer sequence, I know that Networkx has a function to create random trees, but there is a chance I can get duplicates, all I can think of is use Numpy so I can find all the unique elements in a list, here is my code:

import numpy as np
import networkx as nx

n = 3  #Number of nodes
aux = []
prufer = []

for i in range(10):
    aux.append(nx.random_tree(n))

for j in aux:
    prufer.append(nx.to_prufer_sequence(j))

arr = np.array(prufer)
newarr = np.unique(arr, axis = 0)

The problem here it's that I generated 10 random trees, but in the end I only want 3 but when I want to find all the trees using 4 nodes I don't want to generate 50 if I'm only going to use 16. Is there a way I can do this more efficiently? Thank you!

Body:
This  might be a bit bruteforcy, and there might be built-in functionality or a more elegant approach that I am missing, but it certainly is better than randomly generating the trees: You can use itertools to generate pairwise combinations and filter out duplicates and self-pointing loops:

import itertools

def make_all_trees(nodes):
    # generate all pairwise combinations of nodes
    edges =  [a for a in itertools.product(range(nodes), range(nodes))]

    # use sets to lose..
    # ..symmetric edges: (0,1), (1,0) => keep only (0,1)
    edges = list(set([tuple(set(e)) for e in edges]))
    # ..and self-loops: (0,0)
    edges = [e for e in edges if len(e)>1]

    trees = []
    # generate all graphs that have nodes-1 edges
    for o in itertools.combinations(edges, nodes-1):
        #make sure that all nodes are in the edgelist:
        flattened = [item for sublist in o for item in sublist]

        if len(set(flattened)) == nodes:
            G = nx.Graph()
            G.add_edges_from(o)
            # make sure all nodes are connected
            if len(list(nx.connected_components(G)))==1:
                trees.append(G)

    return trees

testcases:

 len(make_all_trees(3)): 3
 len(make_all_trees(4)): 16
 len(make_all_trees(5)): 125

all 4 node trees:

trees = make_all_trees(4)

for p, tree in enumerate(trees):
    plt.subplot(4,4,p+1)
    nx.draw_networkx(tree)
plt.show()


问:
How can I access variables in vector<struct> *obj?
How would I get my variables out of a vector?

I can't use the binary insertion operators or the equal operators.

Earlier, I declared a vector<someStruct> *vObj and allocated it, then returned the vObj
and called it in this function:

```<code>vector<sameStruct> firstFunc();

for (unsigned int x = 0; x < v->size(); x++)
{
   v[x];
}
</code>```

when I debug it, v[x] now has the full contents of the original vector, as it did before without the subscript/index.

But I don't think I've done anything to progress beyond that.

I just have about 4 variables inside my vector; when I debug it, it has the information that I need, but I can't get to it.

答:
To use the [] operator to access elements you must do so on object, not a pointer to an object.

Try;

```<code>(*vec)[x];
</code>```

E.g.

```<code>for (int i = 0; i < vec->size(); i++)
{
  printf("Value at %d is %d\n", i, (*vec)[i]);
}
</code>```

Note that when calling functions on a pointer you usually use the -> operator instead of the . operator, but you could easily do (*vec).some_func(); instead.

Operators such as [], --, ++ and so on can act both on objects and pointers. With objects they act as function calls, but on pointers they act as mathematical operations on the address.

For example;

```<code>pointer[nth];
*(pointer + nth);
</code>```

Have exactly the same effect - they return the nth object from the start of the pointer. (note the location of the * in the second example, it's called after the offset is applied.

Two other tips;

You can also avoid the need to dereference like this by passing the vector as a reference, not a pointer. It's not always a suitable option but it does lead to cleaner code.

```<code>void my_func(std::vector<int>& vector)
{
  // vector can then be used as a regular variable
}
</code>```

If you're going to be passing vectors of a specific type to functions a lot then you can use a typedef both for clarity and to save on typing.

```<code>typedef std::vector<int> IntVector;

void my_func(IntVector& vector)
{
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How would I get my variables out of a vector?

I can't use the binary insertion operators or the equal operators.

Earlier, I declared a vector<someStruct> *vObj and allocated it, then returned the vObj
and called it in this function:

vector<sameStruct> firstFunc();

for (unsigned int x = 0; x < v->size(); x++)
{
   v[x];
}

when I debug it, v[x] now has the full contents of the original vector, as it did before without the subscript/index.

But I don't think I've done anything to progress beyond that.

I just have about 4 variables inside my vector; when I debug it, it has the information that I need, but I can't get to it.

LastEditorDisplayName: Daniel L

Body:
To use the [] operator to access elements you must do so on object, not a pointer to an object.

Try;

(*vec)[x];

E.g.

for (int i = 0; i < vec->size(); i++)
{
  printf("Value at %d is %d\n", i, (*vec)[i]);
}

Note that when calling functions on a pointer you usually use the -> operator instead of the . operator, but you could easily do (*vec).some_func(); instead.

Operators such as [], --, ++ and so on can act both on objects and pointers. With objects they act as function calls, but on pointers they act as mathematical operations on the address.

For example;

pointer[nth];
*(pointer + nth);

Have exactly the same effect - they return the nth object from the start of the pointer. (note the location of the * in the second example, it's called after the offset is applied.

Two other tips;

You can also avoid the need to dereference like this by passing the vector as a reference, not a pointer. It's not always a suitable option but it does lead to cleaner code.

void my_func(std::vector<int>& vector)
{
  // vector can then be used as a regular variable
}

If you're going to be passing vectors of a specific type to functions a lot then you can use a typedef both for clarity and to save on typing.

typedef std::vector<int> IntVector;

void my_func(IntVector& vector)
{
}

OwnerDisplayName: Andrew Grant

LastEditorDisplayName: Andrew Grant


问:
Automatic update from database
I'm developing in WPF and want my DataGrid to automatically refresh when there's a change in the DB, and vice versa.

Today I'm using Timers and simple Selects to perform the updates.
Is there something in .Net that provides that functionality ?

答:
One idea is to use MSMQ. That way multiple client applications can get be notified whenever something changes. You need to add a trigger in your SQL database (or the application that is modifying the database) to notify the message queue whenever something new is added (see: Posting Message to MSMQ through SQL Server). Your client application would then need to subscribe to the Message Queue and would act on any new messages being posted there.

There is also SQL Server Service Broker but I am not really familiar with that, but might be worth investigating.

Title: Automatic update from database


问:
File not found error: Trying to import csv file into python. No such file or directory
So I'm getting the error:

[Errno 2] No such file or directory.

My csv file is ratings.csv I know for sure that my file exists.

Here's my code:

```<code>import csv

ifile = open('ratings.csv', "rb")
reader = csv.reader(ifile)
</code>```

答:
The working directory may be different. So though the file is there in the directory you are looking at, the script is not being executed there.  Can you try with the full pathname of the file instead of the just the file name?

import csv

ifile =  open('/home/dir2/dir3/ratings.csv', "rb")
reader = csv.reader(ifile)```

Body:
So I'm getting the error:

[Errno 2] No such file or directory.

My csv file is ratings.csv I know for sure that my file exists.

Here's my code:

import csv

ifile = open('ratings.csv', "rb")
reader = csv.reader(ifile)


问:
Firebase Jira integration error - Unable to reach the Jira instance
In Firebase in the project setting's integrations tab, it asks to enter your Jira project URL. Firebase docs say it should be in the format:

https://[workspace-name].atlassian.net/projects/[project-key]

When I'm in Jira, and click on the project I want to connect, it opens automatically to the trello board section I connected, and the url I have from the browser is:

https://[workspace-name].atlassian.net/jira/software/projects/[project-key]/boards/1

I get the error 'Unexpected project URL format'

So when I truncate the URL so it will look more like the doc's format to:

https://[workspace-name].atlassian.net/jira/software/projects/[project-key]

I get the error: Unable to reach the Jira instance (also note the word 'software' that differs from the Firebase docs expectation)

Also when I try and use the truncated URL in the browser it gives me 404 error, indicating this is NOT the correct URL.
Why can't I get to the pure project URL by clicking on my Jira project?

答:
For Jira Cloud you can simply go with this URL:

https://[WORKSPACE].atlassian.net/projects/[PROJECT-KEY]/

Where PROJECT-KEY can be found in the Jira administration panel


问:
GraphIQL explorer not showing in Gatsby when using gatsby-source-graphql
I'm new to Gatsby and have set up the aws-appsync-gatsby-sample project.  The GraphQL data correctly renders in the local site as seen here:

However, I want to use the GraphIQL explorer to learn how to further manipulate the GraphIQL queries but the "explorer" option that Gatsby typically displays is no longer showing.  Is it because Im using gatsby-source-graphql?

How to I access the GraphIQL explorer to play with this AppSync API data please?
Alternatively, is there another way to access the GraphIQL explorer on my Mac, or online, to access my data?

Thanks for any help.

答: I was able to fix this by downloading the latest version of gatsby</p>


问:
android thread start issue
I am stating a thread to do certain jobs,

```<code>    Thread download= new Thread("download"){
        public void run(){
            Looper.prepare();
            downloadThreadHandler = new Handler();
            Looper.loop();
        }
    };
    download.start();
</code>```

And I am giving posting Runnables to thread to do tasks inside thread.

```<code>downloadThreadHandler.post(new Runnable() {});
</code>```

When these two snippets are immediate then exception occurs.
If there is some delay between starting thread and posting Runnables, then it works fine.
Also I could not find problem because debugging process adds that delay and it works fine while debugging

答: Post to thread probably occurs before loop fully started. Delay lets loop start.</p>

Title: android thread start issue

Body:
I am stating a thread to do certain jobs,

    Thread download= new Thread("download"){
        public void run(){
            Looper.prepare();
            downloadThreadHandler = new Handler();
            Looper.loop();
        }
    };
    download.start();

And I am giving posting Runnables to thread to do tasks inside thread.

downloadThreadHandler.post(new Runnable() {});

When these two snippets are immediate then exception occurs.
If there is some delay between starting thread and posting Runnables, then it works fine.
Also I could not find problem because debugging process adds that delay and it works fine while debugging


问:
How can i create a dynamic dropdown form using jquery
i am working on a Django project and i am trying to implement a dropdown form on button click. I have a dropdown form when a button is clicked and each form has its own button, the problem is that when i clicked on a particular form button, all other forms dropdown as well. I want only the particular form to dropdown while the others do not. I think this has to do with passing the id of the form to each button clicked. This is what i tried.

Template:

```<code>{% for comment in all_comments %}
<ul>
<li class="float-right">
<!--Dropdown-->
<div class="dropdown dropdown-commentdeleteedit">
<a data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-ellipsis-h grey-text"></i>
</a>
<!-- Menu -->
<div class="dropdown-menu font-small z-depth-1">
<a class="dropdown-item material-tooltip-email editform-dropdown" data-toggle="tooltip" data-placement="top" title="Edit">
<img src="{{ '/static/' }}images/edit24px.png" width="18" height="18"></a>
</div>
</div>
<!--Dropdown-->
</li>
{% endif %}
<h6 class="comment editcomment-text ml-5">
{{ comment.comment_post }}
</h6>

<!-- DROPDOWN EDIT COMMENT FORM -->
<form  method="POST" enctype="multipart/form-data" class="ajaxcomment-editform editcommentform editcomment-form mb-4" id="" action="{% url 'site:comment_update' post.id comment.id %}">
{% csrf_token %}
<textarea name="comment_post" cols="20" rows="5" required="" id="id_comment_post{{ comment.id }}">{{ comment.comment_post }}</textarea>
<button type="submit" class="btn btn-sm waves-effect z-depth-1">Save</button>
</form>
</ul>
{% endfor %}
</code>```

Jquery:

```<code><script type="text/javascript">
//HIDE AND SHOW COMMENT EDIT FORM ON DROPDOWN
$(document).on('click', '.editform-dropdown', function(){
 $('.editcommentform').show();
 $('.editcomment-text').hide();
})
</script>
</code>```

答:
It is opening all dropdowns because $('.editcommentform') selects all elements in the DOM with the class editcommentform. The scope is too broad.

You need to add an event parameter to the handler function, then reference event.target in the function to access the actual object that was clicked. Then you can access the exact .editcommentform and .editcomment-text elements you want to show and hide.

Something like this should work:

```<code><script type="text/javascript">
//HIDE AND SHOW COMMENT EDIT FORM ON DROPDOWN
$(document).on('click', '.editform-dropdown', function(event){
  $(event.target).closest('li').find('.editcommentform').show();
  $(event.target).closest('li').find('.editcomment-text').hide();
})
</script>
</code>```

Calling $(event.target).closest('li') selects the closest parent li element to the clicked object, then calling find('classname') selects that parent's children with the class editcommentform.

Here's a fiddle based on your code that shows how it works: https://jsfiddle.net/BenjaminRay/kfbvo6zL/

Body:
i am working on a Django project and i am trying to implement a dropdown form on button click. I have a dropdown form when a button is clicked and each form has its own button, the problem is that when i clicked on a particular form button, all other forms dropdown as well. I want only the particular form to dropdown while the others do not. I think this has to do with passing the id of the form to each button clicked. This is what i tried.

Template:

{% for comment in all_comments %}

{% endif %}

{{ comment.comment_post }}

<form  method="POST" enctype="multipart/form-data" class="ajaxcomment-editform editcommentform editcomment-form mb-4" id="" action="{% url 'site:comment_update' post.id comment.id %}">
{% csrf_token %}
<textarea name="comment_post" cols="20" rows="5" required="" id="id_comment_post{{ comment.id }}">{{ comment.comment_post }}</textarea>
<button type="submit" class="btn btn-sm waves-effect z-depth-1">Save</button>
</form>

{% endfor %}

Jquery:

Body:
It is opening all dropdowns because $('.editcommentform') selects all elements in the DOM with the class editcommentform. The scope is too broad.

You need to add an event parameter to the handler function, then reference event.target in the function to access the actual object that was clicked. Then you can access the exact .editcommentform and .editcomment-text elements you want to show and hide.

Something like this should work:

<script type="text/javascript">
//HIDE AND SHOW COMMENT EDIT FORM ON DROPDOWN
$(document).on('click', '.editform-dropdown', function(event){
  $(event.target).closest('li').find('.editcommentform').show();
  $(event.target).closest('li').find('.editcomment-text').hide();
})
</script>

Calling $(event.target).closest('li') selects the closest parent li element to the clicked object, then calling find('classname') selects that parent's children with the class editcommentform.

Here's a fiddle based on your code that shows how it works: https://jsfiddle.net/BenjaminRay/kfbvo6zL/


问:
Adding a new label where clicked SWIFT
I would like to write a simple swift code for a MacOS app which add a new label wherever the user perform a mouse click in a window.

This code compiles but make the app crash:

```<code>@IBOutlet var here2 = [NSTextField]()
var count: Int = 0
func getCoordinates(){
        NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) {
        if self.location.x < 700 && self.location.y<750 {
            self.here2.append(NSTextField.init())
            self.here2[self.count].frame.origin = CGPoint(x: self.location.x, y: self.location.y)
            self.here2[self.count].stringValue = String(self.count)
            print("count is: " + String(self.here2.count))
            self.count+=1
        }
        return $0
    }

</code>```

答:
@Marco: The code which I posted is a template (aka boilerplate) example of the programmatic approach to creating applications.  All that I did was copy/paste your function into the AppDelegate class of the template and connect it to a button.  From there I revised your code until the desired result was obtained.  Instead of using a XIB or storyboard the technique requires that source code be written by the author (or use templates).  The good news is that you have control of your application and nothing is done behind your back; what you see is what you get.  The downside is that the technique is cumbersome for really large projects; for this I rely on Xcode with XIBs.  The autocompletion feature of Xcode is also very helpful, while with the programmatic approach you have to rely on Xcode/Help/DeveloperDocumentation as well as internet searches, especially StackOverflow (usually someone else has had the same problem that you are experiencing).  In lieu of using the CommandLine from Terminal for every compile I automated the process with a very simple editor which was written in Swift using Xcode (with XIB).  However, the posted code may also be run in Xcode by doing the following:

1) Create a new macOS App using Swift (User Interface is XIB but it won’t be needed for the demo)
2) Use File/New/File to add a Swift file and name it ‘main.swift’
3) In the new main.swift file change ‘import Foundation’ to ‘import Cocoa’
4) Copy/paste the last five lines of the demo (labelled main.swift) into this file
5) Go into the AppDelegate file that Apple provided and delete everything there except for ‘import Cocoa’
6) Copy/paste the entire AppDelegate class of the posted code (down to the main.swift section which you have already used)
7) Hit the ‘Run’ button, and it should compile without error.

Hope it helps and good luck with your project.  Thanks for posting.

Title: Adding a new label where clicked SWIFT

Body:
I would like to write a simple swift code for a MacOS app which add a new label wherever the user perform a mouse click in a window.

This code compiles but make the app crash:

@IBOutlet var here2 = [NSTextField]()
var count: Int = 0
func getCoordinates(){
        NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) {
        if self.location.x < 700 && self.location.y<750 {
            self.here2.append(NSTextField.init())
            self.here2[self.count].frame.origin = CGPoint(x: self.location.x, y: self.location.y)
            self.here2[self.count].stringValue = String(self.count)
            print("count is: " + String(self.here2.count))
            self.count+=1
        }
        return $0
    }


问:
expected 'while' or expected '}' Answered before yes, but I can't fix it myself
I have already checked all the other questions but I just can't fix it.. I am a nuub at coding.
I don't know why it says it needs a while or where to put it, and it gives the wrong answer for the LOCS function also is there anything i can do about the default pointer warning. this is just a start i will be extending this later so it would be a big help and i have tried while and closing brackets everywhere lol

Btw if anyone can tell me how I can use the input as decision as you can see I am using 1 and 2, but If I could use permanent and casual that would be great.

```<code>// Calculate an employee's weekly salary
// Use a do while loop, and an if else statement to have user input data and display the correct values

#include <iostream>
using namespace std;

void main()
{
    //Declaring the constant variables
    const double BONUS_RATE = 5.0;

    //Declaring the variables
    int hours;
    int sales;
    int Status;

    string permanent, casual, Name, status, result, employee;

    double rate, sale_bonus, netPay, gross;

    //set decimal point to 2 positions
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    //Display name
    cout << "Calculate an employee's weekly salary\n\n";

    //Do while loop to get hourly rate
    do {

        cout << "Enter employee name: ";
        cin >> Name;

        cout << "Please enter 1 if employee is permanent or 2 if casual: ";
        cin >> Status;

        Status = 0;
        while (Status < 1 || Status > 2);

        if (Status = 1)
        {

            cout << "Permanent employees have a fixed salary of $1000 per week" << endl;

            sales = 0;
            (sales < 1 || sales > 10);

            cout << "If any please enter how many sales employee made this week:";
            cin >> sales;

            sale_bonus = sales * BONUS_RATE;
            netPay = 1000 + sale_bonus;

            cout << endl;

            cout
                << "Hours Worked: \t" << hours << endl
                << "Gross Pay:  \t" << gross << endl
                << "Net Pay  \t" << netPay << endl;

        }
        else if (Status = 2) {

            cout << "Casual employee's hourly rate is $15";
            rate = 15.00;
            cout << endl;

            //while loop for hours

            hours = 0;
            while (hours < 1 || hours > 60)
            {
                cout << "Please enter how many hours you have worked this week:" << endl;
                cout << "Minimum hours is 1" << endl;
                cout << "Maximum hours are 60" << endl;
                cout << "Enter hours worked: ";

                cin >> hours;

            }

            //while loop for bonus

            sales = 0;
            while (sales < 1 || sales > 10)
            {
                cout << "Please enter how many sales you made this week:";
                cin >> sales;
            }

            //Calculate pay

            gross = hours * rate;
            sale_bonus = sales * BONUS_RATE;
            netPay = gross + sale_bonus;

            //Display the results
            cout << endl
                << "Hourly Rate:  \t" << rate << endl
                << "Hours Worked: \t" << hours << endl
                << "Gross Pay:  \t" << gross << endl
                << "Net Pay  \t" << netPay << endl;

        }

    }
}
</code>```

答:
Use this code this will work

#include
    using namespace std;

```<code>void main()
{
    //Declaring the constant variables
    const double BONUS_RATE = 5.0;

    //Declaring the variables
    int hours;
    int sales;
    int Status;

    string permanent, casual, Name, status, result, employee;

    double rate, sale_bonus, netPay, gross;

    //set decimal point to 2 positions
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    //Display name
    cout << "Calculate an employee's weekly salary\n\n";

    //Do while loop to get hourly rate
    while(1){

        cout << "Enter employee name: ";
        cin >> Name;

        cout << "Please enter 1 if employee is permanent or 2 if casual: ";
        cin >> Status;

        Status = 0;
        while (Status < 1 || Status > 2);

        if (Status = 1)
        {

            cout << "Permanent employees have a fixed salary of $1000 per week" << endl;

            sales = 0;
            (sales < 1 || sales > 10);

            cout << "If any please enter how many sales employee made this week:";
            cin >> sales;

            sale_bonus = sales * BONUS_RATE;
            netPay = 1000 + sale_bonus;

            cout << endl;

            cout
                << "Hours Worked: \t" << hours << endl
                << "Gross Pay:  \t" << gross << endl
                << "Net Pay  \t" << netPay << endl;

        }
        else if (Status = 2) {

            cout << "Casual employee's hourly rate is $15";
            rate = 15.00;
            cout << endl;

            //while loop for hours

            hours = 0;
            while (hours < 1 || hours > 60)
            {
                cout << "Please enter how many hours you have worked this week:" << endl;
                cout << "Minimum hours is 1" << endl;
                cout << "Maximum hours are 60" << endl;
                cout << "Enter hours worked: ";

                cin >> hours;

            }

            //while loop for bonus

            sales = 0;
            while (sales < 1 || sales > 10)
            {
                cout << "Please enter how many sales you made this week:";
                cin >> sales;
            }

            //Calculate pay

            gross = hours * rate;
            sale_bonus = sales * BONUS_RATE;
            netPay = gross + sale_bonus;

            //Display the results
            cout << endl
                << "Hourly Rate:  \t" << rate << endl
                << "Hours Worked: \t" << hours << endl
                << "Gross Pay:  \t" << gross << endl
                << "Net Pay  \t" << netPay << endl;

        }

    }

}
</code>```

Body:
I have already checked all the other questions but I just can't fix it.. I am a nuub at coding.
I don't know why it says it needs a while or where to put it, and it gives the wrong answer for the LOCS function also is there anything i can do about the default pointer warning. this is just a start i will be extending this later so it would be a big help and i have tried while and closing brackets everywhere lol

Btw if anyone can tell me how I can use the input as decision as you can see I am using 1 and 2, but If I could use permanent and casual that would be great.

// Calculate an employee's weekly salary
// Use a do while loop, and an if else statement to have user input data and display the correct values

#include <iostream>
using namespace std;

void main()
{
    //Declaring the constant variables
    const double BONUS_RATE = 5.0;

    //Declaring the variables
    int hours;
    int sales;
    int Status;

    string permanent, casual, Name, status, result, employee;

    double rate, sale_bonus, netPay, gross;

    //set decimal point to 2 positions
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    //Display name
    cout << "Calculate an employee's weekly salary\n\n";

    //Do while loop to get hourly rate
    do {

        cout << "Enter employee name: ";
        cin >> Name;

        cout << "Please enter 1 if employee is permanent or 2 if casual: ";
        cin >> Status;

        Status = 0;
        while (Status < 1 || Status > 2);

        if (Status = 1)
        {

            cout << "Permanent employees have a fixed salary of $1000 per week" << endl;

            sales = 0;
            (sales < 1 || sales > 10);

            cout << "If any please enter how many sales employee made this week:";
            cin >> sales;

            sale_bonus = sales * BONUS_RATE;
            netPay = 1000 + sale_bonus;

            cout << endl;

            cout
                << "Hours Worked: \t" << hours << endl
                << "Gross Pay:  \t" << gross << endl
                << "Net Pay  \t" << netPay << endl;

        }
        else if (Status = 2) {

            cout << "Casual employee's hourly rate is $15";
            rate = 15.00;
            cout << endl;

            //while loop for hours

            hours = 0;
            while (hours < 1 || hours > 60)
            {
                cout << "Please enter how many hours you have worked this week:" << endl;
                cout << "Minimum hours is 1" << endl;
                cout << "Maximum hours are 60" << endl;
                cout << "Enter hours worked: ";

                cin >> hours;

            }

            //while loop for bonus

            sales = 0;
            while (sales < 1 || sales > 10)
            {
                cout << "Please enter how many sales you made this week:";
                cin >> sales;
            }

            //Calculate pay

            gross = hours * rate;
            sale_bonus = sales * BONUS_RATE;
            netPay = gross + sale_bonus;

            //Display the results
            cout << endl
                << "Hourly Rate:  \t" << rate << endl
                << "Hours Worked: \t" << hours << endl
                << "Gross Pay:  \t" << gross << endl
                << "Net Pay  \t" << netPay << endl;

        }

    }
}

Body:
Use this code this will work

#include
    using namespace std;

void main()
{
    //Declaring the constant variables
    const double BONUS_RATE = 5.0;

    //Declaring the variables
    int hours;
    int sales;
    int Status;

    string permanent, casual, Name, status, result, employee;

    double rate, sale_bonus, netPay, gross;

    //set decimal point to 2 positions
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    //Display name
    cout << "Calculate an employee's weekly salary\n\n";

    //Do while loop to get hourly rate
    while(1){

        cout << "Enter employee name: ";
        cin >> Name;

        cout << "Please enter 1 if employee is permanent or 2 if casual: ";
        cin >> Status;

        Status = 0;
        while (Status < 1 || Status > 2);

        if (Status = 1)
        {

            cout << "Permanent employees have a fixed salary of $1000 per week" << endl;

            sales = 0;
            (sales < 1 || sales > 10);

            cout << "If any please enter how many sales employee made this week:";
            cin >> sales;

            sale_bonus = sales * BONUS_RATE;
            netPay = 1000 + sale_bonus;

            cout << endl;

            cout
                << "Hours Worked: \t" << hours << endl
                << "Gross Pay:  \t" << gross << endl
                << "Net Pay  \t" << netPay << endl;

        }
        else if (Status = 2) {

            cout << "Casual employee's hourly rate is $15";
            rate = 15.00;
            cout << endl;

            //while loop for hours

            hours = 0;
            while (hours < 1 || hours > 60)
            {
                cout << "Please enter how many hours you have worked this week:" << endl;
                cout << "Minimum hours is 1" << endl;
                cout << "Maximum hours are 60" << endl;
                cout << "Enter hours worked: ";

                cin >> hours;

            }

            //while loop for bonus

            sales = 0;
            while (sales < 1 || sales > 10)
            {
                cout << "Please enter how many sales you made this week:";
                cin >> sales;
            }

            //Calculate pay

            gross = hours * rate;
            sale_bonus = sales * BONUS_RATE;
            netPay = gross + sale_bonus;

            //Display the results
            cout << endl
                << "Hourly Rate:  \t" << rate << endl
                << "Hours Worked: \t" << hours << endl
                << "Gross Pay:  \t" << gross << endl
                << "Net Pay  \t" << netPay << endl;

        }

    }

}


问:
How do you put an onclick on a js button
I have some js created buttons from GeeksforGeeks, but I don't know how to put on click on the buttons. I can create a button using the code I found online, but there was no explanation on how to make that button have on click function</p>

答:
You can do it with JS and jQuery both, check both the solutions.

For JS use onlick on button , with jQuery use .click function

function runMe(){
 alert('I am executed with Pure JS');
}

$('document').ready(function(){
  $('#jQueryBubmit').click(function(){
    alert('I am executed with jQuery');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="submit" value="Submit" onclick="runMe();">Submit</button>

<button id="jQueryBubmit" value="Submit">Submit with jQuery</button></code>```

Body:
You can do it with JS and jQuery both, check both the solutions.

For JS use onlick on button , with jQuery use .click function

function runMe(){
 alert('I am executed with Pure JS');
}

$('document').ready(function(){
  $('#jQueryBubmit').click(function(){
    alert('I am executed with jQuery');
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="submit" value="Submit" onclick="runMe();">Submit</button>

<button id="jQueryBubmit" value="Submit">Submit with jQuery</button>


答:
```<code>let btn = document.createElement("button");
btn.innerHTML = 'hello';
btn.addEventListener('click',function(){
  console.log('click clock!');
});
document.body.appendChild(btn);
</code>```

This is how you should implement.
btn.addEventListener('click',funcName);

ex.

```<code>function onClick(){
   //Your Code..
}
btn.addEventListener('click',onClick);
</code>```

Title: How do you put an onclick on a js button

Body: I have some js created buttons from GeeksforGeeks, but I don't know how to put on click on the buttons. I can create a button using the code I found online, but there was no explanation on how to make that button have on click function

Body:
let btn = document.createElement("button");
btn.innerHTML = 'hello';
btn.addEventListener('click',function(){
  console.log('click clock!');
});
document.body.appendChild(btn);

This is how you should implement.
btn.addEventListener('click',funcName);

ex.

function onClick(){
   //Your Code..
}
btn.addEventListener('click',onClick);


问:
Placing the cursor at the top left of a vertically stretched TextField?
I'm trying to make a page through which the user can create a note for my Notes app. This is my build method so far:

```<code>  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Add Note"),
        actions: <Widget>[
          FlatButton(
            child: Icon(
              Icons.save,
              color: Colors.white,
            ),
          )
        ],
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              TextField (
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: "Title",
                ),
                textCapitalization: TextCapitalization.words,
              ),
              SizedBox(
                height: 16,
              ),
              Expanded(
                child: Container(
                  child: TextField (
                    expands: true,
                    maxLines: 25,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      )
    );
  }
</code>```

This is how the page looks right now. How do I ensure that the cursor of the second TextField is placed at the top left and make said TextField stretch to fit the remaining height?

答:
You should set the textAlign property of the TextField to start

```<code>textAlign: start
</code>```

Edit:

based on @Andy_519's and community input please use the following

```<code>textAlignVertical: top
</code>```

Body:
I'm trying to make a page through which the user can create a note for my Notes app. This is my build method so far:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Add Note"),
        actions: <Widget>[
          FlatButton(
            child: Icon(
              Icons.save,
              color: Colors.white,
            ),
          )
        ],
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              TextField (
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: "Title",
                ),
                textCapitalization: TextCapitalization.words,
              ),
              SizedBox(
                height: 16,
              ),
              Expanded(
                child: Container(
                  child: TextField (
                    expands: true,
                    maxLines: 25,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      )
    );
  }

This is how the page looks right now. How do I ensure that the cursor of the second TextField is placed at the top left and make said TextField stretch to fit the remaining height?

Body:
You should set the textAlign property of the TextField to start

textAlign: start

Edit:

based on @Andy_519's and community input please use the following

textAlignVertical: top


问:
When should we go for Spark-sql and when should we go for Spark RDD
On which scenario we should prefer spark RDD to write a solution and on which scenario we should choose to go for spark-sql. I know spark-sql gives better performance and it works best with structure and semistructure data. But what else factors are there that we need to take into consideration while choosing betweeen spark Rdd and spark-sql.</p>

答:
RDD

RDD is a collection of data across the clusters and it handles both unstructured and structured data. It's typically a function part of handling data.

DF

Data frames are basically two dimensional array of objects defining the data in a rows and columns. It's similar to relations tables in the database. Data frame handles only the structured data.


问:
Converting a fix msg to indivdual attributes
I have a fix msg coming in which I need to extract the invdividual attributes. Is there any Java jars or libs currently out there with added fix functionality. Currently looking over QuickFIX/J This however seems to be more focused on send and receiving the FIX msgs. Has anyone any experience in work with translating a FIX msg to it's various objects.</p>

答:
Every message class has a set of functions to extract the fields in the message and standard. An example class MassQuote.

There are named get methods which return you the field. Else you can use the generic getField to return you the field attribute. In case of groups, first get the number of groups and then iterate over the message and use the getGroup method, to extract all groups.


问:
Perforce (AWZ Server Lightsail Windows Instance) - Unreal Engine Source Control - Move Perforce Depot
I'll give a bit of a background as to the setup we have and why. Currently myself and a friend want to collaborate on an Unreal Engine Project. To do this I've set up an Amazon Lightsail Instance with Windows Server running. I've then installed Perforce onto this Server and added two users. Both of us are able to connect to this server from our local machines (great I thought!). Our goal was to attach two 'virtual' disks of 32gb to this server via Lightsails Storage option. I've formatted these discs and they are detected as Disk D and E on the Server. Our goal was to have two depots, one on Disk E and one on Disk D, the reason for this being the C disk was only 20gb (12gb Free after Windows).

I have tried multiple things (not got much hair left after this) to try and map the depots created to each HDD but have had little success and need your wisdom!

I've followed both the process indicated in this support guide (https://community.perforce.com/s/article/2559) via CMD as well as changing the depot storage location in P4Admin on the Server via RDP to the virtual disks D and E respectively.
Example change is from //UE_WIP/... to D:/UE_WIP/... (I have create a folder UE_WIP and UE_LIVE on each HDD).

When I open up P4V on my local machine I'm able to happily connect (as per screenshot) and set workstation to my local machine (detects both depots). This is when we're getting stuck. I then open up a new unreal engine file and save the unreal engine file to the the following local directory E:/DELETE/Perforce/Test/ and open up source control (See image 04). This is great, it detects the workspace and all is connecting to the server.

When I click submit to source control I get the following 'Failed Checking Source Control' when I try adding via P4V manually marking the new content folder for add I get the following 'file(s) not in client view.

All we want is the ability to send an Unreal Engine up to either the WIP Drive Depot or the Live Drive Depot. To resolve this does it require:
Two different workstations (one set up for LIVE and one for WIP)
Do we need to add some local folders to our directory? E:/DELETE/Perforce/UE_WIP & E:/DELETE/Perforce/UE_LIVE?
Do we need to tweak something on the Perforce Server?
Do we need to tweak something in Unreal Engine?

Any and all help would be massively appreciated.

Best,

Ben

https://imgur.com/a/aaMPTvI - Image gallery of issues

答:
Your screenshots don't show how (or if?) you set up your local workspace (i.e. the thing that tells Perforce where the files are on your local workstation).

See: https://www.perforce.com/perforce/r13.1/manuals/p4v/Defining_a_client_view.html

The Perforce server acts as a layer of abstraction between the backend storage (i.e. the depots you've set up) and the client machines where you actually do your work.  The location of the depot files doesn't matter at all to the client (any more than, say, the backend filesystem of a web server matters to your web browser); all that matters is how you set up the workspace, which is a simple matter of "here's where my local files are" (the Root) and "here's how my local paths map to depot paths" (the View).

You get the "file not in view" error if you try to add a local file to the depot and it's not in the View you've defined.  The fix there is generally to simply fix the Root and/or View to accurately describe where you local files are.  One View can easily map to multiple depots (as long as they're on a single server).

(edit)

Specifically, in your case, all of the files you're trying to add are under the path:

E:\DELETE\Perforce\Test\Saved\...

Since you've set up your workspace as:

```<code>Client: bsmith
Root: E:\DELETE\Perforce\bsmith
View:
    //WIP/... //bsmith/WIP/...
    //LIVE/... //bsmith/LIVE/...
</code>```

then your bsmith workspace consists of these two local paths:

```<code>E:\DELETE\Perforce\bsmith\WIP\...
E:\DELETE\Perforce\bsmith\LIVE\...
</code>```

The files you're trying to add aren't even under your Root, much less under either of the View mappings.  That's what the "not in client view" error messages mean.

If you want to add the files where they are, modify your Root and View so that you define your workspace as being where your files are; if you want to have the files in one of the local directories above that you've already defined as being where your workspace lives, you'll have to move them there.  If you put your files in bsmith\WIP, then when you add them they'll go to the WIP depot; if you put them in bsmith\LIVE, then they'll go to the LIVE depot, per your View.

Either way, once they're in your workspace, you can add them to the depot.  Simple as that!

Body:
Your screenshots don't show how (or if?) you set up your local workspace (i.e. the thing that tells Perforce where the files are on your local workstation).

See: https://www.perforce.com/perforce/r13.1/manuals/p4v/Defining_a_client_view.html

The Perforce server acts as a layer of abstraction between the backend storage (i.e. the depots you've set up) and the client machines where you actually do your work.  The location of the depot files doesn't matter at all to the client (any more than, say, the backend filesystem of a web server matters to your web browser); all that matters is how you set up the workspace, which is a simple matter of "here's where my local files are" (the Root) and "here's how my local paths map to depot paths" (the View).

You get the "file not in view" error if you try to add a local file to the depot and it's not in the View you've defined.  The fix there is generally to simply fix the Root and/or View to accurately describe where you local files are.  One View can easily map to multiple depots (as long as they're on a single server).

(edit)

Specifically, in your case, all of the files you're trying to add are under the path:

E:\DELETE\Perforce\Test\Saved\...

Since you've set up your workspace as:

Client: bsmith
Root: E:\DELETE\Perforce\bsmith
View:
    //WIP/... //bsmith/WIP/...
    //LIVE/... //bsmith/LIVE/...

then your bsmith workspace consists of these two local paths:

E:\DELETE\Perforce\bsmith\WIP\...
E:\DELETE\Perforce\bsmith\LIVE\...

The files you're trying to add aren't even under your Root, much less under either of the View mappings.  That's what the "not in client view" error messages mean.

If you want to add the files where they are, modify your Root and View so that you define your workspace as being where your files are; if you want to have the files in one of the local directories above that you've already defined as being where your workspace lives, you'll have to move them there.  If you put your files in bsmith\WIP, then when you add them they'll go to the WIP depot; if you put them in bsmith\LIVE, then they'll go to the LIVE depot, per your View.

Either way, once they're in your workspace, you can add them to the depot.  Simple as that!


问:
Blazor Cannot read the property parentnode of undefined
In the below code, when I click the button, instead of appearing a hello text, it throws an exception: Cannot read the property parentnode of undefined. I know that I can solve it in many ways but what's the reason of this? why is this occurring?</p>

```<code>@page "/"

@{
    void click()
    {
        <h1>Hello</h1>
    }
}

<button @onclick="click">Click me!</button>
</code>```

答:
The correct way to do this is

```<code>@page "/"

@if (ShowH1)
{
  <h1>Hello</h1>
}

<button @onclick="Click">Click me!</button>

@code
{
  bool ShowH1 = false;

  void Click()
  {
    ShowH1 = !ShowH1;
  }
}
</code>```

The reason your code doesn't work is that all mark-up in your .razor file (outside of @code) is transpiled into C#, overriding BuildRenderTree.

BuildRenderTreee is passed a parameter RenderTreeBuilder __builder to render to. Your method is being transpiled as an embedded method, like this

```<code>protected override void BuildRenderTree(RenderTreeBuilder __builder)
{
    void click()
    {
        __builder.AddMarkupContent(0, "\t\t");
        __builder.AddMarkupContent(1, "<h1>Hello</h1>\r\n");
    }

    __builder.AddMarkupContent(2, "\r\n");
    __builder.OpenElement(3, "button");
    __builder.AddAttribute(4, "onclick", ... call our click method));
    __builder.AddContent(5, "Click me!");
    __builder.CloseElement();
}

</code>```

So here you see that the button calls our embedded click method, which has captured the __builder parameter that was passed at the point the component was rendering.

But the __builder was only valid at the point it was rendering. By the time your user clicks the button the __builder is now invalid, and yet your code executes __builder.AddMarkupContent(....) on it - and therefore causes an exception.

Body:
In the below code, when I click the button, instead of appearing a hello text, it throws an exception: Cannot read the property parentnode of undefined. I know that I can solve it in many ways but what's the reason of this? why is this occurring?

@page "/"

@{
    void click()
    {

Hello

    }
}

<button @onclick="click">Click me!</button>

Body:
The correct way to do this is

@page "/"

@if (ShowH1)
{
  <h1>Hello</h1>
}

<button @onclick="Click">Click me!</button>

@code
{
  bool ShowH1 = false;

  void Click()
  {
    ShowH1 = !ShowH1;
  }
}

The reason your code doesn't work is that all mark-up in your .razor file (outside of @code) is transpiled into C#, overriding BuildRenderTree.

BuildRenderTreee is passed a parameter RenderTreeBuilder __builder to render to. Your method is being transpiled as an embedded method, like this

protected override void BuildRenderTree(RenderTreeBuilder __builder)
{
    void click()
    {
        __builder.AddMarkupContent(0, "\t\t");
        __builder.AddMarkupContent(1, "<h1>Hello</h1>\r\n");
    }

    __builder.AddMarkupContent(2, "\r\n");
    __builder.OpenElement(3, "button");
    __builder.AddAttribute(4, "onclick", ... call our click method));
    __builder.AddContent(5, "Click me!");
    __builder.CloseElement();
}

So here you see that the button calls our embedded click method, which has captured the __builder parameter that was passed at the point the component was rendering.

But the __builder was only valid at the point it was rendering. By the time your user clicks the button the __builder is now invalid, and yet your code executes __builder.AddMarkupContent(....) on it - and therefore causes an exception.


问:
require 'bundler' error, cannot load such file -- bundler (LoadError)
Unable to run rails console, rails -v etc. Already tried all of the solutions, reinstalled ruby, installed bundler but neither worked for me.

```<code>Traceback (most recent call last):
    4: from bin/rails:3:in `<main>'
    3: from bin/rails:3:in `load'
    2: from /var/www/App/releases/XXXXXXXXXXX/bin/spring:8:in `<top (required)>'
    1: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
/usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler (LoadError)
</code>```

答:
A few days back I also land up into the same issue, I think it was due to spring caching some gems and configurations. I fixed it by running bundle pristine.

This restores installed gems based on the Gemfile.lock to pristine condition from files located in the gem cache.

Body:
Unable to run rails console, rails -v etc. Already tried all of the solutions, reinstalled ruby, installed bundler but neither worked for me.

Traceback (most recent call last):
    4: from bin/rails:3:in `'
    3: from bin/rails:3:in `load'
    2: from /var/www/App/releases/XXXXXXXXXXX/bin/spring:8:in `<top (required)>'
    1: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
/usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- bundler (LoadError)


问:
fit_params doesn't work with XGBoost and Scikit-learn MultiOutputRegressor
I would like to use MultiOutputRegressor from scikit-learn to train a XGB on a multi output regression problem. But I can't pass a fit_params dictionary to the .fit method of a MultiOutputRegressor. It looks like it doesn't recognize the parameters inside...

I receive this error:

```<code>from sklearn.multioutput import MultiOutputRegressor
from xgboost.sklearn import XGBRegressor
XGB = XGBRegressor(n_jobs=1, max_depth=10, n_estimators=100, learning_rate=0.2)
fit_params = {'early_stopping_rounds':5,
                'eval_set':[(X_holdout,Y_holdout)],
                'eval_metric':'mae',
                'verbose':False}
multi = MultiOutputRegressor(XGB, n_jobs=-1)
multi.fit(X_train,Y_train,**fit_params)

Traceback (most recent call last):

  File "<ipython-input-16-e245db56e1be>", line 9, in <module>
    multi.fit(X_train,Y_train,**fit_params)

TypeError: fit() got an unexpected keyword argument 'early_stopping_rounds'
</code>```

What is strange is that it works with RandomizedSearchCV

```<code>from sklearn.model_selection import RandomizedSearchCV
XGB_cv = RandomizedSearchCV(XGB, params, cv=5, n_jobs=-1, verbose=1, n_iter=1000, scoring='neg_mean_absolute_error')
XGB_cv.fit(X_train, Y_train,**fit_params)
</code>```

答:
It seems that you have installed scikit-learn package version where **fit_params param of fit method is not implemented for MultiOutputRegressor. You can check version of installed package by using following commands:

```<code>import sklearn
print(sklearn.__version__)
</code>```

After upgrading scikit-learn package to version 0.23.1 you can use **fit_params in fit method of MultiOutputRegressor object. You can upgrade it using this way:

```<code>pip install --upgrade scikit-learn
</code>```

Body:
I would like to use MultiOutputRegressor from scikit-learn to train a XGB on a multi output regression problem. But I can't pass a fit_params dictionary to the .fit method of a MultiOutputRegressor. It looks like it doesn't recognize the parameters inside...

I receive this error:

from sklearn.multioutput import MultiOutputRegressor
from xgboost.sklearn import XGBRegressor
XGB = XGBRegressor(n_jobs=1, max_depth=10, n_estimators=100, learning_rate=0.2)
fit_params = {'early_stopping_rounds':5,
                'eval_set':[(X_holdout,Y_holdout)],
                'eval_metric':'mae',
                'verbose':False}
multi = MultiOutputRegressor(XGB, n_jobs=-1)
multi.fit(X_train,Y_train,**fit_params)

Traceback (most recent call last):

  File "<ipython-input-16-e245db56e1be>", line 9, in <module>
    multi.fit(X_train,Y_train,**fit_params)

TypeError: fit() got an unexpected keyword argument 'early_stopping_rounds'

What is strange is that it works with RandomizedSearchCV

from sklearn.model_selection import RandomizedSearchCV
XGB_cv = RandomizedSearchCV(XGB, params, cv=5, n_jobs=-1, verbose=1, n_iter=1000, scoring='neg_mean_absolute_error')
XGB_cv.fit(X_train, Y_train,**fit_params)

Body:
It seems that you have installed scikit-learn package version where **fit_params param of fit method is not implemented for MultiOutputRegressor. You can check version of installed package by using following commands:

import sklearn
print(sklearn.__version__)

After upgrading scikit-learn package to version 0.23.1 you can use **fit_params in fit method of MultiOutputRegressor object. You can upgrade it using this way:

pip install --upgrade scikit-learn


问:
ConcurrentLinkedQueue Questions
Could you please clarify if we need to use explicit synchronization or locks for using ConcurrentLinkedQueue? I am specifically interested in knowing if sync calls are needed for following ConcurrentLinkedQueue methods.

add

clear

size

Possibly size is the only method which might require explicit sync since it's a not an atomic method but ConcurrentLinkedQueue java docs say that

"Beware that, unlike in most
  collections, the size method is NOT a
  constant-time operation. Because of
  the asynchronous nature of these
  queues, determining the current number
  of elements requires a traversal of
  the elements. "

which make me believe that though size call may be slow but it doesn't require any explicit sync call.

Thanks in advance ...

答:
clear() is not atomic operation (it is implemented in AbstractQueue class), as Javadoc and source says: "This implementation repeatedly invokes poll until it returns null.". poll is atomic, but if you use offer while clear() is ongoing, you will add something in the middle of clearing, and clear() will delete it...

If you will use clear() you should use LinkedBlockingQueue instead of ConcurrentLinkedQueue.

Title: ConcurrentLinkedQueue Questions


问:
Download SFTP files that starts with prefix name using SSH.NET in C#
I am using SSH.NET library to download a file from SFTP server. When I gave it full file name it works. But I want to download a file with prefix name and in that folder, the prefix name is POS_ETH_SE7*. There will be always one file. After I download it, I move it to another folder. Here is my  method:

```<code>var auth = new PasswordAuthenticationMethod(username, password);
var connectionInfo = new ConnectionInfo(ipAddress, port, auth);

// Upload File
using (var sftp = new SftpClient(connectionInfo))
{
    string pathLocalFile =
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
            "POS_ETH_SE7.ics");

    sftp.Connect();

    Console.WriteLine("Downloading {0}", remoteFilePath);

    using (Stream fileStream = File.OpenWrite(pathLocalFile))
    using (StreamWriter writer = new StreamWriter(fileStream))

    {
        try
        {
            sftp.DownloadFile(remoteFilePath, fileStream);
        }
        catch (SftpPathNotFoundException ex)
        {

        }
    }
    try
    {
        var inFile = sftp.Get(remoteFilePath);
        inFile.MoveTo(remoteMoveFileToPath + "/POS_ETH_SE7.xml");
    }
    catch (SftpPathNotFoundException ex)
    {
        Console.WriteLine("\nnothing to update...\n");
    }

    sftp.Disconnect();
}
</code>```

答:
```<code>using (var sftp = new SftpClient(connectionInfo))
            {
                sftp.Connect();
                IEnumerable<SftpFile> files = sftp.ListDirectory(configSftpClient.remoteFilePath);
                files = files.Where(file => file.Name.StartsWith(configSftpClient.filePrefix));

                foreach (SftpFile file in files)
                {
                    string pathLocalFile = Path.Combine(configSftpClient.localFilePath, file.Name);
                    try
                    {
                        using (var stream = File.Create(pathLocalFile))
                        {
                            sftp.DownloadFile(file.FullName, stream);
                            var movableFile = sftp.Get(file.FullName);
                            Console.WriteLine(file.FullName);
                            movableFile.MoveTo(configSftpClient.remoteMoveFileToPath + "/" + file.Name);
                            stream.Close();
                        }
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine("file used by other");
                    }

                }
</code>```

Body:
I am using SSH.NET library to download a file from SFTP server. When I gave it full file name it works. But I want to download a file with prefix name and in that folder, the prefix name is POS_ETH_SE7*. There will be always one file. After I download it, I move it to another folder. Here is my  method:

var auth = new PasswordAuthenticationMethod(username, password);
var connectionInfo = new ConnectionInfo(ipAddress, port, auth);

// Upload File
using (var sftp = new SftpClient(connectionInfo))
{
    string pathLocalFile =
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
            "POS_ETH_SE7.ics");

    sftp.Connect();

    Console.WriteLine("Downloading {0}", remoteFilePath);

    using (Stream fileStream = File.OpenWrite(pathLocalFile))
    using (StreamWriter writer = new StreamWriter(fileStream))

    {
        try
        {
            sftp.DownloadFile(remoteFilePath, fileStream);
        }
        catch (SftpPathNotFoundException ex)
        {

        }
    }
    try
    {
        var inFile = sftp.Get(remoteFilePath);
        inFile.MoveTo(remoteMoveFileToPath + "/POS_ETH_SE7.xml");
    }
    catch (SftpPathNotFoundException ex)
    {
        Console.WriteLine("\nnothing to update...\n");
    }

    sftp.Disconnect();
}


问:
Use duplicate class name on an element?
I found that there are many frameworks that will check the duplicate class name before adding the new class name on the element which I think will slow down the performance.

Are there any problems when the element has a duplicate class name?

It will also apply the CSS class without conflict while the duplicate class name is in use.

```<code><div class="aa bb cc aa"></div>
</code>```

Is it OK to add a class name simply just like elem.className += ' ' + 'aa ee', even if the element has a duplicate class name?

答:
The DOM-API  provides a convenient way for adding and removing and testing class-names of DOM-elements:  classList.add(name) and classList.remove(name) and classList.contains(name).

In the ES6 context the question could perhaps be rephrased as:

"If I use .classList.add() to add the same className more than once, and  then want to remove that class with classList.remove(), do I need to call classList.remove() multiple times?

Luckily the answer seems to be a single call to .classList.remove() is enough to remove a given class no matter how many times you have added it.

I couldn't find an easy answer to this by Google so I wrote the following test to tell me that is how it behaves. Calling the below function with DOM-element as argument does NOT throw an error:

```<code>function testClassListRemove (dem)
{
  dem.classList.add ("hello");
  dem.classList.add ("hello");
  dem.classList.add ("hello");
  ok (dem.classList.contains ("hello") );

  dem.classList.remove ("hello");
  ok (!  dem.classList.contains ("hello") );

  function ok (b)
  { if (! b)
    { throw new Error ('not ok ');
    }
  }
}
</code>```

Title: Use duplicate class name on an element?

Body:
I found that there are many frameworks that will check the duplicate class name before adding the new class name on the element which I think will slow down the performance.

Are there any problems when the element has a duplicate class name?

It will also apply the CSS class without conflict while the duplicate class name is in use.

Is it OK to add a class name simply just like elem.className += ' ' + 'aa ee', even if the element has a duplicate class name?

Body:
The DOM-API  provides a convenient way for adding and removing and testing class-names of DOM-elements:  classList.add(name) and classList.remove(name) and classList.contains(name).

In the ES6 context the question could perhaps be rephrased as:

"If I use .classList.add() to add the same className more than once, and  then want to remove that class with classList.remove(), do I need to call classList.remove() multiple times?

Luckily the answer seems to be a single call to .classList.remove() is enough to remove a given class no matter how many times you have added it.

I couldn't find an easy answer to this by Google so I wrote the following test to tell me that is how it behaves. Calling the below function with DOM-element as argument does NOT throw an error:

function testClassListRemove (dem)
{
  dem.classList.add ("hello");
  dem.classList.add ("hello");
  dem.classList.add ("hello");
  ok (dem.classList.contains ("hello") );

  dem.classList.remove ("hello");
  ok (!  dem.classList.contains ("hello") );

  function ok (b)
  { if (! b)
    { throw new Error ('not ok ');
    }
  }
}


问:
create all possible combinations with multiple variants from list
Ok so the problem is as follows:

let's say I have a list like this [12R,102A,102L,250L] what I would want is a list of all possible combinations, however for only one combination/number. so for the example above, the output I would like is:

```<code>[12R,102A,250L]
[12R,102L,250L]
</code>```

my actual problem is a lot more complex with many more sites. Thanks for your help

edit: after reading some comments I guess this is slightly unclear. I have 3 unique numbers here, [12, 102, and 250] and for some numbers, I have different variations, for example [102A, 102L]. what I need is a way to combine the different positions[12,102,250] and all possible variations within. just like the lists, I presented above. they are the only valid solutions. [12R] is not. neither is [12R,102A,102L,250L]. so far I have done this with nested loops, but I have a LOT of variation within these numbers, so I can't really do that anymore

ill edit this again: ok so it seems as though there is still some confusion so I might extend the point I made before. what I am dealing with there is DNA. 12R means the 12th position in the sequence was changed to an R. so the solution     [12R,102A,250L] means that the amino acid on position 12 is R, 102 is A 250 is L.

this is why a solution like [102L, 102R, 250L] is not usable, because the same position can not be occupied by 2 different amino acids.

thank you

答:
Try this:

from itertools import groupby
import re

def __genComb(arr, res=[]):
    for i in range(len(res), len(arr)):
        el=arr[i]
        if(len(el[1])==1):
            res+=el[1]
        else:
            for el_2 in el[1]:
                yield from __genComb(arr, res+[el_2])
            break
    if(len(res)==len(arr)): yield res

def genComb(arr):
    res=[(k, list(v)) for k,v in groupby(sorted(arr), key=lambda x: re.match(r"(\d*)", x).group(1))]
    yield from __genComb(res)
```

<p>Sample output (using the input you provided):</p>

<pre class="lang-py prettyprint-override"><code>test=["12R","102A","102L","250L"]

for el in genComb(test):
    print(el)

# returns:

['102A', '12R', '250L']
['102L', '12R', '250L']
</code>```

Body:
Ok so the problem is as follows:

let's say I have a list like this [12R,102A,102L,250L] what I would want is a list of all possible combinations, however for only one combination/number. so for the example above, the output I would like is:

[12R,102A,250L]
[12R,102L,250L]

my actual problem is a lot more complex with many more sites. Thanks for your help

edit: after reading some comments I guess this is slightly unclear. I have 3 unique numbers here, [12, 102, and 250] and for some numbers, I have different variations, for example [102A, 102L]. what I need is a way to combine the different positions[12,102,250] and all possible variations within. just like the lists, I presented above. they are the only valid solutions. [12R] is not. neither is [12R,102A,102L,250L]. so far I have done this with nested loops, but I have a LOT of variation within these numbers, so I can't really do that anymore

ill edit this again: ok so it seems as though there is still some confusion so I might extend the point I made before. what I am dealing with there is DNA. 12R means the 12th position in the sequence was changed to an R. so the solution     [12R,102A,250L] means that the amino acid on position 12 is R, 102 is A 250 is L.

this is why a solution like [102L, 102R, 250L] is not usable, because the same position can not be occupied by 2 different amino acids.

thank you

Body:
Try this:

from itertools import groupby
import re

def __genComb(arr, res=[]):
    for i in range(len(res), len(arr)):
        el=arr[i]
        if(len(el[1])==1):
            res+=el[1]
        else:
            for el_2 in el[1]:
                yield from __genComb(arr, res+[el_2])
            break
    if(len(res)==len(arr)): yield res

def genComb(arr):
    res=[(k, list(v)) for k,v in groupby(sorted(arr), key=lambda x: re.match(r"(\d*)", x).group(1))]
    yield from __genComb(res)

Sample output (using the input you provided):

test=["12R","102A","102L","250L"]

for el in genComb(test):
    print(el)

# returns:

['102A', '12R', '250L']
['102L', '12R', '250L']


答:
```<code><body>

    <script>

        var button = document.createElement('BUTTON');
        button.setAttribute('id','btn');
        document.body.appendChild(button);

        var buttonById = document.getElementById('btn');
        buttonById.textContent = 'button is not clicked';

        buttonById.addEventListener('click',buttonClickFuntion);

        function buttonClickFuntion() {
            buttonById.textContent = 'button clicked';
        }

    </script>

</body>
</code>```