问:
Convert XML/HTML Entities into Unicode String in Python
I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?

For example:

I get back:

```<code>ǎ
</code>```

which represents an "ǎ" with a tone mark.  In binary, this is represented as the 16 bit 01ce.  I want to convert the html entity into the value  u'\u01ce'

答:
Not sure why the Stack Overflow thread does not include the ';' in the search/replace (i.e. lambda m: '&#%d*;*') If you don't, BeautifulSoup can barf because the adjacent character can be interpreted as part of the HTML code (i.e. &#39B for &#39Blackout).

This worked better for me:

```<code>import re
from BeautifulSoup import BeautifulSoup

html_string='<a href="/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL"title="">'Blackout in a can; on some shelves despite ban</a>'

hexentityMassage = [(re.compile('&#x([^;]+);'),
lambda m: '&#%d;' % int(m.group(1), 16))]

soup = BeautifulSoup(html_string,
convertEntities=BeautifulSoup.HTML_ENTITIES,
markupMassage=hexentityMassage)
</code>```

The int(m.group(1), 16) converts the number (specified in base-16) format back to an integer.

m.group(0) returns the entire match, m.group(1) returns the regexp capturing group

Basically using markupMessage is the same as:

html_string = re.sub('&#x([^;]+);', lambda m: '&#%d;' % int(m.group(1), 16), html_string)

OwnerDisplayName: Cristian

Body:
I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?

For example:

I get back:

ǎ

which represents an "ǎ" with a tone mark.  In binary, this is represented as the 16 bit 01ce.  I want to convert the html entity into the value  u'\u01ce'

Body:
Not sure why the Stack Overflow thread does not include the ';' in the search/replace (i.e. lambda m: '&#%d*;*') If you don't, BeautifulSoup can barf because the adjacent character can be interpreted as part of the HTML code (i.e. &#39B for &#39Blackout).

This worked better for me:

import re
from BeautifulSoup import BeautifulSoup

html_string='<a href="/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL"title="">&#x27;Blackout in a can; on some shelves despite ban</a>'

hexentityMassage = [(re.compile('&#x([^;]+);'),
lambda m: '&#%d;' % int(m.group(1), 16))]

soup = BeautifulSoup(html_string,
convertEntities=BeautifulSoup.HTML_ENTITIES,
markupMassage=hexentityMassage)

The int(m.group(1), 16) converts the number (specified in base-16) format back to an integer.

m.group(0) returns the entire match, m.group(1) returns the regexp capturing group

Basically using markupMessage is the same as:

html_string = re.sub('&#x([^;]+);', lambda m: '&#%d;' % int(m.group(1), 16), html_string)


来源: stackexchange

问:
asp.net core route values to base controller and optionally override actions
I have a base controller where most of my api logic sits. I want to standardise the api verbs and I want this base controller to handle most request by default unless I inherit from this controller and override the specific action.

Given a path like this: "/api/Socks/Get?apiKey=1" I am able to do something like this:

```<code>[Route("api/[controller]/[action]")]
public class RestDbApiController : Controller
{
    [HttpGet]
    public virtual async Task<JsonResult> Get(string apiKey = null) {

.....

public class SockController : RestDbApiController
{}
</code>```

This works okay - ie. the request is routed the action on the base controller. The issue is that I have to declare the SockController, otherwise the request will not route.

I would like to be able to route all requests to "/api/xxxxx" to the base controller without having to declare any other controllers. Please let me know if there is any way to do this.

Why do I want to do this?
I'm trying to make a generic controller with external scripted definitions. Depending on the controller name it would read the script from a similarly named script file. I want to be able to just add the script file to a directory and have it work just like that without having to make any declarations in the code

答:
I agree with @Chris, but if you want to have only one controller, you could omit the "controller name" part from the routing definition. For example, the following requests will be mapped to below action method

```<code>/api/Socks/Get?apiKey=1
/api/OtherSocks/Get?apiKey=1
</code>```

and name parameter will be filled as "Socks", "OtherSocks" respectively:

```<code>public class RestDbApiController : Controller
{
    [HttpGet]
    [Route("api/{name}/[action]")]
    public virtual async Task<JsonResult> Get(string name, string apiKey = null)
    {
        ...
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a base controller where most of my api logic sits. I want to standardise the api verbs and I want this base controller to handle most request by default unless I inherit from this controller and override the specific action.

Given a path like this: "/api/Socks/Get?apiKey=1" I am able to do something like this:

[Route("api/[controller]/[action]")]
public class RestDbApiController : Controller
{
    [HttpGet]
    public virtual async Task<JsonResult> Get(string apiKey = null) {

.....

public class SockController : RestDbApiController
{}

This works okay - ie. the request is routed the action on the base controller. The issue is that I have to declare the SockController, otherwise the request will not route.

I would like to be able to route all requests to "/api/xxxxx" to the base controller without having to declare any other controllers. Please let me know if there is any way to do this.

Why do I want to do this?
I'm trying to make a generic controller with external scripted definitions. Depending on the controller name it would read the script from a similarly named script file. I want to be able to just add the script file to a directory and have it work just like that without having to make any declarations in the code

Body:
I agree with @Chris, but if you want to have only one controller, you could omit the "controller name" part from the routing definition. For example, the following requests will be mapped to below action method

/api/Socks/Get?apiKey=1
/api/OtherSocks/Get?apiKey=1

and name parameter will be filled as "Socks", "OtherSocks" respectively:

public class RestDbApiController : Controller
{
    [HttpGet]
    [Route("api/{name}/[action]")]
    public virtual async Task<JsonResult> Get(string name, string apiKey = null)
    {
        ...
    }
}


问:
Does Spark Dataframe aplies the transformations against DB?
When I get a table with PySpark

df1 = session.read.jdbc(url=self.url,
                        table=self.table,
                        properties={"driver": self.driver,
                                    "user": self.user,
                                    "password": self.password})
```

<p>or</p>

<pre class="lang-py prettyprint-override"><code>df1 = sql.read.format("com.databricks.spark.redshift")
                .options(url=self.url,
                        query=self.table,
                        user=self.user,
                        password=self.password,
                        tempdir="s3://path/data/").load()
</code>```

and then I apply some transformations like joins and groupBy

df3 = df1.join(df2, df1.id == df2.id)
df_res = df3.groupBy("id").agg({'tax': 'sum'})
```

is that done against the DB?
If yes, what is the way to do that in memory?

答:
It is not. While Spark can push down simple projections and selections (details depend on a particular data source implementation) it doesn't apply heavy processing against database, unless it is explicitly instructed to in a supported data source.

For example with jdbc you pass a subquery  as the table argument, and with com.databricks.spark.redshift you can use query option.

With the first snippet (jdbc) Spark will read all the required data (after applying possible projections and selections) using a single executor, in the second snippet the result of the initial query (plus projections and selections) to S3 and read it from there in parallel. In both cases Spark should be able to push down projection (id, tax).

After that Spark will process data locally inside the cluster, this includes join and aggregation.

Body:
When I get a table with PySpark

df1 = session.read.jdbc(url=self.url,
                        table=self.table,
                        properties={"driver": self.driver,
                                    "user": self.user,
                                    "password": self.password})

or

df1 = sql.read.format("com.databricks.spark.redshift")
                .options(url=self.url,
                        query=self.table,
                        user=self.user,
                        password=self.password,
                        tempdir="s3://path/data/").load()

and then I apply some transformations like joins and groupBy

df3 = df1.join(df2, df1.id == df2.id)
df_res = df3.groupBy("id").agg({'tax': 'sum'})

is that done against the DB?
If yes, what is the way to do that in memory?


问:
AWS S3 - Calculate File Hash with Lambda
Is it possible to use a lambda function for every PUT request to a S3 bucket to calculate the file hash? And yes, I know, that S3 uses etags.</p>

答:
You can activate S3 Event Notifications for every PUT event. These events can be delivered to a lambda where you can hash the file.

Events can be enabled under the S3 Bucket -> Properties -> Events

There you can check the 'PUT' event type and set the lambda as event receiver.


