问:
Get identity claims from bearer token (Web API)
I have two Web APIs with a shared machine.key. I would like to pass the bearer token generated by the first Web API to the second Web API as a parameter (i.e. token=xxxxxxxx) and extract the identity claims (i.e userId) from it.

Is this possible? I've looked all over but there doesn't seem to be much information on parsing a text bearer token to extract claims.

Thanks.

答:
If you're using OWIN, you could implement your own OAuthBearerAuthenticationProvider, which takes the token from the query string and sets it to the context:

```<code>internal class MyAuthProvider : OAuthBearerAuthenticationProvider
{
    public override Task RequestToken(OAuthRequestTokenContext context)
        if (context.Token == null)
        {
            var value = context.Request.Query.Get("token");
            if (!string.IsNullOrEmpty(value))
            {
                context.Token = value;
            }
        }

        return Task.FromResult<object>(null);
    }
}
</code>```

You could use it in your Startup.cs like this:

```<code>public void Configuration(IAppBuilder app)
{
    // All the other stuff here

    var audience = "";
    var secret = "...";

    app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
    {
        Provider = new MyAuthProvider(),
        AuthenticationMode = AuthenticationMode.Active,
        AllowedAudiences = new [] { audience },
        IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        {
            new SymmetricKeyIssuerSecurityTokenProvider("MyApp", TextEncodings.Base64Url.Decode(key))
        }
    });

    // All the other stuff here
}
</code>```

When you've implemented your auth like this, you can access the token information in your WebApi controller via the User.Identity property. To read custom claims, you can cast it to ClaimsIdentity.

```<code>var identity = User.Identity as ClaimsIdentity;
var myClaim = identity.Claims.FirstOrDefault(c => c.Type == "myClaimKey");
</code>```

Body:
If you're using OWIN, you could implement your own OAuthBearerAuthenticationProvider, which takes the token from the query string and sets it to the context:

internal class MyAuthProvider : OAuthBearerAuthenticationProvider
{
    public override Task RequestToken(OAuthRequestTokenContext context)
        if (context.Token == null)
        {
            var value = context.Request.Query.Get("token");
            if (!string.IsNullOrEmpty(value))
            {
                context.Token = value;
            }
        }

        return Task.FromResult<object>(null);
    }
}

You could use it in your Startup.cs like this:

public void Configuration(IAppBuilder app)
{
    // All the other stuff here

    var audience = "";
    var secret = "...";

    app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
    {
        Provider = new MyAuthProvider(),
        AuthenticationMode = AuthenticationMode.Active,
        AllowedAudiences = new [] { audience },
        IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        {
            new SymmetricKeyIssuerSecurityTokenProvider("MyApp", TextEncodings.Base64Url.Decode(key))
        }
    });

    // All the other stuff here
}

When you've implemented your auth like this, you can access the token information in your WebApi controller via the User.Identity property. To read custom claims, you can cast it to ClaimsIdentity.

var identity = User.Identity as ClaimsIdentity;
var myClaim = identity.Claims.FirstOrDefault(c => c.Type == "myClaimKey");


来源: stackexchange

问:
Should the password field be unique?
In light of the recent Gawker Media password leak, I've realized that many users share the same passwords. To help encourage stronger passwords, would it be helpful if passwords are constrained to be unique among all users?

One immediate downside I could think of (besides account creation performance?) is being able to know that someone is using a given string as a password. This knowledge, combined with a list of users, could be quite dangerous.

Is there a way to mitigate that downside while retaining the alleged benefits of not allowing repeat passwords?

It's kind of like the XKCD kick bot where you aren't allowed to repeat short, unoriginal sentences like "yah" or "lol".

Edit^2: I thought you could unique-ify against a hash, but as someone pointed out, with varying salts, this would not have the intended effect. Good eye!

答:
absolutely not.

It is critical that no information about passwords be available to users outside the system.  If they can easy guess which passwords are in use, by discovering that a password is unavailable, then they can use those passwords on known usernames and get a good shot at gaining access.

An alternative is to find some kind of common passwords database, and prevent any user from using them.

ContentLicense: CC BY-SA 2.5

Title: Should the password field be unique?


问:
Vue binding overrides element attribute
I have a component that renders a HTML input:

```<code><input
    :placeholder="placeholder"
    v-model="value"
    type="text"
    :disabled="disabled"
    :readOnly="readOnly"
    @focus="onFocus"
/>
</code>```

Note that the type is not binded/reactive.

When I put this component inside another, and bind a object to it, the type gets overrided.

```<code> <my-input v-bind="{type: 'foobar'}"></my-input>
</code>```

Is this a by design or a bug?

Example (check the input[type] in the HTML):

