问:
I want to give 'edit-link i.e edit' if ans column of table from database is null
I am retrieving answer from ans column by using jdbc and showing it into a jsp page in a form of a table, if ans column is null or empty then I have to give a user edit link, but if ans column has a value then I'm going to show answer but the problem is if-else condition is not working. Please help me to solve this, My code is given below:

```<code><div class="table-responsive">
    <table class="table center-aligned-table">
        <thead>
        <tr class="text-primary">
            <th>Question No</th>
            <th>Question Name</th>
            <th>Answer:</th>
            <th> </th>
            <th> </th>

            <th></th>
            <th></th>
            <th></th>
        </tr>
        </thead>
    <tbody>
        <%
            try{
               int oopa=1;
               //String nme=(String)session.getAttribute("vname7");
               DbCon cc=new DbCon();
               Connection onn=cc.fun();
               Statement stt=onn.createStatement();

               ResultSet r=stt.executeQuery("select ques,ans from postquestion;");

                while(r.next()){
        %>

        <tr class="">
            <td><center><%=oopa++%></center></td>
            <td><%=r.getString(1)%></td>
            <%
                if(r.getString(2)==null)
                {
            %>

            <td><a href="">Edit</a></td>

            <%
                }
                else
                {
            %>
            <td><%=r.getString(2)%></td>

            <%
            }
            %>

            <td> </td>

        </tr>

            <%

            }
}
            catch(Exception vjin){
                System.out.println("I am vjin: "+vjin);
                vjin.printStackTrace();
            }

            %>

    </tbody>
    </table>
</div>

</code>```

答:
You might get empty values from your results. So check if r.getString(2) is empty or not, null differs from empty value.

More over, JSP is just a view component, writing DAO code in JSP is not a good practice.

Thanks

Body:
I am retrieving answer from ans column by using jdbc and showing it into a jsp page in a form of a table, if ans column is null or empty then I have to give a user edit link, but if ans column has a value then I'm going to show answer but the problem is if-else condition is not working. Please help me to solve this, My code is given below:

            Question No
            Question Name
            Answer:

        <%
            try{
               int oopa=1;
               //String nme=(String)session.getAttribute("vname7");
               DbCon cc=new DbCon();
               Connection onn=cc.fun();
               Statement stt=onn.createStatement();

               ResultSet r=stt.executeQuery("select ques,ans from postquestion;");

                while(r.next()){
        %>

            <%=oopa++%>
            <%=r.getString(1)%>
            <%
                if(r.getString(2)==null)
                {
            %>

            Edit

            <%
                }
                else
                {
            %>
            <%=r.getString(2)%>

            <%
            }
            %>

            <%

            }
}
            catch(Exception vjin){
                System.out.println("I am vjin: "+vjin);
                vjin.printStackTrace();
            }

            %>


来源: stackexchange

问:
What is Python equivalent of for(i=1;i<10000000;i=1*10)?
In python how can we create a for-loop that does not have a constant step-size? I want to create a for-loop with step-function i=i*10, How can I do that?

For example: I want to create a python equivalent for: for(i=1;i<10000000;i=i*10){...}
How do I do this in python2 and python3?

I know that I can just use while-loop But I want to know if there is a way using for-loop?

答:
Trivially, a C for loop is a syntactic sugar, where

```<code>for (init; cond; step)
  body
</code>```

is equivalent to

```<code>init;
while (cond) {
  body;
  step;
}
</code>```

which is, again trivially, translatable into Python:

```<code>i = 1
while i < 10000000:
    do_stuff(i)
    i *= 10
</code>```

On the other hand, Python's for loop consumes an iterator. I can't think of an off-the-shelf iterator you could use, but if you create an iterator that has the property you desire, you can do so.

```<code>def geometric_range(start, end, step):
    i = start
    while i < end:
        yield i
        i *= step

for i in geometric_range(1, 10000000, 10):
    do_stuff(i)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Trivially, a C for loop is a syntactic sugar, where

for (init; cond; step)
  body

is equivalent to

init;
while (cond) {
  body;
  step;
}

which is, again trivially, translatable into Python:

i = 1
while i < 10000000:
    do_stuff(i)
    i *= 10

On the other hand, Python's for loop consumes an iterator. I can't think of an off-the-shelf iterator you could use, but if you create an iterator that has the property you desire, you can do so.

def geometric_range(start, end, step):
    i = start
    while i < end:
        yield i
        i *= step

for i in geometric_range(1, 10000000, 10):
    do_stuff(i)


答:
One option would be to use a while loop:

```<code>i = 1
while i < 10000000:
    print(i)
    # the rest of your logic
    i = i*10
</code>```

Title: What is Python equivalent of for(i=1;i<10000000;i=1*10)?

Body:
In python how can we create a for-loop that does not have a constant step-size? I want to create a for-loop with step-function i=i*10, How can I do that?

For example: I want to create a python equivalent for: for(i=1;i<10000000;i=i*10){...}
How do I do this in python2 and python3?

I know that I can just use while-loop But I want to know if there is a way using for-loop?

Body:
One option would be to use a while loop:

i = 1
while i < 10000000:
    print(i)
    # the rest of your logic
    i = i*10


问:
uasort() ? - sorting posts from a bank account
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

```<code>date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)
</code>```

btw. the date field is an UNIX timestamp

```<code>array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )
</code>```

答:
Let's combine this from the comments

the query is just as simple as SELECT time, amount, accum_amount FROM table

with this requirement from the original question:

I need to sort by three fields: date, amount, accumulated amount

Now, there were no requirements stated as to whether the sort is ascending or not.  Let's assume ascending.

```<code>SELECT time, amount, accum_amount
  FROM table
 ORDER BY time ASC, amount ASC, accum_amount ASC
</code>```

This will give us all of the data first sorted by time.  When the time is identical, it will sort second by amount, lowest first and highest last.  When the time and amount are identical, it will sort third by the accumulated amount, again sorted lowest first, highest last.

Changing the order of operations with the sort is as simple as swapping around the list in the ORDER BY clause.  Going from largest to smallest is as easy as switching from ASC to DESC.

Note how relatively easy this method is in comparison to sorting in PHP.  Whenever you can, let your database give you pre-sorted results.

Because I need to leave the site for a few hours, I'm just going to type this up real quick.  I'm operating right now under the assumption that you want to recalculate the accumulated value.

Our query is now:

```<code>SELECT time, amount
  FROM table
 ORDER BY time ASC, amount DESC
</code>```

We'll be a friendly bank and perform all deposits (increases in amount) first, then all debits (decreases in amount) last, processing the largest debits later than the smaller debits.

Given $data is our array:

```<code>$running_total = 0;
foreach($data as $index => $row) {
    $data[$index]['accum_amount'] = $running_total + $row['amount'];
    $running_total = $data[$index]['accum_amount'];
}
</code>```

This should successfully rebuild the accum_amount list, given the business rules I have outlined above.

ContentLicense: CC BY-SA 3.0

Body:
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)

btw. the date field is an UNIX timestamp

array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )

Body:
Let's combine this from the comments

the query is just as simple as SELECT time, amount, accum_amount FROM table

with this requirement from the original question:

I need to sort by three fields: date, amount, accumulated amount

Now, there were no requirements stated as to whether the sort is ascending or not.  Let's assume ascending.

SELECT time, amount, accum_amount
  FROM table
 ORDER BY time ASC, amount ASC, accum_amount ASC

This will give us all of the data first sorted by time.  When the time is identical, it will sort second by amount, lowest first and highest last.  When the time and amount are identical, it will sort third by the accumulated amount, again sorted lowest first, highest last.

Changing the order of operations with the sort is as simple as swapping around the list in the ORDER BY clause.  Going from largest to smallest is as easy as switching from ASC to DESC.

Note how relatively easy this method is in comparison to sorting in PHP.  Whenever you can, let your database give you pre-sorted results.

Because I need to leave the site for a few hours, I'm just going to type this up real quick.  I'm operating right now under the assumption that you want to recalculate the accumulated value.

Our query is now:

SELECT time, amount
  FROM table
 ORDER BY time ASC, amount DESC

We'll be a friendly bank and perform all deposits (increases in amount) first, then all debits (decreases in amount) last, processing the largest debits later than the smaller debits.

Given $data is our array:

$running_total = 0;
foreach($data as $index => $row) {
    $data[$index]['accum_amount'] = $running_total + $row['amount'];
    $running_total = $data[$index]['accum_amount'];
}

This should successfully rebuild the accum_amount list, given the business rules I have outlined above.


问:
How to return a nested list of frequency from a Python list?
From a list of cards - return a nested list of the cards with the same numbers and then the rest in a separate list.

```<code>EXAMPLE: ['6C', '7C', '7D', '8S', '6D']
</code>```

returning [['7C', '7D'], ['6C','6D'], ['8S']]

I have attempted using a while loop, but cant figure it out.

Thank you!

答:
Here. Try this.</p>

```<code>from itertools import groupby
a = ['6C', '7C', '7D', '8S', '6D']
a.sort()
final_list = []
for i, j in groupby(a, key=lambda x:x[0]):
    final_list.append(list(j))
print(final_list)
</code>```

Body:
From a list of cards - return a nested list of the cards with the same numbers and then the rest in a separate list.

EXAMPLE: ['6C', '7C', '7D', '8S', '6D']

returning [['7C', '7D'], ['6C','6D'], ['8S']]

I have attempted using a while loop, but cant figure it out.

Thank you!

Body:
Here. Try this.

from itertools import groupby
a = ['6C', '7C', '7D', '8S', '6D']
a.sort()
final_list = []
for i, j in groupby(a, key=lambda x:x[0]):
    final_list.append(list(j))
print(final_list)


问:
Google Indexing API - Invalid attribute. 'url' is not in standard URL format - But my URL is Correct
I am currently using Indexing API v3.

When I am using this API in a loop, I got this error:

Invalid attribute. 'url' is not in standard URL format

But I am pretty sure that my URL is correct, because it is download from Google search console:

Here is the code:

```<code>from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import json

import pandas as pd

JSON_KEY_FILE = "key.json"
SCOPES = ["https://www.googleapis.com/auth/indexing"]

credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)
http = credentials.authorize(httplib2.Http())

# This file contains 2 column, URL and date
csv = pd.read_csv("my_data.csv")
csv[["URL"]][0:10].apply(lambda x: indexURL(x.to_string(), http), axis=1)

