问:
Where does main or UI thread in android prepare looper?
It seems that in the main thread I just need to write a class that extends Handler and override its handleMessage method. Then I can just create Handler object without prepare looper.

```<code>class myHandler extends Handler{

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        String s=(String)msg.obj;
        textView.setText(s);
    }
}
</code>```

In the main thread, following code works:

```<code>handler=new myHandler();
</code>```

But in the worker thread you do need to prepare looper first and then you can create Handler object, otherwise threadLocal.get() can not get looper for the current worker thread. My question is there must be somewhere that prepare the looper for main thread but I just can not find it. I don not know how threadLocal find this looper for main thread.

```<code>class WorkerThread extends Thread{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        Looper.prepare();
        handler=new Handler(){

            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                System.out.println(msg.obj.toString());
                System.out.println(Thread.currentThread().getName());
            }

        };

        Looper.loop();
    }

}
</code>```

答:
Main looper is prepared in the main method of class ActivityThread with the following method call:

```<code>Looper.prepareMainLooper();
</code>```

See source code for example here.

Body:
It seems that in the main thread I just need to write a class that extends Handler and override its handleMessage method. Then I can just create Handler object without prepare looper.

class myHandler extends Handler{

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        String s=(String)msg.obj;
        textView.setText(s);
    }
}

In the main thread, following code works:

handler=new myHandler();

But in the worker thread you do need to prepare looper first and then you can create Handler object, otherwise threadLocal.get() can not get looper for the current worker thread. My question is there must be somewhere that prepare the looper for main thread but I just can not find it. I don not know how threadLocal find this looper for main thread.

class WorkerThread extends Thread{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        Looper.prepare();
        handler=new Handler(){

            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                System.out.println(msg.obj.toString());
                System.out.println(Thread.currentThread().getName());
            }

        };

        Looper.loop();
    }

}

Body:
Main looper is prepared in the main method of class ActivityThread with the following method call:

Looper.prepareMainLooper();

See source code for example here.


来源: stackexchange

问:
Problems while setting up vue-cli
I'm trying to install Vue-cli environemnt via NPM.

```<code>npm install --global vue-cli
</code>```

After that I want to create project

```<code>vue init webpack my-project
</code>```

And I get an error

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

I've read some solutions, most of them concern changing

PATH to C:\Users{YourUser}\AppData\Roaming\npm

Didn't work for me. Can anyone help.

答:
I found this same issue with another possible problem. I had

create-react-app@1.5.2 installed globally

npm list -g --depth=0 will display your globals

I simply uninstalled create-react-app

npm uninstall create-react-app

Vue vue-cli-service now works as expected.

ContentLicense: CC BY-SA 3.0

Title: Problems while setting up vue-cli

Body:
I'm trying to install Vue-cli environemnt via NPM.

npm install --global vue-cli

After that I want to create project

vue init webpack my-project

And I get an error

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

I've read some solutions, most of them concern changing

PATH to C:\Users{YourUser}\AppData\Roaming\npm

Didn't work for me. Can anyone help.

ContentLicense: CC BY-SA 4.0


问:
Unable to syncronize the functions
I'm trying to execute the functions one by one in synchronization.

```<code>var subtasks = ['Site', 'Draw', 'Material', 'Conduction', 'Cable', 'Install', 'Foundation']

function clickMe() {
  return new Promise(resolve => {
    jQuery("#addtoptasksubmit").trigger("click"); // triggering the button click
    resolve("done click");
  });
}

function typeWord(word) {
  return new Promise(resolve => {
    jQuery("#todotask").val(word); // input
    resolve("done type");
  });
}

function createSubTask() {
  return new Promise(res => {
    jQuery('#todotask').focus();
    res("done")

  })
};

function startLoop(i) {
  new Promise(resolve => {
    var promise = createSubTask();
    promise.then(resolve => {
      var typePromise = typeWord(subtasks[i]);
      typePromise.then((resolve) => {
        var clickPromise = clickMe();
        clickPromise.then((resolve) => {
          console.log(resolve);
        });
      });
    });
  })
}

let i = 0;
let prom = startLoop(i);

prom.then((res) => {
  startLoop(i++);
})
</code>```

code is not working properly and also I wanted to increment i automatically. For loop is a no show.

I've tried for loop and recursive async function on chrome.

答:
```<code>var subtasks = ['Site', 'Draw', 'Material', 'Conduction', 'Cable', 'Install', 'Foundation'];

function clickMe() {
  return new Promise(resolve => {
    setTimeout(() => {
      jQuery("#addtoptasksubmit").trigger("click");
      resolve("done click");
    }, 1000);
  });
}

function typeWord(word) {
  return new Promise(resolve => {
    jQuery("#todotask").val(word);
    resolve("done type");
  });
}

function createSubTask() {
  return new Promise(res => {
    jQuery('#todotask').focus();
    res("done");

  })
};

function startLoop(i) {
  return new Promise(res => {
    var promise = createSubTask();
    promise.then(
      (resolve) => {
        var typePromise = typeWord(subtasks[i]);
        typePromise.then((resolve) => {
          console.trace(resolve);
          var clickPromise = clickMe();
          clickPromise.then((resolve) => {
            console.trace(resolve);
            res("done loop " + subtasks[i]);
          });
        });
      }
    );
  })
}

var _index_ = 0;

var _how_ = setInterval(() => {
  if (_index_ < subtasks.length) {
    let loopPromise = startLoop(_index_);
    loopPromise.then((resolve) => {
      _index_ += 1;
    });
  } else {
    console.log("all done go get the new task");
    clearInterval(_how_);
  }
}, 10000);
</code>```

I can optimise it further....

Title: Unable to syncronize the functions

Body:
I'm trying to execute the functions one by one in synchronization.

var subtasks = ['Site', 'Draw', 'Material', 'Conduction', 'Cable', 'Install', 'Foundation']

function clickMe() {
  return new Promise(resolve => {
    jQuery("#addtoptasksubmit").trigger("click"); // triggering the button click
    resolve("done click");
  });
}

function typeWord(word) {
  return new Promise(resolve => {
    jQuery("#todotask").val(word); // input
    resolve("done type");
  });
}

function createSubTask() {
  return new Promise(res => {
    jQuery('#todotask').focus();
    res("done")

  })
};

function startLoop(i) {
  new Promise(resolve => {
    var promise = createSubTask();
    promise.then(resolve => {
      var typePromise = typeWord(subtasks[i]);
      typePromise.then((resolve) => {
        var clickPromise = clickMe();
        clickPromise.then((resolve) => {
          console.log(resolve);
        });
      });
    });
  })
}

let i = 0;
let prom = startLoop(i);

prom.then((res) => {
  startLoop(i++);
})

code is not working properly and also I wanted to increment i automatically. For loop is a no show.

I've tried for loop and recursive async function on chrome.

Body:
var subtasks = ['Site', 'Draw', 'Material', 'Conduction', 'Cable', 'Install', 'Foundation'];

function clickMe() {
  return new Promise(resolve => {
    setTimeout(() => {
      jQuery("#addtoptasksubmit").trigger("click");
      resolve("done click");
    }, 1000);
  });
}

function typeWord(word) {
  return new Promise(resolve => {
    jQuery("#todotask").val(word);
    resolve("done type");
  });
}

function createSubTask() {
  return new Promise(res => {
    jQuery('#todotask').focus();
    res("done");

  })
};

function startLoop(i) {
  return new Promise(res => {
    var promise = createSubTask();
    promise.then(
      (resolve) => {
        var typePromise = typeWord(subtasks[i]);
        typePromise.then((resolve) => {
          console.trace(resolve);
          var clickPromise = clickMe();
          clickPromise.then((resolve) => {
            console.trace(resolve);
            res("done loop " + subtasks[i]);
          });
        });
      }
    );
  })
}

var _index_ = 0;

var _how_ = setInterval(() => {
  if (_index_ < subtasks.length) {
    let loopPromise = startLoop(_index_);
    loopPromise.then((resolve) => {
      _index_ += 1;
    });
  } else {
    console.log("all done go get the new task");
    clearInterval(_how_);
  }
}, 10000);

I can optimise it further....


问:
Troubleshooting Bootstrap button
Submit Button is not working if I put it on a different container or row

If my code is formatted like this the submit button works

```<code><div class="container">
    <div class="row">
       <form>
          <button type="submit">Submit</button>
       </form>
    </div>
</div>
</code>```

If my code is formatted like this the submit button do not work

```<code> <div class="container">

    <div class="row">
       <form>

           {{ some other codes }}

    </div>

    <div class="row">

          <button type="submit">Submit</button>
       </form>
    </div>
</div>
</code>```