问:
how to start QTimer so that the GUI does not hangs-RestartStoppedProcess()-code
I have made new QTimer object in my class's ctor. When the application starts the timer also starts with the specified time. This timer keeps a track of all the process IDs and if finds that a particular process-id is not active(killed from task manager) then it restarts that particular process. Now the issue is my application lags a-bit due to this QTimer object and only after the timeout, the application becomes smooth. But after 5 seconds the timer starts again and the application starts lagging again. What is the best alternative to start a QTimer object apart from ctor of a class?</p>

```<code>qTimer = new QTimer(0);

connect(qTimer, SIGNAL(timeout()), this, SLOT(RestartStoppedProcess()), Qt::DirectConnection);
connect(qTimer, SIGNAL(destroyed()), qTimer, SLOT(deleteLater()), Qt::DirectConnection);

qTimer->setTimerType(Qt::VeryCoarseTimer);
qTimer->start(5000);

void ProcessMonitor::RestartStoppedProcess()
{
    try
    {
        QProcess *objMonitorProcess = new QProcess(this);
        connect(objMonitorProcess, SIGNAL(finished(int,QProcess::ExitStatus)), objMonitorProcess, SLOT(deleteLater()));
        for(int i = 0; i < ui->twShowProcess->rowCount(); i++)
        {
#ifdef Q_WS_LIN
            //            objMonitorProcess->start("pidof", QStringList() << (ui->twShowProcess->item(i, 0)->text()), QIODevice::ReadOnly);
            objMonitorProcess->start("pidof "+ (ui->twShowProcess->item(i, 0)->text()), QIODevice::ReadOnly);
#elif Q_WS_WIN
            QString cmd("wmic process where ");
            QString qszFilters("\"processid=\'");
            QString qszSubFilters = qszFilters.append(ui->twShowProcess->item(i, 1)->text().append("\'").append("\"").append(" get name"));
            cmd.append(qszSubFilters);
            objMonitorProcess->start(cmd.toStdString().c_str(), QIODevice::ReadOnly);
#else
            QString qszProcessName = ui->twShowProcess->item(i, 0)->text().split(".").takeFirst();
            objMonitorProcess->start("pgrep", QStringList() << qszProcessName, QIODevice::ReadOnly);
#endif
            if((objMonitorProcess->waitForStarted(4000) == true) && (objMonitorProcess->state() == QProcess::Running))
            {
                if(objMonitorProcess->waitForFinished(3000) == false)
                    continue;
                else
                {
                    QString qszProcessStatus = ui->twShowProcess->item(i, 3)->text();
                    if(qszProcessStatus.compare("Running") == 0)
                    {
                        QString qszStandardOutput, qszStandardError;
                        qszStandardOutput.clear(); qszStandardError.clear();
                        qszStandardOutput = QString(objMonitorProcess->readAllStandardOutput());
                        qszStandardError = QString(objMonitorProcess->readAllStandardError());
                        if(qszStandardError.simplified().compare("No Instance(s) Available.", Qt::CaseInsensitive) == 0 && qszStandardOutput.simplified().isEmpty() == true)
                        {
                            ui->twShowProcess->selectRow(i);
                            if(ui->twShowProcess->selectedItems().at(0)->text().compare("LTtagdb.exe", Qt::CaseInsensitive) == 0 ||
                                    ui->twShowProcess->selectedItems().at(0)->text().compare("LTmessagebroker.exe", Qt::CaseInsensitive) == 0)
                                this->StopAllApplicationsForcefully();
                            else
                                this->on_actionStop_triggered();

                            if(this->ptrobjContextMenu->isVisible())
                                this->ptrobjContextMenu->close();

                            ui->twShowProcess->clearSelection();

                            if(mobj_ProcessLogMap.mobj_ProcessAndLogMapping.contains(ui->twShowProcess->item(i, 8)->text()) == true)
                            {
                                mobj_ProcessLogMap.mobj_ProcessAndLogMapping.remove(ui->twShowProcess->item(i, 8)->text());
                                mobj_ProcessLogMap.mobj_ProcessAndLogMapping.insert(ui->twShowProcess->item(i, 8)->text(), QString(""));
                            }
                            else
                                this->mobj_ProcessLogMap.mobj_ProcessAndLogMapping.insert(ui->twShowProcess->item(i, 8)->text(), QString(""));
                        }

                        if(ui->twShowProcess->item(i, 0)->text() == "LThistdb.exe")
                        {
                            if(IsServiceRunning(QString("LThistdb.exe")) == false)
                                this->on_actionStopPostgreSQL_DB_Server_triggered();
                        }
                        qszStandardOutput.clear();
                    }
                }
            }
            else
                break;
#ifdef Q_WS_WIN
            cmd.clear();
            qszFilters.clear();
            qszSubFilters.clear();
#endif
        }
    }
    catch(QProcess::ProcessError pError)
    {
        QMessageBox objCrashExit;
        objCrashExit.information(this, "Crashed", "Process error returned code: " + QString::number(pError));
    }
    catch(...)
    {
        QMessageBox objCrashExit;
        objCrashExit.information(this, "Unknown Crash", "Unknown crash exit-child process may not be running correctly!");
    }
}
</code>```

答:
QTimer runs in the UI thread so it blocks your UI if it takes a long time to execute. A simple solution is to just run your "processing" stuff in another background thread, the easiest way to do that in Qt might be using QtConcurrent::run like this from your timeout slot called from the QTimer:

```<code>QtConcurrent::run(yourProcessingFunction);
</code>```

You can obviously create your own Thread and use the build in QTimer from QObject::startTimer(...), but that is more work usually.

Body:
I have made new QTimer object in my class's ctor. When the application starts the timer also starts with the specified time. This timer keeps a track of all the process IDs and if finds that a particular process-id is not active(killed from task manager) then it restarts that particular process. Now the issue is my application lags a-bit due to this QTimer object and only after the timeout, the application becomes smooth. But after 5 seconds the timer starts again and the application starts lagging again. What is the best alternative to start a QTimer object apart from ctor of a class?

qTimer = new QTimer(0);

connect(qTimer, SIGNAL(timeout()), this, SLOT(RestartStoppedProcess()), Qt::DirectConnection);
connect(qTimer, SIGNAL(destroyed()), qTimer, SLOT(deleteLater()), Qt::DirectConnection);

qTimer->setTimerType(Qt::VeryCoarseTimer);
qTimer->start(5000);

