问:
php check username + need variable case insensitive to register in database
I have a file register.php for my site.

```<code>$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
while ($row = $result->fetch_object()) {
    if(empty($row->username)) {
        echo "different username. IS OK !!";
    } else {
        echo "<font color='red'>*</font>".$username."<font color='red'> : this username already exist in DB!!</font><br />";
    }
}
</code>```

Here I compare the ($username from form) with ($row->username from DB)
$row->username exist only if $username is already register. So, if this exist, will go on ELSE part.
If $row->username doesn't exist (is empty) , because SELECT from sql will find no attribute, my code must go on IF part and display this message "different username. IS OK !!"

Why IF part doesn't work? I know sql will return 0, or NULL or "" or something like this. If I put a username which is not already registered, the code don't show the specific message. Because in this part I want to change the message with the code which permit to register new username.

empty($row->username) is not really empty if SQL can't find something to return?

Another problem is : I have a registered username "Test". MySQL is not case-sensitive, but in php, I can register another username "test". The code in php will run as a new register, but in MySQL nothing will happening because "username is unique" there. So, in "check username" from above, I need to check 2 insensitive variables ($username and $row->username). Because if in DB I have Test, and I want to register new user "test", this code will let me to do it. I want to show a error message if this happening.

答:
thanks for fast answers. Honestlly, I don't know where was the issue, because now it's run perfect, without strtolower method. This is my code now:

```<code>$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_object();
$stmt->close();
if(empty($row->username)) {
    // if a cell from below is empty, go on ELSE part
    if (!empty($username) && !empty($password) && !empty($email) && !empty($country)) {
        $sql="INSERT INTO users (username, password, email, borned, gender, country, phone, register_date) VALUES (?,?,?,?,?,?,?, now())";
        $stmt = $con->prepare($sql);
        $stmt->bind_param('sssssss', $username, $password, $email, $borned, $gender, $country, $phone);
        $stmt->execute();
        $stmt->close();
        header ("Location: login.php");
    } else {
        echo "<font color='red'>*Must complete required cells !!</font> ";
    }
// end of register dates
} else {
        echo "<font color='red'>*</font>".$username."<font color='red'> : this username already exist in DB!!</font><br />";
}
</code>```

I have user "Test", if try to register "test" will give a message that the user is already registered.

Thanks again, the thread can be deleted is somebody consider that can not help somebody :D

Body:
I have a file register.php for my site.

$username=filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
while ($row = $result->fetch_object()) {
    if(empty($row->username)) {
        echo "different username. IS OK !!";
    } else {
        echo "*".$username." : this username already exist in DB!!
";
    }
}

Here I compare the ($username from form) with ($row->username from DB)
$row->username exist only if $username is already register. So, if this exist, will go on ELSE part.
If $row->username doesn't exist (is empty) , because SELECT from sql will find no attribute, my code must go on IF part and display this message "different username. IS OK !!"

Why IF part doesn't work? I know sql will return 0, or NULL or "" or something like this. If I put a username which is not already registered, the code don't show the specific message. Because in this part I want to change the message with the code which permit to register new username.

empty($row->username) is not really empty if SQL can't find something to return?

Another problem is : I have a registered username "Test". MySQL is not case-sensitive, but in php, I can register another username "test". The code in php will run as a new register, but in MySQL nothing will happening because "username is unique" there. So, in "check username" from above, I need to check 2 insensitive variables ($username and $row->username). Because if in DB I have Test, and I want to register new user "test", this code will let me to do it. I want to show a error message if this happening.

Body:
thanks for fast answers. Honestlly, I don't know where was the issue, because now it's run perfect, without strtolower method. This is my code now:

$sql="SELECT username FROM users WHERE username=?";
$stmt=$con->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_object();
$stmt->close();
if(empty($row->username)) {
    // if a cell from below is empty, go on ELSE part
    if (!empty($username) && !empty($password) && !empty($email) && !empty($country)) {
        $sql="INSERT INTO users (username, password, email, borned, gender, country, phone, register_date) VALUES (?,?,?,?,?,?,?, now())";
        $stmt = $con->prepare($sql);
        $stmt->bind_param('sssssss', $username, $password, $email, $borned, $gender, $country, $phone);
        $stmt->execute();
        $stmt->close();
        header ("Location: login.php");
    } else {
        echo "<font color='red'>*Must complete required cells !!</font> ";
    }
// end of register dates
} else {
        echo "<font color='red'>*</font>".$username."<font color='red'> : this username already exist in DB!!</font><br />";
}

I have user "Test", if try to register "test" will give a message that the user is already registered.

Thanks again, the thread can be deleted is somebody consider that can not help somebody :D


来源: stackexchange

问:
Online resources for Introduction to computer and computer sciences for absolute beginner
In our office, we have an office boy(completed high school(10+2 years)) with average academic record so far). He wants to learn programming. I have started coaching him in Computer Science basics (history of computer science, number systems, etc.), but I am not able to put in enough time with him(because I have very limited free time and more importantly I do not want to spoon feed him). Now I am not sure how to fill in the gap of theoretical reading.

Now my question is, could anyone point me to some online resources(preferably in simple English) for Introduction to Computer Sciences.

Moreover, I am planning to start him with on programming with book Think Like A Computer Scientist - Python version. If any body knows a better book or an online resource - preferably in Python, please point out.

Thanks

答: http://learnpythonthehardway.org/index might be useful.</p>

ContentLicense: CC BY-SA 2.5


问:
Symfony2 Doctrine2 produce a sql wrong
I have create an entity in the way the ID is a string type.

```<code>class Item
{
/**
 * @var string
 *
 * @ORM\Column(name="id_item", type="string", length=60)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $idItem;
.....
</code>```

When I insert the new element in form I get an error

ERROR - Failed to create object: Acme\BasicCmsBundle\Entity\Device
  Context: {"exception":"Object(Sonata\AdminBundle\Exception\ModelManagerException)","previous_exception_message":"An exception occurred while executing 'INSERT INTO  item (referente_id) VALUES (?)' with params [null]:\n\nSQLSTATE[23502]: Not null violation: 7 ERRORE: valori null nella colonna \"id_item\" violano il vincolo non-null\nDETAIL: La riga in errore contiene (null, null)."}

The Doctrine ORM non inserts the ID in query.

I use:

Symfony 2.7

doctrine 2

sonata Admin bundle

postgresql

答:
if you use postgres try to insert the sequence generator in your entity ;)

Example:

```<code>class Item
{
/**
  * @var string
  *
  * @ORM\Column(name="id_item", type="string", length=60)
  * @ORM\Id
  * @ORM\GeneratedValue(strategy="IDENTITY")
  * @ORM\SequenceGenerator(sequenceName="item_seq",allocationSize=1, initialValue=1)
  */
private $idItem;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Symfony2 Doctrine2 produce a sql wrong

Body:
I have create an entity in the way the ID is a string type.

class Item
{
/**
 * @var string
 *
 * @ORM\Column(name="id_item", type="string", length=60)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $idItem;
.....

When I insert the new element in form I get an error

ERROR - Failed to create object: Acme\BasicCmsBundle\Entity\Device
  Context: {"exception":"Object(Sonata\AdminBundle\Exception\ModelManagerException)","previous_exception_message":"An exception occurred while executing 'INSERT INTO  item (referente_id) VALUES (?)' with params [null]:\n\nSQLSTATE[23502]: Not null violation: 7 ERRORE: valori null nella colonna \"id_item\" violano il vincolo non-null\nDETAIL: La riga in errore contiene (null, null)."}

The Doctrine ORM non inserts the ID in query.

I use:

Symfony 2.7

doctrine 2

sonata Admin bundle

postgresql

Body:
if you use postgres try to insert the sequence generator in your entity ;)

Example:

class Item
{
/**
  * @var string
  *
  * @ORM\Column(name="id_item", type="string", length=60)
  * @ORM\Id
  * @ORM\GeneratedValue(strategy="IDENTITY")
  * @ORM\SequenceGenerator(sequenceName="item_seq",allocationSize=1, initialValue=1)
  */
private $idItem;


问:
Why isn't counter() called in "false && counter()"?
I am trying to figure out how this boolean expression is evaluated:

```<code>int i = 0;
boolean exp = i > 1 && counter();
</code>```

In the following code:

```<code>public class Main {

    static int num = 0;

    public static boolean counter(){
            num++;
         if(num == 6){
             return true;
         }
          return false;
     }
    public static void main(String[] args) {
            //int i = 2;
              int i = 0;
            boolean exp = i > 1 && counter();
            System.out.println(num); // 0
            System.out.println(exp); // false
    }
 }
</code>```

Since i = 0, i > 1 is false and counter() returns false. However, I'm confused because the value of static variable num doesn't change despite the counter() function being in the boolean expression:

```<code>exp = i > 1 && counter();
</code>```

I was expecting the output to be

```<code>1
false
</code>```

but it is

```<code>0
false
</code>```

Why does counter() not seem to be called?

答:
It's because of && is quick boolean operation.
If first operand is false then it will return false immediately without evaluating second operand.
You can use &, it will always evaluate both operands. (also & is a bit-wise operator if the operands are integral.)
The same thing with logical OR : ||. if the first operand is true, it will immediatly retrun true.

Body:
I am trying to figure out how this boolean expression is evaluated:

int i = 0;
boolean exp = i > 1 && counter();

In the following code:

public class Main {

    static int num = 0;

    public static boolean counter(){
            num++;
         if(num == 6){
             return true;
         }
          return false;
     }
    public static void main(String[] args) {
            //int i = 2;
              int i = 0;
            boolean exp = i > 1 && counter();
            System.out.println(num); // 0
            System.out.println(exp); // false
    }
 }

Since i = 0, i > 1 is false and counter() returns false. However, I'm confused because the value of static variable num doesn't change despite the counter() function being in the boolean expression:

exp = i > 1 && counter();

I was expecting the output to be

1
false

but it is

0
false

Why does counter() not seem to be called?


问:
Adding images to Core Data takes a long time
How can I make the way I add images to the core data more efficient? </p>

答:
Its a pretty bad idea to save "Data" or Image here in core data persistance. Also i think you are running this code in the background queue, if not then thats also a bad thing. But then again, saving the image or data into core data persistant store is a very bad idea and should be avoided whenever you can.

As an alternate you can do this -

Save the image in the local directory with a path and a unique
filename.

Save the filename in core data except the path.

Next time when you retrieve the image, get the filename from the Data store.

Append the filename with the whole path untill the folder. Retrieve the image.

This is a much more efficient and better way to store images.


问:
Spring Integration error-channel doesn't receive all exceptions
I am using spring integration's error channel to capture exceptions in the framework. But of the two channels of the same type, one's thrown exceptions are received by the error handler while other's are not.

<int:gateway id="myGateway" service-interface="com.si.MyGateway" request-
channel="myRequestChannel" error-channel="errorHandlingChannel">

<int:chain input-channel="myRequestChannel" output-channel="lastChannel">
            <int:header-enricher>
                <int:error-channel ref="errorHandlingChannel">
            <int:header-enricher>
            <int:service-activator ref="testActivator1"
method="generateException" requires-reply="true" />
            </int:chain>

                <int:chain input-channel="lastChannel" output-
channel="nullChannel">
            <int:header-enricher>
                <int:error-channel ref="errorHandlingChannel">
            <int:header-enricher>
            <int:service-activator ref="testActivator2"
method="generateException" requires-reply="true" />
<int:filter ref="myFilter" discard-channel="nullChannel" />
            <int:service-activator ref="testActivator3"
method="generateException" requires-reply="true" />
<int:filter ref="myFilter" discard-channel="nullChannel" />
            </int:chain>
    <int:service-activator input-channel="errorHandlingChannel"
ref="errorHandler" method="handle" />

        ```