I dont get any error message.. the button is there but its not working.

答:
If you order your tags like below so they close properly. Then your button will work.

Take a look at HTML basics Nesting elements from MDN.

```<code><div class="container">
  <form>
    <div class="row">
      {{ some other codes }}
    </div>
    <div class="row">
      <button id="js" type="submit">Submit</button>
    </div>
  </form>
</div>
</code>```

Title: Troubleshooting Bootstrap button

Body:
Submit Button is not working if I put it on a different container or row

If my code is formatted like this the submit button works

       <form>
          <button type="submit">Submit</button>
       </form>

If my code is formatted like this the submit button do not work

       <form>

           {{ some other codes }}

          <button type="submit">Submit</button>
       </form>

I dont get any error message.. the button is there but its not working.

Body:
If you order your tags like below so they close properly. Then your button will work.

Take a look at HTML basics Nesting elements from MDN.

<div class="container">
  <form>
    <div class="row">
      {{ some other codes }}
    </div>
    <div class="row">
      <button id="js" type="submit">Submit</button>
    </div>
  </form>
</div>


问:
mod redirect and rewrites ( Part 2 )
Further to my previous questions i am getting my self into a mess, so i will try and lay my problem/s out as best as i can here.

I am tidying up my URL structure but have the problem that my urls are well indexed in Search engines, so i need to rewrite my urls while also redirect them.

With help earlier on a previous question i currently have the following in my .htaccess

```<code>Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.mydomain.com/$1 [R=301]

# Rewrite A newly added section rewrite ( no redirect required )
RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

# Rewrite dental news article to neat nice url
RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]
</code>```

So, this is all working as expected, but i have another url that ends in a index.php that sometimes but not always has php variables, this i also need to rewrite and redirect, by trying to do it myself i am creating a conflict of some sorts, and its not working as expected.

The URL i need to rewrite & redirect with a 301 is below

```<code>http://www.mydomain.com/news/dentistry_dental/index.php?month=February&year=2011

With the previous index.php rule it currently displays as

http://www.mydomain.com/news/dentistry_dental/?month=February&year=2011

Half way there i guess... I need it to be the following

http://www.mydomain.com/dental_news/February/2011
</code>```

Baring in mind that the url sometimes has no variables as below

```<code>http://www.mydomain.com/news/dentistry_dental/index.php

Which is currently with the index.php rule above is showing as

http://www.mydomain.com/news/dentistry_dental/

This needs to be

http://www.mydomain.com/dental_news/
</code>```

So yes, i am totally crap at this stuff, it is entirely new to me, so if i can get this sorted ill be a very happy bunny indeed!

Thanks All

EDIT

Ok my current .htaccess looks as below.

```<code>Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.mydomain.com/$1 [R=301]

RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

# Rewrite dental news article to neat nice url
RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)
RewriteRule (.*) /dental_news/%1/%2? [R=301]
RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]
RewriteRule ^dental_news/$ /news/dentistry_dental/index.php [L]
</code>```

As it stands with this, The following occurs

```<code>www.mydomain.com/news/dentistry_dental/index.php
-> www.mydomain.com/dental_news/
</code>```

( ^ Correct )

```<code>www.mydomain.com/news/dentistry_dental/index.php?month=May&year=2011
-> www.mydomain.com/dental_news/April/2011
</code>```

( ^ Wrong : Showing right path in url bar, but displaying article_detail.php instead of index.php with variables)

I am guessing that 2 of the rules are similar and one is picking up the index.php with year and month variables and sending to article_detail page. I might be wrong however and i have no idea how to fix.

EDIT #2

Current .htaccess as below.

```<code>Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^dentalsupportuk.com [nc]
rewriterule ^(.*)$ http://www.dentalsupportuk.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.dentalsupportuk.com/$1 [R=301]

RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

# Rewrite dental news article to neat nice url
RewriteRule ^dental_news/([0-9]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)
RewriteRule (.*) /dental_news/%1/%2? [R=301]
RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]
RewriteRule ^dental_news/([a-zA-Z]*)/([0-9]*)$ news/dentistry_dental/index.php?month=$1&year=$2&redirect [L]
</code>```

www.mydomain.com/dental_news/ is now rewriting to  www.mydomain.com/dental_news/ which doesnt exist so 404 error ( should be rewriting to www.mydomain.com/news/dentistry_dental/ )

www.mydomain.com/dental_news/100/some-title is now rewriting as expected to www.mydomain.com/news/dentistry_dental/article_detail.php with the variables ( working )

www.mydomain.com/news/dentistry_dental/article_detail.php?article=100&title=some-title is redirecting as expected to www.mydomain.com/dental_news/100/some-title and displaying correctly ( working )

www.mydomain.com/news/dentistry_dental/index.php?month=May&year=2010 is redirecting but crashing out Firefox stating ( Firefox has detected that the server is redirecting the request for this address in a way that will never complete. ) ( Not Working, is this some sort of loop causing this? )

www.mydomain.com/dental_news/July/2010/   the rewriting is giving me a 404 error.

So yes, im all over the place, maybe ive put in wrong order or something, but the more i mess the more im scared of breaking everything. Any ideas?

Regards
M

答:
Try adding the follow two rules:

```<code>RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)
RewriteRule (.*) /dental_news/%1/%2? [R=301]

RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]
</code>```

I don't believe it causes any conflicts, and seems to cover the two scenarios you described.

EDIT

OK, so if I'm getting this correct, the URLs that are /dental_news/2968/Redefining-oral-hygiene-intervention should be rewritten to /news/dentistry_dental/article_detail.php with the proper querystrings.  And then the /dental_news/April/2011 should be rewritten to /news/dentistry_dental/index.php.  So...if that is the case, you should be able to add the following rule:

```<code>RewriteRule ^dental_news/([a-zA-Z]*)/([0-9]*)$ news/dentistry_dental/index.php?month=$1&year=$2&redirect [L]
</code>```

It would also probably make sense to make the following update:

Current: RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

Updated: RewriteRule ^dental_news/([0-9]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

The difference there being that it is more specific, and the first regex group will only match a group of digits, and will help to avoid conflict with your rule that is rewriting to the index.php file.

EDIT 2
I believe I tested all of the URLs you provided, and they seem to be working now.  There were a couple of redirect loops that we weren't accounting for.  Hopefully this will help...

```<code>Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.mydomain.com/$1 [R=301]

RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

RewriteRule dental_news/$ /news/dentistry_dental/?rewrite [L]

# Rewrite dental news article to neat nice url
# Protect from looping because of previous rules
RewriteCond %{QUERY_STRING} !rewrite
RewriteRule ^dental_news/([0-9]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&rewrite [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [R=301]

# Protect from looping because of previous rules
RewriteCond %{QUERY_STRING} !rewrite
RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]

# Protect from looping because of previous rules
RewriteCond %{QUERY_STRING} !rewrite
RewriteRule ^dental_news/([a-zA-Z]*)/([0-9]*)/?$ news/dentistry_dental/index.php?month=$1&year=$2&rewrite [L]
</code>```

Hope this helps.

Title: mod redirect and rewrites ( Part 2 )

Body:
Further to my previous questions i am getting my self into a mess, so i will try and lay my problem/s out as best as i can here.

I am tidying up my URL structure but have the problem that my urls are well indexed in Search engines, so i need to rewrite my urls while also redirect them.

With help earlier on a previous question i currently have the following in my .htaccess

Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.mydomain.com/$1 [R=301]

# Rewrite A newly added section rewrite ( no redirect required )
RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

# Rewrite dental news article to neat nice url
RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

So, this is all working as expected, but i have another url that ends in a index.php that sometimes but not always has php variables, this i also need to rewrite and redirect, by trying to do it myself i am creating a conflict of some sorts, and its not working as expected.

The URL i need to rewrite & redirect with a 301 is below

http://www.mydomain.com/news/dentistry_dental/index.php?month=February&year=2011

With the previous index.php rule it currently displays as

http://www.mydomain.com/news/dentistry_dental/?month=February&year=2011

Half way there i guess... I need it to be the following

http://www.mydomain.com/dental_news/February/2011

Baring in mind that the url sometimes has no variables as below

http://www.mydomain.com/news/dentistry_dental/index.php

Which is currently with the index.php rule above is showing as

http://www.mydomain.com/news/dentistry_dental/

This needs to be

http://www.mydomain.com/dental_news/

So yes, i am totally crap at this stuff, it is entirely new to me, so if i can get this sorted ill be a very happy bunny indeed!

Thanks All

EDIT

Ok my current .htaccess looks as below.

Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.mydomain.com/$1 [R=301]

RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

# Rewrite dental news article to neat nice url
RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)
RewriteRule (.*) /dental_news/%1/%2? [R=301]
RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]
RewriteRule ^dental_news/$ /news/dentistry_dental/index.php [L]

