问:
Android Java SQLite database: The database does not take 2 String inputs
I am learing to code and made a stopwatch that saves the laptimes in a String and gets the date as a String as well. I want to put those in a SQLite database (so i can later display the date in a listview and open it in another activity that shows all the laptimes.) I've followed some of the codes on the internet and try to put stuff together so I might look over some things in my code. I've commented on the parts I think i understand so you can follow my thinking a bit.

The problem: when i press save the following code is executed and returns the toastmessage: Somehting went wrong.

```<code> save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String dateStamp = getCurrentTimeStamp();
                AddData(dataInput, dateStamp);
                //DatabaseHelper.deleteAll();
            }
        }); //save data though AddData method as input the listText
</code>```

The method AddData is as follows:

```<code>public void AddData(String time, String date) {
        boolean insertData = DatabaseHelper.addData(time, date);

        if (insertData) {
            toastMessage(dataInput);
        } else {
            toastMessage("Something went wrong");
        }
    }
</code>```

The boolean method in the DatabaseHelper class is this:

```<code>public boolean addData(String times, String date) { //addData that takes a string
        SQLiteDatabase db = this.getWritableDatabase(); //database called db and use getWritableDatabase method
        ContentValues contentValues = new ContentValues();  //make a new object of ContentValues
        contentValues.put(COL_2, times); //put COL_2 and the String in the ContentValues object
        contentValues.put(COL_3, date);

          long result = db.insert(TABLE_NAME, null, contentValues);   //insert contentValues object into the table
        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            db.close();
            return false;
        } else {
            return true;
        }

    }
</code>```

It works when i input just 1 variable in addData() but not with 2 that I later implemented. I think it should work. Below I also put the code that is used to make the SQLite Database.

```<code>public static final String TABLE_NAME = "stopwatch";   //make a table with name
    public static final String COL_1 = "ID";   //make an ID for every colomn
    public static final String COL_2 = "times";    //make a 2nd colomn for data
    public static final String COL_3= "date";

    public DatabaseHelper(Context context) {
        super(context, TABLE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {   //make the onCreate method that takes the database as input
        String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL_2 +" TEXT" + COL_3 +" TEXT)";    //create the table with SQL statements to input the data correctly
        db.execSQL(createTable);    //input the SQL statements in the DB

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  //make upgrade method that takes the database and the versions
        db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);   //execute SQL statements drop table and which one
        onCreate(db);   //run through create method
    }
</code>```

I hope someone can help me to find the problem so I can learn more.

答:
Your create table query is missing a comma after the COL_2 +" TEXT"

```<code>@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL_2 +" TEXT, " + COL_3 +" TEXT)";  // Added a comma after the COL_2
    db.execSQL(createTable);

}
</code>```

Body:
I am learing to code and made a stopwatch that saves the laptimes in a String and gets the date as a String as well. I want to put those in a SQLite database (so i can later display the date in a listview and open it in another activity that shows all the laptimes.) I've followed some of the codes on the internet and try to put stuff together so I might look over some things in my code. I've commented on the parts I think i understand so you can follow my thinking a bit.

The problem: when i press save the following code is executed and returns the toastmessage: Somehting went wrong.

 save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String dateStamp = getCurrentTimeStamp();
                AddData(dataInput, dateStamp);
                //DatabaseHelper.deleteAll();
            }
        }); //save data though AddData method as input the listText

The method AddData is as follows:

public void AddData(String time, String date) {
        boolean insertData = DatabaseHelper.addData(time, date);

        if (insertData) {
            toastMessage(dataInput);
        } else {
            toastMessage("Something went wrong");
        }
    }

The boolean method in the DatabaseHelper class is this:

public boolean addData(String times, String date) { //addData that takes a string
        SQLiteDatabase db = this.getWritableDatabase(); //database called db and use getWritableDatabase method
        ContentValues contentValues = new ContentValues();  //make a new object of ContentValues
        contentValues.put(COL_2, times); //put COL_2 and the String in the ContentValues object
        contentValues.put(COL_3, date);

          long result = db.insert(TABLE_NAME, null, contentValues);   //insert contentValues object into the table
        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            db.close();
            return false;
        } else {
            return true;
        }

    }

It works when i input just 1 variable in addData() but not with 2 that I later implemented. I think it should work. Below I also put the code that is used to make the SQLite Database.

public static final String TABLE_NAME = "stopwatch";   //make a table with name
    public static final String COL_1 = "ID";   //make an ID for every colomn
    public static final String COL_2 = "times";    //make a 2nd colomn for data
    public static final String COL_3= "date";

    public DatabaseHelper(Context context) {
        super(context, TABLE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {   //make the onCreate method that takes the database as input
        String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL_2 +" TEXT" + COL_3 +" TEXT)";    //create the table with SQL statements to input the data correctly
        db.execSQL(createTable);    //input the SQL statements in the DB

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  //make upgrade method that takes the database and the versions
        db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);   //execute SQL statements drop table and which one
        onCreate(db);   //run through create method
    }

I hope someone can help me to find the problem so I can learn more.

Body:
Your create table query is missing a comma after the COL_2 +" TEXT"

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL_2 +" TEXT, " + COL_3 +" TEXT)";  // Added a comma after the COL_2
    db.execSQL(createTable);

}


来源: stackexchange

问:
Simple clock that counts down from 30 seconds and executes a function afterward
I have a game that gives a time limit and I need to display a countdown clock for the users and stop the game once the time is up such as 30 seconds. How can I do this in javascript?</p>

答:
Check out setTimeout and setInterval:

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

ContentLicense: CC BY-SA 2.5


问:
Returning route with a slug, different controller
I run into nasty (for me) problem here.I think pasting code might be to overwhelming so Ill try to say what I want to achieve.
On route /{id}/modify I have a form to create address. On submit i want to be redirected to /{id}/addAddress route which is action of different controller. Data from form I'm sending via array, its okay, but how should I go to the addAddress with the slug, i want to pass return a route with /{$id}/addAddress? Well I hope i said it clearly enough, i still find out that quite difficult.</p>

```<code>if($formAddress->isSubmitted()){
        $post = $formAddress->getData();
        return $this->redirectToRoute("/{id}/addAddress",array("post"=>$post));
}
</code>```

答:
So yeah I got it after little diablo 3 relaxing. seems when you want to be redirected to another controller when in

/2/foo

All you need to do is simple

```<code> return $this->redirect("bar");
</code>```

and you will be redirected to action of different controller, the return will lead you to

/2/bar

Hope this might help some other noobs like me cheers!

ContentLicense: CC BY-SA 3.0

Body:
I run into nasty (for me) problem here.I think pasting code might be to overwhelming so Ill try to say what I want to achieve.
On route /{id}/modify I have a form to create address. On submit i want to be redirected to /{id}/addAddress route which is action of different controller. Data from form I'm sending via array, its okay, but how should I go to the addAddress with the slug, i want to pass return a route with /{$id}/addAddress? Well I hope i said it clearly enough, i still find out that quite difficult.

if($formAddress->isSubmitted()){
        $post = $formAddress->getData();
        return $this->redirectToRoute("/{id}/addAddress",array("post"=>$post));
}

Body:
So yeah I got it after little diablo 3 relaxing. seems when you want to be redirected to another controller when in

/2/foo

All you need to do is simple

 return $this->redirect("bar");

and you will be redirected to action of different controller, the return will lead you to

/2/bar

Hope this might help some other noobs like me cheers!


问:
How to join two collections in mongoose
I have two Schema defined as below:

```<code>var WorksnapsTimeEntry = BaseSchema.extend({
 student: {
     type: Schema.ObjectId,
     ref: 'Student'
 },
 timeEntries: {
     type: Object
 }
 });

var StudentSchema = BaseSchema.extend({
firstName: {
    type: String,
    trim: true,
    default: ''
    // validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
    type: String,
    trim: true,
    default: ''
    // validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
    type: String,
    trim: true
},
municipality: {
    type: String
    }
});
</code>```

And I would like to loop thru each student and show it's time entries. So far I have this code which is obviously not right as I still dont know how do I join WorksnapTimeEntry schema table.

```<code>Student.find({ status: 'student' })
        .populate('student')
        .exec(function (err, students) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            }
            _.forEach(students, function (student) {
               // show student with his time entries....
            });
            res.json(students);
        });
</code>```

Any one knows how do I achieve such thing?

答:
As of version 3.2, you can use $lookup in aggregation pipeline to perform left outer join.</p>

```<code>Student.aggregate([{
    $lookup: {
        from: "worksnapsTimeEntries", // collection name in db
        localField: "_id",
        foreignField: "student",
        as: "worksnapsTimeEntries"
    }
}]).exec(function(err, students) {
    // students contain WorksnapsTimeEntries
});
</code>```

Title: How to join two collections in mongoose

Body:
I have two Schema defined as below:

var WorksnapsTimeEntry = BaseSchema.extend({
 student: {
     type: Schema.ObjectId,
     ref: 'Student'
 },
 timeEntries: {
     type: Object
 }
 });

var StudentSchema = BaseSchema.extend({
firstName: {
    type: String,
    trim: true,
    default: ''
    // validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
    type: String,
    trim: true,
    default: ''
    // validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
    type: String,
    trim: true
},
municipality: {
    type: String
    }
});

And I would like to loop thru each student and show it's time entries. So far I have this code which is obviously not right as I still dont know how do I join WorksnapTimeEntry schema table.

Student.find({ status: 'student' })
        .populate('student')
        .exec(function (err, students) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            }
            _.forEach(students, function (student) {
               // show student with his time entries....
            });
            res.json(students);
        });

Any one knows how do I achieve such thing?

Body:
As of version 3.2, you can use $lookup in aggregation pipeline to perform left outer join.

Student.aggregate([{
    $lookup: {
        from: "worksnapsTimeEntries", // collection name in db
        localField: "_id",
        foreignField: "student",
        as: "worksnapsTimeEntries"
    }
}]).exec(function(err, students) {
    // students contain WorksnapsTimeEntries
});


