问:
order by absolute values of one column while keeping equal values of another column together in R
Example data.frame:

```<code>df <- data.frame(study = c('A', 'A', 'B', 'C', 'D', 'D'),
                 similarity = c(0.61, 0.58, -0.605, 0.4, 0.607, 0.3))

df
   study similarity
1     A      0.610
2     A      0.580
3     B     -0.605
4     C      0.400
5     D      0.607
6     D      0.300
</code>```

I want to order by absolute similarity, but keeping equal values of study together. For the above example the result should be:

```<code>   study similarity
1     A      0.610
2     A      0.580
5     D      0.607
6     D      0.300
3     B     -0.605
4     C      0.400
</code>```

答:
In base R </p>

```<code>df[order(-ave(df$similarity,df$study,FUN=function(x) max(abs(x))),df$study),]
  study similarity
1     A      0.610
2     A      0.580
5     D      0.607
6     D      0.300
3     B     -0.605
4     C      0.400
</code>```

Body:
Example data.frame:

df <- data.frame(study = c('A', 'A', 'B', 'C', 'D', 'D'),
                 similarity = c(0.61, 0.58, -0.605, 0.4, 0.607, 0.3))

df
   study similarity
1     A      0.610
2     A      0.580
3     B     -0.605
4     C      0.400
5     D      0.607
6     D      0.300

I want to order by absolute similarity, but keeping equal values of study together. For the above example the result should be:

   study similarity
1     A      0.610
2     A      0.580
5     D      0.607
6     D      0.300
3     B     -0.605
4     C      0.400

Body:
In base R

df[order(-ave(df$similarity,df$study,FUN=function(x) max(abs(x))),df$study),]
  study similarity
1     A      0.610
2     A      0.580
5     D      0.607
6     D      0.300
3     B     -0.605
4     C      0.400


来源: stackexchange

问:
Physics Engine - Determining the velocity of objects after collision
While researching information for my physics engine, I have come across a problem with determining the velocities of objects (or the magnitude of the "impulse" of the collision) after a collision. Numerous sources have said to use the Coefficient of restitution, but according to Wikipedia, this depends on the properties of both the objects in the collision. Unfortunately, to determine the CoR, you need to know the final velocities of the objects!</p>

答:
Well, you'll have to pick one, or make one up.

The thing is that the two questions are dual -- that is, the one you use is determined by your point of view, or choice.

So, do you know more about the objects?  FIgure out their coefficient from that.  If you have an idea of the velocities after impact, you can work the problem backwards.

If you have neither one, pick a value and see if they behave the way you expect, and if not, frob the values.

And why doesn't Chrome know how to spell "frob"?  It should know all the words in the Jargon File.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Jsoup. Print all text nodes in order
I want to parse this with Jsoup (this is a simplification, I would be parsing entire web pages)

```<code><html><body><p>A<strong>B</strong>C<strong>D</strong>E</p></body></html>
</code>```

to obtain all text elements in the order they appear, this is:

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

I have tried two approaches:

```<code>Elements elements = doc.children().select("*");
for (Element el : elements)
    System.out.println(el.ownText());
</code>```

which returns:

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

This is, the elements between "strong" tags go at the end.

I have also tried a recursive version:

```<code>myfunction(doc.children());

private void myfunction(Elements elements) {
  for (Element el : elements){
    List<Node> nodos = el.childNodes();
    for (Node nodo : nodos) {
      if (nodo instanceof TextNode && !((TextNode) nodo).isBlank()) {
      System.out.println(((TextNode) nodo).text());
    }
  }
  myfunction(el.children());
}
</code>```

But the result is the same as before.

How can this be accomplished? I feel I am making difficult something simple ...

答:
The text() method will do the trick e.g. below

```<code>    public static void main(String[] args) {
            Document doc = Jsoup.parse("<html><body><p>A<strong>B</strong>C<strong>D</strong>E</p></body></html>");
            String texts = doc.body().text();
            System.out.println(texts);
   }
</code>```

Title: Jsoup. Print all text nodes in order

Body:
I want to parse this with Jsoup (this is a simplification, I would be parsing entire web pages)

ABCDE

to obtain all text elements in the order they appear, this is:

A B C D E

I have tried two approaches:

Elements elements = doc.children().select("*");
for (Element el : elements)
    System.out.println(el.ownText());

which returns:

A C E B D

This is, the elements between "strong" tags go at the end.

I have also tried a recursive version:

myfunction(doc.children());

private void myfunction(Elements elements) {
  for (Element el : elements){
    List<Node> nodos = el.childNodes();
    for (Node nodo : nodos) {
      if (nodo instanceof TextNode && !((TextNode) nodo).isBlank()) {
      System.out.println(((TextNode) nodo).text());
    }
  }
  myfunction(el.children());
}

But the result is the same as before.

How can this be accomplished? I feel I am making difficult something simple ...

Body:
The text() method will do the trick e.g. below

    public static void main(String[] args) {
            Document doc = Jsoup.parse("<html><body><p>A<strong>B</strong>C<strong>D</strong>E</p></body></html>");
            String texts = doc.body().text();
            System.out.println(texts);
   }


问:
Why do jQuery.data and .data() behave differently and access different data?
I used to think that jQuery.data and .data() use the same data but are just 2 ways to access this data. After some tests I found out, that this isn't the case.

data() gets data from data-attributes from the DOM and attaches new or changed data to the DOM-Element while not being displayed in the DOM itself.

jQuery.data behaves pretty similar but don't get the data from the data-attribute.

And both methods don't access the same attached data to the DOM-Element.

```<code>var newDiv = $("#newDiv");
var temp = newDiv.data("test");
console.log(temp); //is default
console.log(newDiv.data("test")); //also default
console.log($.data(newDiv, "test")); //undefined

//change jQueryElement.data
newDiv.data("test", "ElementChange");
console.log(newDiv.data("test")); //now ElementChange

//get and change jQuery.data
console.log($.data(newDiv, "test")); //still undefined
$.data(newDiv, "test", "directChange");
console.log($.data(newDiv, "test")); //now directChange

console.log(newDiv.data("test")); //still ElementChange
</code>```

I made a jsfiddle here: https://jsfiddle.net/mgpfw2rr/

Now I wonder why there are 2 methods with only little differences in their initiation-data? At another question at stackoverflow the answer was, that both do the same thing (Differences between jQuery.data() and .data()?) which doesn't seem to be correct or?

Thanks for your help in advance!

答:
As mention by Andreas it even stands in the documentation that jQuery.data doesn't retrieve the data and that .data() is just a new more comfortable method.

Thanks, I thought there would be "more" and didn't notice this at the documentation!

Body:
I used to think that jQuery.data and .data() use the same data but are just 2 ways to access this data. After some tests I found out, that this isn't the case.

data() gets data from data-attributes from the DOM and attaches new or changed data to the DOM-Element while not being displayed in the DOM itself.

jQuery.data behaves pretty similar but don't get the data from the data-attribute.

And both methods don't access the same attached data to the DOM-Element.

var newDiv = $("#newDiv");
var temp = newDiv.data("test");
console.log(temp); //is default
console.log(newDiv.data("test")); //also default
console.log($.data(newDiv, "test")); //undefined

//change jQueryElement.data
newDiv.data("test", "ElementChange");
console.log(newDiv.data("test")); //now ElementChange

//get and change jQuery.data
console.log($.data(newDiv, "test")); //still undefined
$.data(newDiv, "test", "directChange");
console.log($.data(newDiv, "test")); //now directChange

console.log(newDiv.data("test")); //still ElementChange

I made a jsfiddle here: https://jsfiddle.net/mgpfw2rr/

Now I wonder why there are 2 methods with only little differences in their initiation-data? At another question at stackoverflow the answer was, that both do the same thing (Differences between jQuery.data() and .data()?) which doesn't seem to be correct or?

Thanks for your help in advance!


问:
How to access a gridview column on rowdatabound ?
I would like to change the value of my gridview column to active when the value is 1.
I have gridview column like

```<code><asp:BoundField   DataField="STATUS" HeaderText="STATUS" SortExpression="STATUS" HeaderStyle-HorizontalAlign="Left">
                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:BoundField>
</code>```

and cs code

```<code> protected void gvCategory_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[5].Text=="0")
            {
                e.Row.Cells[5].Text = "INACTIVE";
            }
        }
    }
</code>```

This is working but it would fail if i change the column order.
What i need is something like findControl function.
Thanks.

答:
Cleaner easier to read LINQ. Tim's did not work for me.</p>

```<code>private int GetFirstGridViewColIndex(string dataField, object sender)
{
    var boundFieldColumns = ((GridView)sender).Columns.Cast<BoundField>();

    return boundFieldColumns.Where((column, index) => string.Equals(column.DataField, dataField, StringComparison.InvariantCultureIgnoreCase))
        .Select((column, index) => index)
        .First();
}
</code>```

Body:
I would like to change the value of my gridview column to active when the value is 1.
I have gridview column like

<asp:BoundField   DataField="STATUS" HeaderText="STATUS" SortExpression="STATUS" HeaderStyle-HorizontalAlign="Left">
                <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:BoundField>

and cs code

 protected void gvCategory_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[5].Text=="0")
            {
                e.Row.Cells[5].Text = "INACTIVE";
            }
        }
    }

