问:
Can't drop a rectangle at the desired location with JavaFX
I am trying to implement a full press-drag-release gesture with JavaFX. I want to drag a rectangle from one VBox to another. On the MOUSE_DRAG_RELEASED event that happens on the target VBox, I'm trying to add the dragged rectangle as a child of the target VBox.

The problem is that when I release the mouse on the target VBox, the rectangle does not get into the expected position inside the VBox, but is always offset to the right by a fixed distance.

public class DragFromOneVBoxToAnother extends Application {
    private Disk sourceDisk = new Disk();
    private VBox targetVBox = new VBox();

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage stage) {
        // Build the UI
        GridPane root = getUI();

        // Add the event handlers
        this.addEventHandlers();

        Scene scene = new Scene(root, 800, 600);
        stage.setScene(scene);
        stage.show();
    }

    private GridPane getUI() {
        GridPane pane = new GridPane();
        VBox sourceVBox = new VBox();

        sourceDisk.setWidth(90);
        sourceDisk.setHeight(20);

        sourceVBox.setStyle(" -fx-border-color:red; -fx-border-width: 1; -fx-border-style: solid;");
        targetVBox.setStyle(" -fx-border-color:green; -fx-border-width: 1; -fx-border-style: solid;");

        sourceVBox.getChildren().add(sourceDisk);
        targetVBox.getChildren().add(new Rectangle(200, 20));

        pane.setHgap(200);
        pane.addColumn(0, sourceVBox);
        pane.addColumn(1, targetVBox);
        pane.setPadding(new Insets(200, 100, 200, 100));

        return pane;
    }

    private void addEventHandlers() {
        sourceDisk.setOnMouseEntered(event -> sourceDisk.setCursor(Cursor.HAND));

        sourceDisk.setOnMousePressed(event -> {
            sourceDisk.setOrgSceneX(event.getSceneX());
            sourceDisk.setOrgSceneY(event.getSceneY());
            sourceDisk.setOrgTranslateX(sourceDisk.getTranslateX());
            sourceDisk.setOrgTranslateY(sourceDisk.getTranslateY());

            sourceDisk.setMouseTransparent(true);
            sourceDisk.setCursor(Cursor.CLOSED_HAND);
        });

        sourceDisk.setOnDragDetected(event -> sourceDisk.startFullDrag());

        sourceDisk.setOnMouseDragged(event -> {
            double offsetX = event.getSceneX() - sourceDisk.getOrgSceneX();
            double offsetY = event.getSceneY() - sourceDisk.getOrgSceneY();
            double newTranslateX = sourceDisk.getOrgTranslateX() + offsetX;
            double newTranslateY = sourceDisk.getOrgTranslateY() + offsetY;

            sourceDisk.setTranslateX(newTranslateX);
            sourceDisk.setTranslateY(newTranslateY);
        });

        sourceDisk.setOnMouseReleased(event -> {
            sourceDisk.setMouseTransparent(false);
            sourceDisk.setCursor(Cursor.DEFAULT);
        });

        targetVBox.setOnMouseDragReleased(event ->
            targetVBox.getChildren().add(sourceDisk));
    }

    private class Disk extends Rectangle {
        private double orgSceneX;
        private double orgSceneY;
        private double orgTranslateX;
        private double orgTranslateY;

        // below, the getters and setters for all the instance variables
        // were removed for brevity
}
```

I have found that, even though the visual representation of the dragged rectangle seems to be offset when it's dropped, a child appears to actually be added to the target VBox (this can be seen because the border of the VBox expands after the MOUSE_DRAG_RELEASED event).
What could be the issue?

答:
During the mouse drag gesture you modify the translateX/translateY properties of the node. This results in the dragged node being offset from the position where the new parent places it by this transformation. You need to reset those values to properly add the node to the bottom of the VBox:

```<code>targetVBox.setOnMouseDragReleased(event -> {
    targetVBox.getChildren().add(sourceDisk);

    // reset translate values
    sourceDisk.setTranslateX(0);
    sourceDisk.setTranslateY(0);
});
</code>```

Body:
I am trying to implement a full press-drag-release gesture with JavaFX. I want to drag a rectangle from one VBox to another. On the MOUSE_DRAG_RELEASED event that happens on the target VBox, I'm trying to add the dragged rectangle as a child of the target VBox.

The problem is that when I release the mouse on the target VBox, the rectangle does not get into the expected position inside the VBox, but is always offset to the right by a fixed distance.

public class DragFromOneVBoxToAnother extends Application {
    private Disk sourceDisk = new Disk();
    private VBox targetVBox = new VBox();

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage stage) {
        // Build the UI
        GridPane root = getUI();

        // Add the event handlers
        this.addEventHandlers();

        Scene scene = new Scene(root, 800, 600);
        stage.setScene(scene);
        stage.show();
    }

    private GridPane getUI() {
        GridPane pane = new GridPane();
        VBox sourceVBox = new VBox();

        sourceDisk.setWidth(90);
        sourceDisk.setHeight(20);

        sourceVBox.setStyle(" -fx-border-color:red; -fx-border-width: 1; -fx-border-style: solid;");
        targetVBox.setStyle(" -fx-border-color:green; -fx-border-width: 1; -fx-border-style: solid;");

        sourceVBox.getChildren().add(sourceDisk);
        targetVBox.getChildren().add(new Rectangle(200, 20));

        pane.setHgap(200);
        pane.addColumn(0, sourceVBox);
        pane.addColumn(1, targetVBox);
        pane.setPadding(new Insets(200, 100, 200, 100));

        return pane;
    }

    private void addEventHandlers() {
        sourceDisk.setOnMouseEntered(event -> sourceDisk.setCursor(Cursor.HAND));

        sourceDisk.setOnMousePressed(event -> {
            sourceDisk.setOrgSceneX(event.getSceneX());
            sourceDisk.setOrgSceneY(event.getSceneY());
            sourceDisk.setOrgTranslateX(sourceDisk.getTranslateX());
            sourceDisk.setOrgTranslateY(sourceDisk.getTranslateY());

            sourceDisk.setMouseTransparent(true);
            sourceDisk.setCursor(Cursor.CLOSED_HAND);
        });

        sourceDisk.setOnDragDetected(event -> sourceDisk.startFullDrag());

        sourceDisk.setOnMouseDragged(event -> {
            double offsetX = event.getSceneX() - sourceDisk.getOrgSceneX();
            double offsetY = event.getSceneY() - sourceDisk.getOrgSceneY();
            double newTranslateX = sourceDisk.getOrgTranslateX() + offsetX;
            double newTranslateY = sourceDisk.getOrgTranslateY() + offsetY;

            sourceDisk.setTranslateX(newTranslateX);
            sourceDisk.setTranslateY(newTranslateY);
        });

        sourceDisk.setOnMouseReleased(event -> {
            sourceDisk.setMouseTransparent(false);
            sourceDisk.setCursor(Cursor.DEFAULT);
        });

        targetVBox.setOnMouseDragReleased(event ->
            targetVBox.getChildren().add(sourceDisk));
    }

    private class Disk extends Rectangle {
        private double orgSceneX;
        private double orgSceneY;
        private double orgTranslateX;
        private double orgTranslateY;

        // below, the getters and setters for all the instance variables
        // were removed for brevity
}

I have found that, even though the visual representation of the dragged rectangle seems to be offset when it's dropped, a child appears to actually be added to the target VBox (this can be seen because the border of the VBox expands after the MOUSE_DRAG_RELEASED event).
What could be the issue?

Body:
During the mouse drag gesture you modify the translateX/translateY properties of the node. This results in the dragged node being offset from the position where the new parent places it by this transformation. You need to reset those values to properly add the node to the bottom of the VBox:

targetVBox.setOnMouseDragReleased(event -> {
    targetVBox.getChildren().add(sourceDisk);

    // reset translate values
    sourceDisk.setTranslateX(0);
    sourceDisk.setTranslateY(0);
});


来源: stackexchange

问:
How to position two absolute positioned div's side by side in the mobile device,?
I wanna position two absolute div's side by side in the mobile device,
but there is a gap between the two divs.

I want to position them side by side if the size of the mobile device changes(flexible)

Thanks In Advance!

#header {
  position: relative;
}

#menu {
  background-color: green;
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
background-color:pink;
  position: absolute;
  overflow: auto;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 10;
  padding: 1.2rem;
  width: 70%;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div></code>```

答:
#header {
  position: relative;
}
*{
  box-sizing:border-box;
}

#menu {
  position: absolute;
  right: auto;
  width:50vw;
  height:100vh;
  background:red;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
  position: absolute;
  overflow: auto;
  top:0;
  left:50vw;
  z-index: 10;
  padding:1.2rem;
  width: 50vw;
    height:100vh;
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div id="menu">menu</div>
  <div id="tab">tab</div>
</div></code>```

adding box-sizing:border-box solve the problem!

ContentLicense: CC BY-SA 4.0

Body:
I wanna position two absolute div's side by side in the mobile device,
but there is a gap between the two divs.

I want to position them side by side if the size of the mobile device changes(flexible)

Thanks In Advance!

#header {
  position: relative;
}

#menu {
  background-color: green;
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
background-color:pink;
  position: absolute;
  overflow: auto;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 10;
  padding: 1.2rem;
  width: 70%;
  display: block;
}

menu

tab

Body:
#header {
  position: relative;
}
*{
  box-sizing:border-box;
}

#menu {
  position: absolute;
  right: auto;
  width:50vw;
  height:100vh;
  background:red;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
  position: absolute;
  overflow: auto;
  top:0;
  left:50vw;
  z-index: 10;
  padding:1.2rem;
  width: 50vw;
    height:100vh;
  background:yellow;
}

<div class="header">
  <div id="menu">menu</div>
  <div id="tab">tab</div>
</div>

adding box-sizing:border-box solve the problem!


问:
subtract two different sum of column from two different table in select query
I have two tables with the name of add_sell and add_expense.
I have inserted some of value into the tables. I wanted to get the total profit result. I did it myself but the result is showing 0 . Now how can I do that. I also give the total profit formula. Is anyone here to help me? Here is the code given below

```<code>function totalSell(){
    global $conn;
    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');
        if(mysqli_num_rows($result) > 0){

        while($fetch = mysqli_fetch_array($result)){
        echo "SR ".$fetch['Sumearning'];
       }
    }
}