问:
How can I execute Javascript in my Delphi program without TWebBrowser?
I am working with a Web API that uses a Javascript interface to  make requests, and the response is via a callback Javascript function. Is there a way to call Javascript code from Delphi without using a TWebBrowsercomponent?

答:
You can always run cscript.exe on windows machines.

Advantages:

It's available on all default windows installs since windows 98.

It's dead easy.

No third-party Delphi components needed.

No dll's + wrappers needed, so deployment is simple.

Disadvantages:

You'll be spawning new processes. Starting cscript.exe on a web server feels wrong. I'm not sure what the security implications are.

You don't have direct access to the internals of the scripting engine.

Example program (it's just a proof-of-concept.. there are probably better ways to do this):

```<code>program JsExample;
{$APPTYPE CONSOLE}

uses Windows, IoUtils;

// start a new process
function RunProgram(const aProg, aParams: string; aHow2Show: Word; const aWaitTime: dword): boolean;
var LProcInfo: TProcessInformation; LStartUpInfo: TStartupInfo;
begin
  FillChar(LStartUpInfo, SizeOf(TStartupInfo), #0); FillChar(LProcInfo, SizeOf(TProcessInformation), #0);
  with LStartUpInfo do
  begin
    cb := SizeOf(LStartUpInfo);
    lpReserved := nil; lpDesktop := nil; lpTitle := nil; lpReserved2 := nil; cbReserved2 := 0;
    dwFlags := STARTF_USESHOWWINDOW;
    wShowWindow := aHow2Show;
  end;
  Result := CreateProcess(nil, PChar(aProg + ' ' + aParams), nil, nil, false, CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, nil, LStartUpInfo, LProcInfo);
  if Result then
    Result := WaitForSingleObject(LProcInfo.hProcess, aWaitTime) <> WAIT_FAILED;
end;

// run javascript code
procedure RunJs(const aJavaScript: String);
var LTmpFileName: String;
begin
  LTmpFileName := TPath.ChangeExtension(TPath.GetTempFileName, '.js');
  try
    TFile.WriteAllText(LTmpFileName, aJavaScript);
    RunProgram('cscript', '/NOLOGO "' + LTmpFileName + '"', SW_SHOWNORMAL, INFINITE);
  finally
    TFile.Delete(LTmpFileName);
  end;
end;

// main
begin

  // execute some stupid javascript sample code
  RunJs
  (
    'var Text="Hello from JavaScript!";' + // creating a js variable
    'for(var i=0;i<Text.length;i++)' +     // creating a js looop
    '  WScript.Echo(Text.charAt(i));'      // calling string.charAt() and print some stuff
  );

  ReadLn;
end.
</code>```

This method is really simple.. write the JavaScript to a file, then call cscript.exe with the filename as a parameter.

Body:
You can always run cscript.exe on windows machines.

Advantages:

It's available on all default windows installs since windows 98.

It's dead easy.

No third-party Delphi components needed.

No dll's + wrappers needed, so deployment is simple.

Disadvantages:

You'll be spawning new processes. Starting cscript.exe on a web server feels wrong. I'm not sure what the security implications are.

You don't have direct access to the internals of the scripting engine.

Example program (it's just a proof-of-concept.. there are probably better ways to do this):

program JsExample;
{$APPTYPE CONSOLE}

uses Windows, IoUtils;

// start a new process
function RunProgram(const aProg, aParams: string; aHow2Show: Word; const aWaitTime: dword): boolean;
var LProcInfo: TProcessInformation; LStartUpInfo: TStartupInfo;
begin
  FillChar(LStartUpInfo, SizeOf(TStartupInfo), #0); FillChar(LProcInfo, SizeOf(TProcessInformation), #0);
  with LStartUpInfo do
  begin
    cb := SizeOf(LStartUpInfo);
    lpReserved := nil; lpDesktop := nil; lpTitle := nil; lpReserved2 := nil; cbReserved2 := 0;
    dwFlags := STARTF_USESHOWWINDOW;
    wShowWindow := aHow2Show;
  end;
  Result := CreateProcess(nil, PChar(aProg + ' ' + aParams), nil, nil, false, CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, nil, LStartUpInfo, LProcInfo);
  if Result then
    Result := WaitForSingleObject(LProcInfo.hProcess, aWaitTime) <> WAIT_FAILED;
end;

// run javascript code
procedure RunJs(const aJavaScript: String);
var LTmpFileName: String;
begin
  LTmpFileName := TPath.ChangeExtension(TPath.GetTempFileName, '.js');
  try
    TFile.WriteAllText(LTmpFileName, aJavaScript);
    RunProgram('cscript', '/NOLOGO "' + LTmpFileName + '"', SW_SHOWNORMAL, INFINITE);
  finally
    TFile.Delete(LTmpFileName);
  end;
end;

// main
begin

  // execute some stupid javascript sample code
  RunJs
  (
    'var Text="Hello from JavaScript!";' + // creating a js variable
    'for(var i=0;i<Text.length;i++)' +     // creating a js looop
    '  WScript.Echo(Text.charAt(i));'      // calling string.charAt() and print some stuff
  );

  ReadLn;
end.

This method is really simple.. write the JavaScript to a file, then call cscript.exe with the filename as a parameter.


问:
h1 creates unwanted space above the text
I'm sure my question is quite a newbie one, anyway I can't figure out what I'm doing wrong. Basically, I created a
 that I use as header, and inside of it another
 that contains an image (logo) and a title (using
).

The problem is that I get an unwanted extra space above the body
as you can see in this picture.
If I get rid of the
 title then everything is fine. I think the problem is due the float: left; property that I have assigned to the image, because if I assign no float property then the space disappears, but as you can see if I remove the float: left; the image and the title are not "aligned" anymore. So, the question is, how can I make the image to stay on the left and the title on the right of the image, without using float properties?

Any help will be appreciated, thanks!

Edit: Thanks everybody for the answers, I'm studying HTML and CSS at school and things like this are rarely mentioned by my teachers. Thanks again

答:
At start of your work you should clear the style for margin (browser apply some of them).
So just in start of css file write:

```<code>h1 {
  margin: 0;
}
</code>```

A lot of devs just start a css file like :

```<code>* {
 margin: 0;
 padding: 0;
}
</code>```

for clear it :)
Also you should read something about css reset and css normalize :)

Body:
At start of your work you should clear the style for margin (browser apply some of them).
So just in start of css file write:

h1 {
  margin: 0;
}

A lot of devs just start a css file like :

* {
 margin: 0;
 padding: 0;
}

for clear it :)
Also you should read something about css reset and css normalize :)


问:
Passing variable from shell exec to mysql_query
I'm trying to read temperature from sensor DHT22 connected to raspberry pi and write it to mysql DB via PHP script.

I'm getting the temperature like this:

```<code>$temp = shell_exec('./temp.py');
</code>```

Script returns number like 45 or 45.7 etc... The same as humidity.. When I echo it in the same script, it works.
And the thing, which I cannot pass through is here:

```<code>$sql='INSERT INTO values (id, date, time, timestamp, temp, hum) VALUES ("", NOW(), NOW(), NOW(), "$temp", "$hum")';
$result = MySQL_Query($sql);
</code>```

But in DB is always written $temp and $hum, not the actual values. I think that I've already tried all possible combinations of quotation marks, etc...
What can be possibly wrong? Thanks in advance for the answers.

答:
```<code>$sql="INSERT INTO values (id, date, time, timestamp, temp, hum) VALUES (\"\", NOW(), NOW(), NOW(), \"$temp\", \"$hum\")";
$result = MySQL_Query($sql);
</code>```

Notice the double quotes.

There is a difference between double and single quotes:

Double quotes are parsed by the php engine. You can put variables inside them, and can be used to display escaped special characters.

Single quotes, on the other hands, are displayed as they are. They are not parsed by PHP and do not require escaping, except for the ' to tell the interpreter whether the quote is the end of the string or part of it.

You were using single quotes, that's why your string isn't parsed into variables.

Further information could be found in the PHP Manual

Body:
I'm trying to read temperature from sensor DHT22 connected to raspberry pi and write it to mysql DB via PHP script.

I'm getting the temperature like this:

$temp = shell_exec('./temp.py');

Script returns number like 45 or 45.7 etc... The same as humidity.. When I echo it in the same script, it works.
And the thing, which I cannot pass through is here:

$sql='INSERT INTO values (id, date, time, timestamp, temp, hum) VALUES ("", NOW(), NOW(), NOW(), "$temp", "$hum")';
$result = MySQL_Query($sql);

But in DB is always written $temp and $hum, not the actual values. I think that I've already tried all possible combinations of quotation marks, etc...
What can be possibly wrong? Thanks in advance for the answers.

Body:
$sql="INSERT INTO values (id, date, time, timestamp, temp, hum) VALUES (\"\", NOW(), NOW(), NOW(), \"$temp\", \"$hum\")";
$result = MySQL_Query($sql);

Notice the double quotes.

There is a difference between double and single quotes:

Double quotes are parsed by the php engine. You can put variables inside them, and can be used to display escaped special characters.

Single quotes, on the other hands, are displayed as they are. They are not parsed by PHP and do not require escaping, except for the ' to tell the interpreter whether the quote is the end of the string or part of it.

You were using single quotes, that's why your string isn't parsed into variables.

Further information could be found in the PHP Manual


问:
Getting memory leaks from Appcelerator Alloy app
I have an Alloy app. It has got 7 windows and opens at same time. When user close a opened window $.removeListener(); $.destroy(); codes runs at window close event. But I am getting memory leaks on Android device. %90 windows has got ListView, every window has got max 2 Listview. What is the right approach for multiple windows?

答:
Are you 100% sure that your event listeners are being removed?

I don't know the function $.removeListener(); is this a custom function?

