问:
How to use the infer_vector in gensim.doc2vec?
```<code>def cosine(vector1,vector2):
    cosV12 = np.dot(vector1, vector2) / (linalg.norm(vector1) * linalg.norm(vector2))
    return cosV12
model=gensim.models.doc2vec.Doc2Vec.load('Model_D2V_Game')
string='民生 为了 父亲 我 要 坚强 地 ...'
list=string.split(' ')
vector1=model.infer_vector(doc_words=list,alpha=0.1, min_alpha=0.0001,steps=5)
vector2=model.docvecs.doctag_syn0[0]
print cosine(vector2,vector1)
</code>```

-0.0232586

I use a train data to train a doc2vec model. Then, I use infer_vector() to generate a vector given a document which is in trained data. But they are different. The value of cosine was so small (-0.0232586) distance between the vector2 which was saved in doc2vec model and the vector1 which was generated by infer_vector(). But this is not reasonable ah ...

I find where i have error in. I should use 'string=u'民生 为了 父亲 我 要 坚强 地 ...'' instead 'string='民生 为了 父亲 我 要 坚强 地 ...''. When I correct this way, the cosine distance is up to 0.889342.

答:
As you've noticed, infer_vector() requires its doc_words argument to be a list of tokens – matching the same kind of tokenization that was used in training the model. (Passing it a string causes it to just see each individual character as an item in a tokenized list, and even if a few of the tokens are known vocabulary tokens – as with 'a' and 'I' in English – you're unlikely to get good results.)

Additionally, the default parameters of infer_vector() may be far from optimal for many models. In particular, a larger steps (at least as large as the number of model training iterations, but perhaps even many times larger) is often helpful. Also, a smaller starting alpha, perhaps just the common default for bulk training of 0.025, may give better results.

Your test of whether inference gets a vector close to the same vector from bulk-training is a reasonable sanity-check, on both your inference parameters and the earlier training – is the model as a whole learning generalizable patterns in the data? But because most modes of Doc2Vec inherently use randomness, or (during bulk training) can be affected by the randomness introduced by multiple-thread scheduling jitter, you shouldn't expect identical results. They'll just get generally closer, the more training iterations/steps you do.

Finally, note that the most_similar() method on Doc2Vec's docvecs component can also take a raw vector, to give back a list of most-similar already-known vectors. So you can try the following...

```<code>ivec = model.infer_vector(doc_words=tokens_list, steps=20, alpha=0.025)
print(model.most_similar(positive=[ivec], topn=10))
</code>```

...and get a ranked list of the top-10 most-similar (doctag, similarity_score) pairs.

Body:
def cosine(vector1,vector2):
    cosV12 = np.dot(vector1, vector2) / (linalg.norm(vector1) * linalg.norm(vector2))
    return cosV12
model=gensim.models.doc2vec.Doc2Vec.load('Model_D2V_Game')
string='民生 为了 父亲 我 要 坚强 地 ...'
list=string.split(' ')
vector1=model.infer_vector(doc_words=list,alpha=0.1, min_alpha=0.0001,steps=5)
vector2=model.docvecs.doctag_syn0[0]
print cosine(vector2,vector1)

-0.0232586

I use a train data to train a doc2vec model. Then, I use infer_vector() to generate a vector given a document which is in trained data. But they are different. The value of cosine was so small (-0.0232586) distance between the vector2 which was saved in doc2vec model and the vector1 which was generated by infer_vector(). But this is not reasonable ah ...

I find where i have error in. I should use 'string=u'民生 为了 父亲 我 要 坚强 地 ...'' instead 'string='民生 为了 父亲 我 要 坚强 地 ...''. When I correct this way, the cosine distance is up to 0.889342.

Body:
As you've noticed, infer_vector() requires its doc_words argument to be a list of tokens – matching the same kind of tokenization that was used in training the model. (Passing it a string causes it to just see each individual character as an item in a tokenized list, and even if a few of the tokens are known vocabulary tokens – as with 'a' and 'I' in English – you're unlikely to get good results.)

Additionally, the default parameters of infer_vector() may be far from optimal for many models. In particular, a larger steps (at least as large as the number of model training iterations, but perhaps even many times larger) is often helpful. Also, a smaller starting alpha, perhaps just the common default for bulk training of 0.025, may give better results.

Your test of whether inference gets a vector close to the same vector from bulk-training is a reasonable sanity-check, on both your inference parameters and the earlier training – is the model as a whole learning generalizable patterns in the data? But because most modes of Doc2Vec inherently use randomness, or (during bulk training) can be affected by the randomness introduced by multiple-thread scheduling jitter, you shouldn't expect identical results. They'll just get generally closer, the more training iterations/steps you do.

Finally, note that the most_similar() method on Doc2Vec's docvecs component can also take a raw vector, to give back a list of most-similar already-known vectors. So you can try the following...

ivec = model.infer_vector(doc_words=tokens_list, steps=20, alpha=0.025)
print(model.most_similar(positive=[ivec], topn=10))

...and get a ranked list of the top-10 most-similar (doctag, similarity_score) pairs.


来源: stackexchange

问:
How to change CPLEX parameters in oplrun?
Is there a way to let oplrun take a specific CPLEX parameter, such as  CPX_PARAM_LPMETHOD (Linear Programming method). In the reference here, it is called by various names for different languages:

```<code>C Name: CPX_PARAM_LPMETHOD

C++ Name: RootAlg

Java Name: RootAlg

.NET Name: RootAlg

InteractiveOptimizer: lpmethod
</code>```

But there is no reference about the OPL or oplrun.

Is it possible to change this parameter in an oplrun session? Or do I have to use these other languages/interfaces?

答:
In the .mod you may write:

```<code>execute
{
  cplex.lpmethod=4;
}
</code>```

and then you will see in the log:

```<code>CPXPARAM_LPMethod                                4
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to let oplrun take a specific CPLEX parameter, such as  CPX_PARAM_LPMETHOD (Linear Programming method). In the reference here, it is called by various names for different languages:

C Name: CPX_PARAM_LPMETHOD

C++ Name: RootAlg

Java Name: RootAlg

.NET Name: RootAlg

InteractiveOptimizer: lpmethod

But there is no reference about the OPL or oplrun.

Is it possible to change this parameter in an oplrun session? Or do I have to use these other languages/interfaces?

Body:
In the .mod you may write:

execute
{
  cplex.lpmethod=4;
}

and then you will see in the log:

CPXPARAM_LPMethod                                4

ContentLicense: CC BY-SA 4.0


问:
How can I print the text immediately in combobox with bind event?
```<code>from Tkinter import *
import ttk
main=Tk()

def print1(event):
    string = ""
    string = combobox1.get()
    print combobox1.get()

val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<Key>", print1)
combobox1.focus_set()
combobox1.pack()

mainloop()
</code>```

How can I fix the problem that is, when I press the first button, it didn't show immediately.

For example, when I pressed a, it didn't show anything, and then I pressed b. It will show a, but not ab.
How can I fix this bug?
thanks.

答:
You have it very close. The bind statement is slightly different from what you need. The problem was that it was printing before the key was delivered to the combobox. Now it waits until the key is released to fire the event.</p>

```<code>from Tkinter import *
import ttk
main=Tk()

def print1(event):
    string = ""
    string = combobox1.get()
    print combobox1.get()

val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<KeyRelease>", print1)
combobox1.focus_set()
combobox1.pack()

mainloop()
</code>```

Body:
from Tkinter import *
import ttk
main=Tk()

def print1(event):
    string = ""
    string = combobox1.get()
    print combobox1.get()

val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<Key>", print1)
combobox1.focus_set()
combobox1.pack()

mainloop()

How can I fix the problem that is, when I press the first button, it didn't show immediately.

For example, when I pressed a, it didn't show anything, and then I pressed b. It will show a, but not ab.
How can I fix this bug?
thanks.

Body:
You have it very close. The bind statement is slightly different from what you need. The problem was that it was printing before the key was delivered to the combobox. Now it waits until the key is released to fire the event.

from Tkinter import *
import ttk
main=Tk()

def print1(event):
    string = ""
    string = combobox1.get()
    print combobox1.get()

val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<KeyRelease>", print1)
combobox1.focus_set()
combobox1.pack()

mainloop()


问:
SimpleJdbcCall: get result of Microsoft/Sybase stored procedure call
I've a Microsoft and Sybase stored procedures that return result as "return @value". I need to read the value from Java via SimpleJdbcCall.

Is it possible?

答:
Use the SqlOutPutParameters :)

Here is an example :

```<code>SimpleJdbcCall countryProcedure = new SimpleJdbcCall(dataSource)
        .withoutProcedureColumnMetaDataAccess()
        .withProcedureName(procedureName)
        .declareParameters(new SqlOutParameter("RETURNCODE", Types.INTEGER))
        .declareParameters(new SqlOutParameter("RETURNMSG", Types.VARCHAR));
Map result = countryProcedure.execute();
        System.out.println("RETURNCODE: " + result.get("RETURNCODE"));
        System.out.println("RETURNMSG: " + result.get("RETURNMSG"));