function totalExpense(){
    global $conn;
    $ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
    $run_ex = $conn->query($ex);
    if (mysqli_num_rows($run_ex) > 0) {
        while ($tex = mysqli_fetch_array($run_ex)) {
        echo "SR ".$tex['Sumexpense'];
        }
    }
}
</code>```

function totalProfit(){

```<code>    global $conn;

    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');
        while($fetch = mysqli_fetch_array($result)){
            $fetch['Sumearning'];
            echo "Total Earning : ".$totalEarning = "SR ".$fetch['Sumearning'];
       }

$ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
        $run_ex = $conn->query($ex);

        while ($tex = mysqli_fetch_array($run_ex)) {
            $tex['Sumexpense'];
            echo "Total Expense : ".$totlaExpenss = "SR ".$tex['Sumexpense'];
        }
        echo "Your totla Profit is : ".$totalprofit = $totalEarning - $totlaExpenss;
}
</code>```

答:
Total profit result you can get from query itself.

```<code>$sql = "SELECT SUM(`sell_amount`)-(SELECT SUM(`expense_amount`) FROM `add_expense` WHERE expense_amount = `expense_amount`)  AS `PROFITLOSS` FROM `add_sell` WHERE sell_amount = `sell_amount`";
</code>```

Note: as Sumearning and as Sumexpense Removed instead you will get as PROFITLOSS

Body:
I have two tables with the name of add_sell and add_expense.
I have inserted some of value into the tables. I wanted to get the total profit result. I did it myself but the result is showing 0 . Now how can I do that. I also give the total profit formula. Is anyone here to help me? Here is the code given below

function totalSell(){
    global $conn;
    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');
        if(mysqli_num_rows($result) > 0){

        while($fetch = mysqli_fetch_array($result)){
        echo "SR ".$fetch['Sumearning'];
       }
    }
}

function totalExpense(){
    global $conn;
    $ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
    $run_ex = $conn->query($ex);
    if (mysqli_num_rows($run_ex) > 0) {
        while ($tex = mysqli_fetch_array($run_ex)) {
        echo "SR ".$tex['Sumexpense'];
        }
    }
}

function totalProfit(){

    global $conn;

    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');
        while($fetch = mysqli_fetch_array($result)){
            $fetch['Sumearning'];
            echo "Total Earning : ".$totalEarning = "SR ".$fetch['Sumearning'];
       }

$ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
        $run_ex = $conn->query($ex);

        while ($tex = mysqli_fetch_array($run_ex)) {
            $tex['Sumexpense'];
            echo "Total Expense : ".$totlaExpenss = "SR ".$tex['Sumexpense'];
        }
        echo "Your totla Profit is : ".$totalprofit = $totalEarning - $totlaExpenss;
}

Body:
Total profit result you can get from query itself.

$sql = "SELECT SUM(`sell_amount`)-(SELECT SUM(`expense_amount`) FROM `add_expense` WHERE expense_amount = `expense_amount`)  AS `PROFITLOSS` FROM `add_sell` WHERE sell_amount = `sell_amount`";

Note: as Sumearning and as Sumexpense Removed instead you will get as PROFITLOSS


问:
Mailto is not loading the subject(or body);
I have been reading a lot of topics and trying for some time now and i can't seem to get my mailto: to fill in my subject and body.

So it starts the mail-client (i have tried 3 different clients(outlook,windows standard,gmail) and every time it fills in the mail-address but never the subject and body.

```<code>totalmenu() {
var form = document.getElementById('emailform');
// form.action = "mailto:" + personeel.email + "?subject=result&body="
//+ mail();
form.action = "mailto:blabla@gmail.com?Subject=result;
}
</code>```

The comment shows the actual mailto i wanted to use.
I made a new  mailto with only a subject  to check if it was object related but this is not working as well.
any of u guys had similar problems or maybe see what i'm doing wrong here?

答:
I build my own little test code, and probably found what the problem is. This code seems to work:

```<code><html>
<body>
<form id="emailform" method="POST">
  <input type="text" value="this is a test">
  <input type="submit" value="send email">
</form>
<script>
(function() {
  var form = document.getElementById('emailform');
  form.action = "mailto:blabla@example.com?Subject=result";
})();
</script>
</body>
</html>
</code>```

But if I change the form method from "POST" to "GET" it doesn't work anymore.

Are you using "GET"?

I tested the code with Firefox and Chrome on Windows 10.

Body:
I have been reading a lot of topics and trying for some time now and i can't seem to get my mailto: to fill in my subject and body.

So it starts the mail-client (i have tried 3 different clients(outlook,windows standard,gmail) and every time it fills in the mail-address but never the subject and body.

totalmenu() {
var form = document.getElementById('emailform');
// form.action = "mailto:" + personeel.email + "?subject=result&body="
//+ mail();
form.action = "mailto:blabla@gmail.com?Subject=result;
}

The comment shows the actual mailto i wanted to use.
I made a new  mailto with only a subject  to check if it was object related but this is not working as well.
any of u guys had similar problems or maybe see what i'm doing wrong here?

Body:
I build my own little test code, and probably found what the problem is. This code seems to work:

<html>
<body>
<form id="emailform" method="POST">
  <input type="text" value="this is a test">
  <input type="submit" value="send email">
</form>
<script>
(function() {
  var form = document.getElementById('emailform');
  form.action = "mailto:blabla@example.com?Subject=result";
})();
</script>
</body>
</html>

But if I change the form method from "POST" to "GET" it doesn't work anymore.

Are you using "GET"?

I tested the code with Firefox and Chrome on Windows 10.


问:
VBA - How to convert and IEnumerable(Object) to String
I am creating a UI Path bot and using the Excel Read column activity to read contents of a column. I want to use this as text to use somewhere down the line but now the Excel read Column activity outputs an IEnmerable(Object) and I want to pass this to a variable that is a string. So far I am getting an error when I use the following:

```<code>myTextString = CType(myIEnumerableObject, String)
</code>```

or

```<code>myTextString = myIEnumerableObject.ToString  (this is simply stored as System.Object)
</code>```

or

```<code>myTextString = CStr(myIEnumerableObject)
</code>```

What I need is to be able to convert this object to a string, store it in a string variable and be able to re-use it later.

Thanks

答: You can read the data with a Read Range activity (specifying range to your desired column or not) , in that way you can store the data in a DataTable variable and access the column directly by name with mydatatable.Columns.Item("mycolumn"). It's easier and doesn't require additional coding.

Body:
I am creating a UI Path bot and using the Excel Read column activity to read contents of a column. I want to use this as text to use somewhere down the line but now the Excel read Column activity outputs an IEnmerable(Object) and I want to pass this to a variable that is a string. So far I am getting an error when I use the following:

myTextString = CType(myIEnumerableObject, String)

or

myTextString = myIEnumerableObject.ToString  (this is simply stored as System.Object)

or

myTextString = CStr(myIEnumerableObject)

What I need is to be able to convert this object to a string, store it in a string variable and be able to re-use it later.

Thanks


问:
How do I remove the selected tab indicator from the TabWidget?
Here's what I'd like to remove :

How do I replace the indicator showing which tab is currently shown as well as the blue line that spans the entire tabwidget?

To Specify: All I want indicating which tab is selected is this :

tab_button_active.9.png should be shown as background if the tab is SELECTED

tab_button_inactive.9.png should be shown as the background if the tab is NOT SELECTED.

edit : Setting tabStripEnabled to false has no effect. Adding a style to it and having "@android:style/Widget.Holo.ActionBar" as its parent is also not possible since im targetting API level 7 and the ActionBar was implemented in API level 11.

答:
You can simply use this method on your tablayout to hide the tab indicator.</p>

```<code>tabLayout.setSelectedTabIndicatorColor(Color.TRANSPARENT);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can simply use this method on your tablayout to hide the tab indicator.

tabLayout.setSelectedTabIndicatorColor(Color.TRANSPARENT);


问:
Mock Room database for Unit tests
I'm trying to make some Unit tests for my business logic.

Data is read and written to Room database, so the logic depends on what's inside my database.

I can easily buildInMemoryDatabase and test all the logic, but using Instrumental tests which are slow and require a device to be connected.

I want to run Unit tests only where I replace my RoomRepository with some other implementation of Repository interface

```<code>class RoomRepository(
    private val database: RoomDatabase //actual room database
): Repository {

    override fun getFooByType(type: Int): Maybe<List<Item>> {
        return database.fooDao()
            .getFooByType(type)
            .map { names ->
                names.map { name -> Item(name) }
            }
            .subscribeOn(Schedulers.io())
    }
}
</code>```

Maybe there is a way to run Room sqlite on host machine?

Maybe there is another solution?

答:
Please refer to this article.
https://developer.android.com/training/data-storage/room/testing-db

It's Unit test and not slowly like UI Test as you think.

The recommended approach for testing your database implementation is writing a JUnit test that runs on an Android device. Because these tests don't require creating an activity, they should be faster to execute than your UI tests.

Title: Mock Room database for Unit tests

Body:
I'm trying to make some Unit tests for my business logic.

Data is read and written to Room database, so the logic depends on what's inside my database.

I can easily buildInMemoryDatabase and test all the logic, but using Instrumental tests which are slow and require a device to be connected.

I want to run Unit tests only where I replace my RoomRepository with some other implementation of Repository interface

class RoomRepository(
    private val database: RoomDatabase //actual room database
): Repository {

    override fun getFooByType(type: Int): Maybe<List<Item>> {
        return database.fooDao()
            .getFooByType(type)
            .map { names ->
                names.map { name -> Item(name) }
            }
            .subscribeOn(Schedulers.io())
    }
}

Maybe there is a way to run Room sqlite on host machine?

Maybe there is another solution?


