问:
Ionic 2 retrying API call with new access token if unauthorized
I have an ionic 2 app that uses access tokens to authenticate to an API. If an access token expires, it can be exchanged for a new access token using a refresh token.

There is a function handling an API call that returns a promise. If the API call initially succeeds, the promise resolves. If there is a 401 (Unauthorized) error returned, I want to make another API call that uses a refresh token to get a new access token. Then, the original API call should be tried again with the new access token and either resolve if the data is received or reject if there was an error.

I currently have the function working as I intend it to. However, this function is very hard to read. I was wondering how I can refactor this to make it smaller and more readable.

```<code>public readAtmospherePrefs() {
return new Promise((resolve, reject) => {

  this.storage.get('email').then((email) => {

    this.storage.get('token').then((token) => {

      let headers = new Headers();
      headers.append('Authorization', token);
      headers.append('Content-Type', 'application/json');

      let options = new RequestOptions({ headers: headers, search: new URLSearchParams("email=" + email) });

      //Attempt to get data
      this.http.get('api/users/preferences/atmosphere', options).subscribe(res => {
          let data = res.json();

          resolve(data);
          resolve(res.json());
        }, (err) => {
          let error = err;

          //Need to send email and refresh the token if unauthorized
          if(err.status === 401){
            this.storage.get('refreshToken').then((refreshToken) => {
              let body = { email: email, refreshToken: refreshToken}
              let headers2 = new Headers();

              headers2.append('Content-Type', 'application/json');

              //get new access token using the refresh token
              let options2 = new RequestOptions({ headers: headers2});
              this.http.post('api/users/token', body, options2)
              .subscribe(res => {
                let data = res.json();
                let newToken = data.token;
                //set new access token in storage
                this.storage.set('token', newToken).then((newToken) => {
                      let headers3 = new Headers();
                      headers3.append('Authorization', newToken);
                      headers3.append('Content-Type', 'application/json');

                      //retry call with new access token
                      let options = new RequestOptions({ headers: headers3, search: new URLSearchParams("email=" + email) });
                      this.http.get('api/users/preferences/atmosphere', options).subscribe(res => {
                          let data = res.json();

                          resolve(data);
                          resolve(res.json());
                        },
                      (err) => {
                        reject(err);
                      });
                    });

                  }, (err) => {

                reject(err);
              });

            });

          }
          else{
              console.log(error);
              reject(err);
          }

        });
    });

  });

});

  }
</code>```

答:
Why not check your token state before you call?

You can use angular2-jwt to check expire state of your token before you retry. Angular2-jwt

Add a function like these:

```<code>loggedIn(token) {
  return tokenNotExpired(null,token);
 }
</code>```

Your get request should be like this

```<code>    if(!this.loggedIn(token))
        {
             //reset refresh token
         }
   // your plain & simple get request
</code>```

No need to retry.Thanks

Body:
I have an ionic 2 app that uses access tokens to authenticate to an API. If an access token expires, it can be exchanged for a new access token using a refresh token.

There is a function handling an API call that returns a promise. If the API call initially succeeds, the promise resolves. If there is a 401 (Unauthorized) error returned, I want to make another API call that uses a refresh token to get a new access token. Then, the original API call should be tried again with the new access token and either resolve if the data is received or reject if there was an error.

I currently have the function working as I intend it to. However, this function is very hard to read. I was wondering how I can refactor this to make it smaller and more readable.

public readAtmospherePrefs() {
return new Promise((resolve, reject) => {

  this.storage.get('email').then((email) => {

    this.storage.get('token').then((token) => {

      let headers = new Headers();
      headers.append('Authorization', token);
      headers.append('Content-Type', 'application/json');

      let options = new RequestOptions({ headers: headers, search: new URLSearchParams("email=" + email) });

      //Attempt to get data
      this.http.get('api/users/preferences/atmosphere', options).subscribe(res => {
          let data = res.json();

          resolve(data);
          resolve(res.json());
        }, (err) => {
          let error = err;

          //Need to send email and refresh the token if unauthorized
          if(err.status === 401){
            this.storage.get('refreshToken').then((refreshToken) => {
              let body = { email: email, refreshToken: refreshToken}
              let headers2 = new Headers();

              headers2.append('Content-Type', 'application/json');

              //get new access token using the refresh token
              let options2 = new RequestOptions({ headers: headers2});
              this.http.post('api/users/token', body, options2)
              .subscribe(res => {
                let data = res.json();
                let newToken = data.token;
                //set new access token in storage
                this.storage.set('token', newToken).then((newToken) => {
                      let headers3 = new Headers();
                      headers3.append('Authorization', newToken);
                      headers3.append('Content-Type', 'application/json');

                      //retry call with new access token
                      let options = new RequestOptions({ headers: headers3, search: new URLSearchParams("email=" + email) });
                      this.http.get('api/users/preferences/atmosphere', options).subscribe(res => {
                          let data = res.json();

                          resolve(data);
                          resolve(res.json());
                        },
                      (err) => {
                        reject(err);
                      });
                    });

                  }, (err) => {

                reject(err);
              });

            });

          }
          else{
              console.log(error);
              reject(err);
          }

        });
    });

  });

});

  }

Body:
Why not check your token state before you call?

You can use angular2-jwt to check expire state of your token before you retry. Angular2-jwt

Add a function like these:

loggedIn(token) {
  return tokenNotExpired(null,token);
 }

Your get request should be like this

    if(!this.loggedIn(token))
        {
             //reset refresh token
         }
   // your plain & simple get request

No need to retry.Thanks


来源: stackexchange

问:
Why ImageView is not crossing the relativelayout
I have a ImageView within a RelativeLayout. RelativeLayout Height is fixed as 50dp and ImageView height is bigger that 50dp. I want my ImageView to cross the RelativeLayout.

I attach a screen that i want to implement.

```<code><RelativeLayout
android:id="@+id/btnMenu"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#000000"
            android:clipChildren="false"
            android:clipToPadding="false">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:background="@drawable/home_menu"
                android:layout_alignParentLeft="true"/>

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:background="@drawable/home_logo_bottom"
                android:layout_alignParentRight="true"/>

        </RelativeLayout>
</code>```

答:
Use two relative layouts</p>

```<code><RelativeLayout
  android:id="@+id/parentlayout"
   android:layout_width="match_parent"
   android:layout_height="60dp"
   android:background="#000000">

  <RelativeLayout
  android:id="@+id/btnMenu"
   android:layout_width="match_parent"
   android:layout_height="50dp"
    android:layout_alignParentBottom="true"
     android:background="#000000">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:background="@drawable/home_menu"
            android:layout_alignParentLeft="true"/>

        </RelativeLayout>

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:background="@drawable/home_logo_bottom"
            android:layout_alignParentRight="true"/>

     </RelativeLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a ImageView within a RelativeLayout. RelativeLayout Height is fixed as 50dp and ImageView height is bigger that 50dp. I want my ImageView to cross the RelativeLayout.

I attach a screen that i want to implement.

<RelativeLayout
android:id="@+id/btnMenu"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#000000"
            android:clipChildren="false"
            android:clipToPadding="false">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:background="@drawable/home_menu"
                android:layout_alignParentLeft="true"/>

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:background="@drawable/home_logo_bottom"
                android:layout_alignParentRight="true"/>

        </RelativeLayout>

Body:
Use two relative layouts

<RelativeLayout
  android:id="@+id/parentlayout"
   android:layout_width="match_parent"
   android:layout_height="60dp"
   android:background="#000000">

  <RelativeLayout
  android:id="@+id/btnMenu"
   android:layout_width="match_parent"
   android:layout_height="50dp"
    android:layout_alignParentBottom="true"
     android:background="#000000">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:background="@drawable/home_menu"
            android:layout_alignParentLeft="true"/>

        </RelativeLayout>

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:background="@drawable/home_logo_bottom"
            android:layout_alignParentRight="true"/>

     </RelativeLayout>


问:
Multiple markers - Same coordinates
I'm having some troubles trying to display 2 different markers placed at exactly the same coordinates.

The case is: we are displaying stores, and some of them are placed at the same building (ie. a mall), so, they are different stores but shares the same ubication/coordinates.

Our json source content looks like this:

```<code>  {
     "properties" : {
        "id" : "1",
        "name" : "Store 1"
     },
     "geometry" : {
        "coordinates" : [-70.66667, -33.45],
        "type" : "Point"
     }
  },
  {
     "properties" : {
        "id" : "2",
        "name" : "Store 2"
     },
     "geometry" : {
        "coordinates" : [-70.66667, -33.45],
        "type" : "Point"
     }
  }
</code>```

The thing is, just one of them gets displayed.

My question is, is there an out of the box solution for this use-case? Or should we implement our own solution ?

Thanks in advance!

答:
If you are using the Marker class from mapbox-gl, you can just apply standard CSS transform to offset the marker.

Another solution would be something refered to as "spider marker":

https://bewithjonam.github.io/mapboxgl-spiderifier/docs/index.html

https://github.com/bewithjonam/mapboxgl-spiderifier

Title: Multiple markers - Same coordinates

Body:
I'm having some troubles trying to display 2 different markers placed at exactly the same coordinates.

The case is: we are displaying stores, and some of them are placed at the same building (ie. a mall), so, they are different stores but shares the same ubication/coordinates.

Our json source content looks like this:

  {
     "properties" : {
        "id" : "1",
        "name" : "Store 1"
     },
     "geometry" : {
        "coordinates" : [-70.66667, -33.45],
        "type" : "Point"
     }
  },
  {
     "properties" : {
        "id" : "2",
        "name" : "Store 2"
     },
     "geometry" : {
        "coordinates" : [-70.66667, -33.45],
        "type" : "Point"
     }
  }

The thing is, just one of them gets displayed.

My question is, is there an out of the box solution for this use-case? Or should we implement our own solution ?

Thanks in advance!

ContentLicense: CC BY-SA 4.0


问:
Retrieving Redmine issues via API for several projects and trackers
I would like to retrieve all Redmine issues that belong to a list of projects, and have either one of three trackers.

I was hoping to use query parameters project_id and tracker_id with multiple values. I tried tracker_id=3,1,5 and tracker_id=[1,3,5] as well as tracker_id=1&tracker_id=3&tracker_id=5 (and similar for project_id) but none of them will work.

The API page (http://www.redmine.org/projects/redmine/wiki/Rest_Issues) doesn't give any indication that it's possible.  This might mean that I'd have to make a large number of API calls which may be hard to maintain ...

Any help or pointers are appreciated.

答:
It is not user friendly, but it should work if you try this:</p>

```<code>/issues.json?set_filter=1&type=IssueQuery&f[]=tracker_id&op[tracker_id]=%3D&v[tracker_id][]=1&v[tracker_id][]=3&v[tracker_id][]=5
</code>```

Body:
It is not user friendly, but it should work if you try this:

/issues.json?set_filter=1&type=IssueQuery&f[]=tracker_id&op[tracker_id]=%3D&v[tracker_id][]=1&v[tracker_id][]=3&v[tracker_id][]=5


问:
No module found error while deploying Django
I've installed the django-admin-bootstrapped module in my django application. When I run cat requirements.txt it shows:

```<code>django-admin-bootstrapped==1.6.4
</code>```

However, when I run the application using python manage.py runserver 8000 using virtualenv, it gives me the following error:

```<code>ImportError: No module named django_admin_bootstrapped
</code>```

What I find funny is that this error arises when I run the application from the terminal. However, if I run this app from my IDE (PyCharm), it runs perfectly. Am I missing out on anything?

EDITS:

OS: Ubuntu 12.04
Python: v2.7
Steps to install module:
I used the instructions from this website

If there's any more logs or code that is needed, please let me know. Thanks!

答:
Make sure your module names are the same both in your sitepackage folder and your INSTALLED_APPS in settings.py.

It seems that your module name is "django-admin-bootstrapped" but you set the
INSTALLED_APPS like this:

```<code>    INSTALLED_APPS = [
        'django_admin_bootstrapped',
    ]