</div>
</div>
</p>

<p>The errorHandler's handle method accepts MessagingException. When I throw exception from myRequestChannel, it is received by the errorHandler but when the same exception is thrown from testActivator2 or testActivator3, it doesn't reach the errorHandler at all.</p>

<p>both channels are defined as async channels:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><int:channel>
<int:queue capacity="10">
</int:channel></code>```

On debugging, I found that all methods' exceptions are being thrown and follow a chain through spring's classes when an internal class ultimately throws a MessagingException, but the exceptions from the last two activators do not reach the handler.

What could be the reason?

答:
What kind of exceptions do you throw?

If it is MessagingException it must be supplied with the failedMessage, otherwise the error is sent to the default errorChannel on the <poller>.

Body:
I am using spring integration's error channel to capture exceptions in the framework. But of the two channels of the same type, one's thrown exceptions are received by the error handler while other's are not.

<int:gateway id="myGateway" service-interface="com.si.MyGateway" request-
channel="myRequestChannel" error-channel="errorHandlingChannel">

<int:chain input-channel="myRequestChannel" output-channel="lastChannel">
            <int:header-enricher>
                <int:error-channel ref="errorHandlingChannel">
            <int:header-enricher>
            <int:service-activator ref="testActivator1"
method="generateException" requires-reply="true" />
            </int:chain>

                <int:chain input-channel="lastChannel" output-
channel="nullChannel">
            <int:header-enricher>
                <int:error-channel ref="errorHandlingChannel">
            <int:header-enricher>
            <int:service-activator ref="testActivator2"
method="generateException" requires-reply="true" />
<int:filter ref="myFilter" discard-channel="nullChannel" />
            <int:service-activator ref="testActivator3"
method="generateException" requires-reply="true" />
<int:filter ref="myFilter" discard-channel="nullChannel" />
            </int:chain>
    <int:service-activator input-channel="errorHandlingChannel"
ref="errorHandler" method="handle" />

The errorHandler's handle method accepts MessagingException. When I throw exception from myRequestChannel, it is received by the errorHandler but when the same exception is thrown from testActivator2 or testActivator3, it doesn't reach the errorHandler at all.

both channels are defined as async channels:

<int:channel>
<int:queue capacity="10">
</int:channel>

On debugging, I found that all methods' exceptions are being thrown and follow a chain through spring's classes when an internal class ultimately throws a MessagingException, but the exceptions from the last two activators do not reach the handler.

What could be the reason?


问:
Android Layout Editor missing up and down controls
The latest xml layout editor is missing the up and down controls (where you can move Views around the xml hierarchy), now I can't move layouts into another LinearLayout.  Drag and drop simply does not work.

Where have they gone?  What is the new way of doing this?

答:
They broke it in the plugin ADT 8.0.1. see:

link text

You can get the previous plugin by trying

link text

The link's not shown on the developer.android pages but it does work. This version has its own bugs but I believe that the arrows are still there.


问:
Angular 2: getting data from a Class
I've created a class for the default settings of my app. But I have no idea how to get the data from that class and use it in my html. I tried an observable but that's not really working. </p>

<p>My class looks like this: </p>

```<code>export class Instellingen {
  urenTotBehandeling: number = 4;
  toonNaam: boolean = true;
  toonTijd: boolean = true;
  toonType: boolean = true;
  toonSanitair: boolean = true;
  toonKinder: boolean = true;
  toonSalon: boolean = true;
  toonKamerNummer: boolean = true;
  uren = [
    {value: 1, label: '1 uur'},
    {value: 2, label: '2 uren'},
    {value: 3, label: '3 uren'},
    {value: 4, label: '4 uren'}         ];
  hulpKleur:string= "red";
  behandelKleur:string = "orange";
  volKleur:string="green";
  leegKleur:string="white";    }
</code>```

答:
```<code>import { Component } from '@angular/core'
import { NgForm } from '@angular/forms'
@Component({
selector :'ang-model',
template :`
Model :<input [(ngModel)] ='name' /> // Data Binding
       {{name }} // string interpolation`
})
export class AngModelComponent{
       name : string = "Practice ";
}
</code>```

Try the above approach of data binding and string interpolation

Title: Angular 2: getting data from a Class

Body:
I've created a class for the default settings of my app. But I have no idea how to get the data from that class and use it in my html. I tried an observable but that's not really working.

My class looks like this:

export class Instellingen {
  urenTotBehandeling: number = 4;
  toonNaam: boolean = true;
  toonTijd: boolean = true;
  toonType: boolean = true;
  toonSanitair: boolean = true;
  toonKinder: boolean = true;
  toonSalon: boolean = true;
  toonKamerNummer: boolean = true;
  uren = [
    {value: 1, label: '1 uur'},
    {value: 2, label: '2 uren'},
    {value: 3, label: '3 uren'},
    {value: 4, label: '4 uren'}         ];
  hulpKleur:string= "red";
  behandelKleur:string = "orange";
  volKleur:string="green";
  leegKleur:string="white";    }

Body:
import { Component } from '@angular/core'
import { NgForm } from '@angular/forms'
@Component({
selector :'ang-model',
template :`
Model :<input [(ngModel)] ='name' /> // Data Binding
       {{name }} // string interpolation`
})
export class AngModelComponent{
       name : string = "Practice ";
}

Try the above approach of data binding and string interpolation


问:
Installing Angular-CLI on Windows 10
I had installation issues of angular-cli on Windows 10 system.
    The errors were related to Python dependencies and node-gyp. Something as below :</p>

```<code>>execSync@1.0.2 install C:\Users\UserName\AppData\Roaming\npm\node_modules\angular-cli\node_modules\execSync
node install.js
[execsync v1.0.2] Attempting to compile native extensions.
{ Error: spawn node-gyp ENOENT
at exports._errnoException (util.js:1007:11)
</code>```

答:
Update

this seems to be fixed in newer releases and this solution is no longer required.

mukesh51 eventually solved the problem.

the installation seems to work in these steps:

npm install -g node-gyp

npm install -g windows-build-tools

npm install -g @angular/cli

I took these steps from here.

Title: Installing Angular-CLI on Windows 10

Body:
I had installation issues of angular-cli on Windows 10 system.
    The errors were related to Python dependencies and node-gyp. Something as below :