</code>```

Edit :
I looked at it and there is a simpler way. Use the WithReturnValue() on your SimpleJdbcCall and the return value will be stored in the return Map under the "return" key.

ContentLicense: CC BY-SA 2.5

Body:
Use the SqlOutPutParameters :)

Here is an example :

SimpleJdbcCall countryProcedure = new SimpleJdbcCall(dataSource)
        .withoutProcedureColumnMetaDataAccess()
        .withProcedureName(procedureName)
        .declareParameters(new SqlOutParameter("RETURNCODE", Types.INTEGER))
        .declareParameters(new SqlOutParameter("RETURNMSG", Types.VARCHAR));
Map result = countryProcedure.execute();
        System.out.println("RETURNCODE: " + result.get("RETURNCODE"));
        System.out.println("RETURNMSG: " + result.get("RETURNMSG"));

Edit :
I looked at it and there is a simpler way. Use the WithReturnValue() on your SimpleJdbcCall and the return value will be stored in the return Map under the "return" key.


问:
How to add a UITextField within a UIPickerView on viewForRow
I tried the below code in UIPickerView's viewForRow event. Textfield is not appearing while labels are appearing. Is it allowed to add textfields within picker views?

This is my code:

```<code>func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    var rowDict = NSDictionary()
    var retView = UIView()

    let label = UILabel(frame: CGRect.init(x: 0, y: 0, width: 400, height: 40) )
    let textField = UITextField(frame: CGRect.init(x: 0, y: 0, width: 400, height: 40) )

    if(pickerView == pickerView2)
    {
        rowDict = self.arrayList02[row] as! NSDictionary
        let rowValue = rowDict["QueryAttribute"] as? String
        label.numberOfLines = 0
        label.text = rowValue
        label.sizeToFit()
        if rowValue == "Other Specify:"{
            textField.placeholderText = rowValue
            textField.isUserInteractionEnabled = true
            retView = textField
        }
        else {
            retView = label
        }
    }

    return retView
}
</code>```

答:
I tried this code to take user input on selecting a particular option in the UIPickerView

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectionHandler?(pickerView, row, arrayList[row] as! String)
        var rowValue = NSDictionary()
        if(arrayList.count > 0) {
            rowValue = self.arrayList[row] as! NSDictionary
            if(rowValue["ItemCode"] as? String != "99"){
                textView.text = rowValue["Item"] as? String
                textView.tag = rowValue["Id"] as! Int
            }

            if(isOtherSpecifyRequired){
                let lastRow = pickerView.numberOfRows(inComponent: component) - 1
                let lastRowValue = rowValue["Item"] as? String
                setOtherSpecifyField(lastRow: lastRow, row: row, lastRowValue: lastRowValue!, textField: textView)
            }
        }
    }

    func setOtherSpecifyField(lastRow: Int, row: Int, lastRowValue: String, textField: CustomTextField){
        if row == lastRow{
            ShowAlertWithTextBox(title: "Other Specify", message: "Please enter some text ", parentView: textField)
            textField.tag = 0
        }
    }

    func ShowAlertWithTextBox(title: String, message: String, parentView: UITextField)
    {
        let alert = UIAlertController(title: title , message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addTextField(configurationHandler: textFieldHandler)
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
        alert.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
            parentView.text = alert.textFields?[0].text }))
        if let presented = _viewController.presentedViewController {
            presented.removeFromParentViewController()
        }
        if _viewController.presentedViewController == nil {
            self._viewController.present(alert, animated: true, completion: nil)
        }
    }

    func textFieldHandler(textField: UITextField!)
    {
        if (textField) != nil {
            textField.placeholder = "Other Specify"
        }
    }
</code>```

Body:
I tried the below code in UIPickerView's viewForRow event. Textfield is not appearing while labels are appearing. Is it allowed to add textfields within picker views?

This is my code:

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    var rowDict = NSDictionary()
    var retView = UIView()

    let label = UILabel(frame: CGRect.init(x: 0, y: 0, width: 400, height: 40) )
    let textField = UITextField(frame: CGRect.init(x: 0, y: 0, width: 400, height: 40) )

    if(pickerView == pickerView2)
    {
        rowDict = self.arrayList02[row] as! NSDictionary
        let rowValue = rowDict["QueryAttribute"] as? String
        label.numberOfLines = 0
        label.text = rowValue
        label.sizeToFit()
        if rowValue == "Other Specify:"{
            textField.placeholderText = rowValue
            textField.isUserInteractionEnabled = true
            retView = textField
        }
        else {
            retView = label
        }
    }

    return retView
}

Body:
I tried this code to take user input on selecting a particular option in the UIPickerView

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectionHandler?(pickerView, row, arrayList[row] as! String)
        var rowValue = NSDictionary()
        if(arrayList.count > 0) {
            rowValue = self.arrayList[row] as! NSDictionary
            if(rowValue["ItemCode"] as? String != "99"){
                textView.text = rowValue["Item"] as? String
                textView.tag = rowValue["Id"] as! Int
            }

            if(isOtherSpecifyRequired){
                let lastRow = pickerView.numberOfRows(inComponent: component) - 1
                let lastRowValue = rowValue["Item"] as? String
                setOtherSpecifyField(lastRow: lastRow, row: row, lastRowValue: lastRowValue!, textField: textView)
            }
        }
    }

    func setOtherSpecifyField(lastRow: Int, row: Int, lastRowValue: String, textField: CustomTextField){
        if row == lastRow{
            ShowAlertWithTextBox(title: "Other Specify", message: "Please enter some text ", parentView: textField)
            textField.tag = 0
        }
    }

    func ShowAlertWithTextBox(title: String, message: String, parentView: UITextField)
    {
        let alert = UIAlertController(title: title , message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addTextField(configurationHandler: textFieldHandler)
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
        alert.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
            parentView.text = alert.textFields?[0].text }))
        if let presented = _viewController.presentedViewController {
            presented.removeFromParentViewController()
        }
        if _viewController.presentedViewController == nil {
            self._viewController.present(alert, animated: true, completion: nil)
        }
    }

    func textFieldHandler(textField: UITextField!)
    {
        if (textField) != nil {
            textField.placeholder = "Other Specify"
        }
    }


问:
Cucumber : Integration with two different projects
We have two different projects, one in JS and the other with Java, you know if a single cucumber layer can help me integrate between two project, let's say that one project (JS) is running some operations (testing) that appear on the web application and the second project (JAVA) is running the actions on a mobile device, so we want to be able to combine the two actions, mobile and web application, appreciate the help or ideas, thanks Eyal</p>

答:
1) Are they different projects or the same project but there are 2 or 3 out of web, ios or android versions?

2) Must you write your automation suite in the same language as the application to install test data or use it on this suite?

If you answered 1) with "different projects" or 2) with "Yes" - then it's not wise to do this.

If you want to write a library of helper functions for cross platform purposes, then you can definitely do that. I'm currently looking into the 3 platforms myself, dividing my library into modules and requiring the one I need at the start of run time.

EDIT

In your case, I would go for writing a Cucumber JVM framework, as Java has more robust libraries for working with Desktop and Android applications than JS, from what I've seen on this site.


问:
C# create form on separate thread from formless application
I'm currently creating a formless C# application that will act as a SignalR client. The goal is for the client to run silently in the background and show a form when it is triggered by SignalR.

Currently, I'm having an issue showing the GUI. Since SignalR needs to run asynchronously, and I can't have an async Main() method, I currently have to use Task.ContinueWith

```<code>static void Main()
{
    _url = "https://localhost:44300";

    var hubConnection = new HubConnection(_url);
    var hubProxy = hubConnection.CreateHubProxy("HubName");

    hubConnection.Start().ContinueWith(task =>
    {
        if (task.IsFaulted)
        {
            MessageBox.Show("There was an error opening the connection");
        }
        else
        {
            Trace.WriteLine("Connection established");
        }
    }).Wait();

    hubProxy.On("showForm", showForm);
    Application.Run();
}
</code>```

This is the showForm method:

```<code>private static void ShowForm()
{
    var alertForm = new AlertForm();
    alertForm.Show();
}
</code>```

This works fine at first - it connects to the hub, and calls the showForm() method when I call showForm from the server. However, the form never renders and shows as Not Responding. Calling .ShowDialog will mean the form actually renders, but the SignalR client stops listening to the hub.

So, how can I show the form such that it runs on a separate thread and doesn't block the execution of my SignalR client?

答:
The problem with your code is; although you create a message loop with Application.Run in Main, hubProxy.On is executed on a different thread.
Simplest solution would be running every instance of AlertForm in its own thread with its own message loop.

```<code>private static void ShowForm()
{
    var t = new Thread(() =>
    {
        var alertForm = new AlertForm();
        alertForm.Show();
        Application.Run(alertForm); //Begins running a standard application message loop on the current thread, and makes the specified form visible.
    });
    t.SetApartmentState(ApartmentState.STA);
    t.Start();
}
</code>```

Body:
I'm currently creating a formless C# application that will act as a SignalR client. The goal is for the client to run silently in the background and show a form when it is triggered by SignalR.

Currently, I'm having an issue showing the GUI. Since SignalR needs to run asynchronously, and I can't have an async Main() method, I currently have to use Task.ContinueWith

static void Main()
{
    _url = "https://localhost:44300";

    var hubConnection = new HubConnection(_url);
    var hubProxy = hubConnection.CreateHubProxy("HubName");

    hubConnection.Start().ContinueWith(task =>
    {
        if (task.IsFaulted)
        {
            MessageBox.Show("There was an error opening the connection");
        }
        else
        {
            Trace.WriteLine("Connection established");
        }
    }).Wait();

    hubProxy.On("showForm", showForm);
    Application.Run();
}

This is the showForm method:

private static void ShowForm()
{
    var alertForm = new AlertForm();
    alertForm.Show();
}

This works fine at first - it connects to the hub, and calls the showForm() method when I call showForm from the server. However, the form never renders and shows as Not Responding. Calling .ShowDialog will mean the form actually renders, but the SignalR client stops listening to the hub.

So, how can I show the form such that it runs on a separate thread and doesn't block the execution of my SignalR client?

Body:
The problem with your code is; although you create a message loop with Application.Run in Main, hubProxy.On is executed on a different thread.
Simplest solution would be running every instance of AlertForm in its own thread with its own message loop.

private static void ShowForm()
{
    var t = new Thread(() =>
    {
        var alertForm = new AlertForm();
        alertForm.Show();
        Application.Run(alertForm); //Begins running a standard application message loop on the current thread, and makes the specified form visible.
    });
    t.SetApartmentState(ApartmentState.STA);
    t.Start();
}


问:
Unable to clear Test Cases: Am supposed to write code for this:
Apple and Orange problem.

Only 3 of 12 test cases are cleared. Can't think of anything else since hours.

sample input 0

```<code>7 11
5 15
3 2
-2 2 1
5 -6
</code>```

sample output 0

```<code>1
1
</code>```

Problem: https://www.hackerrank.com/challenges/apple-and-orange/problem

Code