</code>```

Body:
I've installed the django-admin-bootstrapped module in my django application. When I run cat requirements.txt it shows:

django-admin-bootstrapped==1.6.4

However, when I run the application using python manage.py runserver 8000 using virtualenv, it gives me the following error:

ImportError: No module named django_admin_bootstrapped

What I find funny is that this error arises when I run the application from the terminal. However, if I run this app from my IDE (PyCharm), it runs perfectly. Am I missing out on anything?

EDITS:

OS: Ubuntu 12.04
Python: v2.7
Steps to install module:
I used the instructions from this website

If there's any more logs or code that is needed, please let me know. Thanks!

Body:
Make sure your module names are the same both in your sitepackage folder and your INSTALLED_APPS in settings.py.

It seems that your module name is "django-admin-bootstrapped" but you set the
INSTALLED_APPS like this:

    INSTALLED_APPS = [
        'django_admin_bootstrapped',
    ]


问:
Rails 3 resource route with param as prefix
My rails 3 app runs in the background of a Apache/mod_proxy server.

In the rails app exists a mandatory prefix :site_pin

In Apache the i have the following to abstract my prefix:

```<code>ServerName example.com

ProxyRequests Off
<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

ProxyPass / http://localhost:3000/site/example/
ProxyPassReverse / http://localhost:3000/site/example/

<Location />
    Order allow,deny
    Allow from all
</Location>
</code>```

In my my routes.rb i have the following:

```<code>resources :products

#RESTful fix
match 'site/:site_pin/:controller/', :action => 'index', :via => [:get]
match 'site/:site_pin/:controller/new', :action => 'new', :via => [:get]
match 'site/:site_pin/:controller/', :action => 'create', :via => [:post]
match 'site/:site_pin/:controller/:id', :action => 'show', :via => [:get]
match 'site/:site_pin/:controller/:id/edit', :action => 'edit', :via => [:get]
match 'site/:site_pin/:controller/:id', :action => 'update', :via => [:put]
match 'site/:site_pin/:controller/:id', :action => 'destroy', :via => [:delete]
</code>```

Everything works fine in this way, but anyone has a better solution for remove this fix and make the routes.rb more clean?

答:
scope would be very effective for this. Replace what you posted above in your routes.rb with:

```<code>scope 'site/:site_pin' do
  resources :products
end
</code>```

Now, run rake:routes in and you should see the following output:

```<code>    products GET    /site/:site_pin/products(.:format)             {:controller=>"products", :action=>"index"}
             POST   /site/:site_pin/products(.:format)             {:controller=>"products", :action=>"create"}
 new_product GET    /site/:site_pin/products/new(.:format)         {:controller=>"products", :action=>"new"}
edit_product GET    /site/:site_pin/products/:id/edit(.:format)    {:controller=>"products", :action=>"edit"}
     product GET    /site/:site_pin/products/:id(.:format)         {:controller=>"products", :action=>"show"}
             PUT    /site/:site_pin/products/:id(.:format)         {:controller=>"products", :action=>"update"}
             DELETE /site/:site_pin/products/:id(.:format)         {:controller=>"products", :action=>"destroy"}
</code>```

:site_pin will be available as params[:site_pin].

Naturally, you'll be able to add other resources and routes into the scope block; all of which will be prefixed with site/:site_pin.

ContentLicense: CC BY-SA 2.5

Body:
My rails 3 app runs in the background of a Apache/mod_proxy server.

In the rails app exists a mandatory prefix :site_pin

In Apache the i have the following to abstract my prefix:

ServerName example.com

ProxyRequests Off
<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

ProxyPass / http://localhost:3000/site/example/
ProxyPassReverse / http://localhost:3000/site/example/

<Location />
    Order allow,deny
    Allow from all
</Location>

In my my routes.rb i have the following:

resources :products

#RESTful fix
match 'site/:site_pin/:controller/', :action => 'index', :via => [:get]
match 'site/:site_pin/:controller/new', :action => 'new', :via => [:get]
match 'site/:site_pin/:controller/', :action => 'create', :via => [:post]
match 'site/:site_pin/:controller/:id', :action => 'show', :via => [:get]
match 'site/:site_pin/:controller/:id/edit', :action => 'edit', :via => [:get]
match 'site/:site_pin/:controller/:id', :action => 'update', :via => [:put]
match 'site/:site_pin/:controller/:id', :action => 'destroy', :via => [:delete]

Everything works fine in this way, but anyone has a better solution for remove this fix and make the routes.rb more clean?

Body:
scope would be very effective for this. Replace what you posted above in your routes.rb with:

scope 'site/:site_pin' do
  resources :products
end

Now, run rake:routes in and you should see the following output:

    products GET    /site/:site_pin/products(.:format)             {:controller=>"products", :action=>"index"}
             POST   /site/:site_pin/products(.:format)             {:controller=>"products", :action=>"create"}
 new_product GET    /site/:site_pin/products/new(.:format)         {:controller=>"products", :action=>"new"}
edit_product GET    /site/:site_pin/products/:id/edit(.:format)    {:controller=>"products", :action=>"edit"}
     product GET    /site/:site_pin/products/:id(.:format)         {:controller=>"products", :action=>"show"}
             PUT    /site/:site_pin/products/:id(.:format)         {:controller=>"products", :action=>"update"}
             DELETE /site/:site_pin/products/:id(.:format)         {:controller=>"products", :action=>"destroy"}

:site_pin will be available as params[:site_pin].

Naturally, you'll be able to add other resources and routes into the scope block; all of which will be prefixed with site/:site_pin.


问:
Clustered Index - Trade-off Query VS Insert?
I'm working on improving database performance of my application and now it comes to the part of clustered index. I don't have experience with it so I would like to ask.

My application caveats

In my application I have the concept of Show.

This means that a user can create/open a Show and then it will access only the objects related to that Show (Actors, clothes, items, etc).
So it is really commom to have queries using "...WHERE ShowId = X"

Also we do have quite a lot of inserts because of integrations (we have a job running daily that would get +/- 30k new rows to the database, all in the same Show) and deletions are not that commom... The user may delete a Show (which is really taking quite a long time).

The usage of the application is usually like:

User creates a Show based on a "Master Show" (which copies a lot of data changing only the ShowId)

User navigates around some screens to check this data

User calls an algorithm that proccess the input of this show and generate a lot of outputs (30k+ inserts again, on the same show)

User analyses these outputs

The question

Based on that, I thought that the best clustered key would be on [ ShowId, id ] for every table. But then, reading this documentation, I have doubts if this wouldn't make it worse given the number of inserts or if, because the inserts are made on the same ShowId, it would be ok.

I don't have access to the PRD database nor to a copy of it for testing. I tested with the dev database but it is so small it didn't seem to have any impact at all.

Can someone help?

答:
It's difficult to give you an answer without more information.  You should consider to post tables structure too.

It's true that for every index you add, you will generate an overhead on insert.  But if you need to use "WHERE SHOWID=..." you will have a strong positive impact for your SELECT in this case (on a large table, and considering SHOWID very selective, ie a few records over a lot of records of the whole table).

You said:

"I don't have access to the PRD database nor to a copy of it for
  testing. I tested with the dev database but it is so small it didn't
  seem to have any impact at all."

But you can use execution plan to see how a query will use your index / table.  Moreover you could quite easily generate multiple random records to make your tests.


问:
How to select an element by it's text with Puppeteer and Headless Chrome
If I have a button that looks like this:

```<code><button type="button" class="list-group-item" style="cursor: pointer;">Button Text</button>
</code>```

I'm trying to click it with:

```<code>await page.click(<button selector>)
</code>```

I can't use the full selector I get if I copy selector from Chrome dev tools because the exact selector can change. Is there a way I can select a button based on what it's text is? For example:

```<code>await page.click('Button Text')
</code>```

I'm also not using JQuery, so please keep that in mind.

答:
Without jQuery and maybe also a bit less overhead, you could use this:</p>

```<code>window.find("Button Text", true, false, true)
? [window.getSelection()].map(_ => _.anchorNode).map(_ => _.childNodes.length
  ? _.click()
  : _.parentElement.click()
) : undefined;
</code>```

Body:
If I have a button that looks like this:

<button type="button" class="list-group-item" style="cursor: pointer;">Button Text</button>

I'm trying to click it with:

await page.click(<button selector>)

I can't use the full selector I get if I copy selector from Chrome dev tools because the exact selector can change. Is there a way I can select a button based on what it's text is? For example:

await page.click('Button Text')

I'm also not using JQuery, so please keep that in mind.

Body:
Without jQuery and maybe also a bit less overhead, you could use this:

window.find("Button Text", true, false, true)
? [window.getSelection()].map(_ => _.anchorNode).map(_ => _.childNodes.length
  ? _.click()
  : _.parentElement.click()
) : undefined;


问:
In MediaWiki: Check if user account is blocked within page
In MediaWiki I'd like to create a page that links to a user account. As we use blocking in order to deactivate user accounts (as there is no other way provided to achieve this) it would be nice to present a note next to a link if the account has been blocked. Therefor I require some way to distinguish between different states of a user account.

Therefor my question: Is there a parser function or some other kind of instrument to detect if a user account is blocked? I can't find one. Or is there some other way how to achieve this functionality within a page?

Note: Deleting a user page is not an option. There is an {{#ifexist}} parser function which could check for existence of a page but I do not want to delete the user pages and do not want to confuse admins. The "user-is-blocked" flag is the only thing available that we could perform some kind of branching on. Do you have any ideas how to accomplish this?

答: You could add an extra class to the username link in the HtmlPageLinkRendererEnd hook. See this patch for something similar (except that it adds the class for links outside the page content).</p>


问:
ORDER BY with different WHERE condition
Here is illustrated scenario for my problem.

```<code>SELECT field
FROM myTable
WHERE field1 = 'abc' AND filed2 = 'xyz' AND field3 = 'pqr'
ORDER BY field4 ASC
</code>```

This query give me result as:

```<code>result1
result2
result3
</code>```

Now if I run following query, then

```<code>SELECT field
FROM myTable
WHERE field1 = 'xxx' AND field2 = 'xyz'
ORDER BY field4 ASC