void ProcessMonitor::RestartStoppedProcess()
{
    try
    {
        QProcess *objMonitorProcess = new QProcess(this);
        connect(objMonitorProcess, SIGNAL(finished(int,QProcess::ExitStatus)), objMonitorProcess, SLOT(deleteLater()));
        for(int i = 0; i < ui->twShowProcess->rowCount(); i++)
        {
#ifdef Q_WS_LIN
            //            objMonitorProcess->start("pidof", QStringList() << (ui->twShowProcess->item(i, 0)->text()), QIODevice::ReadOnly);
            objMonitorProcess->start("pidof "+ (ui->twShowProcess->item(i, 0)->text()), QIODevice::ReadOnly);
#elif Q_WS_WIN
            QString cmd("wmic process where ");
            QString qszFilters("\"processid=\'");
            QString qszSubFilters = qszFilters.append(ui->twShowProcess->item(i, 1)->text().append("\'").append("\"").append(" get name"));
            cmd.append(qszSubFilters);
            objMonitorProcess->start(cmd.toStdString().c_str(), QIODevice::ReadOnly);
#else
            QString qszProcessName = ui->twShowProcess->item(i, 0)->text().split(".").takeFirst();
            objMonitorProcess->start("pgrep", QStringList() << qszProcessName, QIODevice::ReadOnly);
#endif
            if((objMonitorProcess->waitForStarted(4000) == true) && (objMonitorProcess->state() == QProcess::Running))
            {
                if(objMonitorProcess->waitForFinished(3000) == false)
                    continue;
                else
                {
                    QString qszProcessStatus = ui->twShowProcess->item(i, 3)->text();
                    if(qszProcessStatus.compare("Running") == 0)
                    {
                        QString qszStandardOutput, qszStandardError;
                        qszStandardOutput.clear(); qszStandardError.clear();
                        qszStandardOutput = QString(objMonitorProcess->readAllStandardOutput());
                        qszStandardError = QString(objMonitorProcess->readAllStandardError());
                        if(qszStandardError.simplified().compare("No Instance(s) Available.", Qt::CaseInsensitive) == 0 && qszStandardOutput.simplified().isEmpty() == true)
                        {
                            ui->twShowProcess->selectRow(i);
                            if(ui->twShowProcess->selectedItems().at(0)->text().compare("LTtagdb.exe", Qt::CaseInsensitive) == 0 ||
                                    ui->twShowProcess->selectedItems().at(0)->text().compare("LTmessagebroker.exe", Qt::CaseInsensitive) == 0)
                                this->StopAllApplicationsForcefully();
                            else
                                this->on_actionStop_triggered();

                            if(this->ptrobjContextMenu->isVisible())
                                this->ptrobjContextMenu->close();

                            ui->twShowProcess->clearSelection();

                            if(mobj_ProcessLogMap.mobj_ProcessAndLogMapping.contains(ui->twShowProcess->item(i, 8)->text()) == true)
                            {
                                mobj_ProcessLogMap.mobj_ProcessAndLogMapping.remove(ui->twShowProcess->item(i, 8)->text());
                                mobj_ProcessLogMap.mobj_ProcessAndLogMapping.insert(ui->twShowProcess->item(i, 8)->text(), QString(""));
                            }
                            else
                                this->mobj_ProcessLogMap.mobj_ProcessAndLogMapping.insert(ui->twShowProcess->item(i, 8)->text(), QString(""));
                        }

                        if(ui->twShowProcess->item(i, 0)->text() == "LThistdb.exe")
                        {
                            if(IsServiceRunning(QString("LThistdb.exe")) == false)
                                this->on_actionStopPostgreSQL_DB_Server_triggered();
                        }
                        qszStandardOutput.clear();
                    }
                }
            }
            else
                break;
#ifdef Q_WS_WIN
            cmd.clear();
            qszFilters.clear();
            qszSubFilters.clear();
#endif
        }
    }
    catch(QProcess::ProcessError pError)
    {
        QMessageBox objCrashExit;
        objCrashExit.information(this, "Crashed", "Process error returned code: " + QString::number(pError));
    }
    catch(...)
    {
        QMessageBox objCrashExit;
        objCrashExit.information(this, "Unknown Crash", "Unknown crash exit-child process may not be running correctly!");
    }
}

Body:
QTimer runs in the UI thread so it blocks your UI if it takes a long time to execute. A simple solution is to just run your "processing" stuff in another background thread, the easiest way to do that in Qt might be using QtConcurrent::run like this from your timeout slot called from the QTimer:

QtConcurrent::run(yourProcessingFunction);

You can obviously create your own Thread and use the build in QTimer from QObject::startTimer(...), but that is more work usually.


问:
How can I declare an empty variable?
Here's my code:

```<code>private void button1_Click(object sender, EventArgs e)
    {
        var api = RiotApi.GetInstance("KEY");

        try
        {
            var game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
        }

        catch (RiotSharpException ex)
        {
            throw;
        }

        foreach (var player in game.Participants) // Can't find game variable
        {

        }
    }
</code>```

I can't call game.Participants in my foreach loop because i initialize game inside the try statement. I can't initialize game outside the try statement either though because to do that i would have to give it a temporary value and I don't know what kind of value it will be.

Is there a way to declare a variable as null? Or is there potentially a different way to solve this?

答:
Could you do something like this? I dont know what type your GetCurrentGame retuns from the api so I just used GameType as a placeholder.

```<code>private void button1_Click(object sender, EventArgs e)
{
    var api = RiotApi.GetInstance("KEY");

    GameType game = new GameType();

    try
    {
        game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
    }

    catch (RiotSharpException ex)
    {
        throw;
    }

    if(game == null || !game.Participants.Any()) return;

    foreach (var player in game.Participants) // Can't find game variable
    {

    }
}
</code>```

Title: How can I declare an empty variable?

Body:
Here's my code:

private void button1_Click(object sender, EventArgs e)
    {
        var api = RiotApi.GetInstance("KEY");

        try
        {
            var game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
        }

        catch (RiotSharpException ex)
        {
            throw;
        }

        foreach (var player in game.Participants) // Can't find game variable
        {

        }
    }

I can't call game.Participants in my foreach loop because i initialize game inside the try statement. I can't initialize game outside the try statement either though because to do that i would have to give it a temporary value and I don't know what kind of value it will be.

Is there a way to declare a variable as null? Or is there potentially a different way to solve this?

Body:
Could you do something like this? I dont know what type your GetCurrentGame retuns from the api so I just used GameType as a placeholder.

private void button1_Click(object sender, EventArgs e)
{
    var api = RiotApi.GetInstance("KEY");

    GameType game = new GameType();

    try
    {
        game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
    }

    catch (RiotSharpException ex)
    {
        throw;
    }

    if(game == null || !game.Participants.Any()) return;

    foreach (var player in game.Participants) // Can't find game variable
    {

    }
}


问:
Automatic/Programmatically enable Apps Scripts Addon's on Google Docs
I'm searching for this like crazy and I just can't find a answer.

Imagine this. I have a "master" account. Using the Docs API I will grant access to users to some documents. But I need my addon enabled in every file. The users that will have access to the documents are not under my organization G Suite or anything. They are random gmail users.

Is there any way to do it? (besides of doing it manually) I couldn't find it in the documentation.

答:
It's not possible to disable an add-on, but an alternate solution is to create a service model inside your add-on. Maintain a DB of users that have installed your add-on, using this you can develop a logic which user is allowed to use an add-on.

This is by far the best solution I can think of.


问:
Clarity needed: subscribing to router events Aurelia (Typescript)
I am attempting to change the title tag of a page dynamically based on the params of the provided URL. I am doing this by subscribing to the "router:navigation:success" (or "complete") event for the Aurelia router.

This works fine should the page life cycle be completed from start to finish, however, when the URL is changed on the same page (using this.router.navigateToRoute) it was on before, the events I subscribed to does not fire and thus the title tag does not get changed.

For example:

I navigate to /needs/volunteer. The title reads All Volunteering Opportunities

On this page, a selection in a set of dropdowns gets made and using this.router.navigateToRoute the url is changed to /needs/volunteer/city-abc. The title tag still reads All Volunteering Opportunities as the event I subscribed to did not fire.

Should I hit enter on the URL bar with the URL pointing to /needs/volunteer/city-abc, the title tag will read Volunteering Opportunities in City ABC. This is what I expected to happen.

Is there a way to subscribe to an event which points to this.router.navigateToRoute?

The reason for having the above mentioned functionality as we have it at the moment is that when we load the page with URL params, we will automatically set the associated dropdown to the selected value. This also allows people to share the URL and thus the page content.

Thanks in advance for any help.

Edit:

I noticed that for this.router.navigateToRoute the option for trigger: false/true exist. I it is currently set to false and then the router displays the functionality as discribed above.

If I set trigger: true, I get the desired effect, however I notice a complete page reload happens at that point.

I obviously don't want this to happen, so I am still looking at how to subscribe to an event related to this.router.navigateToRoute.

答: Simple answer to the solution was to emit/publish the router:navigation:complete event after having completed the this.router.navigateToRoute method.


问:
Method is not returning CSV file - Java
I am trying to read a  HashMap and write to a CSV file. I am using CSVPrinter, but my method is not returning a CSV file.

This is the code I use:
Edited Code