As it stands with this, The following occurs

www.mydomain.com/news/dentistry_dental/index.php
-> www.mydomain.com/dental_news/

( ^ Correct )

www.mydomain.com/news/dentistry_dental/index.php?month=May&year=2011
-> www.mydomain.com/dental_news/April/2011

( ^ Wrong : Showing right path in url bar, but displaying article_detail.php instead of index.php with variables)

I am guessing that 2 of the rules are similar and one is picking up the index.php with year and month variables and sending to article_detail page. I might be wrong however and i have no idea how to fix.

EDIT #2

Current .htaccess as below.

Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^dentalsupportuk.com [nc]
rewriterule ^(.*)$ http://www.dentalsupportuk.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.dentalsupportuk.com/$1 [R=301]

RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

# Rewrite dental news article to neat nice url
RewriteRule ^dental_news/([0-9]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)
RewriteRule (.*) /dental_news/%1/%2? [R=301]
RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]
RewriteRule ^dental_news/([a-zA-Z]*)/([0-9]*)$ news/dentistry_dental/index.php?month=$1&year=$2&redirect [L]

www.mydomain.com/dental_news/ is now rewriting to  www.mydomain.com/dental_news/ which doesnt exist so 404 error ( should be rewriting to www.mydomain.com/news/dentistry_dental/ )

www.mydomain.com/dental_news/100/some-title is now rewriting as expected to www.mydomain.com/news/dentistry_dental/article_detail.php with the variables ( working )

www.mydomain.com/news/dentistry_dental/article_detail.php?article=100&title=some-title is redirecting as expected to www.mydomain.com/dental_news/100/some-title and displaying correctly ( working )

www.mydomain.com/news/dentistry_dental/index.php?month=May&year=2010 is redirecting but crashing out Firefox stating ( Firefox has detected that the server is redirecting the request for this address in a way that will never complete. ) ( Not Working, is this some sort of loop causing this? )

www.mydomain.com/dental_news/July/2010/   the rewriting is giving me a 404 error.

So yes, im all over the place, maybe ive put in wrong order or something, but the more i mess the more im scared of breaking everything. Any ideas?

Regards
M

Body:
Try adding the follow two rules:

RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)
RewriteRule (.*) /dental_news/%1/%2? [R=301]

RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]

I don't believe it causes any conflicts, and seems to cover the two scenarios you described.

EDIT

OK, so if I'm getting this correct, the URLs that are /dental_news/2968/Redefining-oral-hygiene-intervention should be rewritten to /news/dentistry_dental/article_detail.php with the proper querystrings.  And then the /dental_news/April/2011 should be rewritten to /news/dentistry_dental/index.php.  So...if that is the case, you should be able to add the following rule:

RewriteRule ^dental_news/([a-zA-Z]*)/([0-9]*)$ news/dentistry_dental/index.php?month=$1&year=$2&redirect [L]

It would also probably make sense to make the following update:

Current: RewriteRule ^dental_news/([^/]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

Updated: RewriteRule ^dental_news/([0-9]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&redirect [L]

The difference there being that it is more specific, and the first regex group will only match a group of digits, and will help to avoid conflict with your rule that is rewriting to the index.php file.

EDIT 2
I believe I tested all of the URLs you provided, and they seem to be working now.  There were a couple of redirect loops that we weren't accounting for.  Hopefully this will help...

Options +FollowSymlinks
RewriteEngine on

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]

# Rewrite all index.php to root: / ( with perm redirect )
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.mydomain.com/$1 [R=301]

RewriteRule ^products/digital_imaging/([^/]*)/([^/]*)$ /products/digital_xray.php?id=$1&product=$2 [L]

RewriteRule dental_news/$ /news/dentistry_dental/?rewrite [L]

# Rewrite dental news article to neat nice url
# Protect from looping because of previous rules
RewriteCond %{QUERY_STRING} !rewrite
RewriteRule ^dental_news/([0-9]*)/([^/]*)$ news/dentistry_dental/article_detail.php?article=$1&title=$2&rewrite [L]

#Conditional rewrite of old news article path to new one with 301 redirect
RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} article=([0-9]*)&title=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [L,R=301]

RewriteCond %{REQUEST_URI} !^/dental_news/
RewriteCond %{QUERY_STRING} month=([^&]*)&year=([^&]*)$
RewriteRule (.*) /dental_news/%1/%2? [R=301]

# Protect from looping because of previous rules
RewriteCond %{QUERY_STRING} !rewrite
RewriteRule news/dentistry_dental/$ /dental_news/ [R=301]

# Protect from looping because of previous rules
RewriteCond %{QUERY_STRING} !rewrite
RewriteRule ^dental_news/([a-zA-Z]*)/([0-9]*)/?$ news/dentistry_dental/index.php?month=$1&year=$2&rewrite [L]

Hope this helps.


问:
Setting Custom ActionBar Title from Fragment
In my Main FragmentActivity, I setup my custom ActionBar title like this:

```<code>    LayoutInflater inflator = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflator.inflate(R.layout.custom_titlebar, null);

    TextView tv = (TextView) v.findViewById(R.id.title);
    Typeface tf = Typeface.createFromAsset(this.getAssets(),
            "fonts/capsuula.ttf");
    tv.setTypeface(tf);
    tv.setText(this.getTitle());

    actionBar.setCustomView(v);
</code>```

This works perfect.  However, once I open other Fragments, I want the title to change.  I am not sure how to access the Main Activity to do this?  In the past, I did this:

```<code>((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
            catTitle);
</code>```

Can someone advise on the proper method?

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:text=""
        android:textColor="#fff"
        android:textSize="25sp" />

</RelativeLayout>
</code>```

答:
In your MainActivity, under onCreate:

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

And in your fragment activity under onResume:

```<code>getActivity().setTitle(R.string.app_name_science);
</code>```

Optional:- if they show warning of null reference

```<code>Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

Objects.requireNonNull(getActivity()).setTitle(R.string.app_name_science);
</code>```

Body:
In my Main FragmentActivity, I setup my custom ActionBar title like this:

    LayoutInflater inflator = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflator.inflate(R.layout.custom_titlebar, null);

    TextView tv = (TextView) v.findViewById(R.id.title);
    Typeface tf = Typeface.createFromAsset(this.getAssets(),
            "fonts/capsuula.ttf");
    tv.setTypeface(tf);
    tv.setText(this.getTitle());

    actionBar.setCustomView(v);

This works perfect.  However, once I open other Fragments, I want the title to change.  I am not sure how to access the Main Activity to do this?  In the past, I did this:

((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
            catTitle);

Can someone advise on the proper method?

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:text=""
        android:textColor="#fff"
        android:textSize="25sp" />

</RelativeLayout>

Body:
In your MainActivity, under onCreate:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And in your fragment activity under onResume:

getActivity().setTitle(R.string.app_name_science);

Optional:- if they show warning of null reference

Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

Objects.requireNonNull(getActivity()).setTitle(R.string.app_name_science);


问:
Pythonic way to avoid a mountain of if...else statements?
This has come up several times recently and I'd like to deal with it better than I have been: I have a series of attributes that I'm cross referencing between an object and a dictionary.  If the value is different between them, I want to set the object.attribute to the dictionary['attribute'] value.  I also want to keep track of what's getting changed.

Now, my first thought is to just use an if else statement for every attribute, but after writing a few of these it's apparent that I'm re-writing the same code again and again.  There has to be a DRY way to do this, where I specify only the parts that are changing every time, and then loop through all the attributes.

In production code, there are 15 different attributes, but my example below will just use 2 for simplicity.  I have some idea about how to do this in a clever way, but I'm missing the final step of actually setting the object.attribute equal to the dictionary['attribute'] value.

```<code># Simulated data setup - not under my control IRL
class someClass:
    def __init__(self, name, version):
        self.name = name
        self.version = version

objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

# My code below

# option 1 - a series of for loops
def updateAttributesSimple(obj, adict, msg):
    if obj.name == adict['name']:
        msg.append('Name is the same')
    else:
        msg.append('Name was updated from %s to %s' % (obj.name, adict['name']))
        obj.name = adict['name']

    if obj.version == adict['revision']:
        msg.append('Version is the same')
    else:
        msg.append('Version was updated from %s to %s' % (obj.version, adict['revision']))
        obj.version = adict['revision']