As a general rule I try and put as many of my event listeners into the xml, as these are automatically removed, and have a custom function destroyMe() that runs onClose which removes any other listeners that I may have used and $.destroy()

Ti.App.addEventListener is a killer too, make sure these are removed if you use them!

ps: i totally understand the 7 windows bit :-)

ContentLicense: CC BY-SA 4.0


问:
Joomla increase frontend session time out limit
I want to set joomla front end session to never expire automatically.I am thinking that session time out limit should be 45 days so that users visiting site even after 44 days they still be logged in.I set session timeout limit in back end in the global configuration to expire in 64800 minutes and also I updated the session.gc_maxlifetime to say 3888000 but still it is not working.

Joomla creates the cookie with the name d58ba4091c622661a0d46f03b412ac8b and expiry time says 'At end of session'.

This means that session will expire whenever a user close the browser.

Expiry time should be changed for this cookie according to configuration settings but it still say At end of session .

for an example how stackoverflow session works I need to do in same way.

Is there any way to change this cookie life time from 'At end of session' to something I want?

Should I hard code time limit where this cookie come in existences or how to do this?

Thanks.

答: You definitely don't want to make the session never expire because this will cause all kinds of server and security issues. You need to change the expiration of the cookie to some date in the future. The easiest way to do this would be a plugin that checks for the cookie and updates the exiration.</p>


答:
I can see one problem from a quick glance and that is a missing comma in your creation statement which would mean that your database was not created as you intended. Try the below amendment.</p>

```<code>String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL_2 +" TEXT," + COL_3 +" TEXT)";
</code>```

Title: Android Java SQLite database: The database does not take 2 String inputs

Body:
I can see one problem from a quick glance and that is a missing comma in your creation statement which would mean that your database was not created as you intended. Try the below amendment.

String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL_2 +" TEXT," + COL_3 +" TEXT)";


问:
mongo command not recognized when trying to connect to a mongodb server
I am following the tutorials at docs.mongodb.org, I have completed the first tutorial which was to install mongodb on a Windows machine. I am now at the second stage which is getting started with mongodb development.

I am stuck at the first stage of this section which instructs me to type mongo into a system prompt. When I do this I simply get an error message saying the following:

```<code>'mongo' is not recognized as an internal or external command, operable program or batch file
</code>```

I know this is probably something quite simple that I am doing wrong, does anyone have any ideas?

答: if still not working for you then just close all of your command prompts and then again open and run mongo, mongoimport, mongodb from anywhere it ll work because after setting the path variable command prompt should be restarted.</p>

Body:
I am following the tutorials at docs.mongodb.org, I have completed the first tutorial which was to install mongodb on a Windows machine. I am now at the second stage which is getting started with mongodb development.

I am stuck at the first stage of this section which instructs me to type mongo into a system prompt. When I do this I simply get an error message saying the following:

'mongo' is not recognized as an internal or external command, operable program or batch file

I know this is probably something quite simple that I am doing wrong, does anyone have any ideas?


问:
How to return starting and end point of a path in a hierarchical structure
I have a table that looks like that

```<code>---------------------------
| id1 | id2 | col1 | col2 |
+-----+-----+------+------+
|  1  |  1  |  a   |  b   |
|-----+-----+------+------|
|  1  |  2  |  b   |  c   |
|-----+-----+------+------|
|  5  |  1  |  d   |  f   |
---------------------------
</code>```

The idea is that the table stores paths: a->b->c and d->f. What I want is a query that will return a->c and d->f.

答:
You need a recursive query:

```<code>with recursive find_path (col1, col2, depth) as (
    select col1, col2, 1
    from my_table t
    where not exists (
        select 1
        from my_table
        where col2 = t.col1)
union all
    select p.col1, t.col2, depth+ 1
    from my_table t
    join find_path p on p.col2 = t.col1
)

select distinct on (col1) format('%s -> %s', col1, col2) as path
from find_path
order by col1, depth desc;

  path
--------
 a -> c
 d -> f
(2 rows)
</code>```

The question is not quite clear. If your aim is to get the paths in partitions by id1 in order by id2, you can use the window functions:

```<code>select distinct on (id1)
    id1, first_value(col1) over w, last_value(col2) over w
from my_table
window
    w as (partition by id1 order by id2)
order by id1, id2 desc;

 id1 | first_value | last_value
-----+-------------+------------
   1 | a           | c
   5 | d           | f
(2 rows)
</code>```

Body:
I have a table that looks like that

---------------------------
| id1 | id2 | col1 | col2 |
+-----+-----+------+------+
|  1  |  1  |  a   |  b   |
|-----+-----+------+------|
|  1  |  2  |  b   |  c   |
|-----+-----+------+------|
|  5  |  1  |  d   |  f   |
---------------------------

The idea is that the table stores paths: a->b->c and d->f. What I want is a query that will return a->c and d->f.

Body:
You need a recursive query:

with recursive find_path (col1, col2, depth) as (
    select col1, col2, 1
    from my_table t
    where not exists (
        select 1
        from my_table
        where col2 = t.col1)
union all
    select p.col1, t.col2, depth+ 1
    from my_table t
    join find_path p on p.col2 = t.col1
)

select distinct on (col1) format('%s -> %s', col1, col2) as path
from find_path
order by col1, depth desc;

  path
--------
 a -> c
 d -> f
(2 rows)

The question is not quite clear. If your aim is to get the paths in partitions by id1 in order by id2, you can use the window functions:

select distinct on (id1)
    id1, first_value(col1) over w, last_value(col2) over w
from my_table
window
    w as (partition by id1 order by id2)
order by id1, id2 desc;

 id1 | first_value | last_value
-----+-------------+------------
   1 | a           | c
   5 | d           | f
(2 rows)


问:
Can not export webpack.config when modules:false
Inside my index.js I am using webpack-dev-middleware/webpack-hot-middleware where I require my webpack.config and use it for compiler.

index.js

```<code>  const webpack = require('webpack')
  const webpackConfig = require('../../webpack.config.js')
  const compiler = webpack(webpackConfig)
  const webpackDevMiddleware = require('webpack-dev-middleware')

  app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    hot: true,
    noInfo: true,
    stats: {
      colors: true
    }
  }))

  app.use(require('webpack-hot-middleware')(compiler))
</code>```

I try to export my webpack.config using Common.js by require and module.exports but I get error

```<code>TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
</code>```

webpack.config

```<code>'use strict'

const path = require('path')
const webpack = require('webpack')
const publicPath = path.resolve(__dirname, './src/client')
const buildPath = path.resolve(__dirname, './src')

process.noDeprecation = true

module.exports = {
  devtool: 'source-maps',
  performance: {
    hints: false
  },
  context: publicPath,
  entry: {
    bundle: [
      'react-hot-loader/patch',
      'webpack-hot-middleware/client?reload=false&noInfo=true',
      'script-loader!jquery/dist/jquery.min.js',
      'script-loader!tether/dist/js/tether.min.js',
      'script-loader!bootstrap/dist/js/bootstrap.min.js',
      './app.js'
    ]
  },
  output: {
    path: path.join(buildPath, 'dist'),
    filename: '[name].js',
    publicPath: '/'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      CountdownForm: path.resolve(__dirname, 'src/client/scenes/countdown/components/CountdownForm.jsx'),
      Countdown: path.resolve(__dirname, 'src/client/scenes/countdown/index.jsx'),
     ..
    }
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules|dist|build/,
        loader: 'babel-loader',
        options: {
          plugins: [
            [
              'babel-plugin-react-css-modules',
              {
                context: publicPath,
                filetypes: {
                  '.scss': 'postcss-scss'
                }
              }
            ]
          ]
        }
      },
      {
        test: /\.local\.(css|scss)$/,
        use: [
          'style-loader',
          'css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
          'postcss-loader',
          'sass-loader',
          {
            loader: 'sass-resources-loader',
            options: {
              resources: path.resolve(__dirname, './src/client/styles/global/sass-resources.scss')
            }
          }
        ]
      },
      {
        test: /^((?!\.local).)+\.(css|scss)$/,
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader',
          'sass-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      jquery: 'jquery'
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development')
      }
    })
  ]
}
</code>```

If I use ES6 (I am using babel and this usually works) using import statements at the top instead of require and export default instead of module.exports I get this error

```<code>Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration misses the property 'entry'.
</code>```

All of this is because of modules:false inside my .babelrc If I remove that Common.js way works, but I need this. How can I export webpack.config to compiler using modules:false

```<code>{
  "presets": [
    "react",
    ["es2015", { "modules": false }],
    "stage-0"
  ],
  "plugins": [
    "react-hot-loader/babel",
    "transform-runtime"
  ]
}
</code>```

答:
transform-runtime adds import and that results in mixing import with your module.exports.

Simple fix would be to replace module.exports with es6 export

```<code>module.exports = { ...webpackconfig }
</code>```

becomes

```<code>export default { ...webpackconfig }
</code>```

and update your index.js to use default export

```<code>const webpackConfig = require('../../webpack.config.js').default
</code>```

You can find more information about this on these issues

https://github.com/webpack/webpack/issues/4039
https://github.com/webpack/webpack/issues/3917

Body:
Inside my index.js I am using webpack-dev-middleware/webpack-hot-middleware where I require my webpack.config and use it for compiler.

index.js

  const webpack = require('webpack')
  const webpackConfig = require('../../webpack.config.js')
  const compiler = webpack(webpackConfig)
  const webpackDevMiddleware = require('webpack-dev-middleware')

  app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    hot: true,
    noInfo: true,
    stats: {
      colors: true
    }
  }))

  app.use(require('webpack-hot-middleware')(compiler))

I try to export my webpack.config using Common.js by require and module.exports but I get error

TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

webpack.config

'use strict'

const path = require('path')
const webpack = require('webpack')
const publicPath = path.resolve(__dirname, './src/client')
const buildPath = path.resolve(__dirname, './src')

process.noDeprecation = true