def indexURL(url, http):

    ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"

    content = {}
    content['url'] = url
    content['type'] = "URL_UPDATED"
    json_ctn = json.dumps(content)

    response, content = http.request(ENDPOINT, method="POST", body=json_ctn)

    result = json.loads(content.decode())

    if("error" in result):
        print("Error({} - {}): {}".format(result["error"]["code"], result["error"]["status"], result["error"]["message"]))
    else:
        print("urlNotificationMetadata.url: {}".format(result["urlNotificationMetadata"]["url"]))
        print("urlNotificationMetadata.latestUpdate.url: {}".format(result["urlNotificationMetadata"]["latestUpdate"]["url"]))
        print("urlNotificationMetadata.latestUpdate.type: {}".format(result["urlNotificationMetadata"]["latestUpdate"]["type"]))
        print("urlNotificationMetadata.latestUpdate.notifyTime: {}".format(result["urlNotificationMetadata"]["latestUpdate"]["notifyTime"]))
</code>```

Here is a list of URL sample:

Can anyone please tell me what's wrong with my code?

Thank you very much in advance for all your help.

答:
It seems that even if I apply .strip() to each row, there is still a \n at the end of each URL.

So instead of putting row one by one to lambda, I put the whole series to lambda and use a for-loop to handle it.

The whole working example is here:

Google Indexing API v3 Working Example with Python 3

Body:
I am currently using Indexing API v3.

When I am using this API in a loop, I got this error:

Invalid attribute. 'url' is not in standard URL format

But I am pretty sure that my URL is correct, because it is download from Google search console:

Here is the code:

from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import json

import pandas as pd

JSON_KEY_FILE = "key.json"
SCOPES = ["https://www.googleapis.com/auth/indexing"]

credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)
http = credentials.authorize(httplib2.Http())

# This file contains 2 column, URL and date
csv = pd.read_csv("my_data.csv")
csv[["URL"]][0:10].apply(lambda x: indexURL(x.to_string(), http), axis=1)

def indexURL(url, http):

    ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"

    content = {}
    content['url'] = url
    content['type'] = "URL_UPDATED"
    json_ctn = json.dumps(content)

    response, content = http.request(ENDPOINT, method="POST", body=json_ctn)

    result = json.loads(content.decode())

    if("error" in result):
        print("Error({} - {}): {}".format(result["error"]["code"], result["error"]["status"], result["error"]["message"]))
    else:
        print("urlNotificationMetadata.url: {}".format(result["urlNotificationMetadata"]["url"]))
        print("urlNotificationMetadata.latestUpdate.url: {}".format(result["urlNotificationMetadata"]["latestUpdate"]["url"]))
        print("urlNotificationMetadata.latestUpdate.type: {}".format(result["urlNotificationMetadata"]["latestUpdate"]["type"]))
        print("urlNotificationMetadata.latestUpdate.notifyTime: {}".format(result["urlNotificationMetadata"]["latestUpdate"]["notifyTime"]))

Here is a list of URL sample:

Can anyone please tell me what's wrong with my code?

Thank you very much in advance for all your help.


问:
Query CONTAINS not working only selecting where equals
Queries using contains have recently stopped working correctly.
When value in source data column is 1,2,3 and the query is WHERE B contains '3'

See test sheet here:
https://docs.google.com/spreadsheets/d/1tCJBerHOmVfKbtb81JEyWEp6ZYP0EXyJqG-_7zVWpLw/edit?usp=sharing

Update
It appears that google is now first applying the Number Formatting to the cell then running the QUERY. Ensure your data column is set to PLAIN TEXT.

答:
As per the Update Google has changed to now first run the "Number Format" filters, then the QUERY method runs on the field.
So by default AUTOMATIC NUMBER formatting is applied - google based on the value sets the format on what it thinks is correct.

FIX: Set data to FORMAT > NUMBER > PLAIN TEXT

I have updated the example to illustrate this.

This change would probably assist the general Google Sheets user, but where you are working off raw data ensure you set the PLAIN TEXT number format on the columns.


问:
How can I make sure that a certain line is printed only when the if statement is met in a while-loop
I am trying to print an if statement but only if the values are correct and they meet the requirements. However, the if statement is inside of a while loop and even though it asks the user to try again when the value in the if statement is not correct it still prints out the numbers the user inputted the first time in the WriteLine outside of the if statement (where it says SIMULATION). I want it to ask the user to try again until the values meet the required standard of the if statement.

namespace Woodchuck
{
    class Program
    {
        static void Main(string[] args)
        {
            string restart = "Y";

            while (restart == "Y")
            {
                int totalWoodChucks = 0;
                int days = 0;

                const int MAXDAYS = 10;
                const int MINDAYS = 1;
                const int MAXWOOD = 100;
                const int MINWOOD = 1;

                Write("Enter number of woodchucks for this simulation (1-100): ");
                int.TryParse(ReadLine(), out totalWoodChucks);

                if (totalWoodChucks > MAXWOOD || totalWoodChucks < MINWOOD)
                {
                    WriteLine("Please try again");
                }

                Write("Enter number of days for this simulation (1-10): ");
                int.TryParse(ReadLine(), out days);
                if (days > MAXDAYS || days < MINDAYS)
                {
                    WriteLine("Please try again");
                }

                WriteLine($"SIMULATION 1: {totalWoodChucks} woodchucks over {days} days");

                Write("\nTo run another simulation, enter 'Y':");
                restart = ReadLine().ToUpper();

            }
            //Debug pause
            WriteLine("Press any key to wrap it up...");
        }
    }
}
```

答:
string restart = "Y";

```<code>    while(restart == "Y")
    {
        int totalWoodChucks = 0;
        int days = 0;

        const int MAXDAYS = 10;
        const int MINDAYS = 1;
        const int MAXWOOD = 100;
        const int MINWOOD = 1;

        Write("Enter number of woodchucks for this simulation (1-100): ");
        int.TryParse(ReadLine(), out totalWoodChucks);
        Write("Enter number of days for this simulation (1-10): ");
        int.TryParse(ReadLine(), out days);

        if((totalWoodChucks > MAXWOOD || totalWoodChucks < MINWOOD) &&(days > MAXDAYS || days < MINDAYS))
        {
            WriteLine("Please try again");
            continue;
        }

        WriteLine($"SIMULATION 1: {totalWoodChucks} woodchucks over {days} days");

        Write("\nTo run another simulation, enter 'Y':");
        restart = ReadLine().ToUpper();

    }
    //Debug pause
    WriteLine("Press any key to wrap it up...");
</code>```

What I did was make the checking after the all data is been gathered. then if the data does not meet the requirements it will ask again for another try until the data has been satisfied.

Body:
string restart = "Y";

    while(restart == "Y")
    {
        int totalWoodChucks = 0;
        int days = 0;

        const int MAXDAYS = 10;
        const int MINDAYS = 1;
        const int MAXWOOD = 100;
        const int MINWOOD = 1;

        Write("Enter number of woodchucks for this simulation (1-100): ");
        int.TryParse(ReadLine(), out totalWoodChucks);
        Write("Enter number of days for this simulation (1-10): ");
        int.TryParse(ReadLine(), out days);

        if((totalWoodChucks > MAXWOOD || totalWoodChucks < MINWOOD) &&(days > MAXDAYS || days < MINDAYS))
        {
            WriteLine("Please try again");
            continue;
        }

        WriteLine($"SIMULATION 1: {totalWoodChucks} woodchucks over {days} days");

        Write("\nTo run another simulation, enter 'Y':");
        restart = ReadLine().ToUpper();

    }
    //Debug pause
    WriteLine("Press any key to wrap it up...");

What I did was make the checking after the all data is been gathered. then if the data does not meet the requirements it will ask again for another try until the data has been satisfied.


问:
Socket IO works fine on local machine but doesn't work on Heroku
Situation:

I'm building an web app (a SPA) with ReactJS and ExpressJS. I'm using Socket.IO for real-time chatting. When I build my app and run it on localhost, everything works fine so I decide to deploy it on Heroku. My app is built successfully on Heroku and ready to use.

Problem:

So I enter my app to see if it works fine on Heroku. The app seems to be ok when I enter login page and register page (these pages are not going with Socket.IO). But when I go to chat page (this page is using Socket.IO for real-time chatting), the client is crashed, it's not loaded and throw the below error.

Error:

I get this following error:

```<code>> Uncaught TypeError: Cannot read property 'DEBUG' of undefined
    at load (browser.js:168)
    at Object.eval (browser.js:178)
    at eval (browser.js:197)
    at Object../node_modules/socket.io-client/node_modules/debug/src/browser.js (vendor.js:2639)
    at __webpack_require__ (main.js:788)
    at fn (main.js:151)
    at eval (url.js:7)
    at Object../node_modules/socket.io-client/lib/url.js (vendor.js:2628)
    at __webpack_require__ (main.js:788)
    at fn (main.js:151)
</code>```

When I look at the module online, it has the following check:

```<code>// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (!r && typeof process !== 'undefined' && 'env' in process) {
    r = undefined.DEBUG; //the error is showed here
  }
</code>```

So I start my app on localhost and search for above code, I get this:

```<code>// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (!r && typeof process !== 'undefined' && 'env' in process) {
    r = { /*A JSON object contains .env variables*/ }.DEBUG;
  }
</code>```

Code:

This is my server:

```<code>//requirements...
const socket = require("./server/socket");

const app = express();
const server = http.createServer(app);
const port = process.env.PORT || 3000;

//middlewares...
//routes...
//database connection...

socket(server);

server.listen(port);
console.log("Server started on: " + port);

</code>```

My socket setup:

```<code>const socketIO = require("socket.io");

const socket = server => {
    const io = socketIO(server);
    const chat = io.of("/chat");

    chat.on("connection", client => {
        console.log("User started chat!");

        client.on("disconnect", () => {
            console.log("User left chat!");
        });

        client.on("sendMessage", msg => {
            const data = msg;
            client.broadcast.emit("incomingMessage", { data });
        });
    });
};

module.exports = socket;
</code>```

React component that using Socket.IO:

```<code>const _ChatBox = ({ props }) => {
    const [connection] = useState(io("/chat"));

    useEffect(() => {
        connection.on("incomingMessage", message => {
            //receive message...
        });
    }, []);

    const sendMessageToSocket = data => {
        connection.emit("sendMessage", data);
    };

    return (
        /* JSX here */
    );
};
</code>```

What I want:

I want to know if there is any problem with my code. When I deploy my app to Heroku, is there any extra setup I have to do on Heroku to make my app working with Socket.IO?

