问:
why is my express API not responding?

Background

I am testing a simple Hello World app using NodeJs v7 and express in cloud9.
I am trying to make my example work but I am failing.

Problem

All my cloud9 configurations are fine so that is not the problem. The problem is my app. When i debug, the route "api/v1/HolaBananas" never gets called and I don't know why!

Even worst, when i make the request, the browser just hangs, like it is waiting for an answer from the server that will never come!

Code

The index.js has the initialization and launch code. It is important for me that I keep this separate from api.js for modular reasons.

index.js

```<code>"use strict";

const express = require("express");

const app = express();
app.use("/api/v1", require("./api.js"));

app.listen(process.env.PORT);
console.log(`Server listening on port ${process.env.PORT}!`);
</code>```

The api.js simply contains the routes and what they are supposed to do.

api.js

```<code>"use strict";

const express = require("express");

module.exports = function() {

    const api = express.Router();

    api.get("/HolaBananas", function(req, res){
        res.send("hello bananas!");
    });

    return api;
};
</code>```

Question

I am sure I am not using api.get in the right way, but I truly want to separate my initialization and launch code from the api.

How can I fix my code so it works?

Note

I am following the course

https://www.edx.org/course/introduction-mongodb-using-mean-stack-mongodbx-m101x-0

答:
Solution

While Vikash Sharma's solution would work, I figured it out by following the recommendation of  Jayant Patil and to read this other question:

https://codereview.stackexchange.com/questions/51614/exporting-routes-in-node-js-express-4

Turns out we had the same issue, but the given answer to that question also allows me to encapsulate the api file completely inside a function, preserving its scope.

Still, kudos++ for trying!

Title: why is my express API not responding?

Body:
Background

I am testing a simple Hello World app using NodeJs v7 and express in cloud9.
I am trying to make my example work but I am failing.

Problem

All my cloud9 configurations are fine so that is not the problem. The problem is my app. When i debug, the route "api/v1/HolaBananas" never gets called and I don't know why!

Even worst, when i make the request, the browser just hangs, like it is waiting for an answer from the server that will never come!

Code

The index.js has the initialization and launch code. It is important for me that I keep this separate from api.js for modular reasons.

index.js

"use strict";

const express = require("express");

const app = express();
app.use("/api/v1", require("./api.js"));

app.listen(process.env.PORT);
console.log(`Server listening on port ${process.env.PORT}!`);

The api.js simply contains the routes and what they are supposed to do.

api.js

"use strict";

const express = require("express");

module.exports = function() {

    const api = express.Router();

    api.get("/HolaBananas", function(req, res){
        res.send("hello bananas!");
    });

    return api;
};

Question

I am sure I am not using api.get in the right way, but I truly want to separate my initialization and launch code from the api.

How can I fix my code so it works?

Note

I am following the course

https://www.edx.org/course/introduction-mongodb-using-mean-stack-mongodbx-m101x-0


来源: stackexchange

问:
How to access exported service protected with permission in Android
I created one remote service as follows:-

```<code><service android:name=".XYZService"
            android:permission="com.xyz.service"
            android:exported="true">
            <intent-filter>
                <action android:name="com.abc.def.XYZService"/>
            </intent-filter>
        </service>
</code>```

I am trying to bind with this service by using client application service as follows:-
    //client service onStartCommand code :

```<code> @Override
            public int onStartCommand(Intent intent, int flags, int startId) {

                boolean ret;
                try {
                          Intent i = new Intent("com.abc.def.XYZService");
                    ret = getApplicationContext().bindService(i, serviceConnection,
                            Context.BIND_AUTO_CREATE);
                    if (ret == false) {
                        //log error
                    }

                } catch (SecurityException e) {
                                  e.printStackTrace();
                }
        return super.onStartCommand(intent, flags, startId);
            }
</code>```

client application manifest has following permission:-

```<code> <uses-permission android:name="com.xyz.service" />
</code>```

Still, I am getting following exception:-
Security Exception: The client Service does not have permission to bind to the xyz service.

My intention here is to protect my exported service with some permission and use that permission in client application to access exported service.
Any help will be appreciated.

答:
Use this.

```<code><permission
        android:name="myPermission"
        android:description="@string/myPermissionDescription"
        android:label="@string/myPermissionLabel">
    </permission>
</code>```

more info:
page 1 --
page 2

ContentLicense: CC BY-SA 3.0

Body:
I created one remote service as follows:-

<service android:name=".XYZService"
            android:permission="com.xyz.service"
            android:exported="true">
            <intent-filter>
                <action android:name="com.abc.def.XYZService"/>
            </intent-filter>
        </service>

I am trying to bind with this service by using client application service as follows:-
    //client service onStartCommand code :

 @Override
            public int onStartCommand(Intent intent, int flags, int startId) {

                boolean ret;
                try {
                          Intent i = new Intent("com.abc.def.XYZService");
                    ret = getApplicationContext().bindService(i, serviceConnection,
                            Context.BIND_AUTO_CREATE);
                    if (ret == false) {
                        //log error
                    }

                } catch (SecurityException e) {
                                  e.printStackTrace();
                }
        return super.onStartCommand(intent, flags, startId);
            }

client application manifest has following permission:-

 <uses-permission android:name="com.xyz.service" />

Still, I am getting following exception:-
Security Exception: The client Service does not have permission to bind to the xyz service.

My intention here is to protect my exported service with some permission and use that permission in client application to access exported service.
Any help will be appreciated.

Body:
Use this.

<permission
        android:name="myPermission"
        android:description="@string/myPermissionDescription"
        android:label="@string/myPermissionLabel">
    </permission>

more info:
page 1 --
page 2


问:
Android Hello World stops working after first launch
I trying to get Google's Hello World app for Android working in Eclipse. The first time the AVD indeed displays "Hello World", but when I click it away and restart the application from Eclipse, nothing happens - however long I wait.

Killing adb.exe in the process list does not help.

I actually see a stacktrace when just launching the AVD itself. Unfortunately, launching an AVD apparently takes 3 command prompts which all disappear before you can read what is outut to them.

答:
I think the problem you are having, is that the application is just starting off from where it left off, because the application hasn't changed.

If you change the code, save it (, revert it back again if you want, save it), then try running the application from Eclipse again.

The reason for this is that Eclipse will only install the new APK to the emulator when the code has changed, to save time. If the new APK isn't installed, then typically the original application will just bring itself to the foreground.

If you don't want to change the code, an alternative is to access the DDMS (Window->Open Perspective->DDMS) and open your emulator instance on the left side, choose the name of your application (designated by package name) and click on the red stop button to kill the process. This way, your application should start up as normal, without reverting to its standby instance.

If you are having Logcat issues, for some people running this in the command line helps:

```<code>adb kill-server
adb devices
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I think the problem you are having, is that the application is just starting off from where it left off, because the application hasn't changed.

If you change the code, save it (, revert it back again if you want, save it), then try running the application from Eclipse again.

The reason for this is that Eclipse will only install the new APK to the emulator when the code has changed, to save time. If the new APK isn't installed, then typically the original application will just bring itself to the foreground.

If you don't want to change the code, an alternative is to access the DDMS (Window->Open Perspective->DDMS) and open your emulator instance on the left side, choose the name of your application (designated by package name) and click on the red stop button to kill the process. This way, your application should start up as normal, without reverting to its standby instance.

If you are having Logcat issues, for some people running this in the command line helps:

adb kill-server
adb devices


问:
aggregate function calls cannot be nested postgresql
I get "aggregate function calls cannot be nested" error from PostgreSQL. I tried different bunch of things but could not solve.

```<code>select c.*, (
             select sum((count(distinct product_id))/2)
             from page_views
             where product_id in (c.p1, c.p2)
             group by user_id, session_id
             having count(distinct product_id) > 1
            ) freq
from (
      select a.product_id p1, b.product_id p2
      from (select distinct product_id from page_views) a,
           (select distinct product_id from page_views ) b
      where a.product_id <> b.product_id
     ) c ;
</code>```

Thanks!

答:
If you want to count users who have seen two pages in a single senssion, then this is the query:

```<code>select v1.product_id, v2.product_id, count(distinct v2.user_id)
from page_views v1 join
     page_views v2
     on v1.user_id = v2.user_id and v1.session_id = v2.session_id and
        v1.product_id < v2.product_id