问:
Rownum between clause not working - Oracle
I have a table:

table1

```<code>user_id
1
2
3
4
</code>```

When I run this query:

```<code>SELECT
rownum, user_id
FROM
table1 where rownum between 1 and 4;
</code>```

But when I run, it does not work:

```<code>SELECT
rownum, user_id
FROM
table1 where rownum between 2 and 4;
</code>```

What am I doing wrong?

答:
rownum is incremented as the result set is generated.  If the value "1" is never generated, then "2" is never generated.

Because you want to return the row number, I would recommend using row_number():

```<code>select seqnum, user_id
from (select t1.*, row_number() over (order by ?) as seqnum
      from table1 t1
     ) t1
where seqnum between 2 and 4;
</code>```

The ? is for the column that specifies the order of the result set.

SQL tables represent unordered sets.  So your original query is functionally equivalent to:

```<code>select (1 + rownum), userid
from table1
where rownum <= 3;
</code>```

Because the ordering is not specified.  With a specified ordering, you can use row_number().

In Oracle 12C+, you can also express this as:

```<code>select rownum, userid
from table1
offset 1 row fetch first 3 rows only;
</code>```

Body:
I have a table:

table1

user_id
1
2
3
4

When I run this query:

SELECT
rownum, user_id
FROM
table1 where rownum between 1 and 4;

But when I run, it does not work:

SELECT
rownum, user_id
FROM
table1 where rownum between 2 and 4;

What am I doing wrong?

Body:
rownum is incremented as the result set is generated.  If the value "1" is never generated, then "2" is never generated.

Because you want to return the row number, I would recommend using row_number():

select seqnum, user_id
from (select t1.*, row_number() over (order by ?) as seqnum
      from table1 t1
     ) t1
where seqnum between 2 and 4;

The ? is for the column that specifies the order of the result set.

SQL tables represent unordered sets.  So your original query is functionally equivalent to:

select (1 + rownum), userid
from table1
where rownum <= 3;

Because the ordering is not specified.  With a specified ordering, you can use row_number().

In Oracle 12C+, you can also express this as:

select rownum, userid
from table1
offset 1 row fetch first 3 rows only;


问:
How to import a json file with _id (string) as _id (objectId) in mongodb?
I have an array which has multiple objects and objects have _id (string) already set. While I import the file, i want all _id (string) to get imported into _id (objectId).

I have tried manually using "$oid" but it is not a dynamic solution to my problem.

my import statement

```<code>mongoimport --db delivera --collection restaurants --drop --file list.json --jsonArray
</code>```

my example object

```<code>{
"_id":"5a6900fff467be65019a9001",
"date":"2018-01-24T21:56:15.353Z",
"title":"Italian pasta",
"restaurant": "coffee bean",
"__v":0
}
</code>```

答:
You can make a node.js script for doing import</p>

```<code>var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var url = "mongodb://localhost:27017/delivera"; //host and db
var file = require('./myfile.json');

MongoClient.connect(url, {useNewUrlParser: true }, function(err, db) {
    var dbo = db.db("delivera"); //db
    file.map(elem => {
        elem._id = ObjectID(elem._id)
        dbo.collection("restaurants").insertOne(elem, function(err, res) { //collection
            if (err) throw err;
        });
    })
    console.log("done")
    db.close();
});

</code>```

Body:
I have an array which has multiple objects and objects have _id (string) already set. While I import the file, i want all _id (string) to get imported into _id (objectId).

I have tried manually using "$oid" but it is not a dynamic solution to my problem.

my import statement

mongoimport --db delivera --collection restaurants --drop --file list.json --jsonArray

my example object

{
"_id":"5a6900fff467be65019a9001",
"date":"2018-01-24T21:56:15.353Z",
"title":"Italian pasta",
"restaurant": "coffee bean",
"__v":0
}

Body:
You can make a node.js script for doing import

var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var url = "mongodb://localhost:27017/delivera"; //host and db
var file = require('./myfile.json');

MongoClient.connect(url, {useNewUrlParser: true }, function(err, db) {
    var dbo = db.db("delivera"); //db
    file.map(elem => {
        elem._id = ObjectID(elem._id)
        dbo.collection("restaurants").insertOne(elem, function(err, res) { //collection
            if (err) throw err;
        });
    })
    console.log("done")
    db.close();
});


问:
R Shiny - Dynamically adding dependent inputs using insertUI
The app below contains an actionButton, Add, that inserts two inputs when clicked.

The first input is a selectInput with choices A and B. The second input is a textInput if the user selects A and a numericInput if they select B. I'm not sure how to capture this dependency.

I tried attaching an event handler (the second observeEvent in the code below) to each selectInput that listens to the value of that selectInput and renders the second input accordingly using renderUI. This doesn't work though. I am also wary about using a render function inside an observeEvent since I have read that using a render inside an observer is not good practice (not exactly sure why). It also looks messy.

The app:

```<code>library(shiny)

  ui <- fluidPage(
    actionButton('add', 'Add'),
    div(id = 'placeholder')
  )

  server <- function(input, output, session) {

    rv = reactiveValues(ctn = NULL)

    observeEvent(input$add, {

      rv$ctn = rv$ctn + 1

      Id = function(id, ctn = rv$ctn) paste0(id, ctn)

      insertUI(
        selector = '#placeholder',
        ui = div(
          id = Id('div'),
          selectInput(Id('letter'), 'Letter:', LETTERS[1:2]),
          uiOutput(Id('input'))
        )
      )

      observeEvent(Id('letter'), {
        output[[Id('input')]] <- renderUI({

          switch(
            input[[Id('letter')]],
            'A' = textInput(Id('text'), '', ''),
            'B' = numericInput(Id('numeric'), '', '')
          )
        })

      })
    })

  }

  shinyApp(ui = ui, server = server)
</code>```

The first UI chunk that is inserted works as expected - both inputs are rendered. However, in subsequent chunks (chunks 2 and 3 in the screenshot below) only the selectInput is rendered.

Here is a screenshot:

答:
Below is a working code. The main problem was your ctn reactive value initialized to NULL, because NULL + 1 = numeric(0) and numeric(0) + 1 = numeric(0).

```<code>library(shiny)

ui <- fluidPage(
  actionButton('add', 'Add'),
  div(id = 'placeholder')
)

server <- function(input, output, session) {

  ctn <- reactiveVal(0)
  Id <- reactive({
    function(id){
      paste0(id, ctn())
    }
  })

  observeEvent(input$add, {

    ctn(ctn() + 1)

    insertUI(
      selector = '#placeholder',
      ui = div(
        id = Id()('div'),
        selectInput(Id()('letter'), 'Letter:', LETTERS[1:2]),
        uiOutput(Id()('input'))
      )
    )

  })

  observeEvent(ctn(), {
    id <- Id()('input')
    selection <- Id()('letter')
    output[[id]] <- renderUI({
      req(input[[Id()('letter')]])
      switch(
        input[[selection]],
        'A' = textInput(Id()('text'), 'ENTER TEXT', ''),
        'B' = numericInput(Id()('numeric'), 'ENTER NUMBER', '')
      )
    })
  }, ignoreInit = TRUE)

}
</code>```

Body:
The app below contains an actionButton, Add, that inserts two inputs when clicked.

The first input is a selectInput with choices A and B. The second input is a textInput if the user selects A and a numericInput if they select B. I'm not sure how to capture this dependency.

I tried attaching an event handler (the second observeEvent in the code below) to each selectInput that listens to the value of that selectInput and renders the second input accordingly using renderUI. This doesn't work though. I am also wary about using a render function inside an observeEvent since I have read that using a render inside an observer is not good practice (not exactly sure why). It also looks messy.

The app:

library(shiny)

  ui <- fluidPage(
    actionButton('add', 'Add'),
    div(id = 'placeholder')
  )

  server <- function(input, output, session) {

    rv = reactiveValues(ctn = NULL)

    observeEvent(input$add, {

      rv$ctn = rv$ctn + 1

      Id = function(id, ctn = rv$ctn) paste0(id, ctn)

      insertUI(
        selector = '#placeholder',
        ui = div(
          id = Id('div'),
          selectInput(Id('letter'), 'Letter:', LETTERS[1:2]),
          uiOutput(Id('input'))
        )
      )

      observeEvent(Id('letter'), {
        output[[Id('input')]] <- renderUI({

          switch(
            input[[Id('letter')]],
            'A' = textInput(Id('text'), '', ''),
            'B' = numericInput(Id('numeric'), '', '')
          )
        })

      })
    })

  }

  shinyApp(ui = ui, server = server)

The first UI chunk that is inserted works as expected - both inputs are rendered. However, in subsequent chunks (chunks 2 and 3 in the screenshot below) only the selectInput is rendered.

Here is a screenshot:

Body:
Below is a working code. The main problem was your ctn reactive value initialized to NULL, because NULL + 1 = numeric(0) and numeric(0) + 1 = numeric(0).

library(shiny)

ui <- fluidPage(
  actionButton('add', 'Add'),
  div(id = 'placeholder')
)

server <- function(input, output, session) {

  ctn <- reactiveVal(0)
  Id <- reactive({
    function(id){
      paste0(id, ctn())
    }
  })

  observeEvent(input$add, {

    ctn(ctn() + 1)

    insertUI(
      selector = '#placeholder',
      ui = div(
        id = Id()('div'),
        selectInput(Id()('letter'), 'Letter:', LETTERS[1:2]),
        uiOutput(Id()('input'))
      )
    )

  })

  observeEvent(ctn(), {
    id <- Id()('input')
    selection <- Id()('letter')
    output[[id]] <- renderUI({
      req(input[[Id()('letter')]])
      switch(
        input[[selection]],
        'A' = textInput(Id()('text'), 'ENTER TEXT', ''),
        'B' = numericInput(Id()('numeric'), 'ENTER NUMBER', '')
      )
    })
  }, ignoreInit = TRUE)

}


问:
How can I make the D3 Collide force apply only on X
I would like to use the Collide force in D3 to prevent overlaps between nodes in a force layout, but my y-axis is time-based. I would like to only use the force on the nodes' x positions.