This is working but it would fail if i change the column order.
What i need is something like findControl function.
Thanks.

Body:
Cleaner easier to read LINQ. Tim's did not work for me.

private int GetFirstGridViewColIndex(string dataField, object sender)
{
    var boundFieldColumns = ((GridView)sender).Columns.Cast<BoundField>();

    return boundFieldColumns.Where((column, index) => string.Equals(column.DataField, dataField, StringComparison.InvariantCultureIgnoreCase))
        .Select((column, index) => index)
        .First();
}


问:
How to show a datepicker after pressing a TableView cell swipe edit action
I want to show a datepicker after pressing a tableview swipe edit action button. It is called postpone, and after opening a datepicker, I want my user to choose a date and press done button of datepicker's toolbar. I've created the datepicker and toolbar but I don't know how to show it with the edit action.

Here is the datepicker code :

```<code>func createDatePicker() {
    picker.datePickerMode = .date

    let toolbar = UIToolbar()
    toolbar.barStyle = UIBarStyle.default
    toolbar.isTranslucent = true
    toolbar.tintColor = UIColor(red: 189/255, green: 194/255, blue: 201/255, alpha: 1)
    toolbar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))
    doneButton.tintColor = UIColor.black
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelPicker))
    cancelButton.tintColor = UIColor.black

    toolbar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolbar.isUserInteractionEnabled = true

    //dateTimeTextField.inputAccessoryView = toolbar (I was using this part to open a datepicker with a text field but I don't know how to modify it for the edit action)
    //dateTimeTextField.inputView = picker
    picker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
}
</code>```

The edit action code :

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
{
    let postpone = UITableViewRowAction(style: .normal, title: "Postpone"){(UITableViewRowAction,NSIndexPath) -> Void in
        self.tasks[indexPath.row].status = "postpone"
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: self.tasks)
        UserDefaults.standard.removeObject(forKey: "taskList")
        UserDefaults.standard.set(encodedData, forKey: "taskList")
        self.taskTableView.reloadData()
    }
    postpone.backgroundColor = UIColor.init(red: 222/255, green: 119/255, blue: 49/255, alpha: 1)

    return [done, cancel, postpone]
}
</code>```

Edit Action buttons image:

Datepicker image in a different page :

Update ~ After I added this code

```<code>picker.addSubview(toolbar)
    taskTableView.addSubview(picker)
    taskTableView.bringSubview(toFront: picker)
</code>```

答:
You can show the datePicker adding it to your view:

```<code>func createDatePicker() {
    picker.datePickerMode = .date

    let toolbar = UIToolbar()
    toolbar.barStyle = UIBarStyle.default
    toolbar.isTranslucent = true
    toolbar.tintColor = UIColor(red: 189/255, green: 194/255, blue: 201/255, alpha: 1)
    toolbar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))
    doneButton.tintColor = UIColor.black
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelPicker))
    cancelButton.tintColor = UIColor.black

    toolbar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolbar.isUserInteractionEnabled = true

    picker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)

    //add the picker to your view or tableView if you use UITableViewController
    taskTableView.addSubview(picker)
    taskTableView.bringSubview(toFront: picker)
}

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let postpone = UITableViewRowAction(style: .normal, title: "Postpone"){(UITableViewRowAction,NSIndexPath) -> Void in
        self.tasks[indexPath.row].status = "postpone"
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: self.tasks)
        UserDefaults.standard.removeObject(forKey: "taskList")
        UserDefaults.standard.set(encodedData, forKey: "taskList")
        self.taskTableView.reloadData()

        //show your date picker
        self.createDatePicker()

    }
    postpone.backgroundColor = UIColor.init(red: 222/255, green: 119/255, blue: 49/255, alpha: 1)

    return [done, cancel, postpone]
}
</code>```

To remove the picker call: picker.removeFromSuperview()

Body:
I want to show a datepicker after pressing a tableview swipe edit action button. It is called postpone, and after opening a datepicker, I want my user to choose a date and press done button of datepicker's toolbar. I've created the datepicker and toolbar but I don't know how to show it with the edit action.

Here is the datepicker code :

func createDatePicker() {
    picker.datePickerMode = .date

    let toolbar = UIToolbar()
    toolbar.barStyle = UIBarStyle.default
    toolbar.isTranslucent = true
    toolbar.tintColor = UIColor(red: 189/255, green: 194/255, blue: 201/255, alpha: 1)
    toolbar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))
    doneButton.tintColor = UIColor.black
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelPicker))
    cancelButton.tintColor = UIColor.black

    toolbar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolbar.isUserInteractionEnabled = true

    //dateTimeTextField.inputAccessoryView = toolbar (I was using this part to open a datepicker with a text field but I don't know how to modify it for the edit action)
    //dateTimeTextField.inputView = picker
    picker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
}

The edit action code :

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
{
    let postpone = UITableViewRowAction(style: .normal, title: "Postpone"){(UITableViewRowAction,NSIndexPath) -> Void in
        self.tasks[indexPath.row].status = "postpone"
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: self.tasks)
        UserDefaults.standard.removeObject(forKey: "taskList")
        UserDefaults.standard.set(encodedData, forKey: "taskList")
        self.taskTableView.reloadData()
    }
    postpone.backgroundColor = UIColor.init(red: 222/255, green: 119/255, blue: 49/255, alpha: 1)

    return [done, cancel, postpone]
}

Edit Action buttons image:

Datepicker image in a different page :

Update ~ After I added this code

picker.addSubview(toolbar)
    taskTableView.addSubview(picker)
    taskTableView.bringSubview(toFront: picker)

Body:
You can show the datePicker adding it to your view:

func createDatePicker() {
    picker.datePickerMode = .date

    let toolbar = UIToolbar()
    toolbar.barStyle = UIBarStyle.default
    toolbar.isTranslucent = true
    toolbar.tintColor = UIColor(red: 189/255, green: 194/255, blue: 201/255, alpha: 1)
    toolbar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))
    doneButton.tintColor = UIColor.black
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelPicker))
    cancelButton.tintColor = UIColor.black

    toolbar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolbar.isUserInteractionEnabled = true

    picker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)

    //add the picker to your view or tableView if you use UITableViewController
    taskTableView.addSubview(picker)
    taskTableView.bringSubview(toFront: picker)
}

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let postpone = UITableViewRowAction(style: .normal, title: "Postpone"){(UITableViewRowAction,NSIndexPath) -> Void in
        self.tasks[indexPath.row].status = "postpone"
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: self.tasks)
        UserDefaults.standard.removeObject(forKey: "taskList")
        UserDefaults.standard.set(encodedData, forKey: "taskList")
        self.taskTableView.reloadData()

        //show your date picker
        self.createDatePicker()

    }
    postpone.backgroundColor = UIColor.init(red: 222/255, green: 119/255, blue: 49/255, alpha: 1)

    return [done, cancel, postpone]
}

To remove the picker call: picker.removeFromSuperview()


问:
json files and called features not found in jenkins (with Karate Framework)

In my feature I have:
* def bar = read('classpath:features/xxx/foo.json')

But when I run tests in Jenkins, I have an error:

```<code>java.lang.RuntimeException: javascript evaluation failed: read('classpath:features/xxx/foo.json')
  at com.intuit.karate.Script.evalInNashorn(Script.java:423)
  at com.intuit.karate.Script.evalInNashorn(Script.java:394)
  at com.intuit.karate.Script.eval(Script.java:316)
  at com.intuit.karate.Script.eval(Script.java:194)
  at com.intuit.karate.Script.assign(Script.java:656)
  at com.intuit.karate.Script.assign(Script.java:587)
  at com.intuit.karate.StepDefs.def(StepDefs.java:265)
  at ✽.* def u = read('classpath:features/xxx/foo.json')(features/XXX/calling.feature:7)
Caused by: com.intuit.karate.exception.KarateFileNotFoundException: file not
</code>```

found: features/xxx/foo.json, classpath: true
        at com.intuit.karate.FileUtils.readFileAsString(FileUtils.java:104)
        at com.intuit.karate.FileUtils.readFile(FileUtils.java:80)
        at jdk.nashorn.internal.scripts.Script$Recompilation$8$15A$\^eval_.L:1(:3)
        at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:639)
        at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
        at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
        at jdk.nashorn.api.scripting.ScriptObjectMirror.call(ScriptObjectMirror.java:117)
        at jdk.nashorn.internal.scripts.Script$19$\^eval_.:program(:1)
        at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
        at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
        at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
        at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:449)
        at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
        at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
        at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
        at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
        at com.intuit.karate.Script.evalInNashorn(Script.java:419)
        at com.intuit.karate.Script.evalInNashorn(Script.java:394)
        at com.intuit.karate.Script.eval(Script.java:316)
        at com.intuit.karate.Script.eval(Script.java:194)
        at com.intuit.karate.Script.assign(Script.java:656)
        at com.intuit.karate.Script.assign(Script.java:587)
        at com.intuit.karate.StepDefs.def(StepDefs.java:265)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at cucumber.runtime.Utils$1.call(Utils.java:40)
        at cucumber.runtime.Timeout.timeout(Timeout.java:16)
        at cucumber.runtime.Utils.invoke(Utils.java:34)
        at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
        at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
        at com.intuit.karate.cucumber.CucumberUtils.runStep(CucumberUtils.java:136)
        at com.intuit.karate.cucumber.KarateRuntime.runStep(KarateRuntime.java:78)
        at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
        at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
        at cucumber.runtime.model.CucumberScenario.runBackground(CucumberScenario.java:59)
        at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:42)
        at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
        at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
        at com.intuit.karate.cucumber.CucumberRunner.lambda$parallel$0(CucumberRunner.java:84)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

`