module.exports = {
  devtool: 'source-maps',
  performance: {
    hints: false
  },
  context: publicPath,
  entry: {
    bundle: [
      'react-hot-loader/patch',
      'webpack-hot-middleware/client?reload=false&noInfo=true',
      'script-loader!jquery/dist/jquery.min.js',
      'script-loader!tether/dist/js/tether.min.js',
      'script-loader!bootstrap/dist/js/bootstrap.min.js',
      './app.js'
    ]
  },
  output: {
    path: path.join(buildPath, 'dist'),
    filename: '[name].js',
    publicPath: '/'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      CountdownForm: path.resolve(__dirname, 'src/client/scenes/countdown/components/CountdownForm.jsx'),
      Countdown: path.resolve(__dirname, 'src/client/scenes/countdown/index.jsx'),
     ..
    }
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules|dist|build/,
        loader: 'babel-loader',
        options: {
          plugins: [
            [
              'babel-plugin-react-css-modules',
              {
                context: publicPath,
                filetypes: {
                  '.scss': 'postcss-scss'
                }
              }
            ]
          ]
        }
      },
      {
        test: /\.local\.(css|scss)$/,
        use: [
          'style-loader',
          'css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
          'postcss-loader',
          'sass-loader',
          {
            loader: 'sass-resources-loader',
            options: {
              resources: path.resolve(__dirname, './src/client/styles/global/sass-resources.scss')
            }
          }
        ]
      },
      {
        test: /^((?!\.local).)+\.(css|scss)$/,
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader',
          'sass-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      jquery: 'jquery'
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development')
      }
    })
  ]
}

If I use ES6 (I am using babel and this usually works) using import statements at the top instead of require and export default instead of module.exports I get this error

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration misses the property 'entry'.

All of this is because of modules:false inside my .babelrc If I remove that Common.js way works, but I need this. How can I export webpack.config to compiler using modules:false

{
  "presets": [
    "react",
    ["es2015", { "modules": false }],
    "stage-0"
  ],
  "plugins": [
    "react-hot-loader/babel",
    "transform-runtime"
  ]
}

Body:
transform-runtime adds import and that results in mixing import with your module.exports.

Simple fix would be to replace module.exports with es6 export

module.exports = { ...webpackconfig }

becomes

export default { ...webpackconfig }

and update your index.js to use default export

const webpackConfig = require('../../webpack.config.js').default

You can find more information about this on these issues

https://github.com/webpack/webpack/issues/4039
https://github.com/webpack/webpack/issues/3917


问:
Angula2 input not binding
I am trying to  bind some data but is not working on

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
 template : `<child [in]="25"></child>`
 })
export class AppComponent {}
</code>```

and the child component

```<code>import { Component, Input } from '@angular/core';
@Component({
  selector: 'child',
  template: '<h1>{{in}}</h1>',
})

export class ChildComponent {

   @Input()  in: string;
 }
</code>```

答:
You have two ways of assigning values to an input of a component:

1) Either by passing directly the string value to the input from the template:

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
 template : `<child in="25"></child>`
 })
export class AppComponent {}
</code>```

2) Or by binding the input to a variable defined in your class:

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
 template : `<child [in]="myVar"></child>`
 })
export class AppComponent {
  public myVar: string = "25";
}
</code>```

As a result you cannot bind the input to a numeric variable as you did here, simply because a variable defined in a class cannot be numeric (but it surely can be alphanumeric).

Title: Angula2 input not binding

Body:
I am trying to  bind some data but is not working on

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
 template : `<child [in]="25"></child>`
 })
export class AppComponent {}

and the child component

import { Component, Input } from '@angular/core';
@Component({
  selector: 'child',
  template: '
{{in}}
',
})

export class ChildComponent {

   @Input()  in: string;
 }

Body:
You have two ways of assigning values to an input of a component:

1) Either by passing directly the string value to the input from the template:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
 template : `<child in="25"></child>`
 })
export class AppComponent {}

2) Or by binding the input to a variable defined in your class:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
 template : `<child [in]="myVar"></child>`
 })
export class AppComponent {
  public myVar: string = "25";
}

As a result you cannot bind the input to a numeric variable as you did here, simply because a variable defined in a class cannot be numeric (but it surely can be alphanumeric).


问:
Array number that are multiples of 3
I need to get all number that multiples of 3.
Can someone help me to write it?  Here is what I have so far:</p>

```<code>int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

public class Main {
public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i / 3; i / myList.length;) {

        }
    }
    System.out.println(i / 3 );

}

}
</code>```

答:
you can write like this:</p>

```<code>import java.io.*;
public class Main {
    public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i = 0; i < myList.length; i++) {
            if (myList[i] % 3 == 0) {
                System.out.println(myList[i]); // numbers that are divisible by three
            }
            if (isPrime(myList[i]) == 1) {
               System.out.println(myList[i]); //print prime no.s
            }
        }
    }
    static int isPrime(int n) {
      if (n < 2) return 0;

      for (int i = 2; i*i <= n; i++) {
        if (n%i == 0) {
           return 0;
        }
      }
      return 1;
    }
}
</code>```

Title: Array number that are multiples of 3

Body:
I need to get all number that multiples of 3.
Can someone help me to write it?  Here is what I have so far:

int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

public class Main {
public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i / 3; i / myList.length;) {

        }
    }
    System.out.println(i / 3 );

}

}

Body:
you can write like this:

import java.io.*;
public class Main {
    public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i = 0; i < myList.length; i++) {
            if (myList[i] % 3 == 0) {
                System.out.println(myList[i]); // numbers that are divisible by three
            }
            if (isPrime(myList[i]) == 1) {
               System.out.println(myList[i]); //print prime no.s
            }
        }
    }
    static int isPrime(int n) {
      if (n < 2) return 0;

      for (int i = 2; i*i <= n; i++) {
        if (n%i == 0) {
           return 0;
        }
      }
      return 1;
    }
}


问:
Does wifi scanning comply with Apple's guidelines to scan wifi hotspot on ios4
Does wifi scanning comply with Apple's guidelines to scan wifi hotspot on ios4</p>

答: Does it comply with Apple? You're really asking if Apple will reject it? You can just send it and find out. It's the only way to be sure.</p>


问:
webscraping in R
I am trying to scrape the website property 24 website.
However it returns extra data rows which is not on the page. Here is my code. </p>

```<code>library(rvest)
property<- read_html("https://www.property24.com/houses-for-sale/cape-
   town/western-cape/432")
price <-property%>% html_nodes(".p24_price") %>% html_text()
desc  <-property%>% html_nodes(".p24_excerpt")%>%html_text()
title <-property%>% html_nodes(".p24_title")%>%html_text()

price = gsub("[^0-9]","", price)
desc = gsub("[ \t]{2,}", "", desc)
desc = gsub("\r\n", "", desc)
desc = strtrim(desc,100)

property_table<-data.frame(price,title,desc)
</code>```

答:
The problem is that the price, title, desc vectors have different lengths.

Why is that? Look at their contents.

You will find that some values don't look like a proper price or description.
Because the patterns .p24_price and .p24_excerpt are not specific enough.
You need to look at the page source, and make the patterns more specific.
For example this will be better:

```<code>price <- property %>% html_nodes(".p24_content .p24_price") %>% html_text()
desc  <- property %>% html_nodes(".p24_content .p24_excerpt") %>% html_text()
title <- property %>% html_nodes(".p24_content .p24_title") %>% html_text()
</code>```

But I see at least one more problem.
Some properties have more than one price,
for example:

From R 12 250 000 to R 13 995 999

So the way you extract the price part using gsub needs improvement too.

Title: webscraping in R

Body:
I am trying to scrape the website property 24 website.
However it returns extra data rows which is not on the page. Here is my code.

library(rvest)
property<- read_html("https://www.property24.com/houses-for-sale/cape-
   town/western-cape/432")
price <-property%>% html_nodes(".p24_price") %>% html_text()
desc  <-property%>% html_nodes(".p24_excerpt")%>%html_text()
title <-property%>% html_nodes(".p24_title")%>%html_text()

price = gsub("[^0-9]","", price)
desc = gsub("[ \t]{2,}", "", desc)
desc = gsub("\r\n", "", desc)
desc = strtrim(desc,100)

property_table<-data.frame(price,title,desc)

Body:
The problem is that the price, title, desc vectors have different lengths.

Why is that? Look at their contents.

You will find that some values don't look like a proper price or description.
Because the patterns .p24_price and .p24_excerpt are not specific enough.
You need to look at the page source, and make the patterns more specific.
For example this will be better:

price <- property %>% html_nodes(".p24_content .p24_price") %>% html_text()
desc  <- property %>% html_nodes(".p24_content .p24_excerpt") %>% html_text()
title <- property %>% html_nodes(".p24_content .p24_title") %>% html_text()

But I see at least one more problem.
Some properties have more than one price,
for example:

From R 12 250 000 to R 13 995 999

So the way you extract the price part using gsub needs improvement too.


问:
Spacing at last part of the regex
I've the following regex:

/(\(*)?(\d+)(\)*)?([+\-*\/^%]+)(\(*)?(\)*)?/g

I have the following string:

(5+4+8+5)+(5^2/(23%2))

I use the regex to add space between numbers, arithmetic operators and parentheses.

I do that like:

\1 \2 \3 \4 \5 \6

That turns the string into:

( 5  +   4  +   8  +   5 ) + (  5  ^   2  / (  23  %  2))

As you can see the last two parentheses don't get spaced.

How can I make them space as well?

The output should look like:

( 5  +   4  +   8  +   5 ) + (  5  ^   2  / (  23  %  2 ))

Try out the regex here.

答:
You can try something like this based on word boundaries and on non-word characters:

```<code>\b(?!^|$)|\W\K(?=\W)
</code>```

and replace with a space.

demo

details:

```<code>\b      # a word-boundary
(?!^|$) # not at the start or at the end of the string
|       # OR
\W      # a non-word character
\K      # remove characters on the left from the match result
(?=\W)  # followed by a non-word character
</code>```

Title: Spacing at last part of the regex

Body:
You can try something like this based on word boundaries and on non-word characters:

\b(?!^|$)|\W\K(?=\W)

and replace with a space.

demo

details:

\b      # a word-boundary
(?!^|$) # not at the start or at the end of the string
|       # OR
\W      # a non-word character
\K      # remove characters on the left from the match result
(?=\W)  # followed by a non-word character


问:
Setting flycheck-clang-include-path in .dir-locals using projectile
Trying to set flycheck-clang-include-path without the need to include the full path of the project include directories using projectile, but I get errors... So this works:

```<code>((nil . (
     (company-clang-arguments . (
                     "/home/user/Downloads/project/headers"
                     "/home/user/Downloads/project/source/mon"
                     ))
         (flycheck-clang-include-path . (
                     "/home/user/Downloads/project/headers"
                     "/home/user/Downloads/project/source/mon"
                     ))
     )))
</code>```

But this does not:

```<code>((nil . (
     (company-clang-arguments . (
                     (concat "-I" (projectile-project-root) "headers")
                     (concat "-I" (projectile-project-root) "source/mon")
                     ))
         (flycheck-clang-include-path . (
                     (concat (projectile-project-root) "headers")
                     (concat (projectile-project-root) "source/mon")
                     ))
     )))
</code>```

The error that is reported:

```<code>flycheck-substitute-argument: Value ((concat (projectile-project-root) "headers")) of flycheck-clang-include-path for option "-I" is not a list of strings
</code>```

答:
One possibility is using an eval to evaluate the quoted forms in your dir-locals.  This may be considered unsafe since anything could be evaluated in such a form.

```<code>((nil
  (eval . (let ((root (projectile-project-root)))
            (setq-local company-clang-arguments
                        (list (concat "-I" root "headers")
                              (concat "-I" root "source/mon")))
            (setq-local flycheck-clang-include-path
                        (list (concat root "headers")
                              (concat root "source/mon")))))))
</code>```

Body:
Trying to set flycheck-clang-include-path without the need to include the full path of the project include directories using projectile, but I get errors... So this works:

((nil . (
     (company-clang-arguments . (
                     "/home/user/Downloads/project/headers"
                     "/home/user/Downloads/project/source/mon"
                     ))
         (flycheck-clang-include-path . (
                     "/home/user/Downloads/project/headers"
                     "/home/user/Downloads/project/source/mon"
                     ))
     )))

But this does not:

((nil . (
     (company-clang-arguments . (
                     (concat "-I" (projectile-project-root) "headers")
                     (concat "-I" (projectile-project-root) "source/mon")
                     ))
         (flycheck-clang-include-path . (
                     (concat (projectile-project-root) "headers")
                     (concat (projectile-project-root) "source/mon")
                     ))
     )))

The error that is reported:

flycheck-substitute-argument: Value ((concat (projectile-project-root) "headers")) of flycheck-clang-include-path for option "-I" is not a list of strings

Body:
One possibility is using an eval to evaluate the quoted forms in your dir-locals.  This may be considered unsafe since anything could be evaluated in such a form.

((nil
  (eval . (let ((root (projectile-project-root)))
            (setq-local company-clang-arguments
                        (list (concat "-I" root "headers")
                              (concat "-I" root "source/mon")))
            (setq-local flycheck-clang-include-path
                        (list (concat root "headers")
                              (concat root "source/mon")))))))


问:
Runnable code not stopping for Android
I've already checked this SO post but to no avail: removeCallbacks not stopping runnable

What my app does: I have 2 imageViews. When app runs, one imageView should change it's image from sleep image to wake up image and then back to sleep image. Then handler used for delay before doing same thing for 2nd imageView. And then I want Runnable to stop. I'm using Android's frame animation.
Please help!

```<code>public class MainActivity extends Activity {

    AnimationDrawable[] animDrawList;
    ImageView im;
    ImageView im2;

    private int curPos;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        animDrawList = new AnimationDrawable[2];
        curPos = 0;

        im = (ImageView)findViewById(R.id.image1);
        im2 = (ImageView)findViewById(R.id.image2);

        im.setBackgroundResource(R.drawable.animation_to_run);
        im2.setBackgroundResource(R.drawable.animation_to_run);

        animDrawList[0] = (AnimationDrawable) im.getBackground();
        animDrawList[1] = (AnimationDrawable) im2.getBackground();

        mHandler = new Handler();

        startTask();
    }

    Runnable myThread = new Runnable() {

        volatile boolean stopMe = false;

        @Override
        public void run() {

            if ( curPos <= 1 ) {
                animDrawList[curPos].start();
                curPos++;
            }
            if ( curPos > 1 ) {
                stopMe = true;
            }

            if ( stopMe ) {
                stopTask();
                return;
            }

            mHandler.postDelayed(myThread, 1000);
        }
    };

    void startTask() { myThread.run();  }

    void stopTask() { mHandler.removeCallbacks(myThread); }

}//end of MainActivity class
</code>```

Here is my layout file that's straighforward :

```<code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.example.a.MainActivity">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="90px"
        android:layout_height="90px"
        android:layout_alignParentStart="true"
        android:layout_marginStart="14dp"
        android:layout_marginTop="13dp" />

    <ImageView
        android:id="@+id/image2"
        android:layout_width="90px"
        android:layout_height="90px"
        android:layout_marginEnd="49dp"
        android:layout_marginBottom="93dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>