group by v1.product_id, v2.product_id;
</code>```

This is the most sensible interpretation I can imagine of the actual intent.

Body:
I get "aggregate function calls cannot be nested" error from PostgreSQL. I tried different bunch of things but could not solve.

select c.*, (
             select sum((count(distinct product_id))/2)
             from page_views
             where product_id in (c.p1, c.p2)
             group by user_id, session_id
             having count(distinct product_id) > 1
            ) freq
from (
      select a.product_id p1, b.product_id p2
      from (select distinct product_id from page_views) a,
           (select distinct product_id from page_views ) b
      where a.product_id <> b.product_id
     ) c ;

Thanks!

Body:
If you want to count users who have seen two pages in a single senssion, then this is the query:

select v1.product_id, v2.product_id, count(distinct v2.user_id)
from page_views v1 join
     page_views v2
     on v1.user_id = v2.user_id and v1.session_id = v2.session_id and
        v1.product_id < v2.product_id
group by v1.product_id, v2.product_id;

This is the most sensible interpretation I can imagine of the actual intent.


问:
How to prevent page refresh before a user has selected a button on a dialog box?
My web app is listening out for a page refresh.

I am attempting this by doing the following:

```<code>window.onbeforeunload = dialogBox;
</code>```

The idea is to display a dialog box in order to prevent the page from refreshing until the user has made a choice from selecting either of the two buttons which determines whether they continue with the refresh or cancel the refresh.

Unfortunately the page displays the dialog box for a brief second and then continues with the refresh. Is there anyway that I can use 'onbeforeunload' to prevent the page from continuing with a refresh and show my dialog box?

Is it impossible to achieve using 'onbeforeunload'?

The code for my dialog box:

```<code>function dialogBox()
{
    $("#dialog").html("");
    $("#dialog").append("There appears to be some unsaved changes");
    $( function() {
        $( "#dialog" ).dialog({
            modal: true,
            buttons: {
                Cancel: function() {
                    $(this).dialog( "close" );

                },

                "Save": function() {

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

Thank you all for your time.

Edit: I don't want to prevent a user from refreshing. Rather than display the generic pop-up box that appears when using onbeforeunload, I want to display a custom dialog box by calling a function which generates that. I am somewhat able to display that for a split second, and not permanently until someone has made a selection. That selection should then either continue with the refresh or half it entirely by selecting 'Cancel'.

If it helps, I am using Google Chrome as my web browser of choice.

答:
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

The page states that

Note: To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with. For a list of specific browsers, see the Browser compatibility section.

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.

From firefox v4.0 and Chrome v51.0 the browsers don't even support custom messages in default prompt, so thinking about a custom designed prompt is just an unachievable kind of feature for this Window.unbeforeunload event.

Direct quotation:-

Notes

When this event returns (or sets the returnValue property to) a value other than null or undefined, the user is prompted to confirm the page unload. In some browsers, the return value of the event is displayed in this dialog. Starting with Firefox 4, Chrome 51, Opera 38 and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved."

Syntax

```<code>window.onbeforeunload = funcRef
</code>```

funcRef is a reference to a function or a function expression.
  The function should assign a string value to the returnValue property of the Event object and return the same string.
  Example

```<code>window.onbeforeunload = function(e) {
  var dialogText = 'Dialog text here';
  e.returnValue = dialogText;
  return dialogText;
};
</code>```

Body:
My web app is listening out for a page refresh.

I am attempting this by doing the following:

window.onbeforeunload = dialogBox;

The idea is to display a dialog box in order to prevent the page from refreshing until the user has made a choice from selecting either of the two buttons which determines whether they continue with the refresh or cancel the refresh.

Unfortunately the page displays the dialog box for a brief second and then continues with the refresh. Is there anyway that I can use 'onbeforeunload' to prevent the page from continuing with a refresh and show my dialog box?

Is it impossible to achieve using 'onbeforeunload'?

The code for my dialog box:

function dialogBox()
{
    $("#dialog").html("");
    $("#dialog").append("There appears to be some unsaved changes");
    $( function() {
        $( "#dialog" ).dialog({
            modal: true,
            buttons: {
                Cancel: function() {
                    $(this).dialog( "close" );

                },

                "Save": function() {

                },
            },
        })
    });
}

Thank you all for your time.

Edit: I don't want to prevent a user from refreshing. Rather than display the generic pop-up box that appears when using onbeforeunload, I want to display a custom dialog box by calling a function which generates that. I am somewhat able to display that for a split second, and not permanently until someone has made a selection. That selection should then either continue with the refresh or half it entirely by selecting 'Cancel'.

If it helps, I am using Google Chrome as my web browser of choice.

Body:
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

The page states that

Note: To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with. For a list of specific browsers, see the Browser compatibility section.

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.

From firefox v4.0 and Chrome v51.0 the browsers don't even support custom messages in default prompt, so thinking about a custom designed prompt is just an unachievable kind of feature for this Window.unbeforeunload event.

Direct quotation:-

Notes

When this event returns (or sets the returnValue property to) a value other than null or undefined, the user is prompted to confirm the page unload. In some browsers, the return value of the event is displayed in this dialog. Starting with Firefox 4, Chrome 51, Opera 38 and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved."

Syntax

window.onbeforeunload = funcRef

funcRef is a reference to a function or a function expression.
  The function should assign a string value to the returnValue property of the Event object and return the same string.
  Example

window.onbeforeunload = function(e) {
  var dialogText = 'Dialog text here';
  e.returnValue = dialogText;
  return dialogText;
};


问:
how to parse simple json string array to object in java
I have a json array as a string in the following format:

```<code> [ "Ford", "BMW", "Fiat" ]
</code>```

which is a legal json string. How am I able to use Gson to save into an object?
When I am trying to use getAsJsonArray(), but I get an error:

```<code> java.lang.IllegalStateException: This is not a JSON Array.
</code>```

答:
Use Gson to parse your Json array.

```<code>String input = "[ 'Ford', 'BMW', 'Fiat' ]";

Gson gson = new Gson();
String[] output = gson.fromJson(input, String[].class);

for(String s : output){
    System.out.println(s);
}
</code>```

Output

```<code>Ford
BMW
Fiat
</code>```

Body:
I have a json array as a string in the following format:

 [ "Ford", "BMW", "Fiat" ]

which is a legal json string. How am I able to use Gson to save into an object?
When I am trying to use getAsJsonArray(), but I get an error:

 java.lang.IllegalStateException: This is not a JSON Array.

Body:
Use Gson to parse your Json array.

String input = "[ 'Ford', 'BMW', 'Fiat' ]";

Gson gson = new Gson();
String[] output = gson.fromJson(input, String[].class);

for(String s : output){
    System.out.println(s);
}

Output

Ford
BMW
Fiat


问:
External method from an AJAX callback in JavaScript & jQuery
I have a function in JS & jQuery that fires an AJAX call and it has a callback block to let me know when it's finished:

```<code>function ajaxCall(url, type, dataType, dataToSend, callback) {

    if (dataType == undefined) dataType = "json";
    if (dataToSend == undefined) dataToSend = null;

    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        contentType: "application/json",
        data: dataToSend,
        async: true,
        success: function (result) {
            callback(result);
        },
        error: function (data, status) {
            console.error("Server Error: " + status);
        }
    });
}
</code>```

I am accessing it like so, but using external functions like showAjaxLoader() just doesn't work! it says this function is undefined:

```<code>function registerUser(data) {

    ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {

        // SOME CODE THAT RUNS WHEN IT'S COMPLETE

        // External method:
        showAjaxLoader(false); // Doesn't work

    });
});

function showAjaxLoader(show) {
    var loader = $('.ajax-loader');
    if (show) {
        loader.fadeIn("fast");
    } else {
        loader.fadeOut("fast");
    }
}
</code>```

What am I doing wrong?

Thanks :)

答:
Worked out some sample. this may be good practice. Try this :</p>

```<code>    $(document).ready(function() {
        $("button").click(function() {registerUser();});
    });

    var Scallback = function(arg) {
        alert("Success :"+arg);
        showAjaxLoader(true);
    }
    var Ecallback = function(arg) {
        alert("Err :"+arg);
        showAjaxLoader(true);
    }

    function showAjaxLoader(show) {
        var loader = $('.ajax-loader');
        if (show) {
            loader.fadeIn("fast");
        } else {
            loader.fadeOut("fast");
        }
    }

    function ajaxCall(url, type, Scallback, Ecallback) {
        $.ajax({
            url : url,
            type : type,
            async : true,
            success : function(result) {
                Scallback(result);
            },
            error : function(data) {
                Ecallback(data)
            }
        });
    }

    function registerUser()
    {
        ajaxCall(pathServiceRegister, "GET", Scallback, Ecallback);
    }
</code>```

Body:
I have a function in JS & jQuery that fires an AJAX call and it has a callback block to let me know when it's finished:

function ajaxCall(url, type, dataType, dataToSend, callback) {

    if (dataType == undefined) dataType = "json";
    if (dataToSend == undefined) dataToSend = null;

    $.ajax({
        url: url,
        type: type,
        dataType: dataType,
        contentType: "application/json",
        data: dataToSend,
        async: true,
        success: function (result) {
            callback(result);
        },
        error: function (data, status) {
            console.error("Server Error: " + status);
        }
    });
}

I am accessing it like so, but using external functions like showAjaxLoader() just doesn't work! it says this function is undefined:

function registerUser(data) {

    ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) {

        // SOME CODE THAT RUNS WHEN IT'S COMPLETE

        // External method:
        showAjaxLoader(false); // Doesn't work

    });
});

function showAjaxLoader(show) {
    var loader = $('.ajax-loader');
    if (show) {
        loader.fadeIn("fast");
    } else {
        loader.fadeOut("fast");
    }
}

What am I doing wrong?

Thanks :)

Body:
Worked out some sample. this may be good practice. Try this :

    $(document).ready(function() {
        $("button").click(function() {registerUser();});
    });

    var Scallback = function(arg) {
        alert("Success :"+arg);
        showAjaxLoader(true);
    }
    var Ecallback = function(arg) {
        alert("Err :"+arg);
        showAjaxLoader(true);
    }

    function showAjaxLoader(show) {
        var loader = $('.ajax-loader');
        if (show) {
            loader.fadeIn("fast");
        } else {
            loader.fadeOut("fast");
        }
    }

    function ajaxCall(url, type, Scallback, Ecallback) {
        $.ajax({
            url : url,
            type : type,
            async : true,
            success : function(result) {
                Scallback(result);
            },
            error : function(data) {
                Ecallback(data)
            }
        });
    }

    function registerUser()
    {
        ajaxCall(pathServiceRegister, "GET", Scallback, Ecallback);
    }


问:
CSS rotate div 10deg full width
I have found the following Website.
Special the Section: Social News on the half of the side.

I wonder how to get the rotated divs (i think about 10 deg) over the full width.
Is there any possibility to do that responsive? So i can use the rotated div on a mobile phone?
I`m not as fit to rotate the div. How can i do this using css?

I`ve tried this:

```<code><div class="container"></div>
</code>```

Ans using following css:

```<code>.container {
   transform: rotate(10deg);
   width: 100%;
   height: 200px;
   background: red;
}
</code>```

But the Container is not full width.

答:
It work's without transforms. There are only CSS-Shapes. It's possible with transforms too. On A Collection of Separator Styles there are many other separator styles.

html, body {
  margin: 0;
  padding: 0;
}

.outer {
  position: relative;
}

.outer::before {
  position: absolute;
  top: 0px;

  border-top: solid 40px #ffffff;
  border-right: 100vw solid rgba(0,0,0,0);

  content: '';
}

.outer::after {
  bottom: 0px;
  position: absolute;

  border-bottom: solid 40px #ffffff;
  border-left: 100vw solid rgba(0,0,0,0);

  content: '';
}

.inner {
  height: 200px;
  padding: 60px 1em;

  background: #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div class="inner">…</div>
</div></code>```

Title: CSS rotate div 10deg full width

Body:
I have found the following Website.
Special the Section: Social News on the half of the side.

I wonder how to get the rotated divs (i think about 10 deg) over the full width.
Is there any possibility to do that responsive? So i can use the rotated div on a mobile phone?
I`m not as fit to rotate the div. How can i do this using css?

I`ve tried this:

Ans using following css:

.container {
   transform: rotate(10deg);
   width: 100%;
   height: 200px;
   background: red;
}

But the Container is not full width.

Body:
It work's without transforms. There are only CSS-Shapes. It's possible with transforms too. On A Collection of Separator Styles there are many other separator styles.

html, body {
  margin: 0;
  padding: 0;
}

.outer {
  position: relative;
}

.outer::before {
  position: absolute;
  top: 0px;

  border-top: solid 40px #ffffff;
  border-right: 100vw solid rgba(0,0,0,0);

  content: '';
}

.outer::after {
  bottom: 0px;
  position: absolute;

  border-bottom: solid 40px #ffffff;
  border-left: 100vw solid rgba(0,0,0,0);

  content: '';
}

.inner {
  height: 200px;
  padding: 60px 1em;

  background: #ccc;
}

<div class="outer">
  <div class="inner">…</div>
</div>


问:
Querying array of objects in typescript
I have an array of JSON objects

```<code>array = [{name: "will", age: "18"}
         {name: "Elliott", age: "21"}
        ]
</code>```

Is there a way to get the "age" for any given "name" (as you would do with a SQL statement when querying a database?

答:
Yes.

```<code>let array = [
  { name: "will", age: "18"},
  { name: "john", age: "18"},
  { name: "elliott", age: "21"}
]

array.filter((e) => { return e.name === 'john' })
</code>```

Result

```<code>[ { name: 'john', age: '18' } ]
</code>```

Title: Querying array of objects in typescript

Body:
I have an array of JSON objects

array = [{name: "will", age: "18"}
         {name: "Elliott", age: "21"}
        ]

Is there a way to get the "age" for any given "name" (as you would do with a SQL statement when querying a database?

Body:
Yes.

let array = [
  { name: "will", age: "18"},
  { name: "john", age: "18"},
  { name: "elliott", age: "21"}
]

array.filter((e) => { return e.name === 'john' })

Result

[ { name: 'john', age: '18' } ]


问:
How to make subprocess be called after another command in Python?
I want to write Python script. I am somekind new to it. In that script I want to run another C program, which gives many numbers in output. Smth like:

```<code>1   1   0.000000    0.000172    0.075010    0.937330    33.743876
</code>```

I want to run this program multiple times with other parameters and to collect all outputs in one file. After that I plan to use pandas to sort data and make some plots, but it is not important now. I wrote the following code:

```<code>import subprocess

f = open("ax-rrff.dat", "w")
f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")

p = subprocess.call(['gcc', 'ax-rrff.c', '-lm','-lgsl','-lgslcblas'])

for seed in range(1,2+1):
    for N in range(1,2+1):
        p = subprocess.call(['a.exe',str(seed),'1',str(N),'1000','0','0'], stdout=f)

f.close()
</code>```

(small numbers just to show you). I expect my ax-rrff.dat to be

```<code>seed    N   T   DRA D   Active  AvF
1   1   0.000000    0.000172    0.075010    0.937330    33.743876
1   2   0.000000    0.003598    0.021690    1.564677    14.032332
2   1   0.000000    0.000172    0.062262    0.925817    33.329404
2   2   0.000000    0.002790    0.014749    1.423670    16.689964
</code>```

However, scheduler of compiler thinks that it would be cool to make output in this way:

```<code>1   1   0.000000    0.000172    0.075010    0.937330    33.743876
1   2   0.000000    0.003598    0.021690    1.564677    14.032332
2   1   0.000000    0.000172    0.062262    0.925817    33.329404
2   2   0.000000    0.002790    0.014749    1.423670    16.689964
seed    N   T   DRA D   Active  AvF
</code>```

The question. How can I force sub-processes to run after  f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")?

答:
Ok, I am.on the phone so can't test my answer but I guess your expected output could be achieved like this:

```<code>import subprocess
f = open("ax-rrff.dat", "a")
f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")

p = subprocess.call(['gcc', 'ax-rrff.c', '-lm','-lgsl','-lgslcblas'])

for seed in range(1,2+1):
    for N in range(1,2+1):
        newcall = subprocess.Popen(['a.exe',str(seed),'1',str(N),'1000','0','0'], stdout=subprocess.PIPE)
        newcall.wait()
        output, errors = newcall.communicate()
        f.write(output.decode())

f.close()
</code>```

This would leave one thing unclear though.. since you are declaring p outside the for-loop and then again once inside it.. This leads me to believe you are willing to use the first declaration as input for the second one.. however, what you are doing is simply making a new declaration and thereby overwriting the first one. So you are changing what p is, not using/executing it in any way..

Further explanation:

I changed open(file, 'w') to open(file, 'a'), this means the file will be append mode rather then write mode. This allows you to write as often as you'd like to it and it will add each line in the order it is written to the file from.within your python script.

If you'd still like to use the first declaration of p as input for the second declaration see if you can do so by extending the command line command you insert into subprocess in the for loop.

Body:
I want to write Python script. I am somekind new to it. In that script I want to run another C program, which gives many numbers in output. Smth like:

1   1   0.000000    0.000172    0.075010    0.937330    33.743876

I want to run this program multiple times with other parameters and to collect all outputs in one file. After that I plan to use pandas to sort data and make some plots, but it is not important now. I wrote the following code:

import subprocess

f = open("ax-rrff.dat", "w")
f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")

p = subprocess.call(['gcc', 'ax-rrff.c', '-lm','-lgsl','-lgslcblas'])

for seed in range(1,2+1):
    for N in range(1,2+1):
        p = subprocess.call(['a.exe',str(seed),'1',str(N),'1000','0','0'], stdout=f)

f.close()

(small numbers just to show you). I expect my ax-rrff.dat to be

seed    N   T   DRA D   Active  AvF
1   1   0.000000    0.000172    0.075010    0.937330    33.743876
1   2   0.000000    0.003598    0.021690    1.564677    14.032332
2   1   0.000000    0.000172    0.062262    0.925817    33.329404
2   2   0.000000    0.002790    0.014749    1.423670    16.689964

However, scheduler of compiler thinks that it would be cool to make output in this way:

1   1   0.000000    0.000172    0.075010    0.937330    33.743876
1   2   0.000000    0.003598    0.021690    1.564677    14.032332
2   1   0.000000    0.000172    0.062262    0.925817    33.329404
2   2   0.000000    0.002790    0.014749    1.423670    16.689964
seed    N   T   DRA D   Active  AvF

The question. How can I force sub-processes to run after  f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")?

Body:
Ok, I am.on the phone so can't test my answer but I guess your expected output could be achieved like this:

import subprocess
f = open("ax-rrff.dat", "a")
f.write("seed\tN\tT\tDRA\tD\tActive\tAvF\n")

p = subprocess.call(['gcc', 'ax-rrff.c', '-lm','-lgsl','-lgslcblas'])

for seed in range(1,2+1):
    for N in range(1,2+1):
        newcall = subprocess.Popen(['a.exe',str(seed),'1',str(N),'1000','0','0'], stdout=subprocess.PIPE)
        newcall.wait()
        output, errors = newcall.communicate()
        f.write(output.decode())

f.close()

This would leave one thing unclear though.. since you are declaring p outside the for-loop and then again once inside it.. This leads me to believe you are willing to use the first declaration as input for the second one.. however, what you are doing is simply making a new declaration and thereby overwriting the first one. So you are changing what p is, not using/executing it in any way..

Further explanation:

I changed open(file, 'w') to open(file, 'a'), this means the file will be append mode rather then write mode. This allows you to write as often as you'd like to it and it will add each line in the order it is written to the file from.within your python script.

If you'd still like to use the first declaration of p as input for the second declaration see if you can do so by extending the command line command you insert into subprocess in the for loop.


问:
Dynamic Drop Down Menu and submenu php mysql
I have a menu that needs to be created dynamically from the database.
need to have menu and submenu

for example (wht i want):

```<code><ul class="dropdown">
    <li><a href="#">Link 1</a> </li>
    <li><a href="#">Link 2</a> </li>
    <li><a href="#">Link 3</a> </li>
    <li><a href="#">Link 4</a>
    <ul class="sub_menu">
        <li><a href="#">Link 4 - 1</a></li>
        <li><a href="#">Link 4 - 2</a></li>
        <li><a href="#">Link 4 - 3</a></li>
    </ul>
    </li>
    <li><a href="#">Link 5</a></li>
    <li><a href="#">Link 6</a> </li>
</ul>
</code>```

below is the code i used for menu using function i want submenu as well

```<code>function listMenu(){
    $ans = $this->select("cat_id,cat_name","s_category","1");
    if(is_array($ans)){
        foreach($ans as $val){
            echo
            "<li><a href=\"post-summary.php?cid=$val[0]\" >$val[1]</a></li>";
        }
    }
    else{
        echo "";
    }
}
</code>```

database is as follows:-

```<code>CREATE TABLE IF NOT EXISTS `s_category` (
  `cat_id` int(11) NOT NULL AUTO_INCREMENT,
  `cat_name` varchar(15) NOT NULL,
  `cat_uid` int(2) NOT NULL,
  `cat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `cat_parent` int(11) DEFAULT '0',
  `cat_sort` int(11) DEFAULT NULL,
  `cat_delete` int(1) DEFAULT '0',
  PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
</code>```

答:
created your database and write function with code and change parameters</p>

```<code>  function getAllFrom($field, $table,$where = NULL, $and = NULL , $orderfield, $ordering = "DESC") {

global $con;

$getAll = $con->prepare("SELECT $field FROM $table where $where $and  ORDER BY $orderfield $ordering");

$getAll->execute();

$all = $getAll->fetchAll();

return $all;}

         <ul>
                <?php
                $allCats = getAllFrom("*", "categories", "parent = 0", "" , "cat_id", "ASC");
                     foreach ($allCats as $cat) { ?>
                      <li>
                           <?php
                     echo '<a href="categoreis.php?pagename=' . str_replace(' ', '-', $cat['name_cat']) . '&pageid=' . $cat["cat_id"] . '">

                          ' . $cat['name_cat'] . '

                          </a>';
                          ?>
                          <ul class="sub-menu[enter image description here][1]">
                                <?php
                                  $catsub = $cat['cat_id'];
                                  $SubCats = getAllFrom("*", "categories", "parent = {$catsub}", "" , "cat_id", "ASC");
                                  foreach ($SubCats as $sub) { ?>
                                    <li>
                                    <?php
                                         echo '<a href="categoreis.php?pagename=' . $sub['name_cat'] . '&pageid=' . $sub["cat_id"] . '">

                                              ' . $sub['name_cat'] . '

                                              </a>';
                                              ?>
                                       </li>
                                <?php  }
                                  ?>
                          </ul>
                      </li>
                <?php   }
                 ?>
           </ul>
</code>```

Body:
I have a menu that needs to be created dynamically from the database.
need to have menu and submenu

for example (wht i want):

Link 1

Link 2

Link 3

Link 4

Link 4 - 1

Link 4 - 2

Link 4 - 3

Link 5

Link 6

below is the code i used for menu using function i want submenu as well

function listMenu(){
    $ans = $this->select("cat_id,cat_name","s_category","1");
    if(is_array($ans)){
        foreach($ans as $val){
            echo
            "
$val[1]
";
        }
    }
    else{
        echo "";
    }
}

database is as follows:-

CREATE TABLE IF NOT EXISTS `s_category` (
  `cat_id` int(11) NOT NULL AUTO_INCREMENT,
  `cat_name` varchar(15) NOT NULL,
  `cat_uid` int(2) NOT NULL,
  `cat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `cat_parent` int(11) DEFAULT '0',
  `cat_sort` int(11) DEFAULT NULL,
  `cat_delete` int(1) DEFAULT '0',
  PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

Body:
created your database and write function with code and change parameters

  function getAllFrom($field, $table,$where = NULL, $and = NULL , $orderfield, $ordering = "DESC") {

global $con;

$getAll = $con->prepare("SELECT $field FROM $table where $where $and  ORDER BY $orderfield $ordering");

$getAll->execute();

$all = $getAll->fetchAll();

return $all;}

         <ul>
                <?php
                $allCats = getAllFrom("*", "categories", "parent = 0", "" , "cat_id", "ASC");
                     foreach ($allCats as $cat) { ?>
                      <li>
                           <?php
                     echo '<a href="categoreis.php?pagename=' . str_replace(' ', '-', $cat['name_cat']) . '&pageid=' . $cat["cat_id"] . '">

                          ' . $cat['name_cat'] . '

                          </a>';
                          ?>
                          <ul class="sub-menu[enter image description here][1]">
                                <?php
                                  $catsub = $cat['cat_id'];
                                  $SubCats = getAllFrom("*", "categories", "parent = {$catsub}", "" , "cat_id", "ASC");
                                  foreach ($SubCats as $sub) { ?>
                                    <li>
                                    <?php
                                         echo '<a href="categoreis.php?pagename=' . $sub['name_cat'] . '&pageid=' . $sub["cat_id"] . '">

                                              ' . $sub['name_cat'] . '

                                              </a>';
                                              ?>
                                       </li>
                                <?php  }
                                  ?>
                          </ul>
                      </li>
                <?php   }
                 ?>
           </ul>


问:
Nginx reverse proxy server
I have 2 Ubuntu servers running on same location in digital ocean and the first one running as webserver(nginx) and the other one running as app-server(Nodejs)

Webserver sending request through private ip and as you guys can guess the app-server is not allow the direct requests.

My question is I have image/upload directory in the app-server such as : /srv/upload/user_images and I want to get those images from a web browser.

For example : www.myappserveripaddress.com/srv/upload/user_images/image1.jpeg

but the privilages would be the only image can be accessed from outside.None can access the /srv/upload/user_images/ to see the all images.

I dont know if its possible or not. Only if the user knows the image name , he can enter the ip.com/srv/upload/user_images/imageName.jpg . If this is possible what should I do ?

答:
Not 100% sure I understand your question but in order to link the user to a certain set of images you could append to the name of the image the UserID.

If you have a database, each time a user uploads an image you can also save there just the name of the picture he saved, then when the image is saved in the filesystem you save it with the name {UserID}-{imageName}.jpg.

On his pictures menu he can easily see a list maybe of all the picture names he uploaded. These names are taken from the database and are not a link to a file on the server.  Only when he clicks the image a request is constructed for a resource called /server/images/{UserID}-{imageName}.jpg.

The UserID here ensures you do not have duplicate image names in your server.

Hope this helps. If it is in any way wrong please let me know.

Title: Nginx reverse proxy server


问:
Caused by: java.lang.ClassNotFoundException: org.dom4j.io.STAXEventReader
I am developing a web service application but sessionFactory bean is not creating because of below error. I can't see duplicate or conflict version of dom4j jar. I tried various times to referesh/clean server and project in eclipse.

Hibernate version 5.1.0.Final

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-database.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/dom4j/io/STAXEventReader
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1192)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
      at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 51 more

Caused by: java.lang.NoClassDefFoundError: org/dom4j/io/STAXEventReader
      at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
      at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:87)
      at org.hibernate.cfg.Configuration.<init>(Configuration.java:124)
      at org.springframework.orm.hibernate5.LocalSessionFactoryBuilder.<init>(LocalSessionFactoryBuilder.java:110)
      at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:309)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 61 more

Caused by: java.lang.ClassNotFoundException: org.dom4j.io.STAXEventReader from [Module "deployment.web-services.war:main" from Service Module Loader]
      at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205)
      at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
      at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
      at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
      at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:130)
... 68 more
</code>```

Spring-security.xml

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

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan">
        <list>
            <value>com.foo.bar.entity</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="current_session_context_class">thread</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.validator.apply_to_ddl">true</prop>
            <prop key="hibernate.validator.autoregister_listeners">false</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
</bean>
<!-- Transcation Manager -->
<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:jboss/datasources/myDS" />
</bean>
</code>```

maven dependency:tree command give below result:-

```<code>--- maven-dependency-plugin:2.8:tree (default-cli) @ web-services ---
[INFO] com.car.buk:web-services:war:1.0
[INFO] +- com.car.buk:user-management:jar:1.0:compile
[INFO] +- com.car.buk:entity:jar:1.0:compile
[INFO] +- org.slf4j:slf4j-api:jar:1.7.18:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.5.3:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.5.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.5.3:compile
[INFO] +- org.hibernate:hibernate-core:jar:5.1.0.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  +- org.javassist:javassist:jar:3.20.0-GA:compile
[INFO] |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  +- org.apache.geronimo.specs:geronimo-jta_1.1_spec:jar:1.1.1:compile
[INFO] |  +- org.jboss:jandex:jar:2.0.0.Final:compile
[INFO] |  +- com.fasterxml:classmate:jar:1.3.0:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- xml-apis:xml-apis:jar:1.0.b2:compile
[INFO] |  \- org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final:compile
[INFO] +- org.hibernate:hibernate-entitymanager:jar:5.1.0.Final:compile
[INFO] +- org.springframework:spring-core:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-beans:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-jdbc:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-orm:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-tx:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-test:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-context:jar:4.2.5.RELEASE:compile
[INFO] |  +- org.springframework:spring-aop:jar:4.2.5.RELEASE:compile
[INFO] |  \- org.springframework:spring-expression:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-web:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-web:jar:4.0.4.RELEASE:compile
[INFO] |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] +- org.springframework.security:spring-security-config:jar:4.0.4.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-acl:jar:4.0.4.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-core:jar:4.0.4.RELEASE:compile
[INFO] +- org.springframework.security.oauth:spring-security-oauth2:jar:2.0.9.RELEASE:compile
[INFO] |  +- commons-codec:commons-codec:jar:1.9:compile
[INFO] |  \- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.13:compile
[INFO] |     \- org.codehaus.jackson:jackson-core-asl:jar:1.9.13:compile
[INFO] \- junit:junit:jar:3.8.1:test
</code>```

I am totally stuck. Do any of you guys have any clue how to resolve this??

答:
I used Ivy dependency manager and in my case I remove dom4j from core dependency and again add the last version 1.6.1 and that worked for me. </p>

```<code><dependency org="org.hibernate" name="hibernate-core" rev="5.2.8.Final">
    <exclude  org="dom4j"/>
</dependency>

<dependency org="dom4j" name="dom4j" rev="1.6.1"/>
</code>```

Body:
I am developing a web service application but sessionFactory bean is not creating because of below error. I can't see duplicate or conflict version of dom4j jar. I tried various times to referesh/clean server and project in eclipse.

Hibernate version 5.1.0.Final

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-database.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/dom4j/io/STAXEventReader
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1192)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
      at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
... 51 more

Caused by: java.lang.NoClassDefFoundError: org/dom4j/io/STAXEventReader
      at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
      at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:87)
      at org.hibernate.cfg.Configuration.<init>(Configuration.java:124)
      at org.springframework.orm.hibernate5.LocalSessionFactoryBuilder.<init>(LocalSessionFactoryBuilder.java:110)
      at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:309)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 61 more

Caused by: java.lang.ClassNotFoundException: org.dom4j.io.STAXEventReader from [Module "deployment.web-services.war:main" from Service Module Loader]
      at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:205)
      at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:455)
      at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:404)
      at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:385)
      at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:130)
... 68 more

Spring-security.xml

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

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan">
        <list>
            <value>com.foo.bar.entity</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="current_session_context_class">thread</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.validator.apply_to_ddl">true</prop>
            <prop key="hibernate.validator.autoregister_listeners">false</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:jboss/datasources/myDS" />
</bean>

maven dependency:tree command give below result:-

--- maven-dependency-plugin:2.8:tree (default-cli) @ web-services ---
[INFO] com.car.buk:web-services:war:1.0
[INFO] +- com.car.buk:user-management:jar:1.0:compile
[INFO] +- com.car.buk:entity:jar:1.0:compile
[INFO] +- org.slf4j:slf4j-api:jar:1.7.18:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.5.3:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.5.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.5.3:compile
[INFO] +- org.hibernate:hibernate-core:jar:5.1.0.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  +- org.javassist:javassist:jar:3.20.0-GA:compile
[INFO] |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  +- org.apache.geronimo.specs:geronimo-jta_1.1_spec:jar:1.1.1:compile
[INFO] |  +- org.jboss:jandex:jar:2.0.0.Final:compile
[INFO] |  +- com.fasterxml:classmate:jar:1.3.0:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- xml-apis:xml-apis:jar:1.0.b2:compile
[INFO] |  \- org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final:compile
[INFO] +- org.hibernate:hibernate-entitymanager:jar:5.1.0.Final:compile
[INFO] +- org.springframework:spring-core:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-beans:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-jdbc:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-orm:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-tx:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-test:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-context:jar:4.2.5.RELEASE:compile
[INFO] |  +- org.springframework:spring-aop:jar:4.2.5.RELEASE:compile
[INFO] |  \- org.springframework:spring-expression:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-web:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.2.5.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-web:jar:4.0.4.RELEASE:compile
[INFO] |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] +- org.springframework.security:spring-security-config:jar:4.0.4.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-acl:jar:4.0.4.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-core:jar:4.0.4.RELEASE:compile
[INFO] +- org.springframework.security.oauth:spring-security-oauth2:jar:2.0.9.RELEASE:compile
[INFO] |  +- commons-codec:commons-codec:jar:1.9:compile
[INFO] |  \- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.13:compile
[INFO] |     \- org.codehaus.jackson:jackson-core-asl:jar:1.9.13:compile
[INFO] \- junit:junit:jar:3.8.1:test

I am totally stuck. Do any of you guys have any clue how to resolve this??

Body:
I used Ivy dependency manager and in my case I remove dom4j from core dependency and again add the last version 1.6.1 and that worked for me.

<dependency org="org.hibernate" name="hibernate-core" rev="5.2.8.Final">
    <exclude  org="dom4j"/>
</dependency>

<dependency org="dom4j" name="dom4j" rev="1.6.1"/>


问:
why dropzone submits form twice
Hi I am trying to integrate my form with some other fields and dropzone I find that the controller is called twice not sure why.
Could anyone please help me

```<code>autoProcessQueue : false,
    uploadMultiple : true,
    maxFilesize : 256, // MB
    parallelUploads : 10,
    maxFiles : 10,
    addRemoveLinks : true,
    previewsContainer : ".dropzone-previews",

    //The setting up of the dropzone
    init : function() {

        var myDropzone = this;

        // first set autoProcessQueue = false
        $("form").one("submit", function(event) {
              myDropzone.processQueue();

        });
</code>```

thanks
priya

答:
stop form submit until dropzone upload and after that you have to upload form.</p>

```<code>var submitButton = document.querySelector("#submit");

    submitButton.addEventListener("click", function (file) {

        if (myDropzone.getAcceptedFiles().length > 0) {
            if (submitfiles === true) {
                submitfiles = false;
                return;
            }

            file.preventDefault();
            myDropzone.processQueue();

            myDropzone.on("complete", function () {
                submitfiles = true;
                $('#submit').trigger('click');
            });
        }
    });
</code>```

ContentLicense: CC BY-SA 4.0

Title: why dropzone submits form twice

Body:
Hi I am trying to integrate my form with some other fields and dropzone I find that the controller is called twice not sure why.
Could anyone please help me

autoProcessQueue : false,
    uploadMultiple : true,
    maxFilesize : 256, // MB
    parallelUploads : 10,
    maxFiles : 10,
    addRemoveLinks : true,
    previewsContainer : ".dropzone-previews",

    //The setting up of the dropzone
    init : function() {

        var myDropzone = this;

        // first set autoProcessQueue = false
        $("form").one("submit", function(event) {
              myDropzone.processQueue();

        });

thanks
priya

Body:
stop form submit until dropzone upload and after that you have to upload form.

var submitButton = document.querySelector("#submit");

    submitButton.addEventListener("click", function (file) {

        if (myDropzone.getAcceptedFiles().length > 0) {
            if (submitfiles === true) {
                submitfiles = false;
                return;
            }

            file.preventDefault();
            myDropzone.processQueue();

            myDropzone.on("complete", function () {
                submitfiles = true;
                $('#submit').trigger('click');
            });
        }
    });


问:
Is fs the only builtin module that can access the filesystem?
I know there are other things like require that can access the real filesystem, but this appears to use fs to do so.

Am I right in thinking that there are no other builtins that have direct access to the disk?

That is, if I was able to globally overwrite all fs methods with my own mocks that read from (and write to) an in-memory virtual filesystem, then there would be no way to access the real filesystem – is that correct?

答: In principle, that is correct. But other modules could spawn processes to access the file system or they could use some native addons that use the file system. If you want to do it as a security measure then it will not be sufficient. If you wanted to make sure that no module can access the real file system then you would have to hijack the system calls on the OS level and make sure that no external process could be run as well. Not an easy task. Probably the same could be achieved easier using containers that would run with an in memory file system and would have no way to access the external file system on the host system, not on the level of JavaScript.</p>


问:
Minify Html , Js , Css and Php
Im looking for the better way to minify those files but im still noob , currently im working  with atom editor so im using a plugin called atom-minify whichs minify my css and js but not the html , after this i have to compress the proyecto to upload to the server or it is not necesary ?</p>

答:
Probably best is to use Gulp/ Grunt for such a thing. Here is how to set it up Grunt.

And then use plugin such as Grunt-minified to do your minifications(not sure if minifications is a real word but... :D).

In any case, its better if you use Grunt/ Gulp in your projects as they help you with:

1) Work in as small chunks of CSS and JavaScript as makes sense to you, then concatenate them together for the production website.

2) Compress your CSS and minify your JavaScript to make their file sizes as small as possible for your production website.

3) Optimize your images to reduce their file size without affecting quality.

4) Use Sass for CSS authoring because of all the useful abstraction it allows.

Title: Minify Html , Js , Css and Php


问:
C# How do I leave the maximized window as it is?
I am using visual studio 2010 to do my C# GUI.

The current problem that I am facing is that after maximizing a window, it stays there but when I go to other forms, the window will go back to its original size.

How do I leave the maximized window all the way for all the forms, once I click the maximize button?

Heres an example:

User maximizes Form A

Form A maximized

User goes to Form B

Form B goes back to original size instead of a maximized window

What I want is when user maximizes a form, it stays that way till the program is closed or resized.

答:
Assuming you're using WinForms, you can have either implement a shared FormWindowState manager or use a Multiple Document Interface (MDI) container.

Shared FormWindowState

You can register each of your forms with a class responsible for propagating changes in forms' FormWindowState.

```<code>public class FormWindowStateManager {
    List<Form> _Forms;

    ...

    public void Register(Form form) {
        if(!_Forms.Contains(form)) {
            _Forms.Add(form);
            form.Resize += new EventHandler(Form_Resize);
        }
    }

    public void Unregister(Form form) {
        if(_Forms.Contains(form)) {
            _Forms.Remove(form);
            form.Resize -= new EventHandler(Form_Resize);
        }
    }

    private void Form_Resize(object sender, EventArgs e) {
        Form form = sender as Form;
        if(form != null) {
            if(form.FormWindowState == FormWindowState.Maximized || form.FormWindowState == FormWindowState.Normal) {
                PropagateWindowState(form.FormWindowState);
            }
        }
    }

    private void PropagateWindowState(FormWindowState state) {
        foreach(Form form in _Forms) {
            if(form.FormWindowState != state) {
                form.FormWindowState = state;
            }
        }
    }
}
</code>```

MDI Container

MdiParentForm.cs

```<code>IsMdiContainer = true;
</code>```

MdiChildForm.cs

```<code>MdiParent = myParentForm; // instance of MdiParentForm
</code>```

You can iterate through a form's MDI children using the form's MdiChildren property such that when on MDI child window changes its FormWindowState, the MDI parent form can apply the change to each of its children, similar to the shared FormWindowState approach.

These ideas are just off the top of my head but maybe they'll get you in the right direction.

Body:
Assuming you're using WinForms, you can have either implement a shared FormWindowState manager or use a Multiple Document Interface (MDI) container.

Shared FormWindowState

You can register each of your forms with a class responsible for propagating changes in forms' FormWindowState.

public class FormWindowStateManager {
    List<Form> _Forms;

    ...

    public void Register(Form form) {
        if(!_Forms.Contains(form)) {
            _Forms.Add(form);
            form.Resize += new EventHandler(Form_Resize);
        }
    }

    public void Unregister(Form form) {
        if(_Forms.Contains(form)) {
            _Forms.Remove(form);
            form.Resize -= new EventHandler(Form_Resize);
        }
    }

    private void Form_Resize(object sender, EventArgs e) {
        Form form = sender as Form;
        if(form != null) {
            if(form.FormWindowState == FormWindowState.Maximized || form.FormWindowState == FormWindowState.Normal) {
                PropagateWindowState(form.FormWindowState);
            }
        }
    }

    private void PropagateWindowState(FormWindowState state) {
        foreach(Form form in _Forms) {
            if(form.FormWindowState != state) {
                form.FormWindowState = state;
            }
        }
    }
}

MDI Container

MdiParentForm.cs

IsMdiContainer = true;

MdiChildForm.cs

MdiParent = myParentForm; // instance of MdiParentForm

You can iterate through a form's MDI children using the form's MdiChildren property such that when on MDI child window changes its FormWindowState, the MDI parent form can apply the change to each of its children, similar to the shared FormWindowState approach.

These ideas are just off the top of my head but maybe they'll get you in the right direction.


问:
Is it possible to returning over and over using a loop?
Does a return statement in a for loop(or while loop) break the loop? I would like to have a function return a value every time the loop runs.

Here is my code for reference:
(The first two functions are in a .py file called NYTHeadings. It would be ideal if it could stay that way.)

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

def get_html():

    url = 'https://www.nytimes.com/'
    r = requests.get(url)
    r_html = r.text

    return r_html

def print_titles():

    soup = BeautifulSoup(get_html(), 'html.parser')

    titles = soup.findAll('h2', class_="story-heading")

    for title in titles:
        if title.a:
            titles = title.a.text.replace('\n', ' ').strip()
            #print(titles)
            return titles

        else:
            titles = title.contents[0].strip()
            #print(titles)
            return titles

import NYTimesHeadings as nyt

def write_to_file():

    with open('Write to File Test.txt', 'r+') as file:
        file.write(str(nyt.print_titles()))

    return file

write_to_file()
</code>```

Thanks in advance.

答:
An ordinary for loop will indeed break on a return statement. However, what you have in mind is actually possible by using the yield operator instead of return, which turns your function into a generator.

Read more about generators at https://wiki.python.org/moin/Generators.

Body:
Does a return statement in a for loop(or while loop) break the loop? I would like to have a function return a value every time the loop runs.

Here is my code for reference:
(The first two functions are in a .py file called NYTHeadings. It would be ideal if it could stay that way.)

import requests
from bs4 import BeautifulSoup

def get_html():

    url = 'https://www.nytimes.com/'
    r = requests.get(url)
    r_html = r.text

    return r_html

def print_titles():

    soup = BeautifulSoup(get_html(), 'html.parser')

    titles = soup.findAll('h2', class_="story-heading")

    for title in titles:
        if title.a:
            titles = title.a.text.replace('\n', ' ').strip()
            #print(titles)
            return titles

        else:
            titles = title.contents[0].strip()
            #print(titles)
            return titles

import NYTimesHeadings as nyt

def write_to_file():

    with open('Write to File Test.txt', 'r+') as file:
        file.write(str(nyt.print_titles()))

    return file

write_to_file()

Thanks in advance.


问:
echo php variable with jquery ajax
I'm making my first website and I've encountered a problem with AJAX. I have tried and searched a lot of things but I'm missing something, please help me on this one. I have products' count and it works fine, but I need to refresh page everytime when I add new product to cart to see difference, so I need to use AJAX on my php variable. Please help me write AJAX code. I really appreciate it, thanks a lot and have a good day!

PHP Code:

```<code><?php
 $cart = new cart();
 $products = $cart->getCart();
 $sum = 0;
 foreach($products as $product){
     $sum += $product->count;
 }
 echo $sum;
?>
</code>```

答:
You could perform an ajax request like this. Your php will return the content which can then be appled to the DOM.</p>

```<code>// create array to POST
aData = {
    AjaxRequest:true,
    PostField2:'content',
}

// perform ajax request
$.ajax({
    type: "POST",
    url: "/relative_path_to_script/",
    data: aData,
    cache: false,
    success : function(data){
        console.log( 'response:' + data );
        $('#cartCountID').html(data);
    },

    failure : function(data){
        // report any ajax errors
    },

    complete : function(data){
        // runs once on completion
    }

});
</code>```

Title: echo php variable with jquery ajax

Body:
I'm making my first website and I've encountered a problem with AJAX. I have tried and searched a lot of things but I'm missing something, please help me on this one. I have products' count and it works fine, but I need to refresh page everytime when I add new product to cart to see difference, so I need to use AJAX on my php variable. Please help me write AJAX code. I really appreciate it, thanks a lot and have a good day!

PHP Code:

<?php
 $cart = new cart();
 $products = $cart->getCart();
 $sum = 0;
 foreach($products as $product){
     $sum += $product->count;
 }
 echo $sum;
?>

Body:
You could perform an ajax request like this. Your php will return the content which can then be appled to the DOM.

// create array to POST
aData = {
    AjaxRequest:true,
    PostField2:'content',
}

// perform ajax request
$.ajax({
    type: "POST",
    url: "/relative_path_to_script/",
    data: aData,
    cache: false,
    success : function(data){
        console.log( 'response:' + data );
        $('#cartCountID').html(data);
    },

    failure : function(data){
        // report any ajax errors
    },

    complete : function(data){
        // runs once on completion
    }

});


问:
how to pass variables "$tid, $id" into raw function?
when i call $id and $tid in raw function to fetch some data from sub document of mongodb collection it show me an error these two variables are undefined($tid,$id)?

```<code><?php
$id=IntValue;
$tId=IntValue;
if($tId==0)
{
    $maxPlayers=0;
}
else
{
  $result = DB::collection('PrizeDistributionTemplate')->raw(function($collection)
        {

            return $collection->aggregate(array(
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
                array( '$unwind' => '$templates' ),
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
            ));
        });

  $result=json_decode(json_encode($result),true);
  $maxPlayers=$result['result'][0]['templates']['maxPlayers'];
  $maxPlayers=intval($maxPlayers)+2;
}
?>
</code>```

答:
It will work great with bulk addition, this way you just need to create on array and pass it.</p>

```<code>$temp = [
   [
     'item' => "envelopes"
   ],
   [
     'item' => "envelopesas"
   ],
   [
     'item' => "lala"
   ]
 ];

 $userData = DB::table('log') - > raw(function ($collection) use($temp)
 {

   return $collection - > insertMany($temp);
 });
</code>```

Body:
when i call $id and $tid in raw function to fetch some data from sub document of mongodb collection it show me an error these two variables are undefined($tid,$id)?

<?php
$id=IntValue;
$tId=IntValue;
if($tId==0)
{
    $maxPlayers=0;
}
else
{
  $result = DB::collection('PrizeDistributionTemplate')->raw(function($collection)
        {

            return $collection->aggregate(array(
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
                array( '$unwind' => '$templates' ),
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
            ));
        });

  $result=json_decode(json_encode($result),true);
  $maxPlayers=$result['result'][0]['templates']['maxPlayers'];
  $maxPlayers=intval($maxPlayers)+2;
}
?>

Body:
It will work great with bulk addition, this way you just need to create on array and pass it.

$temp = [
   [
     'item' => "envelopes"
   ],
   [
     'item' => "envelopesas"
   ],
   [
     'item' => "lala"
   ]
 ];

 $userData = DB::table('log') - > raw(function ($collection) use($temp)
 {

   return $collection - > insertMany($temp);
 });


问:
how to append HTML content in angular 2 using innerHTML
I use innerHTML to render HTML Content in my component. But innerHTML remove all the attributes (eg: removes style attributes) in the HTML content and renders it. But need to render as it is, and doesn't want to extract any attribute from the HTML content. Is there any equivalent to innerHTML or do we can accomplish the desired result with innerHTML. Thanks in Advance.

my template file

```<code><div id="more-info-box" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Title</h4>
            </div>
            <div class="modal-body">
                <div class="clearfix">
                    <div [innerHTML]="htmlContent" class="long-desc-wrap">
                    </div>
                </div>
            </div>
         </div>
    </div>
</div><!-- End Info box -->
</code>```

my component file

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'cr-template-content',
  templateUrl: './app/channel.component.html'
})
export class TemplateComponent {
  constructor() {

  }

  htmlContent = '<p>This is my <strong style="color:red">Paragraph</strong></p>'

}
</code>```

My current output is the content rendered without style attribute.
But the desired result should be with style attribute.

答:
```<code> import { DomSanitizer} from '@angular/platform-browser';
 ....
 htmlContent:any;
    constructor(private sanitizer: DomSanitizer){
      this.htmlContent = this.sanitizer.bypassSecurityTrustHtml('<p>This is my <strong style="color:red">Paragraph</strong></p>');
}
</code>```

or you can use a pipe like shown in https://stackoverflow.com/a/41089093/217408

Body:
I use innerHTML to render HTML Content in my component. But innerHTML remove all the attributes (eg: removes style attributes) in the HTML content and renders it. But need to render as it is, and doesn't want to extract any attribute from the HTML content. Is there any equivalent to innerHTML or do we can accomplish the desired result with innerHTML. Thanks in Advance.

my template file

                <button type="button" class="close" data-dismiss="modal">×</button>

Title

my component file

import { Component } from '@angular/core';

@Component({
  selector: 'cr-template-content',
  templateUrl: './app/channel.component.html'
})
export class TemplateComponent {
  constructor() {

  }

  htmlContent = '
This is my Paragraph
'

}

My current output is the content rendered without style attribute.
But the desired result should be with style attribute.

Body:
 import { DomSanitizer} from '@angular/platform-browser';
 ....
 htmlContent:any;
    constructor(private sanitizer: DomSanitizer){
      this.htmlContent = this.sanitizer.bypassSecurityTrustHtml('<p>This is my <strong style="color:red">Paragraph</strong></p>');
}

or you can use a pipe like shown in https://stackoverflow.com/a/41089093/217408


问:
Excel List of values from table?
In an excel sheet I have a table like this:

```<code>    A          B
String 1       0
String 2       0
String 3       7
String 4       0
String 5       0
String 6       2
String 7       0
String 8       4
</code>```

My goal is (using only formulas) to obtain a reduced table filtered by the values in column B that are bigger than 0. Something like this:

```<code>   C          D
String 3      7
String 6      2
String 8      4
</code>```

Taking into account that the values in column B can change dinamically, ¿What's the easiest way to achieve this without VBA or pivot tables?

答:
Without using VBA or pivot table, the only way is to write an unique list of column A member, then use the SUMIF function to sum the points (column B of your example) of each one.

Finally you can apply an autofilter: show if value is greater than 0.

Title: Excel List of values from table?

Body:
In an excel sheet I have a table like this:

    A          B
String 1       0
String 2       0
String 3       7
String 4       0
String 5       0
String 6       2
String 7       0
String 8       4

My goal is (using only formulas) to obtain a reduced table filtered by the values in column B that are bigger than 0. Something like this:

   C          D
String 3      7
String 6      2
String 8      4

Taking into account that the values in column B can change dinamically, ¿What's the easiest way to achieve this without VBA or pivot tables?


问:
You must be logged in to use Magmi
i have installed magmi_full_0.7.22 from git master : https://github.com/dweeves/magmi-git#authentication

when i am trying to login for that first time, i am getting error :

```<code>You must be logged in to use Magmi
</code>```

i used "magmi" for username and password, but still its not working.

答:
The default username and password is:

```<code>username: magmi
password: magmi
</code>```

After login, you can configure Magmi with your database credentials. After that, you will be able to login with your Magento admin username and password.

https://github.com/dweeves/magmi-git#authentication

Title: You must be logged in to use Magmi

Body:
i have installed magmi_full_0.7.22 from git master : https://github.com/dweeves/magmi-git#authentication

when i am trying to login for that first time, i am getting error :

You must be logged in to use Magmi

i used "magmi" for username and password, but still its not working.

Body:
The default username and password is:

username: magmi
password: magmi

After login, you can configure Magmi with your database credentials. After that, you will be able to login with your Magento admin username and password.

https://github.com/dweeves/magmi-git#authentication


问:
Git - Find authors who changed a file
Is there a way in git to list out authors who changed a specific file?

For now all I could do was git log [filename] | grep "Author"

答:
Looks like there is the following command

git shortlog -sn [filename]

Title: Git - Find authors who changed a file


问:
How to start an activity from a dialog in Android
I created a custom dialog and I'd like to start a new activity when OK is clicked. How can I get the context to set it as first argument of my Intent constructor?

I can create the intent using getContext(), but I can't call startActivity. Shall I pass the activity calling the dialog to the dialog's constructor? Is it the usual way to start an activity by clicking a dialog?

```<code>public class CustomDialog extends Dialog implements OnClickListener {
    Button okButton, cancelButton;

    public CustomDialog(Context context) {
        super(context);
        setContentView(R.layout.custom_dialog);
        okButton = (Button) findViewById(R.id.button_ok);
        okButton.setOnClickListener(this);
        cancelButton = (Button) findViewById(R.id.button_cancel);
        cancelButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == cancelButton)
            dismiss();
        else {
            Intent i = new Intent(getContext(), ItemSelection.class);
            startActivity(i); //The method startActivity(Intent) is undefined for the type CustomDialog
        }
    }
}
</code>```

答:
I suggest you use this. It makes it so simple:

```<code>AlertDialog.Builder dialog = new AlertDialog.Builder(RegistrationActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Error Alert");
dialog.setMessage(info[1]);
dialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int id) {
        Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity.class);

        startActivity(intent);
    }
})
.setNegativeButton("", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});