What is wrong?

答:
If I understand your question correctly (it severely lacks details), everything works fine on your local machine, but does not work when running on Jenkins.

Don't you have a little bit more stack trace to provide ?

There could be so many possible reasons. Maybe on Jenkins, non-Java files are not being copied correctly to target/test-classes. Check whether the pom.xml on Jenkins is not behaving differently for example because of a Maven profile. You should work with your Jenkins admin / CI team to solve this.

Body:
In my feature I have:
* def bar = read('classpath:features/xxx/foo.json')

But when I run tests in Jenkins, I have an error:

java.lang.RuntimeException: javascript evaluation failed: read('classpath:features/xxx/foo.json')
  at com.intuit.karate.Script.evalInNashorn(Script.java:423)
  at com.intuit.karate.Script.evalInNashorn(Script.java:394)
  at com.intuit.karate.Script.eval(Script.java:316)
  at com.intuit.karate.Script.eval(Script.java:194)
  at com.intuit.karate.Script.assign(Script.java:656)
  at com.intuit.karate.Script.assign(Script.java:587)
  at com.intuit.karate.StepDefs.def(StepDefs.java:265)
  at ✽.* def u = read('classpath:features/xxx/foo.json')(features/XXX/calling.feature:7)
Caused by: com.intuit.karate.exception.KarateFileNotFoundException: file not

found: features/xxx/foo.json, classpath: true
        at com.intuit.karate.FileUtils.readFileAsString(FileUtils.java:104)
        at com.intuit.karate.FileUtils.readFile(FileUtils.java:80)
        at jdk.nashorn.internal.scripts.Script$Recompilation$8$15A$\^eval_.L:1(:3)
        at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:639)
        at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
        at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
        at jdk.nashorn.api.scripting.ScriptObjectMirror.call(ScriptObjectMirror.java:117)
        at jdk.nashorn.internal.scripts.Script$19$\^eval_.:program(:1)
        at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
        at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
        at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
        at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:449)
        at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
        at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
        at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
        at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
        at com.intuit.karate.Script.evalInNashorn(Script.java:419)
        at com.intuit.karate.Script.evalInNashorn(Script.java:394)
        at com.intuit.karate.Script.eval(Script.java:316)
        at com.intuit.karate.Script.eval(Script.java:194)
        at com.intuit.karate.Script.assign(Script.java:656)
        at com.intuit.karate.Script.assign(Script.java:587)
        at com.intuit.karate.StepDefs.def(StepDefs.java:265)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at cucumber.runtime.Utils$1.call(Utils.java:40)
        at cucumber.runtime.Timeout.timeout(Timeout.java:16)
        at cucumber.runtime.Utils.invoke(Utils.java:34)
        at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
        at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
        at com.intuit.karate.cucumber.CucumberUtils.runStep(CucumberUtils.java:136)
        at com.intuit.karate.cucumber.KarateRuntime.runStep(KarateRuntime.java:78)
        at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
        at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
        at cucumber.runtime.model.CucumberScenario.runBackground(CucumberScenario.java:59)
        at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:42)
        at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
        at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
        at com.intuit.karate.cucumber.CucumberRunner.lambda$parallel$0(CucumberRunner.java:84)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

`

What is wrong?


问:
Disable URL Shortening/ Formatting in Chrome's Console
I'm converting pages from an old format to new via Snippets.  All was right in the world, up until I noticed Chrome's console "shortening" URL's so they would display better.

```<code>var url = "http://www.somewebsite.com/this/is/a/really/really/really/really/long/ass/url/that/will/be/cutoff/later/on/just/wait/wait/for/it/wait/for/it/there/here/are/some/query/strings?awwww=snap&this=is&really=happening"

console.log(url);