result2
result3
result1
</code>```

So, basically both query give same results but with different order. But I want result from first query with second query's ORDER BY. See both have different condition on field1. Everything else is same.

答:
You could add a sub query of the 2nd statement into the 1st like below and order on that.</p>

```<code>SELECT t1.field,
(SELECT top 1 t2.field4
    FROM myTable t2
    WHERE t2.field1 = 'xxx' AND t2.field2 = 'xyz'
    AND t2.field = t1.field) as orderField
FROM myTable t1
WHERE t1.field1 = 'abc' AND t1.filed2 = 'xyz' AND t1.field3 = 'pqr'
ORDER BY orderField ASC
</code>```

Title: ORDER BY with different WHERE condition

Body:
Here is illustrated scenario for my problem.

SELECT field
FROM myTable
WHERE field1 = 'abc' AND filed2 = 'xyz' AND field3 = 'pqr'
ORDER BY field4 ASC

This query give me result as:

result1
result2
result3

Now if I run following query, then

SELECT field
FROM myTable
WHERE field1 = 'xxx' AND field2 = 'xyz'
ORDER BY field4 ASC

result2
result3
result1

So, basically both query give same results but with different order. But I want result from first query with second query's ORDER BY. See both have different condition on field1. Everything else is same.

Body:
You could add a sub query of the 2nd statement into the 1st like below and order on that.

SELECT t1.field,
(SELECT top 1 t2.field4
    FROM myTable t2
    WHERE t2.field1 = 'xxx' AND t2.field2 = 'xyz'
    AND t2.field = t1.field) as orderField
FROM myTable t1
WHERE t1.field1 = 'abc' AND t1.filed2 = 'xyz' AND t1.field3 = 'pqr'
ORDER BY orderField ASC


问:
MVC Model require true
Is there a way through data annotations to require that a boolean property be set to true?</p>

```<code>public class MyAwesomeObj{
    public bool ThisMustBeTrue{get;set;}
}
</code>```

答:
I don't know of a way through DataAnnotations, but this is easily done in your controller.

```<code>public ActionResult Add(Domain.Something model)
{

    if (!model.MyCheckBox)
        ModelState.AddModelError("MyCheckBox", "You forgot to click accept");

    if (ModelState.IsValid) {
        //'# do your stuff
    }

}
</code>```

The only other option would be to build a custom validator for the server side and a remote validator for the client side (remote validation is only available in MVC3+)

Title: MVC Model require true

Body:
Is there a way through data annotations to require that a boolean property be set to true?

public class MyAwesomeObj{
    public bool ThisMustBeTrue{get;set;}
}

Body:
I don't know of a way through DataAnnotations, but this is easily done in your controller.

public ActionResult Add(Domain.Something model)
{

    if (!model.MyCheckBox)
        ModelState.AddModelError("MyCheckBox", "You forgot to click accept");

    if (ModelState.IsValid) {
        //'# do your stuff
    }

}

The only other option would be to build a custom validator for the server side and a remote validator for the client side (remote validation is only available in MVC3+)


问:
How to trigger an action once with a jQuery queue() loop
I have a jQuery object with a number of elements, e.g. $('.items'). I have these items going through some processing inside a queue(), and depending on conditions, I want to change a variable. After the queue has completed, I want to check that variable and trigger an event. My issue is that checking the variable and doing something inside the queue will fire multiple times (for each node in the jQuery object being looped through), and doing this outside the queue happens before the queue finishes, so it's not catching the variable update.

For example:

```<code>var triggered = false;

$('.items').addClass('doing-things').delay(500).queue(function(next) {
  // Do some things
  console.log('Things are happening');
  // Check conditions and change variable
  if ( someCondition ) {
    triggered = true;
  }
  // Finished doing things
  $(this).removeClass('doing-things');
  next();
}).queue(function(next) {
  // Check inside queue
  if ( triggered ) {
    // This will be fired repeatedly in the loop, $('.items').length number of times
    console.log(triggered);
  }
  next();
});

// Check after queue
if ( triggered ) {
  // This will fire once, but will be false, because it will fire before the queue finishes (with delays)
  console.log(triggered);
}
</code>```

Can anyone point me towards how I can update the triggered variable inside the queue, then check it and fire an event (or in this example, do console.log(triggered)) only once?

Edit: Example fiddle here for debugging.

答:
Rather than simply checking for triggered to be true, you wait for triggered to be true

Demo

var triggered = false,
  $test1 = $('#test1'),
    $test2 = $('#test2');

$('.item').addClass('doing-things').delay(1000).queue(function(next) {
  // Do some things
  console.log('Things are happening');
  // Check a condition and change variable
  if ( !triggered ) {
    triggered = true;
  }
  // Finished doing things
  $(this).removeClass('doing-things');
  next();
}).queue(function(next) {
  // Check inside queue
  if ( triggered ) {
    // This will be fired repeatedly in the loop, $('.items').length number of times
    $test1.append('
Fired
');
  }
  next();
});
triggerEvent();

function triggerEvent ()
{
   if( !triggered )
   {
     setTimeout( triggerEvent, 1000 );
   }
   else
   {
       $test2.append('
Fired
');
   }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.item {
  padding: 10px;
  margin: 10px;
  border: 2px solid #aaa;
}

.item.doing-things {
  border-color: #f00;
}

.test {
  padding: 20px;
  margin: 10px;
  background: #fff;
}

#test1 {
  border: 2px solid #0f0;
}

#test2 {
  border: 2px solid #00f;
}</code>```

A

B

C

D

```

Body:
I have a jQuery object with a number of elements, e.g. $('.items'). I have these items going through some processing inside a queue(), and depending on conditions, I want to change a variable. After the queue has completed, I want to check that variable and trigger an event. My issue is that checking the variable and doing something inside the queue will fire multiple times (for each node in the jQuery object being looped through), and doing this outside the queue happens before the queue finishes, so it's not catching the variable update.

For example:

var triggered = false;

$('.items').addClass('doing-things').delay(500).queue(function(next) {
  // Do some things
  console.log('Things are happening');
  // Check conditions and change variable
  if ( someCondition ) {
    triggered = true;
  }
  // Finished doing things
  $(this).removeClass('doing-things');
  next();
}).queue(function(next) {
  // Check inside queue
  if ( triggered ) {
    // This will be fired repeatedly in the loop, $('.items').length number of times
    console.log(triggered);
  }
  next();
});

// Check after queue
if ( triggered ) {
  // This will fire once, but will be false, because it will fire before the queue finishes (with delays)
  console.log(triggered);
}

Can anyone point me towards how I can update the triggered variable inside the queue, then check it and fire an event (or in this example, do console.log(triggered)) only once?

Edit: Example fiddle here for debugging.

Body:
Rather than simply checking for triggered to be true, you wait for triggered to be true

Demo

var triggered = false,
  $test1 = $('#test1'),
    $test2 = $('#test2');

$('.item').addClass('doing-things').delay(1000).queue(function(next) {
  // Do some things
  console.log('Things are happening');
  // Check a condition and change variable
  if ( !triggered ) {
    triggered = true;
  }
  // Finished doing things
  $(this).removeClass('doing-things');
  next();
}).queue(function(next) {
  // Check inside queue
  if ( triggered ) {
    // This will be fired repeatedly in the loop, $('.items').length number of times
    $test1.append('<div>Fired</div>');
  }
  next();
});
triggerEvent();

function triggerEvent ()
{
   if( !triggered )
   {
     setTimeout( triggerEvent, 1000 );
   }
   else
   {
       $test2.append('<div>Fired</div>');
   }
}

.item {
  padding: 10px;
  margin: 10px;
  border: 2px solid #aaa;
}

.item.doing-things {
  border-color: #f00;
}

.test {
  padding: 20px;
  margin: 10px;
  background: #fff;
}

#test1 {
  border: 2px solid #0f0;
}

#test2 {
  border: 2px solid #00f;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">A</div>
<div class="item">B</div>
<div class="item">C</div>
<div class="item">D</div>

<div id="test1" class="test"></div>
<div id="test2" class="test"></div>


问:
how to modify firefox Quantum dev tool fonts?
Today, I update my Firefox browser to Firefox Quantum. But when I want to debug my web app,the Dev tool font is very small. Is there any way to adjust???

firefox dev tool font screenshot

答:
To Increase the font size of the dev tools  press ctrl++ and to decrease the font size press ctrl+-.

Note: Make sure that the focus is on dev tools.


问:
Disabling a form based on the other form's input
I am currently working on 2 drop down forms, say form1 and form2. I have a certain list of values in form1 clicking which form2 would be disabled and for some it would not be disabled. I am working on Angular 4 with TypeScript. Any place where I could start figuring out how to achieve this?

Below is my form code

```<code>  <div class="form-group" style="width: 350px">
      <label for="form_periodicity"><b>Periodicity</b></label><br>
      <select class="form-control" id="periodicity" style="width: 222px">
        <option>EOD</option>
        <option>Daily</option>
        <option>Weekly</option>
        <option>Monthly</option>
        <option>Strict run</option>
      </select>
  </div>
  <div class="form-group" style="width: 350px">
      <label for="form_timeofexecution"><b>Time of execution</b></label><br>
      <select class="form-control" id="timeofexecution" style="width: 222px">
        <option>0:00</option>
        <option>0:30</option>
        <option>1:00</option>
        <option>4:00</option>
        <option>5:00</option>
      </select>
  </div>