```<code>   import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVPrinter;

public class SJV{
    public File writeCSV(Map featureSet) throws IOException{

        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
        Map<String, Integer> map = featureSet;
        File temp = File.createTempFile("tempfile", ".tmp");
        FileWriter fs = new FileWriter(temp);

        CSVPrinter csvFilePrinter = new CSVPrinter(fs, csvFileFormat);
        //csvFilePrinter.printRecord(FILE_HEADER);

        csvFilePrinter.printRecord(map.keySet().toArray());
        csvFilePrinter.printRecord(map.values().toArray());

csvFilePrinter.close();
fs.close();

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

This is the test I have:

```<code>public void testWriteCSV() throws IOException {
    SJV sj = new  SJV();

    HashMap<String, Integer> hmap = new HashMap<String, Integer>();
    hmap.put("Feature1", 1);
    hmap.put("Feature2", 2);
    File fs = sj.writeCSV(hmap);

    if (fs.exists()){
        Scanner input = new Scanner(fs );

        while (input.hasNextLine())
        {
           System.out.println(input.nextLine());
        }
        input.close();
    }
</code>```

I really don't understand why the method is not returning a CSV file.

答:
Try this (In this code I have changed the format from .tmp to .csv)

One problem was we were not closing the csvFilePrinter -> csvFilePrinter.close() and what I understood from the question is that the user is expecting a CSV file extension , so , I have used .csv extension while writting it .
:

```<code>    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;

    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVPrinter;

    public class TestMain {

        public static void main(String args[]) {

            HashMap<String, Integer> hmap = new HashMap<String, Integer>();
            hmap.put("Feature11", 1);
            hmap.put("Feature22", 2);
            CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.lineSeparator());
            Map<String, Integer> map = hmap;
            File temp;
            try {
                temp = File.createTempFile("tempfile", ".csv");
                FileWriter fs = new FileWriter(temp);

                CSVPrinter csvFilePrinter = new CSVPrinter(fs, csvFileFormat);
                csvFilePrinter.printRecord(map.keySet().toArray());
                csvFilePrinter.printRecord(map.values().toArray());
                csvFilePrinter.close();

                System.out.println(" temp " + temp);

                if (temp.exists()) {
                    Scanner input = new Scanner(temp);

                    while (input.hasNextLine()) {
                        System.out.println(input.nextLine());
                    }
                    input.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
</code>```

Edited as per the suggestions in comment (This code works for me and here is the sample output) :

```<code> temp C:\Users\<MY USERNAME>\AppData\Local\Temp\tempfile7124969351872886823.csv
Feature11,Feature22
1,2
</code>```

Title: Method is not returning CSV file - Java

Body:
I am trying to read a  HashMap and write to a CSV file. I am using CSVPrinter, but my method is not returning a CSV file.

This is the code I use:
Edited Code

   import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVPrinter;

public class SJV{
    public File writeCSV(Map featureSet) throws IOException{

        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
        Map<String, Integer> map = featureSet;
        File temp = File.createTempFile("tempfile", ".tmp");
        FileWriter fs = new FileWriter(temp);

        CSVPrinter csvFilePrinter = new CSVPrinter(fs, csvFileFormat);
        //csvFilePrinter.printRecord(FILE_HEADER);

        csvFilePrinter.printRecord(map.keySet().toArray());
        csvFilePrinter.printRecord(map.values().toArray());

csvFilePrinter.close();
fs.close();

        return  temp;
    }
}

This is the test I have:

public void testWriteCSV() throws IOException {
    SJV sj = new  SJV();

    HashMap<String, Integer> hmap = new HashMap<String, Integer>();
    hmap.put("Feature1", 1);
    hmap.put("Feature2", 2);
    File fs = sj.writeCSV(hmap);

    if (fs.exists()){
        Scanner input = new Scanner(fs );

        while (input.hasNextLine())
        {
           System.out.println(input.nextLine());
        }
        input.close();
    }

I really don't understand why the method is not returning a CSV file.

Body:
Try this (In this code I have changed the format from .tmp to .csv)

One problem was we were not closing the csvFilePrinter -> csvFilePrinter.close() and what I understood from the question is that the user is expecting a CSV file extension , so , I have used .csv extension while writting it .
:

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;

    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVPrinter;

    public class TestMain {

        public static void main(String args[]) {

            HashMap<String, Integer> hmap = new HashMap<String, Integer>();
            hmap.put("Feature11", 1);
            hmap.put("Feature22", 2);
            CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.lineSeparator());
            Map<String, Integer> map = hmap;
            File temp;
            try {
                temp = File.createTempFile("tempfile", ".csv");
                FileWriter fs = new FileWriter(temp);

                CSVPrinter csvFilePrinter = new CSVPrinter(fs, csvFileFormat);
                csvFilePrinter.printRecord(map.keySet().toArray());
                csvFilePrinter.printRecord(map.values().toArray());
                csvFilePrinter.close();

                System.out.println(" temp " + temp);

                if (temp.exists()) {
                    Scanner input = new Scanner(temp);

                    while (input.hasNextLine()) {
                        System.out.println(input.nextLine());
                    }
                    input.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

Edited as per the suggestions in comment (This code works for me and here is the sample output) :

 temp C:\Users\<MY USERNAME>\AppData\Local\Temp\tempfile7124969351872886823.csv
Feature11,Feature22
1,2


问:
Jump to method signature from code inside the method, or find out in which method the cursor is currently
I am doing reverse engineering of code that someone else wrote. When I search for all references of a variable or method and click on one of the results it beams my cursor right away on the line of code where it is used (which is a brilliant feature). Visual Studio shows me the class where this variable or method is used but not the method. The problem is that sometimes I end up in a huge method deep within, and the only thing I really need is the name of this cursed method.

Question: Is there a simple way to jump to the signature of the method in which the cursor is situated? Or any other way to find it out? (Besides scrolling dozens of pages of code upwards and likely missing it)

答:
Following the advice by Andrea I did a little research. Combined with this answer the outcome is this shortcut series:

Press Cntrl + F2 this will shift the focus to the dropdown menues above the code.

press 2 times Tab which will navigate to the dropdown menue for class elements as @Andrea suggested,

and hit ENTER to confirm the selection, which will automatically jump with the cursor to the signature of the method!


问:
Importing Excel data into SQL Server and converting to DateTime
guys,

I've got some datetime data in an Excel file, formatted appropriately for SQL Server datetime conversion (yyyy-mm-dd hh:mm:ss:000). Unfortunately, when I try to import the data into an SQL field of type DateTime, I get these error messages:

```<code>Error 0xc02020c5: Data Flow Task 1: Data conversion failed while converting column "Datetime" (27) to column "Datetime" (60).  The conversion returned status value 2 and status text "The value could not be converted because of a potential loss of data."

Error 0xc0209029: Data Flow Task 1: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "Data Conversion 0 - 0.Outputs[Data Conversion Output].Columns[Datetime]" failed because error code 0xC020907F occurred, and the error row disposition on "Data Conversion 0 - 0.Outputs[Data Conversion Output].Columns[Datetime]" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.

Error 0xc0047022: Data Flow Task 1: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Data Conversion 0 - 0" (52) failed with error code 0xC0209029 while processing input "Data Conversion Input" (53). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.

Error 0xc02020c4: Data Flow Task 1: The attempt to add a row to the Data Flow task buffer failed with error code 0xC0047020.

Error 0xc0047038: Data Flow Task 1: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on Source - Sheet2$ returned error code 0xC02020C4.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
</code>```

Any idea on what I'm doing wrong? I specifically have to import from Excel and not from CSV because there is Hebrew text in the source file which SQL Server refuses to recognize with any of the encodings available in CSV import.

`

答: What finally worked was deleting the milliseconds entirely.</p>

Body:
guys,

I've got some datetime data in an Excel file, formatted appropriately for SQL Server datetime conversion (yyyy-mm-dd hh:mm:ss:000). Unfortunately, when I try to import the data into an SQL field of type DateTime, I get these error messages:

Error 0xc02020c5: Data Flow Task 1: Data conversion failed while converting column "Datetime" (27) to column "Datetime" (60).  The conversion returned status value 2 and status text "The value could not be converted because of a potential loss of data."

Error 0xc0209029: Data Flow Task 1: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "Data Conversion 0 - 0.Outputs[Data Conversion Output].Columns[Datetime]" failed because error code 0xC020907F occurred, and the error row disposition on "Data Conversion 0 - 0.Outputs[Data Conversion Output].Columns[Datetime]" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.

Error 0xc0047022: Data Flow Task 1: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Data Conversion 0 - 0" (52) failed with error code 0xC0209029 while processing input "Data Conversion Input" (53). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.

Error 0xc02020c4: Data Flow Task 1: The attempt to add a row to the Data Flow task buffer failed with error code 0xC0047020.

Error 0xc0047038: Data Flow Task 1: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on Source - Sheet2$ returned error code 0xC02020C4.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.

Any idea on what I'm doing wrong? I specifically have to import from Excel and not from CSV because there is Hebrew text in the source file which SQL Server refuses to recognize with any of the encodings available in CSV import.

`


问:
how to convert numberLong to dd/mm/yyyy format in javascript or jquery?
I used date picker which is in dd/mm/yyyy format. For saving this date in mongodb database I converted this date into number Long format and save it. I want to display all records in dd/mm/yyyy format then how can I convert number long to date in dd/mm/yyyy format?      </p>

答:
try this function </p>

```<code>function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));
console.log(getDateIfDate('abc'));
</code>```

Body:
try this function

function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));
console.log(getDateIfDate('abc'));


问:
Why does using a Poco Model for my embedded ViewComponent in an external assembly throw Assembly Error?
I have a Poco Model, in an external assembly where the actual view component is located.

```<code> public class HeaderModel
{
    public HeaderModel()
    {
        MainMenuItems = new List<MainMenuItem>();
    }

    public string ViewComponentName { get; set; }
    public List<MainMenuItem> MainMenuItems { get; set; }
}
</code>```

I'm then returning it as the model for the view component

```<code>public async Task<IViewComponentResult> InvokeAsync()
    {
        var headerModel = new HeaderModel
        {
            ViewComponentName = ApplicationConfiguration.Configuration.Settings.Ui.RightSidebar.ViewComponentName,
            MainMenuItems = MenuProvider.GetTopMenu().ToList()
        };

        return View(headerModel);
    }
</code>```

When I do this I get a:

FileNotFoundException: Could not load file or assembly 'UiSmart.Module, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

The funny thing is that if I specify an IEnumerable as my model type it works fine, but the moment I use a Poco model in the view it has a hissy fit, and even more annoying is that the model is defined in the same assembly as the view component .cs and .cshtml page.

I have a feeling that the view is running in the context of the server and the actual assembly it belongs to is no longer in context/referenced, but it is added as an application part during start-up.

So I'm very confused.

Does anyone have any idea why this could be happening?

答: Ok so the problem is sorted, instead of copying the module dlls to a Modules folder after the build, I'm copying it now to the webbapps bin folder, and all is well, essentially saying that as long as the modules are located side by side of the entry assembly it will work.</p>

Body:
I have a Poco Model, in an external assembly where the actual view component is located.

 public class HeaderModel
{
    public HeaderModel()
    {
        MainMenuItems = new List<MainMenuItem>();
    }

    public string ViewComponentName { get; set; }
    public List<MainMenuItem> MainMenuItems { get; set; }
}

I'm then returning it as the model for the view component

public async Task<IViewComponentResult> InvokeAsync()
    {
        var headerModel = new HeaderModel
        {
            ViewComponentName = ApplicationConfiguration.Configuration.Settings.Ui.RightSidebar.ViewComponentName,
            MainMenuItems = MenuProvider.GetTopMenu().ToList()
        };

        return View(headerModel);
    }

When I do this I get a:

FileNotFoundException: Could not load file or assembly 'UiSmart.Module, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

The funny thing is that if I specify an IEnumerable as my model type it works fine, but the moment I use a Poco model in the view it has a hissy fit, and even more annoying is that the model is defined in the same assembly as the view component .cs and .cshtml page.

I have a feeling that the view is running in the context of the server and the actual assembly it belongs to is no longer in context/referenced, but it is added as an application part during start-up.

So I'm very confused.

Does anyone have any idea why this could be happening?


问:
Why does cat change the contents of binary files?
Apparently, running cat on a binary file and echoing back the contents doesn't seem to be working. Here is the simple script I made:

```<code>#!/bin/sh

CONTENTS=$(cat "$1")
mv "$2" "$1"
echo "$CONTENTS" > "$2"
</code>```

For some reason, this seems to be messing up when I do things like this:

```<code>script first.pptx second.pptx
</code>```

After running this, the new first.pptx file opens fine, but the new second.pptx file is supposedly in an invalid format or something.

Why is this happening and what can I do to fix this?

答:
try doing the same but with temp file.</p>

```<code>cat < $file1 > $tempFile
cat < $file2 > $file1
cat < $tempFile > $file2
rm $tempFile
</code>```

Body:
Apparently, running cat on a binary file and echoing back the contents doesn't seem to be working. Here is the simple script I made:

#!/bin/sh

CONTENTS=$(cat "$1")
mv "$2" "$1"
echo "$CONTENTS" > "$2"

For some reason, this seems to be messing up when I do things like this:

script first.pptx second.pptx

After running this, the new first.pptx file opens fine, but the new second.pptx file is supposedly in an invalid format or something.

Why is this happening and what can I do to fix this?

Body:
try doing the same but with temp file.

cat < $file1 > $tempFile
cat < $file2 > $file1
cat < $tempFile > $file2
rm $tempFile


问:
Android new Intent with back button
In my Android App I use an empty activity with one button. If I push the button I call a new activity with an intent. But on the new activity the back button (top left) to jump back to the last page is missing. Isn't there already a activity template from android studio or a spezial intent call to do this? Or what is the best way to do this?

This is the function which is called on the button press

```<code>void scanClicked(View v){
    Intent intent = new Intent(this, ServiceActivity.class);
    startActivity(intent);
}
</code>```

The ServiceActivity is just an Empty Activity

```<code>    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login"
        android:theme="@style/SplashTheme"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NavigationActivity"
        android:label="@string/title_activity_navigation"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".ServiceActivity"
        android:label="@string/annualServiceTitle">
    </activity>
</code>```

答:
I solved this with two lines of code:

In OnCreate of the second View:

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

and in the Manifest add attribute "parentActivityName" to the second View:

```<code>android:parentActivityName="fronius.com.serviceapp_frontend.NavigationActivity"
</code>```

Title: Android new Intent with back button

Body:
In my Android App I use an empty activity with one button. If I push the button I call a new activity with an intent. But on the new activity the back button (top left) to jump back to the last page is missing. Isn't there already a activity template from android studio or a spezial intent call to do this? Or what is the best way to do this?

This is the function which is called on the button press

void scanClicked(View v){
    Intent intent = new Intent(this, ServiceActivity.class);
    startActivity(intent);
}

The ServiceActivity is just an Empty Activity

    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login"
        android:theme="@style/SplashTheme"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NavigationActivity"
        android:label="@string/title_activity_navigation"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".ServiceActivity"
        android:label="@string/annualServiceTitle">
    </activity>

Body:
I solved this with two lines of code:

In OnCreate of the second View:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and in the Manifest add attribute "parentActivityName" to the second View:

android:parentActivityName="fronius.com.serviceapp_frontend.NavigationActivity"


问:
Synchronize CSS animation after dynamic displaying with jQuery
As you see some box elements are hidden. After clicking the button all box elements will be displayed. The backgrounds are animated. Unfortunately the animations start from the beginn after displaying with jQuery them.

Is there a way to synchronize them somehow?

Here is an example:

```<code>.box:nth-child(n+3) {
   display: none;
}
.box {
   display: block;
   width: 200px;
   height: 50px;
   background: linear-gradient(337deg, rgba(31,212,166,1), rgba(24,54,141,1), rgba(102,24,141,1));
   background-size: 400% 400%;
   animation: AnimationName 4s ease infinite;
   margin-bottom: 5px;
}
</code>```

jQuery:

```<code>$('button').on('click', function(){
    $('.box:nth-child(n+3)').css('display', 'block')
})
</code>```

https://jsfiddle.net/boLgvcc8/

答: You can set the height of the third element to 0px and then on click you can just set it back to 50 with .css('height', '50px');</p>

Body:
As you see some box elements are hidden. After clicking the button all box elements will be displayed. The backgrounds are animated. Unfortunately the animations start from the beginn after displaying with jQuery them.

Is there a way to synchronize them somehow?

Here is an example:

.box:nth-child(n+3) {
   display: none;
}
.box {
   display: block;
   width: 200px;
   height: 50px;
   background: linear-gradient(337deg, rgba(31,212,166,1), rgba(24,54,141,1), rgba(102,24,141,1));
   background-size: 400% 400%;
   animation: AnimationName 4s ease infinite;
   margin-bottom: 5px;
}

jQuery:

$('button').on('click', function(){
    $('.box:nth-child(n+3)').css('display', 'block')
})

https://jsfiddle.net/boLgvcc8/


问:
stop reason = signal SIGILL: privileged instruction
My program c++ build in freebsd clang. But under function is program crash. Help me please.</p>

```<code>Program block;

bool CHARACTER::DragonSoul_ActivateDeck(int deck_idx)
{
    if (deck_idx < DRAGON_SOUL_DECK_0 || deck_idx >= DRAGON_SOUL_DECK_MAX_NUM)
    {
        return false;
    }

    if (DragonSoul_GetActiveDeck() == deck_idx)
        return true;

    DragonSoul_DeactivateAll();

    if (!DragonSoul_IsQualified())
    {
        ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¿ëÈ¥¼® »óÀÚ°¡ È°¼ºÈµÇÁö ¾Ê¾Ò½À´Ï´Ù."));
        return false;
    }

    AddAffect(AFFECT_DRAGON_SOUL_DECK_0 + deck_idx, APPLY_NONE, 0, 0, INFINITE_AFFECT_DURATION, 0, false);

    m_pointsInstant.iDragonSoulActiveDeck = deck_idx;

    for (int i = DRAGON_SOUL_EQUIP_SLOT_START + DS_SLOT_MAX * deck_idx;
        i < DRAGON_SOUL_EQUIP_SLOT_START + DS_SLOT_MAX * (deck_idx + 1); i++)
    {
        LPITEM pItem = GetInventoryItem(i);
        if (NULL != pItem)
            DSManager::instance().ActivateDragonSoul(pItem);
    }
}

lldb debug;

* thread #1: tid = 100852, 0x081086b4 game`CHARACTER::DragonSoul_ActivateDeck(this=0x31bbd000, deck_idx=0) + 388 at char_dragonsoul.cpp:90, stop reason = signal SIGILL: privileged instruction
    frame #0: 0x081086b4 game`CHARACTER::DragonSoul_ActivateDeck(this=0x31bbd000, deck_idx=0) + 388 at char_dragonsoul.cpp:90
   87                   LPITEM pItem = GetInventoryItem(i);
   88                   if (NULL != pItem)
   89                           DSManager::instance().ActivateDragonSoul(pItem);
-> 90           }
   91   }
   92
   93   void CHARACTER::DragonSoul_DeactivateAll()