>execSync@1.0.2 install C:\Users\UserName\AppData\Roaming\npm\node_modules\angular-cli\node_modules\execSync
node install.js
[execsync v1.0.2] Attempting to compile native extensions.
{ Error: spawn node-gyp ENOENT
at exports._errnoException (util.js:1007:11)

ContentLicense: CC BY-SA 4.0


问:
EACCESS error on port 443 within Azure Function request
I am making an https request towards a server, which requires TLS 1.2.

Making a GET request to that server works on my browser, in CURL, but in my Azure Function I get this error :

```<code>Error: connect EACCES 127.0.0.1:443
at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1081:14)
code: 'EACCES',
errno: 'EACCES',
syscall: 'connect',
address: '127.0.0.1',
port: 443
</code>```

This request is done within an azure function. I don't have a custom domain for my azure function, therefor it should use their SSL no ? What am I missing ?

Here is my request:

```<code>var options = {
        url: 'https://somesite.ca/somepath/Services/something.asmx/GetTrustedAutorizationTicket',
        qs: {UserName: 'username', Domain: '', Password: 'pwd', ClearText: 'true'},
        headers: {
            'Content-Type': 'text/xml',
        }
    }

    var req = https.get(options, function(res) {...
</code>```

TIA

答:
There's no url in options. You are looking for hostname and path.

E.g.

const https = require('https');

const options = {
  hostname: 'somesite.ca',
  port: 443,
  path: '/somepath/Services/something.asmx/GetTrustedAutorizationTicket',
  method: 'GET'
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);
  ...
```

Ref: https://nodejs.org/api/https.html#https_https_request_options_callback

Body:
I am making an https request towards a server, which requires TLS 1.2.

Making a GET request to that server works on my browser, in CURL, but in my Azure Function I get this error :

Error: connect EACCES 127.0.0.1:443
at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1081:14)
code: 'EACCES',
errno: 'EACCES',
syscall: 'connect',
address: '127.0.0.1',
port: 443

This request is done within an azure function. I don't have a custom domain for my azure function, therefor it should use their SSL no ? What am I missing ?

Here is my request:

var options = {
        url: 'https://somesite.ca/somepath/Services/something.asmx/GetTrustedAutorizationTicket',
        qs: {UserName: 'username', Domain: '', Password: 'pwd', ClearText: 'true'},
        headers: {
            'Content-Type': 'text/xml',
        }
    }

    var req = https.get(options, function(res) {...

TIA

Body:
There's no url in options. You are looking for hostname and path.

E.g.

const https = require('https');

const options = {
  hostname: 'somesite.ca',
  port: 443,
  path: '/somepath/Services/something.asmx/GetTrustedAutorizationTicket',
  method: 'GET'
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);
  ...

Ref: https://nodejs.org/api/https.html#https_https_request_options_callback


问:
Parameters.ParamByname Doesn't accept string values Delphi
I have the following code

```<code>procedure TFrmMain.ComboBox1KeyPress(Sender: TObject; var Key: Char);
begin

 if Key = #13 then
 begin
  ADOQuery1.close;
  ADOQuery1.sql.Text := 'INSERT INTO palletweighttemp(TickCode,SchedID,BatchNo)values';
  ADOQuery1.SQL.Add(' (:field1,(select SchedID from TicketBatch where TickCode =:field1),');
  ADOQuery1.SQL.Add('(select BatchNo from TicketBatch where TickCode =:field1))');
  ADOQuery1.Parameters.ParamByName('field1').DataType := ftString;
  ADOQuery1.Parameters.ParamByName('field1').Value := ComboBox1.Text;
  ADOQuery1.ExecSQL;
       PopulateDBGrid;
        ComboBox1.SetFocus;
       end;

 end;
</code>```

I Populate my comboBox using

```<code>procedure TFrmMain.PopulateBoxes();
begin
ComboBox1.SetFocus;

ComboBox1.Perform(WM_SYSKEYDOWN, VK_TAB, 0);

ComboBox1.clear;
ADOQuery1.sql.add
('select * from TicketBatch where isProcesed = 0 and TickCode is not null');
ADOQuery1.open;
ComboBox1.Text := '';
while not ADOQuery1.Eof do
begin
ComboBox1.Items.add(ADOQuery1.FieldByName('TickCode').AsString);
ADOQuery1.Next;
end;
 ADOQuery1.close;

 end;
</code>```

If i press enter to run my Combobox1KeyPress procedure an error pops up that

I'm assuming it's because its a needs a integer and currently is a string
Please assist

答:
You must make sure the column data types match in both tables so as the query parameter data type matches the column data types in both tables. With your current code the tables need to be defined like:

PalletWeightTemp.TickCode → TicketBatch.TickCode → (N)VARCHAR
  PalletWeightTemp.SchedID → TicketBatch.SchedID → same data type
  PalletWeightTemp.BatchNo → TicketBatch.BatchNo → same data type

Once you'll have it defined like that, the error message should disappear. If not, another possible source of this error I would focus on is an insertion trigger that contains a similar mismatching data type query.

One last note to the query itself - it can be simplified like this (it removes the redundant subquery):

INSERT INTO PalletWeightTemp
  (TickCode, SchedID, BatchNo)
SELECT
  :TickCode, SchedID, BatchNo
FROM
  TicketBatch WHERE TickCode = :TickCode
```

Body:
I have the following code

procedure TFrmMain.ComboBox1KeyPress(Sender: TObject; var Key: Char);
begin

 if Key = #13 then
 begin
  ADOQuery1.close;
  ADOQuery1.sql.Text := 'INSERT INTO palletweighttemp(TickCode,SchedID,BatchNo)values';
  ADOQuery1.SQL.Add(' (:field1,(select SchedID from TicketBatch where TickCode =:field1),');
  ADOQuery1.SQL.Add('(select BatchNo from TicketBatch where TickCode =:field1))');
  ADOQuery1.Parameters.ParamByName('field1').DataType := ftString;
  ADOQuery1.Parameters.ParamByName('field1').Value := ComboBox1.Text;
  ADOQuery1.ExecSQL;
       PopulateDBGrid;
        ComboBox1.SetFocus;
       end;

 end;

I Populate my comboBox using

procedure TFrmMain.PopulateBoxes();
begin
ComboBox1.SetFocus;

ComboBox1.Perform(WM_SYSKEYDOWN, VK_TAB, 0);

ComboBox1.clear;
ADOQuery1.sql.add
('select * from TicketBatch where isProcesed = 0 and TickCode is not null');
ADOQuery1.open;
ComboBox1.Text := '';
while not ADOQuery1.Eof do
begin
ComboBox1.Items.add(ADOQuery1.FieldByName('TickCode').AsString);
ADOQuery1.Next;
end;
 ADOQuery1.close;

 end;

If i press enter to run my Combobox1KeyPress procedure an error pops up that

I'm assuming it's because its a needs a integer and currently is a string
Please assist


问:
button link with font awesome not working
I've tried re-coding it different ways and I'm not sure why it's not working. I'm trying to make a button that when pressed will send the user to Github all while having a font awesome icon.</p>

```<code> <a href="https://github.com/"> <button type="submit"><i class="fa fa-github"
    aria-hidden="true">GitHub</i></a>
</code>```

答:
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' />

 <button type="submit">GitHub</button>

```

Body:
I've tried re-coding it different ways and I'm not sure why it's not working. I'm trying to make a button that when pressed will send the user to Github all while having a font awesome icon.

  <button type="submit">GitHub

Body:
<html>
<head>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' />

</head>
<body>

<a href="https://github.com/"> <button type="submit"><i class="fa fa-github"
    aria-hidden="true">GitHub</i></button></a>
</body>
</html>


问:
Django template ifequal comparison of decimals
So, I have a decimalfield that can be 3 different values. In my view,
I pass in a dictionary of values that contains the appropriate decimal
values as keys.

```<code>{% for item in booklist %}
    {% for key, value in numvec.items %}
        {{item.number}}
        {% ifequals item.number {{key}} %}
            {{value}}
        {% endifequals %}
    {% endfor %}
{% endfor %}
</code>```

this is the dict I pass in as numvec:

```<code>numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"),
</code>```

"TEST3":Decimal("0.255")}

the number field was defined as having these choices in my model:

```<code>BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),)
</code>```

The item number prints out just fine in the view if I compare the dict
with the attribute, but for some reason the ifequals cannot properly
compare two decimals together. Is this a bug, or am I doing something
wrong in my template with ifequals?

答: According to this, it seems you can only compare strings. I'd make my own template tag if I were you. </p>

Body:
So, I have a decimalfield that can be 3 different values. In my view,
I pass in a dictionary of values that contains the appropriate decimal
values as keys.

{% for item in booklist %}
    {% for key, value in numvec.items %}
        {{item.number}}
        {% ifequals item.number {{key}} %}
            {{value}}
        {% endifequals %}
    {% endfor %}
{% endfor %}

this is the dict I pass in as numvec:

numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"),

"TEST3":Decimal("0.255")}

the number field was defined as having these choices in my model:

BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),)

The item number prints out just fine in the view if I compare the dict
with the attribute, but for some reason the ifequals cannot properly
compare two decimals together. Is this a bug, or am I doing something
wrong in my template with ifequals?

OwnerDisplayName: Bernard Chhun


问:
Access last row added to table - PHP
I have a simple sql query adding a new row to a database and need it to return the a field back to Javascript. The field does Auto_increment but stupildy I called it 'itemId' so mysql_insert_id doesnt work and I don't think I have time to go and amend all the php files that use 'itemId'

Here's my code if it helps:

```<code>$addMainItem = "INSERT INTO newsItems (itemId, title, date, tags, location, latitude, longitude, visibleFrontpage, introText, fullDome, liveEvent, customServing, visitorAttraction, retail, digitalCinema, visiblePublic, thumbPath, links, smallDesc) VALUES ('','$title','$date','$tags','$loco','$lat','$long','$visiFront','$intro','$dome ','$live','$custom','$attrac','$retail','$cinema','$public','$thumbPath','$links','$smallDesc')";
$result = mysql_query($addMainItem) or die('error '.mysql_error());

if($result) echo (mysql_insert_id());
</code>```

答:
```<code>mysql_query("SELECT LAST_INSERT_ID()");
</code>```

Isn't it what are you looking for?

Title: Access last row added to table - PHP

Body:
I have a simple sql query adding a new row to a database and need it to return the a field back to Javascript. The field does Auto_increment but stupildy I called it 'itemId' so mysql_insert_id doesnt work and I don't think I have time to go and amend all the php files that use 'itemId'

Here's my code if it helps:

$addMainItem = "INSERT INTO newsItems (itemId, title, date, tags, location, latitude, longitude, visibleFrontpage, introText, fullDome, liveEvent, customServing, visitorAttraction, retail, digitalCinema, visiblePublic, thumbPath, links, smallDesc) VALUES ('','$title','$date','$tags','$loco','$lat','$long','$visiFront','$intro','$dome ','$live','$custom','$attrac','$retail','$cinema','$public','$thumbPath','$links','$smallDesc')";
$result = mysql_query($addMainItem) or die('error '.mysql_error());

if($result) echo (mysql_insert_id());

Body:
mysql_query("SELECT LAST_INSERT_ID()");

Isn't it what are you looking for?


问:
AngularJS, pause while loading Google Maps API
I'm using Angular Google Maps to load Google Maps API, but there's a 3-4 seconds pause in loading API script. So everything on the page is loaded -> 3-4 seconds pause -> API scripts starts loading -> map displayed.

Looks like it's just waiting for some timer event:

Google Maps config snippet:

```<code>  uiGmapGoogleMapApiProvider.configure({
    key: 'xxxxxxxxxx',
    v: '3',
    libraries: 'geocoder',
    preventLoad: false,
    china: false,
    transport: 'https'
  });
</code>```

Map loads here:

```<code>    <div id="shopMap" ng-init="initShopMap()"></div>
</code>```

via this function:

```<code>$scope.initShopMap = function() {
  if ($scope.shop.latitude && $scope.shop.longitude) {
    uiGmapGoogleMapApi.then(function(maps) {
      shopMap = new maps.Map(document.getElementById("shopMap"), {
        control: {},
        options: {
          draggable: true,
          scrollwheel: false
        },
        center: new maps.LatLng(0, 0),
        zoom: 14,
        marker: {
          options: {
            icon: {
              scaledSize: { width: 24, height: 36 },
              url: '/images/pm-shop-icon.png'
            }
          }
        }
      });

      directionsService = new maps.DirectionsService();

      initMarkers();
      $scope.showShopMap = true;
    });
  }
}
</code>```

Any ideas why that delay might happen? Would very appreciate any hints, thanks ✨

答:
Turned out, that api loading in this project was wrong, there wasn't this line in index.htm:

```<code> <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
</code>```

I wonder how maps even worked without this line :)

Body:
I'm using Angular Google Maps to load Google Maps API, but there's a 3-4 seconds pause in loading API script. So everything on the page is loaded -> 3-4 seconds pause -> API scripts starts loading -> map displayed.

Looks like it's just waiting for some timer event:

Google Maps config snippet:

  uiGmapGoogleMapApiProvider.configure({
    key: 'xxxxxxxxxx',
    v: '3',
    libraries: 'geocoder',
    preventLoad: false,
    china: false,
    transport: 'https'
  });

Map loads here:

via this function:

$scope.initShopMap = function() {
  if ($scope.shop.latitude && $scope.shop.longitude) {
    uiGmapGoogleMapApi.then(function(maps) {
      shopMap = new maps.Map(document.getElementById("shopMap"), {
        control: {},
        options: {
          draggable: true,
          scrollwheel: false
        },
        center: new maps.LatLng(0, 0),
        zoom: 14,
        marker: {
          options: {
            icon: {
              scaledSize: { width: 24, height: 36 },
              url: '/images/pm-shop-icon.png'
            }
          }
        }
      });

      directionsService = new maps.DirectionsService();

      initMarkers();
      $scope.showShopMap = true;
    });
  }
}

Any ideas why that delay might happen? Would very appreciate any hints, thanks ✨

Body:
Turned out, that api loading in this project was wrong, there wasn't this line in index.htm:

 <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>

I wonder how maps even worked without this line :)


问:
Go: JSON marshalling nested struct; incorrectly omitting outer fields
I'm trying to marshal nested structs. See a NON-FUNCTIONING example here (I can't import "compute" and "pretty" in the Go playground, but I've recreated my test logic and pasted the output).

```<code>package main

import (
    "encoding/json"
    "fmt"

    "github.com/kylelemons/godebug/pretty"
    compute "google.golang.org/api/compute/v1"
)

type CreateInstance struct {
    compute.Instance

    // Additional metadata to set for the instance.
    Metadata map[string]string `json:"metadata,omitempty"`
    // OAuth2 scopes to give the instance. If none are specified
    // https://www.googleapis.com/auth/devstorage.read_only will be added.
    Scopes []string `json:",omitempty"`

    // StartupScript is the Sources path to a startup script to use in this step.
    // This will be automatically mapped to the appropriate metadata key.
    StartupScript string `json:",omitempty"`
    // Project to create the instance in, overrides workflow Project.
    Project string `json:",omitempty"`
    // Zone to create the instance in, overrides workflow Zone.
    Zone string `json:",omitempty"`
    // Should this resource be cleaned up after the workflow?
    NoCleanup bool
    // Should we use the user-provided reference name as the actual resource name?
    ExactName bool

    // The name of the disk as known internally to Daisy.
    daisyName string
}