</code>```

Here is my xml file.

```<code> <?xml version="1.0" encoding="utf-8"?>

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"

    android:oneshot="false">

    <item android:drawable="@drawable/restState" android:duration="1000" />
    <item android:drawable="@drawable/upState" android:duration="1000" />
    <item android:drawable="@drawable/restState" android:duration="1000" />

</animation-list>
</code>```

The app runs, no crashes, but it doesn't stop. I want the Runnable to stop after animating, why isn't my flag "stopMe" doing it's job?

UPDATE FROM JUN 4, 2017: I removed the animation code inside the run method and and added logcat output insted in run method and Runnable does stop with "stopMe" boolean so it's issue with the frame animation, is it I can't combine Android's frame animation with Runnable? I'll look into it...

答: I've solved it! I had to set the AnimationDrawable object's setOneShow(boolean playAnimationOncePerAnimationDrawableObject) to true! Voila! </p>

Title: Runnable code not stopping for Android

Body:
I've already checked this SO post but to no avail: removeCallbacks not stopping runnable

What my app does: I have 2 imageViews. When app runs, one imageView should change it's image from sleep image to wake up image and then back to sleep image. Then handler used for delay before doing same thing for 2nd imageView. And then I want Runnable to stop. I'm using Android's frame animation.
Please help!

public class MainActivity extends Activity {

    AnimationDrawable[] animDrawList;
    ImageView im;
    ImageView im2;

    private int curPos;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        animDrawList = new AnimationDrawable[2];
        curPos = 0;

        im = (ImageView)findViewById(R.id.image1);
        im2 = (ImageView)findViewById(R.id.image2);

        im.setBackgroundResource(R.drawable.animation_to_run);
        im2.setBackgroundResource(R.drawable.animation_to_run);

        animDrawList[0] = (AnimationDrawable) im.getBackground();
        animDrawList[1] = (AnimationDrawable) im2.getBackground();

        mHandler = new Handler();

        startTask();
    }

    Runnable myThread = new Runnable() {

        volatile boolean stopMe = false;

        @Override
        public void run() {

            if ( curPos <= 1 ) {
                animDrawList[curPos].start();
                curPos++;
            }
            if ( curPos > 1 ) {
                stopMe = true;
            }

            if ( stopMe ) {
                stopTask();
                return;
            }

            mHandler.postDelayed(myThread, 1000);
        }
    };

    void startTask() { myThread.run();  }

    void stopTask() { mHandler.removeCallbacks(myThread); }

}//end of MainActivity class

Here is my layout file that's straighforward :

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.example.a.MainActivity">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="90px"
        android:layout_height="90px"
        android:layout_alignParentStart="true"
        android:layout_marginStart="14dp"
        android:layout_marginTop="13dp" />

    <ImageView
        android:id="@+id/image2"
        android:layout_width="90px"
        android:layout_height="90px"
        android:layout_marginEnd="49dp"
        android:layout_marginBottom="93dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

Here is my xml file.

 <?xml version="1.0" encoding="utf-8"?>

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"

    android:oneshot="false">

    <item android:drawable="@drawable/restState" android:duration="1000" />
    <item android:drawable="@drawable/upState" android:duration="1000" />
    <item android:drawable="@drawable/restState" android:duration="1000" />

</animation-list>

The app runs, no crashes, but it doesn't stop. I want the Runnable to stop after animating, why isn't my flag "stopMe" doing it's job?

UPDATE FROM JUN 4, 2017: I removed the animation code inside the run method and and added logcat output insted in run method and Runnable does stop with "stopMe" boolean so it's issue with the frame animation, is it I can't combine Android's frame animation with Runnable? I'll look into it...


问:
How to call Stored Procedure with Eloquent (Laravel)?
There is no standard procedure mentioned in documentation that how to call a stored procedure in MYSQL in laravel with Eloquent syntax.

I mean is there any way to call stored procedure in mysql with help of eloquent syntax like

```<code>$result = StoredProcedures::my_custom_procedure(param1, param2);
return view('welcome')->with('result',$result);
</code>```

Is there any way to call and fetch results from stored procedures with pure eloquent syntax(purely eloquent way).

Thanks. Small examples are highly encouraged .

答:
You cannot call stored procedure with eloquent. However you can use query builder approach in the following style.

first import the following namespaces on top of the controller file or in the file where you want to call the Stored Procedure.

```<code>use Illuminate\Support\Facades\DB;
use Doctrine\DBAL\Driver\PDOConnection;
</code>```

then you can call the stored procedure like below,

```<code>$queryResult = $db->prepare('call searchAttendance(?,?,?,?,?)');
$queryResult->bindParam(1, $start_date);
$queryResult->bindParam(2, $end_date);
$queryResult->bindParam(3, $nurseRoles,PDOConnection::PARAM_STR);
$queryResult->bindParam(4, $leaveTypesDayOffIds,PDOConnection::PARAM_STR);
$queryResult->bindParam(5, $leaveTypesVactionIds,PDOConnection::PARAM_STR);
$queryResult->execute();
$results = $queryResult->fetchAll(PDOConnection::FETCH_ASSOC);
$queryResult->closeCursor();
return $results;
</code>```

reference: Click here

Body:
There is no standard procedure mentioned in documentation that how to call a stored procedure in MYSQL in laravel with Eloquent syntax.

I mean is there any way to call stored procedure in mysql with help of eloquent syntax like

$result = StoredProcedures::my_custom_procedure(param1, param2);
return view('welcome')->with('result',$result);

Is there any way to call and fetch results from stored procedures with pure eloquent syntax(purely eloquent way).

Thanks. Small examples are highly encouraged .

Body:
You cannot call stored procedure with eloquent. However you can use query builder approach in the following style.

first import the following namespaces on top of the controller file or in the file where you want to call the Stored Procedure.

use Illuminate\Support\Facades\DB;
use Doctrine\DBAL\Driver\PDOConnection;

then you can call the stored procedure like below,

$queryResult = $db->prepare('call searchAttendance(?,?,?,?,?)');
$queryResult->bindParam(1, $start_date);
$queryResult->bindParam(2, $end_date);
$queryResult->bindParam(3, $nurseRoles,PDOConnection::PARAM_STR);
$queryResult->bindParam(4, $leaveTypesDayOffIds,PDOConnection::PARAM_STR);
$queryResult->bindParam(5, $leaveTypesVactionIds,PDOConnection::PARAM_STR);
$queryResult->execute();
$results = $queryResult->fetchAll(PDOConnection::FETCH_ASSOC);
$queryResult->closeCursor();
return $results;

reference: Click here


问:
ASP.net ListBox currency formatting
Ok guys, I have a ListBox which displays products (they are a custom class and have ID, name, price) that are in a binding list.. I want the ListBox to display the item name AND the price. The listbox (lbProductsChosen) has "DataTextField" set to the Name and DataValueField set to the ID. I am using the PreRender event to check each Item, look at its price from the binding list (blProducts) etc. and it works great. I get the name and price displayed in the list with this. However, when it is displayed, despite me formatting it using String.Format, the result is still a decimal number (ex. 3.20000) and it just looks ugly. Does anyone know why its working to display it, but not displaying it how I want it formatted.</p>

```<code>    protected void lbProductsChosen_PreRender(object sender, EventArgs e)
    {
        foreach (ListItem item in lbProductsChosen.Items)
        {
            string currentDescription = item.Text;
            int convertedValue = Convert.ToInt32(item.Value);
            for (int i = 0; i < blProducts.Count; i++)
            {
                if (blProducts[i].ProductID == convertedValue)
                {
                    decimal ItemPrice = blProducts[i].Price;
                    string convertedPrice = ItemPrice.ToString();
                    string currentPrice = String.Format("{0:c}", convertedPrice);
                    string currentDescriptionPadded = currentDescription.PadRight(30);
                    item.Text = currentDescriptionPadded + currentPrice;
                }
            }
        }
    }