```<code>int main(){

    int s;
    int t;
    scanf("%d %d",&s,&t);

    int a;
    int b;
    scanf("%d %d",&a,&b);

    int m;
    int n;
    scanf("%d %d",&m,&n);

    int *apple = malloc(sizeof(int) * m);
    for(int apple_i = 0; apple_i < m; apple_i++){
       scanf("%d",&apple[apple_i]);
    }

    int *orange = malloc(sizeof(int) * n);
    for(int orange_i = 0; orange_i < n; orange_i++){
       scanf("%d",&orange[orange_i]);
    }

    int fellap=0;
    int fellor=0;
    int d;

    for(int apple_i = 0; apple_i < m; apple_i++){
        d=apple[apple_i]+a;
        f(d>=s && d<=t){
            fellap++;
        }
    }

    for(int orange_i = 0; orange_i < n; orange_i ++){
        d=orange[orange_i]+b;
        if(d>=s&&d<=t){
            fellor++;
        }
    }

    printf("%d\n", fellor);
    printf("%d\n", fellap);

    return 0;
}
</code>```

答:
The bug in your code is a very trivial one. You have switched the output of oranges and apples. Change

```<code>printf("%d\n", fellor);
printf("%d\n", fellap);
</code>```

to

```<code>printf("%d\n", fellap);
printf("%d\n", fellor);
</code>```

I don't see the need of reading all values into an array. You can simply traverse the input and do the calculations at the same time. Here is an example that passes all test cases:

Working code that passes all test cases:

```<code>int main(){
    int s;
    int t;
    scanf("%d %d",&s,&t);
    int a;
    int b;
    scanf("%d %d",&a,&b);
    int m;
    int n;
    scanf("%d %d",&m,&n);

    int noApples=0;
    int noOranges=0;

    for(int apple_i = 0; apple_i < m; apple_i++){
        int apple;
        scanf("%d",&apple);
        if (apple+a >= s && t >= apple+a)
            noApples++;
    }

    for(int orange_i = 0; orange_i < n; orange_i++){
        int orange;
        scanf("%d",&orange);
        if (orange+b >= s && t >= orange+b)
            noOranges++;
    }
    printf("%d\n%d\n", noApples, noOranges);
    return 0;
}
</code>```

Body:
Apple and Orange problem.

Only 3 of 12 test cases are cleared. Can't think of anything else since hours.

sample input 0

7 11
5 15
3 2
-2 2 1
5 -6

sample output 0

1
1

Problem: https://www.hackerrank.com/challenges/apple-and-orange/problem

Code

int main(){

    int s;
    int t;
    scanf("%d %d",&s,&t);

    int a;
    int b;
    scanf("%d %d",&a,&b);

    int m;
    int n;
    scanf("%d %d",&m,&n);

    int *apple = malloc(sizeof(int) * m);
    for(int apple_i = 0; apple_i < m; apple_i++){
       scanf("%d",&apple[apple_i]);
    }

    int *orange = malloc(sizeof(int) * n);
    for(int orange_i = 0; orange_i < n; orange_i++){
       scanf("%d",&orange[orange_i]);
    }

    int fellap=0;
    int fellor=0;
    int d;

    for(int apple_i = 0; apple_i < m; apple_i++){
        d=apple[apple_i]+a;
        f(d>=s && d<=t){
            fellap++;
        }
    }

    for(int orange_i = 0; orange_i < n; orange_i ++){
        d=orange[orange_i]+b;
        if(d>=s&&d<=t){
            fellor++;
        }
    }

    printf("%d\n", fellor);
    printf("%d\n", fellap);

    return 0;
}

Body:
The bug in your code is a very trivial one. You have switched the output of oranges and apples. Change

printf("%d\n", fellor);
printf("%d\n", fellap);

to

printf("%d\n", fellap);
printf("%d\n", fellor);

I don't see the need of reading all values into an array. You can simply traverse the input and do the calculations at the same time. Here is an example that passes all test cases:

Working code that passes all test cases:

int main(){
    int s;
    int t;
    scanf("%d %d",&s,&t);
    int a;
    int b;
    scanf("%d %d",&a,&b);
    int m;
    int n;
    scanf("%d %d",&m,&n);

    int noApples=0;
    int noOranges=0;

    for(int apple_i = 0; apple_i < m; apple_i++){
        int apple;
        scanf("%d",&apple);
        if (apple+a >= s && t >= apple+a)
            noApples++;
    }

    for(int orange_i = 0; orange_i < n; orange_i++){
        int orange;
        scanf("%d",&orange);
        if (orange+b >= s && t >= orange+b)
            noOranges++;
    }
    printf("%d\n%d\n", noApples, noOranges);
    return 0;
}


问:
Bash - How to get multi line text between XML tags
I have a text file...

```<code># <?xml version="1.0" encoding="UTF-8"?>
<response>
<content>Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K</content>
</response>
</code>```

and I want to extract the text between <content> up to </content>. I have tried:

```<code>grep -oP '(?<=<content> ).*?(?= </content>)' file
</code>```

But it doesn't output anything, I want the end result to be like this:

```<code>Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K
</code>```

How can I do this?

答:
try with an awk solution too here.

```<code>awk '/<\/content>/{sub(/<\/content>/,"");print;A="";next} /<content>/{sub(/<content>/,"");A=1} A'   Input_file
</code>```

Looking for string , if any line has that then substituting it with NULL and printing the current line, then making variable A's value to NULL. Mentioning next will skip all further statements.
Now looking for string  if any line has that then substitute the string with NULL and make a variable A with value 1 assign to it.

Now writing only variable A means it is a condition which will check if A's value is TRUE(NOT NULL) then it will print the current line.(A's value will be only TRUE when starting string  found and will be set to NULL when a close string  is found in any line).

Body:
I have a text file...

# <?xml version="1.0" encoding="UTF-8"?>
<response>
<content>Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K</content>
</response>

and I want to extract the text between <content> up to </content>. I have tried:

grep -oP '(?<=<content> ).*?(?= </content>)' file

But it doesn't output anything, I want the end result to be like this:

Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K

How can I do this?

Body:
try with an awk solution too here.

awk '/<\/content>/{sub(/<\/content>/,"");print;A="";next} /<content>/{sub(/<content>/,"");A=1} A'   Input_file

Looking for string , if any line has that then substituting it with NULL and printing the current line, then making variable A's value to NULL. Mentioning next will skip all further statements.
Now looking for string  if any line has that then substitute the string with NULL and make a variable A with value 1 assign to it.

Now writing only variable A means it is a condition which will check if A's value is TRUE(NOT NULL) then it will print the current line.(A's value will be only TRUE when starting string  found and will be set to NULL when a close string  is found in any line).


问:
Having axis ticks show fully for errorbar plot in Matplotlib
I am trying to plot a graph using Matplotlib using the following code:

```<code>fig, axs = plt.subplots()
axs.set_xlim([1,5])
axs.grid()
axs.errorbar(plot1_dataerr[1],range(len(plot1_dataerr[1])),xerr = plot1_dataerr[2], fmt = 'k o')
axs.yaxis.set_ticks(np.arange(len(plot1_dataerr[1])))
axs.set_yticklabels(plot1_dataerr[0])
</code>```

The variable plot1_dataerr contains the labels for the data as its 0th element, the actual means as the 1st element and the half-length of the error bars as the second element. When I run this code (along with the exact data) I get the following:

However as you can see some of the ticks on the y-axis are cut off, they should all start with 'vegetable based side dishes'. Does anyone know what I should change so that everything fits. I don't mind if some of the labels need to occupy 2 lines.

Thanks in advance!

答:
You probably need to increase the left margin. For automatic adjustment, use

```<code>fig.tight_layout()
</code>```

Else, start with

```<code>fig.subplots_adjust(left=0.4)
</code>```

and decrease the value until you are happy with the result.

Body:
I am trying to plot a graph using Matplotlib using the following code:

fig, axs = plt.subplots()
axs.set_xlim([1,5])
axs.grid()
axs.errorbar(plot1_dataerr[1],range(len(plot1_dataerr[1])),xerr = plot1_dataerr[2], fmt = 'k o')
axs.yaxis.set_ticks(np.arange(len(plot1_dataerr[1])))
axs.set_yticklabels(plot1_dataerr[0])

The variable plot1_dataerr contains the labels for the data as its 0th element, the actual means as the 1st element and the half-length of the error bars as the second element. When I run this code (along with the exact data) I get the following:

However as you can see some of the ticks on the y-axis are cut off, they should all start with 'vegetable based side dishes'. Does anyone know what I should change so that everything fits. I don't mind if some of the labels need to occupy 2 lines.

Thanks in advance!

Body:
You probably need to increase the left margin. For automatic adjustment, use

fig.tight_layout()

Else, start with

fig.subplots_adjust(left=0.4)

and decrease the value until you are happy with the result.


问:
D3 force graph doesn't pan or zoom as expected
I've built a D3 force graph largely based on these really helpful examples.

I wanted to add pan and zoom functionality, which I tried to do using another example (looks like I can only include two links, but Google "d3 force zoom eyaler" to find it).

Unfortunately, when I zoom out on a graph that is larger than the initial SVG, I get something like this:

Result of dragging and dropping

Here's the relevant code:

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(d3.behavior.zoom().scaleExtent([0.5,2]).on("zoom", redraw));

function redraw() {
  svg.attr("transform",
      "translate(" + d3.event.translate + ")"
      + " scale(" + d3.event.scale + ")");
}```

How can I change the pan and zoom behaviour so that it scrolls and makes it possible to see the rest of the graph, rather than just allowing me to move the square that was originally visible?

答:
OK, looks like I worked it out... you need to perform the transform on a <g> rather than on the SVG itself. So:

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(d3.behavior.zoom().scaleExtent([0.5,2]).on("zoom", redraw));

var g = svg.append("g"); // add <g>

function redraw() {
  g.attr("transform",    // perform transform on g, not svg
      "translate(" + d3.event.translate + ")"
      + " scale(" + d3.event.scale + ")");
}```

Just putting this here in case anyone else made the same mistake!

Body:
I've built a D3 force graph largely based on these really helpful examples.

I wanted to add pan and zoom functionality, which I tried to do using another example (looks like I can only include two links, but Google "d3 force zoom eyaler" to find it).

Unfortunately, when I zoom out on a graph that is larger than the initial SVG, I get something like this:

Result of dragging and dropping

Here's the relevant code:

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(d3.behavior.zoom().scaleExtent([0.5,2]).on("zoom", redraw));

function redraw() {
  svg.attr("transform",
      "translate(" + d3.event.translate + ")"
      + " scale(" + d3.event.scale + ")");
}