</code>```

答: Run it using a debugger (ie gdb /your/program/executable, then use "run").  Then do "disass"; it will show you the instruction that caused the crash.  Might be, clang emits code for CPU model newer than the one you have.</p>

Body:
My program c++ build in freebsd clang. But under function is program crash. Help me please.

Program block;

bool CHARACTER::DragonSoul_ActivateDeck(int deck_idx)
{
    if (deck_idx < DRAGON_SOUL_DECK_0 || deck_idx >= DRAGON_SOUL_DECK_MAX_NUM)
    {
        return false;
    }

    if (DragonSoul_GetActiveDeck() == deck_idx)
        return true;

    DragonSoul_DeactivateAll();

    if (!DragonSoul_IsQualified())
    {
        ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¿ëÈ¥¼® »óÀÚ°¡ È°¼ºÈµÇÁö ¾Ê¾Ò½À´Ï´Ù."));
        return false;
    }

    AddAffect(AFFECT_DRAGON_SOUL_DECK_0 + deck_idx, APPLY_NONE, 0, 0, INFINITE_AFFECT_DURATION, 0, false);

    m_pointsInstant.iDragonSoulActiveDeck = deck_idx;

    for (int i = DRAGON_SOUL_EQUIP_SLOT_START + DS_SLOT_MAX * deck_idx;
        i < DRAGON_SOUL_EQUIP_SLOT_START + DS_SLOT_MAX * (deck_idx + 1); i++)
    {
        LPITEM pItem = GetInventoryItem(i);
        if (NULL != pItem)
            DSManager::instance().ActivateDragonSoul(pItem);
    }
}

lldb debug;

* thread #1: tid = 100852, 0x081086b4 game`CHARACTER::DragonSoul_ActivateDeck(this=0x31bbd000, deck_idx=0) + 388 at char_dragonsoul.cpp:90, stop reason = signal SIGILL: privileged instruction
    frame #0: 0x081086b4 game`CHARACTER::DragonSoul_ActivateDeck(this=0x31bbd000, deck_idx=0) + 388 at char_dragonsoul.cpp:90
   87                   LPITEM pItem = GetInventoryItem(i);
   88                   if (NULL != pItem)
   89                           DSManager::instance().ActivateDragonSoul(pItem);