final AlertDialog alert = dialog.create();
alert.show();
</code>```

info[1] is my data which is shown. You can replace this with your own message.

Body:
I created a custom dialog and I'd like to start a new activity when OK is clicked. How can I get the context to set it as first argument of my Intent constructor?

I can create the intent using getContext(), but I can't call startActivity. Shall I pass the activity calling the dialog to the dialog's constructor? Is it the usual way to start an activity by clicking a dialog?

public class CustomDialog extends Dialog implements OnClickListener {
    Button okButton, cancelButton;

    public CustomDialog(Context context) {
        super(context);
        setContentView(R.layout.custom_dialog);
        okButton = (Button) findViewById(R.id.button_ok);
        okButton.setOnClickListener(this);
        cancelButton = (Button) findViewById(R.id.button_cancel);
        cancelButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == cancelButton)
            dismiss();
        else {
            Intent i = new Intent(getContext(), ItemSelection.class);
            startActivity(i); //The method startActivity(Intent) is undefined for the type CustomDialog
        }
    }
}

Body:
I suggest you use this. It makes it so simple:

AlertDialog.Builder dialog = new AlertDialog.Builder(RegistrationActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Error Alert");
dialog.setMessage(info[1]);
dialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int id) {
        Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity.class);

        startActivity(intent);
    }
})
.setNegativeButton("", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});

final AlertDialog alert = dialog.create();
alert.show();

info[1] is my data which is shown. You can replace this with your own message.


问:
"standard" shebang with `-e`
So I used to start my bash scripts with #!/bin/bash -e (call bash, and exit on first error)

Now i'm moving to the more portable form  #!/usr/bin/env bash But setting -e doesn't work

```<code>#!/usr/bin/env bash -e
echo 'hi'