How can I change the pan and zoom behaviour so that it scrolls and makes it possible to see the rest of the graph, rather than just allowing me to move the square that was originally visible?

Body:
OK, looks like I worked it out... you need to perform the transform on a <g> rather than on the SVG itself. So:

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(d3.behavior.zoom().scaleExtent([0.5,2]).on("zoom", redraw));

var g = svg.append("g"); // add <g>

function redraw() {
  g.attr("transform",    // perform transform on g, not svg
      "translate(" + d3.event.translate + ")"
      + " scale(" + d3.event.scale + ")");
}

Just putting this here in case anyone else made the same mistake!


问:
Group duplicate column IDs in pandas dataframe
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

```<code>df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])
</code>```

then I want the output:

```<code>[('A', 'C'), ('B', 'D')]
</code>```

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

答:
Based on @John Galt one liner which is like this:

```<code>result_col = [x for x in combinations(df.columns, 2) if (df[x[0]] == df[x[-1]]).all()]
</code>```

you can get the result_row as follows:

```<code>result_row = [x for x in combinations(df.T.columns,2) if (df.T[x[0]] == df.T[x[-1]]).all()]
</code>```

using transpose (df.T)

Body:
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])

then I want the output:

[('A', 'C'), ('B', 'D')]

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

Body:
Based on @John Galt one liner which is like this:

result_col = [x for x in combinations(df.columns, 2) if (df[x[0]] == df[x[-1]]).all()]

you can get the result_row as follows:

result_row = [x for x in combinations(df.T.columns,2) if (df.T[x[0]] == df.T[x[-1]]).all()]

using transpose (df.T)


问:
Android Fragments Get Issue With getFragmentManager()
I want to add a fragment into relative layout and here's my MainActivity.java :

```<code>import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        FragmentOne f1 = new FragmentOne();
        fragmentTransaction.add(R.id.fragment_container, f1);
        fragmentTransaction.commit();

    }
}
</code>```

when I run that code, I got this error :

Error:(15, 61) error: incompatible types: android.app.FragmentManager cannot be converted to android.support.v4.app.FragmentManager

how to add fragment into relative layout? I tried to change getFragmentManager(); into getSupportFragmentManager();

also didn't work. any idea what's wrong with this?

UPDATE : here's what I got when I change getFragmentManager(); into getSupportFragmentManager();

答:
Check your imports. You're importing android.support.v4.app.FragmentManager, so the variable FragmentManager fragmentManager is of type android.support.v4.app.FragmentManager but getFragmentManager returns the platform version of fragment manager android.app.FragmentManager, so these are incompatible types.

Since you are using AppCompatActivity, you should be using getSupportFragmentManager.

You say

I tried to change getFragmentManager(); into getSupportFragmentManager(); also didn't work.

What does "also didn't work" mean? That should work.

Body:
I want to add a fragment into relative layout and here's my MainActivity.java :

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        FragmentOne f1 = new FragmentOne();
        fragmentTransaction.add(R.id.fragment_container, f1);
        fragmentTransaction.commit();

    }
}

when I run that code, I got this error :

Error:(15, 61) error: incompatible types: android.app.FragmentManager cannot be converted to android.support.v4.app.FragmentManager

how to add fragment into relative layout? I tried to change getFragmentManager(); into getSupportFragmentManager();

also didn't work. any idea what's wrong with this?

UPDATE : here's what I got when I change getFragmentManager(); into getSupportFragmentManager();


问:
Create RPM package from ANT script under Windows
I need to create an RPM package from an ANT script that runs on a Windows computer.  This package must contain the result classes from the build plus some other, additional resources.

I guess there should be some program somewhere that can be invoked from the command line to create this package.

The reason why I want to do this under windows is that we have a script that builds installers for several different platforms, and everything is already configured for windows so I want to avoid the pain of migrating everything to linux.

Do you know how could this be achieved?

EDIT:
I've used a separate Linux machine to do this.  I copy all files using the scp task, then execute the rpm command remotely using the ssh task.  If this task returns a success code, I copy the resulting rpm back with scp.

答:
Checking the Ant manual, I found the following optional task:

http://ant.apache.org/manual/Tasks/rpm.html

However, this only runs with linux computers

OwnerDisplayName: Mario Ortegón

LastEditorDisplayName: Mario Ortegón


问:
how to create field alias
I've heared that it could be possible to create an alias for a field using Oracle views, is that really possible? can you show a simple example ?

p.s. I need an alias for each field in my table for some reason regarding my application.
thank you in advance.

答:
I wonder if this is what you are looking for. You can alias a field in a SELECT statement, so that the returned results use the alias for the field name instead of the name as it appears in the table or view.

You do it like this:

```<code>SELECT employee_id "Employee ID number", last_name "Employee last name",
first_name "Employee first name" FROM employees;
</code>```

The aliases are the values in quotes. So, for example, "Employee ID number" is the alias for the field employee_id.

The aliases are contained in double quotes here because of the spaces in them.

These aliases are not saved anywhere in the database. You have to create them in your SQL statement each time.

But they solve the problem of naming the fields the way you want when you return the results to the application.

Title: how to create field alias

Body:
I wonder if this is what you are looking for. You can alias a field in a SELECT statement, so that the returned results use the alias for the field name instead of the name as it appears in the table or view.

You do it like this:

SELECT employee_id "Employee ID number", last_name "Employee last name",
first_name "Employee first name" FROM employees;

The aliases are the values in quotes. So, for example, "Employee ID number" is the alias for the field employee_id.

The aliases are contained in double quotes here because of the spaces in them.

These aliases are not saved anywhere in the database. You have to create them in your SQL statement each time.

But they solve the problem of naming the fields the way you want when you return the results to the application.


问:
C# How to prevent ListBox to select first item when you unselect the last one
C# How to prevent ListBox in MultiSimple selection mode to select first item automatically, when you unselect the last one selected item in the box - it happens only if listbox represented by my own class objects, and everything is ok when it represented by string objects. Thnx!</p>