答:
After spending hours researching and reviewing my code, I have figured out why my app is not working on Heroku. That because the client using dotenv module, and I setup it in webpack.config.js:

```<code>//...requirements
const dotenv = require("dotenv");
const webpack = require("webpack");

module.exports = {
    //...configs
    plugins: [
        //...other plugins
        new webpack.DefinePlugin({
            "process.env": JSON.stringify(dotenv.parsed)
        })
    ]
};
</code>```

Then when I deploy my app on Heroku, Heroku will build my client from source code and server will look for the frontend part in dist folder. The client now can't find the .env file on Heroku so it can't load the environment variables that causes it to throw error.

I removed dotenv because I don't need it now.

Body:
Situation:

I'm building an web app (a SPA) with ReactJS and ExpressJS. I'm using Socket.IO for real-time chatting. When I build my app and run it on localhost, everything works fine so I decide to deploy it on Heroku. My app is built successfully on Heroku and ready to use.

Problem:

So I enter my app to see if it works fine on Heroku. The app seems to be ok when I enter login page and register page (these pages are not going with Socket.IO). But when I go to chat page (this page is using Socket.IO for real-time chatting), the client is crashed, it's not loaded and throw the below error.

Error:

I get this following error:

> Uncaught TypeError: Cannot read property 'DEBUG' of undefined
    at load (browser.js:168)
    at Object.eval (browser.js:178)
    at eval (browser.js:197)
    at Object../node_modules/socket.io-client/node_modules/debug/src/browser.js (vendor.js:2639)
    at __webpack_require__ (main.js:788)
    at fn (main.js:151)
    at eval (url.js:7)
    at Object../node_modules/socket.io-client/lib/url.js (vendor.js:2628)
    at __webpack_require__ (main.js:788)
    at fn (main.js:151)

When I look at the module online, it has the following check:

// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (!r && typeof process !== 'undefined' && 'env' in process) {
    r = undefined.DEBUG; //the error is showed here
  }

So I start my app on localhost and search for above code, I get this:

// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (!r && typeof process !== 'undefined' && 'env' in process) {
    r = { /*A JSON object contains .env variables*/ }.DEBUG;
  }

Code:

This is my server:

//requirements...
const socket = require("./server/socket");

const app = express();
const server = http.createServer(app);
const port = process.env.PORT || 3000;

//middlewares...
//routes...
//database connection...

socket(server);

server.listen(port);
console.log("Server started on: " + port);

My socket setup:

const socketIO = require("socket.io");

const socket = server => {
    const io = socketIO(server);
    const chat = io.of("/chat");

    chat.on("connection", client => {
        console.log("User started chat!");

        client.on("disconnect", () => {
            console.log("User left chat!");
        });

        client.on("sendMessage", msg => {
            const data = msg;
            client.broadcast.emit("incomingMessage", { data });
        });
    });
};

module.exports = socket;

React component that using Socket.IO:

const _ChatBox = ({ props }) => {
    const [connection] = useState(io("/chat"));

    useEffect(() => {
        connection.on("incomingMessage", message => {
            //receive message...
        });
    }, []);

    const sendMessageToSocket = data => {
        connection.emit("sendMessage", data);
    };

    return (
        /* JSX here */
    );
};

What I want:

I want to know if there is any problem with my code. When I deploy my app to Heroku, is there any extra setup I have to do on Heroku to make my app working with Socket.IO?

Body:
After spending hours researching and reviewing my code, I have figured out why my app is not working on Heroku. That because the client using dotenv module, and I setup it in webpack.config.js:

//...requirements
const dotenv = require("dotenv");
const webpack = require("webpack");

module.exports = {
    //...configs
    plugins: [
        //...other plugins
        new webpack.DefinePlugin({
            "process.env": JSON.stringify(dotenv.parsed)
        })
    ]
};

Then when I deploy my app on Heroku, Heroku will build my client from source code and server will look for the frontend part in dist folder. The client now can't find the .env file on Heroku so it can't load the environment variables that causes it to throw error.

I removed dotenv because I don't need it now.


问:
how to test my login page using phpunit in codeigniter?
I am new in phpUnit,my project is in codeigniter and i am using netbeans IDE 8.2 ,my os is windows10,i am trying to test my web site ,Now i have problem that how to test my login page?
i have tried this below code:

class Welcome_test extends TestCase{
    public function addDataProvider(){
        return array(array('email'=>'abc@gmail.com','pass'=>'cdef'));
     }
    /*** @dataProvider addDataProvider*/
    public function test_login(){
        $output = $this->post('Login/submitlogin');
        $this->assertContains('Product List',$output);
    }

}
```

i was expecting result should pass but unfortunately i am getting this error

Welcome_test::test_login()

  PHP Fatal error occured.

  PHP Fatal error(s) occured, test results can be incomplete!

  Review Output window for full output.'

答:
Login page or any page so far can be tested using functional or acceptance testing using codeception.

unit testing helps us know if we are getting right assertions to our databases providing right data but they do not help us properly test the nature and functionality of page.

so I suggest you to use acceptance tests for this purpose.

Body:
I am new in phpUnit,my project is in codeigniter and i am using netbeans IDE 8.2 ,my os is windows10,i am trying to test my web site ,Now i have problem that how to test my login page?
i have tried this below code:

class Welcome_test extends TestCase{
    public function addDataProvider(){
        return array(array('email'=>'abc@gmail.com','pass'=>'cdef'));
     }
    /*** @dataProvider addDataProvider*/
    public function test_login(){
        $output = $this->post('Login/submitlogin');
        $this->assertContains('Product List',$output);
    }

}

i was expecting result should pass but unfortunately i am getting this error

Welcome_test::test_login()

  PHP Fatal error occured.

  PHP Fatal error(s) occured, test results can be incomplete!

  Review Output window for full output.'


问:
Parsing binary file with mixed structure
I need to parse a binary ABIF file in PHP. There is the structure: https://projects.nfstc.org/workshops/resources/articles/ABIF_File_Format.pdf

The file consists three logical parts. Header is fixed at the first 128 bytes, other two parts can be anywhere, it means even between some text or XML data. How to parse this two parts? Any ideas?

I found many solutions how to parse ABIF on other languages: Python, C, C++, VB, Perl, JavaScript but nothing at all about PHP. There is the example in JS: https://github.com/eamitchell/ab1ToJSON

There is the file example: https://sourceforge.net/p/seqmanager/code-0/1/tree//cgi-bin/ABIveiw/test.ab1

```<code>$filename = 'files/2p_Pro_1.ab1';
$handle = fopen($filename, 'rb');
$size = filesize ($filename);
$data = fread($handle, 6);
$data = unpack('a4header/nver', $data);
$result['head'] = $data;

$data = fread($handle, 28);
$data = unpack('a4name/Nnumber/nelementtype/nelementsize/Nnumelements/Ndatasize/Ndataoffset/Ndatahandle', $data);
$result['dir'] = $data;

var_dump($result);
</code>```

It returns:

```<code>Array (
    [head] => Array (
        [header] => ABIF
        [ver] => 101
    )
    [dir] => Array (
        [name] => tdir
        [number] => 1
        [elementtype] => 1023
        [elementsize] => 28
        [numelements] => 165
        [datasize] => 4928
        [dataoffset] => 245963
        [datahandle] => 0
    )
)
</code>```

答: The dataoffset tells where the directory starts. Each directory entry has another dataoffset field that tells where its data starts.

Body:
I need to parse a binary ABIF file in PHP. There is the structure: https://projects.nfstc.org/workshops/resources/articles/ABIF_File_Format.pdf

The file consists three logical parts. Header is fixed at the first 128 bytes, other two parts can be anywhere, it means even between some text or XML data. How to parse this two parts? Any ideas?

I found many solutions how to parse ABIF on other languages: Python, C, C++, VB, Perl, JavaScript but nothing at all about PHP. There is the example in JS: https://github.com/eamitchell/ab1ToJSON

There is the file example: https://sourceforge.net/p/seqmanager/code-0/1/tree//cgi-bin/ABIveiw/test.ab1

$filename = 'files/2p_Pro_1.ab1';
$handle = fopen($filename, 'rb');
$size = filesize ($filename);
$data = fread($handle, 6);
$data = unpack('a4header/nver', $data);
$result['head'] = $data;

$data = fread($handle, 28);
$data = unpack('a4name/Nnumber/nelementtype/nelementsize/Nnumelements/Ndatasize/Ndataoffset/Ndatahandle', $data);
$result['dir'] = $data;

var_dump($result);

It returns:

Array (
    [head] => Array (
        [header] => ABIF
        [ver] => 101
    )
    [dir] => Array (
        [name] => tdir
        [number] => 1
        [elementtype] => 1023
        [elementsize] => 28
        [numelements] => 165
        [datasize] => 4928
        [dataoffset] => 245963
        [datahandle] => 0
    )
)


问:
How to see arguments when creating a new class?
When creating a new class or method I used to be able to see the parameters needed. But, now they don't come up anymore. How do I view parameters when creating a class?

Running the latest windows version.

```<code>public class Main {

    public static void main(String args[]) {
        Case theCase = new Case("Default", "Corsair", "500W");
    }
}

public class Case {

    private String model;
    private String manufacturer;
    private String powerSupply;

    public Case(String model, String manufacturer, String powerSupply,) {
       this.model = model;
       this.manufacturer = manufacturer;
       this.powerSupply = powerSupply;

    }

    public void pressPowerButton() {
        System.out.println("Power button pressed");
    }