</code>```

答:
MSDN states the following about the String.Format method.

Generally, objects in the argument list are converted to their string representations by using the conventions of the current culture, which is returned by the CultureInfo.CurrentCulture property.

If you use the currency format specifier c it will use the currency format which is defined in the system settings. Take a look under control panel -> region -> additional settings -> currency. Maybe you have messed up settings there.

If you want to ignore the local settings which would make sense for currency you could do the following. (example in dollar with allways two decimal places)

```<code>decimal price = 12.10999999m;
String.Format("${0:0.00}", price);
</code>```

$12.10

Be aware of that String.Format doesn't round the number correctly but just cuts it off.

Title: ASP.net ListBox currency formatting

Body:
Ok guys, I have a ListBox which displays products (they are a custom class and have ID, name, price) that are in a binding list.. I want the ListBox to display the item name AND the price. The listbox (lbProductsChosen) has "DataTextField" set to the Name and DataValueField set to the ID. I am using the PreRender event to check each Item, look at its price from the binding list (blProducts) etc. and it works great. I get the name and price displayed in the list with this. However, when it is displayed, despite me formatting it using String.Format, the result is still a decimal number (ex. 3.20000) and it just looks ugly. Does anyone know why its working to display it, but not displaying it how I want it formatted.

    protected void lbProductsChosen_PreRender(object sender, EventArgs e)
    {
        foreach (ListItem item in lbProductsChosen.Items)
        {
            string currentDescription = item.Text;
            int convertedValue = Convert.ToInt32(item.Value);
            for (int i = 0; i < blProducts.Count; i++)
            {
                if (blProducts[i].ProductID == convertedValue)
                {
                    decimal ItemPrice = blProducts[i].Price;
                    string convertedPrice = ItemPrice.ToString();
                    string currentPrice = String.Format("{0:c}", convertedPrice);
                    string currentDescriptionPadded = currentDescription.PadRight(30);
                    item.Text = currentDescriptionPadded + currentPrice;
                }
            }
        }
    }

Body:
MSDN states the following about the String.Format method.

Generally, objects in the argument list are converted to their string representations by using the conventions of the current culture, which is returned by the CultureInfo.CurrentCulture property.

If you use the currency format specifier c it will use the currency format which is defined in the system settings. Take a look under control panel -> region -> additional settings -> currency. Maybe you have messed up settings there.

If you want to ignore the local settings which would make sense for currency you could do the following. (example in dollar with allways two decimal places)

decimal price = 12.10999999m;
String.Format("${0:0.00}", price);

$12.10

Be aware of that String.Format doesn't round the number correctly but just cuts it off.


问:
StackoverflowExcepton in Spring message i18n ReloadableResourceBundleMessageSource
I am enabling message i18n in my Spring web app. For this, I have below code in my servlet.xml

```<code><bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages/message"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
</code>```

After adding above code, as soon as I hit my application in browser, I get below exception log:

```<code>SEVERE: Servlet.service() for servlet [default] in context with path [/ERP-Web] threw exception [Filter execution threw an exception] with root cause
java.lang.StackOverflowError
    at org.springframework.context.support.ReloadableResourceBundleMessageSource.getMergedProperties(ReloadableResourceBundleMessageSource.java:235)
    at org.springframework.context.support.ReloadableResourceBundleMessageSource.resolveCodeWithoutArguments(ReloadableResourceBundleMessageSource.java:176)
    at org.springframework.context.support.AbstractMessageSource.getMessageInternal(AbstractMessageSource.java:209)
    at org.springframework.context.support.AbstractMessageSource.getMessageFromParent(AbstractMessageSource.java:257)
</code>```

where last 2 lines were repeated 100s of times and gives me StackoverflowException.

Exactly same exception is coming when I am using ResourceBundleMessageSource class.

My spring version is 4.3.6.RELEASE.

Below is content of my properties file

```<code>action.add.success = New {0} added successfully.
action.add.failure = Some error occurred in adding new {0}. Please try again later or contact administrator.
</code>```

Sample project is on GitHub

答:
I have tested your sample code in github and when running it has shown the error described, then modify the following:

Config:

```<code><bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages/message"/>
        <property name="defaultEncoding" value="UTF-8"/>