func main() {
    ci := <a *CreateInstance part of a larger data structure>
    j, _ := json.MarshalIndent(ci, "", "  ")
    fmt.Println(string(j))
    pretty.Print(ci)  # Pretty prints the struct.
}

##### OUTPUT #####
{
  "disks": [
    {
      "source": "disk"
    }
  ],
  "machineType": "${machine_type}",
  "name": "${instance_name}"
}
{Instance:      {CanIpForward:      false,
                 CpuPlatform:       "",
                 CreationTimestamp: "",
                 Description:       "",
                 Disks:             [{AutoDelete:        false,
                                      Boot:              false,
                                      DeviceName:        "",
                                      DiskEncryptionKey: nil,
                                      Index:             0,
                                      InitializeParams:  nil,
                                      Interface:         "",
                                      Kind:              "",
                                      Licenses:          [],
                                      Mode:              "",
                                      Source:            "disk",
                                      Type:              "",
                                      ForceSendFields:   [],
                                      NullFields:        []}],
                 Id:                0,
                 Kind:              "",
                 MachineType:       "${machine_type}",
                 Metadata:          nil,
                 Name:              "${instance_name}",
                 NetworkInterfaces: [],
                 Scheduling:        nil,
                 SelfLink:          "",
                 ServiceAccounts:   [],
                 Status:            "",
                 StatusMessage:     "",
                 Tags:              nil,
                 Zone:              "",
                 ServerResponse:    {HTTPStatusCode: 0,
                                     Header:         {}},
                 ForceSendFields:   [],
                 NullFields:        []},
 Metadata:      {},
 Scopes:        [],
 StartupScript: "",
 Project:       "",
 Zone:          "",
 NoCleanup:     false,
 ExactName:     false}
</code>```

Basically, I have a struct, CreateInstance, that embeds an Instance struct from the Google Compute Engine API client lib. CreateInstance also has two bool fields with no JSON tags, ExactName and NoCleanup.

When I try to marshal a CreateInstance, ExactName and NoCleanup are omitted, be they true or false.

答:
A compute.Instance is a json.Marshaler, so by embedding that type you are in essence giving your CreateInstance the MarshalJSON method from compute.Instance, which of course isn't going to output any of the fields in your CreateInstance struct.

You could define your own MarshalJSON method, and try to marshal the Instance manually or re-assign it to a new type that will use the default json output, but the API may be relying on the internal MarshalJSON behavior, so that's not guaranteed to be compatible, currently or with future versions.

Embedding types for json marshaling is is best avoided because it's all too easy to create confusing bugs like this. I would try to compose them in a different manner.

Body:
I'm trying to marshal nested structs. See a NON-FUNCTIONING example here (I can't import "compute" and "pretty" in the Go playground, but I've recreated my test logic and pasted the output).

package main

import (
    "encoding/json"
    "fmt"

    "github.com/kylelemons/godebug/pretty"
    compute "google.golang.org/api/compute/v1"
)

type CreateInstance struct {
    compute.Instance

    // Additional metadata to set for the instance.
    Metadata map[string]string `json:"metadata,omitempty"`
    // OAuth2 scopes to give the instance. If none are specified
    // https://www.googleapis.com/auth/devstorage.read_only will be added.
    Scopes []string `json:",omitempty"`

    // StartupScript is the Sources path to a startup script to use in this step.
    // This will be automatically mapped to the appropriate metadata key.
    StartupScript string `json:",omitempty"`
    // Project to create the instance in, overrides workflow Project.
    Project string `json:",omitempty"`
    // Zone to create the instance in, overrides workflow Zone.
    Zone string `json:",omitempty"`
    // Should this resource be cleaned up after the workflow?
    NoCleanup bool
    // Should we use the user-provided reference name as the actual resource name?
    ExactName bool

    // The name of the disk as known internally to Daisy.
    daisyName string
}

func main() {
    ci :=
    j, _ := json.MarshalIndent(ci, "", "  ")
    fmt.Println(string(j))
    pretty.Print(ci)  # Pretty prints the struct.
}

##### OUTPUT #####
{
  "disks": [
    {
      "source": "disk"
    }
  ],
  "machineType": "${machine_type}",
  "name": "${instance_name}"
}
{Instance:      {CanIpForward:      false,
                 CpuPlatform:       "",
                 CreationTimestamp: "",
                 Description:       "",
                 Disks:             [{AutoDelete:        false,
                                      Boot:              false,
                                      DeviceName:        "",
                                      DiskEncryptionKey: nil,
                                      Index:             0,
                                      InitializeParams:  nil,
                                      Interface:         "",
                                      Kind:              "",
                                      Licenses:          [],
                                      Mode:              "",
                                      Source:            "disk",
                                      Type:              "",
                                      ForceSendFields:   [],
                                      NullFields:        []}],
                 Id:                0,
                 Kind:              "",
                 MachineType:       "${machine_type}",
                 Metadata:          nil,
                 Name:              "${instance_name}",
                 NetworkInterfaces: [],
                 Scheduling:        nil,
                 SelfLink:          "",
                 ServiceAccounts:   [],
                 Status:            "",
                 StatusMessage:     "",
                 Tags:              nil,
                 Zone:              "",
                 ServerResponse:    {HTTPStatusCode: 0,
                                     Header:         {}},
                 ForceSendFields:   [],
                 NullFields:        []},
 Metadata:      {},
 Scopes:        [],
 StartupScript: "",
 Project:       "",
 Zone:          "",
 NoCleanup:     false,
 ExactName:     false}

Basically, I have a struct, CreateInstance, that embeds an Instance struct from the Google Compute Engine API client lib. CreateInstance also has two bool fields with no JSON tags, ExactName and NoCleanup.

When I try to marshal a CreateInstance, ExactName and NoCleanup are omitted, be they true or false.


问:
Ionic 3: BackgroundLocation updates are too rare
I'm currently facing a problem that is not so nice. I already created an issue but no response. I need every location change to update the camera center position. But this doesn't happen. The refresh is not definable with time. It's just very rare for my needs. Android and iOS is the same. The log is called every minute or something like that.
Also I tried the console log outside the ngZone but it's the same.
This is what my configuration code looks like:

```<code>let config = {
  desiredAccuracy: 0,
  stationaryRadius: 1,
  distanceFilter: 0,
  debug: true,
  interval: 2000,
  pauseLocationUpdates: false,
  activityType: "AutomotiveNavigation"
};

this.backgroundGeolocation.configure(config).subscribe((location) => {
  // Run update inside of Angular's zone
  this.zone.run(() => {
    if(this.map) {
      this.map.getMyLocation().then( (userLocation: MyLocation) => {
        console.log("INSIDE ZONE Google Maps Location \n LAT: " + userLocation.latLng.lat + "\nLNG: " + userLocation.latLng.lng);
        this.userLocation = userLocation.latLng;
        this.speed = userLocation.speed;
        this.bearing = userLocation.bearing;
        this.altitude = location.altitude;

        this.cameraFollow();
        this.notify(this.nearestReports[0]);
      }).catch( error => {
        alert("Background - NO GPS FOUND: " + error);
      });
    }
  });
});

// Turn ON the background-geolocation system.
this.backgroundGeolocation.start();
</code>```

答:
Consider using another Ionic Native plugin called Geolocation.

There is a very handy watchPosition() function in there that looks like what you are looking for. Here's an example:

let options = {
  enableHighAccuracy: true,
  timeout: Infinity, // don't return response until new ping is available from OS, to save battery
  maximumAge: 0
};

const subscription = this.geolocation.watchPosition(options)
  .filter((p) => p.coords !== undefined) //Filter Out Errors
  .subscribe(position => {
      console.log(position.coords.longitude + ' ' + position.coords.latitude);
});
```

<p>Don't forget to stop the subscription when not needed in order to save battery:</p>

```subscription.unsubscribe();
```

Body:
I'm currently facing a problem that is not so nice. I already created an issue but no response. I need every location change to update the camera center position. But this doesn't happen. The refresh is not definable with time. It's just very rare for my needs. Android and iOS is the same. The log is called every minute or something like that.
Also I tried the console log outside the ngZone but it's the same.
This is what my configuration code looks like:

let config = {
  desiredAccuracy: 0,
  stationaryRadius: 1,
  distanceFilter: 0,
  debug: true,
  interval: 2000,
  pauseLocationUpdates: false,
  activityType: "AutomotiveNavigation"
};

this.backgroundGeolocation.configure(config).subscribe((location) => {
  // Run update inside of Angular's zone
  this.zone.run(() => {
    if(this.map) {
      this.map.getMyLocation().then( (userLocation: MyLocation) => {
        console.log("INSIDE ZONE Google Maps Location \n LAT: " + userLocation.latLng.lat + "\nLNG: " + userLocation.latLng.lng);
        this.userLocation = userLocation.latLng;
        this.speed = userLocation.speed;
        this.bearing = userLocation.bearing;
        this.altitude = location.altitude;

        this.cameraFollow();
        this.notify(this.nearestReports[0]);
      }).catch( error => {
        alert("Background - NO GPS FOUND: " + error);
      });
    }
  });
});

// Turn ON the background-geolocation system.
this.backgroundGeolocation.start();

Body:
Consider using another Ionic Native plugin called Geolocation.

There is a very handy watchPosition() function in there that looks like what you are looking for. Here's an example:

let options = {
  enableHighAccuracy: true,
  timeout: Infinity, // don't return response until new ping is available from OS, to save battery
  maximumAge: 0
};

const subscription = this.geolocation.watchPosition(options)
  .filter((p) => p.coords !== undefined) //Filter Out Errors
  .subscribe(position => {
      console.log(position.coords.longitude + ' ' + position.coords.latitude);
});

Don't forget to stop the subscription when not needed in order to save battery:

subscription.unsubscribe();


问:
Trying to append dates in R but the time component is being dropped?
I have come across this problem. Consider an array of dates:

```<code>> y <- c("2012-01-02 10:00:00", "2012-01-03 09:00:00")
> as.POSIXct(y)
[1] "2012-01-02 10:00:00" "2012-01-03 09:00:00"
</code>```

Now consider the same array with "2012-01-04 00:00:00". This vector has already undergone as.POSIXct, hence we get c("2012-01-02 10:00:00", "2012-01-03 09:00:00", "2012-01-04"). Then

```<code>> y <- c("2012-01-02 10:00:00", "2012-01-03 09:00:00", "2012-01-04")
> as.POSIXct(y)
[1] "2012-01-02 GMT" "2012-01-03 GMT" "2012-01-04 GMT"
</code>```

Now the times have been dropped from all the dates rather than just adding back 00:00:00 to 2012-01-04. I've played around with formatting POSIXct and strptime, but am not getting anywhere. For example:

```<code>> as.POSIXct(strptime("2011-03-27 00:00:00", "%Y-%m-%d %H:%M:%S"))
[1] "2011-03-27 GMT"
</code>```