// Spits out
// "http://www.somewebsite.com/this/is/a/really/really/really/really/long/ass/u…r/it/there/here/are/some/query/strings?awwww=snap&this=is&really=happening"
</code>```

These aren't the actual URL's, but you get the idea.  Is there a way of removing formatting from Google Chrome's console area?  This snag pretty much ruined all my plans, hoping to not have to use a headless browser just to get raw text output.  :-\

答:
I just had the same problem. I ended up using this little workaround, making the url a non-url by removing leading http/https:</p>

```<code>console.log(url.replace(/^https?:\/\//,""));
</code>```

Body:
I'm converting pages from an old format to new via Snippets.  All was right in the world, up until I noticed Chrome's console "shortening" URL's so they would display better.

var url = "http://www.somewebsite.com/this/is/a/really/really/really/really/long/ass/url/that/will/be/cutoff/later/on/just/wait/wait/for/it/wait/for/it/there/here/are/some/query/strings?awwww=snap&this=is&really=happening"

console.log(url);

// Spits out
// "http://www.somewebsite.com/this/is/a/really/really/really/really/long/ass/u…r/it/there/here/are/some/query/strings?awwww=snap&this=is&really=happening"

These aren't the actual URL's, but you get the idea.  Is there a way of removing formatting from Google Chrome's console area?  This snag pretty much ruined all my plans, hoping to not have to use a headless browser just to get raw text output.  :-\

Body:
I just had the same problem. I ended up using this little workaround, making the url a non-url by removing leading http/https:

console.log(url.replace(/^https?:\/\//,""));

ContentLicense: CC BY-SA 4.0


问:
Regex two digit pairing
I have the following regex I use to find numeric pairs; [0-9][0-9]

If the string is even length, I get exactly what I want.

```<code>string x ="1234";
Regex.Matches(enc, @"[0-9][0-9]")
</code>```

With the regex I get 12,34.

if I have string x="12345" I get 12,34.  How do I modify this if I want 23,45?

答:
Just do it like this:

([0-9]{2})+$

This will match all the pairs, unless you have an odd number of digits, in which case you'll match everything except the first digit. If you need the separate pairs, you can then just split the returned match into sequential pairs.

Live example: https://regex101.com/r/3gNoQd/4

Title: Regex two digit pairing

Body:
I have the following regex I use to find numeric pairs; [0-9][0-9]

If the string is even length, I get exactly what I want.

string x ="1234";
Regex.Matches(enc, @"[0-9][0-9]")

With the regex I get 12,34.

if I have string x="12345" I get 12,34.  How do I modify this if I want 23,45?


问:
How can I merge these regex into one?
(Before I start: I'm doing this in python)

So basically I need my single regex to match all quotation marks immediately before and after my html QUOT tags: If a quotation mark exists in those spaces, I need it to match.

Example:

```<code><QUOT.START> Hello, this doesn't match! <\QUOT.END>

"<QUOT.START> "Hello, this will call 4 matches! " <\QUOT.END> "
</code>```

I have 4 different regexes for this purpose:

```<code>1.   \"+(?=<QUOT\.START>)

2.   (?<=<QUOT\.START>)\"+

3.   \"+(?=<\\QUOT\.END>)

4.   (?<=<\\QUOT\.END>)\"+
</code>```

Can I merge these 4 into basically one?

答:
@ctwheels helped me figure out this (super simple) solution: Being a total newbie at regexes, I didn't know about the |(pipe) syntax . So here is the final regex I wanted (And it works!)</p>

```<code>\"+(?=<QUOT\.START>)|(?<=<QUOT\.START>)\"+|\"+(?=<\\QUOT\.END>)|(?<=<\\QUOT\.END>)\"+
</code>```

Title: How can I merge these regex into one?

Body:
(Before I start: I'm doing this in python)

So basically I need my single regex to match all quotation marks immediately before and after my html QUOT tags: If a quotation mark exists in those spaces, I need it to match.

Example:

<QUOT.START> Hello, this doesn't match! <\QUOT.END>

"<QUOT.START> "Hello, this will call 4 matches! " <\QUOT.END> "

I have 4 different regexes for this purpose:

1.   \"+(?=<QUOT\.START>)

2.   (?<=<QUOT\.START>)\"+

3.   \"+(?=<\\QUOT\.END>)

4.   (?<=<\\QUOT\.END>)\"+

Can I merge these 4 into basically one?

Body:
@ctwheels helped me figure out this (super simple) solution: Being a total newbie at regexes, I didn't know about the |(pipe) syntax . So here is the final regex I wanted (And it works!)

\"+(?=<QUOT\.START>)|(?<=<QUOT\.START>)\"+|\"+(?=<\\QUOT\.END>)|(?<=<\\QUOT\.END>)\"+


问:
My popups are at bottom:0; but after you hover over them 2-3 times they keep going up?
My blog has these popups, and they are at bottom 0. But when you hover over them twice or more times they begin to go up farther each time you hover. Any way to prevent?

Edit: The reason it's doing this is because each time it hovers, the "bottom" resets so it's going -10px from where it last was. I don't know how to stop this.

Answer: I added info.css("bottom', '-10px'); and that fixed it. Thanks to all who answered, though.

答:
In your javascript, change:

```<code>bottom: '-=' + distance,
</code>```

to

```<code>bottom: '+=' + distance,
</code>```

On mouse over you are subtracting -10 pixels to the distance from the bottom. On mouse out, you need to add those -10px.

Sorry for the mix up earlier, I got confused about adding negative numbers.

Body:
In your javascript, change:

bottom: '-=' + distance,

to

bottom: '+=' + distance,

On mouse over you are subtracting -10 pixels to the distance from the bottom. On mouse out, you need to add those -10px.

Sorry for the mix up earlier, I got confused about adding negative numbers.


答:
You can try this:

```<code>s = '<QUOT.START> "Hello, this will call 4 matches! " <\QUOT.END> '
import re
strings = re.findall('\"(.*?)\"', s)
</code>```

Output:

```<code>['Hello, this will call 4 matches! ']
</code>```

Title: How can I merge these regex into one?

Body:
You can try this:

s = '<QUOT.START> "Hello, this will call 4 matches! " <\QUOT.END> '
import re
strings = re.findall('\"(.*?)\"', s)

Output:

['Hello, this will call 4 matches! ']


问:
Using regex in python to extract emails
I wrote the below program to use it for extracting emails that ends with '@aun.edu.ng' in the file 'on_campus.txt' using the regex character asterix. But when I run it, it seems to take the asterix as a string as well.

```<code>import re

def aun_mails():
    mail_file = open('on_campus.txt')
    for m in mail_file:
        m = m.strip()
        if re.search('*@aun.edu.ng', m):

            print m
</code>```

aun_mails()

答:
I think you'll be able to accomplish what you want without the re module.
Take a look at the following example:

```<code>myString = "Blah blah email blah sent by: some.name@aun.edu.ng"
isEmail = myString.endswith('aun.edu.ng') # isEmail will be True in this case

if isEmail == True:
    print myString # or print(myString for python 3.x)
</code>```

Title: Using regex in python to extract emails

Body:
I wrote the below program to use it for extracting emails that ends with '@aun.edu.ng' in the file 'on_campus.txt' using the regex character asterix. But when I run it, it seems to take the asterix as a string as well.

import re

def aun_mails():
    mail_file = open('on_campus.txt')
    for m in mail_file:
        m = m.strip()
        if re.search('*@aun.edu.ng', m):

            print m

aun_mails()

Body:
I think you'll be able to accomplish what you want without the re module.
Take a look at the following example:

myString = "Blah blah email blah sent by: some.name@aun.edu.ng"
isEmail = myString.endswith('aun.edu.ng') # isEmail will be True in this case

if isEmail == True:
    print myString # or print(myString for python 3.x)


问:
Error print user.default swift 3
I have two screens the first of login and the second shows the user information. On the login screen I keep the user_id value in user.defaults and when I go to the second screen I use that value to call a web service and show its information, but I have an error and that the value saved in user.default is nil. and finally when user click cerrar_sesion I remove the user.defaults How can I solve it? This is my code:

```<code>func login(){
        let id_usuario = 7
        Constants.lbd.set(id_usuario, forKey: "id_usuario")
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.synchronize()
}
</code>```

Second view:

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        btn_cerrarSesion.addTarget(self, action: #selector(cerar_sesion), for: .touchUpInside)
        info_usuario()
}

    func info_usuario(){
            let auth = "ASASDWDASD!"
            let id_usuario = Constants.lbd.object(forKey: "id_usuario") as? Int
print(id_usuario)
            Services.objServices.ServObtUsuario(auth: auth!, id_usuario: id_usuario!).then{
                data -> Void in
                let res = JSON(data)
                let status = res["status"].boolValue
                if(status){
                    let info_usuario = res["data"]["usuarios"]
                    for(_, sub_res):(String, JSON) in info_usuario{
                        self.lbl_nombres_usuario.text = sub_res["nombres"].stringValue+" "+sub_res["apellidos"].stringValue
                        self.lbl_username.text = sub_res["username"].stringValue
                    }
                }else{
                    let error = res["error"]["error_data"].stringValue
                    print(error)
                }
                }.catch{
                    error -> Void in
            }
        }

func cerar_sesion(){
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.object(forKey: "id_usuario")
        Constants.lbd.removeObject(forKey: "id_empresa")
        Constants.lbd.removeObject(forKey: "rol")
        Constants.lbd.removeObject(forKey: "auth")
        Constants.lbd.synchronize()
    }
</code>```

finally I get this in console:
nil
fatal error: unexpectedly found nil while unwrapping an Optional value

Thanks in advance

答:
First of all there is a dedicated method to read an Int from UserDefaults (assuming Constants.lbd is a type alias for UserDefaults.standard)

```<code>let id_usuario = Constants.lbd.integer(forKey: "id_usuario")
</code>```

Second of all don't use UserDefaults to share data between view controllers. It's fine to save the value in UserDefaults but it's better to pass the value in the segue for example via the sender parameter

```<code>self.performSegue(withIdentifier: "second_view", sender: id_usuario)
</code>```

And please, this is Swift and not PHP or JavaScript. The variable and function names are supposed to be camelCased rather than snake_cased.

Title: Error print user.default swift 3

Body:
I have two screens the first of login and the second shows the user information. On the login screen I keep the user_id value in user.defaults and when I go to the second screen I use that value to call a web service and show its information, but I have an error and that the value saved in user.default is nil. and finally when user click cerrar_sesion I remove the user.defaults How can I solve it? This is my code:

func login(){
        let id_usuario = 7
        Constants.lbd.set(id_usuario, forKey: "id_usuario")
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.synchronize()
}

Second view:

override func viewDidLoad() {
        super.viewDidLoad()
        btn_cerrarSesion.addTarget(self, action: #selector(cerar_sesion), for: .touchUpInside)
        info_usuario()
}

    func info_usuario(){
            let auth = "ASASDWDASD!"
            let id_usuario = Constants.lbd.object(forKey: "id_usuario") as? Int
print(id_usuario)
            Services.objServices.ServObtUsuario(auth: auth!, id_usuario: id_usuario!).then{
                data -> Void in
                let res = JSON(data)
                let status = res["status"].boolValue
                if(status){
                    let info_usuario = res["data"]["usuarios"]
                    for(_, sub_res):(String, JSON) in info_usuario{
                        self.lbl_nombres_usuario.text = sub_res["nombres"].stringValue+" "+sub_res["apellidos"].stringValue
                        self.lbl_username.text = sub_res["username"].stringValue
                    }
                }else{
                    let error = res["error"]["error_data"].stringValue
                    print(error)
                }
                }.catch{
                    error -> Void in
            }
        }

func cerar_sesion(){
        self.performSegue(withIdentifier: "second_view", sender: self)
        Constants.lbd.object(forKey: "id_usuario")
        Constants.lbd.removeObject(forKey: "id_empresa")
        Constants.lbd.removeObject(forKey: "rol")
        Constants.lbd.removeObject(forKey: "auth")
        Constants.lbd.synchronize()
    }

finally I get this in console:
nil
fatal error: unexpectedly found nil while unwrapping an Optional value

Thanks in advance

Body:
First of all there is a dedicated method to read an Int from UserDefaults (assuming Constants.lbd is a type alias for UserDefaults.standard)

let id_usuario = Constants.lbd.integer(forKey: "id_usuario")

Second of all don't use UserDefaults to share data between view controllers. It's fine to save the value in UserDefaults but it's better to pass the value in the segue for example via the sender parameter

self.performSegue(withIdentifier: "second_view", sender: id_usuario)

And please, this is Swift and not PHP or JavaScript. The variable and function names are supposed to be camelCased rather than snake_cased.


问:
How to reference variable names in a for loop in R?
I'm trying to reference variable names in for loop in R. For example, if I want to change each of the following variables to from numeric to a string

```<code>xtable<- tbl_df(cbind(x1=c(1,2,3), x2=c(3,4,5)))

for (varname in names(xtable)) {
 xtable$varname<- as.character(xtable$varname)
}
</code>```

or rename each variable by adding an 'a' after each variable name

```<code>for (varname in names(xtable)) {
 dplyr::rename(xtable, varname = paste0(varname,'a', sep='') )
}
</code>```

In general, I'm having trouble referencing the indexing variable "varname" within the for loop as the variable name it represents rather than as the word "varname".

答:
Note that tbl_df is depricated in the dplyr library. But you can use data.frame or as.data.frame easily.

```<code>xtable <- data.frame(x1=c(1,2,3), x2=c(3,4,5))
str(xtable) # shows the structure of the data.frame
</code>```

R allows us to perform vector operations easily which take away the requirements for many loops.

```<code># lapply applies a function to every column in a data.frame
xtable <- as.data.frame(lapply(xtable,as.character))
str(xtable) # shows the structure of the data.frame

# we can directly input into the names() of an object
# paste0 has a default separator of ''
# If we put a vector into paste0 it will return a vector!
names(xtable) <- paste0(names(xtable),"a")
str(xtable)
</code>```

But if you really need to reference a variable name in a loop (for a different problem)

```<code>for(varname in names(xtable)) {
  print(xtable[varname]) # xtable[varname] outputs a table with one column including header
  print(xtable[[varname]]) # xtable[[varname]] outputs only the contects of the varname vector
}
</code>```

Body:
I'm trying to reference variable names in for loop in R. For example, if I want to change each of the following variables to from numeric to a string

xtable<- tbl_df(cbind(x1=c(1,2,3), x2=c(3,4,5)))

for (varname in names(xtable)) {
 xtable$varname<- as.character(xtable$varname)
}

or rename each variable by adding an 'a' after each variable name

for (varname in names(xtable)) {
 dplyr::rename(xtable, varname = paste0(varname,'a', sep='') )
}

In general, I'm having trouble referencing the indexing variable "varname" within the for loop as the variable name it represents rather than as the word "varname".

Body:
Note that tbl_df is depricated in the dplyr library. But you can use data.frame or as.data.frame easily.

xtable <- data.frame(x1=c(1,2,3), x2=c(3,4,5))
str(xtable) # shows the structure of the data.frame

R allows us to perform vector operations easily which take away the requirements for many loops.

# lapply applies a function to every column in a data.frame
xtable <- as.data.frame(lapply(xtable,as.character))
str(xtable) # shows the structure of the data.frame

# we can directly input into the names() of an object
# paste0 has a default separator of ''
# If we put a vector into paste0 it will return a vector!
names(xtable) <- paste0(names(xtable),"a")
str(xtable)

But if you really need to reference a variable name in a loop (for a different problem)

for(varname in names(xtable)) {
  print(xtable[varname]) # xtable[varname] outputs a table with one column including header
  print(xtable[[varname]]) # xtable[[varname]] outputs only the contects of the varname vector
}


问:
How to make a flex column put under another?
I need to have one column placed under the other when viewed on a cell phone.
I am using bootstrap 4 and the divs are flex, I use flex columns and flex rows, already using the property property order and it did not work.

My code

```<code><div id="menu-text" class="d-flex flex-row">

        <div class="d-flex flex-column col-sm justify-content-center">
          <div class="d-flex flex-row menu-subtitle">Sashomi  </div>
          <div class="d-flex flex-row menu-small-text">[CORTE DE MARISCOS O CARNE CRUDOS]</div>
          <div class="d-flex flex-row menu-mini-text">[FRESH BEEF OR NATURAL SEAFOOD]</div>
          <img src="images/BrochazoBlanco.png" class="white-brush">

          <div class="d-flex flex-row">

            <div class="d-flex flex-column col-md-3">
              <div class="d-flex flex-row">$ 72</div>
            </div>

            <div class="d-flex flex-column col-md-3">
              <div class="d-flex flex-row">$ 50</div>
            </div>

            <div class="d-flex flex-column col-md-6">
              <div class="d-flex flex-row">Sushi california</div>
            </div>
          </div>
        </div>

        <div class="d-flex flex-column col-sm justify-content-center">
          <div class="d-flex flex-row menu-subtitle">Sashimi</div>
          <div class="d-flex flex-row menu-small-text">[CORTE DE MARISCOS O CARNE CRUDOS]</div>
          <div class="d-flex flex-row menu-mini-text">[FRESH BEEF OR NATURAL SEAFOOD]</div>
          <img src="images/BrochazoBlanco.png" class="white-brush">

          <div class="d-flex flex-row">

            <div class="d-flex flex-column col-md-3">
              <div class="d-flex flex-row">$ 72</div>
            </div>

            <div class="d-flex flex-column col-md-3">
              <div class="d-flex flex-row">$ 50</div>
            </div>

            <div class="d-flex flex-column col-md-6">
              <div class="d-flex flex-row">Sushi california</div>
            </div>
          </div>
        </div>

    </div>
</code>```

答:
Check this example for a simplified, responsive version of the code that you provided.

<s>I don't know how many columns you need, as you didn't give any code, but here is a three column grid that is responsive.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

      One of three columns

      One of three columns

      One of three columns

```

You can see the same thing here, and resize the output to see how it works.</s>

Body:
I need to have one column placed under the other when viewed on a cell phone.
I am using bootstrap 4 and the divs are flex, I use flex columns and flex rows, already using the property property order and it did not work.

My code

Sashomi

[CORTE DE MARISCOS O CARNE CRUDOS]

[FRESH BEEF OR NATURAL SEAFOOD]

$ 72

$ 50

Sushi california

Sashimi

[CORTE DE MARISCOS O CARNE CRUDOS]

[FRESH BEEF OR NATURAL SEAFOOD]

$ 72

$ 50

Sushi california

Body:
Check this example for a simplified, responsive version of the code that you provided.

<s>I don't know how many columns you need, as you didn't give any code, but here is a three column grid that is responsive.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<div class="container-fluid">
  <div class="row">
    <div class="col-sm bg-secondary">
      One of three columns
    </div>
    <div class="col-sm bg-danger">
      One of three columns
    </div>
    <div class="col-sm bg-success">
      One of three columns
    </div>
  </div>
</div>

You can see the same thing here, and resize the output to see how it works.</s>


问:
Visual Basic for Microsoft Access Training
I am currently trying to learn how to create, run, and manage a Database for a company that deals with Chemicals.

My question is simple. Is there a website or a very good read that can help me understand and learn VBA or Visual Basic?

答:
The Access developers handbook (Litwin and Getz) is by far the best reference. BUT, are you sure you want to be developing your application in Access? Why not use SQL Server 2008 Express?

SQL Server 2008 Express How-To-Guide Series


问:
Change input text value in before submitting form
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

```<code><form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));
    if (!isNan(value) && !empty(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});
</script>
</code>```

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

```<code> old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";
</code>```

答:
```<code><form action="" id="form_id">
    <input type="text" name="change_value" id="change_value">
    <input type="text" name="d" id="d">
    <input type="submit" name="">

</form>

$("#form_id").on("submit", function (e) {
        e.preventDefault();//stop submit event
        var self = $(this);//this form
        $("#change_value").val("deneme");//change input
        $("#form_id").off("submit");//need form submit event off.
        self.submit();//submit form
    });
</code>```

Body:
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

<form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

 old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";


问:
BDD with Specflow in Visual Studio 2017 -featurefile Error CS1029
I am trying out BDD with Specflow in Visual Studio 2017. Previously I had created a new project and added Specflow and Nunit using NuGet Package Manager. From the Solution Explorer, I right click and select Add New Item. From the Add New Item window, I could see SpecFlow feature File and Feature.cs file

But I open the Feature.cs it's showing empty with the message

<#error Generation error: The element  may only appear once in this section.>

Then I try to build the solution then  I'm getting error on Output

Error CS1029

error: 'Generation error: The element  may only appear once in this section.'

The references I can see from Solution Explorer are: SpecRun.SpecFlowPlugin TechTalk.SpecFlow TechTalk.SpecRun NUnit.VisualStudio.TestAdapter

Am I missing something?

Thanks, Mohammed

答:
```<code>?xml version="1.0" encoding="utf-8"?>
configuration>
  <configSections>
    <section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
  </configSections>
  <specFlow>
    <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
  <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config --><!-- use unit test provider SpecRun+NUnit or SpecRun+MsTest for being able to execute the tests with SpecRun and another provider --><unitTestProvider name="SpecRun" /><plugins>
      <add name="SpecRun" />
    </plugins></specFlow>
</configuration>
</code>```


问:
git config file - fatal: bad config file line 12 in .git/config
I am getting error fatal: bad config file line 12 in .git/config when I run any git command to do with git config, except when I am in /c/Windows/System32. I have tried running git bash as admin and it doesn't make a difference.

When I look at my .gitconfig file in /c/Users// it looks like:

```<code>[core]
symlinks = false
autocrlf = true
[color]
diff = auto
status = auto
branch = auto
interactive = true
[pack]
packSizeLimit = 2g
[help]
format = html
[http]
sslCAinfo = /bin/<file>
[https]
proxy=<internal proxy>
[user]
name=<name>
email=<email>
[sendemail]
smtpserver = /bin/<file>
[diff "astextplain"]
textconv = astextplain
[rebase]
autosquash = true
</code>```

Of course with the <name>, <internal proxy>, <file> and <email> are replaced with the correct details. Also, the file has a file type of GITCONFIG File and is called .gitconfig.

My gitconfig file in /etc/ looks like:

```<code>[core]
symlinks = false
autocrlf = true
[color]
diff = auto
status = auto
branch = auto
interactive = true
[pack]
packSizeLimit = 2g
[http]
sslCAinfo = /bin/<file>
[https]
proxy=<internal proxy>
[user]
name=<name>
email=<email>
[sendemail]
smtpserver = /bin/<file>
[diff "astextplain"]
textconv = astextplain
[rebase]
autosquash = true
</code>```

Again, the <name>, <internal proxy>, <file> and <email> are replaced with the correct details. In this case, the file has a file type of File and is called gitconfig.

Can anyone please help resolve my issues so I can continue running git commands?

答: The answer to this questions is that I had not run git init inside the intended repository folder and therefore there was no repository.

Body:
I am getting error fatal: bad config file line 12 in .git/config when I run any git command to do with git config, except when I am in /c/Windows/System32. I have tried running git bash as admin and it doesn't make a difference.

When I look at my .gitconfig file in /c/Users// it looks like:

[core]
symlinks = false
autocrlf = true
[color]
diff = auto
status = auto
branch = auto
interactive = true
[pack]
packSizeLimit = 2g
[help]
format = html
[http]
sslCAinfo = /bin/<file>
[https]
proxy=<internal proxy>
[user]
name=<name>
email=<email>
[sendemail]
smtpserver = /bin/<file>
[diff "astextplain"]
textconv = astextplain
[rebase]
autosquash = true

Of course with the <name>, <internal proxy>, <file> and <email> are replaced with the correct details. Also, the file has a file type of GITCONFIG File and is called .gitconfig.

My gitconfig file in /etc/ looks like:

[core]
symlinks = false
autocrlf = true
[color]
diff = auto
status = auto
branch = auto
interactive = true
[pack]
packSizeLimit = 2g
[http]
sslCAinfo = /bin/<file>
[https]
proxy=<internal proxy>
[user]
name=<name>
email=<email>
[sendemail]
smtpserver = /bin/<file>
[diff "astextplain"]
textconv = astextplain
[rebase]
autosquash = true

Again, the <name>, <internal proxy>, <file> and <email> are replaced with the correct details. In this case, the file has a file type of File and is called gitconfig.

Can anyone please help resolve my issues so I can continue running git commands?


问:
How to center text in
 when there is also a button on the right of

The text in the span is not exactly in the middle due to the button on the right. Any help in centering it would be very much appreciated. I've tried adding divs and changing the display property to no avail.

https://jsfiddle.net/9nvukjxa/17/

HTML (uses Bootstrap):

```<code><div class="wrapper">
    <div class="myflash  alert alert-dismissable speechwarning">
        <div class="container">
            <span>This is not exactly centered</span>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
        </div>
    </div>
</div>
</code>```

CSS:

```<code>.container {
    text-align: center;
}
</code>```

答:
There is additional padding-right on .alert-dismissable. You can override this with !important.

You also need to take .close button out of the document flow using position: absolute.

.container {
  text-align: center;
  position: relative;
}

.alert-dismissable {
  padding-right: 15px !important;
}

.myflash.alert-dismissable .close {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="wrapper">
  <div class="myflash  alert alert-dismissable speechwarning">
    <div class="container">
      <span>This <strong>is</strong> exactly centered</span>
      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
  </div>
</div></code>```

Title: How to center text in <div> when there is also a button on the right of <div>

Body:
The text in the span is not exactly in the middle due to the button on the right. Any help in centering it would be very much appreciated. I've tried adding divs and changing the display property to no avail.

https://jsfiddle.net/9nvukjxa/17/

HTML (uses Bootstrap):

            This is not exactly centered
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

CSS:

.container {
    text-align: center;
}

Body:
There is additional padding-right on .alert-dismissable. You can override this with !important.

You also need to take .close button out of the document flow using position: absolute.

.container {
  text-align: center;
  position: relative;
}

.alert-dismissable {
  padding-right: 15px !important;
}

.myflash.alert-dismissable .close {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 1em;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="wrapper">
  <div class="myflash  alert alert-dismissable speechwarning">
    <div class="container">
      <span>This <strong>is</strong> exactly centered</span>
      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    </div>
  </div>
</div>


答: You'll have to add position:absolute to the style of the popup

Title: My popups are at bottom:0; but after you hover over them 2-3 times they keep going up?

Body:
My blog has these popups, and they are at bottom 0. But when you hover over them twice or more times they begin to go up farther each time you hover. Any way to prevent?

Edit: The reason it's doing this is because each time it hovers, the "bottom" resets so it's going -10px from where it last was. I don't know how to stop this.

Answer: I added info.css("bottom', '-10px'); and that fixed it. Thanks to all who answered, though.


问:
Underscore method prefix
I've been examining the code of CodeIgniter and CakePHP and I noticed that some of the methods in their classes are prefixed with an underscore _ or a double underscore __.

What's the purpose of that?

答:
I have a use case for this that is my own preference. I will often write traits that are intended to honor a specific interface, although since traits cannot directly implement an interface, I will designate which interface the trait satisfies in the doc block comment, and prefix protected and private methods that are not related to the interface with a single underscore. This lets you pretty easily follow which methods are provided to satisfy the contract (interface), and which are supporting methods. Eg:

```<code>interface Foo {
    public function bar(array $args = null, array $flags = null);
}
</code>```

The trait below's purpose is to satisfy the requirements of the Foo interface, but only one of it's methods are needed to do so. For clarity, the protected methods are prefixed. Even if they are made public by extension later, this still indicates that they are not contractually dependent by interface, and should not be assumed to be anything relevant.

```<code>/**
 * @satifies Foo
 */
trait FooTrait {

    public function bar(array $args = null, array $flags = null) {
        $this->_handleArgs($args);
        $this->_handleFlags($flags);
    }

    protected function _handleArgs(array $args = null) {
        if (is_null($args) {
            return;
        }
        //do something with the args
    }

    protected function _handleFlags(array $flags = null) {
        if (is_null($flags) {
            return;
        }
        //do something with the flags
    }
}
</code>```

You can then satisfy the interface by implementing it on a class and using the corresponding trait with no additional work.

```<code>final class ConcreteFoo implements Foo {
    use FooTrait;
}
</code>```

This keeps things very loosely coupled, and makes it possible to pretty easily integrate with other classes from other libraries or frameworks that do require a chain of inheritance without having to convolute your logic with a bunch of adapter classes.

My IDE (Netbeans) grumbles about this as a violation of PSR-1. As PSR-1 does not directly affect execution and it is arguable as to whether this is a more readable approach or not, I could really care less. I do try to follow all of the PSR's that directly affect execution though.

Title: Underscore method prefix

Body:
I have a use case for this that is my own preference. I will often write traits that are intended to honor a specific interface, although since traits cannot directly implement an interface, I will designate which interface the trait satisfies in the doc block comment, and prefix protected and private methods that are not related to the interface with a single underscore. This lets you pretty easily follow which methods are provided to satisfy the contract (interface), and which are supporting methods. Eg:

interface Foo {
    public function bar(array $args = null, array $flags = null);
}

The trait below's purpose is to satisfy the requirements of the Foo interface, but only one of it's methods are needed to do so. For clarity, the protected methods are prefixed. Even if they are made public by extension later, this still indicates that they are not contractually dependent by interface, and should not be assumed to be anything relevant.

/**
 * @satifies Foo
 */
trait FooTrait {

    public function bar(array $args = null, array $flags = null) {
        $this->_handleArgs($args);
        $this->_handleFlags($flags);
    }

    protected function _handleArgs(array $args = null) {
        if (is_null($args) {
            return;
        }
        //do something with the args
    }

    protected function _handleFlags(array $flags = null) {
        if (is_null($flags) {
            return;
        }
        //do something with the flags
    }
}

You can then satisfy the interface by implementing it on a class and using the corresponding trait with no additional work.

final class ConcreteFoo implements Foo {
    use FooTrait;
}

This keeps things very loosely coupled, and makes it possible to pretty easily integrate with other classes from other libraries or frameworks that do require a chain of inheritance without having to convolute your logic with a bunch of adapter classes.

My IDE (Netbeans) grumbles about this as a violation of PSR-1. As PSR-1 does not directly affect execution and it is arguable as to whether this is a more readable approach or not, I could really care less. I do try to follow all of the PSR's that directly affect execution though.


问:
The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'
I am trying to configure JSF+Spring+hibernate and I'm tying to run a test but when I use this "tx:annotation-driven" on my application-context.xml file, I get this error:

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

Here is my application-context.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-2.5.6.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-2.5.6.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-2.5.6.xsd
" xmlns:tool="http://www.springframework.org/schema/tool">
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@192.168.56.101:1521:Gpsi"/>
        <property name="username" value="omar"/>
        <property name="password" value="omar"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
       <property name="annotatedClasses">
            <list>
                <value>om.mycompany.model.Course</value>
                <value>om.mycompany.model.Student</value>
                <value>om.mycompany.model.Teacher</value>
            </list>
       </property>
       <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
            </props>
       </property>

    </bean>
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
       <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven transaction.manager="transactionManager"/>

    <context:annotation-config/>
    <context:component-scan base.package="com.mmycompany"/>
</beans>
</code>```

and here is my CourseServiceImplTest. I have still not implemented the tests:

```<code>public class CourseServiceImplTest {

    private static ClassPathXmlApplicationContext context;
    private static CourseService courseService;
    public CourseServiceImplTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
        context=new ClassPathXmlApplicationContext("application-context.xml");
        courseService=(CourseService) context.getBean("courseService");
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        context.close();
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of getAllCourses method, of class CourseServiceImpl.
     */
    @Test
    public void testGetAllCourses() {
        System.out.println("getAllCourses");
        CourseServiceImpl instance = new CourseServiceImpl();
        List expResult = null;
        List result = instance.getAllCourses();
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail("The test case is a prototype.");
    }

    /**
     * Test of getCourse method, of class CourseServiceImpl.
     */
    @Test
    public void testGetCourse() {
        System.out.println("getCourse");
        Integer id = null;
        CourseServiceImpl instance = new CourseServiceImpl();
        Course expResult = null;
        Course result = instance.getCourse(id);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail("The test case is a prototype.");
    }
</code>```

and here is the CourseServiceImpl:

```<code>@Service("courseService")
@Transactional
public class CourseServiceImpl implements CourseService{

    @Autowired
    private SessionFactory sessionFactory;
    @Override
    public List<Course> getAllCourses() {
        return sessionFactory.getCurrentSession().createQuery("from Course").list();
    }

    @Override
    public Course getCourse(Integer id) {
        return (Course) sessionFactory.getCurrentSession().get(Course.class, id);
    }

    @Override
    public void save(Course course) {
       sessionFactory.getCurrentSession().saveOrUpdate(course);
    }

}
</code>```

答:
I'm learning from udemy. I followed every step that my instructor show me to do.
In spring mvc crud section while setting up the devlopment environment i had the same error for:

```<code><mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" />
</code>```

then i just replaced

```<code>    http://www.springframework.org/schema/mvc/spring-mvc.xsd
</code>```

with

```<code>    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
</code>```

and

```<code>    http://www.springframework.org/schema/tx/spring-tx.xsd
</code>```

with

```<code>    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
</code>```

actually i visited these two sites
http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/
and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd  and  spring-tx-4.2.xsd

So, i suggest to try this.
Hope this helps.
Thank you.

Body:
I am trying to configure JSF+Spring+hibernate and I'm tying to run a test but when I use this "tx:annotation-driven" on my application-context.xml file, I get this error:

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

Here is my application-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-2.5.6.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-2.5.6.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-2.5.6.xsd
" xmlns:tool="http://www.springframework.org/schema/tool">
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@192.168.56.101:1521:Gpsi"/>
        <property name="username" value="omar"/>
        <property name="password" value="omar"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
       <property name="annotatedClasses">
            <list>
                <value>om.mycompany.model.Course</value>
                <value>om.mycompany.model.Student</value>
                <value>om.mycompany.model.Teacher</value>
            </list>
       </property>
       <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
            </props>
       </property>

    </bean>
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
       <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven transaction.manager="transactionManager"/>

    <context:annotation-config/>
    <context:component-scan base.package="com.mmycompany"/>
</beans>

and here is my CourseServiceImplTest. I have still not implemented the tests:

public class CourseServiceImplTest {

    private static ClassPathXmlApplicationContext context;
    private static CourseService courseService;
    public CourseServiceImplTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
        context=new ClassPathXmlApplicationContext("application-context.xml");
        courseService=(CourseService) context.getBean("courseService");
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        context.close();
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of getAllCourses method, of class CourseServiceImpl.
     */
    @Test
    public void testGetAllCourses() {
        System.out.println("getAllCourses");
        CourseServiceImpl instance = new CourseServiceImpl();
        List expResult = null;
        List result = instance.getAllCourses();
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail("The test case is a prototype.");
    }

    /**
     * Test of getCourse method, of class CourseServiceImpl.
     */
    @Test
    public void testGetCourse() {
        System.out.println("getCourse");
        Integer id = null;
        CourseServiceImpl instance = new CourseServiceImpl();
        Course expResult = null;
        Course result = instance.getCourse(id);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail("The test case is a prototype.");
    }

and here is the CourseServiceImpl:

@Service("courseService")
@Transactional
public class CourseServiceImpl implements CourseService{

    @Autowired
    private SessionFactory sessionFactory;
    @Override
    public List<Course> getAllCourses() {
        return sessionFactory.getCurrentSession().createQuery("from Course").list();
    }

    @Override
    public Course getCourse(Integer id) {
        return (Course) sessionFactory.getCurrentSession().get(Course.class, id);
    }

    @Override
    public void save(Course course) {
       sessionFactory.getCurrentSession().saveOrUpdate(course);
    }

}

Body:
I'm learning from udemy. I followed every step that my instructor show me to do.
In spring mvc crud section while setting up the devlopment environment i had the same error for:

<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" />

then i just replaced

    http://www.springframework.org/schema/mvc/spring-mvc.xsd

with

    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

and

    http://www.springframework.org/schema/tx/spring-tx.xsd

with

    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

actually i visited these two sites
http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/
and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd  and  spring-tx-4.2.xsd

So, i suggest to try this.
Hope this helps.
Thank you.


问:
Group Arrays based on their Elements
im currently working on a code to group Arrays based on their Elements and i hope u can help me out with your wisdom.

I have given following Arrays:

```<code>List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C", "F", "I"));
List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));
List<String> list3 = new ArrayList<String>(Arrays.asList("J", "K", "B", "L", "F"));
List<String> list4 = new ArrayList<String>(Arrays.asList("L", "K", "D", "C", "J"));
</code>```

Now i want to compare which of these lists have 3 Elements in common and save that ListNames in a new List/Array.

```<code>commonList1{List2, List3,}       - (B,C,F)
commonList4{List5}               - (K,J,L)
</code>```

Has anyone a smarter idea for doing that, instead of running through all Lists, compare each with another and search how many lists have the same intersection?

Best wishes
Tom

答:
```<code>listA.retainAll(listB);
</code>```

listA holds the elements which are also contained in listB.
To avoid changing listA, then you need to create a new list.

```<code>List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);
</code>```

The code above allows you to keep from changing listA or listB and common now contains only the elements which are contained in listA and listB.

Title: Group Arrays based on their Elements

Body:
im currently working on a code to group Arrays based on their Elements and i hope u can help me out with your wisdom.

I have given following Arrays:

List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C", "F", "I"));
List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));
List<String> list3 = new ArrayList<String>(Arrays.asList("J", "K", "B", "L", "F"));
List<String> list4 = new ArrayList<String>(Arrays.asList("L", "K", "D", "C", "J"));

Now i want to compare which of these lists have 3 Elements in common and save that ListNames in a new List/Array.

commonList1{List2, List3,}       - (B,C,F)
commonList4{List5}               - (K,J,L)

Has anyone a smarter idea for doing that, instead of running through all Lists, compare each with another and search how many lists have the same intersection?

Best wishes
Tom

Body:
listA.retainAll(listB);

listA holds the elements which are also contained in listB.
To avoid changing listA, then you need to create a new list.

List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);

The code above allows you to keep from changing listA or listB and common now contains only the elements which are contained in listA and listB.


问:
noUiSlider as a React component
I am trying to convert the noUiSlider plugin to a React JS component. I have ran into an issue. I can't seem to bind the slider values to the inputs that are being created. The slider shows and slides as intended. The inputs show in the HTML with the correct IDs as well, just no values being displayed. Here is my JSX:

```<code>class Slider extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        start: this.props.start,
        connect: this.props.connect,
        step: this.props.step,
        orientation: this.props.orientation, // 'horizontal' or 'vertical'
        range: this.props.range,
        format: this.props.format
    }
    this.handleSliderChange = this.handleSliderChange.bind(this);
}
componentDidMount() {
    let slider = this.props.id;
    noUiSlider.create(slider, {
        start: this.state.start,
        connect: this.state.connect,
        step: this.state.step,
        orientation: this.state.orientation,
        range: this.state.range,
        format: this.state.format
    });
    slider.noUiSlider.on('update', this.handleSliderChange);
}

onChangePage = (event, item) => {
    this.props.onChange(event);
}
render() {
    let inputs = [];
    for (let i = 0; i < 2; i++) {
        inputs.push(<div key={i}><input id={this.props.inputs[i].id}
    onChange={this.onChangePage} value={this.state.start[i]} type="text" />
    </div>);}
    let input2 = this.props.inputs.map((input, inputKey) => {
        return this.props.start.map((prop, propKey) => {
            return <div><input key={inputKey} id={input.id} onChange=
        {this.onChangePage} type="text" /></div>;
        });
    });
    return (
        <div>
            <div className="slider-value-container clearfix">
                {inputs}
            </div>
            <div id={this.props.id} className="slider"></div>
        </div>
    )
 }
</code>```

}

And here is where I am using the component on my page:

```<code><Slider
  id="sqftSlider"
  value={[this.state.lowerValue, this.state.higherValue]}
  inputs={sqftSlider}
  onChange={this.handleFilterChange}
  range={{ min:0, max: 5000 }}
  start={[0, 5000]}
  format={wNumb({
    decimals: 0,
    thousand: ','
  })}
  orientation="horizontal"
  connect={true}
  step={100}
 />
</code>```

This is the array that passes in the id for the inputs.

```<code>const sqftSlider = [{
   id: 'lowerSqftSlider'
},
{
   id: 'upperSqftSlider'
}];
</code>```

Any help appreciated!

答: The updated code above fixed my issue. Creating the handleSliderChange() and putting all of the slider handle values in there along with the for loop creating the inputs fixed it.

Title: noUiSlider as a React component

Body:
I am trying to convert the noUiSlider plugin to a React JS component. I have ran into an issue. I can't seem to bind the slider values to the inputs that are being created. The slider shows and slides as intended. The inputs show in the HTML with the correct IDs as well, just no values being displayed. Here is my JSX:

class Slider extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        start: this.props.start,
        connect: this.props.connect,
        step: this.props.step,
        orientation: this.props.orientation, // 'horizontal' or 'vertical'
        range: this.props.range,
        format: this.props.format
    }
    this.handleSliderChange = this.handleSliderChange.bind(this);
}
componentDidMount() {
    let slider = this.props.id;
    noUiSlider.create(slider, {
        start: this.state.start,
        connect: this.state.connect,
        step: this.state.step,
        orientation: this.state.orientation,
        range: this.state.range,
        format: this.state.format
    });
    slider.noUiSlider.on('update', this.handleSliderChange);
}

onChangePage = (event, item) => {
    this.props.onChange(event);
}
render() {
    let inputs = [];
    for (let i = 0; i < 2; i++) {
        inputs.push(
<input id={this.props.inputs[i].id}
    onChange={this.onChangePage} value={this.state.start[i]} type="text" />

);}
    let input2 = this.props.inputs.map((input, inputKey) => {
        return this.props.start.map((prop, propKey) => {
            return
<input key={inputKey} id={input.id} onChange=
        {this.onChangePage} type="text" />
;
        });
    });
    return (

                {inputs}

    )
 }

}

And here is where I am using the component on my page:

<Slider
  id="sqftSlider"
  value={[this.state.lowerValue, this.state.higherValue]}
  inputs={sqftSlider}
  onChange={this.handleFilterChange}
  range={{ min:0, max: 5000 }}
  start={[0, 5000]}
  format={wNumb({
    decimals: 0,
    thousand: ','
  })}
  orientation="horizontal"
  connect={true}
  step={100}
 />

This is the array that passes in the id for the inputs.

const sqftSlider = [{
   id: 'lowerSqftSlider'
},
{
   id: 'upperSqftSlider'
}];

Any help appreciated!


问:
Replace a text with \n character only at a particular line of the text with escape identifier
I have tried sed and perl commands to replace the text but I didn't get expected results.
For Example :
I want to replace

```<code>ABC"\
}
else {
....
</code>```

with:

```<code>ABC"\
} else {
....
</code>```

How can I do this?
Challenges faced are as follows:

As it contains escape identifier and \n I am unable to search the pattern also.

It is not the beginning or end of the file to truncate the particular line and replace.

Tried to change with respect to a line number in a file but my requirement is to do for multiple files hence, line number is not constant.

Though I can search for else. I'm unable to replace the \n

I have tried the inputs given in Removing new line after a particular text via bash/awk/sed/perl
but they do not serve my purpose.

Please give your inputs and help me if there is any other approach for this.

答:
Perhaps you can try</p>

```<code>sed '/}/N;/\nelse {/s/\n/ /'
</code>```

Body:
I have tried sed and perl commands to replace the text but I didn't get expected results.
For Example :
I want to replace

ABC"\
}
else {
....

with:

ABC"\
} else {
....

How can I do this?
Challenges faced are as follows:

As it contains escape identifier and \n I am unable to search the pattern also.

It is not the beginning or end of the file to truncate the particular line and replace.

Tried to change with respect to a line number in a file but my requirement is to do for multiple files hence, line number is not constant.

Though I can search for else. I'm unable to replace the \n

I have tried the inputs given in Removing new line after a particular text via bash/awk/sed/perl
but they do not serve my purpose.

Please give your inputs and help me if there is any other approach for this.

Body:
Perhaps you can try

sed '/}/N;/\nelse {/s/\n/ /'


问:
UITableView Checkmark Selecting One At A Time
I have a UITableView, and when a cell is pressed, a checkmark is displayed in the accessory view. However I want to only be able to have one checkmark displayed at any given time. How could I do that?</p>

答:
Depends on how you are comparing your data. This is how I use checkmarks for my tableView:

```<code>if([[plistDict objectForKey:@"Warranty"] boolValue] == YES) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
</code>```

You can also compare text:

```<code>if([cell.textLabel.text isEqualToString:@"Some Text"]) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
</code>```

Body:
Depends on how you are comparing your data. This is how I use checkmarks for my tableView:

if([[plistDict objectForKey:@"Warranty"] boolValue] == YES) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

You can also compare text:

if([cell.textLabel.text isEqualToString:@"Some Text"]) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}


问:
Exception in thread "main" java.util.InputMismatchException. Scanner-class
I've looked through some of the questions but I can't seem to find any good solutions.

I have a very simple code that just won't work. It's supposed to get the weight and height of the user, and then compute the BMI.

The values I put in is different everytime.
But lets say 85 for variable vikt and 1.80 for variable langd.
It does work when i use a , instead of a . though.
I get the following error.

```<code>Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at Labb2.BMI.main(BMI.java:32)
C:\Users\Danne\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)
</code>```

The code I use is the following;

```<code>package Labb2;

import java.util.Scanner;

public class BMI {

    public static void main(String[] args) {

        Scanner viktObj = new Scanner(System.in);
        Scanner langdObj = new Scanner(System.in);

        double vikt;
        double langd;
        double bmi;

        System.out.print("Ange din vikt: ");
        vikt = viktObj.nextDouble();

        System.out.print("Ange din längd i meter (ex. 1.70): ");
        langd = langdObj.nextDouble();

        bmi = vikt / (langd * langd);
        System.out.printf("Ditt BMI är: %.2f", bmi);
        System.out.println("");

    }

}
</code>```

答: It seems like you have entered something not a number. When you use nextDouble, that's mean you can only input numbers, not strings. I hope this helps. You can use try-catch in order to avoid errors.

Body:
I've looked through some of the questions but I can't seem to find any good solutions.

I have a very simple code that just won't work. It's supposed to get the weight and height of the user, and then compute the BMI.

The values I put in is different everytime.
But lets say 85 for variable vikt and 1.80 for variable langd.
It does work when i use a , instead of a . though.
I get the following error.

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at Labb2.BMI.main(BMI.java:32)
C:\Users\Danne\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

The code I use is the following;

package Labb2;

import java.util.Scanner;

public class BMI {

    public static void main(String[] args) {

        Scanner viktObj = new Scanner(System.in);
        Scanner langdObj = new Scanner(System.in);

        double vikt;
        double langd;
        double bmi;

        System.out.print("Ange din vikt: ");
        vikt = viktObj.nextDouble();

        System.out.print("Ange din längd i meter (ex. 1.70): ");
        langd = langdObj.nextDouble();

        bmi = vikt / (langd * langd);
        System.out.printf("Ditt BMI är: %.2f", bmi);
        System.out.println("");

    }

}


问:
What is the definition of a non-trainable parameter?
What is the definition of non-trainable parameter in a model?

For example, while you are building your own model, its value is 0 as a default, but when you want to use an inception model, it is becoming something else rather than 0. What would be the reason behind it?

答:
Non-trainable parameters are quite a broad subject. A straightforward example is to consider the case of any specific NN model and its architecture.

Say we have already setup your network definition in Keras, and your architecture is something like 256->500->500->1. Based on this definition, we seem to have a Regression Model (one output) with two hidden layers (500 nodes each) and an input of 256.

One non-trainable parameters of your model is, for example, the number of hidden layers itself (2). Other could be the nodes on each hidden layer (500 in this case), or even the nodes on each individual layer, giving you one parameter per layer plus the number of layers itself.

These parameters are "non-trainable" because you can't optimize its value with your training data. Training algorithms (like back-propagation) will optimize and update the weights of your network, which are the actual trainable parameters here (usually several thousands, depending on your connections). Your training data as it is can't help you determine those non-trainable parameters.

However, this does not mean that numberHiddenLayers is not trainable at all, it only means that in this model and its implementation we are unable to do so. We could make numberHiddenLayers trainable; the easiest way would be to define another ML algorithm that takes this model as input and trains it with several values of numberHiddenLayers. The best value is obtained with the model that outperformed the others, thus optimizing the numberHiddenLayers variable.

In other words, non-trainable parameters of a model are those that you will not be updating and optimized during training, and that have to be defined a priori, or passed as inputs.