问:
goJS lock nodes
I have simple python flask app where I send JSON data to my HTML and with goJS I display my graph which looks like this:

Users can add new nodes and links, but what I want is that starting graph is locked so that users can not edit or delete any nodes or links from that starting graph. I just want that they can add new nodes and links and link it to starting graph nodes.

I really tried to search for this specific case but I haven't found what I am looking for. In documentation there are some options like disabling whole diagram or set it to read only, but that is not what I need. There are some mentions that you can make specific user permissions, but there is not any examples provided, so I need help.

Here is my code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>State Chart</title>
<meta name="description" content="A finite state machine chart with editable and interactive features." />
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/gojs/1.7.27/go.js"></script>
<script src="https://gojs.net/latest/extensions/TextEditorRadioButtons.js"></script>
<script src="https://gojs.net/latest/extensions/TextEditorSelectBox.js"></script>
<script src="https://gojs.net/latest/extensions/DataInspector.js"></script>
<link href="https://gojs.net/latest/extensions/DataInspector.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script id="code">

    function init() {

        var $ = go.GraphObject.make;
        myDiagram =
        $(go.Diagram, "myDiagramDiv",  // must name or refer to the DIV HTML element
        {
            // start everything in the middle of the viewport
            initialContentAlignment: go.Spot.Center,
            // have mouse wheel events zoom in and out instead of scroll up and down
            "toolManager.mouseWheelBehavior": go.ToolManager.WheelZoom,
            // support double-click in background creating a new node
            "clickCreatingTool.archetypeNodeData": { text: "new node" },
            // enable undo & redo
            "undoManager.isEnabled": true,
            "layout": new go.ForceDirectedLayout()
        });

        // when the document is modified, add a "*" to the title and enable the "Save" button
        myDiagram.addDiagramListener("Modified", function(e) {
            var button = document.getElementById("SaveButton");
            if (button) button.disabled = !myDiagram.isModified;
            var idx = document.title.indexOf("*");
            if (myDiagram.isModified) {
            if (idx < 0) document.title += "*";
            } else {
            if (idx >= 0) document.title = document.title.substr(0, idx);
            }
        });

            // define the Node template
        myDiagram.nodeTemplate =
          $(go.Node, "Auto",
            new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
            // define the node's outer shape, which will surround the TextBlock
            $(go.Shape, "RoundedRectangle",
              {
                parameter1: 20,  // the corner has a large radius
                fill: $(go.Brush, "Linear", { 0: "rgb(254, 201, 0)", 1: "rgb(254, 162, 0)" }),
                stroke: null,
                portId: "",  // this Shape is the Node's port, not the whole Node
                fromLinkable: true, fromLinkableDuplicates: true,
                toLinkable: true, toLinkableDuplicates: true,
                cursor: "pointer"
              }),
            $(go.TextBlock,
              {
                font: "bold 11pt helvetica, bold arial, sans-serif",
                editable: true  // editing the text automatically updates the model data
                //textEditor: window.TextEditorRadioButtons, // defined in textEditorRadioButtons.js
                // this specific TextBlock has its own choices:
                //choices: ['One', 'Two', 'Three', 'Four']
              },
            new go.Binding("text").makeTwoWay())
        );

        myDiagram.nodeTemplate.selectionAdornmentTemplate =
        $(go.Adornment, "Spot",
            $(go.Panel, "Auto",
            $(go.Shape, { stroke: "dodgerblue", strokeWidth: 2, fill: null }),
            $(go.Placeholder)
        ),
        $(go.Panel, "Horizontal",
            { alignment: go.Spot.Top, alignmentFocus: go.Spot.Bottom },
            $("Button",
                { click: editText },  // defined below, to support editing the text of the node
                $(go.TextBlock, "t",
                { font: "bold 10pt sans-serif", desiredSize: new go.Size(15, 15), textAlign: "center" })
            ),
            $("Button",
            { // drawLink is defined below, to support interactively drawing new links
                click: drawLink,  // click on Button and then click on target node
                actionMove: drawLink  // drag from Button to the target node
            },
            $(go.Shape,
                { geometryString: "M0 0 L8 0 8 12 14 12 M12 10 L14 12 12 14" })
            ),
            $("Button",
            {
                actionMove: dragNewNode,  // defined below, to support dragging from the button
                _dragData: { text: "?????", color: "lightgray" },  // node data to copy
                click: clickNewNode  // defined below, to support a click on the button
            },
            $(go.Shape,
                { geometryString: "M0 0 L3 0 3 10 6 10 x F1 M6 6 L14 6 14 14 6 14z", fill: "gray" })
          )
        )
      );

    function editText(e, button) {
        //console.log(e);

      var node = button.part.adornedPart;
      console.log("node");
      //console.log(node);
      e.diagram.commandHandler.editTextBlock(node.findObject("TEXTBLOCK"));
      //$("#nodeText").val(node.findObject("TEXTBLOCK"));
    }

    function drawLink(e, button) {
      var node = button.part.adornedPart;
      var tool = e.diagram.toolManager.linkingTool;
      tool.startObject = node.port;
      e.diagram.currentTool = tool;
      tool.doActivate();
    }

   // used by both clickNewNode and dragNewNode to create a node and a link
    // from a given node to the new node
    function createNodeAndLink(data, fromnode) {
        var diagram = fromnode.diagram;
        var model = diagram.model;
        var nodedata = model.copyNodeData(data);
        model.addNodeData(nodedata);
        var newnode = diagram.findNodeForData(nodedata);
        var linkdata = model.copyLinkData({});
        model.setFromKeyForLinkData(linkdata, model.getKeyForNodeData(fromnode.data));
        model.setToKeyForLinkData(linkdata, model.getKeyForNodeData(newnode.data));
        model.addLinkData(linkdata);
        diagram.select(newnode);
        return newnode;
    }

    // the Button.click event handler, called when the user clicks the "N" button
    function clickNewNode(e, button) {
        var data = button._dragData;
        if (!data) return;
        e.diagram.startTransaction("Create Node and Link");
        var fromnode = button.part.adornedPart;
        var newnode = createNodeAndLink(button._dragData, fromnode);
        newnode.location = new go.Point(fromnode.location.x + 200, fromnode.location.y);
        e.diagram.commitTransaction("Create Node and Link");
    }

    // the Button.actionMove event handler, called when the user drags within the "N" button
    function dragNewNode(e, button) {
        var tool = e.diagram.toolManager.draggingTool;
        if (tool.isBeyondDragSize()) {
            var data = button._dragData;
            if (!data) return;
            e.diagram.startTransaction("button drag");  // see doDeactivate, below
            var newnode = createNodeAndLink(data, button.part.adornedPart);
            newnode.location = e.diagram.lastInput.documentPoint;
            // don't commitTransaction here, but in tool.doDeactivate, after drag operation finished
            // set tool.currentPart to a selected movable Part and then activate the DraggingTool
            tool.currentPart = newnode;
            e.diagram.currentTool = tool;
            tool.doActivate();
        }
    }

    // using dragNewNode also requires modifying the standard DraggingTool so that it
    // only calls commitTransaction when dragNewNode started a "button drag" transaction;
    // do this by overriding DraggingTool.doDeactivate:
    var tool = myDiagram.toolManager.draggingTool;
    tool.doDeactivate = function() {
        // commit "button drag" transaction, if it is ongoing; see dragNewNode, above
        if (tool.diagram.undoManager.nestedTransactionNames.elt(0) === "button drag") {
            tool.diagram.commitTransaction();
        }
        go.DraggingTool.prototype.doDeactivate.call(tool);  // call the base method
    };

    // replace the default Link template in the linkTemplateMap
    myDiagram.linkTemplate =
        $(go.Link,  // the whole link panel
        {
            curve: go.Link.Bezier,
            adjusting: go.Link.Stretch,
            reshapable: true,
            relinkableFrom: true,
            relinkableTo: true,
            toShortLength: 3
        },
        new go.Binding("points").makeTwoWay(),
        new go.Binding("curviness"),
        $(go.Shape,  // the link shape
            { strokeWidth: 1.5 }),
        $(go.Shape,  // the arrowhead
            { toArrow: "standard", stroke: null }),
        $(go.Panel, "Auto",
            $(go.Shape,  // the label background, which becomes transparent around the edges
            {
                fill: $(go.Brush, "Radial",
                      { 0: "rgb(240, 240, 240)", 0.3: "rgb(240, 240, 240)", 1: "rgba(240, 240, 240, 0)" }),
                stroke: null
            }),
            $(go.TextBlock, "?????",  // the label text
            {
                textAlign: "center",
                font: "9pt helvetica, arial, sans-serif",
                margin: 4,
                editable: true  // enable in-place editing
            },
            // editing the text automatically updates the model data
            new go.Binding("text").makeTwoWay())
        )
    );

    var inspector = new Inspector('myInspectorDiv', myDiagram,
    {
        // uncomment this line to only inspect the named properties below instead of all properties on each object:
        // includesOwnProperties: false,
        properties: {
            "text": { },
            // an example of specifying the type
            "password": { show: Inspector.showIfPresent, type: 'password' },
            // key would be automatically added for nodes, but we want to declare it read-only also:
            "key": { readOnly: true, show: Inspector.showIfPresent },
            // color would be automatically added for nodes, but we want to declare it a color also:
            "color": { show: Inspector.showIfPresent, type: 'color' },
            // Comments and LinkComments are not in any node or link data (yet), so we add them here:
            "Comments": { show: Inspector.showIfNode  },
            "flag": { show: Inspector.showIfNode, type: 'checkbox' },
            "LinkComments": { show: Inspector.showIfLink },
            "isGroup": { readOnly: true, show: Inspector.showIfPresent }
        }
    });

    // read in the JSON data from flask
    loadGraphData();

    }

    function loadGraphData() {
        var graphDataString = JSON.parse('{{ diagramData | tojson | safe}}');
        console.log("graphDataString");
        console.log(graphDataString);

        myDiagram.model = go.Model.fromJson(graphDataString);
    }

    function saveGraphData(form, event) {
        console.log("inside saveGraphData");
        event.preventDefault();

        document.getElementById("mySavedModel").value = myDiagram.model.toJson();
        form.submit();
    }

    function zoomToFit(){
        console.log("inside zoomToFit");
        myDiagram.zoomToRect(myDiagram.documentBounds);
    }

    function zoomIn(){
        console.log("inside zoomIn");
        myDiagram.commandHandler.increaseZoom();
    }
    function zoomOut(){
        console.log("inside zoomOut");
        myDiagram.commandHandler.decreaseZoom();
    }