# option 2 - trying to be clever about this
def updateAttributesClever(obj, adict, msg):
    attributeList = (('Name', obj.name, adict['name']),
                     ('Version', obj.version, adict['revision']))

    for valTuple in attributeList:
        if valTuple[1] == valTuple[2]:
            msg.append('%s is the same' % (valTuple[0]))
        else:
            msg.append('%s was updated from %s to %s' % (valTuple[0], valTuple[1], valTuple[2]))
            # code to set valTuple[1] = valTuple[2] goes here, but what is it?
            # valTuple[1] = valTuple[2] attempts to set the desired value to a string, rather than the attribute of obj itself

msg = ['Updating Attributes simple way:']
updateAttributesSimple(objA, dictA, msg)
print '\n\t'.join(msg)

#reset data
objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

msg = ['Updating Attributes clever way:']
updateAttributesClever(objB, dictB, msg)
print '\n\t'.join(msg)
</code>```

The idea being that this way, whenever I need to add another attribute, I can just update the list of attributes being inspected and the rest of the code is already written.  What's the Pythonic way to accomplish this?

答:
You might want to think about creating a function which can take an arbitrary object and convert the dictionary of name/value pairs into something more meaningful.  It's not strictly a "Python" strategy but something that is fairly easy to do in Python because of its support of closures and how it treats objects under the hood:

```<code>def checkUpdates( obj ):
    def updated( dictionaryPrevious, msg ):
        for name, value in dictionaryPrevious.items():
            if( obj.__dict__[name] == value ):
                msg.append('Name is the same')
            else:
                msg.append(name + 'has been changed!')
                obj.__dict__[name] = value
    return updated
</code>```

I am making one assumption, the names in the dictionary always correspond to the object variables.  If they're not the same you'll need to make a mapping.

edit:

() => [] and object => obj.  thanks guys.  Sometimes you go from one language to a few others and it all gets muddled.

Body:
This has come up several times recently and I'd like to deal with it better than I have been: I have a series of attributes that I'm cross referencing between an object and a dictionary.  If the value is different between them, I want to set the object.attribute to the dictionary['attribute'] value.  I also want to keep track of what's getting changed.

Now, my first thought is to just use an if else statement for every attribute, but after writing a few of these it's apparent that I'm re-writing the same code again and again.  There has to be a DRY way to do this, where I specify only the parts that are changing every time, and then loop through all the attributes.

In production code, there are 15 different attributes, but my example below will just use 2 for simplicity.  I have some idea about how to do this in a clever way, but I'm missing the final step of actually setting the object.attribute equal to the dictionary['attribute'] value.

# Simulated data setup - not under my control IRL
class someClass:
    def __init__(self, name, version):
        self.name = name
        self.version = version

objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

# My code below

# option 1 - a series of for loops
def updateAttributesSimple(obj, adict, msg):
    if obj.name == adict['name']:
        msg.append('Name is the same')
    else:
        msg.append('Name was updated from %s to %s' % (obj.name, adict['name']))
        obj.name = adict['name']

    if obj.version == adict['revision']:
        msg.append('Version is the same')
    else:
        msg.append('Version was updated from %s to %s' % (obj.version, adict['revision']))
        obj.version = adict['revision']

# option 2 - trying to be clever about this
def updateAttributesClever(obj, adict, msg):
    attributeList = (('Name', obj.name, adict['name']),
                     ('Version', obj.version, adict['revision']))

    for valTuple in attributeList:
        if valTuple[1] == valTuple[2]:
            msg.append('%s is the same' % (valTuple[0]))
        else:
            msg.append('%s was updated from %s to %s' % (valTuple[0], valTuple[1], valTuple[2]))
            # code to set valTuple[1] = valTuple[2] goes here, but what is it?
            # valTuple[1] = valTuple[2] attempts to set the desired value to a string, rather than the attribute of obj itself

msg = ['Updating Attributes simple way:']
updateAttributesSimple(objA, dictA, msg)
print '\n\t'.join(msg)

#reset data
objA = someClass('Test1','1.1')
dictA = {'name':'Test1','revision':'1.2'}

msg = ['Updating Attributes clever way:']
updateAttributesClever(objB, dictB, msg)
print '\n\t'.join(msg)

The idea being that this way, whenever I need to add another attribute, I can just update the list of attributes being inspected and the rest of the code is already written.  What's the Pythonic way to accomplish this?

Body:
You might want to think about creating a function which can take an arbitrary object and convert the dictionary of name/value pairs into something more meaningful.  It's not strictly a "Python" strategy but something that is fairly easy to do in Python because of its support of closures and how it treats objects under the hood:

def checkUpdates( obj ):
    def updated( dictionaryPrevious, msg ):
        for name, value in dictionaryPrevious.items():
            if( obj.__dict__[name] == value ):
                msg.append('Name is the same')
            else:
                msg.append(name + 'has been changed!')
                obj.__dict__[name] = value
    return updated

I am making one assumption, the names in the dictionary always correspond to the object variables.  If they're not the same you'll need to make a mapping.

edit:

() => [] and object => obj.  thanks guys.  Sometimes you go from one language to a few others and it all gets muddled.


问:
Force UITypeEditor to display a initial value for a Enum type
I have a class with name EnumFlagsEditor that inherits from UITypeEditor in order to design a type editor capable to edit a Enum with FlagsAttribute, by using a custom CheckedListBox, and also to be able edit a normal Enum too within the same custom editor.

In the overriden UITypeEditor.GetEditStyle method, I verify whether or not the source Enum has the FlagsAttribute set. If the Enum type has this attribute class, then I return UITypeEditorEditStyle.DropDown to diplay my custom CheckedListBox. If does not have it, I return UITypeEditorEditStyle.Modal and .NET Framework does the rest using the default editor to edit Enums using a default ComboBox to display and select the Enum values/names.

The problem is, the default built-in editor in .NET framework class library to edit a normal Enum, I noticed it searchs for a Enum name with value 0 to display it as default, and If it does not found it, throws a System.ArgumentException and does not display a default value.

Take as example this Enum:

```<code>public enum TestEnum {
    a = 1,
    b = 2,
    c = 4
}
</code>```

That will throw a System.ArgumentException in the editor of a property grid and will not display a default value, because default .NET Framework editor for a Enum expects a value of 0 inside the Enum...

Now, using the System.DayOfWeek Enum to see the difference:

DayOfWeek.Sunday (0) is selected by default so any exception is thrown.

Then, in my EnumFlagsEditor class I would like to prevent this behavior. I want the editor to show a default value in the property grid for my editor. I don't care about the exception, but I would like to display a specific, initial value... to be more exact, the smallest defined value in the source Enum.

How can I do this?.

答:
This is not a UITypeEditor issue, but a TypeConverter issue. What you can do is derive from the standard EnumConverter class, like this:

```<code>[TypeConverter(typeof(MyEnumConverter))]
public enum TestEnum
{
    a = 1,
    b = 2,
    c = 4
}

public class MyEnumConverter : EnumConverter
{
    public MyEnumConverter(Type type)
        : base(type)
    {
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        try
        {
            return base.ConvertTo(context, culture, value, destinationType);
        }
        catch
        {
            if (destinationType == typeof(string))
            {
                // or whatever you see fit
                return "a";
            }
            throw;
        }
    }
}
</code>```

PS: you can avoid the exception catch and do your own conversion, but it may be more difficult than it looks in the general case (depends on enum underlying type, etc.).

Body:
I have a class with name EnumFlagsEditor that inherits from UITypeEditor in order to design a type editor capable to edit a Enum with FlagsAttribute, by using a custom CheckedListBox, and also to be able edit a normal Enum too within the same custom editor.

In the overriden UITypeEditor.GetEditStyle method, I verify whether or not the source Enum has the FlagsAttribute set. If the Enum type has this attribute class, then I return UITypeEditorEditStyle.DropDown to diplay my custom CheckedListBox. If does not have it, I return UITypeEditorEditStyle.Modal and .NET Framework does the rest using the default editor to edit Enums using a default ComboBox to display and select the Enum values/names.

The problem is, the default built-in editor in .NET framework class library to edit a normal Enum, I noticed it searchs for a Enum name with value 0 to display it as default, and If it does not found it, throws a System.ArgumentException and does not display a default value.

Take as example this Enum:

public enum TestEnum {
    a = 1,
    b = 2,
    c = 4
}

That will throw a System.ArgumentException in the editor of a property grid and will not display a default value, because default .NET Framework editor for a Enum expects a value of 0 inside the Enum...

Now, using the System.DayOfWeek Enum to see the difference:

DayOfWeek.Sunday (0) is selected by default so any exception is thrown.

Then, in my EnumFlagsEditor class I would like to prevent this behavior. I want the editor to show a default value in the property grid for my editor. I don't care about the exception, but I would like to display a specific, initial value... to be more exact, the smallest defined value in the source Enum.

How can I do this?.

Body:
This is not a UITypeEditor issue, but a TypeConverter issue. What you can do is derive from the standard EnumConverter class, like this:

[TypeConverter(typeof(MyEnumConverter))]
public enum TestEnum
{
    a = 1,
    b = 2,
    c = 4
}

public class MyEnumConverter : EnumConverter
{
    public MyEnumConverter(Type type)
        : base(type)
    {
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        try
        {
            return base.ConvertTo(context, culture, value, destinationType);
        }
        catch
        {
            if (destinationType == typeof(string))
            {
                // or whatever you see fit
                return "a";
            }
            throw;
        }
    }
}

PS: you can avoid the exception catch and do your own conversion, but it may be more difficult than it looks in the general case (depends on enum underlying type, etc.).


问:
How to get last month record from databse in laravel?

i have a table remaining_bus_fees.

```<code>id    | date         | student_id | remaining_balance
-----------------------------------------------------
1     | 2019-04-05   | 1          |     500
2     | 2019-05-10   | 2          |     400
3     | 2019-05-13   | 3          |     300
</code>```

Now i need how to get last month record against student_id. here is
  query i am using. but this is not working for me.

```<code>$remain_fee = \DB::table('remaining_bus_fees')
        ->whereMonth('date', '<', Carbon::now()->subMonth()->month)
        ->where('student_id', '=', 2)->get();