答:
Thank you very much, but i already use some like this. I don't understand why first item of listBox selected everytime i assign preloaded list as DataSource. I resolve this problem, by making another one temporal List of my object class, which items readed from binary file, and then push them one by one to my original List in foreach cycle by listOfObjects.Add(object) method. I know that every time after code ListOfTags.DataSource = null;
            ListOfTags.DataSource = tags;
            ListOfTags.DisplayMember = "Name";  if my tags (it is a List) are preloaded even in code (for example if i write code List<Tag> tags = new List<Tag> {new Tag("1"),new Tag("2"), new Tag("3")}; , this takes situation when first item of listbox selected, and starts selects everytime after that when i try do deselect last selected item in listBox.


问:
How to trigger function call after Subscription task is executed in Angular
I am working on an Angular 4 application that has a service that enables users to upload images. I want my component to be able to be notified whenever this uploading has succeeded. How is that done?

To give an example, this is my function that returns a Subscription object in my service.ts file:

uploadImage(new_image:File) {
  this.uploading = true;
  let url = '/products/photo/';
  let newImagePayload = new FormData();

  newImagePayload.append('photo', new_image, new_image.name);

  return this.queryService.postQueryFormData(url, newImagePayload)
    .subscribe(result => {
      this.uploading = false;
      this.image_location = result['photo'];
    });
}
```

<p>In my component, this function is called:</p>

```let my_subscription = this.cardService.uploadImage(newImage)
   \\ I want to call this.randomfunction() whenever my uploading is finished.
```

<p>How is this done? I expected that I could do something as follows:</p>

```my_subscription.subscribe()
```

But this is apparently not allowed.

答:
You can't use subscribe, because you are receiving back a Subscription from calling the uploadImage method. I suggest you call the subscribe method inside your component and return an Observable instead. You can use the do operator instead to invoke the action that you want to and return an Observable. The code will look as such:

```<code>uploadImage(new_image: File) {
    this.uploading = true;
    let url = '/products/photo/';
    let newImagePayload = new FormData();

    newImagePayload.append('photo', new_image, new_image.name);

    return this.queryService.postQueryFormData(url, newImagePayload).do(result => {
        this.uploading = false;
        this.image_location = result['photo'];
    });
}
</code>```

Then inside your component you can call the subscribe method.

Body:
I am working on an Angular 4 application that has a service that enables users to upload images. I want my component to be able to be notified whenever this uploading has succeeded. How is that done?

To give an example, this is my function that returns a Subscription object in my service.ts file:

uploadImage(new_image:File) {
  this.uploading = true;
  let url = '/products/photo/';
  let newImagePayload = new FormData();

  newImagePayload.append('photo', new_image, new_image.name);

  return this.queryService.postQueryFormData(url, newImagePayload)
    .subscribe(result => {
      this.uploading = false;
      this.image_location = result['photo'];
    });
}

In my component, this function is called:

let my_subscription = this.cardService.uploadImage(newImage)
   \\ I want to call this.randomfunction() whenever my uploading is finished.

How is this done? I expected that I could do something as follows:

my_subscription.subscribe()

But this is apparently not allowed.

Body:
You can't use subscribe, because you are receiving back a Subscription from calling the uploadImage method. I suggest you call the subscribe method inside your component and return an Observable instead. You can use the do operator instead to invoke the action that you want to and return an Observable. The code will look as such:

uploadImage(new_image: File) {
    this.uploading = true;
    let url = '/products/photo/';
    let newImagePayload = new FormData();

    newImagePayload.append('photo', new_image, new_image.name);

    return this.queryService.postQueryFormData(url, newImagePayload).do(result => {
        this.uploading = false;
        this.image_location = result['photo'];
    });
}

Then inside your component you can call the subscribe method.


问:
Wait until page is loaded with Selenium WebDriver for Python
I want to scrape all the data of a page implemented by a infinite scroll. The following python code works.

```<code>for i in range(100):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(5)
</code>```

This means every time I scroll down to the bottom, I need to wait 5 seconds, which is generally enough for the page to finish loading the newly generated contents. But, this may not be time efficient. The page may finish loading the new contents within 5 seconds. How can I detect whether the page finished loading the new contents every time I scroll down? If I can detect this, I can scroll down again to see more contents once I know the page finished loading. This is more time efficient.

答:
On a side note, instead of scrolling down 100 times, you can check if there are no more modifications to the DOM (we are in the case of the bottom of the page being AJAX lazy-loaded)</p>

```<code>def scrollDown(driver, value):
    driver.execute_script("window.scrollBy(0,"+str(value)+")")

# Scroll down the page
def scrollDownAllTheWay(driver):
    old_page = driver.page_source
    while True:
        logging.debug("Scrolling loop")
        for i in range(2):
            scrollDown(driver, 500)
            time.sleep(2)
        new_page = driver.page_source
        if new_page != old_page:
            old_page = new_page
        else:
            break
    return True
</code>```

Body:
I want to scrape all the data of a page implemented by a infinite scroll. The following python code works.

for i in range(100):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(5)

This means every time I scroll down to the bottom, I need to wait 5 seconds, which is generally enough for the page to finish loading the newly generated contents. But, this may not be time efficient. The page may finish loading the new contents within 5 seconds. How can I detect whether the page finished loading the new contents every time I scroll down? If I can detect this, I can scroll down again to see more contents once I know the page finished loading. This is more time efficient.

Body:
On a side note, instead of scrolling down 100 times, you can check if there are no more modifications to the DOM (we are in the case of the bottom of the page being AJAX lazy-loaded)

def scrollDown(driver, value):
    driver.execute_script("window.scrollBy(0,"+str(value)+")")

# Scroll down the page
def scrollDownAllTheWay(driver):
    old_page = driver.page_source
    while True:
        logging.debug("Scrolling loop")
        for i in range(2):
            scrollDown(driver, 500)
            time.sleep(2)
        new_page = driver.page_source
        if new_page != old_page:
            old_page = new_page
        else:
            break
    return True


问:
how to populate foreign key column in SequelizeJs?
I have a database using sql in which User is associated to Account with userId as foreign key.I want to populate that foreign key column.I have tried to search about setters and getters in sequelize but there was not much to get help from</p>

答:
You can do this in a few ways

Setting the id manually

```<code> const acct = await Account.create({/* ... */}); // could also find, if that's your use case
 const user = await User.create({ accountId: acct.id, /* ... */ });
</code>```

Sequelize functions

Assuming that you've setup your associations like this

```<code> User.hasMany(Account)
 Account.belongsTo(User)
</code>```

You can

```<code> // assume `acct` is in scope
 const user = await User.create({/* ... */});
 await user.addAccount(acct);
</code>```

You can also do it the other way around

```<code> await account.setUser(user);
</code>```

(also note that i'm using await which only works in async functions, but this is all possible with promises, too)

Body:
You can do this in a few ways

Setting the id manually

 const acct = await Account.create({/* ... */}); // could also find, if that's your use case
 const user = await User.create({ accountId: acct.id, /* ... */ });

Sequelize functions

Assuming that you've setup your associations like this

 User.hasMany(Account)
 Account.belongsTo(User)

You can

 // assume `acct` is in scope
 const user = await User.create({/* ... */});
 await user.addAccount(acct);

You can also do it the other way around

 await account.setUser(user);

(also note that i'm using await which only works in async functions, but this is all possible with promises, too)


问:
getJobDataMap in Quartz gives Null Pointer exception
I am trying to put some data into Quartz job data map and access them in the class which implements the Job class. But it gives me the Null Pointer exception. When the application is run without the code which access the Job Data Map, it runs fine.

I use a Cron trigger to execute a scheduled job. In this example case, I configured it to run in each 20 seconds.

```<code>@Bean
public Trigger simpleJobTrigger(@Qualifier("simpleJobDetail") JobDetail jobDetail) {

    CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
    factoryBean.setJobDetail(jobDetail);
    factoryBean.setStartDelay(0L);
    factoryBean.setName("test-trigger");
    factoryBean.setStartTime(LocalDateTime.now().toDate());
    factoryBean.setCronExpression("0/20 * * * * ?");
    factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

    try {
        factoryBean.afterPropertiesSet();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return factoryBean.getObject();

}
</code>```

Following is my simpleJobDetail bean.

```<code>@Bean
public JobDetailFactoryBean simpleJobDetail() {
    JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
    factoryBean.setJobClass(Executor.class);
    factoryBean.setDurability(true);
    factoryBean.setName("test-job");
    factoryBean.getJobDataMap().put("caller", "James");
    return factoryBean;
}
</code>```

This is my execute method.

```<code>public class Executor implements Job {

    @Autowired
    ScheduledTaskService scheduledTaskService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

        JobDataMap jobDataMap = null;
        try {
            jobDataMap = jobExecutionContext.getTrigger().getJobDataMap();
            String caller = jobDataMap.get("caller").toString();
            System.out.println("This is called by the user "+caller);
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("UNABLE TO ACCESS THE JOB DATA MAP "+e);
        }

        scheduledTaskService.doThePayment();

    }
}
</code>```

When I run the application, it prints the log given in the catch clause.

UNABLE TO ACCESS THE JOB DATA MAP java.lang.NullPointerException

Why execute method fails to access the JobDataMap ? Is there any configuration or a property I should set? What is the reason for job map to be not available at this point?
How can I get this resolved?

答:
Found the issue in my code.
When accessing the JobDataMap, I have accessed it in following way.

```<code>jobDataMap = jobExecutionContext.getTrigger().getJobDataMap();
</code>```

instead, in my case, I should access it from JobDetails, not from the trigger.

```<code>jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
</code>```

Body:
I am trying to put some data into Quartz job data map and access them in the class which implements the Job class. But it gives me the Null Pointer exception. When the application is run without the code which access the Job Data Map, it runs fine.

I use a Cron trigger to execute a scheduled job. In this example case, I configured it to run in each 20 seconds.

@Bean
public Trigger simpleJobTrigger(@Qualifier("simpleJobDetail") JobDetail jobDetail) {

    CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
    factoryBean.setJobDetail(jobDetail);
    factoryBean.setStartDelay(0L);
    factoryBean.setName("test-trigger");
    factoryBean.setStartTime(LocalDateTime.now().toDate());
    factoryBean.setCronExpression("0/20 * * * * ?");
    factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

    try {
        factoryBean.afterPropertiesSet();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return factoryBean.getObject();

}

Following is my simpleJobDetail bean.

@Bean
public JobDetailFactoryBean simpleJobDetail() {
    JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
    factoryBean.setJobClass(Executor.class);
    factoryBean.setDurability(true);
    factoryBean.setName("test-job");
    factoryBean.getJobDataMap().put("caller", "James");
    return factoryBean;
}

This is my execute method.

public class Executor implements Job {

    @Autowired
    ScheduledTaskService scheduledTaskService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

        JobDataMap jobDataMap = null;
        try {
            jobDataMap = jobExecutionContext.getTrigger().getJobDataMap();
            String caller = jobDataMap.get("caller").toString();
            System.out.println("This is called by the user "+caller);
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("UNABLE TO ACCESS THE JOB DATA MAP "+e);
        }

        scheduledTaskService.doThePayment();

    }
}

When I run the application, it prints the log given in the catch clause.

UNABLE TO ACCESS THE JOB DATA MAP java.lang.NullPointerException

Why execute method fails to access the JobDataMap ? Is there any configuration or a property I should set? What is the reason for job map to be not available at this point?
How can I get this resolved?

Body:
Found the issue in my code.
When accessing the JobDataMap, I have accessed it in following way.

jobDataMap = jobExecutionContext.getTrigger().getJobDataMap();

instead, in my case, I should access it from JobDetails, not from the trigger.

jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();


答:
This should also do:

```<code>[tuple(d.index) for _,d in df.T.groupby(list(df.T.columns)) if len(d) > 1]
</code>```

Yields:

```<code># [('A', 'C'), ('B', 'D')]
</code>```

Title: Group duplicate column IDs in pandas dataframe

Body:
This should also do:

[tuple(d.index) for _,d in df.T.groupby(list(df.T.columns)) if len(d) > 1]

Yields:

# [('A', 'C'), ('B', 'D')]


问:
Button click causes not post back in IE browser asp.net
Its very strange behavior that I'm facing. I have delete button, OnClick  I'm attaching it to that particular event. I'm storing my entire data in Session so, in if(!IsPostBack) i am clearing out the session when the page Initially loads. When i click on the delete button instead of doing IsPostBack = true it does IsPostBack = false in IE and resets the Session data. But, with other browser i do get the expected functionality.
Does any one have any clue about this issue ?

Button tag aspx file,

```<code><tr id="rowPurpose">
<td>
    <asp:Label ID="lblPurpose1" Font-Bold="true" runat="server">Purpose</asp:Label>
</td>
<td width="65">
    <asp:Button ID="btnDeletePurpose1"   Text="Delete" Visible="false" CommandArgument="lblPurpose1" OnClick="Delete_Purpose" runat="server" />
</td>
</tr>
</code>```

C# file:

```<code>void page_load()
{
    rowPurpose.Attributes["onclick"] = "javascript:Method('id')";
    if (!Page.IsPostBack)
    {
        Session["Key"] = null;
    }
}
</code>```

Thanks in advance!

答:
I got this resolved. From my understanding it was happening because of the two events that are firing at the same time one for the Row and other for the Button click. So i just made cell as clickable instead of whole row and this works fine.

Thanks

Body:
Its very strange behavior that I'm facing. I have delete button, OnClick  I'm attaching it to that particular event. I'm storing my entire data in Session so, in if(!IsPostBack) i am clearing out the session when the page Initially loads. When i click on the delete button instead of doing IsPostBack = true it does IsPostBack = false in IE and resets the Session data. But, with other browser i do get the expected functionality.
Does any one have any clue about this issue ?

Button tag aspx file,

    <asp:Label ID="lblPurpose1" Font-Bold="true" runat="server">Purpose</asp:Label>

    <asp:Button ID="btnDeletePurpose1"   Text="Delete" Visible="false" CommandArgument="lblPurpose1" OnClick="Delete_Purpose" runat="server" />

C# file:

void page_load()
{
    rowPurpose.Attributes["onclick"] = "javascript:Method('id')";
    if (!Page.IsPostBack)
    {
        Session["Key"] = null;
    }
}

Thanks in advance!


问:
Refresh the method after item add or delete from SQL database
As in the title, I am developing an application using C# and WPF which acts as a client on many computers and handling a data using SQL within a company. I want it to refresh the views of the items on all computers using this application when one person adds or deletes something from the server's db. I know I might need to use SQL triggers, but I am kind of confused where to start.

just this type of idea:

```<code>private void Timer_Tick(object sender, EventArgs e)
    {
        if (trigger1.triggered == true)
          {
            RefreshView();
            trigger1.triggered == false;
          }
    }
</code>```

答: It's not a trigger you want.  It's Query Notification.</p>

Body:
As in the title, I am developing an application using C# and WPF which acts as a client on many computers and handling a data using SQL within a company. I want it to refresh the views of the items on all computers using this application when one person adds or deletes something from the server's db. I know I might need to use SQL triggers, but I am kind of confused where to start.

just this type of idea:

private void Timer_Tick(object sender, EventArgs e)
    {
        if (trigger1.triggered == true)
          {
            RefreshView();
            trigger1.triggered == false;
          }
    }


问:
Multiple received callbacks in same App.cable.subscription
I'm developing a chat function where I'd like to have several separate events within the same broadcasting channel for:

Message has been delivered

User is typing

User has read message

Along with the regular flow of messages. I have gotten to the point where every single one of these events are correctly hitting the received: (data) -> callback, and displaying correctly to the correct user.

All events are submitted using different triggers on clientside, such as keydown, submit etc and processed differently, but they all in the end hit the same received callback. How can I scope out these events within this same received(data) -> callback to cover functionality as for when a user has stopped typing (but not sent the message?

For instance, when user is typing:

```<code>$(".new_im_message").on("focusin",function(e) {
  var values = $("#typing_user").val();
  App.instantmessage.is_typing(values);
});
</code>```

Processed appropriately and then hits received callback:

```<code>  received: (data) ->
    $(".user_is_typing").show();
</code>```

User is no longer typing, and no message is sent

```<code>$(".new_im_message").on("blur",function(e) {
  var values = $("#typing_user").val();
  App.instantmessage.is_blur(values);
});
</code>```

Processed appropriately and then hits received:

```<code>  received: (data) ->
    $(".user_is_typing").show();
    $(".user_is_typing").hide(); <<<< can't hide and show at the same time..
</code>```

How can I split the events up?

Is it possible to have multiple received callbacks within the same channel? received1(data) received2(data) etc.

If not, Can I condition it out depending on which data-type (is_typing) (is_blur) is hitting the received callback?

If not, Do I actually need to split it up into different channels entirely?

Thanks!

答:
Whenever you call perform() (i.e. when a user types) in your JS code, I suggest passing in the action; i.e. it might look like something like

```<code>@perform('typing')
</code>```

then in your channel (ruby code), you need to have a method that will respond to the action above:

```<code>def subscribed
  stream_from 'someidentifier'
  # this line is optional. I just added this to immediately notify everyone in the chatroom that a new user joined in to the chatroom
  ActionCable.server.broadcast 'someidentifier', action: 'subscribed', user_id: current_user.id
end

# this will be called by the JS `@perform('typing')` above
def typing
  # we then broadcast to everyone in that chat room (a.k.a "someidentifier" chatroom), that a specific user is currently typing a message. Modify this as you wish
  ActionCable.server.broadcast 'someidentifier', action: 'typing', user_id: current_user.id
end

def blur
  ActionCable.server.broadcast 'someidentifer', action: 'blur', user_id: current_user.id
end
</code>```

Then back in your received(data) function in your JS code, we will segregate the action into the appropriate response logic:

```<code>received: (data) ->
  switch data.action
    when 'subscribed'
      # do something when a new user (data.user_id) has joined in the chatroom
      console.log(data.user_id)
    when 'typing'
      # do something when a user (data.user_id) is typing
      console.log(data.user_id)
    when 'blur'
      # do something when a user (data.user_id) stopped typing
      console.log(data.user_id)
</code>```

Body:
I'm developing a chat function where I'd like to have several separate events within the same broadcasting channel for:

Message has been delivered

User is typing

User has read message

Along with the regular flow of messages. I have gotten to the point where every single one of these events are correctly hitting the received: (data) -> callback, and displaying correctly to the correct user.

All events are submitted using different triggers on clientside, such as keydown, submit etc and processed differently, but they all in the end hit the same received callback. How can I scope out these events within this same received(data) -> callback to cover functionality as for when a user has stopped typing (but not sent the message?

For instance, when user is typing:

$(".new_im_message").on("focusin",function(e) {
  var values = $("#typing_user").val();
  App.instantmessage.is_typing(values);
});

Processed appropriately and then hits received callback:

  received: (data) ->
    $(".user_is_typing").show();

User is no longer typing, and no message is sent

$(".new_im_message").on("blur",function(e) {
  var values = $("#typing_user").val();
  App.instantmessage.is_blur(values);
});

Processed appropriately and then hits received:

  received: (data) ->
    $(".user_is_typing").show();
    $(".user_is_typing").hide(); <<<< can't hide and show at the same time..

How can I split the events up?

Is it possible to have multiple received callbacks within the same channel? received1(data) received2(data) etc.

If not, Can I condition it out depending on which data-type (is_typing) (is_blur) is hitting the received callback?

If not, Do I actually need to split it up into different channels entirely?

Thanks!

Body:
Whenever you call perform() (i.e. when a user types) in your JS code, I suggest passing in the action; i.e. it might look like something like

@perform('typing')

then in your channel (ruby code), you need to have a method that will respond to the action above:

def subscribed
  stream_from 'someidentifier'
  # this line is optional. I just added this to immediately notify everyone in the chatroom that a new user joined in to the chatroom
  ActionCable.server.broadcast 'someidentifier', action: 'subscribed', user_id: current_user.id
end

# this will be called by the JS `@perform('typing')` above
def typing
  # we then broadcast to everyone in that chat room (a.k.a "someidentifier" chatroom), that a specific user is currently typing a message. Modify this as you wish
  ActionCable.server.broadcast 'someidentifier', action: 'typing', user_id: current_user.id
end

def blur
  ActionCable.server.broadcast 'someidentifer', action: 'blur', user_id: current_user.id
end

Then back in your received(data) function in your JS code, we will segregate the action into the appropriate response logic:

received: (data) ->
  switch data.action
    when 'subscribed'
      # do something when a new user (data.user_id) has joined in the chatroom
      console.log(data.user_id)
    when 'typing'
      # do something when a user (data.user_id) is typing
      console.log(data.user_id)
    when 'blur'
      # do something when a user (data.user_id) stopped typing
      console.log(data.user_id)


问:
Ho to declare in header is overload operator in struct?
I have a structure in which the operator template type. Want to make the correct announcement of this structure in header. Write the following code

header file

```<code>struct add_positive {
    template<typename T>
    T operator()(T value, const T& now);
};
</code>```

.cpp file

```<code>template<typename T>
add_positive add_positive::operator()(T value, const T& now) {
    if (now >= 0) {
        return value + now;
    }

    return value;
}
</code>```

But when compiling get the following error:

error: prototype for ‘add_positive add_positive::operator()(T, const T&)’ does not match any in class ‘add_positive’
 add_positive add_positive::operator()(T value, const T& now) {
error: candidate is: template<class T> T add_positive::operator()(T, const T&)
  T operator()(T value, const T& now);

Can't understand what I did wrong?

答:
You can simply use an inline definition:

```<code>struct add_positive {
    template<typename T>
    T operator()(T value, const T& now) {
        if (now >= 0) {
           return value + now;
        }
        return value;
     }
};
</code>```

Note that you usually have to provide a definition for your templated function in the header file.

In the header the following should equally work:

```<code>struct add_positive {
    template<typename T>
    T operator()(T value, const T& now);
};

template<typename T>
T add_positive::operator()(T value, const T& now) {
    if (now >= 0) {
       return value + now;
    }
    return value;
 }
</code>```

Body:
I have a structure in which the operator template type. Want to make the correct announcement of this structure in header. Write the following code

header file

struct add_positive {
    template<typename T>
    T operator()(T value, const T& now);
};

.cpp file

template<typename T>
add_positive add_positive::operator()(T value, const T& now) {
    if (now >= 0) {
        return value + now;
    }

    return value;
}

But when compiling get the following error:

error: prototype for ‘add_positive add_positive::operator()(T, const T&)’ does not match any in class ‘add_positive’
 add_positive add_positive::operator()(T value, const T& now) {
error: candidate is: template<class T> T add_positive::operator()(T, const T&)
  T operator()(T value, const T& now);

Can't understand what I did wrong?

Body:
You can simply use an inline definition:

struct add_positive {
    template<typename T>
    T operator()(T value, const T& now) {
        if (now >= 0) {
           return value + now;
        }
        return value;
     }
};

Note that you usually have to provide a definition for your templated function in the header file.

In the header the following should equally work:

struct add_positive {
    template<typename T>
    T operator()(T value, const T& now);
};

template<typename T>
T add_positive::operator()(T value, const T& now) {
    if (now >= 0) {
       return value + now;
    }
    return value;
 }


问:
Can Delphi 6 be installed in Windows 10
Previously, a few weeks back,

I asked a similar question regarding D6 and Windows 7.

After installing Delphi 6 in another path, it worked.

BUT now,

after upgrading from W7 to Windows 10 it no longer works.

I am prompted to register the software.

I do that, and am told the registration was successful.

Attempting to start again I am told license information

 is invalid or missing.

The program will not start.

What is needed to run D6 in a Windows 10 machine?

答:
Restart Delphi and choose register later.
New LM key will be created and you can continue unregistered
Needed to fix legacy code from 2005

Title: Can Delphi 6 be installed in Windows 10


问:
MySQL combine 3 queries into one
I want to get users from database based on 3 notes.

Where hobbies and countries are exactly as given

If number of users returned is less than 100 then go to next

Where hobbies are same but country is different

If number of total returned users is less than 100 then go to next
Where hobbies are different but country is same.

Here is my query that i wrote to get users whose hobbies and country are same.

```<code>SELECT users.*
FROM users
JOIN user_opt ON users.id = user_opt.UserId
WHERE user_opt.Disc=1 AND user_opt.country IN(".implode(',',$Countries).") AND user_opt.Hobbies REGEXP '".implode('|',$Interests)."'
</code>```

Both Countries and Interests are arrays.
Now here is where i am stuck.I don't know how to check if number of returned rows is less than 100 or not.

答:
Separate queries are perfectly fine: You give up consistency at the database layer, but you can fix it up at the application layer. The way to do it in one query is to

```<code>SELECT *
FROM (SELECT 1 AS chunk, users.*
      FROM users
      WHERE foo=bar
      UNION
      SELECT 2, users.*
      FROM users
      WHERE foo=bar AND foobar=barfoo
      UNION
      SELECT 3, users.*
      ...)
ORDER BY chunk
LIMIT 100
</code>```

But this would most likely completely kill the query-planer and cause it to select all matching rows for all "subqueries" and limiting to the desired number of rows after sorting the entire resultset (only to find out that the first part of that union already had 100 rows). Spare the performance, fake it.

Title: MySQL combine 3 queries into one

Body:
I want to get users from database based on 3 notes.

Where hobbies and countries are exactly as given

If number of users returned is less than 100 then go to next

Where hobbies are same but country is different

If number of total returned users is less than 100 then go to next
Where hobbies are different but country is same.

Here is my query that i wrote to get users whose hobbies and country are same.

SELECT users.*
FROM users
JOIN user_opt ON users.id = user_opt.UserId
WHERE user_opt.Disc=1 AND user_opt.country IN(".implode(',',$Countries).") AND user_opt.Hobbies REGEXP '".implode('|',$Interests)."'

Both Countries and Interests are arrays.
Now here is where i am stuck.I don't know how to check if number of returned rows is less than 100 or not.

Body:
Separate queries are perfectly fine: You give up consistency at the database layer, but you can fix it up at the application layer. The way to do it in one query is to

SELECT *
FROM (SELECT 1 AS chunk, users.*
      FROM users
      WHERE foo=bar
      UNION
      SELECT 2, users.*
      FROM users
      WHERE foo=bar AND foobar=barfoo
      UNION
      SELECT 3, users.*
      ...)
ORDER BY chunk
LIMIT 100

But this would most likely completely kill the query-planer and cause it to select all matching rows for all "subqueries" and limiting to the desired number of rows after sorting the entire resultset (only to find out that the first part of that union already had 100 rows). Spare the performance, fake it.


问:
Just messed up a server misusing chown, how to execute it correctly?
I'm moving from an old shared host to a dedicated server at MediaTemple. The server is running Plesk CP, but, as far as I can tell, there's no way via the Interface to do what I want to do.

On the old shared host, running cPanel, I creative a .zip archive of all the website's files. I downloaded this to my computer, then uploaded it with FTP to the new host account I'd set up.

Finally, I logged in via SSH, navigated to the directory the zip was stored in (something like var/www/vhosts/mysite.com/httpdocs/ and ran the unzip command on the file sitearchive.zip. This extracted everything just the fine. The site appeared to work just fine.

The problem: When I tried to edit a file through FTP, I got Error - 160: Permission Denied. When I Get Info for the file I'm trying to edit, it says the owner and group is swimwir1.

I attemped to use chown at this point to change owner - and yes, as you may be able to tell, I'm a little inexperienced in SSH ;) luckily the server was new, since the command I ran - chown -R newuser / appeared to mess a load of stuff up. The reason I used / on the end rather than /var/www/vhosts/mysite.com/httpdocs/ was because I'd already cded into their, so I presumed the / was relative to where I was working. This may be the case, I have no idea, either way - Plesk was no longer accessible, although Apache and things continued to work. I realised my mistake, and deciding it wasn't worth the hassle of 1) being an amateur and 2) trying to fix it, I just reprovisioned the server to start afresh.

So - what do I do to change the owner of these files correctly?

Thanks for helping out a confused beginner!

Jack

答:
Your command does indeed specify an absolute path to the root of the filesystem.  Any path that begins with a '/' is absolute.  You need:

```<code>chown -R newuser .
</code>```

or:

```<code>chown -R newuser /var/www/vhosts/mysite.com/httpdocs
</code>```

Body:
Your command does indeed specify an absolute path to the root of the filesystem.  Any path that begins with a '/' is absolute.  You need:

chown -R newuser .

or:

chown -R newuser /var/www/vhosts/mysite.com/httpdocs


问:
After assigning Elastic IP address, the EC2 instance is no longer accessible
I create a new Amazon EC2 instance, and it is successfully working. I assign an Elastic IP address and after that my instance is not reachable. I did lots of changes in the VPC, ENI and Elastic IP address, but my instance is not reachable by public DNS, also in any region no EC2 instance is reachable by public DNS.</p>

答:
You need to assign an Internet gateway (IGW) to the subnet your EC2 instance belongs to so you can access over the Internet:

http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Internet_Gateway.html


问:
What is the view and ViewGroup passed to ArrayAdapter and RecyclerView adapter?
Im super confused between what is passed to the methods initially.

In ArrayAdapter getview method, What is the View and ViewGroup passed

```<code> public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }
            ....

        }