</script>
</head>
<body onload="init()">

    <div id=formWrapper style="padding: 30px;">

        <form method="POST" action="http://localhost:5000/updateResultFile" name="updateResultFileForm"
        id="updateResultFileForm"
        onsubmit="saveGraphData(this, event);">

            <div id="graphWrapper" style="margin-bottom: 15px;">
                <div id="myDiagramDiv" style="border: solid 1px black; width: 100%; height: 800px;margin-bottom: 15px;"></div>
                <div style="display: none;"><input id="mySavedModel" name="mySavedModel"></div>

                <button class="btn btn-default" type="submit"> Save <i class="fa fa-save"> </i> </button>

            </div>

        </form>

        <div id="myInspectorDiv">
        </div>

        <div>
            <button class="btn btn-default" onclick="zoomToFit()"> Zoom to fit  <i class="fa fa-search"> </i> </button>
            <button class="btn btn-default" onclick="zoomIn()"> Zoom in  <i class="fa fa-search-plus"> </i> </button>
            <button class="btn btn-default" onclick="zoomOut()"> Zoom out  <i class="fa fa-search-minus"> </i> </button>
        </div>

    </div>

</body>
</html>
</code>```

Any help will be appreciated

答:
Yes, that documentation page about user permissions, https://gojs.net/latest/intro/permissions.html, should give you an answer.

I'm guessing that you don't want to disable all deletions by setting Diagram.allowDelete to false, or to disable all in-place text editing by setting Diagram.allowTextEdit to false. Instead you probably want to prevent deleting or editing the original nodes and links but not any newly created nodes or links. Is that right?

If so, you can set or bind Part.deletable and Part.textEditable to false on all those original Nodes and Links. You can do that in an "InitialLayoutCompleted" DiagramEvent listener. For example in a Diagram initialization:

```<code>$(go.Diagram, . . .,
  { . . .,
    "InitialLayoutCompleted": function(e) {
        e.diagram.nodes.each(function(n) { n.deletable = false; n.textEditable = false; });
        e.diagram.links.each(function(l) { l.deletable = false; l.textEditable = false; });
      },
    . . .
 })
</code>```

Of course you wouldn't need to set Link.textEditable to false if you didn't have any editable text labels in your Links, but you do seem to.

Title: goJS lock nodes

Body:
I have simple python flask app where I send JSON data to my HTML and with goJS I display my graph which looks like this:

Users can add new nodes and links, but what I want is that starting graph is locked so that users can not edit or delete any nodes or links from that starting graph. I just want that they can add new nodes and links and link it to starting graph nodes.

I really tried to search for this specific case but I haven't found what I am looking for. In documentation there are some options like disabling whole diagram or set it to read only, but that is not what I need. There are some mentions that you can make specific user permissions, but there is not any examples provided, so I need help.

Here is my code:

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<title>State Chart</title>
<meta name="description" content="A finite state machine chart with editable and interactive features." />
<meta charset="UTF-8">

<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

<link href="https://gojs.net/latest/extensions/DataInspector.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

        <form method="POST" action="http://localhost:5000/updateResultFile" name="updateResultFileForm"
        id="updateResultFileForm"
        onsubmit="saveGraphData(this, event);">

<input id="mySavedModel" name="mySavedModel">

                <button class="btn btn-default" type="submit"> Save   </button>

        </form>

            <button class="btn btn-default" onclick="zoomToFit()"> Zoom to fit    </button>
            <button class="btn btn-default" onclick="zoomIn()"> Zoom in    </button>
            <button class="btn btn-default" onclick="zoomOut()"> Zoom out    </button>

Any help will be appreciated

Body:
Yes, that documentation page about user permissions, https://gojs.net/latest/intro/permissions.html, should give you an answer.

I'm guessing that you don't want to disable all deletions by setting Diagram.allowDelete to false, or to disable all in-place text editing by setting Diagram.allowTextEdit to false. Instead you probably want to prevent deleting or editing the original nodes and links but not any newly created nodes or links. Is that right?

If so, you can set or bind Part.deletable and Part.textEditable to false on all those original Nodes and Links. You can do that in an "InitialLayoutCompleted" DiagramEvent listener. For example in a Diagram initialization:

$(go.Diagram, . . .,
  { . . .,
    "InitialLayoutCompleted": function(e) {
        e.diagram.nodes.each(function(n) { n.deletable = false; n.textEditable = false; });
        e.diagram.links.each(function(l) { l.deletable = false; l.textEditable = false; });
      },
    . . .
 })

Of course you wouldn't need to set Link.textEditable to false if you didn't have any editable text labels in your Links, but you do seem to.


来源: stackexchange

问:
"Cleaning up" nested if statements

In a console program I am creating, I have a bit of code that parses through a file. After parsing each line, it is checked for syntax errors. If there is a syntax error, the program then stops reading the file and goes to the next part of the program. The problem is, it is very messy as my only solution to it so far is a series of nested if statements or a line of if statements. The problem with nested ifs is it gets very messy very fast, and a series of if statements has the program testing for several things that don't need to be tested. Heres some sudo code of my problem (note I am NOT using a return statement)

Pseudo code shown instead of real code, as it is very large

Nested if:

```<code>open file;
read line;
//Each if is testing something different
//Every error is different
if (line is valid)
{
    read line;
    if (line is valid)
    {
        read line;
        if (line is valid)
        {
            do stuff;
        }
        else
            error;
    }
    else
        error;

}
else
    error;
code that must be reached, even if there was an error;
</code>```

Non-nested ifs:

```<code>bool fail = false;
open file;
read line;
//Each if is testing something different
//Every error is different
if (line is valid)
    read line;
else
{
    error;
    fail = true;
}
if (!error && line is valid)
    read line;
else
{
    error;
fail = true;
}
if (!error && line is valid)
    do stuff;
else
    error;