</code>```

So I want to disable the second form group when Strict run is selected from the first form.

答:
In first select you can fire an function which will work on change event like this

```<code><select class="form-control" id="periodicity" (change)="onChange($event)" style="width: 222px">
  <option>EOD</option>
  <option>Daily</option>
  <option>Weekly</option>
  <option>Monthly</option>
  <option value="0">Strict run</option>
</select>
</code>```

and in ts file define a boolean variable and change its value on change event like this

```<code>disableSelect:bolean
 onChange(e){
 let chosen= parseInt((<HTMLSelectElement>e.srcElement).value);
 if(chosen.value==0){
  this.disableSelect=true;
   return;
 }
this.disableSelect=false;
}
</code>```

and in your second select bind that boolean variable like this

```<code><select class="form-control" id="dayofexecution" [disabled]="disableSelect" style="width: 222px">
</code>```

Body:
I am currently working on 2 drop down forms, say form1 and form2. I have a certain list of values in form1 clicking which form2 would be disabled and for some it would not be disabled. I am working on Angular 4 with TypeScript. Any place where I could start figuring out how to achieve this?

Below is my form code

      Periodicity

      <select class="form-control" id="periodicity" style="width: 222px">
        <option>EOD</option>
        <option>Daily</option>
        <option>Weekly</option>
        <option>Monthly</option>
        <option>Strict run</option>
      </select>

      Time of execution

      <select class="form-control" id="timeofexecution" style="width: 222px">
        <option>0:00</option>
        <option>0:30</option>
        <option>1:00</option>
        <option>4:00</option>
        <option>5:00</option>
      </select>

So I want to disable the second form group when Strict run is selected from the first form.

Body:
In first select you can fire an function which will work on change event like this

<select class="form-control" id="periodicity" (change)="onChange($event)" style="width: 222px">
  <option>EOD</option>
  <option>Daily</option>
  <option>Weekly</option>
  <option>Monthly</option>
  <option value="0">Strict run</option>
</select>

and in ts file define a boolean variable and change its value on change event like this

disableSelect:bolean
 onChange(e){
 let chosen= parseInt((<HTMLSelectElement>e.srcElement).value);
 if(chosen.value==0){
  this.disableSelect=true;
   return;
 }
this.disableSelect=false;
}

and in your second select bind that boolean variable like this

<select class="form-control" id="dayofexecution" [disabled]="disableSelect" style="width: 222px">


问:
Understanding input and labels in word2vec (TensorFlow)
I am trying to properly understand the batch_input and batch_labels from the tensorflow "Vector Representations of Words" tutorial.

For instance, my data

```<code> 1 1 1 1 1 1 1 1 5 251 371 371 1685 ...
</code>```

... starts with

```<code>skip_window = 2 # How many words to consider left and right.
num_skips = 1 # How many times to reuse an input to generate a label.
</code>```

Then the generated input array is:

```<code>bach_input = 1 1 1 1 1 1 5 251 371 ....
</code>```

This makes sense, starts from after 2 (= window size) and then continuous. The labels:

```<code>batch_labels = 1 1 1 1 1 1 251 1 1685 371 589 ...
</code>```

I don't understand these labels very well. There are supposed to be 4 labels for each input right (window size 2, on each side). But the batch_label variable is the same length.

From the tensorflow tutorial:

The skip-gram model takes two inputs. One is a batch full of integers
  representing the source context words, the other is for the target
  words.

As per the tutorial, I have declared the two variables as:

```<code>  batch = np.ndarray(shape=(batch_size), dtype=np.int32)
  labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
</code>```

How should I interpret the batch_labels?

答:
There are supposed to be 4 labels for each input right (window size 2, on each side). But the batch_label variable is the same length.

The key setting is num_skips = 1. This value defines the number of (input, label) tuples each word generates. See the examples with different num_skips below (my data sequence seems to be different from yours, sorry about that).

Example #1 - num_skips=4

batch, labels = generate_batch(batch_size=8, num_skips=4, skip_window=2)
```

<p>It generates 4 labels for each word, i.e. uses the whole context; since <code>batch_size=8</code> only 2 words are processed in this batch (<em>12</em> and <em>6</em>), the rest will go into the next batch:</p>

<pre class="lang-py prettyprint-override"><code>data = [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156, 128, 742, 477, 10572, ...]
batch = [12 12 12 12  6  6  6  6]
labels = [[6 3084 5239 195 195 3084 12 2]]
</code>```

Example #2 - num_skips=2

batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=2)
```

<p>Here you would expect each word appear twice in the <code>batch</code> sequence; the 2 labels are randomly sampled from 4 possible words:</p>

<pre class="lang-py prettyprint-override"><code>data = [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156, 128, 742, 477, 10572, ...]
batch = [ 12  12   6   6 195 195   2   2]
labels = [[ 195 3084   12  195 3137   12   46  195]]
</code>```

Example #3 - num_skips=1

batch, labels = generate_batch(batch_size=8, num_skips=1, skip_window=2)
```

<p>Finally, this setting, same as yours, produces exactly one label per each word; each label is drawn randomly from the 4-word context:</p>

<pre class="lang-py prettyprint-override"><code>data = [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156, 128, 742, 477, 10572, ...]
batch = [  12    6  195    2 3137   46   59  156]
labels = [[  6  12  12 195  59 156  46  46]]
</code>```

How should I interpret the batch_labels?

Each label is the center word to be predicted from the context. But the generated data may take not all (context, center) tuples, depending on the settings of the generator.

Also note that the train_labels tensor is 1-dimensional. Skip-Gram trains the model to predict any context word from the given center word, not all 4 context words at once. This explains why all training pairs (12, 6), (12, 3084), (12, 5239) and (12, 195) are valid.

Body:
I am trying to properly understand the batch_input and batch_labels from the tensorflow "Vector Representations of Words" tutorial.

For instance, my data

 1 1 1 1 1 1 1 1 5 251 371 371 1685 ...

... starts with

skip_window = 2 # How many words to consider left and right.
num_skips = 1 # How many times to reuse an input to generate a label.

Then the generated input array is:

bach_input = 1 1 1 1 1 1 5 251 371 ....

This makes sense, starts from after 2 (= window size) and then continuous. The labels:

batch_labels = 1 1 1 1 1 1 251 1 1685 371 589 ...

I don't understand these labels very well. There are supposed to be 4 labels for each input right (window size 2, on each side). But the batch_label variable is the same length.

From the tensorflow tutorial:

The skip-gram model takes two inputs. One is a batch full of integers
  representing the source context words, the other is for the target
  words.

As per the tutorial, I have declared the two variables as:

  batch = np.ndarray(shape=(batch_size), dtype=np.int32)
  labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)

How should I interpret the batch_labels?

Body:
There are supposed to be 4 labels for each input right (window size 2, on each side). But the batch_label variable is the same length.

The key setting is num_skips = 1. This value defines the number of (input, label) tuples each word generates. See the examples with different num_skips below (my data sequence seems to be different from yours, sorry about that).

Example #1 - num_skips=4

batch, labels = generate_batch(batch_size=8, num_skips=4, skip_window=2)

It generates 4 labels for each word, i.e. uses the whole context; since batch_size=8 only 2 words are processed in this batch (12 and 6), the rest will go into the next batch:

data = [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156, 128, 742, 477, 10572, ...]
batch = [12 12 12 12  6  6  6  6]
labels = [[6 3084 5239 195 195 3084 12 2]]

Example #2 - num_skips=2

batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=2)

Here you would expect each word appear twice in the batch sequence; the 2 labels are randomly sampled from 4 possible words:

data = [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156, 128, 742, 477, 10572, ...]
batch = [ 12  12   6   6 195 195   2   2]
labels = [[ 195 3084   12  195 3137   12   46  195]]

Example #3 - num_skips=1

batch, labels = generate_batch(batch_size=8, num_skips=1, skip_window=2)

Finally, this setting, same as yours, produces exactly one label per each word; each label is drawn randomly from the 4-word context:

data = [5239, 3084, 12, 6, 195, 2, 3137, 46, 59, 156, 128, 742, 477, 10572, ...]
batch = [  12    6  195    2 3137   46   59  156]
labels = [[  6  12  12 195  59 156  46  46]]

How should I interpret the batch_labels?

Each label is the center word to be predicted from the context. But the generated data may take not all (context, center) tuples, depending on the settings of the generator.

Also note that the train_labels tensor is 1-dimensional. Skip-Gram trains the model to predict any context word from the given center word, not all 4 context words at once. This explains why all training pairs (12, 6), (12, 3084), (12, 5239) and (12, 195) are valid.


问:
create csv file using Spring MVC
I Need to create a CSV file using JAVA.

Earlier I created excel file using HSSFBook from Apache POI, and from SPRING support I used AbstarctExcelView.buildExcelDocument().

Similarly, want to ask is there any predefined class like HSSFBook from Apache POI (or from any vendor) to create a csv file. And their spring supports like  AbstarctExcelView class.

答: Try Super CSV ,this has POJO support. You can easily create the csv using your pojos. I prefer this than Apache POI. https://super-csv.github.io/super-csv/examples_writing.html</p>

Title: create csv file using Spring MVC


问:
When is an extension required in workbook name?
I have a directory of excel files that interact with each other through VBA code in a master file.

I've never had a problem with this before, but after copying the whole directory to do some development work on the copy (keeping the original intact in a different location) I'm running into a "subscript out of range" problem when referencing the workbook.

For example, everything ran fine previously with this line of code (nothing in the actual code has been changed):

Code that now throws an error (never used to):

```<code>ScheduleLocation = Workbooks("Master Schedule").Path
</code>```

However, this line now throws an error. If I replace "Master Schedule" with "Master Schedule.xlsm" everything works again. I've had this problem before, but I've never been able to put a finger on the root cause of the problem.

Code that doesn't throw an error:

```<code>ScheduleLocation = Workbooks("Master Schedule.xlsm").Path
</code>```

Hence my question: why is this? Why would the name (without extension) be insufficient sometimes, and sometimes not?

答:
Have you got "Show file extension of known file types" turned on in windows explorer?
Try to run the code with hidden and visible extensions.

It is good practice to assign the workbook to variable on open.

```<code>Dim wbInput as Workbook
Set wbInput = Workbooks.open ("C:\Master Schedule.xslx")
</code>```

Now you can work on variable without caring about the system settings for extensions.

Body:
I have a directory of excel files that interact with each other through VBA code in a master file.

I've never had a problem with this before, but after copying the whole directory to do some development work on the copy (keeping the original intact in a different location) I'm running into a "subscript out of range" problem when referencing the workbook.

For example, everything ran fine previously with this line of code (nothing in the actual code has been changed):

Code that now throws an error (never used to):

ScheduleLocation = Workbooks("Master Schedule").Path

However, this line now throws an error. If I replace "Master Schedule" with "Master Schedule.xlsm" everything works again. I've had this problem before, but I've never been able to put a finger on the root cause of the problem.

Code that doesn't throw an error:

ScheduleLocation = Workbooks("Master Schedule.xlsm").Path

Hence my question: why is this? Why would the name (without extension) be insufficient sometimes, and sometimes not?

Body:
Have you got "Show file extension of known file types" turned on in windows explorer?
Try to run the code with hidden and visible extensions.

It is good practice to assign the workbook to variable on open.

Dim wbInput as Workbook
Set wbInput = Workbooks.open ("C:\Master Schedule.xslx")

Now you can work on variable without caring about the system settings for extensions.


问:
optimization - stepping may behave oddly; variables may not be available in Xcode 9.1
When i put debug point in project i get this one error

App Name was compiled with optimization - stepping may behave oddly;
  variables may not be available.

And Also i don't get debug point and xcode not print any log.

If anyone know solution please share.

答:
You are receiving this message because you set your target's optimization level to one of the Fast options.

Set the Optimization Level to None while debugging to make the message go away and your break points behave normally:


问:
how to 100 text field in table view ios swift
number of cell  in table view 100
and every cell having a text field and when ever  i am scrolling value should be present in text box . and one another LABEL show no OF index in Table view .</p>

答:
create data module class as below

```<code>class Data {
   var text:String?
}
</code>```

then add 100 objects in array and load tableview from array.
Now create custom cell & take reference of textfield in custom cell class. Implement observer for text change on textField in this class.

Now write function as below in custom cell

```<code>func configureCell(data:Data){

}
</code>```

call this function from cell for row at index path pass object at current index in this function.

Now declare local variable in custom cell which will hold reference of then object as below.

```<code>var data:Data?