</bean>
</code>```

Class:

```<code>@RequestMapping(method=RequestMethod.GET)
@ResponseBody
public String getMessage() {
    String msg = messageSource.getMessage("hello.world", null, LocaleContextHolder.getLocale());
    return msg;
}
</code>```

hello.word is the property with text in your file with name message_en.properties.

With this modifications the code run.

Edit for unknown message codes:

I tried with unknown message codes and the error was repeated, so I look at the registry and found that there could be more than one beans with the same name (potential circular references), but I have not detected why this happens, but if you It needs to work you have to rename the beans like this.

```<code><bean id="myMessageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages/message"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
</code>```

and then use:

```<code>@Autowired
private MessageSource myMessageSource;
</code>```

but i think this not resolve the principal problem with the circular potential error.

Body:
I am enabling message i18n in my Spring web app. For this, I have below code in my servlet.xml

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages/message"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

After adding above code, as soon as I hit my application in browser, I get below exception log:

SEVERE: Servlet.service() for servlet [default] in context with path [/ERP-Web] threw exception [Filter execution threw an exception] with root cause
java.lang.StackOverflowError
    at org.springframework.context.support.ReloadableResourceBundleMessageSource.getMergedProperties(ReloadableResourceBundleMessageSource.java:235)
    at org.springframework.context.support.ReloadableResourceBundleMessageSource.resolveCodeWithoutArguments(ReloadableResourceBundleMessageSource.java:176)
    at org.springframework.context.support.AbstractMessageSource.getMessageInternal(AbstractMessageSource.java:209)
    at org.springframework.context.support.AbstractMessageSource.getMessageFromParent(AbstractMessageSource.java:257)

where last 2 lines were repeated 100s of times and gives me StackoverflowException.

Exactly same exception is coming when I am using ResourceBundleMessageSource class.

My spring version is 4.3.6.RELEASE.

Below is content of my properties file

action.add.success = New {0} added successfully.
action.add.failure = Some error occurred in adding new {0}. Please try again later or contact administrator.

Sample project is on GitHub

Body:
I have tested your sample code in github and when running it has shown the error described, then modify the following:

Config:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages/message"/>
        <property name="defaultEncoding" value="UTF-8"/>
</bean>

Class:

@RequestMapping(method=RequestMethod.GET)
@ResponseBody
public String getMessage() {
    String msg = messageSource.getMessage("hello.world", null, LocaleContextHolder.getLocale());
    return msg;
}

hello.word is the property with text in your file with name message_en.properties.

With this modifications the code run.

Edit for unknown message codes:

I tried with unknown message codes and the error was repeated, so I look at the registry and found that there could be more than one beans with the same name (potential circular references), but I have not detected why this happens, but if you It needs to work you have to rename the beans like this.

<bean id="myMessageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages/message"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

and then use:

@Autowired
private MessageSource myMessageSource;

but i think this not resolve the principal problem with the circular potential error.


问:
Appcelerator fails to publish Android app after update (Android SDK version 5.1.1 not found.)
Fails to work after update, keep saying "Android SDK version 5.1.1 not found."

but it's already installed

Tried a clean install and still getting same error

Using:
Appcelerator Studio 4.8.1.201612050850

答: Have you by any chance updated your Java version at the same time? I had a similar issue with Java 8 and had to downgrade it again to 7.</p>


问:
Application freezes for some time
In my app I have a login view. When I enter login details and click login button, the app freezes for some time and then continues. I know it's freezing because it is communicating with remote server but how can I prevent the freeze thing and show a nice looking status animation instead?</p>

答: Your API call is blocking the GUI thread.  You can circumvent this by moving the remote API request call in a NSOperation call, and pop up a loading screen until the API call returns.

Title: Application freezes for some time


问:
Constructor overloads to accept any function
I am attempting to create a class template whose constructor(s) can take any kind of function as argument, that is, it takes a function pointer (which can be a member function pointer) and the corresponding function arguments. Additionally, there should be a static_assert that checks whether the function return type (taken from the function pointer) matches the class template parameter type. Thus, the code should look something like this:

```<code>template <class ReturnType>
struct Bar
{
    template <class RetType, class ... ParamType>
    Bar<ReturnType>(RetType (* func)(ParamType ...), ParamType && ... args) :
        package_(std::bind(func, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
    {
        static_assert(std::is_same<ReturnType, RetType>::value,
            "Type mismatch between class parameter type and constructor parameter type");
    }

    template <class RetType, class ObjType, class ... ParamType>
    Bar<ReturnType>(RetType (ObjType::* func)(ParamType ...), ObjType * obj, ParamType && ... args) :
        package_(std::bind(func, obj, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
    {
        static_assert(std::is_same<ReturnType, RetType>::value,
            "Type mismatch between class parameter type and constructor parameter type");
    }

    std::packaged_task<ReturnType()> package_;
    std::function<void()> function_;
    std::future<ReturnType> future_;
};
</code>```

The idea is that the code compiles for these situations, and allows for Bar::function_ to be called (through the function call operator) without errors:

```<code>struct Foo
{
    int foo(int i) {
        return i;
    }

    int foo() {
        return 1;
    }
};

int foo(int i)
{
    return i;
}

int foo()
{
    return 1;
}

int main()
{
    Foo f = Foo();

    Bar<int> b1(&Foo::foo, &f, 1);
    Bar<int> b2(&Foo::foo, &f);
    Bar<int> b3(foo, 1);
    Bar<int> b4(foo);

    return 0;
}
</code>```

Unfortunately, I have close to zero experience with template metaprogramming, and even though I have ran over several questions here in SO, and attempted several ways of solving my problem, such as using a more generalized approach to the constructor

```<code>template <class RetType, class ... ParamType>
Bar<ReturnType>(RetType func, ParamType && ... args)
</code>```

and combining it with type_traits to determine the return type), I have yet to find a way to make this work. What changes can I do to the constructor(s) that allow this functionality?

Edit:

max66's answer solved my original problem, however, a new one arose, which I hadn't considered in the previous question. I also want to be able to pass variables to the constructor, like so:

```<code>int main()
{
    Foo f = Foo();
    int i = 1;

    Bar<int> b1(&Foo::foo, &f, i); // Error
    Bar<int> b2(&Foo::foo, &f, 1); // Ok
    Bar<int> b3(&Foo::foo, &f); // Ok
    Bar<int> b4(foo, i); // Error
    Bar<int> b5(foo, 1); // Ok
    Bar<int> b6(foo); // Ok

    return 0;
}
</code>```

however, as it is, a compiler error shows up in the cases marked with Error. I am guessing this is because the parameter func in the constructor uses ParamType to determine its type (which doesn't match with the actual ParamTypes in the case of b1 and b4), but I have no idea how to solve this...

答:
You probably want to use std::invoke. It handles working with member function pointers and regular functions for you.

As an outline of the sort of stuff you can do:

```<code>#include <functional>
#include <type_traits>
#include <utility>

template<typename F>
class Bar
{
    F f_;

public:
    template<typename TF>
    Bar(TF && f)
        : f_{ std::forward<TF>(f) }
    {}

    template<typename... Args>
    decltype(auto) operator()(Args &&... args) {
        return std::invoke(f_, std::forward<Args>(args)...);
    }
};

template<typename F>
auto make_bar(F && f)
{
    return Bar<std::decay_t<F>>{ std::forward<F>(f) };
}
</code>```

It can be used like so:

```<code>auto b1 = make_bar(&f);
auto result = b1(myArg1, myArg2); // etc

auto b2 = make_bar(&Foo::fn);
auto result = b1(foo, arg1);
</code>```

In the very least, I would recommend having Bar take the function object type as a template parameter so that you don't have to use std::function, but if you do want to use the exact calling syntax you have, it can be done using std::invoke and std::invoke_result as well.

Body:
I am attempting to create a class template whose constructor(s) can take any kind of function as argument, that is, it takes a function pointer (which can be a member function pointer) and the corresponding function arguments. Additionally, there should be a static_assert that checks whether the function return type (taken from the function pointer) matches the class template parameter type. Thus, the code should look something like this:

template <class ReturnType>
struct Bar
{
    template <class RetType, class ... ParamType>
    Bar<ReturnType>(RetType (* func)(ParamType ...), ParamType && ... args) :
        package_(std::bind(func, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
    {
        static_assert(std::is_same<ReturnType, RetType>::value,
            "Type mismatch between class parameter type and constructor parameter type");
    }

    template <class RetType, class ObjType, class ... ParamType>
    Bar<ReturnType>(RetType (ObjType::* func)(ParamType ...), ObjType * obj, ParamType && ... args) :
        package_(std::bind(func, obj, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
    {
        static_assert(std::is_same<ReturnType, RetType>::value,
            "Type mismatch between class parameter type and constructor parameter type");
    }

    std::packaged_task<ReturnType()> package_;
    std::function<void()> function_;
    std::future<ReturnType> future_;
};

The idea is that the code compiles for these situations, and allows for Bar::function_ to be called (through the function call operator) without errors:

struct Foo
{
    int foo(int i) {
        return i;
    }

    int foo() {
        return 1;
    }
};

int foo(int i)
{
    return i;
}

int foo()
{
    return 1;
}

int main()
{
    Foo f = Foo();

    Bar<int> b1(&Foo::foo, &f, 1);
    Bar<int> b2(&Foo::foo, &f);
    Bar<int> b3(foo, 1);
    Bar<int> b4(foo);

    return 0;
}

Unfortunately, I have close to zero experience with template metaprogramming, and even though I have ran over several questions here in SO, and attempted several ways of solving my problem, such as using a more generalized approach to the constructor

template <class RetType, class ... ParamType>
Bar<ReturnType>(RetType func, ParamType && ... args)

and combining it with type_traits to determine the return type), I have yet to find a way to make this work. What changes can I do to the constructor(s) that allow this functionality?

Edit:

max66's answer solved my original problem, however, a new one arose, which I hadn't considered in the previous question. I also want to be able to pass variables to the constructor, like so:

int main()
{
    Foo f = Foo();
    int i = 1;

    Bar<int> b1(&Foo::foo, &f, i); // Error
    Bar<int> b2(&Foo::foo, &f, 1); // Ok
    Bar<int> b3(&Foo::foo, &f); // Ok
    Bar<int> b4(foo, i); // Error
    Bar<int> b5(foo, 1); // Ok
    Bar<int> b6(foo); // Ok

    return 0;
}

however, as it is, a compiler error shows up in the cases marked with Error. I am guessing this is because the parameter func in the constructor uses ParamType to determine its type (which doesn't match with the actual ParamTypes in the case of b1 and b4), but I have no idea how to solve this...

Body:
You probably want to use std::invoke. It handles working with member function pointers and regular functions for you.

As an outline of the sort of stuff you can do:

#include <functional>
#include <type_traits>
#include <utility>

template<typename F>
class Bar
{
    F f_;

public:
    template<typename TF>
    Bar(TF && f)
        : f_{ std::forward<TF>(f) }
    {}

    template<typename... Args>
    decltype(auto) operator()(Args &&... args) {
        return std::invoke(f_, std::forward<Args>(args)...);
    }
};

template<typename F>
auto make_bar(F && f)
{
    return Bar<std::decay_t<F>>{ std::forward<F>(f) };
}

It can be used like so:

auto b1 = make_bar(&f);
auto result = b1(myArg1, myArg2); // etc

auto b2 = make_bar(&Foo::fn);
auto result = b1(foo, arg1);

In the very least, I would recommend having Bar take the function object type as a template parameter so that you don't have to use std::function, but if you do want to use the exact calling syntax you have, it can be done using std::invoke and std::invoke_result as well.


问:
Error deploying Python package to AWS Lambda
AWS Successfully creates the lambda function when I upload the zip file. But it's giving this error when I test it out.

```<code>{
  "errorMessage": "Unable to import module 'amazonSNS'"
}
</code>```

Following are the contents of the zip file that I created. I tried changing the name of the zip file to "amazonSNS" to match the amazonSNS.py file, but no help, same issue.

The Lambda handler in the Configuration of the Lambda function is set to "amazonSNS.handler" where amazonSNS is the filename and handler is the function name that needs to be called, as they have instructed in the documentation.

Here are the contents of the python file

```<code>import boto3
import MySQLdb

client = boto3.client("sns")
rds = boto3.client("rds")

def handler(event, context):
    conn = MySQLdb.connect("host", "username", "password", "database")
    cur = conn.cursor(MySQLdb.cursors.DictCursor)
    query = "select * from login.login limit 10"
    cur.execute(query)
    print cur.fetchall()
    print conn
</code>```

What might be the issue here?

Here is the Log output

START RequestId: 76a61551-052a-11e6-b466-8fa0769ac309 Version: $LATEST
  Unable to import module 'amazonSNS': No module named _mysql

END RequestId: 76a61551-052a-11e6-b466-8fa0769ac309 REPORT RequestId:
  76a61551-052a-11e6-b466-8fa0769ac309  Duration: 0.33 ms   Billed
  Duration: 100 ms

UPDATE

I added a few more files from "site-package" folder that I thought was part of the MySQLdb package, Here are the current contents of the zip file.

And after this the new Log of the error is.

START RequestId: c0715d9a-0531-11e6-9409-a3b194fd4afd Version: $LATEST
  Unable to import module 'amazonSNS': libmysqlclient.so.18: cannot open
  shared object file: No such file or directory

END RequestId: c0715d9a-0531-11e6-9409-a3b194fd4afd REPORT RequestId:
  c0715d9a-0531-11e6-9409-a3b194fd4afd  Duration: 0.35 ms   Billed
  Duration: 100 ms  Memory Size: 128 MB Max Memory Used: 22 MB

答:
I had this issue when using mysqlclient (the MySQLd fork which works on Python3).

Since I use Zappa for easy deployment, the solution was simple: just switch to the original MySQLd package (which does not support Python 3, though): pip install mysql-python
Zappa comes with a pre-compiled version of it.

Body:
AWS Successfully creates the lambda function when I upload the zip file. But it's giving this error when I test it out.

{
  "errorMessage": "Unable to import module 'amazonSNS'"
}

Following are the contents of the zip file that I created. I tried changing the name of the zip file to "amazonSNS" to match the amazonSNS.py file, but no help, same issue.

The Lambda handler in the Configuration of the Lambda function is set to "amazonSNS.handler" where amazonSNS is the filename and handler is the function name that needs to be called, as they have instructed in the documentation.

Here are the contents of the python file

import boto3
import MySQLdb

client = boto3.client("sns")
rds = boto3.client("rds")

def handler(event, context):
    conn = MySQLdb.connect("host", "username", "password", "database")
    cur = conn.cursor(MySQLdb.cursors.DictCursor)
    query = "select * from login.login limit 10"
    cur.execute(query)
    print cur.fetchall()
    print conn

What might be the issue here?

Here is the Log output

START RequestId: 76a61551-052a-11e6-b466-8fa0769ac309 Version: $LATEST
  Unable to import module 'amazonSNS': No module named _mysql

END RequestId: 76a61551-052a-11e6-b466-8fa0769ac309 REPORT RequestId:
  76a61551-052a-11e6-b466-8fa0769ac309  Duration: 0.33 ms   Billed
  Duration: 100 ms

UPDATE

I added a few more files from "site-package" folder that I thought was part of the MySQLdb package, Here are the current contents of the zip file.

And after this the new Log of the error is.

START RequestId: c0715d9a-0531-11e6-9409-a3b194fd4afd Version: $LATEST
  Unable to import module 'amazonSNS': libmysqlclient.so.18: cannot open
  shared object file: No such file or directory

END RequestId: c0715d9a-0531-11e6-9409-a3b194fd4afd REPORT RequestId:
  c0715d9a-0531-11e6-9409-a3b194fd4afd  Duration: 0.35 ms   Billed
  Duration: 100 ms  Memory Size: 128 MB Max Memory Used: 22 MB


问:
h1 creates unwanted space above the text
I'm sure my question is quite a newbie one, anyway I can't figure out what I'm doing wrong. Basically, I created a
 that I use as header, and inside of it another
 that contains an image (logo) and a title (using
).

The problem is that I get an unwanted extra space above the body
as you can see in this picture.
If I get rid of the
 title then everything is fine. I think the problem is due the float: left; property that I have assigned to the image, because if I assign no float property then the space disappears, but as you can see if I remove the float: left; the image and the title are not "aligned" anymore. So, the question is, how can I make the image to stay on the left and the title on the right of the image, without using float properties?

Any help will be appreciated, thanks!

Edit: Thanks everybody for the answers, I'm studying HTML and CSS at school and things like this are rarely mentioned by my teachers. Thanks again

答: This is because every browser has a default stylesheet, which you can find in Browsers' default CSS stylesheets. As you can see, the default margins are not zero. This can be solved by explicitly adding margin: 0px to your CSS.


问:
How do I suppress any error condition in a sql server login trigger
I have a sql server login trigger to audit logins.

I want to suppress any errors being returned from it, as an error prevents login.

How do I do that?

Here's my trigger code

```<code>CREATE TRIGGER [trigLogon_Audit]
ON ALL SERVER
FOR LOGON
AS
    BEGIN
        IF (IS_MEMBER('dbo') = 1) RETURN;
        INSERT INTO Tracking.dbo.Activity (moment, name) VALUES (GETDATE(), ORIGINAL_LOGIN());

    END;
GO

ENABLE TRIGGER [trigLogon_Audit] ON ALL SERVER
GO
</code>```

答:
You can have error handling code in a trigger but you cannot do much because
when an error happens in a trigger the batch is aborted (unless you raise
the error yourself using RAISERROR).

Two good articles on error handling by Erland Sommarskog:

http://www.sommarskog.se/error-handling-I.html

http://www.sommarskog.se/error-handling-II.html

Body:
I have a sql server login trigger to audit logins.

I want to suppress any errors being returned from it, as an error prevents login.

How do I do that?

Here's my trigger code

CREATE TRIGGER [trigLogon_Audit]
ON ALL SERVER
FOR LOGON
AS
    BEGIN
        IF (IS_MEMBER('dbo') = 1) RETURN;
        INSERT INTO Tracking.dbo.Activity (moment, name) VALUES (GETDATE(), ORIGINAL_LOGIN());

    END;
GO

ENABLE TRIGGER [trigLogon_Audit] ON ALL SERVER
GO


问:
How can I convert a 2D array to a 2D list with Streams?
I've tried this StackOverflow answer's code, but I get the error Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>):

```<code>//data is int[][]
Arrays.stream(data)
    .map(i -> Arrays.stream(i)
        .collect(Collectors.toList()))
            .collect(Collectors.toList());
</code>```

答:
Arrays.stream will go through each int[] in the int[][].
You can convert an int[] to an IntStream.
Then, in order to convert a stream of ints to a List<Integer>,
you first need to box them.
Once boxed to Integers, you can collect them to a list.
And finally collect the stream of List<Integer> into a list.

```<code>List<List<Integer>> list = Arrays.stream(data)
    .map(row -> IntStream.of(row).boxed().collect(Collectors.toList()))
    .collect(Collectors.toList());
</code>```

Demo.

Body:
I've tried this StackOverflow answer's code, but I get the error Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>):

//data is int[][]
Arrays.stream(data)
    .map(i -> Arrays.stream(i)
        .collect(Collectors.toList()))
            .collect(Collectors.toList());

Body:
Arrays.stream will go through each int[] in the int[][].
You can convert an int[] to an IntStream.
Then, in order to convert a stream of ints to a List<Integer>,
you first need to box them.
Once boxed to Integers, you can collect them to a list.
And finally collect the stream of List<Integer> into a list.

List<List<Integer>> list = Arrays.stream(data)
    .map(row -> IntStream.of(row).boxed().collect(Collectors.toList()))
    .collect(Collectors.toList());

Demo.


问:
How is this code assigning subclass object to superclass type?
In the following code, can someone explain to me the meaning of "A ba = (A)b;" and explain to me the outputs and how they are derived.

```<code>class A {
    public void f(A a) { System.out.println("fa(A)");}
    public void f(B b) { System.out.println("fa(B)");}
}

class B extends A {
    public void f(A a) { System.out.println("fb(A)"); }
    public void f(B b) { System.out.println("fb(B)"); }
}

public class TypeMeister {
    public static void main(String[] args){
        A a = new A();
        B b = new B();
        A ba = (A)b; //please explain

        a.f(a);
        a.f(b);
        b.f(a);
        b.f(b);
        a.f(ba);
        b.f(ba);;
        ba.f(a);
        ba.f(b);
        ba.f(ba);
    }
}
</code>```

Thanks for your help.

答:
A ba = (A)b; Is an explicit type cast operation. b is explicitly of type B, but implicitly of type A, since B is a subclass of A.

Since B is a subclass of A, you can initialise object b as so:

```<code>A b = new B();
</code>```

This is equivalent to

```<code>B b = new B();
A ba = (A)b;
</code>```

...but 1 line shorter.

Body:
In the following code, can someone explain to me the meaning of "A ba = (A)b;" and explain to me the outputs and how they are derived.

class A {
    public void f(A a) { System.out.println("fa(A)");}
    public void f(B b) { System.out.println("fa(B)");}
}

class B extends A {
    public void f(A a) { System.out.println("fb(A)"); }
    public void f(B b) { System.out.println("fb(B)"); }
}

public class TypeMeister {
    public static void main(String[] args){
        A a = new A();
        B b = new B();
        A ba = (A)b; //please explain

        a.f(a);
        a.f(b);
        b.f(a);
        b.f(b);
        a.f(ba);
        b.f(ba);;
        ba.f(a);
        ba.f(b);
        ba.f(ba);
    }
}

Thanks for your help.

Body:
A ba = (A)b; Is an explicit type cast operation. b is explicitly of type B, but implicitly of type A, since B is a subclass of A.

Since B is a subclass of A, you can initialise object b as so:

A b = new B();

This is equivalent to

B b = new B();
A ba = (A)b;

...but 1 line shorter.