How can I retrieve the correct values?

答:
This can be solved by using anytime

```<code>anytime::anytime(y)
#[1] "2012-01-02 10:00:00 IST" "2012-01-03 09:00:00 IST" "2012-01-04 00:00:00 IST"
</code>```

Note that anytime have a default set of formats.  We can find those with getFormats().  If the format is not in the list, then use the addFormats to add a format

Or another way is by using parse_date_time from lubridate

```<code>lubridate::parse_date_time(y, guess_formats(y, c('ymd', 'ymd_HMS')))
#[1] "2012-01-02 10:00:00 UTC" "2012-01-03 09:00:00 UTC" "2012-01-04 00:00:00 UTC"
</code>```

We guess the problem stems from the multiple format in the input vector and as.POSIXct takes only a single format, so probably it unifies the format to a single one by removing the time substring from the other elements.  This was tested on R 3.4.0 and on R 3.1.3 and both get the same output as in the OP's post

Body:
I have come across this problem. Consider an array of dates:

> y <- c("2012-01-02 10:00:00", "2012-01-03 09:00:00")
> as.POSIXct(y)
[1] "2012-01-02 10:00:00" "2012-01-03 09:00:00"

Now consider the same array with "2012-01-04 00:00:00". This vector has already undergone as.POSIXct, hence we get c("2012-01-02 10:00:00", "2012-01-03 09:00:00", "2012-01-04"). Then

> y <- c("2012-01-02 10:00:00", "2012-01-03 09:00:00", "2012-01-04")
> as.POSIXct(y)
[1] "2012-01-02 GMT" "2012-01-03 GMT" "2012-01-04 GMT"

Now the times have been dropped from all the dates rather than just adding back 00:00:00 to 2012-01-04. I've played around with formatting POSIXct and strptime, but am not getting anywhere. For example:

> as.POSIXct(strptime("2011-03-27 00:00:00", "%Y-%m-%d %H:%M:%S"))
[1] "2011-03-27 GMT"

How can I retrieve the correct values?

Body:
This can be solved by using anytime

anytime::anytime(y)
#[1] "2012-01-02 10:00:00 IST" "2012-01-03 09:00:00 IST" "2012-01-04 00:00:00 IST"

Note that anytime have a default set of formats.  We can find those with getFormats().  If the format is not in the list, then use the addFormats to add a format

Or another way is by using parse_date_time from lubridate

lubridate::parse_date_time(y, guess_formats(y, c('ymd', 'ymd_HMS')))
#[1] "2012-01-02 10:00:00 UTC" "2012-01-03 09:00:00 UTC" "2012-01-04 00:00:00 UTC"

We guess the problem stems from the multiple format in the input vector and as.POSIXct takes only a single format, so probably it unifies the format to a single one by removing the time substring from the other elements.  This was tested on R 3.4.0 and on R 3.1.3 and both get the same output as in the OP's post


问:
Access multiple versions of a package in Java
We have several applications that use Apache HTTPClient 3 to make HTTP requests. Recently we have also began creating web service clients that use HTTPClient 4 for various reasons. The Apache stance is that "major releases are not backwards compatible". While I would love to update all of our projects to use version 4, that's simply not feasible.

So, while my main question is rather general, my particular question is. How can I use HTTPClient version 3 and 4 in the same application? In our case an application can be a web, desktop, or command line app.

I have read the SO question for java-dynamically-load-multiple-versions-of-same-class which seems semi close but I don't care so much about the dynamic part. In fact I would like the JARs to be shipped with the app (example, WEB-INF/lib for web apps) I also see OSGi mentioned a lot in questions similar to this one but it seems to be overkill or perhaps overly complex (maybe a simple example could prove otherwise).

In the end I want to be able to hand a team a set of jars that they can drop in and it just works independent of their project using HTTP Client 3.

答:
You have to use separate class loaders for v3 and v4. Put v3 and v4 jars to separate folders beyond your application classpath. Use URLClassLoadedr to load each one of the versions. The URL that you pass to each one of class loaders should contain URL to specific version of HTTP client.

But may I give you an advice? Check first that you really need all these before you are starting. That is right that the versions could be incompatible. But there is a huge chance that they are.


问:
How to pass class name as generic type <T> based on enum value?
I have the below function.

```<code>public static string SerializeObjectToXML<T>(object mainColumn)
{
   return string.empty;
}
</code>```

I am trying to pass classname based on enum value as below.

```<code>var tempstr = ClassName.SerializeObjectToXML<EnumClass.class1 == enumvalue ? ClassA: ClassB>(value);
</code>```

Can I do this?  If not how can I achieve this using inline enum condition?

答:
I would suggest this:</p>

```<code>var tempstr = EnumClass.class1 == enumvalue
? ClassName.SerializeObjectToXML<ClassA>(value)
: ClassName.SerializeObjectToXML<ClassB>(value);
</code>```

Body:
I have the below function.

public static string SerializeObjectToXML<T>(object mainColumn)
{
   return string.empty;
}

I am trying to pass classname based on enum value as below.

var tempstr = ClassName.SerializeObjectToXML<EnumClass.class1 == enumvalue ? ClassA: ClassB>(value);

Can I do this?  If not how can I achieve this using inline enum condition?

Body:
I would suggest this:

var tempstr = EnumClass.class1 == enumvalue
? ClassName.SerializeObjectToXML<ClassA>(value)
: ClassName.SerializeObjectToXML<ClassB>(value);


问:
Squid Connection Refused HTTPS
I have managed to get my HTTP "proxy" connection to work but on most https connections I get the error:

Connection to  failed.

The system returned: (111) Connection refused

Here is my config file I am currently using in squid:

```<code>http_port 3128

refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern .               0       20%     4320

acl localnet src 10.0.0.0/8     # RFC 1918 possible internal network
acl localnet src 172.16.0.0/12  # RFC 1918 possible internal network
acl myhost src <myip>
http_access allow myhost
acl SSL_ports port 443

acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT

via off
forwarded_for off

http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow all
dns_nameservers 8.8.8.8 8.8.4.4
</code>```

Running on a Ubuntu 12.04 VPS - connecting remotely via the browser proxy settings page...

All I want to do is to be able to connect to my server and browse http and https sites. Http works with the config above... https does not...

答:
i would recommend keeping

```<code>http_access deny CONNECT !SSL_ports
</code>```

but allowing those listed by adding:

```<code>http_access allow SSL_ports
</code>```

Title: Squid Connection Refused HTTPS

Body:
I have managed to get my HTTP "proxy" connection to work but on most https connections I get the error:

Connection to  failed.

The system returned: (111) Connection refused

Here is my config file I am currently using in squid:

http_port 3128

refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern .               0       20%     4320

acl localnet src 10.0.0.0/8     # RFC 1918 possible internal network
acl localnet src 172.16.0.0/12  # RFC 1918 possible internal network
acl myhost src <myip>
http_access allow myhost
acl SSL_ports port 443

acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT

via off
forwarded_for off

http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow all
dns_nameservers 8.8.8.8 8.8.4.4

Running on a Ubuntu 12.04 VPS - connecting remotely via the browser proxy settings page...

All I want to do is to be able to connect to my server and browse http and https sites. Http works with the config above... https does not...

Body:
i would recommend keeping

http_access deny CONNECT !SSL_ports

but allowing those listed by adding:

http_access allow SSL_ports


问:
Appended href Attribute not Working - Javascript
I'm setting up an alert that will slide in at the top of a page.  In the code the href attribute doesn't seem to be adding the web address. I'm not getting any errors in my console, but can't seem to find out what is causing this.  When you click on the 'Go to Google' button I've set up as a test, it should take you to Google, but it doesn't?  The code and Codepen are below, any help would be amazing.

Codepen is here: https://codepen.io/emilychews/pen/ZyGrrR

HTML

```<code><div id="header">Original Header</div>
</code>```

CSS

```<code>   * {font-family: arial;
 line-height: 100px;}

#header {width: 100%;
height: 100px;
background: red;
color: white;
text-align: center;}

div#newBar {
  width: 100%;
  height: 50px;
  background-color: blue;
  line-height: 50px;
  text-align: center;
  color: white;
}

div#topbar_button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 11%;
  height: 54%;
  background: white;
  position: relative;
  bottom: 41PX;
  margin-left: 75%;
  color: blue;
  border-radius: 2px;
}
</code>```

JAVASCRIPT

```<code>// window.onload = function() {

var header = document.getElementById('header');

var newBar = document.createElement('div');
newBar.id = "newBar";

var newBarText = document.createTextNode("Click on the link to go to Google");
newBar.appendChild(newBarText);

// create button and anchor tag and append
var topBarButton = document.createElement('div');
    topBarButton.id = "topbar_button";
var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    topBarButton.innerHTML = "Visit Google";

newBar.appendChild(topBarButton);

// append new top bar to header
var header = document.getElementById('header');
header.parentNode.insertBefore(newBar, header);

// };
</code>```

答:
```<code>topBarButton.appendChild(anchorTag);
topBarButton.innerHTML = "Visit Google";
</code>```

you just replace the button with "Visit Google"

Body:
I'm setting up an alert that will slide in at the top of a page.  In the code the href attribute doesn't seem to be adding the web address. I'm not getting any errors in my console, but can't seem to find out what is causing this.  When you click on the 'Go to Google' button I've set up as a test, it should take you to Google, but it doesn't?  The code and Codepen are below, any help would be amazing.

Codepen is here: https://codepen.io/emilychews/pen/ZyGrrR

HTML

Original Header

CSS

   * {font-family: arial;
 line-height: 100px;}

#header {width: 100%;
height: 100px;
background: red;
color: white;
text-align: center;}

div#newBar {
  width: 100%;
  height: 50px;
  background-color: blue;
  line-height: 50px;
  text-align: center;
  color: white;
}

div#topbar_button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 11%;
  height: 54%;
  background: white;
  position: relative;
  bottom: 41PX;
  margin-left: 75%;
  color: blue;
  border-radius: 2px;
}

JAVASCRIPT

// window.onload = function() {

var header = document.getElementById('header');

var newBar = document.createElement('div');
newBar.id = "newBar";

var newBarText = document.createTextNode("Click on the link to go to Google");
newBar.appendChild(newBarText);

// create button and anchor tag and append
var topBarButton = document.createElement('div');
    topBarButton.id = "topbar_button";
var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    topBarButton.innerHTML = "Visit Google";

newBar.appendChild(topBarButton);

// append new top bar to header
var header = document.getElementById('header');
header.parentNode.insertBefore(newBar, header);

// };

Body:
topBarButton.appendChild(anchorTag);
topBarButton.innerHTML = "Visit Google";

you just replace the button with "Visit Google"


问:
cloudfoundry java buildpack memory changes not reflecting
I want to make changes in memory settings for my java apps in cloudfoundry java-buildpack. I have tried these two ways:

Using JBP_CONFIG_OPEN_JDK_JRE paramter in my manifest.yml. As
suggested in
https://github.com/cloudfoundry/java-buildpack-memory-calculator