//Note how error is constantly evaluated, even if it has already found to be false
code that must be reached, even if there was an error;
</code>```

I have looked at many different sites, but their verdicts differed from my problem. This code does work at runtime, but as you can see it is not very elegant. Is there anyone who has a more readable/efficient approach on my problem? Any help is appreciated :)

答:
Is there [...] a more readable/efficient approach on my problem

Step 1. Look around for a classical example of text parser

Answer: a compiler, which parses text files and produces different kind of results.

Step 2. Read some theory how does compilers work

There are lots of approaches and techniques. Books, online and open source examples. Simple and complicated.

Sure, you might just skip this step if you are not that interested.

Step 3. Apply theory on you problem

Looking through the theory, you will no miss such therms as "state machine", "automates" etc. Here is a brief explanation on Wikipedia:

https://en.wikipedia.org/wiki/Automata-based_programming

There is basically a ready to use example on the Wiki page:

```<code>#include <stdio.h>
enum states { before, inside, after };
void step(enum states *state, int c)
{
    if(c == '\n') {
        putchar('\n');
        *state = before;
    } else
    switch(*state) {
        case before:
            if(c != ' ') {
                putchar(c);
                *state = inside;
            }
            break;
        case inside:
            if(c == ' ') {
                *state = after;
            } else {
                putchar(c);
            }
            break;
        case after:
            break;
    }
}
int main(void)
{
    int c;
    enum states state = before;
    while((c = getchar()) != EOF) {
        step(&state, c);
    }
    if(state != before)
        putchar('\n');
    return 0;
}
</code>```

Or a C++ example with state machine:

```<code>#include <stdio.h>
class StateMachine {
    enum states { before = 0, inside = 1, after = 2 } state;
    struct branch {
        unsigned char new_state:2;
        unsigned char should_putchar:1;
    };
    static struct branch the_table[3][3];
public:
    StateMachine() : state(before) {}
    void FeedChar(int c) {
        int idx2 = (c == ' ') ? 0 : (c == '\n') ? 1 : 2;
        struct branch *b = & the_table[state][idx2];
        state = (enum states)(b->new_state);
        if(b->should_putchar) putchar(c);
    }
};
struct StateMachine::branch StateMachine::the_table[3][3] = {
                 /* ' '         '\n'        others */
    /* before */ { {before,0}, {before,1}, {inside,1} },
    /* inside */ { {after, 0}, {before,1}, {inside,1} },
    /* after  */ { {after, 0}, {before,1}, {after, 0} }
};
int main(void)
{
    int c;
    StateMachine machine;
    while((c = getchar()) != EOF)
        machine.FeedChar(c);
    return 0;
}
</code>```

Sure, instead of chars you should feed lines.

This technique scales up to a complicated compilers, proven with tons of implementations. So if you are looking for a "right" approach, here it is.

ContentLicense: CC BY-SA 3.0

Title: "Cleaning up" nested if statements

Body:
In a console program I am creating, I have a bit of code that parses through a file. After parsing each line, it is checked for syntax errors. If there is a syntax error, the program then stops reading the file and goes to the next part of the program. The problem is, it is very messy as my only solution to it so far is a series of nested if statements or a line of if statements. The problem with nested ifs is it gets very messy very fast, and a series of if statements has the program testing for several things that don't need to be tested. Heres some sudo code of my problem (note I am NOT using a return statement)

Pseudo code shown instead of real code, as it is very large

Nested if:

open file;
read line;
//Each if is testing something different
//Every error is different
if (line is valid)
{
    read line;
    if (line is valid)
    {
        read line;
        if (line is valid)
        {
            do stuff;
        }
        else
            error;
    }
    else
        error;

}
else
    error;
code that must be reached, even if there was an error;

Non-nested ifs:

bool fail = false;
open file;
read line;
//Each if is testing something different
//Every error is different
if (line is valid)
    read line;
else
{
    error;
    fail = true;
}
if (!error && line is valid)
    read line;
else
{
    error;
fail = true;
}
if (!error && line is valid)
    do stuff;
else
    error;
//Note how error is constantly evaluated, even if it has already found to be false
code that must be reached, even if there was an error;

I have looked at many different sites, but their verdicts differed from my problem. This code does work at runtime, but as you can see it is not very elegant. Is there anyone who has a more readable/efficient approach on my problem? Any help is appreciated :)

Body:
Is there [...] a more readable/efficient approach on my problem

Step 1. Look around for a classical example of text parser

Answer: a compiler, which parses text files and produces different kind of results.

Step 2. Read some theory how does compilers work

There are lots of approaches and techniques. Books, online and open source examples. Simple and complicated.

Sure, you might just skip this step if you are not that interested.

Step 3. Apply theory on you problem

Looking through the theory, you will no miss such therms as "state machine", "automates" etc. Here is a brief explanation on Wikipedia:

https://en.wikipedia.org/wiki/Automata-based_programming

There is basically a ready to use example on the Wiki page:

#include <stdio.h>
enum states { before, inside, after };
void step(enum states *state, int c)
{
    if(c == '\n') {
        putchar('\n');
        *state = before;
    } else
    switch(*state) {
        case before:
            if(c != ' ') {
                putchar(c);
                *state = inside;
            }
            break;
        case inside:
            if(c == ' ') {
                *state = after;
            } else {
                putchar(c);
            }
            break;
        case after:
            break;
    }
}
int main(void)
{
    int c;
    enum states state = before;
    while((c = getchar()) != EOF) {
        step(&state, c);
    }
    if(state != before)
        putchar('\n');
    return 0;
}

Or a C++ example with state machine:

#include <stdio.h>
class StateMachine {
    enum states { before = 0, inside = 1, after = 2 } state;
    struct branch {
        unsigned char new_state:2;
        unsigned char should_putchar:1;
    };
    static struct branch the_table[3][3];
public:
    StateMachine() : state(before) {}
    void FeedChar(int c) {
        int idx2 = (c == ' ') ? 0 : (c == '\n') ? 1 : 2;
        struct branch *b = & the_table[state][idx2];
        state = (enum states)(b->new_state);
        if(b->should_putchar) putchar(c);
    }
};
struct StateMachine::branch StateMachine::the_table[3][3] = {
                 /* ' '         '\n'        others */
    /* before */ { {before,0}, {before,1}, {inside,1} },
    /* inside */ { {after, 0}, {before,1}, {inside,1} },
    /* after  */ { {after, 0}, {before,1}, {after, 0} }
};
int main(void)
{
    int c;
    StateMachine machine;
    while((c = getchar()) != EOF)
        machine.FeedChar(c);
    return 0;
}

Sure, instead of chars you should feed lines.

This technique scales up to a complicated compilers, proven with tons of implementations. So if you are looking for a "right" approach, here it is.


问:
Unable to reference HTML values in Javascript
I am building a Django app and need to do some Javascript processing in the HTML Template. In order to pass values from Django's templating language into Javascript, I have saved the values into meta tags as below:

```<code><head>
    {% for candidate in candidates %}
        <meta id="cand" data-id="{{candidate.id}}" data-order="{{forloop.counter}}">
        <h3>{{forloop.counter}}</h3>
    {% endfor %}
</head>
</code>```

I then try to access the data here:

```<code><script type="text/javascript">

var metatags = document.getElementsByTagName('meta');
for (var i = 0; i < metatags.length; i++) {
    console.log(metatags[i].data-id)
}

</script>
</code>```

However, an issue is thrown trying to access the data:

```<code>Uncaught ReferenceError: id is not defined
</code>```

In reference to the line console.log(metatags[i].data-id)

Why is this not working, am I attempting something impossible, and is there a better or more elegant way of accessing template values in Javascript?

Thanks in advance.

答:
You have incorrect syntax for accessing HTML attributes using JavaScript.

Two ways to access data attributes,

Using dataset

console.log(metatags[i].dataset.id)

Learn more about dataset at MDN

Using getAttribute

console.log(metatags[i].getAttribute('data-id'))

Body:
I am building a Django app and need to do some Javascript processing in the HTML Template. In order to pass values from Django's templating language into Javascript, I have saved the values into meta tags as below:

    {% for candidate in candidates %}
        <meta id="cand" data-id="{{candidate.id}}" data-order="{{forloop.counter}}">

{{forloop.counter}}

    {% endfor %}

I then try to access the data here:

However, an issue is thrown trying to access the data:

Uncaught ReferenceError: id is not defined

In reference to the line console.log(metatags[i].data-id)

Why is this not working, am I attempting something impossible, and is there a better or more elegant way of accessing template values in Javascript?

Thanks in advance.


问:
Ajax doesn't post data
[SOLVED]

That was THE most difficult bug ever - all due to copy/paste stuff up.

This:

```<code>$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
</code>```

should have been that:

```<code>$('#errors'+bUID).append('<ul id="error_list'+bUID+'"></ul>');
</code>```

The damn '+bUID+' was pasted AFTER the " , not BEFORE!

Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))

Here's the js:

```<code>$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    e.preventDefault();
    submitForm(bUID);
    alert(bUID);
});

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();
    alert(bUID);

    // also tried this
    var post_data = {
    'name': $('#name'+bUID).val(),
    'email': $('#email'+bUID).val(),
    'message': $('#message'+bUID).val(),
    'code': $('#code'+bUID).val(),
    'buid': bUID,
    };
    alert(Object.keys(post_data).length);

    // ALSO tried this instead of ajax:
    //$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
    alert(response);
    $.ajax({
        dataType: "json",
        type: "post",
        data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
        //data: post_data,
        url:   $('#contact_form'+bUID).attr('action'),
        success: function(response) {
            if (typeof response !== 'undefined' && response.length > 0) {
                if (response[0] == "success") {
                    $('#success'+bUID).append('<p>Success</p>');
                }
                else {
                    $('#errors'+bUID).append('<p>' + js_errors + '</p>');
                    $('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
                    $.each(response, function(i, v){
                        if (i > 0) {
                            $('#error_list'+bUID).append('<li>' + v + '</li>');
                        }
                    });
                }
            }
        }
    });
}
</code>```

here's the action in view.php:

```<code><?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>