I have tried to combine the collide force with a forceY but if I increase the collide radius I can see that nodes get pushed off frame so the Y position is not preserved.

```<code>  var simulation = d3.forceSimulation(data.nodes)
    .force('links', d3.forceLink(data.links))
    .force('x', d3.forceX(width/2))
    .force('collision', d3.forceCollide().radius(5))
    .force('y', d3.forceY( function(d) {
      var date = moment(d.properties.date, "YYYY-MM-DD");
      var timepos = y_timescale(date)
      return timepos; }));
</code>```

My hunch is that I could modify the source for forceCollide() and remove y but I am  just using D3 with  and I'm not sure how to start making a custom version of the force.

Edit: I have added more context in response to the answer below:
- full code sample here
- screenshot here

答:
Not quite enough code in the question to guarantee this is what you need, but making some assumptions:

Often when using a force layout you would allow the forces to calculate the positions and then reposition the node to a given [x,y] co-ordinate on tick e.g.

```<code>function ticked() {
    nodeSelection.attr('cx', d => d.x).attr('cy', d => d.y);
}
</code>```

Since you don't want the forces to affect the y co-ordinate just remove it from here i.e.

```<code>nodeSelection.attr('cx', d => d.x);
</code>```

And set the y position on, say, enter:

```<code>nodeSelection = nodeSelection
    .enter()
    .append('circle')
    .attr('class', 'node')
    .attr('r', 2)
    .attr('cy', d => {
      // Set y position based on scale here
    })
    .merge(nodeSelection);
</code>```

Body:
I would like to use the Collide force in D3 to prevent overlaps between nodes in a force layout, but my y-axis is time-based. I would like to only use the force on the nodes' x positions.

I have tried to combine the collide force with a forceY but if I increase the collide radius I can see that nodes get pushed off frame so the Y position is not preserved.

  var simulation = d3.forceSimulation(data.nodes)
    .force('links', d3.forceLink(data.links))
    .force('x', d3.forceX(width/2))
    .force('collision', d3.forceCollide().radius(5))
    .force('y', d3.forceY( function(d) {
      var date = moment(d.properties.date, "YYYY-MM-DD");
      var timepos = y_timescale(date)
      return timepos; }));

My hunch is that I could modify the source for forceCollide() and remove y but I am  just using D3 with  and I'm not sure how to start making a custom version of the force.

Edit: I have added more context in response to the answer below:
- full code sample here
- screenshot here

Body:
Not quite enough code in the question to guarantee this is what you need, but making some assumptions:

Often when using a force layout you would allow the forces to calculate the positions and then reposition the node to a given [x,y] co-ordinate on tick e.g.

function ticked() {
    nodeSelection.attr('cx', d => d.x).attr('cy', d => d.y);
}

Since you don't want the forces to affect the y co-ordinate just remove it from here i.e.

nodeSelection.attr('cx', d => d.x);

And set the y position on, say, enter:

nodeSelection = nodeSelection
    .enter()
    .append('circle')
    .attr('class', 'node')
    .attr('r', 2)
    .attr('cy', d => {
      // Set y position based on scale here
    })
    .merge(nodeSelection);


问:
bottom selection view in iOS
I need to select a bottom horizontal list of items. and the data should be changed for each item for selection(like bottom navigation)

I tried with collection view but it's not working

答:
It sounds like what you are looking for is the UITabBarController.

The tab bar interface displays tabs at the bottom of the window for selecting between the different modes and for displaying the views for that mode. This class is generally used as-is, but may also be subclassed.

Each tab of a tab bar controller interface is associated with a custom view controller. When the user selects a specific tab, the tab bar controller displays the root view of the corresponding view controller, replacing any previous views.

Title: bottom selection view in iOS


问:
update Xcode to 10.2.1 run project crash with problem dyld: Library not loaded: @rpath/libswiftCore.dylib
I have a project that was created with Xcode 10, Objective-C, and Swift 4.0 and now upgraded to Xcode 10.2.1.

Error reporting for each run.

I have set Always Embed Swift Standard Libraries to YES

Add @executable_path/Frameworks to "Runpath Search Paths"

These methods don't resolve the issue.

```
dyld: Library not loaded: @rpath/libswiftCore.dylib
  Referenced from: /private/var/containers/Bundle/Application/48371FB5-6A90-4D14-9D65-C7AB5DCAC1A1/one mini.app/Frameworks/Framework152x.framework/Framework152x
  Reason: image not found
```

答: Actually, the problem is the Framework152x.framework is developed in Swift with Xcode version below 10.2. If your project is built with Xcode 10 with Framework152x.framework means Framework152x.framework runtime is swift 4.2. But if you build your project in Xcode 10.2.1 this issue will occur. Because the XCode 10.2.1 has swift 5 Runtime but Framework152x.framework is expecting swift 4.2. You can resolve this problem only by using Framework152x.framework which needs to be built either in Xcode 10.2 or 10.2.1

Body:
I have a project that was created with Xcode 10, Objective-C, and Swift 4.0 and now upgraded to Xcode 10.2.1.

Error reporting for each run.

I have set Always Embed Swift Standard Libraries to YES

Add @executable_path/Frameworks to "Runpath Search Paths"

These methods don't resolve the issue.

dyld: Library not loaded: @rpath/libswiftCore.dylib
  Referenced from: /private/var/containers/Bundle/Application/48371FB5-6A90-4D14-9D65-C7AB5DCAC1A1/one mini.app/Frameworks/Framework152x.framework/Framework152x
  Reason: image not found


问:
Airflow Emr Dag suceeds but cluster not started
I am trying to start an AWS emr cluster and submit a step using  EmrCreateJobFlowOperator and EmrAddStepsOperator, my both steps succed but the cluster is never launch, not even without step

Both of the steps change to succeed status

Here is my code

```<code>default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'retry_delay': timedelta(minutes=2),
    'start_date': datetime(2019, 1, 1),
    'end_date': datetime(2019, 2, 1),

    'depends_on_past': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5)
}

step_args = ["spark-submit", '../test.py']

step = [{"Name": "what_you_do-" + time.strftime("%Y%m%d-%H:%M"),
            'ActionOnFailure': 'CONTINUE',
            'HadoopJarStep': {
                'Jar': 's3n://elasticmapreduce/libs/script-runner/script-runner.jar',
                'Args': step_args
            }
        }]

JOB_FLOW_OVERRIDES = {
'Instances': {
    'InstanceGroups': [
        {

            'InstanceRole': 'MASTER',
            'InstanceType': 'm4.large',
            'InstanceCount': 1
        },
        {

            'InstanceRole': 'CORE',
            'InstanceType': 'm4.large',
            'InstanceCount': 2,

        }
    ]},
    'Name':'airflow-monthly_agg_custom',

            'BootstrapActions':[{
            'Name': 'Install',
            'ScriptBootstrapAction': {
                'Path': 's3://dep-buck/bootstrap.sh'
            }
        }],
    'Configurations': [
  {
     "Classification": "spark-env",
     "Configurations": [
       {
         "Classification": "export",
         "Properties": {
            "PYSPARK_PYTHON": "/usr/bin/python3"
          }
       }
    ]
  }
]}

dag = DAG('emr_job_flow_automatic_steps_7',
          default_args=default_args,
          schedule_interval="@daily",
          max_active_runs=1,

          #    schedule_interval='*/1 * * * *',

          catchup=True,

          #         dagrun_timeout=timedelta(seconds=10)
          )

cluster_creator = EmrCreateJobFlowOperator(
    task_id='create_job_flow2',
    job_flow_overrides=JOB_FLOW_OVERRIDES,
    aws_conn_id='aws_default',
    emr_conn_id='emr_default',
    dag=dag
)

step_adder = EmrAddStepsOperator(
    task_id='add_steps',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    aws_conn_id='aws_default',
    steps=step,
    dag=dag
)

cluster_creator.set_downstream(step_adder)
</code>```

I have tried to search for example or good ocument but there isnt much except function definition on airflow site

for create job flow i have this log repeated several time

for "add step" i have this in log

答:
The Problem was mainly about the visibilty to users and region, it was starting cluster in the default region so i had to change the properties below

Airflow UI > admin > connection > aws_default > extra

```<code>{"region_name": "the region i was watching the ec2 console"}
</code>```

Airflow UI > admin > connection > emr_default > extra

```<code>"VisibleToAllUsers": true,
</code>```

Body:
I am trying to start an AWS emr cluster and submit a step using  EmrCreateJobFlowOperator and EmrAddStepsOperator, my both steps succed but the cluster is never launch, not even without step

Both of the steps change to succeed status

Here is my code

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'retry_delay': timedelta(minutes=2),
    'start_date': datetime(2019, 1, 1),
    'end_date': datetime(2019, 2, 1),

    'depends_on_past': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5)
}

step_args = ["spark-submit", '../test.py']

step = [{"Name": "what_you_do-" + time.strftime("%Y%m%d-%H:%M"),
            'ActionOnFailure': 'CONTINUE',
            'HadoopJarStep': {
                'Jar': 's3n://elasticmapreduce/libs/script-runner/script-runner.jar',
                'Args': step_args
            }
        }]

JOB_FLOW_OVERRIDES = {
'Instances': {
    'InstanceGroups': [
        {

            'InstanceRole': 'MASTER',
            'InstanceType': 'm4.large',
            'InstanceCount': 1
        },
        {

            'InstanceRole': 'CORE',
            'InstanceType': 'm4.large',
            'InstanceCount': 2,

        }
    ]},
    'Name':'airflow-monthly_agg_custom',

            'BootstrapActions':[{
            'Name': 'Install',
            'ScriptBootstrapAction': {
                'Path': 's3://dep-buck/bootstrap.sh'
            }
        }],
    'Configurations': [
  {
     "Classification": "spark-env",
     "Configurations": [
       {
         "Classification": "export",
         "Properties": {
            "PYSPARK_PYTHON": "/usr/bin/python3"
          }
       }
    ]
  }
]}