Making this change in config\open_jdk_jre.yml:

memory_calculator:

  version: 3.8.0_RELEASE

  repository_root:
  "{default.repository.root}/memory-calculator/{platform}/{architecture}"
  stack_threads: 300

   memory_sizes:

  stack: 2M

  metaspace: 160M

  heap: 900M

However, none of this is getting reflected while deployment of my apps. I am using latest java-buildpack.

答:
This depends on the version of the Java build pack that you're using.

Version 3.x

For versions 3.x, you would set an env variable to configure the memory calculator.  Like here.

https://github.com/cloudfoundry/java-buildpack/tree/3.x#configuration-and-extension

Ex:

```<code>cf set-env my-application JBP_CONFIG_OPEN_JDK_JRE '{ memory_calculator: { memory_heuristics: { heap: 85, stack: 10 } } }'
</code>```

This will then override the memory heuristics configuration that defaults in the build pack, specifically the heap and stack weights.

A few notes:

Understanding what the different memory configuration options do is another matter.  You can read about those here.

This is only for OpenJDK, if you're using a different JDK then the configuration options are slightly different. Ex: JBP_CONFIG_ORACLE_JRE for Oracle.  The name mirrors the config file path & name.

It doesn't matter how you set the env variable for your app.  You can use cf set-env like above or you can set the env variable in your manifest.yml file.  Both work just fine.

Version 4.x

In version 4.x, the configuration of the JVM's memory settings has gotten a lot simpler.

however if you believe that your application doesn’t need these JVM defaults, you can now configure those memory regions directly with JVM options.

https://www.cloudfoundry.org/just-released-java-buildpack-4-0/

What this means is you still configure the JVM settings through an env variable, but you only need to set JAVA_OPTS and you use the standard JVM configuration options.

For example:

```<code>cf set-env my-app JAVA_OPTS '-XX:ReservedCodeCacheSize=100M'
</code>```

You can set JAVA_OPTS in your manifest.yml, if you prefer doing that instead of running cf set-env.

Hope that helps!

Body:
This depends on the version of the Java build pack that you're using.

Version 3.x

For versions 3.x, you would set an env variable to configure the memory calculator.  Like here.

https://github.com/cloudfoundry/java-buildpack/tree/3.x#configuration-and-extension

Ex:

cf set-env my-application JBP_CONFIG_OPEN_JDK_JRE '{ memory_calculator: { memory_heuristics: { heap: 85, stack: 10 } } }'

This will then override the memory heuristics configuration that defaults in the build pack, specifically the heap and stack weights.

A few notes:

Understanding what the different memory configuration options do is another matter.  You can read about those here.

This is only for OpenJDK, if you're using a different JDK then the configuration options are slightly different. Ex: JBP_CONFIG_ORACLE_JRE for Oracle.  The name mirrors the config file path & name.

It doesn't matter how you set the env variable for your app.  You can use cf set-env like above or you can set the env variable in your manifest.yml file.  Both work just fine.

Version 4.x

In version 4.x, the configuration of the JVM's memory settings has gotten a lot simpler.

however if you believe that your application doesn’t need these JVM defaults, you can now configure those memory regions directly with JVM options.

https://www.cloudfoundry.org/just-released-java-buildpack-4-0/

What this means is you still configure the JVM settings through an env variable, but you only need to set JAVA_OPTS and you use the standard JVM configuration options.

For example:

cf set-env my-app JAVA_OPTS '-XX:ReservedCodeCacheSize=100M'

You can set JAVA_OPTS in your manifest.yml, if you prefer doing that instead of running cf set-env.

Hope that helps!


问:
How can I control decimal field to allow enter more than one point?
I have a field that I can control that not accepts letters etc. I allow to enter "." In order to input decimals. How can I control that not more than one "."?

Here my source code:

```<code>$(".allow_decimal").on("input", function(evt) {
   var self = $(this);
   self.val(self.val().replace(/[^0-9\.]/g, ''));
   if ((evt.which != 46 || self.val().indexOf('.') != -1) &&
       (evt.which < 48 || evt.which > 57))
   {
     evt.preventDefault();
   }
});
</code>```

答:
The HTML5 specification allows for a number input type. One of the attributes allowed for the number input is step which is the increments that the number may go up/down in:

<form>
<input type="number" step="0.1" />
<input type="submit">
</form>```

While, yes, you can type in something like '2.25', when you try to submit the form, any HTML5 compliant browser will tell you off for it:

This only applies to HTML5 compliant browsers: CanIUse.com

As always - don't trust anything sent by a user - ALWAYS validate on the server ;)

Body:
I have a field that I can control that not accepts letters etc. I allow to enter "." In order to input decimals. How can I control that not more than one "."?

Here my source code:

$(".allow_decimal").on("input", function(evt) {
   var self = $(this);
   self.val(self.val().replace(/[^0-9\.]/g, ''));
   if ((evt.which != 46 || self.val().indexOf('.') != -1) &&
       (evt.which < 48 || evt.which > 57))
   {
     evt.preventDefault();
   }
});

Body:
The HTML5 specification allows for a number input type. One of the attributes allowed for the number input is step which is the increments that the number may go up/down in:

<form>
<input type="number" step="0.1" />
<input type="submit">
</form>

While, yes, you can type in something like '2.25', when you try to submit the form, any HTML5 compliant browser will tell you off for it:

This only applies to HTML5 compliant browsers: CanIUse.com

As always - don't trust anything sent by a user - ALWAYS validate on the server ;)


问:
Wait for Cmd process to end -java
Process p= Runtime.getRuntime().exec("cmd.exe /c cd \""+path+"\" & start cmd.exe /k \"mvn clean install\" & wait");

int i = p.waitFor();

print(p);

答:
Okay just solved it..

Process p= Runtime.getRuntime().exec("cmd.exe /c cd \""+path+"\" & start /wait cmd.exe /k \"mvn clean install\"");

worked

Title: Wait for Cmd process to end -java


问:
lumen throw 405 Method Not Allowed on get route
I am not able to understand why I am getting 405 below

```<code>$app->group(['prefix' => 'api/v1'], function($app)
{
    $app->get('my','MyController@index');
    $app->post('my','MyController@store');
});
</code>```

post url is working as expected but when I defined get route the application start throwing me 405 .

calling url show

```<code>in RoutesRequests.php line 596
at Application->handleDispatcherResponse(array(2, array('POST'))) in RoutesRequests.php line 533
at Application->Laravel\Lumen\Concerns\{closure}() in RoutesRequests.php line 781
at Application->sendThroughPipeline(array(), object(Closure)) in RoutesRequests.php line 534
at Application->dispatch(null) in RoutesRequests.php line 475
at Application->run() in index.php line 28
</code>```

post url is working fine it's just the get url is throwing 405...cleared the cache , generated the autoload file...not sure what wrong..

Define new controller with new route and it throws 404...I am not seeing it as a route issue there is something else..

答:
Just had the same behaviour, spent like an hour trying to solve it.

In the end it was trailing slash in GET query.

Body:
I am not able to understand why I am getting 405 below

$app->group(['prefix' => 'api/v1'], function($app)
{
    $app->get('my','MyController@index');
    $app->post('my','MyController@store');
});

post url is working as expected but when I defined get route the application start throwing me 405 .

calling url show

in RoutesRequests.php line 596
at Application->handleDispatcherResponse(array(2, array('POST'))) in RoutesRequests.php line 533
at Application->Laravel\Lumen\Concerns\{closure}() in RoutesRequests.php line 781
at Application->sendThroughPipeline(array(), object(Closure)) in RoutesRequests.php line 534
at Application->dispatch(null) in RoutesRequests.php line 475
at Application->run() in index.php line 28

post url is working fine it's just the get url is throwing 405...cleared the cache , generated the autoload file...not sure what wrong..

Define new controller with new route and it throws 404...I am not seeing it as a route issue there is something else..


问:
STM32F051 timer configuration
I've met problem with timer configuration in STM32F051.
I'am using StdPeriphLibrary, and I wish to generate an interrupt every 1 ms (freq = 1kHz).

This is the timer initialization:

```<code>void TIMER_initHardware(void)
{

    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

    GPIO_InitTypeDef gpioInitStruct;
    gpioInitStruct.GPIO_Mode = GPIO_Mode_OUT;
    gpioInitStruct.GPIO_OType = GPIO_OType_PP;
    gpioInitStruct.GPIO_Pin = GPIO_Pin_12;
    gpioInitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
    gpioInitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &gpioInitStruct);
    GPIO_ResetBits(GPIOA, GPIO_Pin_12);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_OCInitTypeDef       TIM_OCInitStructure;
    NVIC_InitTypeDef        NVIC_InitStructure;

    NVIC_InitStructure.NVIC_IRQChannel                   = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPriority           = 3;
    NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    RCC_PCLKConfig(RCC_HCLK_Div1);

    SystemCoreClockUpdate();

    TIM_TimeBaseStructure.TIM_Period        = 0xFFFF; //32767;
    TIM_TimeBaseStructure.TIM_Prescaler     = (SystemCoreClock/1000000)-1;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode   = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

    TIM_OCInitStructure.TIM_OCMode      = TIM_OCMode_Timing;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse       = TIMER_TIM2_ADD_1MS;
    TIM_OCInitStructure.TIM_OCPolarity  = TIM_OCPolarity_Low;

    TIM_OC1Init(TIM2, &TIM_OCInitStructure);
    TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);

    TIM_ITConfig(TIM2, TIM_IT_CC1, ENABLE);

    TIM_Cmd(TIM2, ENABLE);

}
</code>```

And here is the interrupt routine:

```<code>void TIM2_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM2, TIM_IT_CC1) != RESET)
    {
        TIM_ClearITPendingBit(TIM2, TIM_IT_CC1);
        TIM_SetCompare1(TIM2, TIM_GetCapture1(TIM2) + TIMER_TIM2_ADD_1MS);
        tick = 1;
        if(GPIO_ReadOutputDataBit(GPIOA, GPIO_Pin_12))
        {
            GPIO_ResetBits(GPIOA, GPIO_Pin_12);
        }
        else
        {
            GPIO_SetBits(GPIOA, GPIO_Pin_12);
        }

}
</code>```

This code Generates an interrupt every 66 ms - checked on oscilloscope.

There are no other interrupts used in application.

答:
Try to update your init code with:

```<code>...
TIM_TimeBaseStructure.TIM_Period        = 999;
...
TIM_OCInitStructure.TIM_Pulse       = 0;
...
</code>```

You have set your timer clock to 1MHz (prescaler), so you need to subdivide this by 1000 (period = 1000-1 = 999). The pulse is not used here.

Also in your interrupt handler, I am not sure that you need to do this and I think it can be removed:

```<code>TIM_SetCompare1(TIM2, TIM_GetCapture1(TIM2) + TIMER_TIM2_ADD_1MS);
</code>```

Title: STM32F051 timer configuration

Body:
I've met problem with timer configuration in STM32F051.
I'am using StdPeriphLibrary, and I wish to generate an interrupt every 1 ms (freq = 1kHz).

This is the timer initialization:

void TIMER_initHardware(void)
{

    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

    GPIO_InitTypeDef gpioInitStruct;
    gpioInitStruct.GPIO_Mode = GPIO_Mode_OUT;
    gpioInitStruct.GPIO_OType = GPIO_OType_PP;
    gpioInitStruct.GPIO_Pin = GPIO_Pin_12;
    gpioInitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
    gpioInitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &gpioInitStruct);
    GPIO_ResetBits(GPIOA, GPIO_Pin_12);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_OCInitTypeDef       TIM_OCInitStructure;
    NVIC_InitTypeDef        NVIC_InitStructure;

    NVIC_InitStructure.NVIC_IRQChannel                   = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPriority           = 3;
    NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    RCC_PCLKConfig(RCC_HCLK_Div1);

    SystemCoreClockUpdate();

    TIM_TimeBaseStructure.TIM_Period        = 0xFFFF; //32767;
    TIM_TimeBaseStructure.TIM_Prescaler     = (SystemCoreClock/1000000)-1;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode   = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

    TIM_OCInitStructure.TIM_OCMode      = TIM_OCMode_Timing;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse       = TIMER_TIM2_ADD_1MS;
    TIM_OCInitStructure.TIM_OCPolarity  = TIM_OCPolarity_Low;

    TIM_OC1Init(TIM2, &TIM_OCInitStructure);
    TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);

    TIM_ITConfig(TIM2, TIM_IT_CC1, ENABLE);

    TIM_Cmd(TIM2, ENABLE);

}

And here is the interrupt routine:

void TIM2_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM2, TIM_IT_CC1) != RESET)
    {
        TIM_ClearITPendingBit(TIM2, TIM_IT_CC1);
        TIM_SetCompare1(TIM2, TIM_GetCapture1(TIM2) + TIMER_TIM2_ADD_1MS);
        tick = 1;
        if(GPIO_ReadOutputDataBit(GPIOA, GPIO_Pin_12))
        {
            GPIO_ResetBits(GPIOA, GPIO_Pin_12);
        }
        else
        {
            GPIO_SetBits(GPIOA, GPIO_Pin_12);
        }

}

This code Generates an interrupt every 66 ms - checked on oscilloscope.

There are no other interrupts used in application.

Body:
Try to update your init code with:

...
TIM_TimeBaseStructure.TIM_Period        = 999;
...
TIM_OCInitStructure.TIM_Pulse       = 0;
...

You have set your timer clock to 1MHz (prescaler), so you need to subdivide this by 1000 (period = 1000-1 = 999). The pulse is not used here.

Also in your interrupt handler, I am not sure that you need to do this and I think it can be removed:

TIM_SetCompare1(TIM2, TIM_GetCapture1(TIM2) + TIMER_TIM2_ADD_1MS);


问:
Duplicate entry for key 'PRIMARY' php
I have the following datatables:

When I enter the data to the participantes_atividades table it shows me this error:

Duplicate entry for key 'PRIMARY

```<code>$sql = "INSERT INTO participantes_atividades (cd_p,cd_ati) VALUES ('$p','$cd')";