<form id="contact_form<?php echo $bUID; ?>"
    class="contact-form"
    enctype="multipart/form-data"
    action="<?php echo $formAction?>"
    method="post"
    accept-charset="utf-8">

    <?php echo $bUID; ?><br />
    <input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">

   ...etc.
</code>```

and here's the controller.php:

```<code>public function action_submit($token = false, $bID = false)
{
    $this->form_errors = array();
    array_push($this->form_errors, "error");
    array_push($this->form_errors, $_POST['name']);
    array_push($this->form_errors, $_POST['email']);
    array_push($this->form_errors, $_POST['message']);
    array_push($this->form_errors, $_POST['code']);
    array_push($this->form_errors, $_POST['buid']);
    echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
    exit;
}
</code>```

it gets all data and shows it in alert but then trows the following error in the console:

```<code>Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg@gmail.commm","gggggggggggggggggggggggg","gggg","171"]
    at r (jquery.js:2)
    at Function.each (jquery.js:2)
    at Object.success (view.js:132)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at x (jquery.js:5)
    at XMLHttpRequest.b (jquery.js:5)
</code>```

Line 132 of the js file is this: $.each(response, function(i, v){

I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg@gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!

What's wrong here? Why doesn't the form get posted?

Thank you very much.

答:
Try this way,</p>

```<code>function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();

    $.post($('#contact_form'+bUID).attr('action'), {name:name, email:email, message:message, code:code, buid:bUID}, function(result){
        alert(result);
    });
}
</code>```

Title: Ajax doesn't post data

Body:
[SOLVED]

That was THE most difficult bug ever - all due to copy/paste stuff up.

This:

$('#errors'+bUID).append('

');

should have been that:

$('#errors'+bUID).append('

');

The damn '+bUID+' was pasted AFTER the " , not BEFORE!

Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))

Here's the js:

$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    e.preventDefault();
    submitForm(bUID);
    alert(bUID);
});

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();
    alert(bUID);

    // also tried this
    var post_data = {
    'name': $('#name'+bUID).val(),
    'email': $('#email'+bUID).val(),
    'message': $('#message'+bUID).val(),
    'code': $('#code'+bUID).val(),
    'buid': bUID,
    };
    alert(Object.keys(post_data).length);

    // ALSO tried this instead of ajax:
    //$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
    alert(response);
    $.ajax({
        dataType: "json",
        type: "post",
        data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
        //data: post_data,
        url:   $('#contact_form'+bUID).attr('action'),
        success: function(response) {
            if (typeof response !== 'undefined' && response.length > 0) {
                if (response[0] == "success") {
                    $('#success'+bUID).append('
Success
');
                }
                else {
                    $('#errors'+bUID).append('
' + js_errors + '
');
                    $('#errors'+bUID).append('

');
                    $.each(response, function(i, v){
                        if (i > 0) {
                            $('#error_list'+bUID).append('
' + v + '
');
                        }
                    });
                }
            }
        }
    });
}

here's the action in view.php:

<?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>

<form id="contact_form<?php echo $bUID; ?>"
    class="contact-form"
    enctype="multipart/form-data"
    action="<?php echo $formAction?>"
    method="post"
    accept-charset="utf-8">

    <?php echo $bUID; ?>

    <input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">

   ...etc.

and here's the controller.php:

public function action_submit($token = false, $bID = false)
{
    $this->form_errors = array();
    array_push($this->form_errors, "error");
    array_push($this->form_errors, $_POST['name']);
    array_push($this->form_errors, $_POST['email']);
    array_push($this->form_errors, $_POST['message']);
    array_push($this->form_errors, $_POST['code']);
    array_push($this->form_errors, $_POST['buid']);
    echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
    exit;
}

it gets all data and shows it in alert but then trows the following error in the console:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg@gmail.commm","gggggggggggggggggggggggg","gggg","171"]
    at r (jquery.js:2)
    at Function.each (jquery.js:2)
    at Object.success (view.js:132)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at x (jquery.js:5)
    at XMLHttpRequest.b (jquery.js:5)

Line 132 of the js file is this: $.each(response, function(i, v){

I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg@gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!

What's wrong here? Why doesn't the form get posted?

Thank you very much.

Body:
Try this way,

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();

    $.post($('#contact_form'+bUID).attr('action'), {name:name, email:email, message:message, code:code, buid:bUID}, function(result){
        alert(result);
    });
}


问:
Unable to ingest the syslog-logstash.conf for remove & replace functions
I am just a newbie to the ELK and trying some testing on this, i'm able to run some tests but while i'm trying a filter with grok & mutate to remoev & replace some feilds from my syslog output i'm getting into below error..

```<code>21:58:47.976 [LogStash::Runner] ERROR logstash.agent - Cannot create pipeline {:reason=>"Expected one of #, {, ,, ] at line 21, column 9 (byte 496) after filter {\n  if [type] == \"syslog\" {\n    grok {\n      match => { \"message\" => \"%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:hostname} %{DATA:program}(?:\\[%{POSINT:pid}\\])?: %{GREEDYDATA:syslog_message}\" }\n    }\n    date {\n      match => [ \"syslog_timestamp\", \"MMM  d HH:mm:ss\", \"MMM dd HH:mm:ss\" ]\n    }\n    mutate {\n      remove_field => [\n        \"message\",\n        \"pid\",\n        \"port\"\n        "}
</code>```

Below is my config file ....

```<code># cat logstash-syslog2.conf
input {
  file {
    path => [ "/scratch/rsyslog/*/messages.log" ]
    type => "syslog"
  }
}

filter {
  if [type] == "syslog" {
    grok {
      match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:hostname} %{DATA:program}(?:\[%{POSINT:pid}\])?: %{GREEDYDATA:syslog_message}" }
    }
    date {
      match => [ "syslog_timestamp", "MMM  d HH:mm:ss", "MMM dd HH:mm:ss" ]
    }
    mutate {
      remove_field => [
        "message",
        "pid",
        "port"
        "_grokparsefailure"
      ]
    }
    mutate {
      replace => [
        "@source_host", "%{allLogs_hostname}"
        "@message", "%{allLogs_message}"
      ]
    }
    mutate {
      remove => [
        "allLogs_hostname",
        "syslog_message",
        "syslog_timestamp"
      ]
    }
}
output {
  if [type] == "syslog" {
    elasticsearch {
      hosts => "localhost:9200"
      index => "%{type}-%{+YYYY.MM.dd}"
    }
  }
}
</code>```

please suggest what i'm doing wrong and  help to understand the remove & replace functions for the lagstash..

PS: my ELK version is 5.4

答:
The Config you posted have lot of syntactical errors , the logsatsh has it's own config language and expects the config file to abide by the rule.
This link has complete logstash config language reference.

I made some corrections to your config file and posted here , Have added my comments and explanation of what was wrong in the config file itself

```<code>input
{
    file
    {
        path => [ "/scratch/rsyslog/*/messages.log" ]
        type => "syslog"
    }
}

filter
{
    if [type] == "syslog"
    {
        grok
        {
            match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:hostname} %{DATA:program}(?:\[%{POSINT:pid}\])?: %{GREEDYDATA:syslog_message}" }
        }

    date
    {
        match => [ "syslog_timestamp", "MMM  d HH:mm:ss", "MMM dd HH:mm:ss" ]
    }

    # Have merged it with the remove_field option below
    #mutate {
    #  remove_field => [
    #    "message",
    #    "pid",
    #    "port",
    #    "_grokparsefailure"
    #  ]
    #}

    mutate
    {

        # The replace option only accept hash data type which has a syntax as below
        # For more details visit the below link
        # https://www.elastic.co/guide/en/logstash/current/plugins-filters-mutate.html#plugins-filters-mutate-replace
        replace => {
            "@source_host" => "%{allLogs_hostname}"
            "@message" => "%{allLogs_message}"
        }
    }

    mutate
    {
        # Mutate does not have remove option i guess your intention is to remove the event field
        # hence used remove_field option here
        # The remove_filed option only accepts arary as value type as shown below
        # For details read the below link
        # https://www.elastic.co/guide/en/logstash/current/plugins-filters-mutate.html#plugins-filters-mutate-remove_field
        remove_field => [
            "message",
            "pid",
            "port",
            "_grokparsefailure",
            "allLogs_hostname",
            "syslog_message",
            "syslog_timestamp"
        ]
    }
  }
}

