问:
The CSRF token is invalid. Please try to resubmit the form
I'm getting this error message every time I try to submit the form:

The CSRF token is invalid. Please try to resubmit the form

My form code is this:

```<code><form novalidate action="{{path('signup_index')}}" method="post" {{form_enctype(form)}} role="form" class="form-horizontal">
    <div class="form-group">
        {{ form_label(form.email, 'Email', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.email, {'attr': {'class': 'col-md-2'}}) }}
        {{ form_errors(form.email) }}
    </div>

    <div class="form-group">
        {{ form_label(form.nickname, 'Nickname', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.nickname, {'attr':{'class': 'col-md-2'}}) }}
        {{ form_errors(form.nickname, {'attr': {'class': 'col-md-3'}}) }}
    </div>
    <div class="form-group">
        {{ form_label(form.password, 'password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.password, {'attr': {'class': 'col-md-2'}}) }}
        {{ form_errors(form.password, {'attr': {'class': 'col-md-3'}}) }}
    </div>

    <div class="form-group">
        {{ form_label(form.password_repeat, 'Repeat password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.password_repeat, {'attr':{'class': 'col-md-2'}}) }}
        {{ form_errors(form.password_repeat, {'attr': {'class': 'col-md-3'}}) }}
    </div>
    <div class="form-group">
        <div class="col-md-1 control-label">
        <input type="submit" value="submit">
    </div>

    </div>
</form>
</code>```

Any ideas?

答:
I had this issue with a weird behavior: clearing the browser cache didn't fix it but clearing the cookies (that is, the PHP session ID cookie) did solve the issue.

This has to be done after you have checked all other answers, including verifying you do have the token in a hidden form input field.

Body:
I'm getting this error message every time I try to submit the form:

The CSRF token is invalid. Please try to resubmit the form

My form code is this:

<form novalidate action="{{path('signup_index')}}" method="post" {{form_enctype(form)}} role="form" class="form-horizontal">

        {{ form_label(form.email, 'Email', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.email, {'attr': {'class': 'col-md-2'}}) }}
        {{ form_errors(form.email) }}

        {{ form_label(form.nickname, 'Nickname', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.nickname, {'attr':{'class': 'col-md-2'}}) }}
        {{ form_errors(form.nickname, {'attr': {'class': 'col-md-3'}}) }}

        {{ form_label(form.password, 'password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.password, {'attr': {'class': 'col-md-2'}}) }}
        {{ form_errors(form.password, {'attr': {'class': 'col-md-3'}}) }}

        {{ form_label(form.password_repeat, 'Repeat password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
        {{ form_widget(form.password_repeat, {'attr':{'class': 'col-md-2'}}) }}
        {{ form_errors(form.password_repeat, {'attr': {'class': 'col-md-3'}}) }}

        <input type="submit" value="submit">

</form>

Any ideas?


来源: stackexchange

问:
How in Yii 2 access AR object as component?
Actually, I want have access to some AR object in anywere.
So I want access to this ojb as yii component.

Like as Yii using this for user: Yii::$app->user->identity - User component contains User AR object.

I want store my Page AR in component. So, it's look like something: Yii::$app->page->page - Page AR is a propery of Page component. Not very nice :(. This is the only way?

答:
In config you can set it. Like user is set and adapt it to your requirements.

```<code>$config = [
    ...
    'components'=>[
        ....
        'user' => [
            'class'=>'yii\web\User',
            'identityClass' => 'common\models\User',
            ...
        ],
        ...
    ],
...
];
</code>```

Read more in yii2 documentation on this link

ContentLicense: CC BY-SA 3.0

Body:
In config you can set it. Like user is set and adapt it to your requirements.

$config = [
    ...
    'components'=>[
        ....
        'user' => [
            'class'=>'yii\web\User',
            'identityClass' => 'common\models\User',
            ...
        ],
        ...
    ],
...
];

Read more in yii2 documentation on this link


问:
Deploying node js and php on heroku
So basically i'm trying to deploy an app that has node js and php in it.
My node js file is not used to run the server, i'm using node js only for socket.io and mysql npm.
My app is working fine when i run it in xampp but when i deployed my app to heroku it is saying "Connection failed: No such file or directory"</p>

答:
So basically i'm trying to deploy an app that has node js and php in it.

So you're deploying two apps then.

You should deploy the Node app as explained here:

https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction

You should deploy the Node app as explained here:

https://devcenter.heroku.com/articles/getting-started-with-php#introduction

Your apps will most  likely need to communicate witch each other, in which case you will need to configure environment variables accordingly. It is possible that your apps do not need to communicate with each other directly, but e.g. use a common database or a queue service etc. You will need to configure both of those to use such a service if needed.

It's hard to provide any more details because you didn't explain anything about what they do, not to even mention any source code examples.

Title: Deploying node js and php on heroku


问:
"Add JUnit library" in Eclipes does not have "Junit 5" option
Can anyone help me to add Junit 5 in eclipse? When I create java project and add junit library it only shows Junit3 and junit4. I did not find junit5 and do not know how to set up things so that I can use Junit5 in project. I also gone through this guide, but did not understand where to setup these codes in eclipse.

Can anyone help me step by step how to implement Junit5 Test in eclipse-neon?

答: Take a look here (it provides an example of using JUnit 5 M3 on Eclipse 4.7 M6).</p>

ContentLicense: CC BY-SA 4.0


问:
How to put gap for toggle image and hint text in Edittext android?
I am new for android. i want space gap between toggle image and hint text same field of edit text

.

This is my edit text xml code

```<code>     <EditText
            android:id="@+id/nation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/email"
            android:layout_centerHorizontal="true"
            android:drawableLeft="@drawable/ic_flag"
            android:layout_marginTop="11dp"
            android:inputType="textCapWords"
            android:hint="Nationality"/>
</code>```

答:
use the drawablePadding property.</p>

```<code><EditText
android:drawablePadding="10dp"
android:id="@+id/nation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/email"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:drawableLeft="@drawable/ic_flag"
android:hint="Nationality"
android:inputType="textCapWords" />
</code>```

Body:
I am new for android. i want space gap between toggle image and hint text same field of edit text

.

This is my edit text xml code

     <EditText
            android:id="@+id/nation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/email"
            android:layout_centerHorizontal="true"
            android:drawableLeft="@drawable/ic_flag"
            android:layout_marginTop="11dp"
            android:inputType="textCapWords"
            android:hint="Nationality"/>

Body:
use the drawablePadding property.

<EditText
android:drawablePadding="10dp"
android:id="@+id/nation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/email"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:drawableLeft="@drawable/ic_flag"
android:hint="Nationality"
android:inputType="textCapWords" />


问:
is there any reasonable number of subviews?
I want to create something similiar to EMD Periodic Table application. I'm wondering how they did this animation when first creen appears. There is over 50 rectangles and they appear with animation. Does it make sense to add 50 subviews and manage them separately? Is it proper way to achieve this effect?

itunes.apple.com/us/app/emd-pte/id377393859?mt=8

--
Piotr

答: They could be Core Animation layers rather than full-on views.</p>

ContentLicense: CC BY-SA 2.5


问:
Trouble formatting json objects with lodash _.groupBy
I'm having trouble reformatting an object in order to group by lists.

```<code>// input
{
    'M': [
        {name: Bob, id: 1},
        {name: John, id: 2},
        {name: John, id: 3},
    ],
    'F': [
        {name: Liz, id: 4},
        {name: Mary, id: 5},
        {name: Mary, id: 6},
    ]
}

// desired output
{
    'M': [
        'Bob': [ {name: Bob, id: 1},]
        'John': [ {name: John, id: 2}, {name: John, id: 3} ]
    ],
    'F': [
        'Liz': [ {name: Liz, id: 4} ]
        'Mary': [ {name: Mary, id: 5}, {name: Mary, id: 6} ]
    ]
}
</code>```

My current script is only returning the 'M' key and I'm not what is causing it

```<code>for (var key in obj) {
    var data = _.groupBy(obj[key], 'name')
    return data;
}
</code>```

I've also tried

```<code>  Object.keys(obj).forEach(obj, key => {
    var data = _.groupBy(obj[key], 'name')
    return data;
  })
</code>```

but it throws TypeError: #<Object> is not a function

答:
Use _.forOwn since you want to iterate its own properties.</p>

```<code>_.forOwn(obj, function(key, val) {
    var ret = {};
    ret[key] = _.groupBy(val, 'name');
    return ret;
});
</code>```

Body:
I'm having trouble reformatting an object in order to group by lists.

// input
{
    'M': [
        {name: Bob, id: 1},
        {name: John, id: 2},
        {name: John, id: 3},
    ],
    'F': [
        {name: Liz, id: 4},
        {name: Mary, id: 5},
        {name: Mary, id: 6},
    ]
}

// desired output
{
    'M': [
        'Bob': [ {name: Bob, id: 1},]
        'John': [ {name: John, id: 2}, {name: John, id: 3} ]
    ],
    'F': [
        'Liz': [ {name: Liz, id: 4} ]
        'Mary': [ {name: Mary, id: 5}, {name: Mary, id: 6} ]
    ]
}

My current script is only returning the 'M' key and I'm not what is causing it

for (var key in obj) {
    var data = _.groupBy(obj[key], 'name')
    return data;
}

I've also tried

  Object.keys(obj).forEach(obj, key => {
    var data = _.groupBy(obj[key], 'name')
    return data;
  })

but it throws TypeError: #<Object> is not a function

Body:
Use _.forOwn since you want to iterate its own properties.

_.forOwn(obj, function(key, val) {
    var ret = {};
    ret[key] = _.groupBy(val, 'name');
    return ret;
});


问:
URL encoded colon (%3A) resolves in 403
I'm hosting some rest APIs in an Apache server (a typical xampp package).

When I attack a resource with an http method (whichever: put, post, get...) and the URL contains an encoded colon %3A, the server sometimes replies with a 403 error. It seems to depend on the folder structure of the server. If there's an existing folder and your url attacks a resource that contains %3A in that folder, the server returns 403. When it doesn't contain %3A, it returns 404 like it should.

with a structure like this:

```<code>htdocs/apis/userContext
htdocs/apis/subscriptions

http://localhost/apis/userContext/users/tel%3A2032342349 Works (returns 404 not found, because users doesn't exist)
http://localhost/apis/userContext/tel%3A2032342349 Doesn't work (returns 403)
http://localhost/subscriptions/tel%3A2032342349 Doesn't work (returns 403)
http://localhost/nonexistingfolder/tel%3A2032342349 works (returns 404, becasue nonexistingfolder doesn't exist)
</code>```

It's quite annoying since a lot of the values that are going to appear in the urls are telURIs and look like this

```<code>tel:+34678678678
</code>```

so please don't tell me not to use colons there because that's simply impossible. How could I fix this?

答:
I was able to find only one valid information about this (from October 2006) - here.

Apparently, this error doesn't appear on Linux, it happens on Windows platforms. According to the source, a short name, followed by colon (:) could be interpreted as a drive name (why is that and why file:// doesn't denote that - I don't know).

I had to solve this issue, but I could set the links myself (don't know if You have the luxury). My solution was to:

replace colons in URI by a character of choice (I chose the underscore) - urlencode($uri) → urlencode(strtr($uri, ":", "_"))

search for those URIs after applying the same replacement - SELECT ... FROM ... WHERE uri = REPLACE(@@uri, ":", "_")

Title: URL encoded colon (%3A) resolves in 403

Body:
I'm hosting some rest APIs in an Apache server (a typical xampp package).

When I attack a resource with an http method (whichever: put, post, get...) and the URL contains an encoded colon %3A, the server sometimes replies with a 403 error. It seems to depend on the folder structure of the server. If there's an existing folder and your url attacks a resource that contains %3A in that folder, the server returns 403. When it doesn't contain %3A, it returns 404 like it should.

with a structure like this:

htdocs/apis/userContext
htdocs/apis/subscriptions

http://localhost/apis/userContext/users/tel%3A2032342349 Works (returns 404 not found, because users doesn't exist)
http://localhost/apis/userContext/tel%3A2032342349 Doesn't work (returns 403)
http://localhost/subscriptions/tel%3A2032342349 Doesn't work (returns 403)
http://localhost/nonexistingfolder/tel%3A2032342349 works (returns 404, becasue nonexistingfolder doesn't exist)

It's quite annoying since a lot of the values that are going to appear in the urls are telURIs and look like this

tel:+34678678678

so please don't tell me not to use colons there because that's simply impossible. How could I fix this?


问:
Entity Framework can't get all the related objects
For some reason I can't get all the related objects from my database. Maybe I made a mistake somewhere, but I can't see it. Can anyone help me out please.

I'm trying to get all the related objects from many-to-many relastionships using:

```<code>            var result = await ec.Organizations.Include(o => o.Countries)
            .ThenInclude(oc => oc.Country)
            .ThenInclude(c => c.Businesses)
            .ThenInclude(cb => cb.Business)
            .ThenInclude(b => b.Families)
            .ThenInclude(bf => bf.Family)
            .ThenInclude(f => f.Offerings)
            .ToListAsync();
</code>```

But, past the last ThenInclude I can't go further. It treats a property after lambda as Offerings Collection.
Ideally it should go further and look like this:

```<code>            var result = await ec.Organizations.Include(o => o.Countries)
            .ThenInclude(oc => oc.Country)
            .ThenInclude(c => c.Businesses)
            .ThenInclude(cb => cb.Business)
            .ThenInclude(b => b.Families)
            .ThenInclude(bf => bf.Family)
            .ThenInclude(f => f.Offerings)
            .ThenInclude(fo => fo.Offering)
            .ThenInclude(o => o.Departments)
            .ThenInclude(od => od.Department)
            .ToListAsync();
</code>```

This is my OnModelCreating method in the Context class:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<OrganizationCountry>()
           .HasKey(t => new { t.CountryId, t.OrganizationId });

        modelBuilder.Entity<OrganizationCountry>()
            .HasOne(oc => oc.Organization)
            .WithMany(o => o.Countries)
            .HasForeignKey(oc => oc.OrganizationId);

        modelBuilder.Entity<OrganizationCountry>()
            .HasOne(oc => oc.Country)
            .WithMany(c => c.Organizations)
            .HasForeignKey(oc => oc.CountryId);

        modelBuilder.Entity<CountryBusiness>()
            .HasKey(t => new { t.BusinessId, t.CountryId });

        modelBuilder.Entity<CountryBusiness>()
            .HasOne(cb => cb.Country)
            .WithMany(c => c.Businesses)
            .HasForeignKey(cb => cb.CountryId);

        modelBuilder.Entity<CountryBusiness>()
            .HasOne(cb => cb.Business)
            .WithMany(b => b.Countries)
            .HasForeignKey(cb => cb.BusinessId);

        modelBuilder.Entity<BusinessFamily>()
            .HasKey(t => new { t.FamilyId, t.BusinessId });

        modelBuilder.Entity<BusinessFamily>()
            .HasOne(bf => bf.Business)
            .WithMany(b => b.Families)
            .HasForeignKey(bf => bf.BusinessId);

        modelBuilder.Entity<BusinessFamily>()
            .HasOne(bf => bf.Family)
            .WithMany(f => f.Businesses)
            .HasForeignKey(bf => bf.FamilyId);

        modelBuilder.Entity<FamilyOffering>()
            .HasKey(t => new { t.OfferingId, t.FamilyId });

        modelBuilder.Entity<FamilyOffering>()
            .HasOne(fo => fo.Family)
            .WithMany(f => f.Offerings)
            .HasForeignKey(fo => fo.FamilyId);

        modelBuilder.Entity<FamilyOffering>()
            .HasOne(fo => fo.Offering)
            .WithMany(o => o.Families)
            .HasForeignKey(fo => fo.OfferingId);

        modelBuilder.Entity<OfferingDepartment>()
            .HasKey(t => new { t.DepartmentId, t.OfferingId });

        modelBuilder.Entity<OfferingDepartment>()
            .HasOne(od => od.Offering)
            .WithMany(o => o.Departments)
            .HasForeignKey(od => od.OfferingId);

        modelBuilder.Entity<OfferingDepartment>()
            .HasOne(od => od.Department)
            .WithMany(d => d.Offerings)
            .HasForeignKey(od => od.DepartmentId);
    }
</code>```

This is my Family and Offering Entities with navigation properties class. All Entities have many-to-many relationship.

```<code> public class Family
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<BusinessFamily> Businesses { get; set; }
        public virtual ICollection<FamilyOffering> Offerings { get; set; }

        public Family()
        {
            Offerings = new List<FamilyOffering>();
            Businesses = new List<BusinessFamily>();
        }
    }

public class Offering
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<FamilyOffering> Families { get; set; }
        public virtual ICollection<OfferingDepartment> Departments { get; set; }

        public Offering()
        {
            Departments = new List<OfferingDepartment>();
            Families = new List<FamilyOffering>();
        }
    }

public class FamilyOffering
    {
        public int FamilyId { get; set; }
        public Family Family { get; set; }

        public int OfferingId { get; set; }
        public Offering Offering { get; set; }
    }
</code>```

答:
It seems it is some Visual Studio IntelliSense bug. IntelliSense doesn't show the properties of type FamilyOffering, but it shows properties of List instead.

But the properties of type FamilyOffering is there. No error is shown

Body:
For some reason I can't get all the related objects from my database. Maybe I made a mistake somewhere, but I can't see it. Can anyone help me out please.

I'm trying to get all the related objects from many-to-many relastionships using:

            var result = await ec.Organizations.Include(o => o.Countries)
            .ThenInclude(oc => oc.Country)
            .ThenInclude(c => c.Businesses)
            .ThenInclude(cb => cb.Business)
            .ThenInclude(b => b.Families)
            .ThenInclude(bf => bf.Family)
            .ThenInclude(f => f.Offerings)
            .ToListAsync();

But, past the last ThenInclude I can't go further. It treats a property after lambda as Offerings Collection.
Ideally it should go further and look like this:

            var result = await ec.Organizations.Include(o => o.Countries)
            .ThenInclude(oc => oc.Country)
            .ThenInclude(c => c.Businesses)
            .ThenInclude(cb => cb.Business)
            .ThenInclude(b => b.Families)
            .ThenInclude(bf => bf.Family)
            .ThenInclude(f => f.Offerings)
            .ThenInclude(fo => fo.Offering)
            .ThenInclude(o => o.Departments)
            .ThenInclude(od => od.Department)
            .ToListAsync();

This is my OnModelCreating method in the Context class:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<OrganizationCountry>()
           .HasKey(t => new { t.CountryId, t.OrganizationId });

        modelBuilder.Entity<OrganizationCountry>()
            .HasOne(oc => oc.Organization)
            .WithMany(o => o.Countries)
            .HasForeignKey(oc => oc.OrganizationId);

        modelBuilder.Entity<OrganizationCountry>()
            .HasOne(oc => oc.Country)
            .WithMany(c => c.Organizations)
            .HasForeignKey(oc => oc.CountryId);

        modelBuilder.Entity<CountryBusiness>()
            .HasKey(t => new { t.BusinessId, t.CountryId });

        modelBuilder.Entity<CountryBusiness>()
            .HasOne(cb => cb.Country)
            .WithMany(c => c.Businesses)
            .HasForeignKey(cb => cb.CountryId);

        modelBuilder.Entity<CountryBusiness>()
            .HasOne(cb => cb.Business)
            .WithMany(b => b.Countries)
            .HasForeignKey(cb => cb.BusinessId);

        modelBuilder.Entity<BusinessFamily>()
            .HasKey(t => new { t.FamilyId, t.BusinessId });

        modelBuilder.Entity<BusinessFamily>()
            .HasOne(bf => bf.Business)
            .WithMany(b => b.Families)
            .HasForeignKey(bf => bf.BusinessId);

        modelBuilder.Entity<BusinessFamily>()
            .HasOne(bf => bf.Family)
            .WithMany(f => f.Businesses)
            .HasForeignKey(bf => bf.FamilyId);

        modelBuilder.Entity<FamilyOffering>()
            .HasKey(t => new { t.OfferingId, t.FamilyId });

        modelBuilder.Entity<FamilyOffering>()
            .HasOne(fo => fo.Family)
            .WithMany(f => f.Offerings)
            .HasForeignKey(fo => fo.FamilyId);

        modelBuilder.Entity<FamilyOffering>()
            .HasOne(fo => fo.Offering)
            .WithMany(o => o.Families)
            .HasForeignKey(fo => fo.OfferingId);

        modelBuilder.Entity<OfferingDepartment>()
            .HasKey(t => new { t.DepartmentId, t.OfferingId });

        modelBuilder.Entity<OfferingDepartment>()
            .HasOne(od => od.Offering)
            .WithMany(o => o.Departments)
            .HasForeignKey(od => od.OfferingId);

        modelBuilder.Entity<OfferingDepartment>()
            .HasOne(od => od.Department)
            .WithMany(d => d.Offerings)
            .HasForeignKey(od => od.DepartmentId);
    }

This is my Family and Offering Entities with navigation properties class. All Entities have many-to-many relationship.

 public class Family
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<BusinessFamily> Businesses { get; set; }
        public virtual ICollection<FamilyOffering> Offerings { get; set; }

        public Family()
        {
            Offerings = new List<FamilyOffering>();
            Businesses = new List<BusinessFamily>();
        }
    }

public class Offering
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<FamilyOffering> Families { get; set; }
        public virtual ICollection<OfferingDepartment> Departments { get; set; }

        public Offering()
        {
            Departments = new List<OfferingDepartment>();
            Families = new List<FamilyOffering>();
        }
    }

public class FamilyOffering
    {
        public int FamilyId { get; set; }
        public Family Family { get; set; }

        public int OfferingId { get; set; }
        public Offering Offering { get; set; }
    }


问:
symfony 2.8 login error doesn't display
I have little problem. My symfony app after bad login doesn't show error mesage in login file ;/ . After typing good login & pasword everthing is ok, im logged & redirected to dashboard.

Sorry for my English:)

here is my controller

```<code>class LoginController extends Controller
{
    /**
     * @Route("/login", name="login")
     *
     * @Template()
     */
    public function loginAction(Request $Request)
    {
        $Session = $this->get('session');

// Login Form
        if($Request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)){
            $loginError = $Request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR);
        }else{
            $loginError = $Session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);
        }

        if(isset($loginError)){
            $this->get('session')->getFlashBag()->add('error', $loginError->getMessage());
        }

        $loginForm = $this->createForm(new LoginType());

        return array(
            'loginForm' => $loginForm->createView()
        );
    }
</code>```

here is block form_errors code in view file form_template.html.twig:

```<code>{% block form_errors %}
{% spaceless %}
    {% if errors|length > 0 %}
        {% for error in errors %}
            <div class="alert alert-danger">
                <button class="close" data-close="alert"></button>
                <span> {{ error.message|trans }} </span>
            </div>
        {% endfor %}
    {% endif %}
{% endspaceless %}
{% endblock %}
</code>```

Thanks :)

答:
Try this :)</p>

```<code>{% block form_errors %}
{% spaceless %}
    {% if errors|length > 0 %}
        {% for error in app.session.flashbag.get('error') %}
            <div class="alert alert-danger">
                <button class="close" data-close="alert"></button>
                <span> {{ error|trans }} </span>
            </div>
        {% endfor %}
    {% endif %}
{% endspaceless %}
{% endblock %}
</code>```

Title: symfony 2.8 login error doesn't display

Body:
I have little problem. My symfony app after bad login doesn't show error mesage in login file ;/ . After typing good login & pasword everthing is ok, im logged & redirected to dashboard.

Sorry for my English:)

here is my controller

class LoginController extends Controller
{
    /**
     * @Route("/login", name="login")
     *
     * @Template()
     */
    public function loginAction(Request $Request)
    {
        $Session = $this->get('session');

// Login Form
        if($Request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)){
            $loginError = $Request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR);
        }else{
            $loginError = $Session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);
        }

        if(isset($loginError)){
            $this->get('session')->getFlashBag()->add('error', $loginError->getMessage());
        }

        $loginForm = $this->createForm(new LoginType());

        return array(
            'loginForm' => $loginForm->createView()
        );
    }

here is block form_errors code in view file form_template.html.twig:

{% block form_errors %}
{% spaceless %}
    {% if errors|length > 0 %}
        {% for error in errors %}

                <button class="close" data-close="alert"></button>
                 {{ error.message|trans }}

        {% endfor %}
    {% endif %}
{% endspaceless %}
{% endblock %}

Thanks :)

Body:
Try this :)

{% block form_errors %}
{% spaceless %}
    {% if errors|length > 0 %}
        {% for error in app.session.flashbag.get('error') %}
            <div class="alert alert-danger">
                <button class="close" data-close="alert"></button>
                <span> {{ error|trans }} </span>
            </div>
        {% endfor %}
    {% endif %}
{% endspaceless %}
{% endblock %}


问:
How do i check a radio button is checked or not using jquery
How do i check a radio button is checked or not using jquery???

here is the code:

```<code>     function handlesClick(myRadio) {
        debugger
       var selectedmerchant = [];
        if (myRadio != '') {
            var myRadios = $('input[name=myRadio]');
            //var checkedValue = $("#myRadio").attr('checked', 'checked');
            //if ($('#myRadio').is(':checked')) { alert("it's checked"); }
            //$('input[type="radio"][class="icheck-list"]:checked').val()
            if ($("#myRadio").is(":checked") === true)
            {
                selectedmerchant.push(myradio);
                selectedmerchant.join(",");
            }
            else
            {
 var index = selectedmerchant.indexof(merchant);
               selectedmerchant.splice(index, 1);
            }
     //if (document.getelementbyid(myradio).checked == true) {
            //    selectedmerchant.push(myradio);
            //    selectedmerchant.join(",");
            //}
            //else {
            //    var index = selectedmerchant.indexof(merchant);
            //    selectedmerchant.splice(index, 1);
            //}
</code>```

i want to check is the checkbox is checked or not so that i can push or slice in a array using javascript.
any code???

here is the html:

```<code>  <div class="row">
    <div class="form-group">
      <div class="col-md-12">
        <label>3.sdfdsfsdfds</label>
        <div class="icheck-list">
          <label class="icheck-list" id="11">

            <input name="3" onclick="handlesClick(this);" id="3_11" type="radio">Strongly Disagree
            <span></span>
          </label>
        </div>
        <div class="icheck-list">
          <label class="icheck-list" id="12">
            <input name="3" onclick="handlesClick(this);" id="3_12" type="radio">Disagree
            <span></span>
          </label>
        </div>
        <div class="icheck-list">
          <label class="icheck-list" id="13">
            <input name="3" onclick="handlesClick(this);" id="3_13" type="radio">Neither Agree or Disagree
            <span></span>
          </label>
        </div>
        <div class="icheck-list">
          <label class="icheck-list" id="14">
            <input name="3" onclick="handlesClick(this);" id="3_14" type="radio">Agree
            <span></span>
          </label>
        </div>
        <div class="icheck-list">
          <label class="icheck-list" id="15">
            <input name="3" onclick="handlesClick(this);" id="3_15" type="radio">Strongly Agree
            <span></span>
          </label>
        </div>
      </div>
    </div>
  </div>
</code>```

答:
For this please try below code :

```<code><input name="3" onclick="handlesClick(this);" id="3_1" type="radio">Agree

<input name="3" onclick="handlesClick(this);" id="3_2" type="radio">Disagree
</code>```

// Here is the JS code //

```<code>function handlesClick(RadioId) {

if (RadioId != '') {
if ($(RadioId).is(":checked") === true)
    {

  //Add condition for checked Radio

     }
 else
    {

   //Add condition for unchecked Radio

    }
  }
}
</code>```

Body:
How do i check a radio button is checked or not using jquery???

here is the code:

     function handlesClick(myRadio) {
        debugger
       var selectedmerchant = [];
        if (myRadio != '') {
            var myRadios = $('input[name=myRadio]');
            //var checkedValue = $("#myRadio").attr('checked', 'checked');
            //if ($('#myRadio').is(':checked')) { alert("it's checked"); }
            //$('input[type="radio"][class="icheck-list"]:checked').val()
            if ($("#myRadio").is(":checked") === true)
            {
                selectedmerchant.push(myradio);
                selectedmerchant.join(",");
            }
            else
            {
 var index = selectedmerchant.indexof(merchant);
               selectedmerchant.splice(index, 1);
            }
     //if (document.getelementbyid(myradio).checked == true) {
            //    selectedmerchant.push(myradio);
            //    selectedmerchant.join(",");
            //}
            //else {
            //    var index = selectedmerchant.indexof(merchant);
            //    selectedmerchant.splice(index, 1);
            //}

i want to check is the checkbox is checked or not so that i can push or slice in a array using javascript.
any code???

here is the html:

        3.sdfdsfsdfds

            <input name="3" onclick="handlesClick(this);" id="3_11" type="radio">Strongly Disagree

            <input name="3" onclick="handlesClick(this);" id="3_12" type="radio">Disagree

            <input name="3" onclick="handlesClick(this);" id="3_13" type="radio">Neither Agree or Disagree

            <input name="3" onclick="handlesClick(this);" id="3_14" type="radio">Agree

            <input name="3" onclick="handlesClick(this);" id="3_15" type="radio">Strongly Agree

Body:
For this please try below code :

<input name="3" onclick="handlesClick(this);" id="3_1" type="radio">Agree

<input name="3" onclick="handlesClick(this);" id="3_2" type="radio">Disagree

// Here is the JS code //

function handlesClick(RadioId) {

if (RadioId != '') {
if ($(RadioId).is(":checked") === true)
    {

  //Add condition for checked Radio

     }
 else
    {

   //Add condition for unchecked Radio

    }
  }
}


问:
Fancybox v3 ignores data-options
I use Fandybox v3. Unfortunately there is a problem with usage of data-options.

This is my Code:

```<code><a data-fancybox data-options='{"caption": "My caption", "src": "iframe.html", "css": {"maxWidth": "500", "width": "500", "maxHeight": "300", "height": "300"}}' href="javascript:;" title="abc">
</code>```

No matter what I did, the cation shown below the iframe is always "abc" instead of "My caption" and the settings für width and height are also ignored.

What am I doing wrong?

答:
It looks like a bug in fancyBox3, if you want to set the caption set a value to data-caption attribute :

```<code><a data-fancybox data-caption="My caption" href="javascript:;">
    Open external page using iframe
</a>
</code>```

The problem is near these lines :

```<code>// Caption is a "special" option, it can be passed as a method
if ( $.type( obj.opts.caption ) === 'function' ) {
     obj.opts.caption = obj.opts.caption.apply( item, [ self, obj ] );

} else if ( 'caption' in data ) {
    obj.opts.caption = data.caption;

} else if ( opts.$orig ) {
   obj.opts.caption = $item.attr( 'title' );
}
</code>```

I'm investigating why this happens.

EDIT :

I fixed the fancybox caption issue there (maybe you should put an issue on github for this):

https://jsfiddle.net/Tintin37/g675hag6/

Title: Fancybox v3 ignores data-options

Body:
I use Fandybox v3. Unfortunately there is a problem with usage of data-options.

This is my Code:

No matter what I did, the cation shown below the iframe is always "abc" instead of "My caption" and the settings für width and height are also ignored.

What am I doing wrong?

Body:
It looks like a bug in fancyBox3, if you want to set the caption set a value to data-caption attribute :

<a data-fancybox data-caption="My caption" href="javascript:;">
    Open external page using iframe
</a>

The problem is near these lines :

// Caption is a "special" option, it can be passed as a method
if ( $.type( obj.opts.caption ) === 'function' ) {
     obj.opts.caption = obj.opts.caption.apply( item, [ self, obj ] );

} else if ( 'caption' in data ) {
    obj.opts.caption = data.caption;

} else if ( opts.$orig ) {
   obj.opts.caption = $item.attr( 'title' );
}

I'm investigating why this happens.

EDIT :

I fixed the fancybox caption issue there (maybe you should put an issue on github for this):

https://jsfiddle.net/Tintin37/g675hag6/


问:
Running node.js app and getting angular is not defined message
I am trying to run an app in node.js and I've never used node before, when I enter node app.js into terminal, I get this error message:

```<code>ReferenceError: angular is not defined
at Object.<anonymous> (/Users/michael/Desktop/myapp/app/app.js:20:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3
</code>```

I installed angular. Here is the section of code for the app.js file that is mentioned in the error:

```<code>var app = angular
.module('gbook', ['ui.router', 'uiSwitch', 'LocalStorageModule', 'vsGoogleAutocomplete', 'ngCookies', 'gbook.config', 'gbook.intlTelInput', 'ui.timepicker', 'ngAnimate', 'ngSanitize', 'mgcrea.ngStrap', 'froala', 'ui.bootstrap'])
.config(config)
.run(run);
</code>```

I also have this code in index.js under the angular folder:

```<code>require('./angular');
module.exports = angular;
</code>```

Did I do something wrong installing angular, or is it something else?

答:
You can't use angular in server side, however you could use a render engine like ejs or jade with express and use angular in a .ejs file. This way you can also have access to variables used on your backend. I suggest googling expressjs and ejs and doing a bit of research on it.

One more thing, make sure your AngularJS is hooked properly on your frontend either through a cdn or JavaScript files.

Body:
I am trying to run an app in node.js and I've never used node before, when I enter node app.js into terminal, I get this error message:

ReferenceError: angular is not defined
at Object.<anonymous> (/Users/michael/Desktop/myapp/app/app.js:20:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3

I installed angular. Here is the section of code for the app.js file that is mentioned in the error:

var app = angular
.module('gbook', ['ui.router', 'uiSwitch', 'LocalStorageModule', 'vsGoogleAutocomplete', 'ngCookies', 'gbook.config', 'gbook.intlTelInput', 'ui.timepicker', 'ngAnimate', 'ngSanitize', 'mgcrea.ngStrap', 'froala', 'ui.bootstrap'])
.config(config)
.run(run);

I also have this code in index.js under the angular folder:

require('./angular');
module.exports = angular;

Did I do something wrong installing angular, or is it something else?


问:
Qt: force UI update in the main thread
I'm writing an image viewer and I want to pre-load the next image after displaying the current one.

The problem is now: When I display an image (e.g. by applying a QPixmap to a QLabel) and load the next image in the same Qt-method-call (e.g. in the same function) the image will be displayed after the pre-loading. So I still have the time gap..

I could switch to a threaded solution but this would introduce a lot of more problems.

So my question for now is: Can I force Qt to update()/redraw() the UI in the current call stack or will I have to find a way to do the pre-loading in another "metacall"?

答:
I would try to solve the problem in the following way (without dealing with threads):</p>

```<code>void setCurrentImage()
{
    [..]
    label->setPixmap(pixmap);
    QTimer::singleShot(0, this, SLOT(preloadNextImage()));
    [..]
}

// A slot.
void preloadNextImage()
{
    // Do preload.
}
</code>```

Title: Qt: force UI update in the main thread

Body:
I would try to solve the problem in the following way (without dealing with threads):

void setCurrentImage()
{
    [..]
    label->setPixmap(pixmap);
    QTimer::singleShot(0, this, SLOT(preloadNextImage()));
    [..]
}

// A slot.
void preloadNextImage()
{
    // Do preload.
}


问:
Difference between Pattern.quote() and its String concatenation equivalent?
Consider the following pieces of code:

```<code>Pattern p = Pattern.compile(Pattern.quote("[r.e.g.e.x]"));
</code>```

and

```<code>Pattern p = Pattern.compile("\\Q" + "[r.e.g.e.x]" + "\\E");
</code>```

As far as I know, they produce the exact same output. I know that the first is more easy to read, as stated in this answer. But which approach is better or faster?

答:
The statement in the answer that:

Calling the Pattern.quote() method wraps the string in \Q...\E, which turns the text is into a regex literal.

Is strictly speaking not correct. Indeed. Because that would give weird results if \Q and \E are already in the original string.

If you call for instance Pattern.quote("\\Q[r.e.g.e.x]\\E") it will produce "\\Q\\Q[r.e.g.e.x]\\E\\\\E\\Q\\E".

As a result wrapping "\\Q" and "\\E" is obviously incorrect (for some edge-cases, I admit that). You better use Pattern.quote if you want to be safe.

The wrapping with "\\Q" and "\\E" you do yourself will be a bit faster (since you save on a method call, an indexOf(..) and an if statement in case there is no "\\E"), but usually you better use libraries since they tend to contain less bugs, and if there are bugs, these are resolved eventually.

You can find the source code here:

```<code>public static String quote(String s) {
    int slashEIndex = s.indexOf("\\E");
    if (slashEIndex == -1)
        return "\\Q" + s + "\\E";

    StringBuilder sb = new StringBuilder(s.length() * 2);
    sb.append("\\Q");
    slashEIndex = 0;
    int current = 0;
    while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
        sb.append(s.substring(current, slashEIndex));
        current = slashEIndex + 2;
        sb.append("\\E\\\\E\\Q");
    }
    sb.append(s.substring(current, s.length()));
    sb.append("\\E");
    return sb.toString();
}
</code>```

So as long as there is no "\\E", we are fine. But in the other case, we have to substitute every "\\E" with "\\E\\\\E\\Q"...

Body:
Consider the following pieces of code:

Pattern p = Pattern.compile(Pattern.quote("[r.e.g.e.x]"));

and

Pattern p = Pattern.compile("\\Q" + "[r.e.g.e.x]" + "\\E");

As far as I know, they produce the exact same output. I know that the first is more easy to read, as stated in this answer. But which approach is better or faster?

Body:
The statement in the answer that:

Calling the Pattern.quote() method wraps the string in \Q...\E, which turns the text is into a regex literal.

Is strictly speaking not correct. Indeed. Because that would give weird results if \Q and \E are already in the original string.

If you call for instance Pattern.quote("\\Q[r.e.g.e.x]\\E") it will produce "\\Q\\Q[r.e.g.e.x]\\E\\\\E\\Q\\E".

As a result wrapping "\\Q" and "\\E" is obviously incorrect (for some edge-cases, I admit that). You better use Pattern.quote if you want to be safe.

The wrapping with "\\Q" and "\\E" you do yourself will be a bit faster (since you save on a method call, an indexOf(..) and an if statement in case there is no "\\E"), but usually you better use libraries since they tend to contain less bugs, and if there are bugs, these are resolved eventually.

You can find the source code here:

public static String quote(String s) {
    int slashEIndex = s.indexOf("\\E");
    if (slashEIndex == -1)
        return "\\Q" + s + "\\E";

    StringBuilder sb = new StringBuilder(s.length() * 2);
    sb.append("\\Q");
    slashEIndex = 0;
    int current = 0;
    while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
        sb.append(s.substring(current, slashEIndex));
        current = slashEIndex + 2;
        sb.append("\\E\\\\E\\Q");
    }
    sb.append(s.substring(current, s.length()));
    sb.append("\\E");
    return sb.toString();
}

So as long as there is no "\\E", we are fine. But in the other case, we have to substitute every "\\E" with "\\E\\\\E\\Q"...


问:
Spring threads in web app
I am writing server for MMO browser game, and I need to make few threads.
They will be running all the time with some sleep time.
Is it good idea, to use spring threads like this?

```<code>@Component
@Scope("prototype")
public class PrintTask2 implements Runnable{

String name;

public void setName(String name){
    this.name = name;
}

@Override
public void run() {

    System.out.println(name + " is running");

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(name + " is running");

}
</code>```

}

with task executor implemented as bean?

```<code><bean id="taskExecutor"
       class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>
</code>```

Also, threads are started in singleton also defined as a bean.

What can be wrong in my approach?

答:
You can use @Async in case you want to invoke a single thread programmatically (e.g. you want to send 50 mail and you send them creating 50 different thread, each one to send a single message, then wait until all threads end), or @Scheduled to let a method / thread run at fixed rate (or after some time from previous execution end).

You can put an eye on https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support for further details.

```<code>@Service
public class MyAsyncStuff {
    @Async
    public Future<String> callMe(String param) {
       // do your work here...
       return new AsyncResult<String>("Sent: "+param);
    }
}

@Service
public class MyWorker {
    @Inject
    MyAsyncStuff stuff;

    public void invoker() {
        List<Future<String>> futures = new Arraylist<>();
        for (int i=0; i<10; i++) {
           futures.add(stuff.callMe("Invoked "+i));
        }
        for (Future<String> fut : futures) {
           try {
              System.out.println(futures.get();
           } catch (Exception e) {
             // Spock? Do something!
           }
        }
     }
 }
</code>```

Title: Spring threads in web app

Body:
I am writing server for MMO browser game, and I need to make few threads.
They will be running all the time with some sleep time.
Is it good idea, to use spring threads like this?

@Component
@Scope("prototype")
public class PrintTask2 implements Runnable{

String name;

public void setName(String name){
    this.name = name;
}

@Override
public void run() {

    System.out.println(name + " is running");

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(name + " is running");

}

}

with task executor implemented as bean?

<bean id="taskExecutor"
       class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>

Also, threads are started in singleton also defined as a bean.

What can be wrong in my approach?

Body:
You can use @Async in case you want to invoke a single thread programmatically (e.g. you want to send 50 mail and you send them creating 50 different thread, each one to send a single message, then wait until all threads end), or @Scheduled to let a method / thread run at fixed rate (or after some time from previous execution end).

You can put an eye on https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support for further details.

@Service
public class MyAsyncStuff {
    @Async
    public Future<String> callMe(String param) {
       // do your work here...
       return new AsyncResult<String>("Sent: "+param);
    }
}

@Service
public class MyWorker {
    @Inject
    MyAsyncStuff stuff;

    public void invoker() {
        List<Future<String>> futures = new Arraylist<>();
        for (int i=0; i<10; i++) {
           futures.add(stuff.callMe("Invoked "+i));
        }
        for (Future<String> fut : futures) {
           try {
              System.out.println(futures.get();
           } catch (Exception e) {
             // Spock? Do something!
           }
        }
     }
 }


问:
width and height of image are zero because of asynchronous image loading in objective c iOS
i am trying to get image width and height out of dispatch_async function but it gives zero result.

Below is my code

```<code>dispatch_async(dispatch_get_main_queue(), ^{
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://url%@",[[arrayEvents objectAtIndex:j] valueForKey:@"image"]]]];

                //NSData *imageData = [NSData dataWithContentsOfURL:url];
                UIImage *images = [[UIImage alloc]initWithData:imageData];
                CGFloat height = images.size.height;
                CGFloat width = images.size.width;
                ratio_2=scrrenwidth/width;
                scaledHeight_2=height*ratio_2;

                 img_vw2.image=[UIImage imageWithData:imageData];

 });

 NSLog(@"%f",scaledHeight_2);
</code>```

When I print Inside the dispatch_async I got correct Image height and width but when I print outside the dispatch_async it gives me 0 as a value.

Thanks in advance

答:
Because you are using
GCD. That means you telling the compiler to do 2 task at a single time. So first he compiles the code outside the GCD block i.e. dispatch_asynlater it compiles the GCD code.

For confirmation of my answer you can put an break point and you can check or you can check by by which data is printed first in console.

In your case data is fetched in the GCD, so until it doen't get data it always be 0.

Hope it helps you to understand what actually you have done in your code..

Body:
i am trying to get image width and height out of dispatch_async function but it gives zero result.

Below is my code

dispatch_async(dispatch_get_main_queue(), ^{
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://url%@",[[arrayEvents objectAtIndex:j] valueForKey:@"image"]]]];

                //NSData *imageData = [NSData dataWithContentsOfURL:url];
                UIImage *images = [[UIImage alloc]initWithData:imageData];
                CGFloat height = images.size.height;
                CGFloat width = images.size.width;
                ratio_2=scrrenwidth/width;
                scaledHeight_2=height*ratio_2;

                 img_vw2.image=[UIImage imageWithData:imageData];

 });

 NSLog(@"%f",scaledHeight_2);

When I print Inside the dispatch_async I got correct Image height and width but when I print outside the dispatch_async it gives me 0 as a value.

Thanks in advance


问:
Generating string in code when one of a group of properties change
I am seeking advice on how to be notified when one of many properties change.

For example, lets say I want to bind a control's text to a FullAddress property in my WPF ViewModel that I can calculate on the fly whenever one of a set of properties changes, such as StreetNumber, StreetName, Suburb, PostCode etc.

I am thinking that I need to bind my displaying control to the FullAddress property, but how do I have it automatically update whenever one of the dependent properties changes? Can I bind the property's codebehind to multiple other properties on the same ViewModel? If so how? Is there a better way?

答:
I think your only option here is to have objects of your class subscribe to their own INPC events and change their dependent properties automatically. The workflow would go like this:

Object is created

Object subscribes to its own INPC

A dependent property is changed

The INPC subscription detects that a dependent property for FullAddress has changed, and updates the FullAddress value

The FullAddress setter fires its own INPC event

WPF detects that FullAddress has changed and updates the UI

Update: Sample code

```<code>class NotificationExample : INotifyPropertyChanged
{
    private string firstName;
    private string lastName;
    public event PropertyChangedEventHandler PropertyChanged;

    public string FirstName
    {
        get { return this.firstName; }

        set
        {
            this.firstName = value;
            this.OnPropertyChanged("FirstName");
        }
    }

    public string LastName
    {
        get { return this.lastName; }

        set
        {
            this.lastName = value;
            this.OnPropertyChanged("LastName");
        }
    }

    public string FullName
    {
        get { return string.Format("{0} {1}", this.firstName, this.lastName); }
    }

    public NotificationExample()
    {
        this.PropertyChanged += this.NotifyIfFullNameChanged;
    }

    private void OnPropertyChanged(string propertyName)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private void NotifyIfFullNameChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "FirstName" || e.PropertyName == "LastName")
        {
            this.OnPropertyChanged("FullName");
        }
    }
}
</code>```

Body:
I think your only option here is to have objects of your class subscribe to their own INPC events and change their dependent properties automatically. The workflow would go like this:

Object is created

Object subscribes to its own INPC

A dependent property is changed

The INPC subscription detects that a dependent property for FullAddress has changed, and updates the FullAddress value

The FullAddress setter fires its own INPC event

WPF detects that FullAddress has changed and updates the UI

Update: Sample code

class NotificationExample : INotifyPropertyChanged
{
    private string firstName;
    private string lastName;
    public event PropertyChangedEventHandler PropertyChanged;

    public string FirstName
    {
        get { return this.firstName; }

        set
        {
            this.firstName = value;
            this.OnPropertyChanged("FirstName");
        }
    }

    public string LastName
    {
        get { return this.lastName; }

        set
        {
            this.lastName = value;
            this.OnPropertyChanged("LastName");
        }
    }

    public string FullName
    {
        get { return string.Format("{0} {1}", this.firstName, this.lastName); }
    }

    public NotificationExample()
    {
        this.PropertyChanged += this.NotifyIfFullNameChanged;
    }

    private void OnPropertyChanged(string propertyName)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private void NotifyIfFullNameChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "FirstName" || e.PropertyName == "LastName")
        {
            this.OnPropertyChanged("FullName");
        }
    }
}


问:
How does django detect file changes
I'm trying to watch for changes in .py files, in a directory.
I went through existing solution.
I'm curious on how django library solves this problem. The development server is restarted on file changes.</p>

答:
The code can be found in django.utils.autoreload. The autoreloader uses a separate thread that watches any python module that has been imported, and any translation file.

If inotify is available, Django uses that to listen to change events. Otherwise, it checks the timestamps of every file every second. If there are any changes, the process is restarted.

Django's autoreloader may not be the best source of inspiration. Better options may be Watchman (with the appropriate python bindings) or the pure-python alternative Watchdog.

Title: How does django detect file changes


问:
In posts page show only last 2 years posts in Wordpress
I have created a page for posts called Blog, in Reading settings I have selected Blog page as posts page. Now what I want is I want show only last two years posts, not all. How can I achieve that?

Thanks in advance.

答:
Here is the basic code for your query.

```<code><?php
$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'order'         => 'DESC',
    'orderby'       => 'date',
    'date_query' => array(
        array(
            'column' => 'post_date_gmt',
            'before' => '2 year ago',
        ),
    ),
);
$query = new WP_Query( $args );
if($query->have_posts()): while($query->have_posts()): $query->the_post();
    /*
    * Your HTML styles to display the post
    */
    ?>
    <h1><?php the_title(); ?></h1>
    <p><?php the_content(); ?></p>
<?php
endwhile;
wp_reset_postdata();
endif;
?>
</code>```

Also, please refer to the following document for more knowledge about it.

Query in WP Date

Hope its works for you

Thanks

Body:
Here is the basic code for your query.

<?php
$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'order'         => 'DESC',
    'orderby'       => 'date',
    'date_query' => array(
        array(
            'column' => 'post_date_gmt',
            'before' => '2 year ago',
        ),
    ),
);
$query = new WP_Query( $args );
if($query->have_posts()): while($query->have_posts()): $query->the_post();
    /*
    * Your HTML styles to display the post
    */
    ?>
    <h1><?php the_title(); ?></h1>
    <p><?php the_content(); ?></p>
<?php
endwhile;
wp_reset_postdata();
endif;
?>

Also, please refer to the following document for more knowledge about it.

Query in WP Date

Hope its works for you

Thanks


问:
How to express a jQuery selector containing an XML namespace?
I am trying to write my selector for jQuery. The attribute is xlink:href and the value is #_SAPGUI-icons_0_s_wfwire. I tried to construct it like this:

```<code>$('[xlink:href="#_SAPGUI-icons_0_s_wfwire"]')
</code>```

I get a syntax error because of the expression [xlink:href="#_SAPGUI-icons_0_s_wfwire"].

Do you have any idea how to go about this?

答:
The issue is because of the : in the selector. You need to escape it using \\, like this:

$('[xlink\\:href="#_SAPGUI-icons_0_s_wfwire"]').addClass('foo');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.foo { color: red; }</code>```

#_SAPGUI-icons_000

#_SAPGUI-icons_0_s_wfwire

#_SAPGUI-icons_111
```

Body:
I am trying to write my selector for jQuery. The attribute is xlink:href and the value is #_SAPGUI-icons_0_s_wfwire. I tried to construct it like this:

$('[xlink:href="#_SAPGUI-icons_0_s_wfwire"]')

I get a syntax error because of the expression [xlink:href="#_SAPGUI-icons_0_s_wfwire"].

Do you have any idea how to go about this?

Body:
The issue is because of the : in the selector. You need to escape it using \\, like this:

$('[xlink\\:href="#_SAPGUI-icons_0_s_wfwire"]').addClass('foo');

.foo { color: red; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div xlink:href="#_SAPGUI-icons_000">#_SAPGUI-icons_000</div>
<div xlink:href="#_SAPGUI-icons_0_s_wfwire">#_SAPGUI-icons_0_s_wfwire</div>
<div xlink:href="#_SAPGUI-icons_111">#_SAPGUI-icons_111</div>


问:
Getting HTTP Status 415 - Unsupported Media Type with Jersey
Below is my POJO class

```<code>public class Credentials {
private int cred_id;
private String cred_user_name;
private String cred_password;
private String cred_token;

public Credentials(int cred_id, String cred_user_name,
        String cred_password, String cred_token) {
    this.cred_id = cred_id;
    this.cred_user_name = cred_user_name;
    this.cred_password = cred_password;
    this.cred_token = cred_token;
}

public int getCred_id() {
    return cred_id;
}

public void setCred_id(int cred_id) {
    this.cred_id = cred_id;
}

public String getCred_user_name() {
    return cred_user_name;
}

public void setCred_user_name(String cred_user_name) {
    this.cred_user_name = cred_user_name;
}

public String getCred_password() {
    return cred_password;
}

public void setCred_password(String cred_password) {
    this.cred_password = cred_password;
}

public String getCred_token() {
    return cred_token;
}

public void setCred_token(String cred_token) {
    this.cred_token = cred_token;
}
</code>```

}

Below is my resource class

```<code>public class ValidateUser {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String validateUser(Credentials credentials) {
    System.out.println("Going to validate the user" + credentials);
    String username = credentials.getCred_user_name();
    String password = credentials.getCred_password();
    CredentialsAccessor ca = new CredentialsAccessor();
    long count = 0;
    count = ca.authenticateUser(username, password);
    if (count > 0) {
        JSONObject jObject = new JSONObject();
        try {
            jObject.put("valid", "true");
            return jObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            return "{'valid':'error'}";
        }
    } else {
        JSONObject jObject = new JSONObject();
        try {
            jObject.put("valid", "false");
            return jObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            return "{'valid':'error'}";
        }
    }
}
</code>```

}

Please see the maven dependencies here

I ensured that in the RESTClient i give the content type as Content-Type:application/json

Please see the RESTClient

Below is my web.xml

But even then i get the error 'Getting HTTP Status 415 - Unsupported Media'

Can you image, where am I going wrong?

答:
I See you have MOXy. But MOXy only knows how to handle classes annotated with @XmlRootElement. That's the reason for the 415: Jersey can't find a MessageBodyReader to handle the type.

After you add the @XmlRootElement on top of the Credentials class, you're going to get another error because MOXy will not be able to actually deserialize the JSON to your Credentials. The reason is that there's no default (no-arg) constructor. So add that, and I'm thinking you should be good.

Body:
Below is my POJO class

public class Credentials {
private int cred_id;
private String cred_user_name;
private String cred_password;
private String cred_token;

public Credentials(int cred_id, String cred_user_name,
        String cred_password, String cred_token) {
    this.cred_id = cred_id;
    this.cred_user_name = cred_user_name;
    this.cred_password = cred_password;
    this.cred_token = cred_token;
}

public int getCred_id() {
    return cred_id;
}

public void setCred_id(int cred_id) {
    this.cred_id = cred_id;
}

public String getCred_user_name() {
    return cred_user_name;
}

public void setCred_user_name(String cred_user_name) {
    this.cred_user_name = cred_user_name;
}

public String getCred_password() {
    return cred_password;
}

public void setCred_password(String cred_password) {
    this.cred_password = cred_password;
}

public String getCred_token() {
    return cred_token;
}

public void setCred_token(String cred_token) {
    this.cred_token = cred_token;
}

}

Below is my resource class

public class ValidateUser {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String validateUser(Credentials credentials) {
    System.out.println("Going to validate the user" + credentials);
    String username = credentials.getCred_user_name();
    String password = credentials.getCred_password();
    CredentialsAccessor ca = new CredentialsAccessor();
    long count = 0;
    count = ca.authenticateUser(username, password);
    if (count > 0) {
        JSONObject jObject = new JSONObject();
        try {
            jObject.put("valid", "true");
            return jObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            return "{'valid':'error'}";
        }
    } else {
        JSONObject jObject = new JSONObject();
        try {
            jObject.put("valid", "false");
            return jObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            return "{'valid':'error'}";
        }
    }
}

}

Please see the maven dependencies here

I ensured that in the RESTClient i give the content type as Content-Type:application/json

Please see the RESTClient

Below is my web.xml

But even then i get the error 'Getting HTTP Status 415 - Unsupported Media'

Can you image, where am I going wrong?


问:
Spring @Autowired usage
What are the pros and cons of using @Autowired in a class that will be wired up by Spring?

Just to clarify, I'm talking specifically about the @Autowired annotation, not auto-wiring in XML.

I probably just don't understand it, but to me it almost seems like an anti-pattern - your classes start to become aware that they are tied to a DI framework, rather than just being POJOs.  Maybe I'm a glutton for punishment, but I like having the external XML config for beans, and I like to have explicit wirings, so I know exactly what is wired where.

答: We are switching from @Autowire back to XML configuration in our big project. The problem is very low bootstrap performance. Autowiring scanner loads all classes from autowiring search classpath, so, lots of classes are loaded eagerly during Spring initialization.</p>

OwnerDisplayName: Andy White

Title: Spring @Autowired usage

LastEditorDisplayName: Andy White


问:
Print and Insert a static matrix in C
I'd like to fill and print a static matrix, for sorting then with the Young Tablue proprieties Here, but I have a problem with some dimension (row and col) input, with some input show me the right matrix, but with others give me seg.fault or a weird output.
Here the function:

```<code>#include <stdio.h>
#include <stdlib.h>
#define MAX 32

void fill( int A[MAX][MAX], int numRig, int numCol, int numElem){
 int i,j;
 int count = 0;

 for ( i = 0 ; i < numRig; i++ ) {

     for ( j = 0 ; j < numCol; j++) {

             A[i][j] = rand() % 20;
            //fscanf(stdin,"%d", &A[i][j]);
             //DEBUG
             printf("%d\n", A[i][j]);

    }
 }

 }

void stamp(int A[MAX][MAX], int numRig, int numCol){
int k,h;

  for ( h = 0 ; h < numRig; h++ ) {

     for ( k = 0 ; k < numCol; k++) {

            printf("%d ", A[h][k]);
        }
        printf("\n");
    }
 }
</code>```

the main

```<code> int main () {
   int row,col;
   printf("Insert row and col:\n");
   scanf("%d %d", &row, &col);
   int A[row][col];
   fill(A,row,col);
   stamp(A,row,col);
   return 0;
}
</code>```

output with row=4 and col=4:
 "3 6 17 15 -1 0 0 0 2017675728 32765 -741456064 21906
-1 0 0 0 2017675728 32765 -741456064 21906 0 0 -741454033 21906
2017675728 32765 -741456064 21906 0 0 -741454033 21906 4 0 0 0
0 0 -741454033 21906 4 0 0 0 2017675976 32765 2017675552 32765
4 0 0 0 2017675976 32765 2017675552 32765 3 0 0 0
2017675976 32765 2017675552 32765 3 0 0 0 4 0 0 0
"

I tried with dynamic allocation:
     a=(int**)malloc(row*(sizeof(int*)));
    for(i=0;i<row;i++)
    a[i]=(int*)malloc(col*sizeof(int));

and all works fine, but I must use static allocation.

答:
Because the address of A[i][j] is by definition &A[0][0] + i * cols + j where cols is the declared number of columns of the matrix.

So if you declare the matrix as int A[4][4] in the main, you only reserve memory for 16 ints. But as you use it as int A[32][32] in your functions address of A[3][0] is 60 places after A[0][0] so far beyond the allocated array => you just invoke Undefined Behaviour

You must declare the matrix in main as int A[MAX][MAX];, you can then safely only use first rows and first columns as long as the matrix is declared with same dimensions in main and all the functions.

Variable Length Array can also be a nice alternative here (thanks to Jonathan Leffler for suggesting this). They are supported in C99, and are optionally supported since C11, but all major recent C compilers accept it, even if MSVC support is fairly recent.

That means that you can still declare int A[row][col]; in main, but your function declaration must become:

```<code>void fill( int numRig, int numCol, int A[numRig][numCol]){
...
}
void stamp(int numRig, int numCol, int A[numRig][numCol]){
...
}
</code>```

The variable length array shall be declared after its dimension in the function declaration.

But now as the declared dimensions of the matrix are consistent throughout the program, no undefined behaviour is involved...

According to the standard anyway, simply aliasing a matrix or a simple array to a matrix or array of a different size is undefined behaviour.

Title: Print and Insert a static matrix in C

Body:
I'd like to fill and print a static matrix, for sorting then with the Young Tablue proprieties Here, but I have a problem with some dimension (row and col) input, with some input show me the right matrix, but with others give me seg.fault or a weird output.
Here the function:

#include <stdio.h>
#include <stdlib.h>
#define MAX 32

void fill( int A[MAX][MAX], int numRig, int numCol, int numElem){
 int i,j;
 int count = 0;

 for ( i = 0 ; i < numRig; i++ ) {

     for ( j = 0 ; j < numCol; j++) {

             A[i][j] = rand() % 20;
            //fscanf(stdin,"%d", &A[i][j]);
             //DEBUG
             printf("%d\n", A[i][j]);

    }
 }

 }

void stamp(int A[MAX][MAX], int numRig, int numCol){
int k,h;

  for ( h = 0 ; h < numRig; h++ ) {

     for ( k = 0 ; k < numCol; k++) {

            printf("%d ", A[h][k]);
        }
        printf("\n");
    }
 }

the main

 int main () {
   int row,col;
   printf("Insert row and col:\n");
   scanf("%d %d", &row, &col);
   int A[row][col];
   fill(A,row,col);
   stamp(A,row,col);
   return 0;
}

output with row=4 and col=4:
 "3 6 17 15 -1 0 0 0 2017675728 32765 -741456064 21906
-1 0 0 0 2017675728 32765 -741456064 21906 0 0 -741454033 21906
2017675728 32765 -741456064 21906 0 0 -741454033 21906 4 0 0 0
0 0 -741454033 21906 4 0 0 0 2017675976 32765 2017675552 32765
4 0 0 0 2017675976 32765 2017675552 32765 3 0 0 0
2017675976 32765 2017675552 32765 3 0 0 0 4 0 0 0
"

I tried with dynamic allocation:
     a=(int**)malloc(row*(sizeof(int*)));
    for(i=0;i<row;i++)
    a[i]=(int*)malloc(col*sizeof(int));

and all works fine, but I must use static allocation.

Body:
Because the address of A[i][j] is by definition &A[0][0] + i * cols + j where cols is the declared number of columns of the matrix.

So if you declare the matrix as int A[4][4] in the main, you only reserve memory for 16 ints. But as you use it as int A[32][32] in your functions address of A[3][0] is 60 places after A[0][0] so far beyond the allocated array => you just invoke Undefined Behaviour

You must declare the matrix in main as int A[MAX][MAX];, you can then safely only use first rows and first columns as long as the matrix is declared with same dimensions in main and all the functions.

Variable Length Array can also be a nice alternative here (thanks to Jonathan Leffler for suggesting this). They are supported in C99, and are optionally supported since C11, but all major recent C compilers accept it, even if MSVC support is fairly recent.

That means that you can still declare int A[row][col]; in main, but your function declaration must become:

void fill( int numRig, int numCol, int A[numRig][numCol]){
...
}
void stamp(int numRig, int numCol, int A[numRig][numCol]){
...
}

The variable length array shall be declared after its dimension in the function declaration.

But now as the declared dimensions of the matrix are consistent throughout the program, no undefined behaviour is involved...

According to the standard anyway, simply aliasing a matrix or a simple array to a matrix or array of a different size is undefined behaviour.


问:
General error: 1366 Incorrect integer value
So I am working on an app until I got an error which I can't figure out why this does not work, essentially the code is trying to put something in a database, which it is not doing. I got this error with it.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'id' at row 1' in /Users/DannyTran/Desktop/WebServer/social-network/classes/DB.php:10 Stack trace: #0 /Users/DannyTran/Desktop/WebServer/social-network/classes/DB.php(10): PDOStatement->execute(Array) #1 /users/DannyTran/Desktop/WebServer/social-network/register.php(24): DB::query('INSERT INTO use...', Array) #2 {main} thrown in /Users/DannyTran/Desktop/WebServer/social-network/classes/DB.php on line 10

Here is the code that I would have:

Database:

```<code> CREATE TABLE `users` (
     `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `username` varchar(255) NOT NULL DEFAULT '',
      `first_name` varchar(255) NOT NULL DEFAULT '',
      `last_name` varchar(255) NOT NULL DEFAULT '',
      `email` varchar(255) NOT NULL DEFAULT '',
      `password` varchar(255) NOT NULL DEFAULT '',
      `gender` varchar(11) NOT NULL DEFAULT '',
      `country` varchar(255) NOT NULL DEFAULT '',
      `verified` int(11) NOT NULL,
      `role` varchar(255) NOT NULL DEFAULT '',
      `bio` text,
      `website` text,
      `status` text,
      `register` date NOT NULL,
      `last` date NOT NULL,
      `activated` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

Register.php:

```<code>    <?php
    include('./classes/DB.php');
    $pdo = new PDO('mysql:host=127.0.0.1;DBname=socialnetwork;charset=utf8', 'root', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if(isset($_POST['register'])) {
        $fn = strip_tags(@$_POST['fname']);
        $ln = strip_tags(@$_POST['lname']);
        $un = strip_tags(@$_POST['uname']);
        $em = strip_tags(@$_POST['email']);
        $pswd = strip_tags(@$_POST['password']);
        $pswd2 = strip_tags(@$_POST['password2']);
        $country = strip_tags(@$_POST['country']);
        $gender = strip_tags(@$_POST['gender']);
        $date = date("m-d-Y"); // Year - Month - Day
        $no = 0;
        $role = 'Member';
        $status = 'Hello world!';
        $website = '';
        $bio = '';

        DB::query('INSERT INTO users VALUES (\'\' , :username, :first_name, :last_name, :email, :password, :gender, :country, :verified, :role, :bio, :website, :status, :register, :last, :activated)', array(':username'=>$un,':first_name'=>$fn, ':last_name'=>$ln, ':email'=>$em, ':password'=>$pswd, ':gender'=>$gender, ':country'=>$country, ':verified'=>0, ':role'=>$role, ':bio'=>$bio, ':website'=>$website, ':status'=>$status, ':register'=>$date, ':last'=>$date, ':activated'=>0));
        echo "Welcome!";
    };

?>

<h1>Register Now</h1>
        <form action="#" method="post">
            <input type="text" placeholder="First Name" name="fname" required/><br /><br />
            <input type="text" placeholder="Last Name" name="lname" required/><br /><br />
            <input type="text" placeholder="Username" name="uname" required/><br /><br />
            <input type="email" placeholder="E-Mail Address" name="email" required/><br /><br />
            <input type="password" placeholder="Password" name="pswd" required/><br /><br />
            <input type="password" placeholder="Confirm Password" name="pswd2" required/><br /><br />
            <select name="gender">
                <option value="" disabled selected>Gender</option>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
                <option value="Other">Other</option>
            </select><br /><br />
            <?php require_once './options/countries.php'; ?><br /><br />
            <input name="register" type="submit" value="Login" /><br /><br />
        </form>
        <a href="login.php">Have an account? Login!</a>
</code>```

DB.php:

```<code><?php

class DB {
        private static function connect() {
                $pdo = new PDO('mysql:host=127.0.0.1;dbname=socialnetwork;charset=utf8', 'root', 'password');
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $pdo;
        }
        public static function query($query, $params = array()) {
                $statement = self::connect()->prepare($query);
                $statement->execute($params);
                // $data = $statement->fetchAll();
                // return $data;
        }
    }
?>
</code>```

I would appreciate any help I could get, thank you!

答:
The error message tells you what's wrong; you're trying to insert a row with an id integer value ''.

That is not valid.

Either provide a valid integer as id, or fallback on the auto-increment feature by not providing an id at all. The downside there is that you have to name each column for which you do wish to provide values.

Read the MySQL documentation on INSERT to find out how to use it.

Body:
So I am working on an app until I got an error which I can't figure out why this does not work, essentially the code is trying to put something in a database, which it is not doing. I got this error with it.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'id' at row 1' in /Users/DannyTran/Desktop/WebServer/social-network/classes/DB.php:10 Stack trace: #0 /Users/DannyTran/Desktop/WebServer/social-network/classes/DB.php(10): PDOStatement->execute(Array) #1 /users/DannyTran/Desktop/WebServer/social-network/register.php(24): DB::query('INSERT INTO use...', Array) #2 {main} thrown in /Users/DannyTran/Desktop/WebServer/social-network/classes/DB.php on line 10

Here is the code that I would have:

Database:

 CREATE TABLE `users` (
     `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `username` varchar(255) NOT NULL DEFAULT '',
      `first_name` varchar(255) NOT NULL DEFAULT '',
      `last_name` varchar(255) NOT NULL DEFAULT '',
      `email` varchar(255) NOT NULL DEFAULT '',
      `password` varchar(255) NOT NULL DEFAULT '',
      `gender` varchar(11) NOT NULL DEFAULT '',
      `country` varchar(255) NOT NULL DEFAULT '',
      `verified` int(11) NOT NULL,
      `role` varchar(255) NOT NULL DEFAULT '',
      `bio` text,
      `website` text,
      `status` text,
      `register` date NOT NULL,
      `last` date NOT NULL,
      `activated` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Register.php:

    <?php
    include('./classes/DB.php');
    $pdo = new PDO('mysql:host=127.0.0.1;DBname=socialnetwork;charset=utf8', 'root', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if(isset($_POST['register'])) {
        $fn = strip_tags(@$_POST['fname']);
        $ln = strip_tags(@$_POST['lname']);
        $un = strip_tags(@$_POST['uname']);
        $em = strip_tags(@$_POST['email']);
        $pswd = strip_tags(@$_POST['password']);
        $pswd2 = strip_tags(@$_POST['password2']);
        $country = strip_tags(@$_POST['country']);
        $gender = strip_tags(@$_POST['gender']);
        $date = date("m-d-Y"); // Year - Month - Day
        $no = 0;
        $role = 'Member';
        $status = 'Hello world!';
        $website = '';
        $bio = '';

        DB::query('INSERT INTO users VALUES (\'\' , :username, :first_name, :last_name, :email, :password, :gender, :country, :verified, :role, :bio, :website, :status, :register, :last, :activated)', array(':username'=>$un,':first_name'=>$fn, ':last_name'=>$ln, ':email'=>$em, ':password'=>$pswd, ':gender'=>$gender, ':country'=>$country, ':verified'=>0, ':role'=>$role, ':bio'=>$bio, ':website'=>$website, ':status'=>$status, ':register'=>$date, ':last'=>$date, ':activated'=>0));
        echo "Welcome!";
    };

?>

Register Now

        <form action="#" method="post">
            <input type="text" placeholder="First Name" name="fname" required/>

            <input type="text" placeholder="Last Name" name="lname" required/>

            <input type="text" placeholder="Username" name="uname" required/>

            <input type="email" placeholder="E-Mail Address" name="email" required/>

            <input type="password" placeholder="Password" name="pswd" required/>

            <input type="password" placeholder="Confirm Password" name="pswd2" required/>

            <select name="gender">
                <option value="" disabled selected>Gender</option>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
                <option value="Other">Other</option>
            </select>

            <?php require_once './options/countries.php'; ?>

            <input name="register" type="submit" value="Login" />

        </form>
        Have an account? Login!

DB.php:

<?php

class DB {
        private static function connect() {
                $pdo = new PDO('mysql:host=127.0.0.1;dbname=socialnetwork;charset=utf8', 'root', 'password');
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $pdo;
        }
        public static function query($query, $params = array()) {
                $statement = self::connect()->prepare($query);
                $statement->execute($params);
                // $data = $statement->fetchAll();
                // return $data;
        }
    }
?>

I would appreciate any help I could get, thank you!


问:
how to update mysql column using symfony
I created in view file html input form and I named it "thenum"

```<code>{% extends 'base.html.twig' %}

{% block body %}
    <h1>User edit</h1>

    {{ form_start(edit_form) }}
        {{ form_widget(edit_form) }}
        <input type="text" name="thenum" value="0"><br>

        <input type="submit" value="Edit" />
    {{ form_end(edit_form) }}

{% endblock %}
</code>```

and in my default controller file

```<code>public function indexAction()
{

    $user = $this->container->get('security.context')->getToken()->getUser();
    $user->getId();
    $conn = $this->get('database_connection');

    $users = $conn->query("UPDATE user SET batman= 'thenum' WHERE username ='$user'");
    return $this->render('siteblogBundle:Default:index.html.twig', array('edit_form' => $users));
}
</code>```

but I get this error when I run my code

Type error: Argument 1 passed to
  Symfony\Component\Form\FormRenderer::renderBlock() must be an instance
  of Symfony\Component\Form\FormView, instance of
  Doctrine\DBAL\Driver\PDOStatement given, called in
  /opt/lampp/htdocs/x/chessMult/1/sym/thesym/app/cache/dev/twig/96/96f6b6f8c21d5412246839a2d6e2eb66ac4141143dd67e2b91f285f2a31b60fc.php
  on line 44

答:
You should use a Symfony Form . The returned data from the form can be flushed to update your database record. There is an example provided in the docs.</p>

```<code>$task = new Task();

$form = $this->createFormBuilder($task)
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->add('save', SubmitType::class, array('label' => 'Create Task'))
    ->getForm();

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    // $form->getData() holds the submitted values
    // but, the original `$task` variable has also been updated
    $task = $form->getData();

    // ... perform some action, such as saving the task to the database
    // for example, if Task is a Doctrine entity, save it!
    // $em = $this->getDoctrine()->getManager();
    // $em->persist($task);
    // $em->flush();

    return $this->redirectToRoute('task_success');
}

return $this->render('default/new.html.twig', array(
    'form' => $form->createView(),
));
</code>```

Body:
I created in view file html input form and I named it "thenum"

{% extends 'base.html.twig' %}

{% block body %}

User edit

    {{ form_start(edit_form) }}
        {{ form_widget(edit_form) }}
        <input type="text" name="thenum" value="0">

        <input type="submit" value="Edit" />
    {{ form_end(edit_form) }}

{% endblock %}

and in my default controller file

public function indexAction()
{

    $user = $this->container->get('security.context')->getToken()->getUser();
    $user->getId();
    $conn = $this->get('database_connection');

    $users = $conn->query("UPDATE user SET batman= 'thenum' WHERE username ='$user'");
    return $this->render('siteblogBundle:Default:index.html.twig', array('edit_form' => $users));
}

but I get this error when I run my code

Type error: Argument 1 passed to
  Symfony\Component\Form\FormRenderer::renderBlock() must be an instance
  of Symfony\Component\Form\FormView, instance of
  Doctrine\DBAL\Driver\PDOStatement given, called in
  /opt/lampp/htdocs/x/chessMult/1/sym/thesym/app/cache/dev/twig/96/96f6b6f8c21d5412246839a2d6e2eb66ac4141143dd67e2b91f285f2a31b60fc.php
  on line 44

Body:
You should use a Symfony Form . The returned data from the form can be flushed to update your database record. There is an example provided in the docs.

$task = new Task();

$form = $this->createFormBuilder($task)
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->add('save', SubmitType::class, array('label' => 'Create Task'))
    ->getForm();

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    // $form->getData() holds the submitted values
    // but, the original `$task` variable has also been updated
    $task = $form->getData();

    // ... perform some action, such as saving the task to the database
    // for example, if Task is a Doctrine entity, save it!
    // $em = $this->getDoctrine()->getManager();
    // $em->persist($task);
    // $em->flush();

    return $this->redirectToRoute('task_success');
}

return $this->render('default/new.html.twig', array(
    'form' => $form->createView(),
));


问:
Perform a reverse cumulative sum on a numpy array
Can anyone recommend a way to do a reverse cumulative sum on a numpy array?

Where 'reverse cumulative sum' is defined as below (I welcome any corrections on the name for this procedure):

if

```<code>x = np.array([0,1,2,3,4])
</code>```

then

```<code>np.cumsum(x)
</code>```

gives

```<code>array([0,1,3,6,10])
</code>```

However, I would like to get

```<code>array([10,10,9,7,4]
</code>```

Can anyone suggest a way to do this?

答:
You can use .flipud() for this as well, which is equivalent to [::-1]
https://docs.scipy.org/doc/numpy/reference/generated/numpy.flipud.html

```<code>In [0]: x = np.array([0,1,2,3,4])

In [1]: np.flipud(np.flipud(x).cumsum())
Out[1]: array([10, 10,  9,  7,  4]
</code>```

.flip() is new as of NumPy 1.12, and combines the .flipud() and .fliplr() into one API.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html

This is equivalent, and has fewer function calls:

```<code>np.flip(np.flip(x, 0).cumsum(), 0)
</code>```

Body:
Can anyone recommend a way to do a reverse cumulative sum on a numpy array?

Where 'reverse cumulative sum' is defined as below (I welcome any corrections on the name for this procedure):

if

x = np.array([0,1,2,3,4])

then

np.cumsum(x)

gives

array([0,1,3,6,10])

However, I would like to get

array([10,10,9,7,4]

Can anyone suggest a way to do this?

Body:
You can use .flipud() for this as well, which is equivalent to [::-1]
https://docs.scipy.org/doc/numpy/reference/generated/numpy.flipud.html

In [0]: x = np.array([0,1,2,3,4])

In [1]: np.flipud(np.flipud(x).cumsum())
Out[1]: array([10, 10,  9,  7,  4]

.flip() is new as of NumPy 1.12, and combines the .flipud() and .fliplr() into one API.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html

This is equivalent, and has fewer function calls:

np.flip(np.flip(x, 0).cumsum(), 0)


问:
How to use the --name argument to getopt?
In the following example, I expected the error message to come from xyz, not from getopt. What am I doing wrong?

```<code>/tmp> getopt  --name xyz --options "xyz:" -- -x
 -x --
/tmp> getopt  --name xyz --options "xyz:" -- -x -z
getopt: option requires an argument -- z
 -x --
</code>```

How do I make it say xyz: option requires an argument -- z; isn't that what --name is for?

UPDATE

Seems to be a bug. My getopt comes from cygwin

```<code>$ getopt --version
getopt from util-linux 2.25.2
</code>```

答:
This is a bug (or just a non-portability issue) which is already fixed in util-linux 2.28, by commit 30fbf2f6. Before this fix it worked only on Linux, OSX and a few BSD flavors but not on WIN32 or GNU-Hurd for example.

If you can't upgrade util-linux (might be difficult to build on windows), then you could use this shell workaround:

```<code>bash -c 'exec -a "XYZ" getopt --options "xyz:" -- -x -z'
</code>```

Note that still using the --name option would override this trick again once if getopt will be updated one day.

Of course you could also simply copy/link/rename the getopt program to whatever name you want.

Body:
In the following example, I expected the error message to come from xyz, not from getopt. What am I doing wrong?

/tmp> getopt  --name xyz --options "xyz:" -- -x
 -x --
/tmp> getopt  --name xyz --options "xyz:" -- -x -z
getopt: option requires an argument -- z
 -x --

How do I make it say xyz: option requires an argument -- z; isn't that what --name is for?

UPDATE

Seems to be a bug. My getopt comes from cygwin

$ getopt --version
getopt from util-linux 2.25.2

Body:
This is a bug (or just a non-portability issue) which is already fixed in util-linux 2.28, by commit 30fbf2f6. Before this fix it worked only on Linux, OSX and a few BSD flavors but not on WIN32 or GNU-Hurd for example.

If you can't upgrade util-linux (might be difficult to build on windows), then you could use this shell workaround:

bash -c 'exec -a "XYZ" getopt --options "xyz:" -- -x -z'

Note that still using the --name option would override this trick again once if getopt will be updated one day.

Of course you could also simply copy/link/rename the getopt program to whatever name you want.


问:
How to add own traffic layer on google map
I have json like below.

```<code>[{
    "startnode_lat": "x1",
    "startnode_lng": "y1",
    "endnode_lat": "x11",
    "endnode_lng": "y11",
    "color": "green"
}, {
    "startnode_lat": "x2",
    "startnode_lng": "y2",
    "endnode_lat": "x22",
    "endnode_lng": "y22",
    "color": "red"
}, {
    "startnode_lat": "x3",
    "startnode_lng": "y3",
    "endnode_lat": "x33",
    "endnode_lng": "y33",
    "color": "yellow"
}]
</code>```

How to add this json like traffic layer on google map

答:
I think the easiest way should be creating your JSON file in accordance with the GeoJSON format:

http://geojson.org/geojson-spec.html

After that you will be able to load it in Maps JavaScript API data layer as shown in the following example:

https://developers.google.com/maps/documentation/javascript/examples/layer-data-simple

Hope it helps!

Body:
I have json like below.

[{
    "startnode_lat": "x1",
    "startnode_lng": "y1",
    "endnode_lat": "x11",
    "endnode_lng": "y11",
    "color": "green"
}, {
    "startnode_lat": "x2",
    "startnode_lng": "y2",
    "endnode_lat": "x22",
    "endnode_lng": "y22",
    "color": "red"
}, {
    "startnode_lat": "x3",
    "startnode_lng": "y3",
    "endnode_lat": "x33",
    "endnode_lng": "y33",
    "color": "yellow"
}]

How to add this json like traffic layer on google map


问:
How to implement a soft-margin SVM model using Matlab's quadprog?
Suppose we are given a training dataset {yᵢ, xᵢ}, for i = 1, ..., n, where yᵢ can either be -1 or 1 and xᵢ can be e.g. a 2D or 3D point.

In general, when the input points are linearly separable, the SVM model can be defined as follows

```<code>min 1/2*||w||²
w,b
</code>```

subject to the constraints (for i = 1, ..., n)

```<code>yᵢ*(w*xᵢ - b) >= 1
</code>```

This is often called the hard-margin SVM model, which is thus a constrained minimization problem, where the unknowns are w and b. We can also omit 1/2 in the function to be minimized, given it's just a constant.

Now, the documentation about Matlab's quadprog states

x = quadprog(H, f, A, b) minimizes 1/2*x'*H*x + f'*x subject to the restrictions A*x ≤ b. A is a matrix of doubles, and b is a vector of doubles.

We can implement the hard-margin SVM model using quadprog function, to get the weight vector w, as follows

H becomes an identity matrix.

f' becomes a zeros matrix.

A is the left-hand side of the constraints

b is equal to -1 because the original constraint had >= 1, it becomes <= -1 when we multiply with -1 on both sides.

Now, I am trying to implement a soft-margin SVM model. The minimization equation here is

```<code>min (1/2)*||w||² + C*(∑ ζᵢ)
w,b
</code>```

subject to the constraints (for i = 1, ..., n)

```<code>yᵢ*(w*xᵢ - b) >= 1 - ζᵢ
</code>```

such that ζᵢ >= 0, where ∑ is the summation symbol, ζᵢ = max(0, 1 - yᵢ*(w*xᵢ - b)) and C is a hyper-parameter.

How can this optimization problem be solved using the Matlab's quadprog function? It's not clear to me how the equation should be mapped to the parameters of the quadprog function.

The "primal" form of the soft-margin SVM model (i.e. the definition above) can be converted to a "dual" form. I did that, and I am able to get the Lagrange variable values (in the dual form). However, I would like to know if I can use quadprog to solve directly the primal form without needing to convert it to the dual form.

答:
If let z = (w; w0; eps)T be a the long vector with n+1+m elements.(m the number of points)
Then,

```<code>H= diag([ones(1,n),zeros(1,m+1)]).
f = [zeros(1; n + 1); ones(1;m)]
</code>```

The inequality constraints can be specified as :

```<code>A = -diag(y)[X; ones(m; 1); zeroes(m;m)] -[zeros(m,n+1),eye(m)],
</code>```

where X is the n x m input matrix in the primal form.Out of the 2 parts for A, the first part is for w0 and the second part is for eps.

```<code>b = ones(m,1)
</code>```

The equality constraints :

```<code>Aeq = zeros(1,n+1 +m)
beq = 0
</code>```

Bounds:

```<code>lb = [-inf*ones(n+1,1); zeros(m,1)]
ub = [inf*ones(n+1+m,1)]
</code>```

Now, z=quadprog(H,f,A,b,Aeq,beq,lb,ub)

Body:
Suppose we are given a training dataset {yᵢ, xᵢ}, for i = 1, ..., n, where yᵢ can either be -1 or 1 and xᵢ can be e.g. a 2D or 3D point.

In general, when the input points are linearly separable, the SVM model can be defined as follows

min 1/2*||w||²
w,b

subject to the constraints (for i = 1, ..., n)

yᵢ*(w*xᵢ - b) >= 1

This is often called the hard-margin SVM model, which is thus a constrained minimization problem, where the unknowns are w and b. We can also omit 1/2 in the function to be minimized, given it's just a constant.

Now, the documentation about Matlab's quadprog states

x = quadprog(H, f, A, b) minimizes 1/2*x'*H*x + f'*x subject to the restrictions A*x ≤ b. A is a matrix of doubles, and b is a vector of doubles.

We can implement the hard-margin SVM model using quadprog function, to get the weight vector w, as follows

H becomes an identity matrix.

f' becomes a zeros matrix.

A is the left-hand side of the constraints

b is equal to -1 because the original constraint had >= 1, it becomes <= -1 when we multiply with -1 on both sides.

Now, I am trying to implement a soft-margin SVM model. The minimization equation here is

min (1/2)*||w||² + C*(∑ ζᵢ)
w,b

subject to the constraints (for i = 1, ..., n)

yᵢ*(w*xᵢ - b) >= 1 - ζᵢ

such that ζᵢ >= 0, where ∑ is the summation symbol, ζᵢ = max(0, 1 - yᵢ*(w*xᵢ - b)) and C is a hyper-parameter.

How can this optimization problem be solved using the Matlab's quadprog function? It's not clear to me how the equation should be mapped to the parameters of the quadprog function.

The "primal" form of the soft-margin SVM model (i.e. the definition above) can be converted to a "dual" form. I did that, and I am able to get the Lagrange variable values (in the dual form). However, I would like to know if I can use quadprog to solve directly the primal form without needing to convert it to the dual form.

Body:
If let z = (w; w0; eps)T be a the long vector with n+1+m elements.(m the number of points)
Then,

H= diag([ones(1,n),zeros(1,m+1)]).
f = [zeros(1; n + 1); ones(1;m)]

The inequality constraints can be specified as :

A = -diag(y)[X; ones(m; 1); zeroes(m;m)] -[zeros(m,n+1),eye(m)],

where X is the n x m input matrix in the primal form.Out of the 2 parts for A, the first part is for w0 and the second part is for eps.

b = ones(m,1)

The equality constraints :

Aeq = zeros(1,n+1 +m)
beq = 0

Bounds:

lb = [-inf*ones(n+1,1); zeros(m,1)]
ub = [inf*ones(n+1+m,1)]

Now, z=quadprog(H,f,A,b,Aeq,beq,lb,ub)


问:
How to set an image path in src attribute using vue 2
İs that possible to give an attribute like that?

```<code>src="${urlPath}/img/icon-{{flight.OperatingAirline._CompanyShortName}}.png"
</code>```

doesn't works.

答:
After edit @SLYcee's answer for JSTL combined solution:</p>

```<code>:src="'${urlPath}/img/icon-' + flight.OperatingAirline._CompanyShortName + '.png'"
</code>```

Body:
İs that possible to give an attribute like that?

src="${urlPath}/img/icon-{{flight.OperatingAirline._CompanyShortName}}.png"

doesn't works.

Body:
After edit @SLYcee's answer for JSTL combined solution:

:src="'${urlPath}/img/icon-' + flight.OperatingAirline._CompanyShortName + '.png'"


问:
Can I create a value for a missing tag in XPath?
I have an application which extracts data from an XML file using XPath. If a node in that XML source file is missing I want to return the value "N/A" (much like the Oracle NVL function). The trick is that the application doesn't support XSLT; I'd like to do this using XPath and XPath alone.

Is that possible?

答:
For empty nodes, you need

```<code>boolean(string-length($node))
</code>```

(You can omit the call to number() as the cast from boolean to number is implicit here.)

OwnerDisplayName: JPLemme

Body:
For empty nodes, you need

boolean(string-length($node))

(You can omit the call to number() as the cast from boolean to number is implicit here.)

OwnerDisplayName: jelovirt