if (mysqli_query($connect, $sql) or die (mysqli_error($connect)))
</code>```

答:
If you are inserting data in "participantes" then the value being inserted in "codigo participante" already exists. A primary key field needs to be unique, which your data insert is violating.
It would be similar to other table.</p>

Title: Duplicate entry for key 'PRIMARY' php

Body:
I have the following datatables:

When I enter the data to the participantes_atividades table it shows me this error:

Duplicate entry for key 'PRIMARY

$sql = "INSERT INTO participantes_atividades (cd_p,cd_ati) VALUES ('$p','$cd')";

if (mysqli_query($connect, $sql) or die (mysqli_error($connect)))


问:
How can i decide the optimal iterations for grabcut algorithm?
Grab cut algorithm gives different results for different number of iterations and settle down after some time without any further change. But for my dataset, if i allow it to settle down, it is cropping foreground also. If i do for 2,3 iterations only, then the result is better.

My target is to get the complete foreground without missing any detail. Even the output has some background, it is acceptable. SO my question is how many iterations are optimal for grabcut with minimum foreground cut?

答:
in the function
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,iterCount,cv2.GC_INIT_WITH_RECT)
you can change iterCount upto 5 for normal use of Grabcut Algorithm.

When you use iterCount = 1 or iterCount = 2 you will get minimum background subtraction as per your drawn rectangle.

So, if you want grabCut with minimum foreground cut, user iterCount=2 and then specify your rectangle close to main object.

Hope this helps...


问:
Where is the API for "Invisible Ink" located?
I have secrets that need to be shared in my application, and would like to adopt the "Invisible Ink" feature that is new in iOS 10.

https://youtu.be/n5jXg_NNiCA?t=1h27m30s

Since I'm creating a greenfield application (version 1) I think this visual element of consistency is a good thing to include in my app.

Is the invisible ink UX available for developers?

答:
First and foremost, the invisible ink view is inside a private framework, and using private frameworks will cause your app to be rejected in the App Store reviewing process. Still, for the community's sake, here's your answer (I'm sorry I got it to you in Obj-C, I'll try and come back later to update it to Swift):

You need to go around using dlopen to load the ChatKit framework manually in your app:

```<code>dlopen("/System/Library/PrivateFrameworks/ChatKit.framework/ChatKit", RTLD_LAZY);
// or use RTLD_NOW if you need it loaded immediately
</code>```

Then, instantiate a CKInvisibleInkImageEffectView using NSClassFromString:

```<code>id invisibleInk = [[NSClassFromString(@"CKInvisibleInkImageEffectView") alloc] initWithFrame: yourFrame];
[invisibleInk performSelector:@selector(setImage:) withObject: yourUIImage];
//You likely want to put the InvisibleInkView right over an UIImageView containing the very same image
</code>```

That should do the trick for you. Remember to actually add the InvisibleInk view wherever you want using yourView.addSubview(invisibleInk), and have fun.

Body:
First and foremost, the invisible ink view is inside a private framework, and using private frameworks will cause your app to be rejected in the App Store reviewing process. Still, for the community's sake, here's your answer (I'm sorry I got it to you in Obj-C, I'll try and come back later to update it to Swift):

You need to go around using dlopen to load the ChatKit framework manually in your app:

dlopen("/System/Library/PrivateFrameworks/ChatKit.framework/ChatKit", RTLD_LAZY);
// or use RTLD_NOW if you need it loaded immediately

Then, instantiate a CKInvisibleInkImageEffectView using NSClassFromString:

id invisibleInk = [[NSClassFromString(@"CKInvisibleInkImageEffectView") alloc] initWithFrame: yourFrame];
[invisibleInk performSelector:@selector(setImage:) withObject: yourUIImage];
//You likely want to put the InvisibleInkView right over an UIImageView containing the very same image

That should do the trick for you. Remember to actually add the InvisibleInk view wherever you want using yourView.addSubview(invisibleInk), and have fun.


问:
Can a library in Android have its own intent filters?
I'd like to develop a library that can be included in other Android applications to intercept certain kinds of intent. Is it possible?

I've created a library and a test project, both having their own AndroidManifest.xml files. In library's manifest I've defined an intent filter for action "TEST". But when I launch an intent with action "TEST" from the test project, that intent filter does not work.

Are intent filters from libraries ever used by Android?

答:
Are intent filters from libraries ever used by Android?

Presently, AFAIK, the manifest from the library is ignored. That might change in the future.


问:
Invalid entitlements error when adding push notifications
I'm trying to add push notifications to my chat app following this tutorial: https://www.appcoda.com/firebase-push-notifications/

I've toggled Push Notifications to On in "Capabilities":

My provisioning profile is set up for push notifications:

I downloaded it, and double clicked it to install.

For Code Signing, in Target -> Code Signing:

And Project -> Code Signing:

Entitlements file:

When I ran the project it succeeded, then said "The executable was signed with invalid entitlements". Full error The entitlements specified in your application’s Code Signing Entitlements file are invalid, not permitted, or do not match those specified in your provisioning profile. (0xE8008016).

Thanks for reading.. Any help on this will be hugely appreciated!

EDIT: Additional Information

Using Xcode 8.2.1

In my App ID in the developers portal, Game Center, In-App Purchases, and Push Notifications are enabled. It's my understanding that Game Center and IAP are enabled by default.

I've tried turning GC and IAP On, and then Off again. Restart Xcode, clean, build. No luck

I've tried turning GC and IAP On, then regenerating my provisioning profiles, installing them, cleaning and building. No luck.

My Bundle ID matches everywhere.

答:
From your project settings, go to general then check the checkbox Automatically manage signing then select your team from below field! that's it!

You can refer the below screen shot,


问:
Apache POI can't format filled cells as numeric
I am trying to change CellTypes of already filled Cells in Apache POI, but I keep getting an IllegalStateException. The problem should be reproduceable using POI(-ooxml) 3.16.

```<code>public static void main(String[] args) throws Exception
{
    //Setting up the workbook and the sheet
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet s = wb.createSheet();

    //Setting up the CTTable
    XSSFTable t = s.createTable();
    CTTable ctt = t.getCTTable();
    ctt.setId(1);
    ctt.setName("CT Table Test");
    ctt.setRef("A1:B2");
    CTTableColumns cttcs = ctt.addNewTableColumns();
    CTTableColumn cttc1 = cttcs.addNewTableColumn();
    cttc1.setId(1);
    CTTableColumn cttc2 = cttcs.addNewTableColumn();
    cttc2.setId(2);

    //Creating the cells
    XSSFCell c1 = s.createRow(0).createCell(0);
    XSSFCell c2 = s.getRow(0).createCell(1);
    XSSFCell c3 = s.createRow(1).createCell(0);
    XSSFCell c4 = s.getRow(1).createCell(1);

    //Inserting values; some numeric strings, some alphabetical strings
    c1.setCellValue(/*12*/"12"); //Numbers have to be inputted as a string
    c2.setCellValue(/*34*/"34"); //for the code to work
    c3.setCellValue("AB");
    c4.setCellValue("CD");

    //With those lines, the code would also crash
    //c1.setCellType(CellType.NUMERIC);
    //c2.setCellType(CellType.NUMERIC);

    //On write() it produces a "java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell"
    FileOutputStream fos = new FileOutputStream("test.xlsx");
    wb.write(fos);
    fos.flush();
    fos.close();
    wb.close();
}
</code>```

Also, when not setting any CellValue for c1 and c2, you can actually set their CellType to NUMERIC and suddenly the code works again. It also works without the CTTable.

Any ideas or workarounds? Or is it a bug of POI (since it tries fetching a string value from any Cell regardless of its CellType)?

答:
You need to use Apache POI 3.17 beta 1 or later for this to work (or a nightly build from after 20170607)

If you do, you can also make your code significantly simpler and cleaner too. As shown in the testNumericCellsInTable() unit test, your code could simplify to something like:

```<code>    Workbook wb = new XSSFWorkbook();
    Sheet s = wb.createSheet();

    // Create some cells, some numeric, some not
    Cell c1 = s.createRow(0).createCell(0);
    Cell c2 = s.getRow(0).createCell(1);
    Cell c3 = s.getRow(0).createCell(2);
    Cell c4 = s.createRow(1).createCell(0);
    Cell c5 = s.getRow(1).createCell(1);
    Cell c6 = s.getRow(1).createCell(2);
    c1.setCellValue(12);
    c2.setCellValue(34.56);
    c3.setCellValue("ABCD");
    c4.setCellValue("AB");
    c5.setCellValue("CD");
    c6.setCellValue("EF");

    // Setting up the CTTable
    Table t = s.createTable();
    t.setName("TableTest");
    t.setDisplayName("CT_Table_Test");
    t.addColumn();
    t.addColumn();
    t.addColumn();
    t.setCellReferences(new AreaReference(
            new CellReference(c1), new CellReference(c6)
    ));