output
{
    if [type] == "syslog"
    {
        elasticsearch
        {
            # The Hosts option only takes uri as a value type , originally you have provided string as it's value type
            # For more info please read the below link
            #https://www.elastic.co/guide/en/logstash/current/plugins-outputs-elasticsearch.html#plugins-outputs-elasticsearch-hosts
            hosts => ["localhost:9200"]
            index => "%{type}-%{+YYYY.MM.dd}"
        }
    }
}
</code>```

You can test whether the config file is syntactically correct by  using logstash command line option -t this option will test and report the config file is syntactically correct

```<code>bin\logstash -f 'path-to-your-config-file' -t
</code>```

Please let me know for any clarification

Body:
I am just a newbie to the ELK and trying some testing on this, i'm able to run some tests but while i'm trying a filter with grok & mutate to remoev & replace some feilds from my syslog output i'm getting into below error..

21:58:47.976 [LogStash::Runner] ERROR logstash.agent - Cannot create pipeline {:reason=>"Expected one of #, {, ,, ] at line 21, column 9 (byte 496) after filter {\n  if [type] == \"syslog\" {\n    grok {\n      match => { \"message\" => \"%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:hostname} %{DATA:program}(?:\\[%{POSINT:pid}\\])?: %{GREEDYDATA:syslog_message}\" }\n    }\n    date {\n      match => [ \"syslog_timestamp\", \"MMM  d HH:mm:ss\", \"MMM dd HH:mm:ss\" ]\n    }\n    mutate {\n      remove_field => [\n        \"message\",\n        \"pid\",\n        \"port\"\n        "}

Below is my config file ....

# cat logstash-syslog2.conf
input {
  file {
    path => [ "/scratch/rsyslog/*/messages.log" ]
    type => "syslog"
  }
}

filter {
  if [type] == "syslog" {
    grok {
      match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:hostname} %{DATA:program}(?:\[%{POSINT:pid}\])?: %{GREEDYDATA:syslog_message}" }
    }
    date {
      match => [ "syslog_timestamp", "MMM  d HH:mm:ss", "MMM dd HH:mm:ss" ]
    }
    mutate {
      remove_field => [
        "message",
        "pid",
        "port"
        "_grokparsefailure"
      ]
    }
    mutate {
      replace => [
        "@source_host", "%{allLogs_hostname}"
        "@message", "%{allLogs_message}"
      ]
    }
    mutate {
      remove => [
        "allLogs_hostname",
        "syslog_message",
        "syslog_timestamp"
      ]
    }
}
output {
  if [type] == "syslog" {
    elasticsearch {
      hosts => "localhost:9200"
      index => "%{type}-%{+YYYY.MM.dd}"
    }
  }
}

please suggest what i'm doing wrong and  help to understand the remove & replace functions for the lagstash..

PS: my ELK version is 5.4

Body:
The Config you posted have lot of syntactical errors , the logsatsh has it's own config language and expects the config file to abide by the rule.
This link has complete logstash config language reference.

I made some corrections to your config file and posted here , Have added my comments and explanation of what was wrong in the config file itself

input
{
    file
    {
        path => [ "/scratch/rsyslog/*/messages.log" ]
        type => "syslog"
    }
}

filter
{
    if [type] == "syslog"
    {
        grok
        {
            match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:hostname} %{DATA:program}(?:\[%{POSINT:pid}\])?: %{GREEDYDATA:syslog_message}" }
        }

    date
    {
        match => [ "syslog_timestamp", "MMM  d HH:mm:ss", "MMM dd HH:mm:ss" ]
    }

    # Have merged it with the remove_field option below
    #mutate {
    #  remove_field => [
    #    "message",
    #    "pid",
    #    "port",
    #    "_grokparsefailure"
    #  ]
    #}

    mutate
    {

        # The replace option only accept hash data type which has a syntax as below
        # For more details visit the below link
        # https://www.elastic.co/guide/en/logstash/current/plugins-filters-mutate.html#plugins-filters-mutate-replace
        replace => {
            "@source_host" => "%{allLogs_hostname}"
            "@message" => "%{allLogs_message}"
        }
    }

    mutate
    {
        # Mutate does not have remove option i guess your intention is to remove the event field
        # hence used remove_field option here
        # The remove_filed option only accepts arary as value type as shown below
        # For details read the below link
        # https://www.elastic.co/guide/en/logstash/current/plugins-filters-mutate.html#plugins-filters-mutate-remove_field
        remove_field => [
            "message",
            "pid",
            "port",
            "_grokparsefailure",
            "allLogs_hostname",
            "syslog_message",
            "syslog_timestamp"
        ]
    }
  }
}

output
{
    if [type] == "syslog"
    {
        elasticsearch
        {
            # The Hosts option only takes uri as a value type , originally you have provided string as it's value type
            # For more info please read the below link
            #https://www.elastic.co/guide/en/logstash/current/plugins-outputs-elasticsearch.html#plugins-outputs-elasticsearch-hosts
            hosts => ["localhost:9200"]
            index => "%{type}-%{+YYYY.MM.dd}"
        }
    }
}

You can test whether the config file is syntactically correct by  using logstash command line option -t this option will test and report the config file is syntactically correct

bin\logstash -f 'path-to-your-config-file' -t

Please let me know for any clarification


问:
Could not start the Nginx engine: nginx: [alert] Unable to start the Phusion Passenger watchdog
I installed passenger standalone on my centos 6 vps and I want to run it behing apache reverse proxy. I have checked the other posted problem and found their solution is not for the standalone...and it concerns ruby on rails which I don't know at all.

The problem is when I start the passenger  sudo passenger start     application I am getting this error :

Could not start the Nginx engine: nginx: [alert] Unable to start the
  Phusion Passenger watchdog because it encountered the following error
  during startup: Unable to start the Passenger core: it seems to have
  crashed during startup for an unknown reason, with exit code 1 (-1:
  Unknown error)

The error is speaking of Nginx but I didn't install any..and in passenger standalone installation there is no where it is recommanded for it to work.

I went to check my log file and found things I don't understand :

```<code>[ N 2017-12-02 06:19:54.7231 24223/T1 age/Wat/WatchdogMain.cpp:1267 ]: Starting Passenger watchdog... [ E 2017-12-02 06:19:54.7880 24226/T1 age/Sha/Fun/Initialization.cpp:569 ]: *** ERROR: Cannot open /var/www/mainfolder/myapp/passenger.3000.log for writing: Permission denied (errno=13)
     in 'Passenger::VariantMap Passenger::Agent::Fundamentals::initializeAgent(int, char***, const char*, void (*)(int, const char**, Passenger::VariantMap&), void (*)(Passenger::VariantMap&), int)' (Initialization.cpp:538)

[ W 2017-12-02 06:19:55.7969 24223/T1 age/Wat/WatchdogMain.cpp:353 ]: Cannot open cleanup PID file /tmp/passenger-standalone.10mxrug/temp_dir_toucher.pid 2017/12/02 06:19:54 [alert] 24220#0: Unable to start the Phusion Passenger watchdog because it encountered the following error during startup: Unable to start the Passenger core: it seems to have crashed during startup for an unknown reason, with exit code 1 (-1: Unknown error) [ N 2017-12-02 06:21:21.6338 24269/T1 age/Wat/WatchdogMain.cpp:1267 ]: Starting Passenger watchdog... [ E 2017-12-02 06:21:21.6456 24272/T1 age/Sha/Fun/Initialization.cpp:569 ]: *** ERROR: Cannot open /var/www/mainfolder/myapp/passenger.3000.log for writing: Permission denied (errno=13)
     in 'Passenger::VariantMap Passenger::Agent::Fundamentals::initializeAgent(int, char***, const char*, void (*)(int, const char**, Passenger::VariantMap&), void (*)(Passenger::VariantMap&), int)' (Initialization.cpp:538)

[ W 2017-12-02 06:21:22.6516 24269/T1 age/Wat/WatchdogMain.cpp:353 ]: Cannot open cleanup PID file /tmp/passenger-standalone.1pdjhr4/temp_dir_toucher.pid 2017/12/02 06:21:21 [alert] 24266#0: Unable to start the Phusion Passenger watchdog because it encountered the following error during startup: Unable to start the Passenger core: it seems to have crashed during startup for an unknown reason, with exit code 1 (-1: Unknown error) [ N 2017-12-02 07:01:35.1783 25608/T1 age/Wat/WatchdogMain.cpp:1267 ]: Starting Passenger watchdog... [ E 2017-12-02 07:01:35.1919 25611/T1 age/Sha/Fun/Initialization.cpp:569 ]: *** ERROR: Cannot open /var/www/mainfolder/myapp/passenger.3000.log for writing: Permission denied (errno=13)
     in 'Passenger::VariantMap Passenger::Agent::Fundamentals::initializeAgent(int, char***, const char*, void (*)(int, const char**, Passenger::VariantMap&), void (*)(Passenger::VariantMap&), int)' (Initialization.cpp:538)