func configureCell(data:Data){
self.data = data
 self.textField.text = data.text
}
</code>```

now in text did change method update text in data.text property

```<code>func textFieldDidChangeText(textField:UITextField){
    self.data.text =  textField.text
}
</code>```

set textField text to data.text, so value will be retained even you scroll the application

Body:
create data module class as below

class Data {
   var text:String?
}

then add 100 objects in array and load tableview from array.
Now create custom cell & take reference of textfield in custom cell class. Implement observer for text change on textField in this class.

Now write function as below in custom cell

func configureCell(data:Data){

}

call this function from cell for row at index path pass object at current index in this function.

Now declare local variable in custom cell which will hold reference of then object as below.

var data:Data?

func configureCell(data:Data){
self.data = data
 self.textField.text = data.text
}

now in text did change method update text in data.text property

func textFieldDidChangeText(textField:UITextField){
    self.data.text =  textField.text
}

set textField text to data.text, so value will be retained even you scroll the application


问:
Can't use Bootstrap in PHP file
I'm fetching some data from a MySQL database onto a WebPage. I came up with a simple PHP page that queries the database and shows the query in the form of a table and it works just fine.

However, when I try to add bootstrap to the page and style it, the entire page stops working.

Here's my index.php

```<code><!DOCTYPE html>
<html>
<head>
<title>MakersBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<center>
<h1>Sensor Testing Dashboard</h1>
<div class="container">
<?php
echo "<table class='table table-hover' align=center>";
 echo "<thead><tr><th>Sensor Id</th><th>Temperature</th><th>Light</th><th>Last Updated</th></tr></thead>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
}

$servername = "localhost";
$username = "root";
$password = "paanikiboond";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM sensor ORDER BY LastUpdate DESC LIMIT 1");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
</div>

$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>

</body>
</html>
</code>```

Any idea what I may be doing wrong here?

答:
First, I think you must separte properly your HTML, and your PHP.

In your code, mixte HTML tag + HTML tag from PHP code in your HTML body is... not too regulatory. And very difficult to maintain.

You can, create an architecture like that :

```<code><?php
    // Create connexion, and get your results.
    $connexion = new PDO();
    $results = [];
?>

<!DOCTYPE html>
<html>
    <head>
        <!-- Your link and scripts-->
    </head>
    <body>
        <h1></h1>
        <div>
           <?php if (!empty($results){ ?>
           <table class='table table-hover'>
               <!-- Show your results. -->
               <? foreach($results as $result)
                  {

                  }
               ?>
           </table>
           <?php }else{
               echo 'no results found';
             }
           ?>
        </div>
    </body>
</html>
</code>```

Also, Boostrap is a Javascript library, It doesn't work directly on PHP, but it read the HTML structure, with your elements and their classes. If your javascript is loaded, and your structure is well done, that work! You have samples and documentation of Boostrtap here;

In your code you forgotten to close your  element and you've a problem in this lines :

```<code>echo "</table>";  // that is PHP, but PHP is not close with `?>`

</div> <!-- That is HTML but in PHP code witouth `echo ''` -->
</code>```

If PHP and HTML has well separted, you will have fewer problems of forgetting :D You have many links in Internet for understand this good practise

PS : don't forgot to code with proper line indentions: it's much more readable:

```<code><html>
<head> <!-- Very difficult to see we havn't a </head> close tag -->
<body>
<div>
My content
</div>
</body>
</html>

<html>
    <head> <!-- Very easy to see we havn't a </head> close tag -->
    <body>
        <div>
            My content
        </div>
    </body>
</html>
</code>```

Hope I help you.

Title: Can't use Bootstrap in PHP file

Body:
I'm fetching some data from a MySQL database onto a WebPage. I came up with a simple PHP page that queries the database and shows the query in the form of a table and it works just fine.

However, when I try to add bootstrap to the page and style it, the entire page stops working.

Here's my index.php

<!DOCTYPE html>

<title>MakersBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Sensor Testing Dashboard

<?php
echo "
";
 echo "

Sensor Id	Temperature	Light	Last Updated

";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "" . parent::current(). "	";
    }

    function beginChildren() {
        echo "
";
    }

    function endChildren() {
        echo "
" . "\n";
    }
}

$servername = "localhost";
$username = "root";
$password = "paanikiboond";
$dbname = "testbox1";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM sensor ORDER BY LastUpdate DESC LIMIT 1");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "
";

$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>

Any idea what I may be doing wrong here?

Body:
First, I think you must separte properly your HTML, and your PHP.

In your code, mixte HTML tag + HTML tag from PHP code in your HTML body is... not too regulatory. And very difficult to maintain.

You can, create an architecture like that :

<?php
    // Create connexion, and get your results.
    $connexion = new PDO();
    $results = [];
?>

<!DOCTYPE html>
<html>
    <head>
        <!-- Your link and scripts-->
    </head>
    <body>
        <h1></h1>
        <div>
           <?php if (!empty($results){ ?>
           <table class='table table-hover'>
               <!-- Show your results. -->
               <? foreach($results as $result)
                  {

                  }
               ?>
           </table>
           <?php }else{
               echo 'no results found';
             }
           ?>
        </div>
    </body>
</html>

Also, Boostrap is a Javascript library, It doesn't work directly on PHP, but it read the HTML structure, with your elements and their classes. If your javascript is loaded, and your structure is well done, that work! You have samples and documentation of Boostrtap here;

In your code you forgotten to close your <head></head> element and you've a problem in this lines :

echo "</table>";  // that is PHP, but PHP is not close with `?>`

</div> <!-- That is HTML but in PHP code witouth `echo ''` -->

If PHP and HTML has well separted, you will have fewer problems of forgetting :D You have many links in Internet for understand this good practise

PS : don't forgot to code with proper line indentions: it's much more readable:

<html>
<head> <!-- Very difficult to see we havn't a </head> close tag -->
<body>
<div>
My content
</div>
</body>
</html>

<html>
    <head> <!-- Very easy to see we havn't a </head> close tag -->
    <body>
        <div>
            My content
        </div>
    </body>
</html>

Hope I help you.


问:
Can I set the visibility of a TTextBox in a function?
I tried

```<code>function hilfe() {
    $this->hilfe_txt->Visible->true;
}
</code>```

to set the visibility of

```<code><com:TTextBox id="hilfe_txt" Visible="false" Text""/>
</code>```

error is: [Notice] Trying to get property of non-object

Any ideas to solve that problem?

答:
Solved it!

```<code>$this->hilfe_txt->Visible=true;
</code>```

Simple but took a long time to find.

Body:
I tried

function hilfe() {
    $this->hilfe_txt->Visible->true;
}

to set the visibility of

<com:TTextBox id="hilfe_txt" Visible="false" Text""/>

error is: [Notice] Trying to get property of non-object

Any ideas to solve that problem?

Body:
Solved it!

$this->hilfe_txt->Visible=true;

Simple but took a long time to find.


问:
firebase how to get child of child?
so i am stuck. i want to retrieve child of child from my firebase database.

my database struture looks like this

```<code>users{
    user1{
        name:
        regno:
        carmodel:
        caryear}
    user2{
        name:
        regno:
        carmodel:
        caryear}
    user3{
        name:
        regno:
        carmodel:
        caryear}}
</code>```

Regno = car registration number.

when i type in a "carreg no" and press ok. i want the code to search every carreg. if a match is found execute next set of codes.

so far i have tried to store it in a array. but the code seems to fail when i put reg or any variable name that exist.

```<code> public void input(){

    FirebaseDatabase firebase = FirebaseDatabase.getInstance();
    final DatabaseReference table_user = firebase.getReference("User");
    table_user.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //Get map of users in datasnapshot
                    collectPhoneNumbers((Map<String,Object>) dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    //handle databaseError
                }
            });