</code>```

答:
Change your code to this and it should work fine, you need to convert your Carbon::now() to date format as you will use whereDate here, it will consider only date.

```<code>$remain_fee = \DB::table('remaining_bus_fees')
        ->whereDate('date', '<', Carbon::now()->subMonth()->toDateString())
        ->where('student_id', '=', 2)->get();
</code>```

Example in tinker

```<code>>>> App\User::whereDate('created_at', Carbon\Carbon::now()->subMonth()->toDateSt
ring())->get()
=> Illuminate\Database\Eloquent\Collection {#3120
     all: [
       App\User {#3114
         id: 90,
         name: "******",
         email: "******@gmail.com",
         created_at: "2019-05-01 06:17:47",
         updated_at: "2019-05-02 00:28:18",
       },
     ],
   }
>>>
</code>```

Body:
i have a table remaining_bus_fees.

id    | date         | student_id | remaining_balance
-----------------------------------------------------
1     | 2019-04-05   | 1          |     500
2     | 2019-05-10   | 2          |     400
3     | 2019-05-13   | 3          |     300

Now i need how to get last month record against student_id. here is
  query i am using. but this is not working for me.

$remain_fee = \DB::table('remaining_bus_fees')
        ->whereMonth('date', '<', Carbon::now()->subMonth()->month)
        ->where('student_id', '=', 2)->get();

Body:
Change your code to this and it should work fine, you need to convert your Carbon::now() to date format as you will use whereDate here, it will consider only date.

$remain_fee = \DB::table('remaining_bus_fees')
        ->whereDate('date', '<', Carbon::now()->subMonth()->toDateString())
        ->where('student_id', '=', 2)->get();

Example in tinker

>>> App\User::whereDate('created_at', Carbon\Carbon::now()->subMonth()->toDateSt
ring())->get()
=> Illuminate\Database\Eloquent\Collection {#3120
     all: [
       App\User {#3114
         id: 90,
         name: "******",
         email: "******@gmail.com",
         created_at: "2019-05-01 06:17:47",
         updated_at: "2019-05-02 00:28:18",
       },
     ],
   }
>>>


问:
Flutter animations: how to keep position of parent widget
I'm having some trouble with an animation in Flutter.
There are 3 circles next to each other. When one of them is pressed, I want it to expand and collapse. The animation works, but the whole row of circles moves downward when it happens, to keep the top margin of the row the circles are in. How do I make sure the row keeps it original position?

I've only applied the animation to the center circle to test it. I'm sorry if the code is messy, it's because I was testing this. This is the animation and animation controller:

```<code>    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    _animation = Tween(begin: 0.25, end: 0.35).animate(
        CurvedAnimation(parent: _animationController, curve: Curves.elasticIn))
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _animationController.reverse();
        }
      });
</code>```

These are the circles:

```<code>Column(
        children: <Widget>[
Container(
            margin: EdgeInsets.only(top: 16.0),
            child: Center(
              child: Text(
                'Circles',
                style: TextStyle(fontSize: 18),
              ),
            ),
          ),
Container(
            margin: EdgeInsets.only(top: 8.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                ),
                AnimatedBuilder(
                  animation: _animation,
                  builder: (context, child) {
                    return GestureDetector(
                      onTap: () {
                        _animationController.forward();
                      },
                      child: Container(
                        width: MediaQuery.of(context).size.width *
                            _animation.value,
                        height: MediaQuery.of(context).size.height *
                            _animation.value,
                        margin: EdgeInsets.symmetric(horizontal: 8.0),
                        child: Center(child: Text('Circle')),
                        decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(color: AppColors.primaryBlue)),
                      ),
                    );
                  },
                ),
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                )
              ],
            ),
          ),