dag = DAG('emr_job_flow_automatic_steps_7',
          default_args=default_args,
          schedule_interval="@daily",
          max_active_runs=1,

          #    schedule_interval='*/1 * * * *',

          catchup=True,

          #         dagrun_timeout=timedelta(seconds=10)
          )

cluster_creator = EmrCreateJobFlowOperator(
    task_id='create_job_flow2',
    job_flow_overrides=JOB_FLOW_OVERRIDES,
    aws_conn_id='aws_default',
    emr_conn_id='emr_default',
    dag=dag
)

step_adder = EmrAddStepsOperator(
    task_id='add_steps',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    aws_conn_id='aws_default',
    steps=step,
    dag=dag
)

cluster_creator.set_downstream(step_adder)

I have tried to search for example or good ocument but there isnt much except function definition on airflow site

for create job flow i have this log repeated several time

for "add step" i have this in log

Body:
The Problem was mainly about the visibilty to users and region, it was starting cluster in the default region so i had to change the properties below

Airflow UI > admin > connection > aws_default > extra

{"region_name": "the region i was watching the ec2 console"}

Airflow UI > admin > connection > emr_default > extra

"VisibleToAllUsers": true,


问:
Junit testing a void response method
I have a void method namely invokeEllaAsync that I would like to test in the Spring eco-system and provided below. The method also calls another void method from inside as a nested call.

The mocking information is provided below,

```<code>   @InjectMocks
    private EllaService ellaService;

    private IrisBo validIrisBo;

    @Mock
    private EllaRequestDto ellaRequestDtoMock;

    @Mock
    private EntityServiceConnectable<EllaResponseDto> connectorMock;

    @Mock
    private EllaResponseDto ellaResponseMock;

    @Async
    public void invokeEllaAsync( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {

        try {
            callEllaService( irisBo );
        }

        /**
         * Asynchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
         *
         * @param irisEo
         * @return List<ResultBo>
         * @throws EllaGatewayUnsuccessfulResponseException
         */

        catch( EllaGatewayUnsuccessfulResponseException ex ) {
            throw new EllaGatewayUnsuccessfulResponseException( ex.getMessage(), ex.getCause() );
        }
    }

    private void callEllaService( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {

        HttpHeaders elladHeaders = createRequestHeaders( irisBo );

        ServiceResponse<EllaResponseDto> response = connector.call( EllaDtoConverter.convertToRequest( irisBo ), elladHeaders );

        if( !response.isSuccess() ) {
            throw new EllaGatewayUnsuccessfulResponseException( response.getErrorMessage(), response.getException().getCause() );
        }

    }
</code>```

I try to test the invokeEllaAsync method as follows,

```<code>    @Test
    public void testInvokeEllaShowsSuccess() {

        ServiceResponse<EllaResponseDto> validServiceResponseMock = mock( ServiceResponse.class );

        when( connectorMock.call( any(), (HttpHeaders) any() ) ).thenReturn( validServiceResponseMock );
        when( validServiceResponseMock.isSuccess() ).thenReturn( true );

        ellaService.invokeEllaAsync( validIrisBo );
        verify( ellaService, times( 1 ) ).invokeEllaAsync( validIrisBo );
    }
</code>```

I get the error provided below,

```<code>org.mockito.exceptions.misusing.NotAMockException:
Argument passed to verify() is of type EllaService and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
    verify(mock).someMethod();
    verify(mock, times(10)).someMethod();
    verify(mock, atLeastOnce()).someMethod();
</code>```

If I understand it correctly, the ellaService is the type of @InjectMocks and not the @Mock. Hence, the test is not executed.

How do I write the test correctly?

答:
The problem is you can verify only mocked components (Annotated with @ Mock).
EllaService is not a moc, but instance of real class from your code. @ InjectMock annotation just set private fields of EllaService with mocks.

Generally when test void method you need to ensure that some mocked components were called with expected parameters, so you need to verify not ellaService call, but call to mocked components that is used in invokeEllaAsync method.

Title: Junit testing a void response method

Body:
I have a void method namely invokeEllaAsync that I would like to test in the Spring eco-system and provided below. The method also calls another void method from inside as a nested call.