# output:
>> /usr/bin/env: ‘bash -e’: No such file or directory
</code>```

How can I use -e with the portable shebang?

答:
You can use the set command.

set - Set or unset values of shell options and positional parameters.

```<code>#!/usr/bin/env bash
set -e

echo hi
</code>```

Title: "standard" shebang with `-e`

Body:
So I used to start my bash scripts with #!/bin/bash -e (call bash, and exit on first error)

Now i'm moving to the more portable form  #!/usr/bin/env bash But setting -e doesn't work

#!/usr/bin/env bash -e
echo 'hi'

# output:
>> /usr/bin/env: ‘bash -e’: No such file or directory

How can I use -e with the portable shebang?

Body:
You can use the set command.

set - Set or unset values of shell options and positional parameters.

#!/usr/bin/env bash
set -e

echo hi


问:
VBA Solver Compile Error: Sub or Function not defined
I am using office 365 for Mac, with version number 15.32.

I repeatedly get the "compile error: sub or function not defined" when I try to run the macro that is trying to implement a solver function, which was a previously recorded macro (so I know it is correct).  The error highlights the "SolverOk" part of the code.

I understand that this often occurs when the reference to Solver.xlam is not present, however I have no idea how to do this on the Mac if this is truly the issue.  Attached is a screenshot of what I am trying to achieve.  Does the Solver.xlam thing on the left indicates that it is there?  If so, do you have any idea what the problem is?

Screenshot of available references

Screenshot of error + VBA code

答:
Open File/Options/Add-Ins

On the page with the add ins, click on the bottom "Manage Excel Add-Ins" .. "Go..." and look for SOLVER related Add-ins there.

Once these are activated, return to VBA (Alt-F11) and then the "SOLVER" option should be available in Tools/References, where you want to Add it.


问:
Speeding up rowwise comparison
I have a data.frame like the following:

```<code>id year  x y         v1
 1 2006 12 1  0.8510703
 1 2007 12 1  0.5954527
 1 2008 12 2 -1.9312854
 1 2009 12 1  0.1558393
 1 2010  8 1  0.9051487
 2 2001 12 2 -0.5480566
 2 2002 12 2 -0.7607420
 2 2003  3 2 -0.8094283
 2 2004  3 2 -0.1732794