</code>```

List_item xml is

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.09"
        android:fontFamily="serif"

        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold" />

    ....
</LinearLayout>
</code>```

What is the ViewGroup passed in RecyclerView adapter here.

```<code>@Override
    public NumberViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        Context context = viewGroup.getContext();
        int layoutIdForListItem = R.layout.number_list_item;
        LayoutInflater inflater = LayoutInflater.from(context);
        boolean shouldAttachToParentImmediately = false;

        View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
        NumberViewHolder viewHolder = new NumberViewHolder(view);

        return viewHolder;
    }
</code>```

Number_list_item is

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <TextView
        android:id="@+id/tv_item_number"
        style="@style/TextAppearance.AppCompat.Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|start"
        android:fontFamily="monospace"
        android:textSize="42sp"
        tools:text="#42" />
</FrameLayout>
</code>```

What does the below line do exacty besides inflating the layout.

```<code>View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately
</code>```

答:
```<code>    View view = inflater.inflate(layoutIdForListItem, viewGroup,
                                 shouldAttachToParentImmediately);
</code>```

When you want to show any view on UI it must have some height and width. In a inflate method,

First parameter is a resource id of a view, which should inflate. In a case of Adapter, it should be item view which is going to be recycled.

Second parameter is a ViewGroup, generally parent view. Parent view must be a ViewGroup because ViewGroup contains child views not vice versa. In a case of ListView sometimes size(width) of an inflated view not adopted automatically depends on its parent.

For an example - If a ListView have a width match_parent then there is a possibility width of your inflated view less than its parent if you skipped this parameter.

Third parameter is used to decide whether you want to add your inflated view inside parent ViewGroup(2nd parameter). In a case of ListView, if you make it true then you will get RunTimeException (View already have a parent), this parameter should be true if you want to add new view inside parent view.

For an example - If I want to add View in my UI only after sudden action, then I will inflate a 'View' and add in a ViewGroup.

Body:
Im super confused between what is passed to the methods initially.

In ArrayAdapter getview method, What is the View and ViewGroup passed

 public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }
            ....

        }

List_item xml is

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.09"
        android:fontFamily="serif"

        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold" />

    ....
</LinearLayout>

What is the ViewGroup passed in RecyclerView adapter here.

@Override
    public NumberViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        Context context = viewGroup.getContext();
        int layoutIdForListItem = R.layout.number_list_item;
        LayoutInflater inflater = LayoutInflater.from(context);
        boolean shouldAttachToParentImmediately = false;

        View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
        NumberViewHolder viewHolder = new NumberViewHolder(view);

        return viewHolder;
    }

Number_list_item is

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <TextView
        android:id="@+id/tv_item_number"
        style="@style/TextAppearance.AppCompat.Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|start"
        android:fontFamily="monospace"
        android:textSize="42sp"
        tools:text="#42" />
</FrameLayout>

What does the below line do exacty besides inflating the layout.

View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately

Body:
    View view = inflater.inflate(layoutIdForListItem, viewGroup,
                                 shouldAttachToParentImmediately);

When you want to show any view on UI it must have some height and width. In a inflate method,

First parameter is a resource id of a view, which should inflate. In a case of Adapter, it should be item view which is going to be recycled.

Second parameter is a ViewGroup, generally parent view. Parent view must be a ViewGroup because ViewGroup contains child views not vice versa. In a case of ListView sometimes size(width) of an inflated view not adopted automatically depends on its parent.

For an example - If a ListView have a width match_parent then there is a possibility width of your inflated view less than its parent if you skipped this parameter.

Third parameter is used to decide whether you want to add your inflated view inside parent ViewGroup(2nd parameter). In a case of ListView, if you make it true then you will get RunTimeException (View already have a parent), this parameter should be true if you want to add new view inside parent view.

For an example - If I want to add View in my UI only after sudden action, then I will inflate a 'View' and add in a ViewGroup.


问:
Dedicate every element in a list to a variable
So let's say we have the lists a = [1,2,3,4] and s = ["q", "w", "e", "r"].
I want to dedicate every element in s a value in a, so that print(w) prints 2 and so on. You could write

```<code>for u in range(0, len(a)):
   s[u] = a[u]