-> 90           }
   91   }
   92
   93   void CHARACTER::DragonSoul_DeactivateAll()


问:
Module 'pygame' has no 'KEYDOWN' member
I'm new to PyGame and just trying to mak it detect pressed keys bbut the error
"Module 'pygame' has no 'KEYDOWN' member" Appears.
I've tried alot of other suggestions for others problems but none have worked for me</p>

```<code>import pygame as Game
import sys, time
from random import randrange

# Setup Variables
Width = 500
Height = 500
Change_To = Direction

# Initialize PyGame
Check_Errors = Game.init()
# Check for errors in initializing PyGame
if Check_Errors[1] != 0:
    print("(!)There were {0} initializing errors,
EXITING...".format(Check_Errors[1]))
    sys.exit
else:
    print("PyGame initialized successfully!")

# Setup Game Board
Board = Game.display.set_mode([Width, Height])
Game.display.set_caption("Snake Game!")

# Setup Events
while True:
    for Event in Game.event.get():
        if Event.type == Game.KEYDOWN:
            if Event.key == Game.K_UP:
                Change_To = 'UP'
            if Event.key == Game.K_LEFT:
                Change_To = 'LEFT'
            if Event.key == Game.K_DOWN:
                Change_To = 'DOWN'
            if Event.key == Game.K_RIGHT:
                Change_To = 'RIGHT'
</code>```

答:
The code you have posted works when I try it, and it reports KEYDOWN events as expected.

Is your Python module called Game?

And by the way, sys.exit in your initialization error check doesn't do what you think it does. It should be sys.exit().

Title: Module 'pygame' has no 'KEYDOWN' member

Body:
I'm new to PyGame and just trying to mak it detect pressed keys bbut the error
"Module 'pygame' has no 'KEYDOWN' member" Appears.
I've tried alot of other suggestions for others problems but none have worked for me

import pygame as Game
import sys, time
from random import randrange

# Setup Variables
Width = 500
Height = 500
Change_To = Direction