private void collectPhoneNumbers(Map<String,Object> users) {

        ArrayList<Long> phoneNumbers = new ArrayList<>();

        //iterate through each user, ignoring their UID
        for (Map.Entry<String, Object> entry : users.entrySet()){

            //Get user map
            Map singleUser = (Map) entry.getValue();
            //Get phone field and append to list
            phoneNumbers.add((Long) singleUser.get("namesd"));
        }

        System.out.println(phoneNumbers.toString());

        mVoiceInputTv.setText("" + phoneNumbers);
    }
}
</code>```

i got this from another stackflow. before this i tried creating a for look. it was successfull but result failed 80% of the time. (not always correct).

答:
To solve this, you need to query your database using orderByChild() method like this:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
Query regnoQuery = usersRef.orderByChild("regno").equalsTo(regno);
</code>```

In which regno argument from equalsTo() is the the actual registration number that you are looking for. Then attach a listener to the regnoQuery and use getChildrenCount() method on the dataSnapshot object. If the number of childrens is noOfChildrens > 0 then execute the set of codes you need.

Title: firebase how to get child of child?

Body:
so i am stuck. i want to retrieve child of child from my firebase database.

my database struture looks like this

users{
    user1{
        name:
        regno:
        carmodel:
        caryear}
    user2{
        name:
        regno:
        carmodel:
        caryear}
    user3{
        name:
        regno:
        carmodel:
        caryear}}

Regno = car registration number.

when i type in a "carreg no" and press ok. i want the code to search every carreg. if a match is found execute next set of codes.

so far i have tried to store it in a array. but the code seems to fail when i put reg or any variable name that exist.

 public void input(){

    FirebaseDatabase firebase = FirebaseDatabase.getInstance();
    final DatabaseReference table_user = firebase.getReference("User");
    table_user.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //Get map of users in datasnapshot
                    collectPhoneNumbers((Map<String,Object>) dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    //handle databaseError
                }
            });

private void collectPhoneNumbers(Map<String,Object> users) {

        ArrayList<Long> phoneNumbers = new ArrayList<>();

        //iterate through each user, ignoring their UID
        for (Map.Entry<String, Object> entry : users.entrySet()){

            //Get user map
            Map singleUser = (Map) entry.getValue();
            //Get phone field and append to list
            phoneNumbers.add((Long) singleUser.get("namesd"));
        }

        System.out.println(phoneNumbers.toString());

        mVoiceInputTv.setText("" + phoneNumbers);
    }
}

i got this from another stackflow. before this i tried creating a for look. it was successfull but result failed 80% of the time. (not always correct).

Body:
To solve this, you need to query your database using orderByChild() method like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
Query regnoQuery = usersRef.orderByChild("regno").equalsTo(regno);

In which regno argument from equalsTo() is the the actual registration number that you are looking for. Then attach a listener to the regnoQuery and use getChildrenCount() method on the dataSnapshot object. If the number of childrens is noOfChildrens > 0 then execute the set of codes you need.


答:
Answering your questions:

As described on official keras FAQ

the training loss is the average of the losses over each batch of training data. Because your model is changing over time, the loss over the first batches of an epoch is generally higher than over the last batches. On the other hand, the testing loss for an epoch is computed using the model as it is at the end of the epoch, resulting in a lower loss.

Training should be stopped when val_acc stops increasing, otherwise your model will probably overffit. You can use earlystopping callback to stop training.

Your model seems to achieve very good results. Keep up the good work.

Title: How to understand loss acc val_loss val_acc in Keras model fitting

Body:
I'm new on Keras and have some questions on how to understanding my model results. Here is my result:(for your convenience, I only paste the loss acc val_loss val_acc after each epoch here)

Train on 4160 samples, validate on 1040 samples as below:

Epoch 1/20
4160/4160 - loss: 3.3455 - acc: 0.1560 - val_loss: 1.6047 - val_acc: 0.4721

Epoch 2/20
4160/4160 - loss: 1.7639 - acc: 0.4274 - val_loss: 0.7060 - val_acc: 0.8019

Epoch 3/20
4160/4160 - loss: 1.0887 - acc: 0.5978 - val_loss: 0.3707 - val_acc: 0.9087

Epoch 4/20
4160/4160 - loss: 0.7736 - acc: 0.7067 - val_loss: 0.2619 - val_acc: 0.9442

Epoch 5/20
4160/4160 - loss: 0.5784 - acc: 0.7690 - val_loss: 0.2058 - val_acc: 0.9433

Epoch 6/20
4160/4160 - loss: 0.5000 - acc: 0.8065 - val_loss: 0.1557 - val_acc: 0.9750

Epoch 7/20
4160/4160 - loss: 0.4179 - acc: 0.8296 - val_loss: 0.1523 - val_acc: 0.9606

Epoch 8/20
4160/4160 - loss: 0.3758 - acc: 0.8495 - val_loss: 0.1063 - val_acc: 0.9712

Epoch 9/20
4160/4160 - loss: 0.3202 - acc: 0.8740 - val_loss: 0.1019 - val_acc: 0.9798

Epoch 10/20
4160/4160 - loss: 0.3028 - acc: 0.8788 - val_loss: 0.1074 - val_acc: 0.9644

Epoch 11/20
4160/4160 - loss: 0.2696 - acc: 0.8923 - val_loss: 0.0581 - val_acc: 0.9856

Epoch 12/20
4160/4160 - loss: 0.2738 - acc: 0.8894 - val_loss: 0.0713 - val_acc: 0.9837

Epoch 13/20
4160/4160 - loss: 0.2609 - acc: 0.8913 - val_loss: 0.0679 - val_acc: 0.9740

Epoch 14/20
4160/4160 - loss: 0.2556 - acc: 0.9022 - val_loss: 0.0599 - val_acc: 0.9769

Epoch 15/20
4160/4160 - loss: 0.2384 - acc: 0.9053 - val_loss: 0.0560 - val_acc: 0.9846

Epoch 16/20
4160/4160 - loss: 0.2305 - acc: 0.9079 - val_loss: 0.0502 - val_acc: 0.9865

Epoch 17/20
4160/4160 - loss: 0.2145 - acc: 0.9185 - val_loss: 0.0461 - val_acc: 0.9913

Epoch 18/20
4160/4160 - loss: 0.2046 - acc: 0.9183 - val_loss: 0.0524 - val_acc: 0.9750

Epoch 19/20
4160/4160 - loss: 0.2055 - acc: 0.9120 - val_loss: 0.0440 - val_acc: 0.9885

Epoch 20/20
4160/4160 - loss: 0.1890 - acc: 0.9236 - val_loss: 0.0501 - val_acc: 0.9827

Here are my understandings:

The two losses (both loss and val_loss) are decreasing and the tow acc (acc and val_acc) are increasing. So this indicates the modeling is trained in a good way.

The val_acc is the measure of how good the predictions of your model are. So for my case, it looks like the model was trained pretty well after 6 epochs, and the rest training is not necessary.

My Questions are:

The acc (the acc on training set) is always smaller, actually much smaller, than val_acc. Is this normal? Why this happens?In my mind, acc should usually similar to better than val_acc.

After 20 epochs, the acc is still increasing. So should I use more epochs and stop when acc stops increasing? Or I should stop where val_acc stops increasing, regardless of the trends of acc?

Is there any other thoughts on my results?

Thanks!


问:
NFC tag user memory binary
I'm trying to read NDEF records out of some NTAG213 & NTAG216 NFC tags, and I seem to be getting some extra bytes in the user memory i'm not expecting.

Based on the spec, the user memory should start from block 4, but when I read from the NTAG213 tags, i see 7 extra bytes before the NDEF record start, and 2 extra bytes for the NTAG216 tags.

Here's the example of the NTAG213 memory:

```<code>01| 04 ae f4 d6
02| 0a d7 49 80
03| 14 48 00 00
04| e1 10 6d 00
05| 03 db 91 01 <-- NDEF starts at 91?
06| 1a 54 02 65
07| 6e 43 4f 43
08| 4f 4e 55 54
09| 20 42 4f 44
10| 59 20 4d 49
11| ...
</code>```

The NDEF record appears to start with the header byte (91) in block 05, rather than the start on block 04.

Does anyone know what the extra bytes are for, or how I can tell what the offset should be for reading back just the NDEF data?

The bytes look a bit like some of the "Memory content at delivery".  But i'm not sure what the purpose is.

答:
Storage of NDEF data on Type 2 Tags is defined by the NFC Forum Type 2 tag specification. This specification defines that the first four byte of the user memory (fourth page) describe the NDEF capabilities of the tag and that the following bytes contain a sequence of Type-Length-Value (TLV) constructs, one of those (T=3) is the NDEF Message TLV that contains the actual NDEF data. Other TLV's describe memory locations that contain tag specific data like lock bytes and must be skipped when reading or writing NDEF data.

Your example content is an NTAG216 (not NTAG213).

The content of the fourth page is a magic byte (0xE1) that indicates NDEF format, followed by the NDEF mapping version (0x10 => Version 1.0), followed by the raw tag capacity in multiples of 8 (0x6D * 8 == 872 byte user data), followed by the read/write permissions (0x00 => readable and writable w/o restrictions).

The fifth page starts with the NDEF TLV Type (0x03 => NDEF message), followed by the TLV Length (0xDB == 219 byte) which gives the TLV Value field size. The bytes following are the actual NDEF message data but be aware that for some tags this may not be contiguous memory (other TLVs may indicate memory bytes that must be skipped when reading or writing).

For all the bells and whistles you can study an ndef read and ndef write or obtain a copy of the Type 2 Tag specification from the NFC Forum specifications page.

Title: NFC tag user memory binary

Body:
I'm trying to read NDEF records out of some NTAG213 & NTAG216 NFC tags, and I seem to be getting some extra bytes in the user memory i'm not expecting.

Based on the spec, the user memory should start from block 4, but when I read from the NTAG213 tags, i see 7 extra bytes before the NDEF record start, and 2 extra bytes for the NTAG216 tags.

Here's the example of the NTAG213 memory:

01| 04 ae f4 d6
02| 0a d7 49 80
03| 14 48 00 00
04| e1 10 6d 00
05| 03 db 91 01 <-- NDEF starts at 91?
06| 1a 54 02 65
07| 6e 43 4f 43
08| 4f 4e 55 54
09| 20 42 4f 44
10| 59 20 4d 49
11| ...