</code>```

I would like to sum up (grouped by id) v1 of consecutive years (so 2010 and 2009, 2009 and 2008 and so on) only if x and y match. Expected output:

```<code>id year        res
 1 2010         NA
 1 2009         NA
 1 2008         NA
 1 2007  1.4465230
 2 2004 -0.9827077
 2 2003         NA
 2 2002 -1.3087987
</code>```

The oldest year per id is removed, as there is no preceding year.

I have a slow lapply solution in place but would like to speed things up, as my data is rather large.

Data:

```<code>set.seed(1)
dat <- data.frame(id = c(rep(1,5),rep(2,4)),year = c(2006:2010,2001:2004),
                x = c(12,12,12,12,8,12,12,3,3), y = c(1,1,2,1,1,2,2,2,2),
                v1 = rnorm(9))
</code>```

Current Solution:

```<code>require(dplyr)

myfun <- function(dat) { do.call(rbind,lapply(rev(unique(dat$year)[-1]),
            function(z) inner_join(dat[dat$year==z,2:5],
            dat[dat$year==z-1,2:5],
            by=c("x","y")) %>%
            summarise(year = z, res = ifelse(nrow(.) < 1,NA,sum(v1.x,v1.y)))))
        }

dat %>% group_by(id) %>% do(myfun(.))
</code>```

答:
Assuming there are sorted years as in the example:

```<code>dat %>%
  group_by(id) %>%
  mutate(res = v1 + lag(v1),                                     #simple lag for difference
         res = ifelse(x == lag(x) & y == lag(y), v1, NA)) %>%    #NA if x and y don't match
  slice(-1)                                                      #drop the first year