</code>```

(Unlike your problem code, this does a mixture of integers, floating point numbers and strings for the table headers, to show the various options)

Body:
I am trying to change CellTypes of already filled Cells in Apache POI, but I keep getting an IllegalStateException. The problem should be reproduceable using POI(-ooxml) 3.16.

public static void main(String[] args) throws Exception
{
    //Setting up the workbook and the sheet
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet s = wb.createSheet();

    //Setting up the CTTable
    XSSFTable t = s.createTable();
    CTTable ctt = t.getCTTable();
    ctt.setId(1);
    ctt.setName("CT Table Test");
    ctt.setRef("A1:B2");
    CTTableColumns cttcs = ctt.addNewTableColumns();
    CTTableColumn cttc1 = cttcs.addNewTableColumn();
    cttc1.setId(1);
    CTTableColumn cttc2 = cttcs.addNewTableColumn();
    cttc2.setId(2);

    //Creating the cells
    XSSFCell c1 = s.createRow(0).createCell(0);
    XSSFCell c2 = s.getRow(0).createCell(1);
    XSSFCell c3 = s.createRow(1).createCell(0);
    XSSFCell c4 = s.getRow(1).createCell(1);

    //Inserting values; some numeric strings, some alphabetical strings
    c1.setCellValue(/*12*/"12"); //Numbers have to be inputted as a string
    c2.setCellValue(/*34*/"34"); //for the code to work
    c3.setCellValue("AB");
    c4.setCellValue("CD");

    //With those lines, the code would also crash
    //c1.setCellType(CellType.NUMERIC);
    //c2.setCellType(CellType.NUMERIC);

    //On write() it produces a "java.lang.IllegalStateException: Cannot get a STRING value from a NUMERIC cell"
    FileOutputStream fos = new FileOutputStream("test.xlsx");
    wb.write(fos);
    fos.flush();
    fos.close();
    wb.close();
}

Also, when not setting any CellValue for c1 and c2, you can actually set their CellType to NUMERIC and suddenly the code works again. It also works without the CTTable.

Any ideas or workarounds? Or is it a bug of POI (since it tries fetching a string value from any Cell regardless of its CellType)?

Body:
You need to use Apache POI 3.17 beta 1 or later for this to work (or a nightly build from after 20170607)

If you do, you can also make your code significantly simpler and cleaner too. As shown in the testNumericCellsInTable() unit test, your code could simplify to something like:

    Workbook wb = new XSSFWorkbook();
    Sheet s = wb.createSheet();

    // Create some cells, some numeric, some not
    Cell c1 = s.createRow(0).createCell(0);
    Cell c2 = s.getRow(0).createCell(1);
    Cell c3 = s.getRow(0).createCell(2);
    Cell c4 = s.createRow(1).createCell(0);
    Cell c5 = s.getRow(1).createCell(1);
    Cell c6 = s.getRow(1).createCell(2);
    c1.setCellValue(12);
    c2.setCellValue(34.56);
    c3.setCellValue("ABCD");
    c4.setCellValue("AB");
    c5.setCellValue("CD");
    c6.setCellValue("EF");

    // Setting up the CTTable
    Table t = s.createTable();
    t.setName("TableTest");
    t.setDisplayName("CT_Table_Test");
    t.addColumn();
    t.addColumn();
    t.addColumn();
    t.setCellReferences(new AreaReference(
            new CellReference(c1), new CellReference(c6)
    ));

(Unlike your problem code, this does a mixture of integers, floating point numbers and strings for the table headers, to show the various options)


问:
Abstract class and unique pointer
I have the following error in my code:

error: allocating an object of abstract class type 'Material'

I don't know how to handle this case.

I'm aware that std::make_unique performs an allocation, so it can't allocate the object of type Material, but I don't know how to correct it.

```<code>#include <iostream>
#include <memory>

struct Material
{
  Material() = default;
  virtual int get_color() const = 0;
};

struct Basic : public Material
{
  Basic() = default;
  virtual int get_color() const override
  {
    return 1;
  }
};

struct Mix : public Material
{
  Mix(const Material& mat1, const Material& mat2)
    : mat1_(std::make_unique<Material>(mat1))
    , mat2_(std::make_unique<Material>(mat2))
  {}

  virtual int get_color() const override
  {
    return mat1_->get_color() + mat2_->get_color();
  }
private:
  std::unique_ptr<Material> mat1_;
  std::unique_ptr<Material> mat2_;
};

int main()
{
  auto mix = Mix(Basic(), Basic());
  std::cout << mix.get_color() << '\n';
}
</code>```

答:
The problem is because Mix tries to create an object of the abstract class Material:

```<code>: mat1_(std::make_unique<Material>(mat1))
</code>```

Ideally, based on the signature

```<code>Mix(const Material& mat1, const Material& mat2)
</code>```

Mix should be able to just operate on any type of Material passed to it.

The fact that Mix is passed with abstract class reference is good. But the fact that Mix is trying to create objects of derived class is unusual. What if there were other derived classes?

I would design slightly differently such that Mix is not the owner of the constituents; they are created and owned by something outside, Mix just mixes what is passed to it.

```<code>struct Mix : public Material
{
  Mix(const Material& mat1, const Material& mat2)
    : mat1_{mat1}, mat2_{mat2}
  {}

  virtual int get_color() const override
  {
    return mat1_.get_color() + mat2_.get_color();
  }
private:
  Material const& mat1_;
  Material const& mat2_;
};

int main()
{
  std::unique_ptr<Material> mat1 = std::make_unique<Basic>();
  std::unique_ptr<Material> mat2 = std::make_unique<Basic>();

  auto mix = Mix(*(mat1.get()), *(mat2.get()));
  std::cout << mix.get_color() << '\n';
}
</code>```

Title: Abstract class and unique pointer

Body:
I have the following error in my code:

error: allocating an object of abstract class type 'Material'

I don't know how to handle this case.

I'm aware that std::make_unique performs an allocation, so it can't allocate the object of type Material, but I don't know how to correct it.

#include <iostream>
#include <memory>

struct Material
{
  Material() = default;
  virtual int get_color() const = 0;
};

struct Basic : public Material
{
  Basic() = default;
  virtual int get_color() const override
  {
    return 1;
  }
};

struct Mix : public Material
{
  Mix(const Material& mat1, const Material& mat2)
    : mat1_(std::make_unique<Material>(mat1))
    , mat2_(std::make_unique<Material>(mat2))
  {}

  virtual int get_color() const override
  {
    return mat1_->get_color() + mat2_->get_color();
  }
private:
  std::unique_ptr<Material> mat1_;
  std::unique_ptr<Material> mat2_;
};

int main()
{
  auto mix = Mix(Basic(), Basic());
  std::cout << mix.get_color() << '\n';
}

Body:
The problem is because Mix tries to create an object of the abstract class Material:

: mat1_(std::make_unique<Material>(mat1))

Ideally, based on the signature

Mix(const Material& mat1, const Material& mat2)

Mix should be able to just operate on any type of Material passed to it.

The fact that Mix is passed with abstract class reference is good. But the fact that Mix is trying to create objects of derived class is unusual. What if there were other derived classes?

I would design slightly differently such that Mix is not the owner of the constituents; they are created and owned by something outside, Mix just mixes what is passed to it.

struct Mix : public Material
{
  Mix(const Material& mat1, const Material& mat2)
    : mat1_{mat1}, mat2_{mat2}
  {}

  virtual int get_color() const override
  {
    return mat1_.get_color() + mat2_.get_color();
  }
private:
  Material const& mat1_;
  Material const& mat2_;
};

int main()
{
  std::unique_ptr<Material> mat1 = std::make_unique<Basic>();
  std::unique_ptr<Material> mat2 = std::make_unique<Basic>();

  auto mix = Mix(*(mat1.get()), *(mat2.get()));
  std::cout << mix.get_color() << '\n';
}


问:
how to convert date time to only time in c#
i want to convert datetime format to only time format.

data type - string

```<code>op- 5/31/2017 8:43:20 PM
req op - 8:43 (in 24 hours format)
</code>```

code

```<code>TankDetailsModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();
</code>```

答:
Use this code:</p>

```<code>string myDateString = "2/17/2011 6:46:01 PM";
DateTime datetime = DateTime.Parse(myDateString);
string timeString = datetime.ToShortTimeString();
Console.WriteLine(timeString);
</code>```

Body:
i want to convert datetime format to only time format.

data type - string

op- 5/31/2017 8:43:20 PM
req op - 8:43 (in 24 hours format)

code

TankDetailsModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();

Body:
Use this code:

string myDateString = "2/17/2011 6:46:01 PM";
DateTime datetime = DateTime.Parse(myDateString);
string timeString = datetime.ToShortTimeString();
Console.WriteLine(timeString);


问:
MongoDB Aggregation Limit Lookup
I am using $lookup in PyMongo to successfully "join" two collections (this works). I am having a problem where the second collection I am joining in may exceed the BSON document size when it returns all of the records.

I am looking to use $limit to limit the number of records that are allowed to join under "match_docs" eg: 100 records maximum from "comments" per obj_id:

```<code>db.indicators.aggregate([
  {
    "$lookup": {
      "from": "comments",
      "localField": "_id",
      "foreignField": "obj_id",
      "as": "match_docs"
    }
  }
])
</code>```

I've tried various types of $limit, and it seems to only limit the total number of results overall, not just for the join.

答:
If you do a $unwind immediately following a $lookup, the pipeline will be optimized, basically combining the 2 stages helping to bypass the 16MB limit that could result from the $lookup returning a large number of documents.

Keep in mind, if a single document in the foreign collection plus the size of the document in the local collection exceed 16 MB, this optimization cannot help.

Title: MongoDB Aggregation Limit Lookup

Body:
I am using $lookup in PyMongo to successfully "join" two collections (this works). I am having a problem where the second collection I am joining in may exceed the BSON document size when it returns all of the records.

I am looking to use $limit to limit the number of records that are allowed to join under "match_docs" eg: 100 records maximum from "comments" per obj_id:

db.indicators.aggregate([
  {
    "$lookup": {
      "from": "comments",
      "localField": "_id",
      "foreignField": "obj_id",
      "as": "match_docs"
    }
  }
])

I've tried various types of $limit, and it seems to only limit the total number of results overall, not just for the join.