# Initialize PyGame
Check_Errors = Game.init()
# Check for errors in initializing PyGame
if Check_Errors[1] != 0:
    print("(!)There were {0} initializing errors,
EXITING...".format(Check_Errors[1]))
    sys.exit
else:
    print("PyGame initialized successfully!")

# Setup Game Board
Board = Game.display.set_mode([Width, Height])
Game.display.set_caption("Snake Game!")

# Setup Events
while True:
    for Event in Game.event.get():
        if Event.type == Game.KEYDOWN:
            if Event.key == Game.K_UP:
                Change_To = 'UP'
            if Event.key == Game.K_LEFT:
                Change_To = 'LEFT'
            if Event.key == Game.K_DOWN:
                Change_To = 'DOWN'
            if Event.key == Game.K_RIGHT:
                Change_To = 'RIGHT'


问:
Field has incomplete type in forward declaration
I reproduce an error with the following simple file.

It says:

field has incomplete type 'Foo'

bar.h:

```<code>class Foo;

class Bar{
    private:
        int x_;
        Foo foo_; // error: incomplete type

    public:
        void setx(int x) {x_ = x;};
        void increment(int);

};

class Foo{

public:
    void run(int y,Bar& bar) {bar.setx(y);};
};

void Bar::increment(int i){foo_.run(i,*this);}
</code>```

Member foo_ must not be a reference or a pointer. The reason for this is that in my actual code,  I cannot initialize Foo in the initialization list of Bar.

答:
Your problem can be reduced to this:

```<code>class Foo;

class Bar{
    Foo foo_; // error: incomplete type
};
</code>```

Here you did a forward declaration for type Foo, i.e. a declaration without a complete definition: that's enough in C++ to declare a pointer, but not a concrete instance as you did in Bar.

Either give a complete definition to your class:

```<code>class Foo{
    // put details here
};

class Bar{
    Foo foo_; // OK
};
</code>```

Or use (smart) pointers, e.g.:

```<code>class Foo;

class Bar{
    std::unique_ptr<Foo> foo_; // OK
};
</code>```

Or change order declaration as pointed by Bartek Banachewicz.

ContentLicense: CC BY-SA 4.0

Body:
I reproduce an error with the following simple file.

It says:

field has incomplete type 'Foo'

bar.h:

class Foo;

class Bar{
    private:
        int x_;
        Foo foo_; // error: incomplete type

    public:
        void setx(int x) {x_ = x;};
        void increment(int);

};

class Foo{

public:
    void run(int y,Bar& bar) {bar.setx(y);};
};

void Bar::increment(int i){foo_.run(i,*this);}

Member foo_ must not be a reference or a pointer. The reason for this is that in my actual code,  I cannot initialize Foo in the initialization list of Bar.

Body:
Your problem can be reduced to this:

class Foo;

class Bar{
    Foo foo_; // error: incomplete type
};

Here you did a forward declaration for type Foo, i.e. a declaration without a complete definition: that's enough in C++ to declare a pointer, but not a concrete instance as you did in Bar.

Either give a complete definition to your class:

class Foo{
    // put details here
};

class Bar{
    Foo foo_; // OK
};

Or use (smart) pointers, e.g.:

class Foo;

class Bar{
    std::unique_ptr<Foo> foo_; // OK
};

Or change order declaration as pointed by Bartek Banachewicz.


答:
In this case it's simple enough: since Foo only uses a reference to Bar, flipping them around will do the trick:

```<code>class Bar;

class Foo{
public:
    void run(int y,Bar& bar);
};

class Bar { ... };

void Foo::run(int y, Bar& bar) {
    bar.setx(y);
}
</code>```

You also need to move the body of Foo::run below, because it's actually using the Bar member function.

Title: Field has incomplete type in forward declaration

Body:
In this case it's simple enough: since Foo only uses a reference to Bar, flipping them around will do the trick:

class Bar;

class Foo{
public:
    void run(int y,Bar& bar);
};

class Bar { ... };

void Foo::run(int y, Bar& bar) {
    bar.setx(y);
}

You also need to move the body of Foo::run below, because it's actually using the Bar member function.


问:
SpringBoot: running a multi module project
I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
is a multi-module project with Spring Boot, the project will have 3 modules.
Here the parent module pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.tdkcloud</groupId>
    <artifactId>tdk-cloud</artifactId>
    <version>0.0.2-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>tdk-core</module>
        <module>tdk-batch</module>
        <module>tdk-web</module>
    </modules>

    <dependencies>
        <!-- Spring Boot dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>uk.co.jemos.podam</groupId>
            <artifactId>podam</artifactId>
            <version>7.0.5.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- Logging dependencies -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

        <!-- Email dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <!-- Security dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- Spring data -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

    </dependencies>

</project>
</code>```

Here the module core

```<code><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.tdkcloud</groupId>
        <artifactId>tdk-cloud</artifactId>
        <version>0.0.2-SNAPSHOT</version>
    </parent>

  <groupId>com.tdkcloud.core</groupId>
  <artifactId>tdk-core</artifactId>
   <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>

        <!--  Hibernate dependencies -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>com.googlecode.libphonenumber</groupId>
            <artifactId>libphonenumber</artifactId>
            <version>8.4.3</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <!-- <version>1.10</version> -->
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <!-- <version>2.9.0.pr3</version> -->
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <!-- <version>2.9.0.pr3</version> -->
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.9</version>
</dependency>

    </dependencies>

</project>
</code>```

and here the module web:

```<code><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.tdkcloud</groupId>
        <artifactId>tdk-cloud</artifactId>
        <version>0.0.2-SNAPSHOT</version>
    </parent>

  <groupId>com.tdkcloud.web</groupId>
  <artifactId>tdk-web</artifactId>
  <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <start-class>com.tdkcloud.TdkCloudApplication</start-class>
  </properties>

  <dependencies>

        <!-- tdk-core dependencies -->
         <dependency>
            <groupId>com.tdkcloud.core</groupId>
            <artifactId>tdk-core</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- Webjars for JQuery and Bootstrap -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7-1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.2.0</version>
        </dependency>

        <!-- Spring Security -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <!-- <version>3.0.2.RELEASE</version> -->
        </dependency>

   </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.tdkcloud.TdkCloudApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

     <!--  <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>  -->

</project>
</code>```

from the parent root I generate all the modules using:

```<code>mvn clean package
</code>```

But the problem is that the tdk-web-0.0.2-SNAPSHOT.jar does not contain the tdk-core-0.0.2-SNAPSHOT.jar and then it fails on the startup

Here the maven result:

```<code>MacBook-Pro-de-nunito:tdk-cloud calzada$ mvn clean package -Dmaven.test.skip=true
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] tdk-cloud
[INFO] tdk-core
[INFO] tdk-batch
[INFO] tdk-web
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-cloud 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-cloud ---
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-core 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] The POM for com.h2database:h2:jar:1.4.194 is missing, no dependency information available
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-core ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-core ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-core ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 52 source files to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-core ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-core ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-core ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-core ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target/tdk-core-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-batch 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-batch ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-batch ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/src/main/resources
[INFO] skip non existing resourceDirectory /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-batch ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-batch ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-batch ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-batch ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-batch ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target/tdk-batch-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-web 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-web ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-web ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] Copying 339 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-web ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 25 source files to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-web ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-web ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-web ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-web ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target/tdk-web-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.3.RELEASE:repackage (default) @ tdk-web ---
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] tdk-cloud ....................................... SUCCESS [  0.105 s]
[INFO] tdk-core ........................................ SUCCESS [  1.634 s]
[INFO] tdk-batch ....................................... SUCCESS [  0.114 s]
[INFO] tdk-web ......................................... SUCCESS [  1.506 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.663 s
[INFO] Finished at: 2017-05-30T05:37:04+02:00
[INFO] Final Memory: 47M/539M
[INFO] ------------------------------------------------------------------------
MacBook-Pro-de-nunito:tdk-cloud calzada$
</code>```

This is the error I got:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field emailService in com.tdkcloud.web.controllers.AppErrorController required a bean of type 'com.tdkcloud.backend.service.EmailService' that could not be found.

Action:

Consider defining a bean of type 'com.tdkcloud.backend.service.EmailService' in your configuration.
</code>```

I unzipped the jar and there is no class of the core module

adding the proposed code to the module web:

```<code><plugin>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>install</phase>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
</code>```

I have the next error:  Error resolving template "/tdk/login/login", template might not exist or might not be accessible by any of the configured Template Reso

but the template is there:

答:
```<code>            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
</code>```

I suggest this for creating a executable Jar.

Body:
I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
is a multi-module project with Spring Boot, the project will have 3 modules.
Here the parent module pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath />
    </parent>

    <groupId>com.tdkcloud</groupId>
    <artifactId>tdk-cloud</artifactId>
    <version>0.0.2-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>tdk-core</module>
        <module>tdk-batch</module>
        <module>tdk-web</module>
    </modules>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>uk.co.jemos.podam</groupId>
            <artifactId>podam</artifactId>
            <version>7.0.5.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

    </dependencies>

</project>

Here the module core

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.tdkcloud</groupId>
        <artifactId>tdk-cloud</artifactId>
        <version>0.0.2-SNAPSHOT</version>
    </parent>

  <groupId>com.tdkcloud.core</groupId>
  <artifactId>tdk-core</artifactId>
   <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>com.googlecode.libphonenumber</groupId>
            <artifactId>libphonenumber</artifactId>
            <version>8.4.3</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>

        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>

        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>

        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.9</version>
</dependency>

    </dependencies>

</project>

and here the module web:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.tdkcloud</groupId>
        <artifactId>tdk-cloud</artifactId>
        <version>0.0.2-SNAPSHOT</version>
    </parent>

  <groupId>com.tdkcloud.web</groupId>
  <artifactId>tdk-web</artifactId>
  <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <start-class>com.tdkcloud.TdkCloudApplication</start-class>
  </properties>

  <dependencies>

         <dependency>
            <groupId>com.tdkcloud.core</groupId>
            <artifactId>tdk-core</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7-1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>

        </dependency>

   </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.tdkcloud.TdkCloudApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

from the parent root I generate all the modules using:

mvn clean package

But the problem is that the tdk-web-0.0.2-SNAPSHOT.jar does not contain the tdk-core-0.0.2-SNAPSHOT.jar and then it fails on the startup

Here the maven result:

MacBook-Pro-de-nunito:tdk-cloud calzada$ mvn clean package -Dmaven.test.skip=true
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] tdk-cloud
[INFO] tdk-core
[INFO] tdk-batch
[INFO] tdk-web
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-cloud 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-cloud ---
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-core 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] The POM for com.h2database:h2:jar:1.4.194 is missing, no dependency information available
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-core ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-core ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-core ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 52 source files to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-core ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-core ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-core ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-core ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target/tdk-core-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-batch 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-batch ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-batch ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/src/main/resources
[INFO] skip non existing resourceDirectory /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-batch ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-batch ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-batch ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-batch ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-batch ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target/tdk-batch-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-web 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-web ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-web ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] Copying 339 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-web ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 25 source files to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-web ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-web ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-web ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-web ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target/tdk-web-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.3.RELEASE:repackage (default) @ tdk-web ---
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] tdk-cloud ....................................... SUCCESS [  0.105 s]
[INFO] tdk-core ........................................ SUCCESS [  1.634 s]
[INFO] tdk-batch ....................................... SUCCESS [  0.114 s]
[INFO] tdk-web ......................................... SUCCESS [  1.506 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.663 s
[INFO] Finished at: 2017-05-30T05:37:04+02:00
[INFO] Final Memory: 47M/539M
[INFO] ------------------------------------------------------------------------
MacBook-Pro-de-nunito:tdk-cloud calzada$

This is the error I got:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field emailService in com.tdkcloud.web.controllers.AppErrorController required a bean of type 'com.tdkcloud.backend.service.EmailService' that could not be found.

Action:

Consider defining a bean of type 'com.tdkcloud.backend.service.EmailService' in your configuration.

I unzipped the jar and there is no class of the core module

adding the proposed code to the module web:

<plugin>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>install</phase>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

I have the next error:  Error resolving template "/tdk/login/login", template might not exist or might not be accessible by any of the configured Template Reso

but the template is there:

Body:
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

I suggest this for creating a executable Jar.


问:
Why does gprof occasionally not print number of calls for particular functions?
The application is compiled with -O0 -g -pg and gprof is run with its default settings.</p>

答: (self-answer) I believe it was static declarations.</p>

ContentLicense: CC BY-SA 2.5


问:
Why Angular Material is responive and AngualJS Material isn't?
I'm trying to choose a framework for an application of mine and I stumbled across
Angular Material and AngularJS Material I understand that both are from Google (correct me if I'm wrong) but basically are both doing more or less the same, rendering components in a HTML page, what I don't get (and google around is not very efficent due to confusion on similar name) why Angular material is not responsive and AngularJS Material is? Wich one I should choose in order to make my app responsive? Or..how would I get an Angular Material app respnsive?</p>

答: You should use angularjs material because responsiveness comes as a built in since it is a directive based approach applying any CSS will be quite complicated in that.</p>


问:
How to avoid auto increment of primary key in inserting query?
First I allowed user to type in combo box to search quickly when there are many projects. I was wondering if I can stop the insert query if the user accidentally press an additional letter and it will cause null, and I had try catch block but it only shows error message but the primary key skip a number.

Selecting ProjectID to fill comboBox

```<code>private void GetProjectID()
{
    newConnection.ConnectionM();
    SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand();
    cmd.CommandText = "Select * from Project where ProjectName='" + comboBoxProjectTitle.Text + "' ";
    try
    {
        SqlDataReader reader = cmd.ExecuteReader();
        while(reader.Read())
        {
            ProjectID = reader.GetInt32(0);

        }
        reader.Close();
        SqlConnectionOLTP.cn.Close();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
</code>```

Inserting to database:

```<code>SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand();
cmd.CommandText = "Insert into Cost(ProjectID,PropertyID,CostCategoryID,EstimatedAmount) values ('" + ProjectID + "','" + PropertyID + "','" + CostCatID + "'," + "'" + textBoxAmount.Text + "') ";
cmd.ExecuteNonQuery();
SqlConnectionOLTP.cn.Close();
MessageBox.Show("Saved");
</code>```

答:
Run this code on SSMS i.e sql server management studio

```<code> ALTER TABLE [Project] DROP ProjectID
   SET IDENTITY_INSERT <Project> OFF
</code>```

Body:
First I allowed user to type in combo box to search quickly when there are many projects. I was wondering if I can stop the insert query if the user accidentally press an additional letter and it will cause null, and I had try catch block but it only shows error message but the primary key skip a number.

Selecting ProjectID to fill comboBox

private void GetProjectID()
{
    newConnection.ConnectionM();
    SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand();
    cmd.CommandText = "Select * from Project where ProjectName='" + comboBoxProjectTitle.Text + "' ";
    try
    {
        SqlDataReader reader = cmd.ExecuteReader();
        while(reader.Read())
        {
            ProjectID = reader.GetInt32(0);

        }
        reader.Close();
        SqlConnectionOLTP.cn.Close();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Inserting to database:

SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand();
cmd.CommandText = "Insert into Cost(ProjectID,PropertyID,CostCategoryID,EstimatedAmount) values ('" + ProjectID + "','" + PropertyID + "','" + CostCatID + "'," + "'" + textBoxAmount.Text + "') ";
cmd.ExecuteNonQuery();
SqlConnectionOLTP.cn.Close();
MessageBox.Show("Saved");

Body:
Run this code on SSMS i.e sql server management studio

 ALTER TABLE [Project] DROP ProjectID
   SET IDENTITY_INSERT <Project> OFF


问:
How can I declare an empty variable?
Here's my code:

```<code>private void button1_Click(object sender, EventArgs e)
    {
        var api = RiotApi.GetInstance("KEY");

        try
        {
            var game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
        }

        catch (RiotSharpException ex)
        {
            throw;
        }

        foreach (var player in game.Participants) // Can't find game variable
        {

        }
    }
</code>```

I can't call game.Participants in my foreach loop because i initialize game inside the try statement. I can't initialize game outside the try statement either though because to do that i would have to give it a temporary value and I don't know what kind of value it will be.

Is there a way to declare a variable as null? Or is there potentially a different way to solve this?

答:
Something like this:

```<code>private void button1_Click(object sender, EventArgs e)
{
    var api = RiotApi.GetInstance("KEY");

    // if we have api, try get the game
    var game = api != null
      ? api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188)
      : null;

    // if we have game, process the players
    if (game != null)
        foreach (var player in game.Participants)
        {
            //TODO: put relevant logic here
        }
}
</code>```

Please, notice, that try {} catch (RiotSharpException ex) {throw;} is a redundant construction and can be dropped.

Title: How can I declare an empty variable?

Body:
Here's my code:

private void button1_Click(object sender, EventArgs e)
    {
        var api = RiotApi.GetInstance("KEY");

        try
        {
            var game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
        }

        catch (RiotSharpException ex)
        {
            throw;
        }

        foreach (var player in game.Participants) // Can't find game variable
        {

        }
    }

I can't call game.Participants in my foreach loop because i initialize game inside the try statement. I can't initialize game outside the try statement either though because to do that i would have to give it a temporary value and I don't know what kind of value it will be.

Is there a way to declare a variable as null? Or is there potentially a different way to solve this?

Body:
Something like this:

private void button1_Click(object sender, EventArgs e)
{
    var api = RiotApi.GetInstance("KEY");

    // if we have api, try get the game
    var game = api != null
      ? api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188)
      : null;

    // if we have game, process the players
    if (game != null)
        foreach (var player in game.Participants)
        {
            //TODO: put relevant logic here
        }
}

Please, notice, that try {} catch (RiotSharpException ex) {throw;} is a redundant construction and can be dropped.