The mocking information is provided below,

   @InjectMocks
    private EllaService ellaService;

    private IrisBo validIrisBo;

    @Mock
    private EllaRequestDto ellaRequestDtoMock;

    @Mock
    private EntityServiceConnectable<EllaResponseDto> connectorMock;

    @Mock
    private EllaResponseDto ellaResponseMock;

    @Async
    public void invokeEllaAsync( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {

        try {
            callEllaService( irisBo );
        }

        /**
         * Asynchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
         *
         * @param irisEo
         * @return List<ResultBo>
         * @throws EllaGatewayUnsuccessfulResponseException
         */

        catch( EllaGatewayUnsuccessfulResponseException ex ) {
            throw new EllaGatewayUnsuccessfulResponseException( ex.getMessage(), ex.getCause() );
        }
    }

    private void callEllaService( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {

        HttpHeaders elladHeaders = createRequestHeaders( irisBo );

        ServiceResponse<EllaResponseDto> response = connector.call( EllaDtoConverter.convertToRequest( irisBo ), elladHeaders );

        if( !response.isSuccess() ) {
            throw new EllaGatewayUnsuccessfulResponseException( response.getErrorMessage(), response.getException().getCause() );
        }

    }

I try to test the invokeEllaAsync method as follows,

    @Test
    public void testInvokeEllaShowsSuccess() {

        ServiceResponse<EllaResponseDto> validServiceResponseMock = mock( ServiceResponse.class );

        when( connectorMock.call( any(), (HttpHeaders) any() ) ).thenReturn( validServiceResponseMock );
        when( validServiceResponseMock.isSuccess() ).thenReturn( true );

        ellaService.invokeEllaAsync( validIrisBo );
        verify( ellaService, times( 1 ) ).invokeEllaAsync( validIrisBo );
    }

I get the error provided below,

org.mockito.exceptions.misusing.NotAMockException:
Argument passed to verify() is of type EllaService and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
    verify(mock).someMethod();
    verify(mock, times(10)).someMethod();
    verify(mock, atLeastOnce()).someMethod();

If I understand it correctly, the ellaService is the type of @InjectMocks and not the @Mock. Hence, the test is not executed.

How do I write the test correctly?


问:
Python - The ElementTree XML API (not parsing as expected)
XML response is not easily parsing into an Element Tree object.

I have tried parsing as a string and finding and replacing values, it gets very messy, parsing XML must be easier than this?

```<code>    import requests
    from lxml import etree

    response = requests.get(url="http://www.yournavigation.org/api/1.0/gosmore.php?format=kml&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik")

    root = etree.fromstring(response.content)

    for child in root:
        print (child.tag, child.attrib)

    print(etree.tostring(root, pretty_print=True))
</code>```

I expect the Element Tree object to print in a prettify format and my Root to have many children. The Tree object does not print in this manner and the Root looks to have no children.

Am I able to collate here best practice information on parsing XML using this method, thank you.

Body:
XML response is not easily parsing into an Element Tree object.

I have tried parsing as a string and finding and replacing values, it gets very messy, parsing XML must be easier than this?

    import requests
    from lxml import etree

    response = requests.get(url="http://www.yournavigation.org/api/1.0/gosmore.php?format=kml&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik")

    root = etree.fromstring(response.content)

    for child in root:
        print (child.tag, child.attrib)

    print(etree.tostring(root, pretty_print=True))

I expect the Element Tree object to print in a prettify format and my Root to have many children. The Tree object does not print in this manner and the Root looks to have no children.

Am I able to collate here best practice information on parsing XML using this method, thank you.

Body:
Try this code:

import xml.etree.ElementTree as ET
import requests
import re

r = requests.get(
    'http://www.yournavigation.org/api/1.0/gosmore.php?forat=kml&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik')
if r.status_code == 200:
    # remove namespace
    xmlstring = re.sub(' xmlns="[^"]+"', '', r.content, count=1)
    root = ET.fromstring(xmlstring)
    ET.dump(root)

output

<kml>
  <Document>
    <name>KML Samples</name>
    <open>1</open>
    <distance>21.452372</distance>
    <traveltime>1228</traveltime>
    <description>To enable simple instructions add: 'instructions=1' as parameter to the URL</description>
    <Folder>
      <name>Paths</name>
      <visibility>0</visibility>
      <description>Examples of paths.</description>
      <Placemark>
        <name>Tessellated</name>
        <visibility>0</visibility>
        <description>If the &lt;tessellate&gt; tag has a value of 1, the line will contour to the underlying terrain</description>
        <LineString>
          <tessellate>1</tessellate>
          <coordinates> 5.963585,52.215950
5.963585,52.215950
5.963563,52.215986
5.963552,52.216012
5.964570,52.216254
5.964680,52.216333
5.964812,52.216371
5.966120,52.216622
5.967970,52.217000
5.968272,52.217056
5.969040,52.216970
5.969243,52.216943
5.969853,52.216862
5.969980,52.216840
5.970410,52.216760
5.970430,52.216757
5.970608,52.216718
5.970875,52.216652
5.971517,52.216534
5.972517,52.216352
5.972689,52.216347
5.972828,52.216322
5.973490,52.216180
5.974320,52.216020
5.974858,52.215917
5.975508,52.215795
5.975618,52.215774
5.975806,52.215736
5.975964,52.215707
5.976454,52.215615
5.976790,52.215550
5.977030,52.215500
5.978012,52.215322
5.978128,52.215301
5.978297,52.215269
5.978550,52.215223
5.979900,52.214980
5.979972,52.214967
5.980610,52.214850
5.981604,52.214682
5.982088,52.214593
5.982319,52.214555
5.983603,52.214328
5.983800,52.214290
5.984046,52.214244
5.984611,52.214147
5.984766,52.214123
5.984979,52.214089
5.985825,52.213893
5.985988,52.213862
5.986167,52.213827
5.986373,52.213785
5.987057,52.213667
5.987258,52.213647
5.988991,52.213331
5.991815,52.212817
5.993959,52.212422
5.996034,52.212043
5.996967,52.211876
5.997648,52.211743
5.998927,52.211492
5.999520,52.211376
5.999731,52.211334
5.999916,52.211301
6.000084,52.211273
6.000583,52.211188
6.003432,52.210674
6.004653,52.210453
6.004780,52.210428
6.004768,52.210359
6.004796,52.210315
6.004844,52.210283
6.004888,52.210267
6.004979,52.210256
6.005070,52.210271
6.005135,52.210305
6.005173,52.210356
6.005279,52.210337
6.008708,52.209720
6.011155,52.209269
6.012734,52.208984
6.012875,52.208959
6.012863,52.208920
6.012867,52.208894
6.012891,52.208857
6.012923,52.208833
6.012978,52.208812
6.013050,52.208803
6.013133,52.208814
6.013185,52.208838
6.013344,52.208817
6.013912,52.208709
6.014164,52.208648
6.014589,52.208512
6.014934,52.208433
6.015404,52.208346
6.018004,52.207885
6.019191,52.207672
6.019602,52.207601
6.020681,52.207393
...
          </coordinates>
        </LineString>
      </Placemark>
    </Folder>
  </Document>
</kml>


问:
Get the title of another page in PmWiki
I have a valid page name that I need to resolve to a page title. Example:

Main.TargetPage

(:title Page One:)
I am the page of which the title needs to be got.
```

<h2>Main.CurrentPage</h2>

<pre class="lang-none prettyprint-override"><code>(:title Example Page:)
I am the page that the PHP script is being run from.
</code>```

How can I get the title of Main.TargetPage from Main.CurrentPage?

答: You can get the other's page title by command <strong>{Main.TargetPage$Title}</strong>, see official docs: </p>

Title: Get the title of another page in PmWiki

Body:
I have a valid page name that I need to resolve to a page title. Example:

Main.TargetPage

(:title Page One:)
I am the page of which the title needs to be got.

Main.CurrentPage

(:title Example Page:)
I am the page that the PHP script is being run from.

How can I get the title of Main.TargetPage from Main.CurrentPage?

Body: You can get the other's page title by command {Main.TargetPage$Title}, see official docs:


问:
Implement a text highlighting feature in javascript
I have a task to create API using ExpressJS that will manage highlights which will be made on the frontend. How can I keep track of my highlighted text if someone updates a part of the text?

I was keeping the three starting and ending characters of the highlighted text. But a problem is, how will I manage those characters if the text is edited.

```<code>const { textH, allText } = req.body;
let chars = { };
const enclosingChars = (hLighted, theString) => {
  let startingChars = null, endingChars = null;
  const index = theString.indexOf(hLighted);
  const last3 = index + hLighted.length;
  if ((index - 3) > -1) startingChars = theString.substring(index - 3, index);
  if ((index + 3) <= theString.length) endingChars = theString.substring(last3, last3 + 3);
  return { startingChars, endingChars };
};
if (allText.includes(textH)) {
  chars = enclosingChars(textH, allText);
}
chars.hLighted = textH;
</code>```

If a part of the highlighted text is edited, I will delete the highlighted in my storage. If not, I want to check if my starting and ending characters have changed, then I change them accordingly.
But I don't know how to get that highlighted text if its index changed

答:
so it will be not as easy as you think if you consider keeping track of edits outside of the highlighted text.

the text might contain more than one similar phrase/word (to the highlighted)

the newly inserted phrase might be similar to the highlighted one (worse if before the main one in terms of indices)

so if any of the above scenarios happens the indices will be of no use because you can fall to the wrong text

Do the following

a. when highlighting keep the following
       1. the content : to make sure if the edit happens in there, you know it and you can act accordingly

```<code>   2. keep track of the index range of your text even in case the shift is required (when the text before it is edited)

   3. take a screenshot of the entire article and store it so that when an edit to the article happens you know exactly which part is edited. this will require to check word by word and see if any word in the new text is different from the word of the same index in the old (screenshot). and you can shift the ranges of the highlighted text accordingly.
</code>```

Remember any edit that happens after the highlighted text is innocuous.
Hope this helps.

Body:
I have a task to create API using ExpressJS that will manage highlights which will be made on the frontend. How can I keep track of my highlighted text if someone updates a part of the text?

I was keeping the three starting and ending characters of the highlighted text. But a problem is, how will I manage those characters if the text is edited.

const { textH, allText } = req.body;
let chars = { };
const enclosingChars = (hLighted, theString) => {
  let startingChars = null, endingChars = null;
  const index = theString.indexOf(hLighted);
  const last3 = index + hLighted.length;
  if ((index - 3) > -1) startingChars = theString.substring(index - 3, index);
  if ((index + 3) <= theString.length) endingChars = theString.substring(last3, last3 + 3);
  return { startingChars, endingChars };
};
if (allText.includes(textH)) {
  chars = enclosingChars(textH, allText);
}
chars.hLighted = textH;

If a part of the highlighted text is edited, I will delete the highlighted in my storage. If not, I want to check if my starting and ending characters have changed, then I change them accordingly.
But I don't know how to get that highlighted text if its index changed

Body:
so it will be not as easy as you think if you consider keeping track of edits outside of the highlighted text.

the text might contain more than one similar phrase/word (to the highlighted)

the newly inserted phrase might be similar to the highlighted one (worse if before the main one in terms of indices)

so if any of the above scenarios happens the indices will be of no use because you can fall to the wrong text

Do the following

a. when highlighting keep the following
       1. the content : to make sure if the edit happens in there, you know it and you can act accordingly

   2. keep track of the index range of your text even in case the shift is required (when the text before it is edited)

   3. take a screenshot of the entire article and store it so that when an edit to the article happens you know exactly which part is edited. this will require to check word by word and see if any word in the new text is different from the word of the same index in the old (screenshot). and you can shift the ranges of the highlighted text accordingly.

Remember any edit that happens after the highlighted text is innocuous.
Hope this helps.


问:
How to position two absolute positioned div's side by side in the mobile device,?
I wanna position two absolute div's side by side in the mobile device,
but there is a gap between the two divs.

I want to position them side by side if the size of the mobile device changes(flexible)

Thanks In Advance!

#header {
  position: relative;
}

#menu {
  background-color: green;
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
background-color:pink;
  position: absolute;
  overflow: auto;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 10;
  padding: 1.2rem;
  width: 70%;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div></code>```

答:
Almost there, you just had to use percentages and calculate it of the opposite side.

Fiddle: https://jsfiddle.net/bnx6ozh4/

```<code><div class="header">
    <div id="menu">menu</div>
    <div id="search"></div>
    <div id="tab">tab</div>
</div>
</code>```

And for the CSS

```<code>#header {
  position: relative;
}

#menu {
  position: absolute;
  bottom: 0;
  top: 0;
  width: 20%;
  right: 80%;
  background: green;
}

#tab {
  position: absolute;
  overflow: auto;
  right: 0;
  z-index: 10;
  padding: 1.2rem;
  left: 20%;
  background: red;
}
</code>```

Body:
I wanna position two absolute div's side by side in the mobile device,
but there is a gap between the two divs.

I want to position them side by side if the size of the mobile device changes(flexible)

Thanks In Advance!

#header {
  position: relative;
}

#menu {
  background-color: green;
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
background-color:pink;
  position: absolute;
  overflow: auto;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 10;
  padding: 1.2rem;
  width: 70%;
  display: block;
}

menu

tab

Body:
Almost there, you just had to use percentages and calculate it of the opposite side.

Fiddle: https://jsfiddle.net/bnx6ozh4/

<div class="header">
    <div id="menu">menu</div>
    <div id="search"></div>
    <div id="tab">tab</div>
</div>

And for the CSS

#header {
  position: relative;
}

#menu {
  position: absolute;
  bottom: 0;
  top: 0;
  width: 20%;
  right: 80%;
  background: green;
}

#tab {
  position: absolute;
  overflow: auto;
  right: 0;
  z-index: 10;
  padding: 1.2rem;
  left: 20%;
  background: red;
}


问:
Get visible and not hidden items with jquery
I need a to take all li elements to array. And ul and li both should be not visibility: hidden and not display: none. This is my code.

```<code>var links = $("li").is(":visible").is(":hidden");
var currentLink = links.first();

alert(currentLink.text());
</code>```

This is my list

```<code><ul>
   <li style='display: none'>Coffee</li>
   <li style='visibility: hidden'>Tea</li>
   <li>Milk</li>
</ul>
</code>```

(I need to show tea in alert and not coffee)

but I'm getting this error,

TypeError: $(...).is(...).is is not a function

答:
By looking at the answers I manage to create a perfect answer. I'm posting it in case if someone in the future may came up with same issue. Thanks so much for everyone helped me.</p>

```<code>var links = [];
$("li:not(:hidden)").each(function(index, item){
    if($(item).css("visibility") != "hidden"){
       links.push(item);
    }
});
</code>```

Body:
I need a to take all li elements to array. And ul and li both should be not visibility: hidden and not display: none. This is my code.

var links = $("li").is(":visible").is(":hidden");
var currentLink = links.first();

alert(currentLink.text());

This is my list

Coffee

Tea

Milk

(I need to show tea in alert and not coffee)

but I'm getting this error,

TypeError: $(...).is(...).is is not a function

Body:
By looking at the answers I manage to create a perfect answer. I'm posting it in case if someone in the future may came up with same issue. Thanks so much for everyone helped me.

var links = [];
$("li:not(:hidden)").each(function(index, item){
    if($(item).css("visibility") != "hidden"){
       links.push(item);
    }
});


问:
Art Game - Force JSON call to be uncached
I created a "guess the card art" game for Yu-Gi-Oh! here.

Basically it calls my php API which gets a random card every time.

API call: https://db.ygoprodeck.com/api/v4/artgame.php?format=speed

The API is called through JSON to show the card. The first JSON call is when a format is selected. It will show a card and you can guess. Right/Wrong/Skip causes the next JSON call to activate which brings up the next card.

Occasionally, the card will remain the same for the initial call and the first subsequent call, as if the call has been cached. It only ever happens for the first and subsequent call but doesn't occuer every time, usually if I clear my cache and try again.

I'm using these cache control methods on the top of my PHP API file:

```<code>header("Access-Control-Allow-Origin: *");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
</code>```

My JSON call:

```<code>var url = "https://db.ygoprodeck.com/api/v4/artgame.php"+difficultyformat;