    public String getModel() {
        return model;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public String getPowerSupply() {
        return powerSupply;
    }
}
</code>```

When making theCase I can't see what my parameters are and have to move to the "Case" class back and forth

答: Nevermind in order to see the parameters as you type you must type them while in the editor without moving your cursor.</p>

Body:
When creating a new class or method I used to be able to see the parameters needed. But, now they don't come up anymore. How do I view parameters when creating a class?

Running the latest windows version.

public class Main {

    public static void main(String args[]) {
        Case theCase = new Case("Default", "Corsair", "500W");
    }
}

public class Case {

    private String model;
    private String manufacturer;
    private String powerSupply;

    public Case(String model, String manufacturer, String powerSupply,) {
       this.model = model;
       this.manufacturer = manufacturer;
       this.powerSupply = powerSupply;

    }

    public void pressPowerButton() {
        System.out.println("Power button pressed");
    }

    public String getModel() {
        return model;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public String getPowerSupply() {
        return powerSupply;
    }
}

When making theCase I can't see what my parameters are and have to move to the "Case" class back and forth


问:
PHP Nusoap Webservice on HTTPS with a C# client
I use nusoap library to create a webservice with PHP (like this : http://www.sanity-free.org/125/php_webservices_and_csharp_dotnet_soap_clients.html).
The client is in C#.
With http, all works normally.

With https, I have an error in visual studio when trying to add the service :
"There was an error dowloading https://service?wsdl". The request was aborted : could not create SSL/TLS secure channel.

Is this linked to schemas on http ?

<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://services/soap/SimpleService" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://services/soap/SimpleService">

There is no https in the targetNamespace... I don't know how to solve that in the code.

Thanks for help !

答:
I had the same problem, as it was working fine on http, but wasn't on https. Just to share my whole programming path here, to help others.

I originally followed this tutorial: php webservice with nusoap and c#. Only thing he doesn't say in the tutorial is that you should put all the php code in one php file (but ok, it might be just straightforward really, so no real complaints on that one).

I first tried this on http, and I was happy it worked, but later I had to move to ssl, and since I was testing it on my local server I had a selfsigned certificate, and I got the error: "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

I googled and finally found the solution on this link here: damir dobric blog

Basically you should add the line:

```<code>ServicePointManager.ServerCertificateValidationCallback +=
new System.Net.Security.RemoteCertificateValidationCallback(
customXertificateValidation);
</code>```

and add the implementation of the function customXertificateValidation to return true (this is what I did for testing purposes).

ContentLicense: CC BY-SA 2.5

Body:
I had the same problem, as it was working fine on http, but wasn't on https. Just to share my whole programming path here, to help others.

I originally followed this tutorial: php webservice with nusoap and c#. Only thing he doesn't say in the tutorial is that you should put all the php code in one php file (but ok, it might be just straightforward really, so no real complaints on that one).

I first tried this on http, and I was happy it worked, but later I had to move to ssl, and since I was testing it on my local server I had a selfsigned certificate, and I got the error: "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

I googled and finally found the solution on this link here: damir dobric blog

Basically you should add the line:

ServicePointManager.ServerCertificateValidationCallback +=
new System.Net.Security.RemoteCertificateValidationCallback(
customXertificateValidation);

and add the implementation of the function customXertificateValidation to return true (this is what I did for testing purposes).


问:
Render javascript file with inline javascript
I am having the following *.js file:

```<code>var text = `
This is a test ${Company.Name}.
`

module.exports = {
    text
};
</code>```

My main file looks like the following:

```<code>const Company = {}
Company.Name = "Apple"
</code>```

Basically, I would like to "render" the text and fill it with my predefined variable.

Any suggestions what is the best way to "load" the text file in the main file?

I appreciate your replies!

答:
in *.js file

```<code>var text = (Company)=> `This is a test ${Company.Name}.`

module.exports = {
    text
};
</code>```

in main.js file

```<code>let { text }  = require('./hello');

const Company = {}
Company.Name = "Apple"

let try = text(Company);
console.log(try):
</code>```

Body:
I am having the following *.js file:

var text = `
This is a test ${Company.Name}.
`

module.exports = {
    text
};

My main file looks like the following:

const Company = {}
Company.Name = "Apple"

Basically, I would like to "render" the text and fill it with my predefined variable.

Any suggestions what is the best way to "load" the text file in the main file?

I appreciate your replies!

Body:
in *.js file

var text = (Company)=> `This is a test ${Company.Name}.`

module.exports = {
    text
};

in main.js file

let { text }  = require('./hello');

const Company = {}
Company.Name = "Apple"

let try = text(Company);
console.log(try):


问:
Facebook messenger platform: generic template with quick replies
I was looking at some pretty popular bots like "The Guardian" and i noticed that whenever you get a generic template reply from it it also displays some quick reply buttons (see the photo attached). How did "The Guardian Bot" achieve this? How he combined quick replies and a generic template? It must be two messages involved.

答:
This worked for me in Dialogflow, return similar Json Object in backend to achieve the result: </p>

```<code> {
  "facebook": {
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"generic",
        "elements":[
           {
            "title":"Welcome!",
            "image_url":"https://petersfancybrownhats.com/company_image.png",
            "subtitle":"We have the right hat for everyone.",
            "default_action": {
              "type": "web_url",
              "url": "https://petersfancybrownhats.com/view?item=103",
              "webview_height_ratio": "tall"
            },
            "buttons":[
              {
                "type":"web_url",
                "url":"https://petersfancybrownhats.com",
                "title":"View Website"
              },{
                "type":"postback",
                "title":"Start Chatting",
                "payload":"DEVELOPER_DEFINED_PAYLOAD"
              }
            ]
          }
        ]
      }
    },
     "quick_replies":[
      {
        "content_type":"text",
        "title":"Search",
        "payload":"<POSTBACK_PAYLOAD>",
        "image_url":"http://example.com/img/red.png"
      },
      {
        "content_type":"location"
      }
    ]
  }
}
</code>```

Body:
This worked for me in Dialogflow, return similar Json Object in backend to achieve the result:

 {
  "facebook": {
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"generic",
        "elements":[
           {
            "title":"Welcome!",
            "image_url":"https://petersfancybrownhats.com/company_image.png",
            "subtitle":"We have the right hat for everyone.",
            "default_action": {
              "type": "web_url",
              "url": "https://petersfancybrownhats.com/view?item=103",
              "webview_height_ratio": "tall"
            },
            "buttons":[
              {
                "type":"web_url",
                "url":"https://petersfancybrownhats.com",
                "title":"View Website"
              },{
                "type":"postback",
                "title":"Start Chatting",
                "payload":"DEVELOPER_DEFINED_PAYLOAD"
              }
            ]
          }
        ]
      }
    },
     "quick_replies":[
      {
        "content_type":"text",
        "title":"Search",
        "payload":"<POSTBACK_PAYLOAD>",
        "image_url":"http://example.com/img/red.png"
      },
      {
        "content_type":"location"
      }
    ]
  }
}


问:
filter by key in javascript
I would like to filter by key in javascript.

I have a ajax function , on passing id, will result obj1 in success one after other.
I would like to combine all results by key and push to single object.
How to do the following in javascript.

```<code>var id =["trans", "fund"]
setTimeout(()=>{
      id.map((e)=>this.static(e))
    }, 2000)

static(id){
var li = $.ajax({
           url: "/en",
          method: 'get',
          global: false,
          async: false,
          data: {
            providers: id
          },
          success: function (data) {
            return data;
          }
        }).responseText;
  var obj1=data; //I need to combine and store data in expected output format
}

//on first call
var obj1={
  country: "SG",
  trans: [{
    rate: 20,
    members: 100
  }]
}
//on second call
var obj1={
  country: "TH",
  fund: [{
    rate: 20,
    members: 100
  }]
}

</code>```

Expected Output:

```<code>var result ={
  trans: [{
    rate: 20,
    members: 100
  }],
  fund: [{
    rate: 20,
    members: 100
  }]
}
</code>```

答:
Try this:

var id =["trans", "fund"];
var result = {};
//on first call
var obj1={
    country: "SG",
    trans: [{
        rate: 20,
        members: 100
    }]
}
result = getObj(result,obj1);
//on second call
var obj1={
    country: "TH",
    fund: [{
        rate: 20,
        members: 100
    }]
}
result = getObj(result,obj1);
console.log(result);

function getObj(result,obj){
    for (let i = 0; i < id.length; i++) {
        if (obj[id[i]]) {
            result[id[i]] =  obj[id[i]];
            return result;
        }
    }
    return result;
}```

Title: filter by key in javascript

Body:
I would like to filter by key in javascript.

I have a ajax function , on passing id, will result obj1 in success one after other.
I would like to combine all results by key and push to single object.
How to do the following in javascript.

var id =["trans", "fund"]
setTimeout(()=>{
      id.map((e)=>this.static(e))
    }, 2000)

static(id){
var li = $.ajax({
           url: "/en",
          method: 'get',
          global: false,
          async: false,
          data: {
            providers: id
          },
          success: function (data) {
            return data;
          }
        }).responseText;
  var obj1=data; //I need to combine and store data in expected output format
}

//on first call
var obj1={
  country: "SG",
  trans: [{
    rate: 20,
    members: 100
  }]
}
//on second call
var obj1={
  country: "TH",
  fund: [{
    rate: 20,
    members: 100
  }]
}

Expected Output:

var result ={
  trans: [{
    rate: 20,
    members: 100
  }],
  fund: [{
    rate: 20,
    members: 100
  }]
}


问:
How can I feature-detect CSS filters?
In some browsers, including Chrome stable, you can do this:

```<code>h3 {
  -webkit-filter: grayscale(1);
  filter: grayscale(1);
}
</code>```

And wouldn’t you know it, the h1 will be rendered completely in grayscale. Everything old is new again.

Anyway — does anyone know of any way to feature-detect for this?

I need to be able to apply other styles if the filter won’t work.

答:
You can now use CSS' build-in @support to conditionally apply styles. Note that the browser support for @support is good but not perfect. This is a nice article explaining how it works with several examples: https://iamsteve.me/blog/entry/feature-detection-with-css

For instance, you can do something like this (see it live):

```<code>@supports (filter: grayscale(1)) or (-webkit-filter: grayscale(1)) {
  h3 {
    -webkit-filter: grayscale(1);
    filter: grayscale(1);
  }
}

@supports not (filter: grayscale(1)) and not not (-webkit-filter: grayscale(1)) {
  h3 {
    color: #808080;
  }
}
</code>```

Title: How can I feature-detect CSS filters?

Body:
In some browsers, including Chrome stable, you can do this:

h3 {
  -webkit-filter: grayscale(1);
  filter: grayscale(1);
}

And wouldn’t you know it, the h1 will be rendered completely in grayscale. Everything old is new again.

Anyway — does anyone know of any way to feature-detect for this?

I need to be able to apply other styles if the filter won’t work.

Body:
You can now use CSS' build-in @support to conditionally apply styles. Note that the browser support for @support is good but not perfect. This is a nice article explaining how it works with several examples: https://iamsteve.me/blog/entry/feature-detection-with-css

For instance, you can do something like this (see it live):

@supports (filter: grayscale(1)) or (-webkit-filter: grayscale(1)) {
  h3 {
    -webkit-filter: grayscale(1);
    filter: grayscale(1);
  }
}

@supports not (filter: grayscale(1)) and not not (-webkit-filter: grayscale(1)) {
  h3 {
    color: #808080;
  }
}


问:
How can I repeat a nunjucks block in the same file?
I'm working on a static site that is using gulp and nunjucks.