</code>```

But here print(w) makes no sense and we get an error.

答:
A dict does exactly this:

```<code>In [1261]: d = dict(zip(s, a))

In [1262]: d
Out[1262]: {'e': 3, 'q': 1, 'r': 4, 'w': 2}
</code>```

To get the value associated with e, simply use dict indexing:

```<code>In [1263]: d['e']
Out[1263]: 3
</code>```

Body:
So let's say we have the lists a = [1,2,3,4] and s = ["q", "w", "e", "r"].
I want to dedicate every element in s a value in a, so that print(w) prints 2 and so on. You could write

for u in range(0, len(a)):
   s[u] = a[u]

But here print(w) makes no sense and we get an error.

Body:
A dict does exactly this:

In [1261]: d = dict(zip(s, a))

In [1262]: d
Out[1262]: {'e': 3, 'q': 1, 'r': 4, 'w': 2}

To get the value associated with e, simply use dict indexing:

In [1263]: d['e']
Out[1263]: 3


问:
Custom alert dialog is shown different in older Api's
When I run my device on API 23
I get this alert dialog

But On API 23 I got this

I used this code

```<code>final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.alertaialog);

final TextView alertmessage = (TextView)dialog.findViewById(R.id.alertmessage);
final TextView alert = (TextView)dialog.findViewById(R.id.message);
final Button button = (Button) dialog.findViewById(R.id.alertbutton);
</code>```

What should I do?

答: Use AppCompatDialog for consistent, Material theming across devices.</p>

Body:
When I run my device on API 23
I get this alert dialog

But On API 23 I got this

I used this code

final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.alertaialog);

final TextView alertmessage = (TextView)dialog.findViewById(R.id.alertmessage);
final TextView alert = (TextView)dialog.findViewById(R.id.message);
final Button button = (Button) dialog.findViewById(R.id.alertbutton);

What should I do?


问:
How to process Every Item In a list
Hi all I'm trying to extract text from several websites
everything works ok but when I run the script I only extract one website
from the domain (list) that I created which has 3 websites
what I'm doing it wrong i need to extract all the domian items to a file

Thanks

```<code>from bs4 import BeautifulSoup
import requests
import urllib3
import certifi