</code>```

You can probably notice I'm quite new to animations in Flutter, so other feedback is very welcome too. Thanks!

答:
Output:

Full code:

```<code>Column(
  children: <Widget>[
    Container(
      margin: EdgeInsets.only(top: 16.0),
      child: Center(
        child: Text(
          'Circles',
          style: TextStyle(fontSize: 18),
        ),
      ),
    ),
    Container(
      height: 200,
      margin: EdgeInsets.only(top: 8.0),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width * 0.25,
            height: MediaQuery.of(context).size.height * 0.2,
            margin: EdgeInsets.symmetric(horizontal: 8.0),
            child: Center(child: Text('Circle')),
            decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
          ),
          Spacer(),
          AnimatedBuilder(
            animation: _animation,
            builder: (context, child) {
              return GestureDetector(
                onTap: () {
                  _animationController.forward();
                },
                child: Container(
                  width: MediaQuery.of(context).size.width * _animation.value,
                  height: MediaQuery.of(context).size.height * _animation.value,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
                ),
              );
            },
          ),
          Spacer(),
          Container(
            width: MediaQuery.of(context).size.width * 0.25,
            height: MediaQuery.of(context).size.height * 0.2,
            margin: EdgeInsets.symmetric(horizontal: 8.0),
            child: Center(child: Text('Circle')),
            decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
          )
        ],
      ),
    ),
  ],
);
</code>```

Body:
I'm having some trouble with an animation in Flutter.
There are 3 circles next to each other. When one of them is pressed, I want it to expand and collapse. The animation works, but the whole row of circles moves downward when it happens, to keep the top margin of the row the circles are in. How do I make sure the row keeps it original position?

I've only applied the animation to the center circle to test it. I'm sorry if the code is messy, it's because I was testing this. This is the animation and animation controller:

    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    _animation = Tween(begin: 0.25, end: 0.35).animate(
        CurvedAnimation(parent: _animationController, curve: Curves.elasticIn))
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _animationController.reverse();
        }
      });

These are the circles:

Column(
        children: <Widget>[
Container(
            margin: EdgeInsets.only(top: 16.0),
            child: Center(
              child: Text(
                'Circles',
                style: TextStyle(fontSize: 18),
              ),
            ),
          ),
Container(
            margin: EdgeInsets.only(top: 8.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                ),
                AnimatedBuilder(
                  animation: _animation,
                  builder: (context, child) {
                    return GestureDetector(
                      onTap: () {
                        _animationController.forward();
                      },
                      child: Container(
                        width: MediaQuery.of(context).size.width *
                            _animation.value,
                        height: MediaQuery.of(context).size.height *
                            _animation.value,
                        margin: EdgeInsets.symmetric(horizontal: 8.0),
                        child: Center(child: Text('Circle')),
                        decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(color: AppColors.primaryBlue)),
                      ),
                    );
                  },
                ),
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                )
              ],
            ),
          ),

You can probably notice I'm quite new to animations in Flutter, so other feedback is very welcome too. Thanks!

Body:
Output:

Full code:

Column(
  children: <Widget>[
    Container(
      margin: EdgeInsets.only(top: 16.0),
      child: Center(
        child: Text(
          'Circles',
          style: TextStyle(fontSize: 18),
        ),
      ),
    ),
    Container(
      height: 200,
      margin: EdgeInsets.only(top: 8.0),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width * 0.25,
            height: MediaQuery.of(context).size.height * 0.2,
            margin: EdgeInsets.symmetric(horizontal: 8.0),
            child: Center(child: Text('Circle')),
            decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
          ),
          Spacer(),
          AnimatedBuilder(
            animation: _animation,
            builder: (context, child) {
              return GestureDetector(
                onTap: () {
                  _animationController.forward();
                },
                child: Container(
                  width: MediaQuery.of(context).size.width * _animation.value,
                  height: MediaQuery.of(context).size.height * _animation.value,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
                ),
              );
            },
          ),
          Spacer(),
          Container(
            width: MediaQuery.of(context).size.width * 0.25,
            height: MediaQuery.of(context).size.height * 0.2,
            margin: EdgeInsets.symmetric(horizontal: 8.0),
            child: Center(child: Text('Circle')),
            decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
          )
        ],
      ),
    ),
  ],
);


问:
Trying to reformat a list of dictionaries in Python
I have a column called genres in my dataframe where each row consists of a list of dictionaries objects. For example, here is the first row:

```<code>[{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]
</code>```

What I would like to do is reformat this so that each row only contains the information found in the "name" key, preferably dumped into a list.

So for example, the output for the first row would resemble the following:

```<code>["Action", "Adventure", "Fantasy", "Science Fiction"]
</code>```

Any help would be immensely appreciated.

答:
Use list-comprehension that takes out each dictionary out of list and extract 'name':

```<code>[x['name'] for x in lst]
</code>```

In code:

```<code>lst = [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]

print([x['name'] for x in lst])
# ['Action', 'Adventure', 'Fantasy', 'Science Fiction']
</code>```

Body:
I have a column called genres in my dataframe where each row consists of a list of dictionaries objects. For example, here is the first row:

[{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]

What I would like to do is reformat this so that each row only contains the information found in the "name" key, preferably dumped into a list.

So for example, the output for the first row would resemble the following:

["Action", "Adventure", "Fantasy", "Science Fiction"]

Any help would be immensely appreciated.

Body:
Use list-comprehension that takes out each dictionary out of list and extract 'name':

[x['name'] for x in lst]

In code:

lst = [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]

print([x['name'] for x in lst])
# ['Action', 'Adventure', 'Fantasy', 'Science Fiction']


答:
```<code>data = [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]

out = [x['name'] for x in data]

print(out)
</code>```

Title: Trying to reformat a list of dictionaries in Python


问:
Login using restApi(PHP) on Ionic4 not working
I have developed an API in php which contains a Login method. When I run the API in postman with parameters such as email and password, the correct user is returned along with a JWT token that has been generated. However in my code in when I use a post method with the API the user seems to be returned but when I use navCtrl.navigateForward the page wont move from the login page to my dashboard. </p>

```<code>auth-servie.ts

login(email, pw) {
  if (email === '' || pw === '') {
    this.presentAlert();
  } else {
  const params = new HttpParams()
  .set('email', email)
  .set('pw', pw);
  return this.http.post<any>(apiUrl + 'login', {email, pw},
{params});
  }
}

login.ts

login() {
    this.authService.login(this.email, this.pw).subscribe(res => {
          if (res) {
            // store jwt
            // move to dashboard
            console.log('Valid User');
            this.navCtrl.navigateForward('/menu/first');
          }
      },  error => {
          if (error.status === 401) {
            console.log('Authorisation Required');
          }
        }
      );
  }
</code>```

答:
If you get a correct response from your api with the auth token so the problem is in your ionic code, I have never used ionic but take a look to the second answer in the below post:

enter link description here

Regards

Body:
I have developed an API in php which contains a Login method. When I run the API in postman with parameters such as email and password, the correct user is returned along with a JWT token that has been generated. However in my code in when I use a post method with the API the user seems to be returned but when I use navCtrl.navigateForward the page wont move from the login page to my dashboard.

auth-servie.ts

login(email, pw) {
  if (email === '' || pw === '') {
    this.presentAlert();
  } else {
  const params = new HttpParams()
  .set('email', email)
  .set('pw', pw);
  return this.http.post<any>(apiUrl + 'login', {email, pw},
{params});
  }
}

login.ts

login() {
    this.authService.login(this.email, this.pw).subscribe(res => {
          if (res) {
            // store jwt
            // move to dashboard
            console.log('Valid User');
            this.navCtrl.navigateForward('/menu/first');
          }
      },  error => {
          if (error.status === 401) {
            console.log('Authorisation Required');
          }
        }
      );
  }


问:
TextView button using bluetooth keyboard and voice assistant
I have two TextView in xml as buttons (Yes) and (No). I'm testing a mobile application using a bluetooth keyboard and voice assistant for blind people. What I want to happen is when the user selects the Yes button the voice assistant will say "Yes is selected" or if the user selects No it will say "No is selected".

I'm using Android Studio. This is an old mobile application that needs to be updated for blind people.

```<code><TextView
    android:id="@+id/vhr_question_yes"
    android:text="Yes"
    android:clickable="true" />
<TextView
    android:id="@+id/vhr_question_no"
    android:text="No"
    android:clickable="true" />
</code>```

答:
You may set the view state to selected. This way, the screen reader will notify the user a change on its state.

```<code>textView.setOnClickListener { view ->
    view.isSelected = true
}
</code>```

In this case above, the screen reader will announce only that the view is selected. When the user navigates back to this view, the reader will announce again that this view is selected.

If you really need the entire text to be spoken, you may use a screen reader announcement.

```<code>textView.setOnClickListener {view ->
    view.isSelected = true

    (view as? TextView)?.let {
        it.announceForAccessibility("${it.text} is selected")
    }
}
</code>```

The user may rely on consistency through the platform. When a view is selected, the reader may read as selected, yes. So, announcements should be used carefully.
Also, using only announcements, the selected state will not be persisted if the user comes back to this view later.

Body:
I have two TextView in xml as buttons (Yes) and (No). I'm testing a mobile application using a bluetooth keyboard and voice assistant for blind people. What I want to happen is when the user selects the Yes button the voice assistant will say "Yes is selected" or if the user selects No it will say "No is selected".

I'm using Android Studio. This is an old mobile application that needs to be updated for blind people.

<TextView
    android:id="@+id/vhr_question_yes"
    android:text="Yes"
    android:clickable="true" />
<TextView
    android:id="@+id/vhr_question_no"
    android:text="No"
    android:clickable="true" />

Body:
You may set the view state to selected. This way, the screen reader will notify the user a change on its state.

textView.setOnClickListener { view ->
    view.isSelected = true
}

In this case above, the screen reader will announce only that the view is selected. When the user navigates back to this view, the reader will announce again that this view is selected.

If you really need the entire text to be spoken, you may use a screen reader announcement.

textView.setOnClickListener {view ->
    view.isSelected = true

    (view as? TextView)?.let {
        it.announceForAccessibility("${it.text} is selected")
    }
}

The user may rely on consistency through the platform. When a view is selected, the reader may read as selected, yes. So, announcements should be used carefully.
Also, using only announcements, the selected state will not be persisted if the user comes back to this view later.


问:
What open-source QR Code Generator would you recommend?
I'm looking for a library to generate QR codes in .NET I've stumbled across a few paid ones, but very few free ones that look any good. Anyone have experience with a good free open-source library?

Thanks

答:
In past I used this one.

It's really "heavy" (about 6MB) but it worked for me and it's released under Code Project Open License (CPOL). I forgot: C# source code is provided.

Another one is MessagingToolKit, which is provided even with a free license; I don't remember (excuse me) if QR is inside free license or not.


问:
"Scrollbar not showing in 'firefox browser' css problem"
Scrollbar not showing in firefox browser but in chrome it is working fine below is the css code

```<code>::ng-deep .adf-search-fitler {
  overflow-y: auto;
  height: -webkit-fill-available;
  width: 300px;
  max-width: none;
  min-width: 300px;
}
</code>```

This -webkit-fill-available will work on chrome browser but "how to achieve the scrollbar 'firefox browser'"

答:
You can add multiple height properties:

```<code>::ng-deep .adf-search-fitler {
  overflow-y: auto;
  height: -webkit-fill-available;
  height: -moz-available;
  height: fill-available;
  width: 300px;
  max-width: none;
  min-width: 300px;
}
</code>```

To explain it -moz will be ignored by chrome and vice versa.

Body:
Scrollbar not showing in firefox browser but in chrome it is working fine below is the css code

::ng-deep .adf-search-fitler {
  overflow-y: auto;
  height: -webkit-fill-available;
  width: 300px;
  max-width: none;
  min-width: 300px;
}

This -webkit-fill-available will work on chrome browser but "how to achieve the scrollbar 'firefox browser'"

Body:
You can add multiple height properties:

::ng-deep .adf-search-fitler {
  overflow-y: auto;
  height: -webkit-fill-available;
  height: -moz-available;
  height: fill-available;
  width: 300px;
  max-width: none;
  min-width: 300px;
}

To explain it -moz will be ignored by chrome and vice versa.


问:
clicking on download complete notification shows “Can't open file” toast?
First in my app I let system downloader app download an apk for me. Then I use This code to install the apk file downloaded by Android default download manager:

```<code>if (getFileId() == downloadId) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + getFileName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
    Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
    intent.setData(apkUri);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
} else {
    Uri apkUri = Uri.fromFile(file);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
}
</code>```

This code automatically runs when download is finished and a download receiver is called. And it works well. Problem is if user clicks on the notification made by default system download manager (Download complete notification), in API >= 23, I get a "Can't open file" message, which is very annoying (For any reason user might want to click on the notification). I want user be able to install apk file when they click on the notification, which is already working at api<23. How can I solve this problem?

答:
Most likely it has to do with the way that Android 7.0 handles permissions as compared to 6.0. You need to request permissions in a different way since Android 7.0. Try to tinker with the ContextCompat.checkSelfPermission() method. The message would be shown because the permission to open file is not requested with this method. Here's a little snippet to get you on the right track:

```<code>if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

      ActivityCompat.requestPermissions(thisActivity,
              new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
              YourRequestCode);
}
</code>```

Here, thisActivity is your current activity.

Body:
First in my app I let system downloader app download an apk for me. Then I use This code to install the apk file downloaded by Android default download manager:

if (getFileId() == downloadId) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + getFileName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
    Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
    intent.setData(apkUri);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
} else {
    Uri apkUri = Uri.fromFile(file);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
}

This code automatically runs when download is finished and a download receiver is called. And it works well. Problem is if user clicks on the notification made by default system download manager (Download complete notification), in API >= 23, I get a "Can't open file" message, which is very annoying (For any reason user might want to click on the notification). I want user be able to install apk file when they click on the notification, which is already working at api<23. How can I solve this problem?

Body:
Most likely it has to do with the way that Android 7.0 handles permissions as compared to 6.0. You need to request permissions in a different way since Android 7.0. Try to tinker with the ContextCompat.checkSelfPermission() method. The message would be shown because the permission to open file is not requested with this method. Here's a little snippet to get you on the right track:

if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

      ActivityCompat.requestPermissions(thisActivity,
              new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
              YourRequestCode);
}

Here, thisActivity is your current activity.


问:
How do I make to some of the files that I have changed is not offered in the commit?
I use TortoiseGit 1.8.3.
I changed one of the files: Makefile, but I want to not offer commit it to me every once in a Git Commit.
I added it to the "delete and add to ignore list", but it does not help.
How do I make to some of the files that I have changed is not offered in the commit?

I want, that Makefile was in remote repository as read-only, that I could edit it locally, and then TortoiseGit does not offer to me to commit it.

That I wanted for Git-bash: https://www.kernel.org/pub/software/scm/git/docs/git-update-index.html

答: The approved answer is good but in case you're hunting for the dialogues and options here you have a short help:


问:
array filter in python?
For example, I have two lists

```<code> A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements
</code>```

Is there a built-in function in python to do this?

答:
No, there is no build in function in python to do this, because simply:

```<code>set(A)- set(subset_of_A)
</code>```

will provide you the answer.

Title: array filter in python?

Body:
For example, I have two lists

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements

Is there a built-in function in python to do this?

Body:
No, there is no build in function in python to do this, because simply:

set(A)- set(subset_of_A)

will provide you the answer.


问:
Error Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name.
I keep getting this error
Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name.
i am trying to use the default view from
from django.contrib.auth.views

```<code>from django.conf.urls import url
from accounts import views
from django.contrib.auth.views import (login,
logout,
password_reset,
password_reset_done,
password_reset_confirm,
)