[ W 2017-12-02 07:01:36.1992 25608/T1 age/Wat/WatchdogMain.cpp:353 ]: Cannot open cleanup PID file /tmp/passenger-standalone.2zbgfm/temp_dir_toucher.pid 2017/12/02 07:01:34 [alert] 25605#0: Unable to start the Phusion Passenger watchdog because it encountered the following error during startup: Unable to start the Passenger core: it seems to have crashed during startup for an unknown reason, with exit code 1 (-1: Unknown error)
</code>```

Inside myapp directory I have the Passengerfile.json with the following configuration:

```<code>{
  // Tell Passenger that this is a Node.js app.
  // Replace "app.js" with your app's entry point file.
  "app_type": "node",
  "startup_file": "app.js",
  // Run the app in a production environment. The default value is "development".
  "environment": "production",
  // Run Passenger on the given port. In this example, we use port 80,
  // the standard HTTP port.
  "port": 3000,
  // Tell Passenger to daemonize into the background.
  "daemonize": true,
  // Tell Passenger to run the app as the given user. Only has effect
  // if Passenger was started with root privileges.
  "user": "mynodeappauser"
  }
</code>```

I need to understand what is blocking the app from running.

答:
In the text of the error: Cannot open /var/www/mainfolder/myapp/passenger.3000.log for writing: Permission denied

Make sure your mynodeappauser user has permission to create and write to this file.

Body:
I installed passenger standalone on my centos 6 vps and I want to run it behing apache reverse proxy. I have checked the other posted problem and found their solution is not for the standalone...and it concerns ruby on rails which I don't know at all.

The problem is when I start the passenger  sudo passenger start     application I am getting this error :

Could not start the Nginx engine: nginx: [alert] Unable to start the
  Phusion Passenger watchdog because it encountered the following error
  during startup: Unable to start the Passenger core: it seems to have
  crashed during startup for an unknown reason, with exit code 1 (-1:
  Unknown error)

The error is speaking of Nginx but I didn't install any..and in passenger standalone installation there is no where it is recommanded for it to work.

I went to check my log file and found things I don't understand :

[ N 2017-12-02 06:19:54.7231 24223/T1 age/Wat/WatchdogMain.cpp:1267 ]: Starting Passenger watchdog... [ E 2017-12-02 06:19:54.7880 24226/T1 age/Sha/Fun/Initialization.cpp:569 ]: *** ERROR: Cannot open /var/www/mainfolder/myapp/passenger.3000.log for writing: Permission denied (errno=13)
     in 'Passenger::VariantMap Passenger::Agent::Fundamentals::initializeAgent(int, char***, const char*, void (*)(int, const char**, Passenger::VariantMap&), void (*)(Passenger::VariantMap&), int)' (Initialization.cpp:538)

[ W 2017-12-02 06:19:55.7969 24223/T1 age/Wat/WatchdogMain.cpp:353 ]: Cannot open cleanup PID file /tmp/passenger-standalone.10mxrug/temp_dir_toucher.pid 2017/12/02 06:19:54 [alert] 24220#0: Unable to start the Phusion Passenger watchdog because it encountered the following error during startup: Unable to start the Passenger core: it seems to have crashed during startup for an unknown reason, with exit code 1 (-1: Unknown error) [ N 2017-12-02 06:21:21.6338 24269/T1 age/Wat/WatchdogMain.cpp:1267 ]: Starting Passenger watchdog... [ E 2017-12-02 06:21:21.6456 24272/T1 age/Sha/Fun/Initialization.cpp:569 ]: *** ERROR: Cannot open /var/www/mainfolder/myapp/passenger.3000.log for writing: Permission denied (errno=13)
     in 'Passenger::VariantMap Passenger::Agent::Fundamentals::initializeAgent(int, char***, const char*, void (*)(int, const char**, Passenger::VariantMap&), void (*)(Passenger::VariantMap&), int)' (Initialization.cpp:538)

[ W 2017-12-02 06:21:22.6516 24269/T1 age/Wat/WatchdogMain.cpp:353 ]: Cannot open cleanup PID file /tmp/passenger-standalone.1pdjhr4/temp_dir_toucher.pid 2017/12/02 06:21:21 [alert] 24266#0: Unable to start the Phusion Passenger watchdog because it encountered the following error during startup: Unable to start the Passenger core: it seems to have crashed during startup for an unknown reason, with exit code 1 (-1: Unknown error) [ N 2017-12-02 07:01:35.1783 25608/T1 age/Wat/WatchdogMain.cpp:1267 ]: Starting Passenger watchdog... [ E 2017-12-02 07:01:35.1919 25611/T1 age/Sha/Fun/Initialization.cpp:569 ]: *** ERROR: Cannot open /var/www/mainfolder/myapp/passenger.3000.log for writing: Permission denied (errno=13)
     in 'Passenger::VariantMap Passenger::Agent::Fundamentals::initializeAgent(int, char***, const char*, void (*)(int, const char**, Passenger::VariantMap&), void (*)(Passenger::VariantMap&), int)' (Initialization.cpp:538)

[ W 2017-12-02 07:01:36.1992 25608/T1 age/Wat/WatchdogMain.cpp:353 ]: Cannot open cleanup PID file /tmp/passenger-standalone.2zbgfm/temp_dir_toucher.pid 2017/12/02 07:01:34 [alert] 25605#0: Unable to start the Phusion Passenger watchdog because it encountered the following error during startup: Unable to start the Passenger core: it seems to have crashed during startup for an unknown reason, with exit code 1 (-1: Unknown error)

Inside myapp directory I have the Passengerfile.json with the following configuration:

{
  // Tell Passenger that this is a Node.js app.
  // Replace "app.js" with your app's entry point file.
  "app_type": "node",
  "startup_file": "app.js",
  // Run the app in a production environment. The default value is "development".
  "environment": "production",
  // Run Passenger on the given port. In this example, we use port 80,
  // the standard HTTP port.
  "port": 3000,
  // Tell Passenger to daemonize into the background.
  "daemonize": true,
  // Tell Passenger to run the app as the given user. Only has effect
  // if Passenger was started with root privileges.
  "user": "mynodeappauser"
  }

I need to understand what is blocking the app from running.


问:
Printing 2-d Array

I want to print the row major using function

the code is given below

```<code>void rowmajor(int array,int row, int column)
{
    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < column; ++j)
        {
            printf("A(%d,%d) =\n", i+1,j+1);
            printf("%d\n", array[i][j]);
        }
    }
}
</code>```

In the main function, the code for printing 2-d array is properly working but it's not working this code.

The error generated is as given

```<code>clang -ggdb3 -O0 -std=c11 -Wall -Werror    matrix.c  -lcs50 -lm -o matrix
matrix.c:16:25: error: subscripted value is not an array, pointer, or vector
</code>```

答:
You have passed the parameter the wrong way.

```<code>void rowmajor(int row, int column, int array[][column])
{
    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < column; ++j)
        {
            printf("A(%d,%d) =\n", i+1,j+1);
            printf("%d\n", &array[i][j]);
        }
    }
}
</code>```

When you pass an array it decays into int (*)[column]  but you considered it to be of type int which it is not that's why compiler complained.

Remember when you pass an array, you need to specify the column part otherwise you will run into errors.

Also you are passing wrong parameter to printf. In case of printing it will be

```<code>   printf("%d",array[i][j]);
</code>```

&array[i][j] means the address where of the element arr[i][j].

And also there is  one thing a beginner face - keep in mind an array (int[row][column]) when passed to function is not int**

Interesting Note:
 You can pass the array to the function as void rowmajor(int row, int column, int array[][column]), void rowmajor(int row, int column, int array[row][column]) is better in case of type safety.
As mentioned by Lundin, suppose you declare an 2d array int array[2][3] then in case you call it like this rowmajor(3,3,array) then in first case it wouldn't generate any warning but in second case it would.

Title: Printing 2-d Array

Body:
I want to print the row major using function

the code is given below

void rowmajor(int array,int row, int column)
{
    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < column; ++j)
        {
            printf("A(%d,%d) =\n", i+1,j+1);
            printf("%d\n", array[i][j]);
        }
    }
}

In the main function, the code for printing 2-d array is properly working but it's not working this code.

The error generated is as given

clang -ggdb3 -O0 -std=c11 -Wall -Werror    matrix.c  -lcs50 -lm -o matrix
matrix.c:16:25: error: subscripted value is not an array, pointer, or vector

Body:
You have passed the parameter the wrong way.

void rowmajor(int row, int column, int array[][column])
{
    for (int i = 0; i < row; ++i)
    {
        for (int j = 0; j < column; ++j)
        {
            printf("A(%d,%d) =\n", i+1,j+1);
            printf("%d\n", &array[i][j]);
        }
    }
}

When you pass an array it decays into int (*)[column]  but you considered it to be of type int which it is not that's why compiler complained.

Remember when you pass an array, you need to specify the column part otherwise you will run into errors.

Also you are passing wrong parameter to printf. In case of printing it will be

   printf("%d",array[i][j]);

&array[i][j] means the address where of the element arr[i][j].

And also there is  one thing a beginner face - keep in mind an array (int[row][column]) when passed to function is not int**

Interesting Note:
 You can pass the array to the function as void rowmajor(int row, int column, int array[][column]), void rowmajor(int row, int column, int array[row][column]) is better in case of type safety.
As mentioned by Lundin, suppose you declare an 2d array int array[2][3] then in case you call it like this rowmajor(3,3,array) then in first case it wouldn't generate any warning but in second case it would.


问:
What does 'c' mean in Bash commands like args and grep?
```<code>echo "^[$*]*[$5][$*]*$" |xargs -I c grep -i c words| grep -i ".....*"| grep -
iv "...........*"| sort -f >list
</code>```

Can anyone tell me what the c means after xarg and grep?

important note: words is a document containing words

答:
From the manual page for xargs:

-I replace-str

Replace occurrences of replace-str in the initial-arguments with  names  read  from  standard input.  Also, unquoted blanks do not terminate input items; instead  the  separator  is  the  newline character. Implies -x and -L1.

So xargs -I c grep -i c words will replace c (the argument of -I) with what's read from standard input, in this case ^[<positional_args_here>]*[<5th_positional_arg_here>][<positional_args_here>]*$. (The shell will replace $* and $5 in the quoted string with the positional arguments and the 5th positional argument respectively.)

Body:
echo "^[$*]*[$5][$*]*$" |xargs -I c grep -i c words| grep -i ".....*"| grep -
iv "...........*"| sort -f >list

Can anyone tell me what the c means after xarg and grep?

important note: words is a document containing words


问:
jQuery Newbie, need a little help
Okay, so I am in the process of recreating this feature:

http://www.w3.org/html/logo/#the-technology

I current have it so when you click on a link, it will add a class to the image that relates to that link (href="#one" on the  and then id="#one" on the ), however it is currently not going through each  tag and only one. And also it is not removing the class I requested.

Code follows:

JS

```<code>$(document).ready(function() {

var container = '#portfolio #text_container';

var img_container = '#portfolio #image_container';

$(container).children('a').bind('click', function() {

var this_attr = $(this).attr('href');

var this_img = $(img_container).find('img').attr('id');

if(this_attr == this_img) {

    //$(img_container).find('img').hasClass('current').removeClass('current');

        // ^^^ This line isn't working, any ideas? :/

    $(img_container + ' img[id*="' + this_attr + '"]').addClass('current');

}

else {

    alert(this_img + ' this img');

        alert(this_attr + ' this attr');

}

  });

});
</code>```

And the HTML is as follows

```<code><div id="portfolio">

    <div id="image_container">
        <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="current" id="#one" />
        <img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" id="#two" />
    </div>

    <div id="text_container">
        <a href="#one" class="link">Item 1</a>
        <a href="#two" class="link">Item 2</a>

        <p id="#one" class="current">A bunch of text!</p>
        <p id="#two">The second bunch of text!</p>
    </div>