The NDEF record appears to start with the header byte (91) in block 05, rather than the start on block 04.

Does anyone know what the extra bytes are for, or how I can tell what the offset should be for reading back just the NDEF data?

The bytes look a bit like some of the "Memory content at delivery".  But i'm not sure what the purpose is.


问:
Google Sheets Filter Function if no value multiple columns
I want to pull all relevant data from Data!F:G on this sheet:
https://docs.google.com/spreadsheets/d/18hJW4ojAbe1dUF1lDdSOI11cTEaMeJ6N-VZ6BB7LrAY/edit#gid=1162973857

I am assuming it's a filter function but want to ensure that all data is pulled if the fields in Dashboard!C1:C5 are empty.

=filter(Data!F:G,
         Data!A:A = C1,
         Data!B:B = C2,
         Data!C:C = C3,
         Data!D:D = C4,
         Data!E:E = C5)

works when all fields are complete but not if one of them is empty.

Thank you!

答:
There is no wild card in Google Sheets Filter unfortunately, but you could test if a column is equal to itself like this

```<code>=filter(Data!F:G,Data!A:A = if(C1="",Data!A:A,C1), Data!B:B = if(C2="",Data!B:B,C2), Data!C:C = if(C3="",Data!C:C,C3), Data!D:D = if(C4="",Data!D:D,C4), Data!E:E = if(C5="",Data!E:E,C5))
</code>```

This is probably a bit tidier (the equivalent of an OR expression in a filter)

```<code>=filter(Data!F:G,(C1="")+(Data!A:A=C1), (C2="")+(Data!B:B=C2), (C3="")+(Data!C:C=C3), (C4="")+(Data!D:D = C4), (C5="")+(Data!E:E=C5))
</code>```

Body:
There is no wild card in Google Sheets Filter unfortunately, but you could test if a column is equal to itself like this

=filter(Data!F:G,Data!A:A = if(C1="",Data!A:A,C1), Data!B:B = if(C2="",Data!B:B,C2), Data!C:C = if(C3="",Data!C:C,C3), Data!D:D = if(C4="",Data!D:D,C4), Data!E:E = if(C5="",Data!E:E,C5))

This is probably a bit tidier (the equivalent of an OR expression in a filter)

=filter(Data!F:G,(C1="")+(Data!A:A=C1), (C2="")+(Data!B:B=C2), (C3="")+(Data!C:C=C3), (C4="")+(Data!D:D = C4), (C5="")+(Data!E:E=C5))


问:
Do subclasses ALWAYS need to implement a designated initializer in Objective-C?
Do subclasses that don't need to add class-specific initialization code have to implement the designated initializer of the super class?

The Apple's documentation for NSObject's init method provides some discussion:

"Every class must guarantee that the
init method either returns a fully
functional instance of the class or
raises an exception. Subclasses should
override the init method to add
class-specific initialization code."

"If a subclass does any initialization
of its own, it must define its own
designated initializer. This method
should begin by sending a message to
super to invoke the designated
initializer of its superclass."

However, nothing is specified for the case when a subclass needs no extra initialization code.

The code below attempts to clarify my question. ClassA has the designated initializer named initWithX:Y:. ClassB does not need to an extra initialization, everything is provided by ClassA.

Explanatory Code:

```<code>@interface ClassA : NSObject {
  NSInteger x;
  NSInteger y;
}

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY;

@end

@implementation ClassA

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super init]) {
    x = initX;
    y = initY;
  }
  return self;
}
@end

@interface ClassB : ClassA {
  //no extra variables
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (NSInteger)extraMethodOne;
+ (NSInteger)extraMethodTwoWithInteger:(NSInteger)anInteger;

@end

@implementation ClassB

/////////////??QUESTION HERE??///////////////////
//Is the implementation below needed?
//If I call [[ClassB alloc] initWithX:1 Y:2], won't it run the code in ClassA
//  with the self set to whatever [ClassB alloc] is?
/////////////////////////////////////////////////
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super initWithX:initX Y:initY]) {
    /* Don't need class-specific initialization code */
  }
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (int)extraMethodOne {return 1;}
+ (int)extraMethodTwoWithInteger:(NSInteger)anInteger {return 2 + anInteger;}

@end
</code>```

答:
"However, nothing is specified for the case when a subclass needs no extra initialization code."

That is correct -- do nothing.

When Apple says ""If a subclass does any initialization of its own ... blah blah" what they mean is "If and only if a subclass does any initialization of its own ... blah blah ... otherwise do nothing at all."

It's worth remembering that: it's not very often you will build an entire massive subclass that has a whole chain of it's own initializers (the designated initializer, and more beyond that), and then you (or others) will be subclassing that new subclass.  (If it is true that you or others will be subclassing that new subclass, then, yeah, that's when you have to have been careful to do just what Apple says above.)

In practice 99% of the time, you are just subclassing UIView, and you put some code in the "init" framework XCode automatically pastes in for you.  If, incredibly, someone then subclassed our subclass there, they would have to figure out that, wait for it, "init" is the designated initialiser in your subclass!

Regarding the Apple doco. They do an amazing job, but, there are many examples of that flavour of problem in the doco. A good example: Is there a proper way to handle overlapping NSView siblings?.  Notice the part that says "nonsensical"

Body:
Do subclasses that don't need to add class-specific initialization code have to implement the designated initializer of the super class?

The Apple's documentation for NSObject's init method provides some discussion:

"Every class must guarantee that the
init method either returns a fully
functional instance of the class or
raises an exception. Subclasses should
override the init method to add
class-specific initialization code."

"If a subclass does any initialization
of its own, it must define its own
designated initializer. This method
should begin by sending a message to
super to invoke the designated
initializer of its superclass."

However, nothing is specified for the case when a subclass needs no extra initialization code.

The code below attempts to clarify my question. ClassA has the designated initializer named initWithX:Y:. ClassB does not need to an extra initialization, everything is provided by ClassA.

Explanatory Code:

@interface ClassA : NSObject {
  NSInteger x;
  NSInteger y;
}

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY;

@end

@implementation ClassA

- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super init]) {
    x = initX;
    y = initY;
  }
  return self;
}
@end

@interface ClassB : ClassA {
  //no extra variables
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (NSInteger)extraMethodOne;
+ (NSInteger)extraMethodTwoWithInteger:(NSInteger)anInteger;

@end

@implementation ClassB

/////////////??QUESTION HERE??///////////////////
//Is the implementation below needed?
//If I call [[ClassB alloc] initWithX:1 Y:2], won't it run the code in ClassA
//  with the self set to whatever [ClassB alloc] is?
/////////////////////////////////////////////////
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
  if(self = [super initWithX:initX Y:initY]) {
    /* Don't need class-specific initialization code */
  }
}

//some extra static methods add to provide some differences
//  between ClassA and ClassB in sample code
+ (int)extraMethodOne {return 1;}
+ (int)extraMethodTwoWithInteger:(NSInteger)anInteger {return 2 + anInteger;}

@end


问:
Android studio 3, annotation processors must be explicitly declared now
I updated my Android studio to 3.0 & starting get this error:

```<code>annotation processors must be explicitly declared now
-parceler-0.2.15.jar(org.parceler:parceler:0.2.15)
</code>```

My build.gradle contains the dependency :

```<code>dependencies {
compile 'org.parceler:parceler:0.2.15'
}
</code>```

How to get rid of this error now with Android Studio 3.0?

答:
Each annotation library also needs an annotation processor. In most cases, these are bundled into the main dependency though it can be a second dependency in this case.

So you use the annotationProcessor keyword:

```<code>annotationProcessor 'org.parceler:parceler:0.2.15'
</code>```

This is in addition to compiling, don't remove that dependency.

Body:
I updated my Android studio to 3.0 & starting get this error:

annotation processors must be explicitly declared now
-parceler-0.2.15.jar(org.parceler:parceler:0.2.15)

My build.gradle contains the dependency :

dependencies {
compile 'org.parceler:parceler:0.2.15'
}

How to get rid of this error now with Android Studio 3.0?

Body:
Each annotation library also needs an annotation processor. In most cases, these are bundled into the main dependency though it can be a second dependency in this case.

So you use the annotationProcessor keyword:

annotationProcessor 'org.parceler:parceler:0.2.15'

This is in addition to compiling, don't remove that dependency.


问:
App failed to start because it could not find Qt platform plugin "Windows" in ""
I have been bogging my mind on this one for a few days with various versions of python and freeze utilities.
Python 3.6, PyQt5
I created a script, and am trying to make a standalone .exe
However, when running pyinstaller, I get the result I have posted below. I am currently using an Anaconda distribution, so I am not sure if this has anything to do with it. How do I resolve this issue?

I have tried to fix it for several days using different python and pyqt versions, but the short story is that some of the libraries I am using come into conflict in other versions. I am posting this again because nothing else has really worked, and I am on my last straws.

Thanks in advance.
Error Window:

答:
From this page:
PyQt5 - Failed to load platform plugin "windows". Available platforms are: windows, minimal
this answer solved my problem.
Copying the folder platforms from python installation directory into my built folder solved the problem. the "platforms" folder contains qminimal.dll.
Maybe it helps you too!</p>


问:
cordova run android with mac
Failed to restore plugin "cordova-plugin-file-transfer" from config.xml. You might need to try adding it again. Error: Version of installed plugin: "cordova-plugin-file@4.3.3" does not satisfy dependency plugin requirement "cordova-plugin-file@^5.0.0". Try --force to use installed plugin as dependency.

I am facing above issue while running

```<code>ionic cordova run android
</code>```

on mac. not sure why its giving this issue. I am using android 6.4.0.

答:
TL;DR: run these commands:

```<code>ionic cordova plugin rm cordova-plugin-file --force
ionic cordova plugin add cordova-plugin-file@latest
ionic cordova run android
</code>```

When you run ionic cordova run android, the Cordova CLI is running a prepare operation which tries to restore any plugins which are present in your config.xml/package.json but not installed in you local project.

So it's trying to install a recent version of cordova-plugin-file-transfer but this is failing because you have v4.3.3 of cordova-plugin-file installed in plugins/ and cordova-plugin-file-transfer now requires v5.0.0+

Title: cordova run android with mac