</code>```

You can use %>% select(id, year, res), and %>% arrange(id, desc(year)) at the end if you want.

Title: Speeding up rowwise comparison

Body:
I have a data.frame like the following:

id year  x y         v1
 1 2006 12 1  0.8510703
 1 2007 12 1  0.5954527
 1 2008 12 2 -1.9312854
 1 2009 12 1  0.1558393
 1 2010  8 1  0.9051487
 2 2001 12 2 -0.5480566
 2 2002 12 2 -0.7607420
 2 2003  3 2 -0.8094283
 2 2004  3 2 -0.1732794

I would like to sum up (grouped by id) v1 of consecutive years (so 2010 and 2009, 2009 and 2008 and so on) only if x and y match. Expected output:

id year        res
 1 2010         NA
 1 2009         NA
 1 2008         NA
 1 2007  1.4465230
 2 2004 -0.9827077
 2 2003         NA
 2 2002 -1.3087987

The oldest year per id is removed, as there is no preceding year.

I have a slow lapply solution in place but would like to speed things up, as my data is rather large.

Data:

set.seed(1)
dat <- data.frame(id = c(rep(1,5),rep(2,4)),year = c(2006:2010,2001:2004),
                x = c(12,12,12,12,8,12,12,3,3), y = c(1,1,2,1,1,2,2,2,2),
                v1 = rnorm(9))

Current Solution:

require(dplyr)

myfun <- function(dat) { do.call(rbind,lapply(rev(unique(dat$year)[-1]),
            function(z) inner_join(dat[dat$year==z,2:5],
            dat[dat$year==z-1,2:5],
            by=c("x","y")) %>%
            summarise(year = z, res = ifelse(nrow(.) < 1,NA,sum(v1.x,v1.y)))))
        }

dat %>% group_by(id) %>% do(myfun(.))

Body:
Assuming there are sorted years as in the example:

dat %>%
  group_by(id) %>%
  mutate(res = v1 + lag(v1),                                     #simple lag for difference
         res = ifelse(x == lag(x) & y == lag(y), v1, NA)) %>%    #NA if x and y don't match
  slice(-1)                                                      #drop the first year

You can use %>% select(id, year, res), and %>% arrange(id, desc(year)) at the end if you want.


问:
How to secure assets files in Android
I need to store audio files in the application. Access to these files should be restricted. How can I safely store these files?

I tried to store in the assets folder, but when unpacking the apk, these files can be obtained.

Also I used the extension files as a zip archive, however, this file can be assigned and the files can be retrieved by the user.

Is there a way to store files so that the user can not get them?

答:
Is there a way to store files so that the user can not get them?

Download them and never write them to disk.

Or, download them and write them to internal storage (e.g., getCacheDir()), noting that users who root their devices could still get at them.

You are welcome to try encrypting the assets, then decrypting them before use. However, since the decryption algorithm and key will be in the app, people can reverse-engineer the app and learn how to decrypt the assets.

Title: How to secure assets files in Android


问:
isAlive() returns false
I have a class MyTunnel which extends Thread class :

```<code>public class MyTunnel extends Thread {
    protected Object obj;
    public MyTunnel() {
        super(MyTunnel.class.getName());
        obj = new Object();
        prepare();
    }
    public void prepare() {
        System.out.println("Before starting...");
        start();
        synchronized(obj) {
            try {
                obj.wait(3000);
            } catch (InterruptedException e) {
                System.out.println("Error while waiting thread to start");
            }
        }

        System.out.println("After starting...");
    }

    @Override
    public void run() {
        System.out.println("running...");
    }

}
</code>```

When I run following code on main thread:

```<code>System.out.println("Before creating tunnel...");
MyTunnel tunnel = new MyTunnel();
System.out.println("After creating tunnel...");