</div>
</code>```

Please let me know if you need any more information :)

rcravens fixed this with the following code..

JS

```<code>$(document).ready(function() {

    $('#text_container a').click(function(evt) {
        evt.preventDefault();

        $('.current').removeClass('current');

        var href = $(this).attr('href');

        $("." + href).addClass('current');

    });
</code>```

And the HTML..

```<code><div id="portfolio">

    <div id="image_container">
        <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="one current" />
        <img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" class="two" />
    </div>

    <div id="text_container">
        <a href="one" class="link">Item 1</a>
        <a href="two" class="link">Item 2</a>

        <p class="one current">A bunch of text!</p>
        <p class="two">The second bunch of text!</p>
    </div>

</div>
</code>```

答:
My interpretation of what you are trying to do is here:

http://jsfiddle.net/rcravens/wMhEC/

The code is changed a bit. You shouldn't have multiple elements with the same id.

Bob

ContentLicense: CC BY-SA 2.5

Title: jQuery Newbie, need a little help

Body:
Okay, so I am in the process of recreating this feature:

http://www.w3.org/html/logo/#the-technology

I current have it so when you click on a link, it will add a class to the image that relates to that link (href="#one" on the  and then id="#one" on the ), however it is currently not going through each  tag and only one. And also it is not removing the class I requested.

Code follows:

JS

$(document).ready(function() {

var container = '#portfolio #text_container';

var img_container = '#portfolio #image_container';

$(container).children('a').bind('click', function() {

var this_attr = $(this).attr('href');

var this_img = $(img_container).find('img').attr('id');

if(this_attr == this_img) {

    //$(img_container).find('img').hasClass('current').removeClass('current');

        // ^^^ This line isn't working, any ideas? :/

    $(img_container + ' img[id*="' + this_attr + '"]').addClass('current');

}

else {

    alert(this_img + ' this img');

        alert(this_attr + ' this attr');

}

  });

});

And the HTML is as follows

        Item 1
        Item 2

A bunch of text!

The second bunch of text!

Please let me know if you need any more information :)

rcravens fixed this with the following code..

JS

$(document).ready(function() {

    $('#text_container a').click(function(evt) {
        evt.preventDefault();

        $('.current').removeClass('current');

        var href = $(this).attr('href');

        $("." + href).addClass('current');

    });

And the HTML..

        Item 1
        Item 2

A bunch of text!

The second bunch of text!


问:
Distribute number of CPU cores per instance in a VM
I'm running two separate instances of SQL Server 2012 in a VM that has 8 cores. How do I tell each instance to use only 2 cores (or any number) to be compliant with the per core licensing model?

Is the Affinity Mask setting used for this purpose?

I'm guessing this is not possible and that I would have to license the entire 8 cores whether or not they're used but need a confirmation.

Thanks,
Ali

答:
I found out the answer and thought someone else might benefit from it.

Affinity mask has nothing to do with licensing. The number of cores assigned to a VM must be licensed for a production load no matter what.

Thanks,
Ali


问:
If required field is empty, don't open popup
I have a contact form that when you press the send button, opens a popup asking for confirmation of reading the privacy policy.

For now, the form doesn't send anything if there are empty required field, but it opens the popup.

I need to prevent the popup to open if there are still required field to complete.

Here's the code:

$('#myCheck').click(function() {
     $(this).toggleClass("checked");
});

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

$('.checkz').click(function () {
    $('#invias').toggleDisabled();
    $('#invias').toggleClass("activ3");
    });

    $(".pex").click(function (e) {
    e.stopPropagation();
});

function checkInputs() {
  var isValid = true;
  $('input').filter('[required]').each(function() {
    if ($(this).val() === '') {
      $('#confirm').prop('disabled', true)
      isValid = false;
      return false;
    }
  });
  if(isValid) {$('#confirm').prop('disabled', false)}
  return isValid;
}

//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})

checkInputs()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.checkz {width:20px;
height:20px;
background: transparent;
background-size: contain;
border:1px solid #CCC;
border-radius:5px;
display:inline-block;
    margin-bottom: 5px;
    margin-right: 10px;}

#invias {opacity:0.5}

.activ3 {opacity:1 !important}

#popup {
    background-color: rgba( 231, 135, 74, 0.85 );
    position: fixed;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1999999999;
    overflow: initial;
    transition: all .15s ease-in-out;
}

.pex {width:500px;padding:30px;background:#FFF;z-index:1999999999;margin: 10% auto 0;text-align: center;}

.cst {display: inline-block;
    text-align: left;}

.checked {background-image: url(https://image.flaticon.com/icons/png/512/3/3596.png)}

button:disabled {opacity:0.5 !important}</code>```

<form method="post" name="contactform" class="peThemeContactForm">

            <input type="text" name="author" class="form-control input-lg" placeholder="Name*" required />

            <input type="email" name="email" class="form-control input-lg" placeholder="Email*" required />

            <input type="text" name="phone" class="form-control input-lg" placeholder="Phone">

            <textarea name="message" class="form-control input-lg" placeholder="Message*" required ></textarea>

    Send message

Dichiaro di aver letto, compreso ed accettato

l'informativa sul trattamento dei miei dati personali

Close <button type="submit" class="btn btn-custom" id="invias" onclick="popupban()" disabled>Accept</button>

```

You could use the following fiddle to test: http://jsfiddle.net/2BgdD/12/

Thanks a lot.

答:
If you set isValid as a global variable, you can use it to do a check before firing your popupshow method:

```<code>function popupshow() {
  if (!isValid) return;
  document.getElementById("popup").style = "";
}
</code>```

You would need to adjust your checkInputs method as well though:

```<code>function checkInputs() {
  $('input').filter('[required]').each(function() {
    if ($(this).val() === '') {
      $('#confirm').prop('disabled', true)
      isValid = false;
    } else {
      isValid = true;
    }
  });
  if(isValid) {$('#confirm').prop('disabled', false)}
  return isValid;
}
</code>```

Updated Demo

Body:
I have a contact form that when you press the send button, opens a popup asking for confirmation of reading the privacy policy.

For now, the form doesn't send anything if there are empty required field, but it opens the popup.

I need to prevent the popup to open if there are still required field to complete.

Here's the code:

$('#myCheck').click(function() {
     $(this).toggleClass("checked");
});

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

$('.checkz').click(function () {
    $('#invias').toggleDisabled();
    $('#invias').toggleClass("activ3");
    });

    $(".pex").click(function (e) {
    e.stopPropagation();
});

function checkInputs() {
  var isValid = true;
  $('input').filter('[required]').each(function() {
    if ($(this).val() === '') {
      $('#confirm').prop('disabled', true)
      isValid = false;
      return false;
    }
  });
  if(isValid) {$('#confirm').prop('disabled', false)}
  return isValid;
}

//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})

checkInputs()

.checkz {width:20px;
height:20px;
background: transparent;
background-size: contain;
border:1px solid #CCC;
border-radius:5px;
display:inline-block;
    margin-bottom: 5px;
    margin-right: 10px;}

#invias {opacity:0.5}

.activ3 {opacity:1 !important}

#popup {
    background-color: rgba( 231, 135, 74, 0.85 );
    position: fixed;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1999999999;
    overflow: initial;
    transition: all .15s ease-in-out;
}

.pex {width:500px;padding:30px;background:#FFF;z-index:1999999999;margin: 10% auto 0;text-align: center;}

.cst {display: inline-block;
    text-align: left;}

.checked {background-image: url(https://image.flaticon.com/icons/png/512/3/3596.png)}

button:disabled {opacity:0.5 !important}

<form method="post" name="contactform" class="peThemeContactForm">

            <input type="text" name="author" class="form-control input-lg" placeholder="Name*" required />

            <input type="email" name="email" class="form-control input-lg" placeholder="Email*" required />

            <input type="text" name="phone" class="form-control input-lg" placeholder="Phone">

            <textarea name="message" class="form-control input-lg" placeholder="Message*" required ></textarea>

    Send message

Dichiaro di aver letto, compreso ed accettato

l'informativa sul trattamento dei miei dati personali

Close <button type="submit" class="btn btn-custom" id="invias" onclick="popupban()" disabled>Accept</button>

You could use the following fiddle to test: http://jsfiddle.net/2BgdD/12/

Thanks a lot.

Body:
If you set isValid as a global variable, you can use it to do a check before firing your popupshow method:

function popupshow() {
  if (!isValid) return;
  document.getElementById("popup").style = "";
}

You would need to adjust your checkInputs method as well though:

function checkInputs() {
  $('input').filter('[required]').each(function() {
    if ($(this).val() === '') {
      $('#confirm').prop('disabled', true)
      isValid = false;
    } else {
      isValid = true;
    }
  });
  if(isValid) {$('#confirm').prop('disabled', false)}
  return isValid;
}

Updated Demo


问:
How to fix broken transform-origin on iOS11 and macOS10.12 Safari?
I'm trying to implement CSS animation by using svg.

I am expecting that 2 svg boxes is rotating (spinning) with transform-origin: center center; 360 degrees. Looks like it behave what I expected with Chrome and Firefox but not with macOS 10.12 (High Sierra) and iOS 11.0.x and 11.1 beta Safari.

Seems like transform-origin: center center; does not work in Safari?

Is there any way to fix this issue?

What I expect:

What I see on Safari:

Here is a sample code

HTML:

```<code>svg(width=500, height=500, viewBox='0 0 500 500')
  rect(x=100, y=100, width=50, height=100)
  rect(x=400, y=100, width=50, height=100)
</code>```

CSS:

```<code>@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

rect {
  transform-origin: center center;
  animation-duration: 3s;
  animation-name: rotate;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

  &:nth-child(1) {
    fill: red;
  }

  &:nth-child(2) {
    fill: blue;
  }
}
</code>```

You can see the behavior here by accessing with Chrome and Safari:
https://codepen.io/manaten/pen/aLeXjW

EDIT:

https://codepen.io/manaten/pen/aVzeEK
Another example of the issue. Looks like origin is set to be the center of svg element by Safari.

答:
try transform-box:fill-box;
this defines the layout box, to which the transform and transform-origin properties relate to</p>

Body:
I'm trying to implement CSS animation by using svg.

I am expecting that 2 svg boxes is rotating (spinning) with transform-origin: center center; 360 degrees. Looks like it behave what I expected with Chrome and Firefox but not with macOS 10.12 (High Sierra) and iOS 11.0.x and 11.1 beta Safari.

Seems like transform-origin: center center; does not work in Safari?

Is there any way to fix this issue?

What I expect:

What I see on Safari:

Here is a sample code

HTML:

svg(width=500, height=500, viewBox='0 0 500 500')
  rect(x=100, y=100, width=50, height=100)
  rect(x=400, y=100, width=50, height=100)

CSS:

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

rect {
  transform-origin: center center;
  animation-duration: 3s;
  animation-name: rotate;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

  &:nth-child(1) {
    fill: red;
  }

  &:nth-child(2) {
    fill: blue;
  }
}

You can see the behavior here by accessing with Chrome and Safari:
https://codepen.io/manaten/pen/aLeXjW

EDIT:

https://codepen.io/manaten/pen/aVzeEK
Another example of the issue. Looks like origin is set to be the center of svg element by Safari.


问:
Strip leading dot from filenames bash script
I have some files in a bunch of directories that have a leading dot and thus are hidden. I would like to revert that and strip the leading dot.

I was unsuccessful with the following:

```<code>for file in `find files/ -type f`;
do
base=`basename $file`
if [ `$base | cut -c1-2` = "." ];
then newname=`$base | cut -c2-`;
dirs=`dirname $file`;
echo $dirs/$newname;
fi
done
</code>```

Which fails on the condition statement:

```<code>[: =: unary operator expected
</code>```

Furthermore, some files have a space in them and file returns them split.

Any help would be appreciated.

答:
This script works with any file you
can throw at it, even if they have
spaces, newlines or other nefarious
characters in their name.

It works no matter how many subdirectories deep the hidden file is

Unlike other answers thus far, you
don't have to change the rest of the script when you change the path
given to find

*Note: I included an echo so that you can test it like a dry-run.  Remove the single echo if you are satisfied with the results.

```<code>find . -name '.*' -exec sh -c 'for arg; do d="${arg%/*}"; f=${arg:${#d}}; echo mv "$arg" "$d/${f#.}"; done' _ {} +
</code>```

Body:
I have some files in a bunch of directories that have a leading dot and thus are hidden. I would like to revert that and strip the leading dot.

I was unsuccessful with the following:

for file in `find files/ -type f`;
do
base=`basename $file`
if [ `$base | cut -c1-2` = "." ];
then newname=`$base | cut -c2-`;
dirs=`dirname $file`;
echo $dirs/$newname;
fi
done

Which fails on the condition statement:

[: =: unary operator expected

Furthermore, some files have a space in them and file returns them split.

Any help would be appreciated.

Body:
This script works with any file you
can throw at it, even if they have
spaces, newlines or other nefarious
characters in their name.

It works no matter how many subdirectories deep the hidden file is

Unlike other answers thus far, you
don't have to change the rest of the script when you change the path
given to find

*Note: I included an echo so that you can test it like a dry-run.  Remove the single echo if you are satisfied with the results.

find . -name '.*' -exec sh -c 'for arg; do d="${arg%/*}"; f=${arg:${#d}}; echo mv "$arg" "$d/${f#.}"; done' _ {} +


问:
Blank page with vue-router with history mode and production
I'm new with vue and I've the next error. I build a little project with the next template https://github.com/vuejs-templates/webpack with default configuration.

I've added vue-router and it works fine when I'm in develop mode, but when I build production mode and use, it show a blank page.

If I remove history mode of configuration, it works. Any suggestion?

Thanks.

答: Does production mode involve a change of web-server or machine? It sounds like the production environment may not have the fallback route configured on the server.</p>