//Get Card Data
jQuery.getJSON(url,
    function(data) {

        jQuery.each(data, function (i, val) {

        jQuery('.imgholder').append('<img src="'+val[0].image_url+'">');

        });
    }
);
</code>```

答:
Ah silly me. I didn't realize getJSON has built in caching.

I changed this:

```<code>//Get Card Data
jQuery.getJSON(url,
    function(data) {

        jQuery.each(data, function (i, val) {

        jQuery('.imgholder').append('<img src="'+val[0].image_url+'">');

        });
    }
);
</code>```

To This:

```<code>var url = "https://db.ygoprodeck.com/api/v4/artgame.php"+difficultyformat;

//Get Card Data
jQuery.ajax({
    cache: false,
    url: url,
    dataType: "json",
    success: function(data) {

    jQuery.each(data, function (i, val) {

        jQuery('.imgholder').append('<img src="'+val[0].image_url+'">');

        });
    }
});
</code>```

You can also use the following but it disabled cache globally which I definitely don't want:

```<code>jQuery(document).ready(function() {
  jQuery.ajaxSetup({ cache: false });
});
</code>```

Body:
I created a "guess the card art" game for Yu-Gi-Oh! here.

Basically it calls my php API which gets a random card every time.

API call: https://db.ygoprodeck.com/api/v4/artgame.php?format=speed

The API is called through JSON to show the card. The first JSON call is when a format is selected. It will show a card and you can guess. Right/Wrong/Skip causes the next JSON call to activate which brings up the next card.

Occasionally, the card will remain the same for the initial call and the first subsequent call, as if the call has been cached. It only ever happens for the first and subsequent call but doesn't occuer every time, usually if I clear my cache and try again.

I'm using these cache control methods on the top of my PHP API file:

header("Access-Control-Allow-Origin: *");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

My JSON call:

var url = "https://db.ygoprodeck.com/api/v4/artgame.php"+difficultyformat;

//Get Card Data
jQuery.getJSON(url,
    function(data) {

        jQuery.each(data, function (i, val) {

        jQuery('.imgholder').append('');

        });
    }
);

Body:
Ah silly me. I didn't realize getJSON has built in caching.

I changed this:

//Get Card Data
jQuery.getJSON(url,
    function(data) {

        jQuery.each(data, function (i, val) {

        jQuery('.imgholder').append('<img src="'+val[0].image_url+'">');

        });
    }
);

To This:

var url = "https://db.ygoprodeck.com/api/v4/artgame.php"+difficultyformat;

//Get Card Data
jQuery.ajax({
    cache: false,
    url: url,
    dataType: "json",
    success: function(data) {

    jQuery.each(data, function (i, val) {

        jQuery('.imgholder').append('<img src="'+val[0].image_url+'">');

        });
    }
});

You can also use the following but it disabled cache globally which I definitely don't want:

jQuery(document).ready(function() {
  jQuery.ajaxSetup({ cache: false });
});


问:
Using two mouse events after each other
I am creating a canvas alike  without using canvas tag , by creating new div each time mouse is down, i can't figure out how to run a second event.
Like mousedown then mousemove event where the seconed event occur only after the first one is true?
also if you can help with the  offset coordinates   </p>

```<code>var paintbox = document.getElementById("canvas");
var start = function() {
    paintbox.addEventListener("mousedown", drawOnCanvas);
};
var newColor = document.getElementById("colorPick");
var drawOnCanvas = function() {
        var newClick = document.createElement("div");
        newClick.setAttribute("id", "smallDiv");
        newClick.style.backgroundColor = newColor.value;
        newClick.style.width = "10px";
        newClick.style.height = "10px";
        newClick.style.position = "absolute";
        paintbox.appendChild(newClick);

    }
</code>```

答:
Set the handler on the mousemove event instead of mousedown and in the handler check whether the mouse button is down.

It would be better to move the 10px/position style settings in a CSS class. Also, don't generate elements with the same id attribute value: that generates invalid HTML. Use a class instead.

For the positioning you can use the pageX and pageY properties of the event object.

Finally, as the events will be triggered on the small divs when you make small moves, an extra check might be necessary to verify the mouse is still in the paint box.

var paintbox = document.getElementById("canvas");
var start = function() {
    paintbox.addEventListener("mousemove", drawOnCanvas);
};
var newColor = document.getElementById("colorPick");

var drawOnCanvas = function(e) {
    if ((e.buttons & 1) === 0) return; // Mouse button is not down
    // Extra check to see we are well within the box boundaries:
    var box = paintbox.getBoundingClientRect();
    if (e.clientX - 5 < box.left || e.clientX + 5 > box.right
         || e.clientY - 5 < box.top || e.clientY + 5 > box.bottom) return;
    var newClick = document.createElement("div");
    newClick.className = "smallDiv"; // Don't create duplicate ID; put CSS in class
    newClick.style.backgroundColor = newColor.value;
    paintbox.appendChild(newClick);
    newClick.style.left = (e.pageX-5) + "px";
    newClick.style.top = (e.pageY-5) + "px";
}

start();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
    height: 150px;
    width: 300px;
    border: 1px solid;
    display: inline-block;
    margin: 10px;
}
.smallDiv {
    width: 10px;
    height: 10px;
    position: absolute;
}</code>```

Color: <input id="colorPick" type="color">

```

Title: Using two mouse events after each other

Body:
I am creating a canvas alike  without using canvas tag , by creating new div each time mouse is down, i can't figure out how to run a second event.
Like mousedown then mousemove event where the seconed event occur only after the first one is true?
also if you can help with the  offset coordinates

var paintbox = document.getElementById("canvas");
var start = function() {
    paintbox.addEventListener("mousedown", drawOnCanvas);
};
var newColor = document.getElementById("colorPick");
var drawOnCanvas = function() {
        var newClick = document.createElement("div");
        newClick.setAttribute("id", "smallDiv");
        newClick.style.backgroundColor = newColor.value;
        newClick.style.width = "10px";
        newClick.style.height = "10px";
        newClick.style.position = "absolute";
        paintbox.appendChild(newClick);

    }

Body:
Set the handler on the mousemove event instead of mousedown and in the handler check whether the mouse button is down.

It would be better to move the 10px/position style settings in a CSS class. Also, don't generate elements with the same id attribute value: that generates invalid HTML. Use a class instead.

For the positioning you can use the pageX and pageY properties of the event object.

Finally, as the events will be triggered on the small divs when you make small moves, an extra check might be necessary to verify the mouse is still in the paint box.

var paintbox = document.getElementById("canvas");
var start = function() {
    paintbox.addEventListener("mousemove", drawOnCanvas);
};
var newColor = document.getElementById("colorPick");

var drawOnCanvas = function(e) {
    if ((e.buttons & 1) === 0) return; // Mouse button is not down
    // Extra check to see we are well within the box boundaries:
    var box = paintbox.getBoundingClientRect();
    if (e.clientX - 5 < box.left || e.clientX + 5 > box.right
         || e.clientY - 5 < box.top || e.clientY + 5 > box.bottom) return;
    var newClick = document.createElement("div");
    newClick.className = "smallDiv"; // Don't create duplicate ID; put CSS in class
    newClick.style.backgroundColor = newColor.value;
    paintbox.appendChild(newClick);
    newClick.style.left = (e.pageX-5) + "px";
    newClick.style.top = (e.pageY-5) + "px";
}

start();

#canvas {
    height: 150px;
    width: 300px;
    border: 1px solid;
    display: inline-block;
    margin: 10px;
}
.smallDiv {
    width: 10px;
    height: 10px;
    position: absolute;
}

Color: <input id="colorPick" type="color"><br>
<div id="canvas"></div>


问:
how to get the column name of the greatest value by using greatest function postgresql?
I have four columns in my table which are col1,col2,col3,col4.
I can find the greatest value by using

```<code>select greatest(col1,col2,col3,col4) from mytable;
</code>```

But I need to know the column name of the greatest value.

答:
You can use;</p>

```<code> select case greatest(col1, col2, col3, col4)
          when col1 then
           'col1' || '=' || col1
          when col2 then
           'col2' || '=' || col2
          when col3 then
           'col3' || '=' || col3
          when col4 then
           'col4' || '=' || col4
        end as greatest_value
   from (select max(col1) as col1,
                max(col2) as col2,
                max(col3) as col3,
                max(col4) as col4
           from mytable)
</code>```

Body:
I have four columns in my table which are col1,col2,col3,col4.
I can find the greatest value by using

select greatest(col1,col2,col3,col4) from mytable;

But I need to know the column name of the greatest value.

Body:
You can use;

 select case greatest(col1, col2, col3, col4)
          when col1 then
           'col1' || '=' || col1
          when col2 then
           'col2' || '=' || col2
          when col3 then
           'col3' || '=' || col3
          when col4 then
           'col4' || '=' || col4
        end as greatest_value
   from (select max(col1) as col1,
                max(col2) as col2,
                max(col3) as col3,
                max(col4) as col4
           from mytable)


问:
Git hook to reject commits where files contain a specific string
I am using Guard with Rspec; I use focus: true to force it run only tests I am working on. But sometimes I forget to remove focus: true and it is causing distraction for my future self and people I work with.

I want to make a git hook that would check the spec folder to make sure there is no focus: true in test files apart from spec/rails_helper.rb and keep it in Repository.

I have read this answer Putting git hooks into repository, guess it has to be a bit awkward.

How are hooks used to prevent a commit based on the contents of files?

Update

Here is what I have now but it doesn't work, even if there is no match, git refuses to commit.

```<code>FILES_PATTERN='\.rb(\..+)?$'
FORBIDDEN="(\, focus: true|binding\.pry)"
git diff --cached --name-only | egrep "$FILES_PATTERN" | xargs egrep --with-filename -n "$FORBIDDEN" && echo "Commit reject, found $FORBIDDEN reference, please remove" && exit 1
exit 0
</code>```

答:
Server-Side Git Hooks

I came up with this example for the use case of code formatting, but pretty much if you just replace the usage of Prettier with grep -r 'bad-thing' it should work as well:

```<code>ref_name=$1
new_rev=$3