For example, say I have a block for an article's title that I want to display in two places on the same page. How would I implement that?

I saw in jinja that you could do something like {% set title_s %}{% block title %}MY DEFAULT TITLE{% endblock %}{% endset %} in another stackoverflow post, but that doesn't seem to work in nunjucks. I just get the text "undefined" when I use {{title_s}}.

Edit: I ended up just using {% set title %}PAGE TITLE{% endset %} in the child template. This means I can use that value inside the parent template. I'm not sure now which way is proper.

答:
I am not sure i understand your question clearly, but see this example if that what you are asking for

article.njk

```<code>{% macro articleMacro(title, headerOnly = false) %}
  <article>
    {% if headerOnly %}
      <header>{{title}}</header>
    {% else %}
      <header>{{title}}</header>
      <p>article body</p>
      <footer></footer>
    {% endif %}
  </article>
{% endmacro %}
</code>```

page.njk

```<code>{% import "article.njk" as article %}

// this will render full article
{{ article('header one', false) }}

// this will render article header
{{ article('header one', true) }}
</code>```

Body:
I am not sure i understand your question clearly, but see this example if that what you are asking for

article.njk

{% macro articleMacro(title, headerOnly = false) %}
  <article>
    {% if headerOnly %}
      <header>{{title}}</header>
    {% else %}
      <header>{{title}}</header>
      <p>article body</p>
      <footer></footer>
    {% endif %}
  </article>
{% endmacro %}

page.njk

{% import "article.njk" as article %}

// this will render full article
{{ article('header one', false) }}

// this will render article header
{{ article('header one', true) }}


问:
How can I link a static library to a source used as an native library in NDK Android Build
I want to include a static library built for the C++ code provided, I tried linking the static library, but build cannot link the library. I am getting the following error:

undefined reference to 'Test_C_Interface'

I am new to Java NDK/cmake. Please help me with this

This is the cpp code used(native-lib.cpp)

    extern int Test_C_Interface();

    extern "C" JNIEXPORT jstring JNICALL

    Java_com_example_tvgui_MainActivity_stringFromJNI(JNIEnv *env, jobject /* this */) {
        std::string hello = "From C++";

        int ret_val;

        ret_val = Test_C_Interface();

        if(ret_val == 100){
            hello = "From C";
        }
       return env->NewStringUTF(hello.c_str());
    }
```

<p>This is the c code used to make the static library(sample.c/libsample.a)[Library built using NDK ARM-v7a ToolChain]</p>

<pre class="lang-c prettyprint-override"><code>    #include<stdio.h>

    int Test_C_Interface(void)
    {
        printf("Inside C Library\n");

        return 100;
    }
</code>```

This is the cmake file

```<code>    cmake_minimum_required(VERSION 3.4.1)

    add_library(
            native-lib
            SHARED
            native-lib.cpp)

    find_library(
            log-lib
            log)

    target_link_libraries(
            native-lib
            ${log-lib}
            ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/libsample.a)
</code>```

I need to build a application from like :

```<code>libsample.a
             \
              \
                ====libnative-lib.so + Java = .apk
              /
             /
native-lib.cpp
</code>```

UPDATE
The problem was solved by modifying the code as below :

```<code>extern "C"{
     int Test_C_Interface();
}
</code>```

答:
You should put your libsample.a into directories in below structure according to your ABI, e.g.

```<code>libs
│   ├── x86/libsample.a
│   ├── x86_64/libsample.a
│   ├── arm64-v8a/libsample.a
│   ├── armeabi-v7a/libsample.a

</code>```

And then update your cmakefile as below:

```<code>target_link_libraries(
            native-lib
            ${log-lib}
            ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/<ANDROID_ABI>/libsample.a)
</code>```

Please ensure that ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs is a correct path.

For the CMake variables, e.g. ANDROID_ABI, you can refer to Android NDK path variable in CMake build tool chain

Body:
I want to include a static library built for the C++ code provided, I tried linking the static library, but build cannot link the library. I am getting the following error:

undefined reference to 'Test_C_Interface'

I am new to Java NDK/cmake. Please help me with this

This is the cpp code used(native-lib.cpp)

    extern int Test_C_Interface();

    extern "C" JNIEXPORT jstring JNICALL

    Java_com_example_tvgui_MainActivity_stringFromJNI(JNIEnv *env, jobject /* this */) {
        std::string hello = "From C++";

        int ret_val;

        ret_val = Test_C_Interface();

        if(ret_val == 100){
            hello = "From C";
        }
       return env->NewStringUTF(hello.c_str());
    }

This is the c code used to make the static library(sample.c/libsample.a)[Library built using NDK ARM-v7a ToolChain]

    #include<stdio.h>

    int Test_C_Interface(void)
    {
        printf("Inside C Library\n");

        return 100;
    }

This is the cmake file

    cmake_minimum_required(VERSION 3.4.1)

    add_library(
            native-lib
            SHARED
            native-lib.cpp)

    find_library(
            log-lib
            log)

    target_link_libraries(
            native-lib
            ${log-lib}
            ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/libsample.a)

I need to build a application from like :

libsample.a
             \
              \
                ====libnative-lib.so + Java = .apk
              /
             /
native-lib.cpp

UPDATE
The problem was solved by modifying the code as below :

extern "C"{
     int Test_C_Interface();
}

Body:
You should put your libsample.a into directories in below structure according to your ABI, e.g.

libs
│   ├── x86/libsample.a
│   ├── x86_64/libsample.a
│   ├── arm64-v8a/libsample.a
│   ├── armeabi-v7a/libsample.a

And then update your cmakefile as below:

target_link_libraries(
            native-lib
            ${log-lib}
            ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/<ANDROID_ABI>/libsample.a)

Please ensure that ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs is a correct path.

For the CMake variables, e.g. ANDROID_ABI, you can refer to Android NDK path variable in CMake build tool chain


问:
HTML comments break down
I have a page that is generated which inserts an HTML comment near the top of the page.  Inside the comment is a *nix-style command.

```<code><!-- command --option value --option2 value2 --option3 -->
</code>```

This comment breaks the page completely.  What is wrong with the comment to cause this to happen, and why is this the case?

答:
Comments at the top of the page before  will throw IE into quirks mode, which could explain why the page breaks, if that's where your comment appears.

For more information, check out the "Triggering different rendering modes" on this wikipedia page

Title: HTML comments break down

Body:
I have a page that is generated which inserts an HTML comment near the top of the page.  Inside the comment is a *nix-style command.

This comment breaks the page completely.  What is wrong with the comment to cause this to happen, and why is this the case?

Body:
Comments at the top of the page before <html> will throw IE into quirks mode, which could explain why the page breaks, if that's where your comment appears.

For more information, check out the "Triggering different rendering modes" on this wikipedia page


问:
Can you view an aggregate changeset in git? If so, how?
In Subversion you can specify a range of versions to get an aggregate view of a series of commits.  Is this possible in git?  If so, how?</p>

答:
You can pass ranges of revisions using the .. (and ...) operator.

```<code>git diff 6d0918...HEAD
</code>```

instead of giving (abbreviated) SHA hashes, you can also denote revisions relative to branches and tags:

```<code>git diff HEAD~4 # shows the diff from the last four commits to the current one
</code>```

Have a look at the chapter "Specifying Revisions" in the git-rev-parse manual page

OwnerDisplayName: Teflon Ted

LastEditorDisplayName: Teflon Ted

Body:
You can pass ranges of revisions using the .. (and ...) operator.

git diff 6d0918...HEAD

instead of giving (abbreviated) SHA hashes, you can also denote revisions relative to branches and tags:

git diff HEAD~4 # shows the diff from the last four commits to the current one

Have a look at the chapter "Specifying Revisions" in the git-rev-parse manual page

OwnerDisplayName: pilif


问:
C# Manage windows events
I would like to delete an event from the Windows event log using C#.

Can anyone point me in the right direction of how to achieve this?

答: I don't think it's possible. Take a look at the System.Diagnostics namespace and tis EventLog* classes for additional documentation.</p>

OwnerDisplayName: Jade M

Title: C# Manage windows events

OwnerDisplayName: siz


问:
how to keep adding files to files array with multiple button clicks
Basically, i have an input element of type file:

```<code><form method="post" action="upload-page.php" enctype="multipart/form-data">
    <input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>
</code>```

Now for each click on the file button, the files array only keeps track of the files selected for current click, how do i make so it keeps track of all the files for every click?

答: You must add more input elements to the page.

Body:
Basically, i have an input element of type file:

<form method="post" action="upload-page.php" enctype="multipart/form-data">
    <input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>

Now for each click on the file button, the files array only keeps track of the files selected for current click, how do i make so it keeps track of all the files for every click?


答:
You can do this by using a while loop until the required conditions are met.

Here is a simple example of how you could do this:

```<code>int totalWoodChucks = 0;
int days = 0;

const int MAXDAYS = 10;
const int MINDAYS = 1;
const int MAXWOOD = 100;
const int MINWOOD = 1;

bool validWoodChucks = false;
while(!validWoodChucks)
{
    Console.Write("Enter number of woodchucks for this simulation (1-100): ");
    int.TryParse(Console.ReadLine(), out totalWoodChucks);

    if(totalWoodChucks > MAXWOOD || totalWoodChucks < MINWOOD)
    {
        Console.WriteLine("Invalid woodchucks. Please try again.");
    }
    else
    {
        validWoodChucks = true;
    }

}

bool validDays = false;
while(!validDays)
{
    Console.Write("Enter number of days for this simulation (1-10): ");
    int.TryParse(Console.ReadLine(), out days);
    if (days > MAXDAYS || days < MINDAYS)
    {
        Console.WriteLine("Invalid days. Please try again.");
    }
    else
    {
        validDays = true;
    }
}

Console.WriteLine("Wood chucks: " + totalWoodChucks);
Console.WriteLine("Days: " + days);

Console.ReadLine();
</code>```

Example when used:

```<code>Enter number of woodchucks for this simulation (1-100): -10
Invalid woodchucks. Please try again.
Enter number of woodchucks for this simulation (1-100): 50
Enter number of days for this simulation (1-10): 20
Invalid days. Please try again.
Enter number of days for this simulation (1-10): 10
Wood chucks: 50
Days: 10
</code>```

Title: How can I make sure that a certain line is printed only when the if statement is met in a while-loop

Body:
I am trying to print an if statement but only if the values are correct and they meet the requirements. However, the if statement is inside of a while loop and even though it asks the user to try again when the value in the if statement is not correct it still prints out the numbers the user inputted the first time in the WriteLine outside of the if statement (where it says SIMULATION). I want it to ask the user to try again until the values meet the required standard of the if statement.