System.out.println("Is tunnel alive ? " + tunnel.isAlive());
</code>```

I see print out like this:

```<code>Before creating tunnel...
Before starting...
running...
After starting...
After creating tunnel...
Is tunnel alive ? false
</code>```

My question is, why tunnel.isAlive() returns false (in last print out message)?

But if I change prepare() function to:

```<code>public void prepare() {
    System.out.println("Before starting...");
    start();
    System.out.println("After starting...");
}
</code>```

run the code again, tunnel.isAlive() then returns true. Why?

答:
The first scenario:

Your current ("main") thread starts the new thread, then the call obj.wait(3000); causes the current thread to wait with a timeout of 3 seconds. It's not the new thread that waits!

As the current thread waits, the new thread is executed. It only writes "running..." and finishes very quickly.

Thus, the "main" thread is resumed (after 3 seconds), the new thread is already dead, so isAlive() returns false.

The second scenario:

Your current ("main") thread starts the new thread and continues executing.

The new thread may or may not run while the main thread does just a few System.out.println() calls.

Thus, there's a chance that the new thread is not yet executed and the new thread is still alive, so isAlive() returns true.

Note that it may happen that the new thread is executed just after having been started in the second scenario. So even in the second scenario isAlive() may return false, but the chances are lower than in the first one (-> race conditions).

P.S. if you include any "heavy" operation in the second scenario just before calling isAlive(), then it's likely that the result is false. Pls try the following:

```<code>    System.out.println("Before creating tunnel...");
    final MyTunnel tunnel = new MyTunnel();
    System.out.println("After creating tunnel...");

    for (int i = 0; i < 100; ++i) {
        System.out.print("");
    }

    System.out.println("Is tunnel alive ? " + tunnel.isAlive()); // returns false on my machine