urlpatterns =[
url(r'^$', views.cover, name='cover'),
url(r'^home/$', views.home, name = 'home'),
url(r'^login/$', login, {'template_name':'accounts/login.html'}, name ="login"),
url(r'^logout/$', logout, {'template_name':'accounts/logout.html'}, name = "logout"), # views define a link to connecct this to views then to template
url(r'^register/$', views.register, name="register"),
url(r'^profile/$', views.view_profile, name='view_profile'),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
url(r'^change-password/$', views.change_password, name='change_password'),
url(r'^reset-password/$', password_reset, name= 'password_reset'),
url(r'^reset-password/done/$', password_reset_done, name='password_reset_done'),
url(r'^reset-password/confirm/$', password_reset_confirm, name='password_reset_confirm')
]
</code>```

Please anybody help me out... i have check all... but couldnt find the fault.

答:
For me the key info that was missing was the reverse resolve needing the name attribute set on the url entry!

```<code>    path(
    'password_change/done/',
    auth_views.PasswordChangeDoneView.as_view(template_name='SyllabusTrackerApp/change-password-done.html'),
    name="password_change_done"
),
</code>```

The app_name namespace wasn't set either, but those weren't used in my setup for simplicity, so I could ignore that.

Body:
I keep getting this error
Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name.
i am trying to use the default view from
from django.contrib.auth.views

from django.conf.urls import url
from accounts import views
from django.contrib.auth.views import (login,
logout,
password_reset,
password_reset_done,
password_reset_confirm,
)

urlpatterns =[
url(r'^$', views.cover, name='cover'),
url(r'^home/$', views.home, name = 'home'),
url(r'^login/$', login, {'template_name':'accounts/login.html'}, name ="login"),
url(r'^logout/$', logout, {'template_name':'accounts/logout.html'}, name = "logout"), # views define a link to connecct this to views then to template
url(r'^register/$', views.register, name="register"),
url(r'^profile/$', views.view_profile, name='view_profile'),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
url(r'^change-password/$', views.change_password, name='change_password'),
url(r'^reset-password/$', password_reset, name= 'password_reset'),
url(r'^reset-password/done/$', password_reset_done, name='password_reset_done'),
url(r'^reset-password/confirm/$', password_reset_confirm, name='password_reset_confirm')
]

Please anybody help me out... i have check all... but couldnt find the fault.

Body:
For me the key info that was missing was the reverse resolve needing the name attribute set on the url entry!

    path(
    'password_change/done/',
    auth_views.PasswordChangeDoneView.as_view(template_name='SyllabusTrackerApp/change-password-done.html'),
    name="password_change_done"
),

The app_name namespace wasn't set either, but those weren't used in my setup for simplicity, so I could ignore that.


问:
Why is a device needed between JTAG and the TRACE32 software from Lauterbach?
What is the point of having this rectangular thingy like https://www.microsemi.com/images/soc/partners/solution/ip/Trace_small.jpg? How comes that gdbserver is able to debug over the Ethernet without any additional H/W and this TRACE32 behemoth S/W itself cannot decode/encode signals coming out of and to JTAG port? Isn't JTAG a port itself? Doesn't it send signals? Why cannot this piece of S/W interpret them? Why is this thingy needed (which BTW once works, once doesn't and in general is black magic). Is there a reason for existing of a specific device between JTAG and USB port (having in mind that TRACE32 installations has 800 MB...)</p>

答:
There are probably certain aspects to consider:

Run mode debugging vs. Stop mode debugging

Simple signal converter vs. Smart debug probe

Pure JTAG debugger vs. Debug & Trace tool

Run mode debugging vs. Stop mode debugging

"Run mode debugging" means "Debug an application on a system running an operating system". That is what is also happening when you debug an application on your Windows/Linux/Mac machine. When you hit a breakpoint in your application the CPU is still running. It is only the debugged application which is stopped.

So if your embedded system is running an operating system your GDB might be able to connect via Ethernet to a gdbserver running on your target OS, which allows your to debug an application on your device.

"Stop mode debugging" means "Debugging all software on a CPU by controlling the run-state of the CPU". So if you hit a breakpoint on a CPU with stop mode debugging, your entire CPU will stop. This allows you to debug bare metal applications or an operation system itself or an application in the context of the operation system or even a hypervisor.

For stop mode debugging you usually need a chip with a JTAG interface (or SWD or similar) and an in-circuit debugger. Basically something which allows you to control the CPU on a very low level. In former times this was done by using an in-circuit emulator (instead of JTAG) which replaced the CPU with a special bond-out chip, which allowed also to control the chip on a very low level. To make thinks more confusing some vendors call their JTAG probes also "in-circuit emulator".

Simple signal converter vs. Smart debug probe

For stop mode debugging you need a probe which converts the interfaces of your PC to the low level debug interface of your chip. So basically some USB to JTAG converter. Or and Ethernet to JTAG converter.

The simplest probe I can think of is simply some device which allows you to control some GPIOs (General Purpose Input Output) pins via USB. Then all the JTAG communication protocol and higher debug protocol is totally done in software. Advantage: Very flexible. Disadvantage: Very slow.

More advanced probes know how to do JTAG and thus, only the high level debug protocol has to be handled via USB, while the low level JTAG communication is done by the probe itself. These probes are often still quite slow, since USB is not so efficient when you need short latencies.

High end probes usually handle the debug protocol itself, which is individual for each CPU architecture or sometimes even for a single chip. So the host PC running the debug software sends only a high level command like "do a single step", while all the rest is handled by the probe itself. This boosts performance especially with complex multicore chips which required often a lot of JTAG communication until even a simple task completes.

Simple USB to JTAG converters are often already on the PCB of cheap evaluation boards. In theory you could also integrate such a converter directly in the chip itself, but this is usually not done by the chip manufacturers, since it would increase the costs of every single chip. In the professional sector high end debuggers are pretty common, because companies don't want to have their developers sitting in front of their PC just waiting for a slow debugger to finish an application download.

In general I assume that the faster, more flexible and more feature-rich a debugger is, the bigger and more expensive it gets. So it depends a lot on your needs.

Pure JTAG debugger vs. Debug & Trace tool

All JTAG debuggers allow you to stop and restart your CPU, set breakpoints and read and write memory and CPU registers. That is the stop more debugging I've mentioned above.

Some debug probes allow you also to record the code execution and data accesses by the CPU while the CPU is running and without stopping it. This is called a Real Time Trace. For such a trace recording you need both a debug probe and a chip which supports this.

E.g. on ARM Cortex chips this feature is called the ETM, which is not available with Cortex-M0/M0+ chips but usually available with Cortex-A/R chips and Cortex-M3 (and bigger) chips when the chip has 100 pins and more.

Tools which support trace are usually bigger and more expensive than debug probes without trace support.

Things which have an influence on the price of a debugger with trace recorder:

Size of internal memory to save the trace data

Supported maximum speed on one target trace pin (for parallel trace).

Number of supported trace pins (for parallel trace) (e.g. single pin SWO trace is usually much cheaper than ETM trace).

Support of high speed serial trace ports/maximum speed per lane/number of supported lanes.

Upload speed to the host PC (Does the probe have a USB 3 and/or Gigabit Ehternet inteface or just USB 2?)

The device from Lauterbach, which you are referring to, supports the tracing of Cortex-M chips with a total of 1600 MBit/s on the trace port. The official product page is here https://www.lauterbach.com/microtrace_cortexm.html

You wrote

which BTW once works, once doesn't and in general is black magic

If your tool is not working, I suggest to request support from your tool vendor. For Lauterbach visit https://www.lauterbach.com/tsupport.html

JTAG debugging itself is really not black magic: The JTAG protocol itself is an IEEE standard and the debug protocol (on the next level) is often described in the chip manufacturers manuals accessible to the public. However it is of course a lot of engineering.


问:
How to paginate images from photo library in UICollectionView
I have imported images from photoLibrary in UICollectionView and the collectionView take a lot of time to initial the photo inside the collectionView so I need to pagination these images by vertical scroll firstly I want to load in collectionView 10 images then the user paginate load 10 images and the process continue</p>

```<code>import UIKit
import Photos
import XLPagerTabStrip