http = urllib3.PoolManager(
    cert_reqs='CERT_REQUIRED',
    ca_certs=certifi.where())

domain =('https://www.betfair.com/exchange/', 'https://docs.python.org/3/library/urllib.parse.html','https://anaconda.org/pypi/urllib3')
for url in domain:
    page = requests.get(url, verify=True)
    soup = BeautifulSoup(page.content, 'html.parser')
    content = (soup.get_text().encode('utf-8'))
    with open("article.txt", "w") as wa, open("article.txt", "r") as ra, open('outfile.txt', "w") as outfile:
        wa.write(content)
        for line in ra:
            if not line.strip(): continue
            outfile.write(line)
</code>```

答:
I believe that you are overwriting the file every time. That's why you should open the files in an append mode, like this:

```<code>with open('filename.txt', 'a'):
    ...
</code>```

Hope it helps

Title: How to process Every Item In a list

Body:
Hi all I'm trying to extract text from several websites
everything works ok but when I run the script I only extract one website
from the domain (list) that I created which has 3 websites
what I'm doing it wrong i need to extract all the domian items to a file

Thanks

from bs4 import BeautifulSoup
import requests
import urllib3
import certifi

http = urllib3.PoolManager(
    cert_reqs='CERT_REQUIRED',
    ca_certs=certifi.where())

domain =('https://www.betfair.com/exchange/', 'https://docs.python.org/3/library/urllib.parse.html','https://anaconda.org/pypi/urllib3')
for url in domain:
    page = requests.get(url, verify=True)
    soup = BeautifulSoup(page.content, 'html.parser')
    content = (soup.get_text().encode('utf-8'))
    with open("article.txt", "w") as wa, open("article.txt", "r") as ra, open('outfile.txt', "w") as outfile:
        wa.write(content)
        for line in ra:
            if not line.strip(): continue
            outfile.write(line)

Body:
I believe that you are overwriting the file every time. That's why you should open the files in an append mode, like this:

with open('filename.txt', 'a'):
    ...

Hope it helps


问:
spring mvc form textarea initial contents
How do I put initial text into a Spring form textarea? The TLD rejects PCData content inside form:textarea. The point of this form is to ask a user to edit/correct some text, so the text has to get into the form in the first place. The JSP page is pulling the text from the model and wants to put it into the textarea.</p>

答:
You could set the initial value with Javascript. You could use  tags to control when you need to set the message in the textbox so the script code will be rendered or not.

Another way it could be setting the text value in the corresponding property of the model attribute, though I think it is more clean the other solution because this message is just a help to the user, so I think it should be done in the view.


问:
How to ignore a click on a specific children in jQuery
I have several divs inside a parent div, and one of the children divs is a check box inside a span tag.
When I click on the parent or the other children of the parent div I want to use the .show() function. But when I click on the checkbox which is also a children I want to ignore the click. How can i do it?

My html logic:

```<code><parent-div>
   <children1>  CONTENT </children1>
   <checkbox> CONTENT </checkbox> // The click shoud be ignored
   <children2>   CONTENT   </children2>
</parent-div>
</code>```

This is my code so far. i´ve tried to do it with the "e.preventDefault();" function.

$(document).ready(function () {

    $(".entry").on('click', function (e) {
        if ($(e.target).is('span')) {
            e.preventDefault();
            return;
        }
        $(this).siblings(".tag-cloud").show(".tag-cloud");
    });

//just for closing
    $(".exit-tags").on('click', function (event) {
        $(this).closest(".tag-cloud").hide(".tag-cloud");
    });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tag-cloud {
display:none;
}

.exit-tags:hover {
cursor: pointer;
color: red;
}
.user, .h4, .ckbox {
float: left;
}</code>```

UserName

      <input type="checkbox" id="checkbox">

                        Movie Name

                      Movie Name

tag1

tag2

                    <form action="">
                        <input type="text" placeholder="Tag eingeben">
                    </form>

                        [ X ]

                            Creation Date

                           Watched Date

```

答:
Did you try using </p>

```<code>event.stopPropagation();
</code>```

Body:
I have several divs inside a parent div, and one of the children divs is a check box inside a span tag.
When I click on the parent or the other children of the parent div I want to use the .show() function. But when I click on the checkbox which is also a children I want to ignore the click. How can i do it?

My html logic:

<parent-div>
   <children1>  CONTENT </children1>
   <checkbox> CONTENT </checkbox> // The click shoud be ignored
   <children2>   CONTENT   </children2>
</parent-div>

This is my code so far. i´ve tried to do it with the "e.preventDefault();" function.

$(document).ready(function () {

    $(".entry").on('click', function (e) {
        if ($(e.target).is('span')) {
            e.preventDefault();
            return;
        }
        $(this).siblings(".tag-cloud").show(".tag-cloud");
    });

//just for closing
    $(".exit-tags").on('click', function (event) {
        $(this).closest(".tag-cloud").hide(".tag-cloud");
    });

});

.tag-cloud {
display:none;
}

.exit-tags:hover {
cursor: pointer;
color: red;
}
.user, .h4, .ckbox {
float: left;
}

UserName

      <input type="checkbox" id="checkbox">

                        Movie Name

                      Movie Name

tag1

tag2

                    <form action="">
                        <input type="text" placeholder="Tag eingeben">
                    </form>

                        [ X ]

                            Creation Date

                           Watched Date

Body:
Did you try using

event.stopPropagation();


问:
Convert first page to tif using Magick.NET
Following gm convert command converts first page of source.pdf to output.tif

```<code>convert source.pdf[0] output.tif
</code>```

I wonder how to do it with Magick.NET library? Following code does not work for me.

```<code>using (MagickImage image = new MagickImage("source.pdf"))
{
  image.Write("output.tif");
}
</code>```

答:
ImageMagick cannot handle PostScript and PDF files itself and by its own,
for this it uses a third party software called Ghostscript.

So, you need to install the latest version of GhostScript before you can convert a pdf using Magick.NET.

After installing GhostScript use following code to extract first page to TIF-file.

```<code>        using (MagickImageCollection image = new MagickImageCollection())
        {
            MagickReadSettings settings = new MagickReadSettings();
            settings.Density = new Density(300, 300); // Settings the density to 300 dpi will create an image with a better quality
            settings.FrameIndex = 0; // First page
            settings.FrameCount = 1; // Number of pages
            image.Read(@"source.pdf", settings);
            image.Write(@"output.tif");
        }
</code>```

You can adjust quality of resulting TIF by changing settings.Density param (300 dpi is for high quality offset/digital printing, 72 dpi is ok for monitor screens only).

Body:
Following gm convert command converts first page of source.pdf to output.tif

convert source.pdf[0] output.tif

I wonder how to do it with Magick.NET library? Following code does not work for me.

using (MagickImage image = new MagickImage("source.pdf"))
{
  image.Write("output.tif");
}

Body:
ImageMagick cannot handle PostScript and PDF files itself and by its own,
for this it uses a third party software called Ghostscript.

So, you need to install the latest version of GhostScript before you can convert a pdf using Magick.NET.

After installing GhostScript use following code to extract first page to TIF-file.

        using (MagickImageCollection image = new MagickImageCollection())
        {
            MagickReadSettings settings = new MagickReadSettings();
            settings.Density = new Density(300, 300); // Settings the density to 300 dpi will create an image with a better quality
            settings.FrameIndex = 0; // First page
            settings.FrameCount = 1; // Number of pages
            image.Read(@"source.pdf", settings);
            image.Write(@"output.tif");
        }

You can adjust quality of resulting TIF by changing settings.Density param (300 dpi is for high quality offset/digital printing, 72 dpi is ok for monitor screens only).


问:
Create a dynamic menu in Umbraco 7
I am working on Umbraco and struggling to create dynamic menu in Umbraco.

The menu li's should be called using menuTitle.

The code I have currently is in partial views.

```<code><nav>
  <ul>
    <li>
      <a href="#">Home</a>
    <li>

    @foreach (var m in Model.Menu)
    {
      <li>
        <a href="@m.Url">@m.menuTitle</a>
      </li>
    }
  </ul>
</nav>
<div class="clear"></div>
</code>```

答:
I Think following will do the trick.</p>

```<code>@{
    @* Get the root of the website *@
    var root = CurrentPage.AncestorOrSelf(1);
}

<ul>
    @foreach (var page in root.Children.Where("Visible"))
    {
        <li class="@(page.IsAncestorOrSelf(CurrentPage) ? "current" : null)">
            <a href="@page.Url">@page.Name</a>
        </li>
    }
</ul>
</code>```

Title: Create a dynamic menu in Umbraco 7

Body:
I am working on Umbraco and struggling to create dynamic menu in Umbraco.

The menu li's should be called using menuTitle.

The code I have currently is in partial views.

      Home

    @foreach (var m in Model.Menu)
    {

        @m.menuTitle

    }

Body:
I Think following will do the trick.

@{
    @* Get the root of the website *@
    var root = CurrentPage.AncestorOrSelf(1);
}

<ul>
    @foreach (var page in root.Children.Where("Visible"))
    {
        <li class="@(page.IsAncestorOrSelf(CurrentPage) ? "current" : null)">
            <a href="@page.Url">@page.Name</a>
        </li>
    }
</ul>