namespace Woodchuck
{
    class Program
    {
        static void Main(string[] args)
        {
            string restart = "Y";

            while (restart == "Y")
            {
                int totalWoodChucks = 0;
                int days = 0;

                const int MAXDAYS = 10;
                const int MINDAYS = 1;
                const int MAXWOOD = 100;
                const int MINWOOD = 1;

                Write("Enter number of woodchucks for this simulation (1-100): ");
                int.TryParse(ReadLine(), out totalWoodChucks);

                if (totalWoodChucks > MAXWOOD || totalWoodChucks < MINWOOD)
                {
                    WriteLine("Please try again");
                }

                Write("Enter number of days for this simulation (1-10): ");
                int.TryParse(ReadLine(), out days);
                if (days > MAXDAYS || days < MINDAYS)
                {
                    WriteLine("Please try again");
                }

                WriteLine($"SIMULATION 1: {totalWoodChucks} woodchucks over {days} days");

                Write("\nTo run another simulation, enter 'Y':");
                restart = ReadLine().ToUpper();

            }
            //Debug pause
            WriteLine("Press any key to wrap it up...");
        }
    }
}

Body:
You can do this by using a while loop until the required conditions are met.

Here is a simple example of how you could do this:

int totalWoodChucks = 0;
int days = 0;

const int MAXDAYS = 10;
const int MINDAYS = 1;
const int MAXWOOD = 100;
const int MINWOOD = 1;

bool validWoodChucks = false;
while(!validWoodChucks)
{
    Console.Write("Enter number of woodchucks for this simulation (1-100): ");
    int.TryParse(Console.ReadLine(), out totalWoodChucks);

    if(totalWoodChucks > MAXWOOD || totalWoodChucks < MINWOOD)
    {
        Console.WriteLine("Invalid woodchucks. Please try again.");
    }
    else
    {
        validWoodChucks = true;
    }

}

bool validDays = false;
while(!validDays)
{
    Console.Write("Enter number of days for this simulation (1-10): ");
    int.TryParse(Console.ReadLine(), out days);
    if (days > MAXDAYS || days < MINDAYS)
    {
        Console.WriteLine("Invalid days. Please try again.");
    }
    else
    {
        validDays = true;
    }
}

Console.WriteLine("Wood chucks: " + totalWoodChucks);
Console.WriteLine("Days: " + days);

Console.ReadLine();

Example when used:

Enter number of woodchucks for this simulation (1-100): -10
Invalid woodchucks. Please try again.
Enter number of woodchucks for this simulation (1-100): 50
Enter number of days for this simulation (1-10): 20
Invalid days. Please try again.
Enter number of days for this simulation (1-10): 10
Wood chucks: 50
Days: 10


问:
How to include the same element (nbr. or symbol) between the elements of a list in scheme?
I am getting started with the basics of scheme right now. I came across an exercise where a procedure needs to be created which adds the element x that can be symbols or numbers in between the elements of a given list.

For example:

The procedure (tech 7 (list 23 24 25)) should result in (23 7 24 7 25).

So far I have only a theoretical approach. It aims at splitting up the given list in car and cdr and to combine cdr with a newly created list of the element x thru append.

```<code>(define (tech x lst)
  (if (null? lst)
      '()
      (cons (car lst) (append (cons ('x) (* 'x (length cdr lst))
                                    (cdr lst)))))
</code>```

Can anybody tell me what is wrong with the code? It only returns errors...

答:
There are several issues with your code:

You should avoid using append, most of the time using cons is the correct approach for building a list.

Why are you multiplying 'x by the length of the list? that doesn't make any sense.

You're confusing the symbol 'x with the value of the x variable.

You need to consider a third case for handling the last element, because the list doesn't end in x.

Last but not least: you forgot to call the recursion! it'll never work if you omit a call to tech inside tech.

This fixes all the issues, most of the original code had to be rewritten:

```<code>(define (tech x lst)
  (cond ((null? lst) '())       ; base case: empty list
        ((null? (cdr lst)) lst) ; list with a single element
        (else (cons (car lst)   ; this is how we add
                    (cons x     ; the element to the list
                          (tech x (cdr lst))))))) ; advance recursion
</code>```

It works as expected:

```<code>(tech 7 '(23 24 25))
=> '(23 7 24 7 25)
</code>```

Body:
I am getting started with the basics of scheme right now. I came across an exercise where a procedure needs to be created which adds the element x that can be symbols or numbers in between the elements of a given list.

For example:

The procedure (tech 7 (list 23 24 25)) should result in (23 7 24 7 25).

So far I have only a theoretical approach. It aims at splitting up the given list in car and cdr and to combine cdr with a newly created list of the element x thru append.