Body:
Failed to restore plugin "cordova-plugin-file-transfer" from config.xml. You might need to try adding it again. Error: Version of installed plugin: "cordova-plugin-file@4.3.3" does not satisfy dependency plugin requirement "cordova-plugin-file@^5.0.0". Try --force to use installed plugin as dependency.

I am facing above issue while running

ionic cordova run android

on mac. not sure why its giving this issue. I am using android 6.4.0.

Body:
TL;DR: run these commands:

ionic cordova plugin rm cordova-plugin-file --force
ionic cordova plugin add cordova-plugin-file@latest
ionic cordova run android

When you run ionic cordova run android, the Cordova CLI is running a prepare operation which tries to restore any plugins which are present in your config.xml/package.json but not installed in you local project.

So it's trying to install a recent version of cordova-plugin-file-transfer but this is failing because you have v4.3.3 of cordova-plugin-file installed in plugins/ and cordova-plugin-file-transfer now requires v5.0.0+


问:
Symfony2 - Access is denied (user is not fully authenticated)
I'm developing a website using Symfony2, and until today - had no problem logging in. But now when logging in I'm not correctly authenticated - Symfony profiler lists me as logged in as: anon instead of the user I logged in as. I'm also redirected back to the login page instead of the target path.

The login process consists of a traditional login form (i.e. username + password) with a submit button. All user credentials are stored in MySQL and I've setup a User entity as a provider.

There are no errors in my php errors log, or listed in the Symfony profiler under Exception or Logs.

One observation I've made is nothing is listed under the Session Attributes heading (within Symfony profiler > Request) - normally there would be some security context information listed after successfully logging in, but now it's always empty. I tried setting a basic session variable on the homepage which was partially successful as it gets set and is shown under Session Attributes, but get's cleared whenever attempting to login!

This is my security.yml file:

```<code># app/config/security.yml

security:
  encoders:
    Woodcut\UserBundle\Entity\User: sha512

  role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

  providers:
    main:
        entity: { class: Woodcut\UserBundle\Entity\User, property: username }

  firewalls:
    secured_area:
        pattern:   ^/
        anonymous: ~
        form_login:
            login_path: login
            check_path: login_check
            username_parameter: _username
            success_handler: custom_authentication_handler
            failure_handler: custom_authentication_handler
            #always_use_default_target_path: true
            #default_target_path: /login_router
        logout:
            path: /logout
            target: /
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false

  access_control:
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/ratings/update, roles: ROLE_USER }
    - { path: ^/ratings/new, roles: ROLE_USER }
    - { path: ^/favourite, roles: ROLE_USER }
</code>```

I'm using a typical LAMP stack to run my site with Symfony 2.3.13 and PHP 5.4.28 on a Ubuntu 12.04 Virtual machine. PHP is running as mod_php.

Output from Symfony Profiler > Debug:

```<code>INFO - Populated SecurityContext with an anonymous Token
DEBUG - Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall  \ExceptionListener::onKernelException".
DEBUG - Access is denied (user is not fully authenticated) by "/vagrant_www/vprojects/woodcut/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/AccessListener.php" at line 70; redirecting to authentication entry point
DEBUG - Calling Authentication entry point
</code>```

If someone can please help me determine why users are authenticated as anonymous instead of as themselves that would be great. Been pulling my hear out the last two days trying to find the cause.

Thanks in advance for any help provided!

Additional info: I have a VPS running a copy of the site (for client previewing). I dev on my local VM and git push my changes, I then SSH into my VPS and do a git pull to keep my two version in sync.

What's strange is the VPS version does not exhibit this issue (i.e. login works fine) yet both versions use an identical codebase except for some minor differences in their respective parameters.yml and parameters_dev.yml files.

Update: Problem started happening after making a large number of edits to the code base and performing a apt-get update and apt-get upgrade on my VM. So in an effort to isolate the possible cause I rolled back to an earlier commit - to see if the problem was code related. But despite rolling back to before my major coding changes, the problem is still there.

This has me thinking the cause may not be code related and instead could be server related, something in the new version of PHP (5.4.28) that was installed via apt-get upgrade perhaps OR a new php.ini directive maybe?

I've run the Symfony configuration checker tool and everything seems fine!

Weird.

答:
This problem happens when the PHPSESSID cookie is changing with each request.
If that is your case then you should check the PHPSESSID response cookies between these request, I bet you that they are changed. Why is that happening, that is the real question!

Let's assume for a moment that the above assertion is true.

By seeing this cookie changing all the time Symfony/PHP assumes that the session manager have created in fact a new user session, obviously that would require the user to re-authenticate (unless RememberMe=true which wouldn't cause a login page redirection).

For instance, while working in dev environment I had no problem with this session issue. However, as soon I switched to prod environment - and by this I mean (1) I flushed the --env=prod cache then (2) I loaded the production /app.php instead /app_dev.php page - it just started to redirect me to the login page after a successful authentication & request.

Obviously at first I thought that there is a configuration problem, perhaps I'm using a different set of params on these environments. But that wasn't the case. So there must be something else, but what?

I've checked the var/session/prod directory and I saw many sess_xxx files. The same in var/session/dev directory. Obviously that is not OK. So I removed the var/session/{prod,dev} entirely then I reloaded the /app.php page. This created 2-3 sess_xxx files in both environment, in prod but also in dev. That is not good. It is a sign that somehow something sends a request to the app_dev.php which will load the dev enviroment which might log out you automatically (based on your app's security/firewall configuration). I opened the app_dev.php and I added an exit(0) then suddenly everything started to work well. So that was what was happening, somehow these environments were mixed and a call to prod would eventually trigger a call to the dev which would log you out immediately.

For a quick fix some people just change the framework::session::save_path to /tmp, which is going to be shared by both environments and thus you are not going to be logged out although your app will somehow still send a request to both the app.php and app_dev.php but since they used the same session folder they think the session is the same (unchanged). So in general this is a quick fix as long the session path is the same for all environments. However this is not the solution to the problem!

One other fix is to not use the app_dev.php in the same time with app.php (or vice-versa) and by that I mean only one file/env at a time. That's also a quick fix and not the solution.

What I did, but I still don't understand what happened, was to remove entirely the web {assetic,css,js,fonts} (or bin/console assetic:dump --env=prod --no-debug) stuff and recreate them again with --env=prod --no-debug. That did the trick but I still don't understand how that could fix it.

I hope the steps above would help you to trace the cause of your problem better than I did :-)

Body:
I'm developing a website using Symfony2, and until today - had no problem logging in. But now when logging in I'm not correctly authenticated - Symfony profiler lists me as logged in as: anon instead of the user I logged in as. I'm also redirected back to the login page instead of the target path.

The login process consists of a traditional login form (i.e. username + password) with a submit button. All user credentials are stored in MySQL and I've setup a User entity as a provider.

There are no errors in my php errors log, or listed in the Symfony profiler under Exception or Logs.

One observation I've made is nothing is listed under the Session Attributes heading (within Symfony profiler > Request) - normally there would be some security context information listed after successfully logging in, but now it's always empty. I tried setting a basic session variable on the homepage which was partially successful as it gets set and is shown under Session Attributes, but get's cleared whenever attempting to login!

This is my security.yml file:

# app/config/security.yml

security:
  encoders:
    Woodcut\UserBundle\Entity\User: sha512

  role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

  providers:
    main:
        entity: { class: Woodcut\UserBundle\Entity\User, property: username }

  firewalls:
    secured_area:
        pattern:   ^/
        anonymous: ~
        form_login:
            login_path: login
            check_path: login_check
            username_parameter: _username
            success_handler: custom_authentication_handler
            failure_handler: custom_authentication_handler
            #always_use_default_target_path: true
            #default_target_path: /login_router
        logout:
            path: /logout
            target: /
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false

  access_control:
    - { path: ^/admin, roles: ROLE_ADMIN }
    - { path: ^/ratings/update, roles: ROLE_USER }
    - { path: ^/ratings/new, roles: ROLE_USER }
    - { path: ^/favourite, roles: ROLE_USER }

I'm using a typical LAMP stack to run my site with Symfony 2.3.13 and PHP 5.4.28 on a Ubuntu 12.04 Virtual machine. PHP is running as mod_php.

Output from Symfony Profiler > Debug:

INFO - Populated SecurityContext with an anonymous Token
DEBUG - Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall  \ExceptionListener::onKernelException".
DEBUG - Access is denied (user is not fully authenticated) by "/vagrant_www/vprojects/woodcut/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/AccessListener.php" at line 70; redirecting to authentication entry point
DEBUG - Calling Authentication entry point

If someone can please help me determine why users are authenticated as anonymous instead of as themselves that would be great. Been pulling my hear out the last two days trying to find the cause.

Thanks in advance for any help provided!

Additional info: I have a VPS running a copy of the site (for client previewing). I dev on my local VM and git push my changes, I then SSH into my VPS and do a git pull to keep my two version in sync.

What's strange is the VPS version does not exhibit this issue (i.e. login works fine) yet both versions use an identical codebase except for some minor differences in their respective parameters.yml and parameters_dev.yml files.

Update: Problem started happening after making a large number of edits to the code base and performing a apt-get update and apt-get upgrade on my VM. So in an effort to isolate the possible cause I rolled back to an earlier commit - to see if the problem was code related. But despite rolling back to before my major coding changes, the problem is still there.

This has me thinking the cause may not be code related and instead could be server related, something in the new version of PHP (5.4.28) that was installed via apt-get upgrade perhaps OR a new php.ini directive maybe?

I've run the Symfony configuration checker tool and everything seems fine!

Weird.


问:
how do I use the Rails.logger from javascript
I nside a html.erb, I want to use the logger</p>

```<code><script type="text/javascript">
  $j(function(){

    $j('#AddQuestion').click(function(){
     //Send and http transaction to the server to get the address
      $j('#dialog').dialog(
        {buttons:{OK:function (event) {
                say('You clicked the ' + $(event.target).text() + ' button' );
              },  No:function (event) {
                say('You clicked the ' + $(event.target).text() + ' button' );
              }
                }
         });

      $j('#dialog').dialog('open');

    });
  });
</script>
</code>```

答:
You need to understand the difference between server-side code (code that runs on the web server, e.g. Ruby/Rails) and client-side code (code that runs on the web browser of the user, e.g. JavaScript).

The only way that JavaScript can use a Ruby method is by making a request (typically via AJAX) to the server, and having the server invoke Ruby code in response.