</code>```

Title: isAlive() returns false

Body:
I have a class MyTunnel which extends Thread class :

public class MyTunnel extends Thread {
    protected Object obj;
    public MyTunnel() {
        super(MyTunnel.class.getName());
        obj = new Object();
        prepare();
    }
    public void prepare() {
        System.out.println("Before starting...");
        start();
        synchronized(obj) {
            try {
                obj.wait(3000);
            } catch (InterruptedException e) {
                System.out.println("Error while waiting thread to start");
            }
        }

        System.out.println("After starting...");
    }

    @Override
    public void run() {
        System.out.println("running...");
    }

}

When I run following code on main thread:

System.out.println("Before creating tunnel...");
MyTunnel tunnel = new MyTunnel();
System.out.println("After creating tunnel...");

System.out.println("Is tunnel alive ? " + tunnel.isAlive());

I see print out like this:

Before creating tunnel...
Before starting...
running...
After starting...
After creating tunnel...
Is tunnel alive ? false

My question is, why tunnel.isAlive() returns false (in last print out message)?

But if I change prepare() function to:

public void prepare() {
    System.out.println("Before starting...");
    start();
    System.out.println("After starting...");
}

run the code again, tunnel.isAlive() then returns true. Why?

Body:
The first scenario:

Your current ("main") thread starts the new thread, then the call obj.wait(3000); causes the current thread to wait with a timeout of 3 seconds. It's not the new thread that waits!

As the current thread waits, the new thread is executed. It only writes "running..." and finishes very quickly.

Thus, the "main" thread is resumed (after 3 seconds), the new thread is already dead, so isAlive() returns false.

The second scenario:

Your current ("main") thread starts the new thread and continues executing.

The new thread may or may not run while the main thread does just a few System.out.println() calls.

Thus, there's a chance that the new thread is not yet executed and the new thread is still alive, so isAlive() returns true.

Note that it may happen that the new thread is executed just after having been started in the second scenario. So even in the second scenario isAlive() may return false, but the chances are lower than in the first one (-> race conditions).

P.S. if you include any "heavy" operation in the second scenario just before calling isAlive(), then it's likely that the result is false. Pls try the following:

    System.out.println("Before creating tunnel...");
    final MyTunnel tunnel = new MyTunnel();
    System.out.println("After creating tunnel...");

    for (int i = 0; i < 100; ++i) {
        System.out.print("");
    }

    System.out.println("Is tunnel alive ? " + tunnel.isAlive()); // returns false on my machine