(define (tech x lst)
  (if (null? lst)
      '()
      (cons (car lst) (append (cons ('x) (* 'x (length cdr lst))
                                    (cdr lst)))))

Can anybody tell me what is wrong with the code? It only returns errors...

Body:
There are several issues with your code:

You should avoid using append, most of the time using cons is the correct approach for building a list.

Why are you multiplying 'x by the length of the list? that doesn't make any sense.

You're confusing the symbol 'x with the value of the x variable.

You need to consider a third case for handling the last element, because the list doesn't end in x.

Last but not least: you forgot to call the recursion! it'll never work if you omit a call to tech inside tech.

This fixes all the issues, most of the original code had to be rewritten:

(define (tech x lst)
  (cond ((null? lst) '())       ; base case: empty list
        ((null? (cdr lst)) lst) ; list with a single element
        (else (cons (car lst)   ; this is how we add
                    (cons x     ; the element to the list
                          (tech x (cdr lst))))))) ; advance recursion

It works as expected:

(tech 7 '(23 24 25))
=> '(23 7 24 7 25)


问:
Kafka Client Timeout of 60000ms expired before the position for partition could be determined
I'm trying to connect Flink to a Kafka consumer

I'm using Docker Compose to build 4 containers zookeeper, kafka, Flink JobManager and Flink TaskManager.

For zookeeper and Kafka I'm using wurstmeister images, and for Flink I'm using the official image.

docker-compose.yml

```<code>version: '3.1'
services:
  zookeeper:
    image: wurstmeister/zookeeper:3.4.6
    hostname: zookeeper
    expose:
      - "2181"
    ports:
      - "2181:2181"

  kafka:
    image: wurstmeister/kafka:2.11-2.0.0
    depends_on:
      - zookeeper
    ports:
      - "9092:9092"
    hostname: kafka
    links:
      - zookeeper
    environment:
      KAFKA_ADVERTISED_HOST_NAME: kafka
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_PORT: 9092
      KAFKA_CREATE_TOPICS: 'pipeline:1:1:compact'

  jobmanager:
    build: ./flink_pipeline
    depends_on:
      - kafka
    links:
      - zookeeper
      - kafka
    expose:
      - "6123"
    ports:
      - "8081:8081"
    command: jobmanager
    environment:
      JOB_MANAGER_RPC_ADDRESS: jobmanager
      BOOTSTRAP_SERVER: kafka:9092
      ZOOKEEPER: zookeeper:2181

  taskmanager:
    image: flink
    expose:
      - "6121"
      - "6122"
    links:
      - jobmanager
      - zookeeper
      - kafka
    depends_on:
      - jobmanager
    command: taskmanager
    # links:
    #   - "jobmanager:jobmanager"
    environment:
      JOB_MANAGER_RPC_ADDRESS: jobmanager
</code>```

And When I submit a simple job to Dispatcher the Job fails with the following error:

```<code>org.apache.kafka.common.errors.TimeoutException: Timeout of 60000ms expired before the position for partition pipeline-0 could be determined
</code>```

My Job code is:

```<code>public class Main {
    public static void main( String[] args ) throws Exception
    {
        // get the execution environment
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // get input data by connecting to the socket
        Properties properties = new Properties();
        String bootstrapServer = System.getenv("BOOTSTRAP_SERVER");
        String zookeeperServer = System.getenv("ZOOKEEPER");

        if (bootstrapServer == null) {
            System.exit(1);
        }

        properties.setProperty("zookeeper", zookeeperServer);
        properties.setProperty("bootstrap.servers", bootstrapServer);
        properties.setProperty("group.id", "pipeline-analysis");

        FlinkKafkaConsumer kafkaConsumer = new FlinkKafkaConsumer<String>("pipeline", new SimpleStringSchema(), properties);
        // kafkaConsumer.setStartFromGroupOffsets();
        kafkaConsumer.setStartFromLatest();

        DataStream<String> stream = env.addSource(kafkaConsumer);

        // Defining Pipeline here

        // Printing Outputs
        stream.print();

        env.execute("Stream Pipeline");
    }
}
</code>```

答:
I know I'm late to the party but I had the exact same error. In my case, I was not setting up TopicPartitions correctly. My topic had 2 partitions and my producer was producing messages just fine, but it's the spark streaming application, as my consumer, that wasn't really starting and giving up after 60 secs complaining the same error.

Wrong code that I had -

```<code>List<TopicPartition> topicPartitionList = Arrays.asList(new topicPartition(topicName, Integer.parseInt(numPartition)));
</code>```

Correct code -

```<code>List<TopicPartition> topicPartitionList = new ArrayList<TopicPartition>();

for (int i = 0; i < Integer.parseInt(numPartitions); i++) {
    topicPartitionList.add(new TopicPartition(topicName, i));
}
</code>```

Body:
I'm trying to connect Flink to a Kafka consumer

I'm using Docker Compose to build 4 containers zookeeper, kafka, Flink JobManager and Flink TaskManager.

For zookeeper and Kafka I'm using wurstmeister images, and for Flink I'm using the official image.

docker-compose.yml

version: '3.1'
services:
  zookeeper:
    image: wurstmeister/zookeeper:3.4.6
    hostname: zookeeper
    expose:
      - "2181"
    ports:
      - "2181:2181"

  kafka:
    image: wurstmeister/kafka:2.11-2.0.0
    depends_on:
      - zookeeper
    ports:
      - "9092:9092"
    hostname: kafka
    links:
      - zookeeper
    environment:
      KAFKA_ADVERTISED_HOST_NAME: kafka
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_PORT: 9092
      KAFKA_CREATE_TOPICS: 'pipeline:1:1:compact'

  jobmanager:
    build: ./flink_pipeline
    depends_on:
      - kafka
    links:
      - zookeeper
      - kafka
    expose:
      - "6123"
    ports:
      - "8081:8081"
    command: jobmanager
    environment:
      JOB_MANAGER_RPC_ADDRESS: jobmanager
      BOOTSTRAP_SERVER: kafka:9092
      ZOOKEEPER: zookeeper:2181

  taskmanager:
    image: flink
    expose:
      - "6121"
      - "6122"
    links:
      - jobmanager
      - zookeeper
      - kafka
    depends_on:
      - jobmanager
    command: taskmanager
    # links:
    #   - "jobmanager:jobmanager"
    environment:
      JOB_MANAGER_RPC_ADDRESS: jobmanager

And When I submit a simple job to Dispatcher the Job fails with the following error:

org.apache.kafka.common.errors.TimeoutException: Timeout of 60000ms expired before the position for partition pipeline-0 could be determined

My Job code is:

public class Main {
    public static void main( String[] args ) throws Exception
    {
        // get the execution environment
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // get input data by connecting to the socket
        Properties properties = new Properties();
        String bootstrapServer = System.getenv("BOOTSTRAP_SERVER");
        String zookeeperServer = System.getenv("ZOOKEEPER");

        if (bootstrapServer == null) {
            System.exit(1);
        }

        properties.setProperty("zookeeper", zookeeperServer);
        properties.setProperty("bootstrap.servers", bootstrapServer);
        properties.setProperty("group.id", "pipeline-analysis");

        FlinkKafkaConsumer kafkaConsumer = new FlinkKafkaConsumer<String>("pipeline", new SimpleStringSchema(), properties);
        // kafkaConsumer.setStartFromGroupOffsets();
        kafkaConsumer.setStartFromLatest();

        DataStream<String> stream = env.addSource(kafkaConsumer);

        // Defining Pipeline here

        // Printing Outputs
        stream.print();

        env.execute("Stream Pipeline");
    }
}

Body:
I know I'm late to the party but I had the exact same error. In my case, I was not setting up TopicPartitions correctly. My topic had 2 partitions and my producer was producing messages just fine, but it's the spark streaming application, as my consumer, that wasn't really starting and giving up after 60 secs complaining the same error.

Wrong code that I had -

List<TopicPartition> topicPartitionList = Arrays.asList(new topicPartition(topicName, Integer.parseInt(numPartition)));

Correct code -

List<TopicPartition> topicPartitionList = new ArrayList<TopicPartition>();

for (int i = 0; i < Integer.parseInt(numPartitions); i++) {
    topicPartitionList.add(new TopicPartition(topicName, i));
}


问:
Docker 1 exited with code 0 when using knex migrate
I'm getting this error

app_1

  Using environment: development app_1    Ran 1 seed

files express_app_1 exited with code 0

when executing this command on docker-compose.yml.

```<code>command: bash -c "npm run migrate && npm run seed"
</code>```

What would be an alternative way to execute this command so i can avoid the error.

docker-compose.yml

```<code># docker-compose.yml
version: "3"
services:
  app:
    build: .
    depends_on:
      - database
    ports:
      - 3000:3000
    environment:
      - HOST=database
      # name of the container for ex .*****
      # docker exec -it ***** psql -U postgres -c "create database es6knex"
      # ^ this creates the es6knex database
      - DBNAME=es6knex
    env_file:
      - .env
    command: bash -c "npm run migrate && npm run seed"

  database:
    image: postgres:9.6.8-alpine
    volumes:
      - db-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: ${DBPASS:-password}
      POSTGRES_USER: ${DBUSER:-knexuser}
      POSTGRES_DB: ${DBNAME:-es6knex}
    ports:
      - 8002:5432
    env_file:
      - .env
volumes:
  db-data:
</code>```

package.json

```<code>{
  "name": "elies6express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "./node_modules/.bin/mocha --watch --require @babel/register",
    "start": "nodemon --exec babel-node main.js",
    "migrate": "babel-node node_modules/.bin/knex migrate:latest",
    "seed": "babel-node node_modules/.bin/knex seed:run"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "bookshelf": "^0.14.2",
    "chai-http": "^4.3.0",
    "cookie-parser": "^1.4.4",
    "cors": "^2.8.5",
    "dotenv": "^8.0.0",
    "express": "^4.17.0",
    "knex": "^0.16.5",
    "morgan": "^1.9.1",
    "path": "^0.12.7",
    "pg": "^7.11.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.4.4",
    "@babel/core": "^7.4.5",
    "@babel/node": "^7.4.5",
    "@babel/preset-env": "^7.4.5",
    "@babel/register": "^7.4.4",
    "chai": "^4.2.0",
    "mocha": "^6.1.4",
    "nodemon": "^1.19.0",
    "reify": "^0.19.1",
    "request": "^2.88.0"
  }
}
</code>```

Dockerfile

```<code>FROM node:8

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 3000
CMD [ "npm", "start" ]
</code>```

答:
What you get is not really an error. Your container exists normally (code 0) because there is no running process anymore.

In your Dockerfile you correctly define a running process that would keep the container alive (npm start). But then you overwrite that in your docker-compose.yml. You should correct your command line in docker-compose.yml:

OLD

```<code>command: bash -c "npm run migrate && npm run seed"
</code>```

NEW

```<code>command: bash -c "npm run migrate && npm run seed && npm start"
</code>```

A side note for the "docker exec" command that you mention in your yml file. You can also run "docker-compose exec database psql -U ....". This way you use the service name directly instead of the container name.

Body:
I'm getting this error

app_1

  Using environment: development app_1    Ran 1 seed

files express_app_1 exited with code 0

when executing this command on docker-compose.yml.

command: bash -c "npm run migrate && npm run seed"

What would be an alternative way to execute this command so i can avoid the error.

docker-compose.yml

# docker-compose.yml
version: "3"
services:
  app:
    build: .
    depends_on:
      - database
    ports:
      - 3000:3000
    environment:
      - HOST=database
      # name of the container for ex .*****
      # docker exec -it ***** psql -U postgres -c "create database es6knex"
      # ^ this creates the es6knex database
      - DBNAME=es6knex
    env_file:
      - .env
    command: bash -c "npm run migrate && npm run seed"

  database:
    image: postgres:9.6.8-alpine
    volumes:
      - db-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: ${DBPASS:-password}
      POSTGRES_USER: ${DBUSER:-knexuser}
      POSTGRES_DB: ${DBNAME:-es6knex}
    ports:
      - 8002:5432
    env_file:
      - .env
volumes:
  db-data:

package.json

{
  "name": "elies6express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "./node_modules/.bin/mocha --watch --require @babel/register",
    "start": "nodemon --exec babel-node main.js",
    "migrate": "babel-node node_modules/.bin/knex migrate:latest",
    "seed": "babel-node node_modules/.bin/knex seed:run"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "bookshelf": "^0.14.2",
    "chai-http": "^4.3.0",
    "cookie-parser": "^1.4.4",
    "cors": "^2.8.5",
    "dotenv": "^8.0.0",
    "express": "^4.17.0",
    "knex": "^0.16.5",
    "morgan": "^1.9.1",
    "path": "^0.12.7",
    "pg": "^7.11.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.4.4",
    "@babel/core": "^7.4.5",
    "@babel/node": "^7.4.5",
    "@babel/preset-env": "^7.4.5",
    "@babel/register": "^7.4.4",
    "chai": "^4.2.0",
    "mocha": "^6.1.4",
    "nodemon": "^1.19.0",
    "reify": "^0.19.1",
    "request": "^2.88.0"
  }
}

Dockerfile

FROM node:8

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 3000
CMD [ "npm", "start" ]

Body:
What you get is not really an error. Your container exists normally (code 0) because there is no running process anymore.

In your Dockerfile you correctly define a running process that would keep the container alive (npm start). But then you overwrite that in your docker-compose.yml. You should correct your command line in docker-compose.yml:

OLD

command: bash -c "npm run migrate && npm run seed"

NEW

command: bash -c "npm run migrate && npm run seed && npm start"

A side note for the "docker exec" command that you mention in your yml file. You can also run "docker-compose exec database psql -U ....". This way you use the service name directly instead of the container name.


问:
How can I make my program still run after running once
I wrote a program which interferes with the user. However it only works once. I want my program to run until the user writes "q" or "Q". So far I wrote this:</p>

```<code>import java.util.Scanner;
public class isbn {
    public static boolean validISBN(String isbnNumber) {
        isbnNumber = isbnNumber.replace("-", "").trim();
        if (isbnNumber.length() == 10 && isbnNumber.matches("[0-9]+")) {
            int sum = 0;
            for(int i = 10; i > 0; i--) {
                if (isbnNumber.charAt(9) == 'X' && i == 1) {
                    sum += i * 10;
                } else {
                    sum += i * Character.getNumericValue(isbnNumber.charAt(10 - i));
                }
            }
            if (sum % 11 == 0) {
                System.out.println("Valid");
            } else {
                System.out.println("Invalid");
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Input ISBN Number: ");
        String isbnNumber = keyboard.next();
        validISBN(isbnNumber);
    }
}
</code>```

答:
Like others answers have said you need to use a loop that will wait for user input. You can do this by using java.util.Scanner#hasNext() method and evaluate it in a while loop.

Here is a snippet from Javadoc:

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input

And here is the actual implementation:

import java.util.Scanner;

public class Main {

public static final Scanner READER = new Scanner(System.in);

public static boolean validISBN(String isbnNumber) {

    isbnNumber = isbnNumber.replace("-", "").trim();
    if (isbnNumber.length() == 10 && isbnNumber.matches("[0-9]+"))
    {
        int sum = 0;
        for(int i = 10; i > 0; i--) {
            if (isbnNumber.charAt(9) == 'X' && i == 1) {
                sum += i * 10;
            } else {
                sum += i * Character.getNumericValue(isbnNumber.charAt(10 - i));
            }
        }
        return sum % 11 == 0;
    }
    return false;
}

public static String getISBN() {

    System.out.println("Input ISBN number: ");
    while (READER.hasNext())
    {
        String input = READER.next();
        if (input.equalsIgnoreCase("q")) {
            System.out.println("Exiting application...");
            System.exit(0);
        }
        else if (validISBN(input)) {
            System.out.println("Your ISBN has been accepted.");
            return input;
        }
        else {
            System.out.println("Invalid ISBN number, please try again: ");
        }
    }
    throw new IllegalStateException("No more tokes in user input stream");
}

public static void main(String[] args) {

    String isbn = getISBN();
}
```

}

Body:
I wrote a program which interferes with the user. However it only works once. I want my program to run until the user writes "q" or "Q". So far I wrote this:

import java.util.Scanner;
public class isbn {
    public static boolean validISBN(String isbnNumber) {
        isbnNumber = isbnNumber.replace("-", "").trim();
        if (isbnNumber.length() == 10 && isbnNumber.matches("[0-9]+")) {
            int sum = 0;
            for(int i = 10; i > 0; i--) {
                if (isbnNumber.charAt(9) == 'X' && i == 1) {
                    sum += i * 10;
                } else {
                    sum += i * Character.getNumericValue(isbnNumber.charAt(10 - i));
                }
            }
            if (sum % 11 == 0) {
                System.out.println("Valid");
            } else {
                System.out.println("Invalid");
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Input ISBN Number: ");
        String isbnNumber = keyboard.next();
        validISBN(isbnNumber);
    }
}

Body:
Like others answers have said you need to use a loop that will wait for user input. You can do this by using java.util.Scanner#hasNext() method and evaluate it in a while loop.

Here is a snippet from Javadoc:

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input

And here is the actual implementation:

import java.util.Scanner;

public class Main {

public static final Scanner READER = new Scanner(System.in);

public static boolean validISBN(String isbnNumber) {

    isbnNumber = isbnNumber.replace("-", "").trim();
    if (isbnNumber.length() == 10 && isbnNumber.matches("[0-9]+"))
    {
        int sum = 0;
        for(int i = 10; i > 0; i--) {
            if (isbnNumber.charAt(9) == 'X' && i == 1) {
                sum += i * 10;
            } else {
                sum += i * Character.getNumericValue(isbnNumber.charAt(10 - i));
            }
        }
        return sum % 11 == 0;
    }
    return false;
}

public static String getISBN() {

    System.out.println("Input ISBN number: ");
    while (READER.hasNext())
    {
        String input = READER.next();
        if (input.equalsIgnoreCase("q")) {
            System.out.println("Exiting application...");
            System.exit(0);
        }
        else if (validISBN(input)) {
            System.out.println("Your ISBN has been accepted.");
            return input;
        }
        else {
            System.out.println("Invalid ISBN number, please try again: ");
        }
    }
    throw new IllegalStateException("No more tokes in user input stream");
}

public static void main(String[] args) {

    String isbn = getISBN();
}

}


问:
how to use flashbug
How to use flashbug? Comparing the printscreens from addon page:
https://addons.mozilla.org/en-us/firefox/addon/flashbug/

with printscreen that I made:
http://img42.imageshack.us/img42/7686/flbug.jpg
http://img840.imageshack.us/img840/1255/flbug2.jpg

On my printscreens flashbug looks empty. Additionally, I made a statement trace("aaa"); and nothing appears in tab "Trace". So obviously I must be doing something wrong.

Or maybe there is a different/easier way to debug flash from a browser.

答:
i'm always using firebug to print debug messages from flash. there is a ExternalInterface class in actionscript3, which can be used make to calls to the firebug console, like this:

```<code>ExternalInterface.call('console.log', 'hello');
</code>```

you can even pass whole objects from actionscript, ie:

```<code>var object = {message:'hello'}
ExternalInterface.call('console.log', object);
</code>```

see the docs on ExternalInterface for further explanations.

Title: how to use flashbug

Body:
i'm always using firebug to print debug messages from flash. there is a ExternalInterface class in actionscript3, which can be used make to calls to the firebug console, like this:

ExternalInterface.call('console.log', 'hello');

you can even pass whole objects from actionscript, ie:

var object = {message:'hello'}
ExternalInterface.call('console.log', object);

see the docs on ExternalInterface for further explanations.


问:
Count a foreach loop and create new element in php
I'm working on a Mega Menu for WooCommerce Product Category. I'm able to get the list of all Subcategories using the code below;

```<code>$parent_id = 37; //ID of the Parent Category
$subCat_of_parent = get_terms('product_cat',array('child_of' => $parent_id));
</code>```

Then used in a html structure as below;

```<code><div class="row">
    <div class="col-md-6">
        <ul>
        <?php
        foreach ($subCat_of_parent as $subcat) {
            ?>
            <li>
                <a href="<?php echo get_category_link($subcat->term_id); ?>"><?php echo $subcat->name; ?></a>
            </li>
            <?php
        }
         ?>
        </ul>
    </div>
</div>
</code>```

This worked by getting all the list of subcategory of the parent category in this format;

```<code><div class="row">
    <div class="col-md-6">
        <ul>
           <li><a>1st subcategory</a></li>
           <li><a>2nd subcategory</a></li>
           <li><a>3rd subcategory</a></li>
           <li><a>4th subcategory</a></li>
           <li><a>5th subcategory</a></li>
           <li><a>6th subcategory</a></li>
        </ul>
    <div>
</div>
</code>```

what i want to achieve is after the 3rd subcategory, it should break and continue on a new column, so that i can get something like this;

```<code><div class="row">
    <div class="col-md-6">
        <ul>
           <li><a>1st subcategory</a></li>
           <li><a>2nd subcategory</a></li>
           <li><a>3rd subcategory</a></li>
        </ul>
    <div>

    <div class="col-md-6">
        <ul>
           <li><a>4th subcategory</a></li>
           <li><a>5th subcategory</a></li>
           <li><a>6th subcategory</a></li>
        </ul>
    <div>
</div>
</code>```

How can i achieve this? Thanks for your help in advance

答:
Below code is working, You can use this.</p>

```<code><?php
$subCat_of_parent = array('1st sub', '2nd sub', '3rd sub', '4th sub', '5 sub', '6 sub', '7 sub');
$subCat_of_parent = array_chunk($subCat_of_parent, 3);
?>
<div class="row">
    <?php
    foreach ($subCat_of_parent as $subcats) {
    ?>
        <div class="col-md-6">
            <ul>
            <?php
            foreach ($subcats as $subcat) {
                ?>
                <li><a href="#"><?php echo $subcat; ?></a></li>
                <?php
            }
            ?>
            </ul>
        </div>
    <?php
    }
    ?>
</div>
</code>```

Body:
I'm working on a Mega Menu for WooCommerce Product Category. I'm able to get the list of all Subcategories using the code below;

$parent_id = 37; //ID of the Parent Category
$subCat_of_parent = get_terms('product_cat',array('child_of' => $parent_id));

Then used in a html structure as below;

        <?php
        foreach ($subCat_of_parent as $subcat) {
            ?>

                <a href="<?php echo get_category_link($subcat->term_id); ?>"><?php echo $subcat->name; ?>

            <?php
        }
         ?>

This worked by getting all the list of subcategory of the parent category in this format;

1st subcategory

2nd subcategory

3rd subcategory

4th subcategory

5th subcategory

6th subcategory

what i want to achieve is after the 3rd subcategory, it should break and continue on a new column, so that i can get something like this;

1st subcategory

2nd subcategory

3rd subcategory

4th subcategory

5th subcategory

6th subcategory

How can i achieve this? Thanks for your help in advance

Body:
Below code is working, You can use this.

<?php
$subCat_of_parent = array('1st sub', '2nd sub', '3rd sub', '4th sub', '5 sub', '6 sub', '7 sub');
$subCat_of_parent = array_chunk($subCat_of_parent, 3);
?>
<div class="row">
    <?php
    foreach ($subCat_of_parent as $subcats) {
    ?>
        <div class="col-md-6">
            <ul>
            <?php
            foreach ($subcats as $subcat) {
                ?>
                <li><a href="#"><?php echo $subcat; ?></a></li>
                <?php
            }
            ?>
            </ul>
        </div>
    <?php
    }
    ?>
</div>


问:
Can't clone git project with Netbeans IDE, but CLI works
I'm trying to work with GIT (confluence) using NetBeans as IDE.
I correctly (I think) added connection string:

```<code>http://git-repo:7990/scm/riw/php-project.git
</code>```

with username and password fields configured with my credentials

I followed the steps in this Netbeans official video

But once I get tho what I suppose is the last step I get this message:

http://dds@git-repo:7990/scm/riw/php-project.git Starting read stage without written request data pending is not supported

On my local system I find the project folder with inner .git folder, but there are no project files.

with CLI running:

```<code>git clone http://git-repo:7990/scm/riw/php-project.git
</code>```

I'm asked for username and password then all data is downloaded.

My question is: what should I do to make netbeans git plugin work as supposed to?

I'm running the last version of netbeans: Apache NetBeans IDE 11.0 (Build incubator-netbeans-release-404-on-20190319)

My OS is Xubuntu, with Oracle Java 12 and php 7.2

答:
As a workaround, since the CLI git clone does work:

clone it manually,

then import the project in your NetBeans, and do check the fetch/pull/push works that way.

May be it is a certificate issue to be accepted.

Body:
I'm trying to work with GIT (confluence) using NetBeans as IDE.
I correctly (I think) added connection string:

http://git-repo:7990/scm/riw/php-project.git

with username and password fields configured with my credentials

I followed the steps in this Netbeans official video

But once I get tho what I suppose is the last step I get this message:

http://dds@git-repo:7990/scm/riw/php-project.git Starting read stage without written request data pending is not supported

On my local system I find the project folder with inner .git folder, but there are no project files.

with CLI running:

git clone http://git-repo:7990/scm/riw/php-project.git

I'm asked for username and password then all data is downloaded.

My question is: what should I do to make netbeans git plugin work as supposed to?

I'm running the last version of netbeans: Apache NetBeans IDE 11.0 (Build incubator-netbeans-release-404-on-20190319)

My OS is Xubuntu, with Oracle Java 12 and php 7.2


问:
How to block SEMRUSH bots in IIS
We are receiving tons of web request from SEMRUSH bots
https://imgur.com/bdiX45Q
How to block them in IIS?</p>

答:
The easiest method might be to add SEMrush to your robots.txt file.  If you need more info about how this works, check Wikipedia for "Robots exclusion standard".

Per the SEMrush site (https://www.semrush.com/bot/), to block SEMrushBot from crawling your site for web graph of links, add the following lines to your robots.txt:

```<code>User-agent: SemrushBot
Disallow: /
</code>```

Hope this helps.

Title: How to block SEMRUSH bots in IIS

Body:
The easiest method might be to add SEMrush to your robots.txt file.  If you need more info about how this works, check Wikipedia for "Robots exclusion standard".

Per the SEMrush site (https://www.semrush.com/bot/), to block SEMrushBot from crawling your site for web graph of links, add the following lines to your robots.txt:

User-agent: SemrushBot
Disallow: /

Hope this helps.