# only check branches, not tags or bare commits
if [ -z $(echo $ref_name | grep "refs/heads/") ]; then
  exit 0
fi

# don't check empty branches
if [ "$(expr "${new_rev}" : '0*$')" -ne 0 ]; then
  exit 0
fi

# Checkout a copy of the branch (but also changes HEAD)
my_work_tree=$(mktemp -d -t git-work-tree.XXXXXXXX) 2>/dev/null
git --work-tree="${my_work_tree}" --git-dir="." checkout $new_rev -f >/dev/null

# Do the formatter check
echo "Checking code formatting..."
pushd ${my_work_tree} >/dev/null
prettier './**/*.{js,css,html,json,md}' --list-different
my_status=$?
popd >/dev/null

# reset HEAD to master, and cleanup
git --work-tree="${my_work_tree}" --git-dir="." checkout master -f >/dev/null
rm -rf "${my_work_tree}"

# handle error, if any
if [ "0" != "$my_status" ]; then
  echo "Please format the files listed above and re-commit."
  echo "(and don't forget your .prettierrc, if you have one)"
  exit 1
fi
</code>```

There are some limitations to this, so I'd recommend taking a look at the "more complete" version as well:

Reject Ugly Commits with Server-Side Git Hooks

The Gist of it...

If you want to do this server-side you'll be working with a bare repository (most likely), so you have to do a little bit of extra work to create a temporary place to check things out (as shown above).

Basically, this is the process:

use a server-side update hook (similar to pre-receive)

inspect the branch and commit

checkout the bare repo to a temp folder

run the check for specific string (grep -r 'bad-thing' .)

exit non-zero if there are offending files

And I would have adjusted the script to do the greping, but it's late (or rather very early) and I don't trust myself to not make a typo that breaks everything in trying to make a "simple" change. I know that the above works (because I've used it), so I'll leave at that.

HTH (not the OP per se, but others in the future - and perhaps myself again)

Body:
I am using Guard with Rspec; I use focus: true to force it run only tests I am working on. But sometimes I forget to remove focus: true and it is causing distraction for my future self and people I work with.

I want to make a git hook that would check the spec folder to make sure there is no focus: true in test files apart from spec/rails_helper.rb and keep it in Repository.

I have read this answer Putting git hooks into repository, guess it has to be a bit awkward.

How are hooks used to prevent a commit based on the contents of files?

Update

Here is what I have now but it doesn't work, even if there is no match, git refuses to commit.

FILES_PATTERN='\.rb(\..+)?$'
FORBIDDEN="(\, focus: true|binding\.pry)"
git diff --cached --name-only | egrep "$FILES_PATTERN" | xargs egrep --with-filename -n "$FORBIDDEN" && echo "Commit reject, found $FORBIDDEN reference, please remove" && exit 1
exit 0

Body:
Server-Side Git Hooks

I came up with this example for the use case of code formatting, but pretty much if you just replace the usage of Prettier with grep -r 'bad-thing' it should work as well:

ref_name=$1
new_rev=$3

# only check branches, not tags or bare commits
if [ -z $(echo $ref_name | grep "refs/heads/") ]; then
  exit 0
fi

# don't check empty branches
if [ "$(expr "${new_rev}" : '0*$')" -ne 0 ]; then
  exit 0
fi

# Checkout a copy of the branch (but also changes HEAD)
my_work_tree=$(mktemp -d -t git-work-tree.XXXXXXXX) 2>/dev/null
git --work-tree="${my_work_tree}" --git-dir="." checkout $new_rev -f >/dev/null

# Do the formatter check
echo "Checking code formatting..."
pushd ${my_work_tree} >/dev/null
prettier './**/*.{js,css,html,json,md}' --list-different
my_status=$?
popd >/dev/null

# reset HEAD to master, and cleanup
git --work-tree="${my_work_tree}" --git-dir="." checkout master -f >/dev/null
rm -rf "${my_work_tree}"

# handle error, if any
if [ "0" != "$my_status" ]; then
  echo "Please format the files listed above and re-commit."
  echo "(and don't forget your .prettierrc, if you have one)"
  exit 1
fi

There are some limitations to this, so I'd recommend taking a look at the "more complete" version as well:

Reject Ugly Commits with Server-Side Git Hooks

The Gist of it...

If you want to do this server-side you'll be working with a bare repository (most likely), so you have to do a little bit of extra work to create a temporary place to check things out (as shown above).

Basically, this is the process:

use a server-side update hook (similar to pre-receive)

inspect the branch and commit

checkout the bare repo to a temp folder

run the check for specific string (grep -r 'bad-thing' .)

exit non-zero if there are offending files

And I would have adjusted the script to do the greping, but it's late (or rather very early) and I don't trust myself to not make a typo that breaks everything in trying to make a "simple" change. I know that the above works (because I've used it), so I'll leave at that.

HTH (not the OP per se, but others in the future - and perhaps myself again)


问:
Got UndeclaredThrowableException at com.sun.proxy.$Proxy10.Open when trying to open an excel workbook
I have a feature in a plugin which exports some checklist items into Excel file. Before, everything worked fine, but since a few days ago i got an error with $Proxy10.Open() when trying to open the excel workbook. I don't know if this information is relevant, but i can reproduce this problem only on a few computers, on some of them i can reproduce it only if iam connecting to it remotely.

The error is:

```<code>    java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy10.Open(Unknown Source)
    Caused by: java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(FutureTask.java:205)
at com.sun.jna.platform.win32.COM.util.ComThread.execute(ComThread.java:157)
at com.sun.jna.platform.win32.COM.util.Factory$ProxyObject2.invoke(Factory.java:93)
... 5 more
</code>```

This is how i initialize COM subsystem:

```<code>Ole32.INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_MULTITHREADED);
facade.comFactory = new Factory();
</code>```

This is how I am initializing the excel application:

```<code>ComExcel_Application excel = facade.comFactory.createObject(ComExcel_Application.class);
facade.excelApp = excel.queryInterface(Application.class);
facade.excelApp.setVisible(true);
System.out.println("Using Excel version: " + facade.excelApp.getVersion());
</code>```

And this is where the exception is thrown:

```<code>Workbook myWorkbook = excelApp.getWorkbooks().Open(fullName.toString());
</code>```

I want to ask what is the root problem of this error and any hints are welcomed. I tried to find any related questions or errors, but nothing found.

答:
The problem came from the point where the Factory() is initialized for COM object creation. com.sun.jna.platform.win32.COM.util.Factory uses a thread to run the calls and this thread imposes an upper limit of execution time which is by default 5000ms. So I have extended the thread’s execution time to 15000ms.</p>

```<code>facade.comFactory = new Factory(new ComThread("COM Thread", 15000, new
                  Thread.UncaughtExceptionHandler() {
                        @Override
                        public void uncaughtException(Thread t, Throwable e) {
                            // do something intelligent
                        }
                    }));
</code>```

Body:
I have a feature in a plugin which exports some checklist items into Excel file. Before, everything worked fine, but since a few days ago i got an error with $Proxy10.Open() when trying to open the excel workbook. I don't know if this information is relevant, but i can reproduce this problem only on a few computers, on some of them i can reproduce it only if iam connecting to it remotely.

The error is:

    java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy10.Open(Unknown Source)
    Caused by: java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(FutureTask.java:205)
at com.sun.jna.platform.win32.COM.util.ComThread.execute(ComThread.java:157)
at com.sun.jna.platform.win32.COM.util.Factory$ProxyObject2.invoke(Factory.java:93)
... 5 more

This is how i initialize COM subsystem:

Ole32.INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_MULTITHREADED);
facade.comFactory = new Factory();

This is how I am initializing the excel application:

ComExcel_Application excel = facade.comFactory.createObject(ComExcel_Application.class);
facade.excelApp = excel.queryInterface(Application.class);
facade.excelApp.setVisible(true);
System.out.println("Using Excel version: " + facade.excelApp.getVersion());

And this is where the exception is thrown:

Workbook myWorkbook = excelApp.getWorkbooks().Open(fullName.toString());

I want to ask what is the root problem of this error and any hints are welcomed. I tried to find any related questions or errors, but nothing found.

Body:
The problem came from the point where the Factory() is initialized for COM object creation. com.sun.jna.platform.win32.COM.util.Factory uses a thread to run the calls and this thread imposes an upper limit of execution time which is by default 5000ms. So I have extended the thread’s execution time to 15000ms.

facade.comFactory = new Factory(new ComThread("COM Thread", 15000, new
                  Thread.UncaughtExceptionHandler() {
                        @Override
                        public void uncaughtException(Thread t, Throwable e) {
                            // do something intelligent
                        }
                    }));


问:
Secure, portable encrypted config values -- possible?
I'm just curious if anyone has any great ideas on this.

We have a lot of C# windows services.  Each app is installed on multiple machines (anywhere from 2-80, depending on the app.)

Due to the security setup of the network, we cannot (consistently) use Windows authentication to the SQL servers, so our connection strings and credentials have actual usernames and passwords.

Our infrastructure folks want to be able to do the following when deploying the software:
1) Edit the configuration once -- set the appropriate server, user, and passwords for various database connections.
2) Have the connection strings (at least) encrypted or otherwise unreadable to the naked eye
3) Copy that configuration file to all installations of a particular piece of software.  This means that the encryption cannot be tied to a specific machine.

Can DPAPI do this?  Can one set of keys be installed on all targets to allow the decryption of a common config file?  How is the configuration edited in this case?  How do you keep other users from viewing the encrypted configuration in the same manner?

答: This sounds like a job for an X509 certificate.</p>

OwnerDisplayName: Joe

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Charlie Martin