private let reuseIdentifier = "Cell"

class PhotosRecyclerCollection: UICollectionViewController, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate {

    var imageArray = [UIImage]()

    override func viewDidLoad() {
        grabPhotos()
    }

    func grabPhotos(){

        let imgManager = PHImageManager.default()

        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = true
        requestOptions.deliveryMode = .highQualityFormat

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions) {

            if fetchResult.count > 0 {

                for i in 0..<fetchResult.count{

                    imgManager.requestImage(for: fetchResult.object(at: i) as! PHAsset, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: {

                        image , error in

                        self.imageArray.append(image!)
                    })
                }
            }

            else {

                print("You got no photos")

                self.collectionView?.reloadData()
            }
        }

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotosCollectionViewCell", for: indexPath) as! PhotosCollectionViewCell

        let imageView = cell.viewWithTag(1) as! UIImageView

        imageView.image = imageArray[indexPath.row]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let width = collectionView.frame.width / 4 - 1

        return CGSize(width: width, height: width)

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let mainStoryBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let desVC = mainStoryBoard.instantiateViewController(withIdentifier: "imageCropper") as! ImageCropperViewController
        desVC.image = imageArray[indexPath.row]
        self.navigationController?.pushViewController(desVC, animated: true)
    }

}
</code>```

答:
You don't need to paginate. It takes a lot of time to load because you are preloading all the images.

Simply stop preloading the images in memory and just get the relevant image when it is actually needed.

To do so add fetchResult as an instance variable:

```<code>private var fetchResult: PHFetchResult?
</code>```

Replace

```<code>if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions) {

            if fetchResult.count > 0 {

                for i in 0..<fetchResult.count{

                    imgManager.requestImage(for: fetchResult.object(at: i) as! PHAsset, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: {

                        image , error in

                        self.imageArray.append(image!)
                    })
                }
            }
</code>```

with

```<code>if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
{
    self.fetchResult = fetchResult
}
</code>```

Replace return imageArray.count with return self.fetchResult?.count ?? 0

And finally:

```<code>let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = imageArray[indexPath.row]
</code>```

with

```<code>imgManager.requestImage(for: fetchResult!.object(at: i) as! PHAsset, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: { image , error in
    let currentIndexPath = collectionView.indexPath(for: cell)
    if (currentIndexPath.compare(indexPath) == .orderedSame) {
        let imageView = cell.viewWithTag(1) as! UIImageView
        imageView.image = image

    }
})
</code>```

Body:
I have imported images from photoLibrary in UICollectionView and the collectionView take a lot of time to initial the photo inside the collectionView so I need to pagination these images by vertical scroll firstly I want to load in collectionView 10 images then the user paginate load 10 images and the process continue

import UIKit
import Photos
import XLPagerTabStrip

private let reuseIdentifier = "Cell"

class PhotosRecyclerCollection: UICollectionViewController, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate {

    var imageArray = [UIImage]()

    override func viewDidLoad() {
        grabPhotos()
    }

    func grabPhotos(){

        let imgManager = PHImageManager.default()

        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = true
        requestOptions.deliveryMode = .highQualityFormat

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions) {

            if fetchResult.count > 0 {

                for i in 0..<fetchResult.count{

                    imgManager.requestImage(for: fetchResult.object(at: i) as! PHAsset, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: {

                        image , error in

                        self.imageArray.append(image!)
                    })
                }
            }

            else {

                print("You got no photos")

                self.collectionView?.reloadData()
            }
        }

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotosCollectionViewCell", for: indexPath) as! PhotosCollectionViewCell

        let imageView = cell.viewWithTag(1) as! UIImageView

        imageView.image = imageArray[indexPath.row]

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let width = collectionView.frame.width / 4 - 1

        return CGSize(width: width, height: width)

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let mainStoryBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let desVC = mainStoryBoard.instantiateViewController(withIdentifier: "imageCropper") as! ImageCropperViewController
        desVC.image = imageArray[indexPath.row]
        self.navigationController?.pushViewController(desVC, animated: true)
    }

}

Body:
You don't need to paginate. It takes a lot of time to load because you are preloading all the images.

Simply stop preloading the images in memory and just get the relevant image when it is actually needed.

To do so add fetchResult as an instance variable:

private var fetchResult: PHFetchResult?

Replace

if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions) {

            if fetchResult.count > 0 {

                for i in 0..<fetchResult.count{

                    imgManager.requestImage(for: fetchResult.object(at: i) as! PHAsset, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: {

                        image , error in

                        self.imageArray.append(image!)
                    })
                }
            }

with

if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
{
    self.fetchResult = fetchResult
}

Replace return imageArray.count with return self.fetchResult?.count ?? 0

And finally:

let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = imageArray[indexPath.row]

with

imgManager.requestImage(for: fetchResult!.object(at: i) as! PHAsset, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: { image , error in
    let currentIndexPath = collectionView.indexPath(for: cell)
    if (currentIndexPath.compare(indexPath) == .orderedSame) {
        let imageView = cell.viewWithTag(1) as! UIImageView
        imageView.image = image

    }
})