const Input = {
    template: '<input type="text"/>'
    //                      ^^^^ "text" gets overriden to "foobar"
}
new Vue({
    el: '#demo',
    components: {
        'my-input': Input
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://vuejs.org/js/vue.min.js"></script>
<div id="demo">
    <my-input v-bind="{type: 'foobar'}"></my-input>
</div></code>```

答:
VueJS adds the component attributes to the first child node of the component template.

Look this fiddle

http://jsfiddle.net/8hzhvrng/

The my-input has a inputroot child and then it gets the type="password"

The my-input2 has a div root child which gets the type="number"

ContentLicense: CC BY-SA 3.0

Title: Vue binding overrides element attribute

Body:
I have a component that renders a HTML input:

<input
    :placeholder="placeholder"
    v-model="value"
    type="text"
    :disabled="disabled"
    :readOnly="readOnly"
    @focus="onFocus"
/>

Note that the type is not binded/reactive.

When I put this component inside another, and bind a object to it, the type gets overrided.

 <my-input v-bind="{type: 'foobar'}"></my-input>

Is this a by design or a bug?

Example (check the input[type] in the HTML):

const Input = {
    template: '<input type="text"/>'
    //                      ^^^^ "text" gets overriden to "foobar"
}
new Vue({
    el: '#demo',
    components: {
        'my-input': Input
    }
});

    <my-input v-bind="{type: 'foobar'}"></my-input>


问:
How can I use ui:define and ui:insert within the same ui:composition?
I have a ui:composition that sits within a template, and I want to repeat an element both in template and the composition itself.

Here's an example.

template.xhtml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      xmlns:fn="http://java.sun.com/jsp/jstl/functions"
      xmlns:ui="http://java.sun.com/jsf/facelets"
       xmlns:pt="http://xmlns.jcp.org/jsf/passthrough">

    <h:head>
        <title>JSF 2.0 Hello World</title>
        <link rel="stylesheet" type="text/css" href="css/style.css"/>
    </h:head>

    <h:body>
        <div class = "header">
            <div class = "mylogo"></div>
            HEADER
            <!-- I want this content logo to be defined within module.xhtml-->
            <ui:insert name = "content-logo"></ui:insert>
        </div>

        <div class = "content">
            <ui:insert name = "content"></ui:insert>
        </div>

        <div class ="footer">
            FOOTER
        </div>
    </h:body>
</html>
</code>```

module.xhtml

```<code><!DOCTYPE html>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:o="http://omnifaces.org/ui"
                template="template.xhtml">

                 <!-- define the module content-logo here-->
                 <ui:define name ="content-logo">
                    <div class ="another-logo"> foo</div>
                </ui:define>

                <ui:define name ="content">

                    <-- we also want to display the content-logo here-->
                    <ui:insert name = "content-logo"/>
                    <div class = "foo">
                        My main content
                    </div>

                </ui:define>

</ui:composition>
</code>```

The defined content-logo will display within the template header fine - but it doesn't display in the composition body. Is there a way I can make this work without resorting to copying the HTML?

答:
You can use ui:include in your module.xhtml like this</p>

```<code><ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:o="http://omnifaces.org/ui"
                template="template.xhtml">

                <!-- define the module content-logo here-->
                <ui:define name ="content-logo">
                    <ui:include src="logo.xhtml"/>
                </ui:define>

                <ui:define name ="content">

                    <-- we also want to display the content-logo here-->
                    <ui:include src="logo.xhtml"/>
                    <div class = "foo">
                        My main content
                    </div>

                </ui:define>

</ui:composition>
</code>```

Body:
I have a ui:composition that sits within a template, and I want to repeat an element both in template and the composition itself.

Here's an example.

template.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>JSF 2.0 Hello World</title>
        <link rel="stylesheet" type="text/css" href="css/style.css"/>
    </h:head>

    <h:body>

            HEADER

            <ui:insert name = "content-logo"></ui:insert>

            <ui:insert name = "content"></ui:insert>

            FOOTER

    </h:body>

module.xhtml

<!DOCTYPE html>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:o="http://omnifaces.org/ui"
                template="template.xhtml">

                 <ui:define name ="content-logo">

 foo

                </ui:define>

                <ui:define name ="content">

                    <-- we also want to display the content-logo here-->
                    <ui:insert name = "content-logo"/>

                        My main content

                </ui:define>

</ui:composition>

The defined content-logo will display within the template header fine - but it doesn't display in the composition body. Is there a way I can make this work without resorting to copying the HTML?

Body:
You can use ui:include in your module.xhtml like this

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:o="http://omnifaces.org/ui"
                template="template.xhtml">

                <!-- define the module content-logo here-->
                <ui:define name ="content-logo">
                    <ui:include src="logo.xhtml"/>
                </ui:define>

                <ui:define name ="content">

                    <-- we also want to display the content-logo here-->
                    <ui:include src="logo.xhtml"/>
                    <div class = "foo">
                        My main content
                    </div>

                </ui:define>

</ui:composition>


问:
How to check if radio is checked in blade Laravel 5
I have two radio in my blade and i want if radio 1 checked display some step in modal popup
 else if radio 2 checked display another step in this modal event

this is my radio in view :

```<code>  <div class="row setup-content" id="step-1">
  <div class="col-xs-6 col-md-offset-3">
  <div class="col-md-12">
  <h3> Step 1</h3>
  <label><input type="radio" class="message_pri" id="web" name="web" value="Web">Web</label>
  <label><input type="radio" class="message_pri" id="mobile" name="web" value="Mobile">Mobile</label>
  <button class="btn btn-primary nextBtn btn-lg pull-right btnnext" type="button" >Next</button>
</div>
</code>```

答:
You can done this with another simply way
Just add this script to your page

```<code>        $('.message_pri').on('change',function(){
        if($('#web').is(':checked')){
            alert('web');
        }else{
            alert('mobile');
        }
    })
</code>```

Check here:-https://jsfiddle.net/Bibhudatta_sahoo/5cy19n1w/

Body:
I have two radio in my blade and i want if radio 1 checked display some step in modal popup
 else if radio 2 checked display another step in this modal event

this is my radio in view :

 Step 1

  <input type="radio" class="message_pri" id="web" name="web" value="Web">Web
  <input type="radio" class="message_pri" id="mobile" name="web" value="Mobile">Mobile
  <button class="btn btn-primary nextBtn btn-lg pull-right btnnext" type="button" >Next</button>

Body:
You can done this with another simply way
Just add this script to your page

        $('.message_pri').on('change',function(){
        if($('#web').is(':checked')){
            alert('web');
        }else{
            alert('mobile');
        }
    })

Check here:-https://jsfiddle.net/Bibhudatta_sahoo/5cy19n1w/


问:
How to skip wrapping to Try if the argument is already a Try-instance?
Suppose I have a method which wraps a block to Try:

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

Then what if arg passed is already an instance of Try[U]? I would like the wrapping method in this case just return the arg itself without wrapping. So far the only way I've come up with to do this is following:

def wrapToTry[T,U](arg: =>T):Try[U] = if(arg.isInstanceOf[Try[U]]) arg.asInstanceOf[Try[U]] else Try(arg).asInstanceOf[Try[U]]

I really don't like it and tried to figure out how to solve it.
First I tried to overload:

```<code>def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

def wrapToTry[T](arg: =>Try[T]):Try[T] = arg
</code>```

but that does not compile due to type erasure with the compilation error

```<code>Error:(10, 7) double definition:
def wrapToTry[T](arg: => T): scala.util.Try[T] at line 8 and
def wrapToTry[T](arg: => scala.util.Try[T]): scala.util.Try[T] at line 10
have same type after erasure: (arg: Function0)scala.util.Try
  def wrapToTry[T](arg: =>Try[T]):Try[T] = arg
      ^
</code>```

Ok, I got it, this is because the parameter is by-name, lesson learned.
Then my idea was to create an overloaded version of the method with evidence like in the following snippet:

```<code>object Test {
  import scala.util.Try
  import scala.util.Success

  def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

  def wrapToTry[T, U](arg: =>T)(implicit evidence: T <:< Try[U]) = arg

  def main(args:Array[String]):Unit = {
    println(wrapToTry("alex"))
    println(wrapToTry(Success("alex")))
  }

}
</code>```

But that does not compile due to ambiguity with the following compiler error:

```<code>Error:(15, 13) ambiguous reference to overloaded definition,
both method wrapToTry in object Test of type [T, U](arg: => T)(implicit evidence: <:<[T,scala.util.Try[U]])T
and  method wrapToTry in object Test of type [T](arg: => T)scala.util.Try[T]
match argument types (String) and expected result type Any
    println(wrapToTry("alex"))
            ^
</code>```

I do believe there should be an elegant way to implement this. Could you advice?

***************************************UPDATE*************************************

Per request of readers who think the problem in this question is useless here goes the context in which the problem arises.

TLDR

I have an DSL to simplify work with ScalaTest suites.
Part of this DSL implementation is:

```<code>class Test(block: => Assertion){

    def afterThat[T, U](followUp: =>T):Assertion = {
      val start = Try(block)
      val followUpAttempt:Try[U] = if(followUp.isInstanceOf[Try[U]]) followUp.asInstanceOf[Try[U]] else Try(followUp.asInstanceOf[U])
      start.flatMap(r => followUpAttempt.map(_ => r)).get
    }

  }

  object Test{
    def apply(body: => Assertion):Test = new Test(body)
    implicit def assertionToTest(a: => Assertion):Test = new Test(a)
  }
</code>```

This allows me to write tests like the following one:

```<code>"Admin" should "be able to create a new interest segment" in{
    val group = interestsGroup
    val segment = tempInterestSegment
    Test{
      Given("an existing interests segment group")
      SegmentGroupsPage.open
      SegmentGroupsPage.createNewSegmentGroup(group)
      And("admin is on Segments view")
      SegmentsPage.open
      When("he creates a new interest segment in this segment group")
      SegmentsPage.createNewSegment(segment)
      Then("this segment is shown in the list")
      SegmentsPage.isParticularSegmentShownInTheList(segment.name) shouldBe true
      And("it has correct values on its details view.")
      SegmentsPage.openSegmentDetailsView(segment.name)
      SegmentsPage.fieldsHaveCorrectValues(segment) shouldBe true
    } afterThat cleanUpTest(segment, group)
  }
</code>```

Also I can have as many afterThat at the end of each test as I want to. Each of them gets wrapped into Try so I am sure they ALL get executed and in the end I still have my original Assertion as a result.

Then I encountered a test where a follow-up block which I pass to afterThat is already a Try instance. It will work BUT I SIMPLY DONT LIKE NESTED TRY so decided to exercise if I will be able to solve this.

答:
If you insist on having 1 method name for both Try and non-Try arguments, which is understandable in case of a DSL, you can use a typeclass based trick. One variation of which you can see here:</p>

```<code>class Test(block: => Assertion){

  def afterThat[T](followUp: =>T)(implicit after: Test.AfterThat[T]): Assertion =
    after(block, followUp)

}

object Test {
  def apply(body: => Assertion): Test = new Test(body)
  implicit def assertionToTest(a: => Assertion): Test = new Test(a)

  private[Test] sealed trait AfterThat[T] {
    def apply(block: => Assertion, f: => T): Assertion
  }

  private[Test] object AfterThat extends LowerPriority {
    implicit def itsaTry[T,U](implicit ev: T <:< Try[U]) = new AfterThat[T] {
      def apply(block: => Assertion, f: => T): Assertion = {
        val start = Try(block)
        val followUp = ev(f)
        start.flatMap(r => followUp.map(_ => r)).get
      }
    }
  }

  private[Test] trait LowerPriority {
    implicit def notTry[T] = new AfterThat[T] {
      def apply(block: => Assertion, f: => T): Assertion = {
        implicitly[AfterThat[Try[T]]].apply(block, Try(f))
      }
    }
  }
}
</code>```

Body:
Suppose I have a method which wraps a block to Try:

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

Then what if arg passed is already an instance of Try[U]? I would like the wrapping method in this case just return the arg itself without wrapping. So far the only way I've come up with to do this is following:

def wrapToTry[T,U](arg: =>T):Try[U] = if(arg.isInstanceOf[Try[U]]) arg.asInstanceOf[Try[U]] else Try(arg).asInstanceOf[Try[U]]

I really don't like it and tried to figure out how to solve it.
First I tried to overload:

def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

def wrapToTry[T](arg: =>Try[T]):Try[T] = arg

but that does not compile due to type erasure with the compilation error

Error:(10, 7) double definition:
def wrapToTry[T](arg: => T): scala.util.Try[T] at line 8 and
def wrapToTry[T](arg: => scala.util.Try[T]): scala.util.Try[T] at line 10
have same type after erasure: (arg: Function0)scala.util.Try
  def wrapToTry[T](arg: =>Try[T]):Try[T] = arg
      ^

Ok, I got it, this is because the parameter is by-name, lesson learned.
Then my idea was to create an overloaded version of the method with evidence like in the following snippet:

object Test {
  import scala.util.Try
  import scala.util.Success

  def wrapToTry[T](arg: =>T):Try[T] = Try(arg)

  def wrapToTry[T, U](arg: =>T)(implicit evidence: T <:< Try[U]) = arg

  def main(args:Array[String]):Unit = {
    println(wrapToTry("alex"))
    println(wrapToTry(Success("alex")))
  }

}

But that does not compile due to ambiguity with the following compiler error:

Error:(15, 13) ambiguous reference to overloaded definition,
both method wrapToTry in object Test of type [T, U](arg: => T)(implicit evidence: <:<[T,scala.util.Try[U]])T
and  method wrapToTry in object Test of type [T](arg: => T)scala.util.Try[T]
match argument types (String) and expected result type Any
    println(wrapToTry("alex"))
            ^

I do believe there should be an elegant way to implement this. Could you advice?

***************************************UPDATE*************************************

Per request of readers who think the problem in this question is useless here goes the context in which the problem arises.

TLDR

I have an DSL to simplify work with ScalaTest suites.
Part of this DSL implementation is:

class Test(block: => Assertion){

    def afterThat[T, U](followUp: =>T):Assertion = {
      val start = Try(block)
      val followUpAttempt:Try[U] = if(followUp.isInstanceOf[Try[U]]) followUp.asInstanceOf[Try[U]] else Try(followUp.asInstanceOf[U])
      start.flatMap(r => followUpAttempt.map(_ => r)).get
    }

  }

  object Test{
    def apply(body: => Assertion):Test = new Test(body)
    implicit def assertionToTest(a: => Assertion):Test = new Test(a)
  }

This allows me to write tests like the following one:

"Admin" should "be able to create a new interest segment" in{
    val group = interestsGroup
    val segment = tempInterestSegment
    Test{
      Given("an existing interests segment group")
      SegmentGroupsPage.open
      SegmentGroupsPage.createNewSegmentGroup(group)
      And("admin is on Segments view")
      SegmentsPage.open
      When("he creates a new interest segment in this segment group")
      SegmentsPage.createNewSegment(segment)
      Then("this segment is shown in the list")
      SegmentsPage.isParticularSegmentShownInTheList(segment.name) shouldBe true
      And("it has correct values on its details view.")
      SegmentsPage.openSegmentDetailsView(segment.name)
      SegmentsPage.fieldsHaveCorrectValues(segment) shouldBe true
    } afterThat cleanUpTest(segment, group)
  }

Also I can have as many afterThat at the end of each test as I want to. Each of them gets wrapped into Try so I am sure they ALL get executed and in the end I still have my original Assertion as a result.

Then I encountered a test where a follow-up block which I pass to afterThat is already a Try instance. It will work BUT I SIMPLY DONT LIKE NESTED TRY so decided to exercise if I will be able to solve this.

Body:
If you insist on having 1 method name for both Try and non-Try arguments, which is understandable in case of a DSL, you can use a typeclass based trick. One variation of which you can see here:

class Test(block: => Assertion){

  def afterThat[T](followUp: =>T)(implicit after: Test.AfterThat[T]): Assertion =
    after(block, followUp)

}

object Test {
  def apply(body: => Assertion): Test = new Test(body)
  implicit def assertionToTest(a: => Assertion): Test = new Test(a)

  private[Test] sealed trait AfterThat[T] {
    def apply(block: => Assertion, f: => T): Assertion
  }

  private[Test] object AfterThat extends LowerPriority {
    implicit def itsaTry[T,U](implicit ev: T <:< Try[U]) = new AfterThat[T] {
      def apply(block: => Assertion, f: => T): Assertion = {
        val start = Try(block)
        val followUp = ev(f)
        start.flatMap(r => followUp.map(_ => r)).get
      }
    }
  }

  private[Test] trait LowerPriority {
    implicit def notTry[T] = new AfterThat[T] {
      def apply(block: => Assertion, f: => T): Assertion = {
        implicitly[AfterThat[Try[T]]].apply(block, Try(f))
      }
    }
  }
}


问:
Run PHP script in Wordpress
I'm a complete newbie when it comes to WordPress so please be kind. :-)

Current situation:

On my WordPress website I've made a "Contact page" with the following code.

```<code><form action="demo.php" method="post" ></form>
<p>First Name: <input type="text" name="firstname" /></p>
<p>Last Name: <input type="text" name="lastname" /></p>
<p>email: <input type="text" name="email" /></p>
<input type="submit" value="Verstuur" />
</form>
</code>```

The demo.php look like this:

```<code><?php
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$value = $_POST['firstname'];
$value2 = $_POST['lastname'];
$value3 = $_POST['email'];

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('$value', '$value2', '$value3')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
</code>```

When I run these script outside WordPress they work like a charm. The data that the user has given is nicely written into my database and I get the message that a new record was created.
But when I put the script inside WordPress nothing works anymore. Of course I get to see my form, but that's where it stops. To be honest I don't even know where to put the demo.php file. I've tried it to put in every different WordPress folder that there is but without luck.

I've looked all over the internet to find the correct solution for my issue but nearly everywhere they are using plugins. And here it comes...I don't want to use a plugin.

I know this is not a "Who do I need to do this...." platform, so my question is that I want to find out how experienced WordPress developers go about this so I can learn for the future.

Thank you very much.

答:
Check this

Please use at top of the file,

```<code>global $wpdb;
</code>```

Then,

```<code>$wpdb->query("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('$value', '$value2', '$value3')");
</code>```

In wordpress you need to use $wpdb to get the db connection and perform db queries.

Title: Run PHP script in Wordpress

Body:
I'm a complete newbie when it comes to WordPress so please be kind. :-)

Current situation:

On my WordPress website I've made a "Contact page" with the following code.

<form action="demo.php" method="post" ></form>

First Name: <input type="text" name="firstname" />

Last Name: <input type="text" name="lastname" />

email: <input type="text" name="email" />

<input type="submit" value="Verstuur" />
</form>

The demo.php look like this:

<?php
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$value = $_POST['firstname'];
$value2 = $_POST['lastname'];
$value3 = $_POST['email'];

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('$value', '$value2', '$value3')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

When I run these script outside WordPress they work like a charm. The data that the user has given is nicely written into my database and I get the message that a new record was created.
But when I put the script inside WordPress nothing works anymore. Of course I get to see my form, but that's where it stops. To be honest I don't even know where to put the demo.php file. I've tried it to put in every different WordPress folder that there is but without luck.

I've looked all over the internet to find the correct solution for my issue but nearly everywhere they are using plugins. And here it comes...I don't want to use a plugin.

I know this is not a "Who do I need to do this...." platform, so my question is that I want to find out how experienced WordPress developers go about this so I can learn for the future.

Thank you very much.

Body:
Check this

Please use at top of the file,

global $wpdb;

Then,

$wpdb->query("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('$value', '$value2', '$value3')");

In wordpress you need to use $wpdb to get the db connection and perform db queries.


问:
django cache REST API Urls issue
I have followed the solution provided in Stack overflow Link & it is working perfectly when i use this from my browser. However, when i tried hitting that url with curl, it doesn't cache for the browser..

Let me explain.

If i hit a url like example.org/results?limit=7 from my chrome, it
  takes 8-10 seconds to load & successive hits takes time in
  milliseconds

So what i did is call this URL with the curl command; but it didn't use the cached data & created the cache again.

So i found out the issue is with the arg parameter in the below code as it contains the browser headers in WSGIRequest object which is being used in caching key as it contains the headers also which i don't require for caching. This is failing my purpose of curl requests to create the cache automatically from celery task.

```<code>@method_decorator(cache_page(60 * 60 * 24))
def dispatch(self, *arg, **kwargs):
    print(arg)
    print(kwargs)
    return super(ProfileLikeHistoryApi, self).dispatch(*arg, **kwargs)
</code>```

What can i do is to pass only the kwargs to create the cache or any other alternative by which i can do cache for urls only not the headers

Thanks for the help in advance.

答:
TLDR; Remove method decorator and cache manually

```<code>from django.core.cache import cache
from django.utils.encoding import force_bytes, force_text, iri_to_uri
import hashlib

def dispatch(self, *arg, **kwargs):

    if self.request.method == 'GET' or self.request.method == 'HEAD':
        key = hashlib.md5(force_bytes(iri_to_uri(self.request.build_absolute_uri()))))
        data = cache.get(key)
        if not data:
            data = super(ProfileLikeHistoryApi, self).dispatch(*arg, **kwargs)
            cache.set(key, data, 60*60*24)
            return data

   return super(ProfileLikeHistoryApi, self).dispatch(*arg, **kwargs)
</code>```

cache_page decorator

Yes, you are right that cache page decorator will decide what to cache based on the headers. However only 'vary' headers are supposed to have an impact.

Secondly only GET and HEAD requests are cached (and cachable) so that's why in the above code we check the method first.

md5

You might have heard that is obsolete and not secure. That maybe so for cryptography, but it does not apply in our case. The hash generation scheme used here is exactly the same as used by django's _generate_cache_key but we leave out the headers from the equation.

That one guy get's a slow page

Every day there will be one guy who get's a slow page because the cache has expired. Everyone else will get stale data. Data that's as old as 23 hours and 59 minutes.

Consider running a background process or a cron that runs this tasks in the background say every 6 hours and freshens the cache.

Now that maybe a bit difficult with memcached, because it doesn't provide an easy way to find all keys with a specific pattern, but if you used redis or cached in the db, it becomes easy.

Title: django cache REST API Urls issue

Body:
I have followed the solution provided in Stack overflow Link & it is working perfectly when i use this from my browser. However, when i tried hitting that url with curl, it doesn't cache for the browser..

Let me explain.

If i hit a url like example.org/results?limit=7 from my chrome, it
  takes 8-10 seconds to load & successive hits takes time in
  milliseconds

So what i did is call this URL with the curl command; but it didn't use the cached data & created the cache again.

So i found out the issue is with the arg parameter in the below code as it contains the browser headers in WSGIRequest object which is being used in caching key as it contains the headers also which i don't require for caching. This is failing my purpose of curl requests to create the cache automatically from celery task.

@method_decorator(cache_page(60 * 60 * 24))
def dispatch(self, *arg, **kwargs):
    print(arg)
    print(kwargs)
    return super(ProfileLikeHistoryApi, self).dispatch(*arg, **kwargs)

What can i do is to pass only the kwargs to create the cache or any other alternative by which i can do cache for urls only not the headers

Thanks for the help in advance.

Body:
TLDR; Remove method decorator and cache manually

from django.core.cache import cache
from django.utils.encoding import force_bytes, force_text, iri_to_uri
import hashlib

def dispatch(self, *arg, **kwargs):

    if self.request.method == 'GET' or self.request.method == 'HEAD':
        key = hashlib.md5(force_bytes(iri_to_uri(self.request.build_absolute_uri()))))
        data = cache.get(key)
        if not data:
            data = super(ProfileLikeHistoryApi, self).dispatch(*arg, **kwargs)
            cache.set(key, data, 60*60*24)
            return data

   return super(ProfileLikeHistoryApi, self).dispatch(*arg, **kwargs)

cache_page decorator

Yes, you are right that cache page decorator will decide what to cache based on the headers. However only 'vary' headers are supposed to have an impact.

Secondly only GET and HEAD requests are cached (and cachable) so that's why in the above code we check the method first.

md5

You might have heard that is obsolete and not secure. That maybe so for cryptography, but it does not apply in our case. The hash generation scheme used here is exactly the same as used by django's _generate_cache_key but we leave out the headers from the equation.

That one guy get's a slow page

Every day there will be one guy who get's a slow page because the cache has expired. Everyone else will get stale data. Data that's as old as 23 hours and 59 minutes.

Consider running a background process or a cron that runs this tasks in the background say every 6 hours and freshens the cache.

Now that maybe a bit difficult with memcached, because it doesn't provide an easy way to find all keys with a specific pattern, but if you used redis or cached in the db, it becomes easy.


问:
Using Opencv 3.1 from CAFFE
I am trying to use OPENCV 3.1 from inside of the caffe . This is my test code

```<code>#include <caffe/caffe.hpp>
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/tracking.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#endif  // USE_OPENCV
#include<iostream>

#ifdef USE_OPENCV

int main(){
    std::cout<<"USE_OPENCV value is 1\n";
    return 0;
}
#else
int main(){
    std::cout<<"USE_OPENCV value is 0\n";
    return 0;
}
#endif
</code>```

I am compiling it using following command

```<code> g++ -I path_to_caffe/distribute/include/  test3.cpp -std=c++0x  -lboost_system
</code>```

It compiles with giving the following output while executing :

USE_OPENCV value is 0

Before compiling the caffe i make this changes in Makefile.config file:

```<code>USE_OPENCV := 1
. . .
OPENCV_VERSION := 3
. . .
USE_PKG_CONFIG := 1
</code>```

While compiling caffe, I  firstly cleand it and then compiled it using following commands:

```<code>make clean
make all -j $(($(nproc) + 1))
make test
make runtest
make pycaffe
make distribute
</code>```

It compiles without giving error , but while testing my test file it does not gives the output that i expect.

答:
All glories goes to Shai. The solution is to add -DUSE_OPENCV flag .</p>

```<code>g++ -I path_to_caffe/distribute/include/ test3.cpp -std=c++0x -lboost_system -DUSE_OPENCV
</code>```

Title: Using Opencv 3.1 from CAFFE

Body:
I am trying to use OPENCV 3.1 from inside of the caffe . This is my test code

#include <caffe/caffe.hpp>
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/tracking.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#endif  // USE_OPENCV
#include<iostream>

#ifdef USE_OPENCV

int main(){
    std::cout<<"USE_OPENCV value is 1\n";
    return 0;
}
#else
int main(){
    std::cout<<"USE_OPENCV value is 0\n";
    return 0;
}
#endif

I am compiling it using following command

 g++ -I path_to_caffe/distribute/include/  test3.cpp -std=c++0x  -lboost_system

It compiles with giving the following output while executing :

USE_OPENCV value is 0

Before compiling the caffe i make this changes in Makefile.config file:

USE_OPENCV := 1
. . .
OPENCV_VERSION := 3
. . .
USE_PKG_CONFIG := 1

While compiling caffe, I  firstly cleand it and then compiled it using following commands:

make clean
make all -j $(($(nproc) + 1))
make test
make runtest
make pycaffe
make distribute

It compiles without giving error , but while testing my test file it does not gives the output that i expect.

Body:
All glories goes to Shai. The solution is to add -DUSE_OPENCV flag .

g++ -I path_to_caffe/distribute/include/ test3.cpp -std=c++0x -lboost_system -DUSE_OPENCV


问:
Select/Option/Value on change using Classic ASP
I tried to create a select option value on change using classic ASP but it didn't work. No error but when I view, nothing pop up from second select.

I like to select student name from first select box, if it matches, then second box shows course name, and third box shows Semester.

I like to store student names and StudentID into DB.

Can anyone help?

Students table

```<code>StudentID   Firstname   Lastname
-------------------------------
01         AAA         LN1
02         BBB         LN2
03         CCC         LN3
</code>```

Class table

```<code>Course    CourseID StudentID Semester
-------------------------------------
History   C01      01        Spring
History   C01      01        Summer
Math      C02      02        Spring
Math      C02      02        Fall
</code>```

Code

```<code>            <%          Set oRs = Server.CreateObject("adodb.recordset")
                            strSQL = " SELECT StudentID, Firstname, Lastname FROM Students Where StudentID = '" & Request.ServerVariables("LOGON_Student") & "'"
                            oRs.Open strSQL, myConn
                            sName = oRs("Lastname") & ", " & oRs("Firstname")
                            if not oRs.eof then %>
                                            <select name="Students" id="selectStudent" onChange="this.form.action='default.asp';this.form.submit();">
            <option value="<%= oRs(0) %>" <% if trim(request.Form("Students")) = trim(oRs(0)) then response.write " selected "end if %>><%= sName %></option>
            <option value="<%= oRs("StudentID") %>" hidden></option>
                                            </select>
                            <%          end if
            %>
             <%          if request.Form("Students") <> "" then
                            strSQL = " SELECT Course FROM Class WHERE StudentID = '" & request.Form("StudentID") & "'"
                            Set oRs = Server.CreateObject("adodb.RecordSet")
                            oRs.Open strSQL, myConn
                            if not oRs.eof then %>
                                            <select name="Class" id="selectClass" onChange="this.form.action='default.asp';this.form.submit();">
                                                            <% do until oRs.eof  %>
                                                                            <option value="<%= oRs(0) %>" <% if trim(request.Form("Class")) = trim(oRs(0)) then response.write " selected "end if %>><%= oRs(0) %></option>
                                                            <% oRs.MoveNext
                                                                            loop       %>
                                            </select>
                            <% end if
                            end if
            %>
            <%          if request.Form("Class") <> "" then
                            strSQL = " SELECT Semester FROM Class WHERE Course = '" & request.Form("Course") & "'"
                            Set oRs = Server.CreateObject("adodb.RecordSet")
                            oRs.Open strSQL, myConn
                            if not oRs.eof then %>
                                            <select name="Class" id="selectClass" onChange="this.form.action='default.asp';this.form.submit();">
                                                            <% do until oRs.eof  %>
                                                                            <option value="<%= oRs(0) %>" <% if trim(request.Form("Class")) = trim(oRs(0)) then response.write " selected "end if %>><%= oRs(0) %></option>
                                                            <% oRs.MoveNext
                                                                            loop       %>
                                            </select>
                            <% end if
                            end if
            %>
</code>```

答:
You are using wrong value in your SQL statement.

You should use the name of the first drop down element, not the name of the database field.

Also, you really better use parameters, not inject the value directly, as this can let the user take control of your database and possibly whole server. (To learn more, read about SQL Injection attacks.)

So, correct SQL would be:

```<code>strSQL = "SELECT Course FROM Class WHERE StudentID = ?"
Set oCommand = Server.Createobject("ADODB.Command")
Set oCommand.ActiveConnection = myConn
oCommand.CommandText = strSQL
oCommand.Parameters.Append(oCommand.CreateParameter("StudentID", 3, , , Request.Form("Students")) )
Set oRS = oCommand.Execute
</code>```

Make sure to remove the line oRs.Open strSQL, myConn from your code when having this.

As you see, I changed Request.Form("StudentID") to Request.Form("Students"), and now the query should return results.

Body:
I tried to create a select option value on change using classic ASP but it didn't work. No error but when I view, nothing pop up from second select.

I like to select student name from first select box, if it matches, then second box shows course name, and third box shows Semester.

I like to store student names and StudentID into DB.

Can anyone help?

Students table

StudentID   Firstname   Lastname
-------------------------------
01         AAA         LN1
02         BBB         LN2
03         CCC         LN3

Class table

Course    CourseID StudentID Semester
-------------------------------------
History   C01      01        Spring
History   C01      01        Summer
Math      C02      02        Spring
Math      C02      02        Fall

Code

            <%          Set oRs = Server.CreateObject("adodb.recordset")
                            strSQL = " SELECT StudentID, Firstname, Lastname FROM Students Where StudentID = '" & Request.ServerVariables("LOGON_Student") & "'"
                            oRs.Open strSQL, myConn
                            sName = oRs("Lastname") & ", " & oRs("Firstname")
                            if not oRs.eof then %>
                                            <select name="Students" id="selectStudent" onChange="this.form.action='default.asp';this.form.submit();">
            <option value="<%= oRs(0) %>" <% if trim(request.Form("Students")) = trim(oRs(0)) then response.write " selected "end if %>><%= sName %></option>
            <option value="<%= oRs("StudentID") %>" hidden></option>
                                            </select>
                            <%          end if
            %>
             <%          if request.Form("Students") <> "" then
                            strSQL = " SELECT Course FROM Class WHERE StudentID = '" & request.Form("StudentID") & "'"
                            Set oRs = Server.CreateObject("adodb.RecordSet")
                            oRs.Open strSQL, myConn
                            if not oRs.eof then %>
                                            <select name="Class" id="selectClass" onChange="this.form.action='default.asp';this.form.submit();">
                                                            <% do until oRs.eof  %>
                                                                            <option value="<%= oRs(0) %>" <% if trim(request.Form("Class")) = trim(oRs(0)) then response.write " selected "end if %>><%= oRs(0) %></option>
                                                            <% oRs.MoveNext
                                                                            loop       %>
                                            </select>
                            <% end if
                            end if
            %>
            <%          if request.Form("Class") <> "" then
                            strSQL = " SELECT Semester FROM Class WHERE Course = '" & request.Form("Course") & "'"
                            Set oRs = Server.CreateObject("adodb.RecordSet")
                            oRs.Open strSQL, myConn
                            if not oRs.eof then %>
                                            <select name="Class" id="selectClass" onChange="this.form.action='default.asp';this.form.submit();">
                                                            <% do until oRs.eof  %>
                                                                            <option value="<%= oRs(0) %>" <% if trim(request.Form("Class")) = trim(oRs(0)) then response.write " selected "end if %>><%= oRs(0) %></option>
                                                            <% oRs.MoveNext
                                                                            loop       %>
                                            </select>
                            <% end if
                            end if
            %>

Body:
You are using wrong value in your SQL statement.

You should use the name of the first drop down element, not the name of the database field.

Also, you really better use parameters, not inject the value directly, as this can let the user take control of your database and possibly whole server. (To learn more, read about SQL Injection attacks.)

So, correct SQL would be:

strSQL = "SELECT Course FROM Class WHERE StudentID = ?"
Set oCommand = Server.Createobject("ADODB.Command")
Set oCommand.ActiveConnection = myConn
oCommand.CommandText = strSQL
oCommand.Parameters.Append(oCommand.CreateParameter("StudentID", 3, , , Request.Form("Students")) )
Set oRS = oCommand.Execute

Make sure to remove the line oRs.Open strSQL, myConn from your code when having this.

As you see, I changed Request.Form("StudentID") to Request.Form("Students"), and now the query should return results.


问:
Control img's border perimeter by time countdown - from full circle, through partial arc, to nothing
I use html, css, angularjs in the front.
I've got an img which in the initial state is surrounded with a full circle of a thick border. I start a countdown of a minute. I would like the border to get partially disappeared as the time goes down.

For example, after the first second only 59/60 of the perimeter of the border is shown, after the second one only 58/60 is shown, ..., after 30 seconds there's only a half of a circle and so on, until it gets totally disappeared.

In addition, if it's possible, I would like the transitions to be smooth.

Thanks for any help

答:
You have to use a combination of ng-class for conditionnal CSS on your case AND css transition.

See for example this example of a smooth transition that is for a 5s for an element to be half visible

```<code>#myTransition {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;
}
</code>```

Body:
You have to use a combination of ng-class for conditionnal CSS on your case AND css transition.

See for example this example of a smooth transition that is for a 5s for an element to be half visible

#myTransition {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;
}


问:
php update button only update last record
this is my first PHP program and I'm kind of stuck in update button code I think the problem is with the Driver_ID I tried many different things but nothing works for me. my problem is how can I get the Driver_ID to make the button work?
in this code below I only get the last row id. If someone can help me I would really appreciate it.

```<code><?php
include("dbconnection.php");

//Fetch the data from tables
$query="SELECT * FROM drivers JOIN users ON users.User_ID = drivers.User_ID";
$result = mysqli_query($connect,$query);
            while($row = mysqli_fetch_array($result))
  {
       echo "<tr>
    <td>".$row['Driver_ID']."</td>
    <td>" . $row['Driver_Name'] . "</td>
    <td>" . $row['User_Name'] . "</td>

            <td><p data-placement='top' data-toggle='tooltip' title='Edit'><button class='btn btn-primary btn-xs' data-title='Edit' data-toggle='modal' data-target='#edit'value='".$row['Driver_ID']."' name='editr'><span class='glyphicon glyphicon-pencil'></span></button></p></td>

              <td><p data-placement='top' data-toggle='tooltip' title='Delete'><button class='btn  btn-danger btn-xs' data-title='Delete' data-toggle='modal' data-target='#delete'><span class='glyphicon glyphicon-trash'></span></button></p></td>
               </tr>";

  $id=$row['Driver_ID'];
            }

mysqli_close($connect);
?>
</code>```

The html code for the hidden control

```<code>  <input class="form-control " type="hidden" value="<?php echo  $id ?>"  name="driverid"  >
</code>```

the code for the update button

```<code> <?php

require("dbconnection.php");

if(isset($_POST['update']))
    // include Database connection file
                {
    $driver_id=$_POST['driverid'];
$driver_name = $_POST['txtname'];

    $user_id = $_POST['UserN'];

 $sql = "UPDATE drivers

                  SET Driver_Name='$driver_name',User_ID='$user_id'
                  WHERE Driver_ID='$driver_id'";

if (mysqli_query($connect, $sql)) {
echo "Record updated successfully";
header('Refresh:5 ; url=drivers.php');
}
 else {
echo "Error updating record: " . mysqli_error($connect);
}
}

    mysqli_close($connect);
?>
</code>```

答:
Use input like this:
As you need all results you need to store them all

your main while loop could be like

```<code>    $r=null;
    while(){
    $r++;

   echo '<input class="form-control " type="hidden" value="<?php echo  $id ?>"  name="driverid[]"  >'

    }
    echo '<input type="hidden" value='".$r."' name="records">';
</code>```

After that just use some loop to see all results
and then in update /insert

```<code>$records=htmlentities($_POST['records'], ENT_QUOTES, "UTF-8");
$i=0;
while ($i <= $records){
$driverid=htmlentities($_POST['driverid'][], ENT_QUOTES, "UTF-8");

//your update/insert query here
$i++;
}
</code>```

i hope this helps

Body:
this is my first PHP program and I'm kind of stuck in update button code I think the problem is with the Driver_ID I tried many different things but nothing works for me. my problem is how can I get the Driver_ID to make the button work?
in this code below I only get the last row id. If someone can help me I would really appreciate it.

<?php
include("dbconnection.php");

//Fetch the data from tables
$query="SELECT * FROM drivers JOIN users ON users.User_ID = drivers.User_ID";
$result = mysqli_query($connect,$query);
            while($row = mysqli_fetch_array($result))
  {
       echo "

    ".$row['Driver_ID']."
    " . $row['Driver_Name'] . "
    " . $row['User_Name'] . "

<button class='btn btn-primary btn-xs' data-title='Edit' data-toggle='modal' data-target='#edit'value='".$row['Driver_ID']."' name='editr'></button>

<button class='btn  btn-danger btn-xs' data-title='Delete' data-toggle='modal' data-target='#delete'></button>

";

  $id=$row['Driver_ID'];
            }

mysqli_close($connect);
?>

The html code for the hidden control

  <input class="form-control " type="hidden" value="<?php echo  $id ?>"  name="driverid"  >

the code for the update button

 <?php

require("dbconnection.php");

if(isset($_POST['update']))
    // include Database connection file
                {
    $driver_id=$_POST['driverid'];
$driver_name = $_POST['txtname'];

    $user_id = $_POST['UserN'];

 $sql = "UPDATE drivers

                  SET Driver_Name='$driver_name',User_ID='$user_id'
                  WHERE Driver_ID='$driver_id'";

if (mysqli_query($connect, $sql)) {
echo "Record updated successfully";
header('Refresh:5 ; url=drivers.php');
}
 else {
echo "Error updating record: " . mysqli_error($connect);
}
}

    mysqli_close($connect);
?>

Body:
Use input like this:
As you need all results you need to store them all

your main while loop could be like

    $r=null;
    while(){
    $r++;

   echo '<input class="form-control " type="hidden" value="<?php echo  $id ?>"  name="driverid[]"  >'

    }
    echo '<input type="hidden" value='".$r."' name="records">';

After that just use some loop to see all results
and then in update /insert

$records=htmlentities($_POST['records'], ENT_QUOTES, "UTF-8");
$i=0;
while ($i <= $records){
$driverid=htmlentities($_POST['driverid'][], ENT_QUOTES, "UTF-8");

//your update/insert query here
$i++;
}

i hope this helps


问:
Defensive copy of a mutable collection in Kotlin data class
I want to have a data class accepting a read-only list:

```<code>data class Notebook(val notes: List<String>) {
}
</code>```

But it can accept MutableList as well, because it is a subtype of the List.

For example the following code modifies the passed in list:

```<code>fun main(args: Array<String>) {
    val notes = arrayListOf("One", "Two")
    val notebook = Notebook(notes)

    notes.add("Three")

    println(notebook)       // prints: Notebook(notes=[One, Two, Three])
}
</code>```

Is there a way how perform defensive copy of the passed in list in the data class?

答:
Option 1

You can use .toList() to make a copy, although you will need another property internally that holds the list copy or you need to move away from a data class to a normal class.

As a data class:

```<code>data class Notebook(private val _notes: List<String>) {
    val notes: List<String> = _notes.toList()
}
</code>```

The problem here is that your data class is going to have .equals() and .hashCode() based on a potentially mutating list.

So the alternative is to use a normal class:

```<code>class Notebook(notes: List<String>) {
    val notes: List<String> = notes.toList()
}
</code>```

Option 2

Kotlin team is working on truly immutable collections as well, you might be able to preview them if they are stable enough for use:  https://github.com/Kotlin/kotlinx.collections.immutable

Option 3

Another way would be to create an interface that does allow the descendant type of MutableList to be used.  This is exactly what the Klutter library does by creating a hierarchy of light-weight delegating classes that can wrap lists to ensure no mutation is possible.  Since they use delegation they have little overhead.  You can use this library, or just look at the source code as an example of how to create this type of protected collections.  Then you change your method to ask for this protected version instead of the original.  See the source code for Klutter ReadOnly Collection Wrappers and associated tests for ideas.

As an example of using these classes from Klutter, the data class would be:

```<code>data class Notebook(val notes: ReadOnlyList<String>) {
</code>```

And the caller would be forced to comply by passing in a wrapped list which is pretty simple:

```<code>val myList = mutableListOf("day", "night")
Notebook(myList.toImmutable())  // copy and protect
</code>```

What is happening is that the caller (by invoking asReadOnly()) is making the defensive copy to satisfy the requirements of your method, and there is no way to then mutate the protected copy because of how these classes are designed.

One flaw in the Klutter implementation is that it does not have a separate hierarchy for ReadOnly vs. Immutable so if the caller instead calls asReadOnly() the holder of the list can still cause mutation.  So in your version of this code (or an update to Klutter) it would be best to make sure all of your factory methods always make a copy and never allow these classes to be constructed in any other way (i.e. make constructors internal).  Or have a second hierarchy that is used when the copy has clearly been made.  The simplest way is to copy the code to your own library, remove the asReadOnly() methods leaving only toImmutable() and make the collection class constructors all internal.

Further information

see also: Kotlin and Immutable Collections?

Body:
I want to have a data class accepting a read-only list:

data class Notebook(val notes: List<String>) {
}

But it can accept MutableList as well, because it is a subtype of the List.

For example the following code modifies the passed in list:

fun main(args: Array<String>) {
    val notes = arrayListOf("One", "Two")
    val notebook = Notebook(notes)

    notes.add("Three")

    println(notebook)       // prints: Notebook(notes=[One, Two, Three])
}

Is there a way how perform defensive copy of the passed in list in the data class?

Body:
Option 1

You can use .toList() to make a copy, although you will need another property internally that holds the list copy or you need to move away from a data class to a normal class.

As a data class:

data class Notebook(private val _notes: List<String>) {
    val notes: List<String> = _notes.toList()
}

The problem here is that your data class is going to have .equals() and .hashCode() based on a potentially mutating list.

So the alternative is to use a normal class:

class Notebook(notes: List<String>) {
    val notes: List<String> = notes.toList()
}

Option 2

Kotlin team is working on truly immutable collections as well, you might be able to preview them if they are stable enough for use:  https://github.com/Kotlin/kotlinx.collections.immutable

Option 3

Another way would be to create an interface that does allow the descendant type of MutableList to be used.  This is exactly what the Klutter library does by creating a hierarchy of light-weight delegating classes that can wrap lists to ensure no mutation is possible.  Since they use delegation they have little overhead.  You can use this library, or just look at the source code as an example of how to create this type of protected collections.  Then you change your method to ask for this protected version instead of the original.  See the source code for Klutter ReadOnly Collection Wrappers and associated tests for ideas.

As an example of using these classes from Klutter, the data class would be:

data class Notebook(val notes: ReadOnlyList<String>) {

And the caller would be forced to comply by passing in a wrapped list which is pretty simple:

val myList = mutableListOf("day", "night")
Notebook(myList.toImmutable())  // copy and protect

What is happening is that the caller (by invoking asReadOnly()) is making the defensive copy to satisfy the requirements of your method, and there is no way to then mutate the protected copy because of how these classes are designed.

One flaw in the Klutter implementation is that it does not have a separate hierarchy for ReadOnly vs. Immutable so if the caller instead calls asReadOnly() the holder of the list can still cause mutation.  So in your version of this code (or an update to Klutter) it would be best to make sure all of your factory methods always make a copy and never allow these classes to be constructed in any other way (i.e. make constructors internal).  Or have a second hierarchy that is used when the copy has clearly been made.  The simplest way is to copy the code to your own library, remove the asReadOnly() methods leaving only toImmutable() and make the collection class constructors all internal.

Further information

see also: Kotlin and Immutable Collections?


问:
c# override ToString() method in variable
Using this example code:

```<code>public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

Product p = new Product();
p.active = true;
</code>```

How can I override the ToString() method so I can use this:

```<code>MessageBox.Show(p.active.ToString());
</code>```

答:
For what it's worth, you could use an extension method:

```<code>public static string toString(this bool b)
{
    return b ? "Si" : "No";
}

MessageBox.Show(p.active.toString());
</code>```

That works because of your typo, toString instead of ToString.

You can't change the return value of a method without changing it. Boolean.ToString returns either "True" or "False" and nothing can change that (apart from Microsoft).

But of course you could also write:

```<code>MessageBox.Show(p.active ? "Si" : "No");
</code>```

Body:
Using this example code:

public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

Product p = new Product();
p.active = true;

How can I override the ToString() method so I can use this:

MessageBox.Show(p.active.ToString());

Body:
For what it's worth, you could use an extension method:

public static string toString(this bool b)
{
    return b ? "Si" : "No";
}

MessageBox.Show(p.active.toString());

That works because of your typo, toString instead of ToString.

You can't change the return value of a method without changing it. Boolean.ToString returns either "True" or "False" and nothing can change that (apart from Microsoft).

But of course you could also write:

MessageBox.Show(p.active ? "Si" : "No");


问:
how to get "address of entry point" from exe file in visual c++?
I am writing a C++ application in Visual Studio 2008, and need to get the Address of Entry Point by reading en executable file. How can I get this?</p>

答:
With the help of IMAGE_NT_HEADERS you can access entry of point of any executable.

```<code>typedef struct _IMAGE_NT_HEADERS {
  DWORD                 Signature;
  IMAGE_FILE_HEADER     FileHeader;
  IMAGE_OPTIONAL_HEADER OptionalHeader;
} IMAGE_NT_HEADERS, *PIMAGE_NT_HEADERS;
</code>```

From above structure IMAGE_OPTIONAL_HEADER having AddressOfEntryPoint member variable to access address of entry point.

Following small code will help you more:

```<code>FILE *executable;
executable= fopen("YourExe.exe","rb");

IMAGE_NT_HEADERS executableInformation;
fread(&executableInformation,sizeof(executableInformation),1,executable);
</code>```

Note : code is not tested and may have errors.

Body:
With the help of IMAGE_NT_HEADERS you can access entry of point of any executable.

typedef struct _IMAGE_NT_HEADERS {
  DWORD                 Signature;
  IMAGE_FILE_HEADER     FileHeader;
  IMAGE_OPTIONAL_HEADER OptionalHeader;
} IMAGE_NT_HEADERS, *PIMAGE_NT_HEADERS;

From above structure IMAGE_OPTIONAL_HEADER having AddressOfEntryPoint member variable to access address of entry point.

Following small code will help you more:

FILE *executable;
executable= fopen("YourExe.exe","rb");

IMAGE_NT_HEADERS executableInformation;
fread(&executableInformation,sizeof(executableInformation),1,executable);

Note : code is not tested and may have errors.


问:
How exactly works the Angular 2 property binding? What really happens in this example?
I am an absolute beginner with Angular 2 and I have the following doubt relate property binding.

This example works but I have doubt about what exactly happen under the hood.

I have a component view (the servers.component.html file) containing this button:

```<code><button [disabled]="!allowNewServer" class="btn btn-primary">Add Server</button>
</code>```

The related component is:

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

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
  allowNewServer = false;

  constructor() {
    setTimeout(() => {
      this.allowNewServer = true;
    }, 8000);
  }

  ngOnInit() {
  }

}
</code>```

As you can see at the beginning the allowNewServer value is false, after 8 seconds it is setted to true by a function declared in the constructor.

On my button is setted this disabled attribute:

```<code> [disabled]="!allowNewServer"
</code>```

So at the beginning the button is disabled and after 8 seconds it will enabled.

Mu doubts are:

1) What exactly means the [...] Angular syntax?

2) I expected that was rendered something like disabled=true (at the beginning) and after 8 seconds something like disabled=dalse, but after 8 seconds simply the disable attribute is deleted. So I think that I am not understending what the [...] syntax mean.

答:
To answer your question

What exactly means the [...] Angular syntax?

The above syntax is for data binding. As the official docs say.

Write a template property binding to set a property of a view element. The binding sets the property to the value of a template expression.An element property between enclosing square brackets identifies the target property

To answer you second question

I expected that was rendered something like disabled=true (at the beginning) and after 8 seconds something like disabled=false, but after 8 seconds simply the disable attribute is deleted. So I think that I am not understending what the [...] syntax mean.

[disabled]="!allowNewServer"

this line of cod will be do is that it will set the disabled attribute to true or false based on allowNewServer. But disabled is a Boolean attribute i.e means just the presence of the attribute means its set to true and absence means it false. Official Docs say

A number of attributes are boolean attributes. The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

So when the value is set to false which is not considered as a valid value angular removes the attribute as its considered that absence means false. Hence the behavior.

For Reference:

Boolean Attributes

Property binding

Hope it helps :)

Body:
I am an absolute beginner with Angular 2 and I have the following doubt relate property binding.

This example works but I have doubt about what exactly happen under the hood.

I have a component view (the servers.component.html file) containing this button:

<button [disabled]="!allowNewServer" class="btn btn-primary">Add Server</button>

The related component is:

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

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
  allowNewServer = false;

  constructor() {
    setTimeout(() => {
      this.allowNewServer = true;
    }, 8000);
  }

  ngOnInit() {
  }

}

As you can see at the beginning the allowNewServer value is false, after 8 seconds it is setted to true by a function declared in the constructor.

On my button is setted this disabled attribute:

 [disabled]="!allowNewServer"

So at the beginning the button is disabled and after 8 seconds it will enabled.

Mu doubts are:

1) What exactly means the [...] Angular syntax?

2) I expected that was rendered something like disabled=true (at the beginning) and after 8 seconds something like disabled=dalse, but after 8 seconds simply the disable attribute is deleted. So I think that I am not understending what the [...] syntax mean.


问:
How to autosize User control when it's shown
I have a Winforms project with a bunch of User controls.  I'd like the user control to move itself to be at the 1,1 position relative to its container (whether it's a form or a Panel control).  And resize itself to be able to fit half the container.

What event can I respond to in the UserControl to be able to do this without any code having to be written in the container (e.g. the form or panel).

答:
You could use the basic Load event.

The code could be like this:

```<code>private void UserControl1_Load(object sender, EventArgs e)
{
    Control parent = this.Parent;
    if (parent != null)
    {
        this.Location = new Point(1, 1);
        this.Width = (parent.Width / 2);
        this.Height = (parent.Height / 2);
    }
}
</code>```

OwnerDisplayName: AngryHacker

LastEditorDisplayName: Joel Coehoorn

Body:
You could use the basic Load event.

The code could be like this:

private void UserControl1_Load(object sender, EventArgs e)
{
    Control parent = this.Parent;
    if (parent != null)
    {
        this.Location = new Point(1, 1);
        this.Width = (parent.Width / 2);
        this.Height = (parent.Height / 2);
    }
}

OwnerDisplayName: mapache


问:
Sockets vs web service .NET (file updater)
I'm going to make a program (c# .NET) that downloads files from a server (basically a file updater) and I'll have around 1,000 clients downloading files ( from 1 to 10 each client) this files are small ( from 100k to 2.5 MB). So what kind of communication would you recommend? sockets? web service? WSE 3 MTOM? or prob another suggestion? thanks</p>

答:
Any reason not to just download the files from a web server, using the built-in WebClient class?  On the server-side, depending on what you needed, you could either throw the files out statically onto the file system, or use an ASHX handler to "create" them dynamically.

Steer well away from native sockets.  You can do it, and it's fast, but all you'll end up doing is reinventing the wheel.  IIS or Apache will give you fundamentally identical performance as raw sockets, for the tiniest fraction of the investment in time and resources.


问:
Outlook Mail Rest API message id repeating for different mails?
I am using outlook rest api to interact with my emails. I am storing my emails in a SQL database. The message response object has a filed called ID which according to the documentation is "The unique identifier of the message.". But I can see this id is same for multiple emails.

What is the exact behaviour of Id field??

答: You need to make sure you're comparing them in a case-sensitive manner. They do not repeat.</p>