问:
Django Rest Framework HTTP Post Calls and Authentication with Ionic Framework
I implemented the Django Rest Framework into my Django project so I could use Django as a backend to my Ionic Framework app while maintaining the web app that I can make with Django. I went through the process to OAuth2, using the oauth toolkit, but now I am unsure on how to make the http request calls from the ionic framework side to authenticate a user and get a token. So far on the Ionic side I have the http request as:

```<code>login(username, password, url) {
    let headers = new Headers()
    headers.append("Content-Type", "application/x-www-form-urlencoded");

    return this.http.post(url,
      {"username": username,
        "password": password,
      }, {headers: headers})
      .map(res => res.json());
  }
</code>```

But when I run it in my browser, I get No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.

On the server side the curl command curl -X POST -d "grant_type=password&username=USERNAME&password=PASSWORD" -u "CLIENT ID:CLIENT SECRET" https://www.example.com/o/token/ works perfectly fine and returns a token, where USERNAME, PASSWORD, CLIENT ID, and CLIENT SECRET are all the respective values.

I'm not sure if this is the right question, but how do I turn the cURL command into something I can use in my Ionic app?

These are my Rest Framework and CORS Settings:

```<code>REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ]
}

CORS_ORIGIN_WHITELIST = [
    'localhost:8100',
]

CORS_ALLOW_CREDENTIALS = True
</code>```

答:
So it turns out that if you are sending requests with the origin being localhost or 127.0.0.1, which is the same thing, most browsers send the origin as Null, so it is better to add CORS_ORIGIN_ALLOW_ALL = True to the settings.py file of the main Django project.

Once that was there, I was getting errors about the grant_type being invalid, so in my request I had to add "grant_type": "password", and I also had to add "client_id": <your client id here> where the <your client id here> is your client id without the <>.

I also found that Postman is a great application to help with api creation and translating cURL commands into HTTP requests that work.

Body:
I implemented the Django Rest Framework into my Django project so I could use Django as a backend to my Ionic Framework app while maintaining the web app that I can make with Django. I went through the process to OAuth2, using the oauth toolkit, but now I am unsure on how to make the http request calls from the ionic framework side to authenticate a user and get a token. So far on the Ionic side I have the http request as:

login(username, password, url) {
    let headers = new Headers()
    headers.append("Content-Type", "application/x-www-form-urlencoded");

    return this.http.post(url,
      {"username": username,
        "password": password,
      }, {headers: headers})
      .map(res => res.json());
  }

But when I run it in my browser, I get No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.

On the server side the curl command curl -X POST -d "grant_type=password&username=USERNAME&password=PASSWORD" -u "CLIENT ID:CLIENT SECRET" https://www.example.com/o/token/ works perfectly fine and returns a token, where USERNAME, PASSWORD, CLIENT ID, and CLIENT SECRET are all the respective values.

I'm not sure if this is the right question, but how do I turn the cURL command into something I can use in my Ionic app?

These are my Rest Framework and CORS Settings:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ]
}

CORS_ORIGIN_WHITELIST = [
    'localhost:8100',
]

CORS_ALLOW_CREDENTIALS = True


来源: stackexchange

问:
How do I use PowerShell to remove registry keys from a remote computer?
I am trying to use PowerShell to remove profiles and associated registry entries on remote computers. The account I am using has administrator permissions on the remote computers. I have no trouble pulling the SIDs of the accounts or deleting the profile. My problem comes when trying to remove the registry key for the account located at HKLM:\SOFTWARE\Microsoft\'Windows NT'\CurrentVersion\ProfileList. There is a key for every SID and I want to remove the ones that match the profiles I am deleting.

This is what I have tried so far:

```<code>Enter-PSSession $comp
Remove-Item "HKLM:\SOFTWARE\Microsoft\'Windows NT'\CurrentVersion\ProfileList\$SID"
Exit-PSSession
</code>```

This got the following result:

```<code>Remove-Item : Cannot find path 'HKLM:\SOFTWARE\Microsoft\'Windows
NT'\CurrentVersion\ProfileList\S-1-5-21-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-1000' because it does not exist.
</code>```

If I run the same command on the local machine, the key is deleted successfully.

I also tried:

```<code>Enter-PSSession $comp
Remove-ItemProperty -path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' -name $SID
Exit-PSSession
</code>```

Which returned the following:

```<code>Remove-Itemproperty : Requested registry access is not allowed.
</code>```

I have also tried using invoke-command to run the exact same command that works locally and I get the same error.

Is there something I am missing? Can any of you kind folks point out what I am doing wrong? I would really like to do this with built-in commands rather than installing a third party module if possible.

答:
If you are looking to remove user profiles and cannot use a third party tool I would recommend using the CIM classes.

```<code>Get-CimInstance -ClassName Win32_UserProfile -Filter "SID = 'S-1-5-21-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-1000'" -ComputerName $comp | Remove-CIMInstance -WhatIf
</code>```

If you do not have winrm enabled or configured you can fallback on WMI.

```<code>Get-WmiObject -Class WIN32_UserProfile -Filter "SID = 'S-1-5-21-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-1000'" -ComputerName $comp | Remove-WmiObject -WhatIf
</code>```

This will get not only the registry key but also the folders associated with the profile.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use PowerShell to remove profiles and associated registry entries on remote computers. The account I am using has administrator permissions on the remote computers. I have no trouble pulling the SIDs of the accounts or deleting the profile. My problem comes when trying to remove the registry key for the account located at HKLM:\SOFTWARE\Microsoft\'Windows NT'\CurrentVersion\ProfileList. There is a key for every SID and I want to remove the ones that match the profiles I am deleting.

This is what I have tried so far:

Enter-PSSession $comp
Remove-Item "HKLM:\SOFTWARE\Microsoft\'Windows NT'\CurrentVersion\ProfileList\$SID"
Exit-PSSession

This got the following result:

Remove-Item : Cannot find path 'HKLM:\SOFTWARE\Microsoft\'Windows
NT'\CurrentVersion\ProfileList\S-1-5-21-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-1000' because it does not exist.

If I run the same command on the local machine, the key is deleted successfully.

I also tried:

Enter-PSSession $comp
Remove-ItemProperty -path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' -name $SID
Exit-PSSession

Which returned the following:

Remove-Itemproperty : Requested registry access is not allowed.

I have also tried using invoke-command to run the exact same command that works locally and I get the same error.

Is there something I am missing? Can any of you kind folks point out what I am doing wrong? I would really like to do this with built-in commands rather than installing a third party module if possible.

Body:
If you are looking to remove user profiles and cannot use a third party tool I would recommend using the CIM classes.

Get-CimInstance -ClassName Win32_UserProfile -Filter "SID = 'S-1-5-21-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-1000'" -ComputerName $comp | Remove-CIMInstance -WhatIf

If you do not have winrm enabled or configured you can fallback on WMI.

Get-WmiObject -Class WIN32_UserProfile -Filter "SID = 'S-1-5-21-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-1000'" -ComputerName $comp | Remove-WmiObject -WhatIf

This will get not only the registry key but also the folders associated with the profile.


问:
new never fails?
In C++, we usually see and write code like,

```<code>Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}
</code>```

But in C#, I rarely see this: (at least I've never seen this)

```<code>Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}
</code>```

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

答:
In C++, unlike malloc, new doesn't return NULL on failure. In fact, it throws a std::bad_alloc exception on failure.

If you want new to return NULL on failure, you have to explicitly tell it not to throw an exception. Use std::nothrow version for that purpose. (header file : <new>)

ContentLicense: CC BY-SA 2.5

Title: new never fails?

Body:
In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.


问:
Failing to login when scraping a forum using python-requests
I am trying to scrape a forum, but I can't resolve the login part

Context about the forum to scrape

The part I want to scrape is only available to logged-in users. The forum seems to be phpBB. I can't give you the link because it is local.

Attempt to log-in using requests

I have tried to authenticate with following code:

url = 'http://forum.com'  #not real one XD

pet = requests.get(url, auth=HTTPBasicAuth('user', 'passw'), verify=False)
```
<p>and also:</p>
<pre class="lang-py prettyprint-override"><code>pet =requests.get(url, auth=HTTPDigestAuth('user', 'pass'), verify=False)
</code>```

Parsing HTML to extract content

For information extraction I use BeautifulSoup:

soup = BeautifulSoup(pet.content)
print(soup.prettify())
```
<h3>Problem</h3>
<p>When I execute those commands, it returns the information of the forum page without login. So apparently the login thing doesn't work.</p>
<p>I put <code>Verify=False</code> because if I don't, then an SSL-error is raised.</p>
<p>How can I achieve this?
I would prefer solutions using the <em>requests</em> module, but also others are welcome.</p>
<h3>Authentication and Login-Page</h3>
<p>I don't know what kind of authentication the forum has (Basic, Digest, ...).</p>
<p>This is the piece of HTML from the login-page where the user and password are asked:</p>
<pre class="lang-html prettyprint-override"><code>    <dl>
          <dt>
           <label for="username">
            Nombre de Usuario:
           </label>
          </dt>
          <dd>
           <input class="inputbox autowidth" id="username" name="username" size="25" tabindex="1" type="text" value=""/>
          </dd>
         </dl>
         <dl>
          <dt>
           <label for="password">
            Contraseña:
           </label>
          </dt>
          <dd>
           <input autocomplete="off" class="inputbox autowidth" id="password" name="password" size="25" tabindex="2" type="password"/>
          </dd>
          <dd>

            Olvidé mi contraseña

          </dd>
         </dl>
         <dl>
          <dd>
           <label for="autologin">
            <input id="autologin" name="autologin" tabindex="4" type="checkbox"/>
            Recordar
           </label>
          </dd>
          <dd>
           <label for="viewonline">
            <input id="viewonline" name="viewonline" tabindex="5" type="checkbox"/>
            Ocultar mi estado de conexión en esta sesión
           </label>
          </dd>
         </dl>
         <input name="redirect" type="hidden" value="./search.php?search_id=newposts"/>
         <dl>
          <dt>
          </dt>
          <dd>
           <input name="sid" type="hidden" value="b48ad769e2eab979294621d07e3ef19d"/>
           <input class="button1" name="login" tabindex="6" type="submit" value="Identificarse"/>
          </dd>
         </dl>
</code>```

Remark:

When I make a request for the page to scrape (the one that doesn't appear unless logged-in), it returns a HTTP status code 200.
But the HTML it returns is the one of the login-page.

答: when doing an auth to a page, curiously you do not send the requests to the login page, you directs the requests to the page that you want to scrap (in case it's using basic outh) Try it out.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to scrape a forum, but I can't resolve the login part

Context about the forum to scrape

The part I want to scrape is only available to logged-in users. The forum seems to be phpBB. I can't give you the link because it is local.

Attempt to log-in using requests

I have tried to authenticate with following code:

url = 'http://forum.com'  #not real one XD

pet = requests.get(url, auth=HTTPBasicAuth('user', 'passw'), verify=False)

and also:

pet =requests.get(url, auth=HTTPDigestAuth('user', 'pass'), verify=False)

Parsing HTML to extract content

For information extraction I use BeautifulSoup:

soup = BeautifulSoup(pet.content)
print(soup.prettify())

Problem

When I execute those commands, it returns the information of the forum page without login. So apparently the login thing doesn't work.

I put Verify=False because if I don't, then an SSL-error is raised.

How can I achieve this?
I would prefer solutions using the requests module, but also others are welcome.

Authentication and Login-Page

I don't know what kind of authentication the forum has (Basic, Digest, ...).

This is the piece of HTML from the login-page where the user and password are asked:

            Nombre de Usuario:

           <input class="inputbox autowidth" id="username" name="username" size="25" tabindex="1" type="text" value=""/>

            Contraseña:

           <input autocomplete="off" class="inputbox autowidth" id="password" name="password" size="25" tabindex="2" type="password"/>

            Olvidé mi contraseña

            <input id="autologin" name="autologin" tabindex="4" type="checkbox"/>
            Recordar

            <input id="viewonline" name="viewonline" tabindex="5" type="checkbox"/>
            Ocultar mi estado de conexión en esta sesión

         <input name="redirect" type="hidden" value="./search.php?search_id=newposts"/>

           <input name="sid" type="hidden" value="b48ad769e2eab979294621d07e3ef19d"/>
           <input class="button1" name="login" tabindex="6" type="submit" value="Identificarse"/>

Remark:

When I make a request for the page to scrape (the one that doesn't appear unless logged-in), it returns a HTTP status code 200.
But the HTML it returns is the one of the login-page.


问:
Async function not returning value, but console.log() does: how to do?
I have an es6 class, with an init() method responsible for fetching data, transforming it, then update the class's property this.data with newly transformed data.
So far so good.
The class itself has another getPostById() method, to just do what it sounds like. Here is the code for the class:

```<code>class Posts {
  constructor(url) {
    this.ready = false
    this.data = {}
    this.url = url
  }
  async init() {
      try {
        let res = await fetch( this.url )
        if (res.ok) {
            let data = await res.json()

          // Do bunch of transformation stuff here

          this.data = data
          this.ready = true
            return data
        }
      }
      catch (e) {
         console.log(e)
      }
  }
  getPostById(id){
     return this.data.find( p => p.id === id )
  }
}
</code>```

Straightforward, except I have an async/await mechanism in the init() method.
Now, this code will work correctly:

```<code>let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')

allPosts.init()
        .then( d => console.log(allPosts.getPostById(4)) )
// resulting Object correctly logged in console
</code>```

but it only gets printed into the console:
How could I use allPosts.getPostById(4) as a return of a function ?

Like:

```<code>let myFunc = async () => {
   const postId = 4
   await allPosts.init()  // I need to wait for this to finish before returning

   // This is logging correct value
   console.log( 'logging: ' + JSON.stringify(allPosts.getPostById( postId ), null, 4) )

   // How can I return the RESULT of allPosts.getPostById( postId ) ???
   return allPosts.getPostById( postId )
}
</code>```

myFunc() returns a Promise but not the final value. I have read several related posts on the subject but they all give example of logging, never returning.

Here is a fiddle that includes two ways of handling init(): using Promise and using async/await. No matter what I try, I can't manage to USE the FINAL VALUE of getPostById(id).

The question of this post is: how can I create a function that will RETURN the VALUE of getPostById(id) ?

EDIT:

A lot of good answers trying to explain what Promises are in regards to the main execution loop.
After a lot of videos and other good reads, here is what I understand now:

my function init() correctly returns. However, within the main event loop: it returns a Promise, then it is my job to catch the result of this Promise from within a kinda parallel loop (not a new real thread). In order to catch the result from the parallel loop there are two ways:

use .then( value => doSomethingWithMy(value) )

use let value = await myAsyncFn(). Now here is the foolish hiccup:

await can only be used within an async function :p

thus itself returning a Promise, usable with await which should be embed in an async function, which will be usable with await etc...

This means we cannot really WAIT for a Promise: instead we should catch parallel loop indefinitely: using .then() or async/await.

Thanks for the help !

答:
Your question and the comments suggest you could use a little intuition nudge about the way the event loop works. It really is confusing at first, but after a while it becomes second nature.

Rather than thinking about the FINAL VALUE, think about the fact that you have a single thread and you can't stop it — so you want the FUTURE VALUE -- the value on the next or some future event loop. Everything you write that is not asynchronous is going to happen almost immediately — functions return with some value or undefined immediately. There's nothing you can do about. When you need something asynchronously, you need to setup a system that is ready to deal with the async values when they return sometime in the future. This is what events, callbacks, promises (and async/await) all try to help with. If some data is asynchronous, you simply can not use it in the same event loop.

So what do you do?

If you want a pattern where you create an instance, call init() and then some function that further process it, you simply need to setup a system that does the processing when the data arrives. There are a lot of ways to do this. Here's one way that's a variation on your class:

function someAsync() {
  console.log("someAsync called")
  return new Promise(resolve => {
    setTimeout(() => resolve(Math.random()), 1000)
  })
}

class Posts {
  constructor(url) {
    this.ready = false
    this.data = "uninitilized"
    this.url = url
  }
  init() {
    this.data = someAsync()

  }
  time100() {
    // it's important to return the promise here
    return this.data.then(d => d * 100)
  }
}

let p = new Posts()
p.init()
processData(p)
// called twice to illustrate point
processData(p)

async function processData(posts) {
  let p = await posts.time100()
  console.log("randomin * 100:", p)
}```

init() saves the promise returned from someAsync(). someAsync() could be anything that returns a promise. It saves the promise in an instance property. Now you can call then() or use async/await to get the value. It will either immediately return the value if the promise has already resolved or it will deal with it when it has resolved. I called processData(p) twice just to illustrate that it doesn't calle the someAsync() twice.

That's just one pattern. There are a lot more — using events, observables, just using then() directly, or even callbacks which are unfashionable, but still can be useful.

Body:
I have an es6 class, with an init() method responsible for fetching data, transforming it, then update the class's property this.data with newly transformed data.
So far so good.
The class itself has another getPostById() method, to just do what it sounds like. Here is the code for the class:

class Posts {
  constructor(url) {
    this.ready = false
    this.data = {}
    this.url = url
  }
  async init() {
      try {
        let res = await fetch( this.url )
        if (res.ok) {
            let data = await res.json()

          // Do bunch of transformation stuff here

          this.data = data
          this.ready = true
            return data
        }
      }
      catch (e) {
         console.log(e)
      }
  }
  getPostById(id){
     return this.data.find( p => p.id === id )
  }
}

Straightforward, except I have an async/await mechanism in the init() method.
Now, this code will work correctly:

let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')

allPosts.init()
        .then( d => console.log(allPosts.getPostById(4)) )
// resulting Object correctly logged in console

but it only gets printed into the console:
How could I use allPosts.getPostById(4) as a return of a function ?

Like:

let myFunc = async () => {
   const postId = 4
   await allPosts.init()  // I need to wait for this to finish before returning

   // This is logging correct value
   console.log( 'logging: ' + JSON.stringify(allPosts.getPostById( postId ), null, 4) )

   // How can I return the RESULT of allPosts.getPostById( postId ) ???
   return allPosts.getPostById( postId )
}

myFunc() returns a Promise but not the final value. I have read several related posts on the subject but they all give example of logging, never returning.

Here is a fiddle that includes two ways of handling init(): using Promise and using async/await. No matter what I try, I can't manage to USE the FINAL VALUE of getPostById(id).

The question of this post is: how can I create a function that will RETURN the VALUE of getPostById(id) ?

EDIT:

A lot of good answers trying to explain what Promises are in regards to the main execution loop.
After a lot of videos and other good reads, here is what I understand now:

my function init() correctly returns. However, within the main event loop: it returns a Promise, then it is my job to catch the result of this Promise from within a kinda parallel loop (not a new real thread). In order to catch the result from the parallel loop there are two ways:

use .then( value => doSomethingWithMy(value) )

use let value = await myAsyncFn(). Now here is the foolish hiccup:

await can only be used within an async function :p

thus itself returning a Promise, usable with await which should be embed in an async function, which will be usable with await etc...

This means we cannot really WAIT for a Promise: instead we should catch parallel loop indefinitely: using .then() or async/await.

Thanks for the help !

Body:
Your question and the comments suggest you could use a little intuition nudge about the way the event loop works. It really is confusing at first, but after a while it becomes second nature.

Rather than thinking about the FINAL VALUE, think about the fact that you have a single thread and you can't stop it — so you want the FUTURE VALUE -- the value on the next or some future event loop. Everything you write that is not asynchronous is going to happen almost immediately — functions return with some value or undefined immediately. There's nothing you can do about. When you need something asynchronously, you need to setup a system that is ready to deal with the async values when they return sometime in the future. This is what events, callbacks, promises (and async/await) all try to help with. If some data is asynchronous, you simply can not use it in the same event loop.

So what do you do?

If you want a pattern where you create an instance, call init() and then some function that further process it, you simply need to setup a system that does the processing when the data arrives. There are a lot of ways to do this. Here's one way that's a variation on your class:

function someAsync() {
  console.log("someAsync called")
  return new Promise(resolve => {
    setTimeout(() => resolve(Math.random()), 1000)
  })
}

class Posts {
  constructor(url) {
    this.ready = false
    this.data = "uninitilized"
    this.url = url
  }
  init() {
    this.data = someAsync()

  }
  time100() {
    // it's important to return the promise here
    return this.data.then(d => d * 100)
  }
}

let p = new Posts()
p.init()
processData(p)
// called twice to illustrate point
processData(p)

async function processData(posts) {
  let p = await posts.time100()
  console.log("randomin * 100:", p)
}

init() saves the promise returned from someAsync(). someAsync() could be anything that returns a promise. It saves the promise in an instance property. Now you can call then() or use async/await to get the value. It will either immediately return the value if the promise has already resolved or it will deal with it when it has resolved. I called processData(p) twice just to illustrate that it doesn't calle the someAsync() twice.

That's just one pattern. There are a lot more — using events, observables, just using then() directly, or even callbacks which are unfashionable, but still can be useful.


问:
How to use select dropdown to filter table td value
I have a table which its td value is corresponding to the value of the select dropdown. So when the dropdown is being selected, i would like the table to filter its table row according to the selected value. eg If One is selected,
the table will conduct filter and only show two table row which its td value is 1. Currently,the code isn't working for some reason.

$(document).ready(function($) {

  $('#select').change(function() {

    var selection = $(this).val();
    var dataset = $('#select').find('tr');

    dataset.show();

    dataset.filter(function(index, item) {
      return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
    }).hide();

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>

<table border="2">

<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>

</table></code>```

答:
just use table instead of select

var dataset = $('table').find('tr');

$(document).ready(function($) {

  $('#select').change(function() {

    var selection = $(this).val();
     var dataset = $('table').find('tr');

    dataset.show();

    dataset.filter(function(index, item) {
      return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
    }).hide();

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>

<table border="2">

<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>

</table></code>```

Body:
I have a table which its td value is corresponding to the value of the select dropdown. So when the dropdown is being selected, i would like the table to filter its table row according to the selected value. eg If One is selected,
the table will conduct filter and only show two table row which its td value is 1. Currently,the code isn't working for some reason.

$(document).ready(function($) {

  $('#select').change(function() {

    var selection = $(this).val();
    var dataset = $('#select').find('tr');

    dataset.show();

    dataset.filter(function(index, item) {
      return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
    }).hide();

  });
});

<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>

1

2

2

3

1

Body:
just use table instead of select

var dataset = $('table').find('tr');

$(document).ready(function($) {

  $('#select').change(function() {

    var selection = $(this).val();
     var dataset = $('table').find('tr');

    dataset.show();

    dataset.filter(function(index, item) {
      return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
    }).hide();

  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>

<table border="2">

<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>

</table>


问:
Restore Database from Codeigniter Backup
I was trying to make an automated database backup using built-in CodeIgniter $this->dbutil->backup().

The script is:

```<code>    $this->load->dbutil();

    $backup = $this->dbutil->backup(array(
        'tables'        => array(),   // Array of tables to backup.
        'ignore'        => array('regencies', 'villages', 'provinces'),                     // List of tables to omit from the backup
        'add_drop'      => TRUE,                        // Whether to add DROP TABLE statements to backup file
        'add_insert'    => TRUE,                        // Whether to add INSERT data to backup file
        'newline'       => "\n"                         // Newline character used in backup file
    ));

    $this->load->helper('file');

    $latest = md5(uniqid());

    write_file(APPPATH . 'backup/'. $latest .'.gz', $backup);
</code>```

The scripts run just fine. But the problem comes when i wan't to restore. It comes like this:

As a result of that i cannot restore it from CLI (mysql -u root -p dbname < db.sql) and from Navicat/Sequel Pro.

The question is, how to restore that it to database again? (Notice that there's no quot after VALUES)

答:
This is a simple SQL syntax issue.  String literals need to be enclosed in single quotes.

```<code>INSERT INTO `foo` (`bar`,`bell`) VALUES ( Hey diddle diddle , cat and fiddle )
</code>```

won't work. We need

```<code>INSERT INTO `foo` (`bar`,`bell`) VALUES ('Hey diddle diddle','cat and fiddle')
                                         ^-----------------^ ^--------------^
</code>```

Take a closer look at the actual SQL statement you are trying to execute.

Your "unloader" is going to need to be smarter, enclosing string and date values in single quotes when they get put into a SQL statement.  (For convenience, numeric literals can be enclosed in single quotes as well, so you don't need to discriminate, just enclose all values in the VALUES list in single quotes.

Also be aware of what will happen when a value includes a single quote. For example:

```<code> ... VALUES ( 'O'Leary' , ...
              ^_^
</code>```

That's also going to be an error.  Single quotes within a value will need to be escaped. One way to do that in MySQL is to precede a single quote with another single quote, like this:

```<code> ... VALUES ( 'O''Leary' , ...
              ^--------^
</code>```

This would be valid, and would evaluate to a string containing a single single quote O'Leary

Also, MySQL will interpret a backslash character in a string literal as an escape character. For example:

```<code> ... VALUES ( 'this probably \not what we want' ,
                             ^^
</code>```

That sequence \n is going to interpreted as a newline character, not as the character n. So, backslash characters are also going to need to be escaped.

et al.

Body:
I was trying to make an automated database backup using built-in CodeIgniter $this->dbutil->backup().

The script is:

    $this->load->dbutil();

    $backup = $this->dbutil->backup(array(
        'tables'        => array(),   // Array of tables to backup.
        'ignore'        => array('regencies', 'villages', 'provinces'),                     // List of tables to omit from the backup
        'add_drop'      => TRUE,                        // Whether to add DROP TABLE statements to backup file
        'add_insert'    => TRUE,                        // Whether to add INSERT data to backup file
        'newline'       => "\n"                         // Newline character used in backup file
    ));

    $this->load->helper('file');

    $latest = md5(uniqid());

    write_file(APPPATH . 'backup/'. $latest .'.gz', $backup);

The scripts run just fine. But the problem comes when i wan't to restore. It comes like this:

As a result of that i cannot restore it from CLI (mysql -u root -p dbname < db.sql) and from Navicat/Sequel Pro.

The question is, how to restore that it to database again? (Notice that there's no quot after VALUES)

Body:
This is a simple SQL syntax issue.  String literals need to be enclosed in single quotes.

INSERT INTO `foo` (`bar`,`bell`) VALUES ( Hey diddle diddle , cat and fiddle )

won't work. We need

INSERT INTO `foo` (`bar`,`bell`) VALUES ('Hey diddle diddle','cat and fiddle')
                                         ^-----------------^ ^--------------^

Take a closer look at the actual SQL statement you are trying to execute.

Your "unloader" is going to need to be smarter, enclosing string and date values in single quotes when they get put into a SQL statement.  (For convenience, numeric literals can be enclosed in single quotes as well, so you don't need to discriminate, just enclose all values in the VALUES list in single quotes.

Also be aware of what will happen when a value includes a single quote. For example:

 ... VALUES ( 'O'Leary' , ...
              ^_^

That's also going to be an error.  Single quotes within a value will need to be escaped. One way to do that in MySQL is to precede a single quote with another single quote, like this:

 ... VALUES ( 'O''Leary' , ...
              ^--------^

This would be valid, and would evaluate to a string containing a single single quote O'Leary

Also, MySQL will interpret a backslash character in a string literal as an escape character. For example:

 ... VALUES ( 'this probably \not what we want' ,
                             ^^

That sequence \n is going to interpreted as a newline character, not as the character n. So, backslash characters are also going to need to be escaped.

et al.


问:
How do I get python to display xbar? A line over the letter x
I've been looking at math notation and different packages but have yet to find anything that lets me print xbar (the average x).

I am hoping to use xbar as a label in matplotlib.

Any suggestions?

Thank you. Cheers

答:
If you are using jupyter you can simply do this for one letter (x):  </p>

```<code>$\bar x$

#or for a string
$\overline {xyzabc}$

#note that one $ will give you an inline output and $$...$$ would start
#a new line after your output
</code>```

Body:
If you are using jupyter you can simply do this for one letter (x):

$\bar x$

#or for a string
$\overline {xyzabc}$

#note that one $ will give you an inline output and $$...$$ would start
#a new line after your output


问:
orientation of div display on html page
Below is code that shows three different reports inside their corresponding divs.

Hookdiv , keymessagediv and WhoToVisit

Now for the first two, it displays two pie charts. For WhoToVisit, it displays a table's data.

HTML

```<code><div id="Hooksdiv" style="float:right">
   <div id="chartContainer" style="height: 50%; width: 100%;"></div><!-- 370px -->
</div>

<p id="demo2"></p>

<div id="keymessagediv" style="float:left">
    <div id="chartContainerkey" style="height: 50%; width: 60%;"></div>
    <div id="keyMessageChartContainerkey" style="height: 50%; width: 60%;"></div>
</div>

<div id="WhoToVisit">
    <table id="strikerate" class="dataTable" width="100%" height = "50%" style = "position: relative ;bottom: 0;left: 0;">
                <tr>
                    <th id="accName">Name</th>
                    <th id="PrimaryaccName">Primary Account</th>
                    <th id="plannedCall">Planned Calls</th>
                    <th id="actualCall">Actual Calls</th>
                    <th id="strike">Strike Rate</th>
                    <th id="coverage">Coverage</th>

                </tr>
    </table>
</div>
</code>```

Can some please help me place the divs as required in the image below. I am unable to position it as expected.
Please find attached image to positions of the divs

答:
Your first two div should have the equal width so that it can easily fit in a single row. I have given the height of 200px, you can modify it as per your requirements. You can also use bootstrap to achieve this.</p>

```<code><div id="Hooksdiv" style="float:right;border: 2px solid black; width: 50%; height: 200px;">
   <div id="chartContainer" style="height: 50%; width: 100%;"></div><!-- 370px -->
   Hooksdiv
</div>

<p id="demo2"></p>

<div id="keymessagediv" style="float:left; border: 2px solid green; width: 49%; height: 200px;">
    <div id="chartContainerkey" style="height: 50%; width: 60%;"></div>
    <div id="keyMessageChartContainerkey" style="height: 50%; width: 60%;">keymessagediv</div>
</div>

<div id="WhoToVisit" style="border: 2px solid red;">
    <table id="strikerate" class="dataTable" width="100%" height = "50%" style = "position: relative ;bottom: 0;left: 0;">
                <tr>
                    <th id="accName">Name</th>
                    <th id="PrimaryaccName">Primary Account</th>
                    <th id="plannedCall">Planned Calls</th>
                    <th id="actualCall">Actual Calls</th>
                    <th id="strike">Strike Rate</th>
                    <th id="coverage">Coverage</th>

                </tr>
    </table>
</div>
</code>```

Title: orientation of div display on html page

Body:
Below is code that shows three different reports inside their corresponding divs.

Hookdiv , keymessagediv and WhoToVisit

Now for the first two, it displays two pie charts. For WhoToVisit, it displays a table's data.

HTML

                    Name
                    Primary Account
                    Planned Calls
                    Actual Calls
                    Strike Rate
                    Coverage

Can some please help me place the divs as required in the image below. I am unable to position it as expected.
Please find attached image to positions of the divs

Body:
Your first two div should have the equal width so that it can easily fit in a single row. I have given the height of 200px, you can modify it as per your requirements. You can also use bootstrap to achieve this.

<div id="Hooksdiv" style="float:right;border: 2px solid black; width: 50%; height: 200px;">
   <div id="chartContainer" style="height: 50%; width: 100%;"></div><!-- 370px -->
   Hooksdiv
</div>

<p id="demo2"></p>

<div id="keymessagediv" style="float:left; border: 2px solid green; width: 49%; height: 200px;">
    <div id="chartContainerkey" style="height: 50%; width: 60%;"></div>
    <div id="keyMessageChartContainerkey" style="height: 50%; width: 60%;">keymessagediv</div>
</div>

<div id="WhoToVisit" style="border: 2px solid red;">
    <table id="strikerate" class="dataTable" width="100%" height = "50%" style = "position: relative ;bottom: 0;left: 0;">
                <tr>
                    <th id="accName">Name</th>
                    <th id="PrimaryaccName">Primary Account</th>
                    <th id="plannedCall">Planned Calls</th>
                    <th id="actualCall">Actual Calls</th>
                    <th id="strike">Strike Rate</th>
                    <th id="coverage">Coverage</th>

                </tr>
    </table>
</div>


问:
Why is that my $wpdb->delete value is FALSE, And won't execute properly?
I'm going to delete a row in a table using the $wpdb object

here's my code:

```<code>function delete_variation($variation_ID){
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = 'wp-posts';
    $wpdb->delete( $table_name , $where);
}
</code>```

every arguments are fine, I've got results.. But the

```<code>$wpdb->delete( $table_name , $where);
</code>```

returned FALSE and won't execute?

no errors has been found, everything seems okay, just that it returned FALSE.

Thanks!

答: Generally WP uses underscores for table names; so if you're planning on deleting from the main WP posts table, try using $wpdb->posts instead for your table name.

Body:
I'm going to delete a row in a table using the $wpdb object

here's my code:

function delete_variation($variation_ID){
    $where = array(
            'ID' => $variation_ID,
            'post_type' => 'product_variation'
        );
    $table_name = 'wp-posts';
    $wpdb->delete( $table_name , $where);
}

every arguments are fine, I've got results.. But the

$wpdb->delete( $table_name , $where);

returned FALSE and won't execute?

no errors has been found, everything seems okay, just that it returned FALSE.

Thanks!


问:
Ionic - Error: Uncaught (in promise): removeView was not found
My Ionic app was working fine and I haven't done anything to it but suddenly I am getting this error and I don't know why.

"Error: Uncaught (in promise): removeView was not found

答:
Here is one for the alertController but works very similar.</p>

```<code>logout() {
  let prompt = this.alertCtrl.create({
    title: 'Logout',
    subTitle: 'Are You Sure You Want To Logout?',
    buttons: [
      {
        text: 'No',
        handler: data => {
          let navTransition = prompt.dismiss();
           navTransition.then(() => {
             this.navCtrl.pop();
           });
         return false;
       }

     },
     {
       text: 'Yes',
       handler: data => {
         this.lgout();
       }
     }
   ]
  });
 prompt.present();
}
</code>```

Body:
Here is one for the alertController but works very similar.

logout() {
  let prompt = this.alertCtrl.create({
    title: 'Logout',
    subTitle: 'Are You Sure You Want To Logout?',
    buttons: [
      {
        text: 'No',
        handler: data => {
          let navTransition = prompt.dismiss();
           navTransition.then(() => {
             this.navCtrl.pop();
           });
         return false;
       }

     },
     {
       text: 'Yes',
       handler: data => {
         this.lgout();
       }
     }
   ]
  });
 prompt.present();
}


问:
Onelogin SAMLResponse api request
I'm creating automated integration tests for SSO process.
I'm new with SAML concept and probably my understanding of how it works inaccurate or wrong at all.

We chose to use OneLogin as IdP. Steps to automate:

User request target resource without credentials. For example my-api.com/v1/cats

Verify user has been redirected to https://{app}.onelogin.com/trust/saml2/http-post/sso/{app-id}?SAMLRequest={request}

User login to SSO

Verify user has been redirected to POST my-api.com/v1/saml/consume with SAMLResponse inside body

Verify POST my-api.com/v1/saml/consume with right SAMLResponse give user service provider token and then redirect to initial url - my-api.com/v1/cats

And I'm stuck on step 2: "user login to SSO". I want to do it using onelogin API, not webform. But I didn't find documentation for it. I inspected network calls while I perform login using https://{my-app}.onelogin.com/login page.

After I fill email and password and click "Login" button
1. POST request to https://{my-app}.onelogin.com/sessions with form-data authenticity_token={token}&email={email}&password={password}&commit=Log%20in&_=
2. Onelogin redirect user to make GET request to https://{app}.onelogin.com/trust/saml2/http-post/sso/{app-id}?SAMLRequest={request}(this is initial url generated by our service provider)
3. User redirected to my-api.com/v1/saml/consume

I tried to do POST to https://{my-app}.onelogin.com/sessions with same body as in step 1 using postman but I retrieve

422: UNPROCESSABLE CHANGES. Maybe you tried to change something you don't have access to.

My question: is it possible to retrieve SAMLResponse using Onelogin API? And is process I described right?

答:
SAML request from OneLogin or any other IDp is a form post with SAMLRequest in the body of the request. The user is going to bounce (redirect) from their site to yours. Once at your site you validate the SAMLrequest and you will use the nameid  to authenticate the user and you are done.

So you won't retrieve the response using OneLogin API, it is always a form POST from the IDp.

I hope this helps.

Title: Onelogin SAMLResponse api request


问:
BeagleBoard x15 shows only the last counter number? Qt
I use BeagleBoard x15 to show a counter. When I click a button, it will run a loop:

```<code>for(int i=0;i<10;i++){
    ui->label->setText(QString::number(i));
    delay(1s);
}
</code>```

But it only showed the last number: '9' on label. It should show: 1, 2, 3, 4, 5,...9 after each 1s. I use Qt.

Can you tell me what happen? Thank you.

答:
The problem is caused because the application of Qt lives in a loop that your delay blocks, the correct thing is to use a QTimer:

```<code>ui->label->setText("0");
QTimer *timer(this);
connect(timer, &QTimer::timeout, [timer, this](){
    int i = ui->label->text().toInt();
    ui->label->setText(QString::number(i+1));
    if(i == 9)
        timer->stop();
});

timer->start(1000);
</code>```

Body:
I use BeagleBoard x15 to show a counter. When I click a button, it will run a loop:

for(int i=0;i<10;i++){
    ui->label->setText(QString::number(i));
    delay(1s);
}

But it only showed the last number: '9' on label. It should show: 1, 2, 3, 4, 5,...9 after each 1s. I use Qt.

Can you tell me what happen? Thank you.

Body:
The problem is caused because the application of Qt lives in a loop that your delay blocks, the correct thing is to use a QTimer:

ui->label->setText("0");
QTimer *timer(this);
connect(timer, &QTimer::timeout, [timer, this](){
    int i = ui->label->text().toInt();
    ui->label->setText(QString::number(i+1));
    if(i == 9)
        timer->stop();
});

timer->start(1000);


问:
Python- writing a loop that creates appends data to a dictionary of dictionaries with date being the key value?
I'm trying to create a dictionary of dictionaries where the key for each dictionary is datetime.now() and the value for each key is a dictionary. This dictionary is pulled from an API and I'm running the loop on a constant basis. It looks something like this:

```<code>orders_dict = {}
sleep_time = 1
crypto = 'BTC' #ETH, LTC

x = 0
while x < 5:
try:
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

    order_book = public_client.get_product_order_book('{}-USD'.format(crypto), level=2)

    # Append to dictionaries
    orders_dict[now] = orders_dict

    x += 1
    time.sleep(sleep_time)

except:

    continue
</code>```

In theory this should work, but for some reason when I run this code the values for each key is messed up:

```<code>{'2017-12-06 02:44:57': {...},
 '2017-12-06 02:44:58': {...},
 '2017-12-06 02:45:00': {...},
 '2017-12-06 02:45:02': {...},
 '2017-12-06 02:45:03': {...}}
</code>```

And when I try extracting by key it still doesn't work. Appreciate insight in what's going on and if there's a better way to approach this issue.

答:
You may want to use defaultdict from collections module that ease of  complexity associated with nested dicts.

Once we define a defaultdict of dictionary, you can simply create a new key pair with key being now and value being record from api. (as below).

```<code>>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d
defaultdict(<type 'dict'>, {})
>>> now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
>>> d[now]= { 'book1' : 'author1', 'book2' : 'author2'}
>>> d
defaultdict(<type 'dict'>, {'2017-12-06 04:11:02': {'book1': 'author1', 'book2': 'author2'}})
>>>
</code>```

Body:
I'm trying to create a dictionary of dictionaries where the key for each dictionary is datetime.now() and the value for each key is a dictionary. This dictionary is pulled from an API and I'm running the loop on a constant basis. It looks something like this:

orders_dict = {}
sleep_time = 1
crypto = 'BTC' #ETH, LTC

x = 0
while x < 5:
try:
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

    order_book = public_client.get_product_order_book('{}-USD'.format(crypto), level=2)

    # Append to dictionaries
    orders_dict[now] = orders_dict

    x += 1
    time.sleep(sleep_time)

except:

    continue

In theory this should work, but for some reason when I run this code the values for each key is messed up:

{'2017-12-06 02:44:57': {...},
 '2017-12-06 02:44:58': {...},
 '2017-12-06 02:45:00': {...},
 '2017-12-06 02:45:02': {...},
 '2017-12-06 02:45:03': {...}}

And when I try extracting by key it still doesn't work. Appreciate insight in what's going on and if there's a better way to approach this issue.

Body:
You may want to use defaultdict from collections module that ease of  complexity associated with nested dicts.

Once we define a defaultdict of dictionary, you can simply create a new key pair with key being now and value being record from api. (as below).

>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d
defaultdict(<type 'dict'>, {})
>>> now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
>>> d[now]= { 'book1' : 'author1', 'book2' : 'author2'}
>>> d
defaultdict(<type 'dict'>, {'2017-12-06 04:11:02': {'book1': 'author1', 'book2': 'author2'}})
>>>


问:
Auto resize of N images to fit container
I have the following design:

```<code><View style={{flexDirection: "column", justifyContent: "space-around", alignItems: "center", flex: 1}}>
  <TopElement style={{position: "absolute", top:5}}/>
  <Image key={1}/>
  <Image key={2}/>
  ...
  <Image key={n}/>
  <BottomElement style={{position: "absolute", bottom:5}}/>
</View>
</code>```

My n Images are too big to fit the wrapper container (e.g. my screen). Would it be possible to resize them (keeping aspect ratio) without touching TopElement and BottomElement current dimensions? I would like those to stick at the borders of the container.

I am not sure if there is a builtin function, if using Layout FlexBox props is the solution or maybe computing manually each Image's dimension depending on the screen height, or maybe adding another View to wrap them all...?

答:
You can do it as below:

<View style={{flexDirection: "column", justifyContent: "space-around",
      alignItems: "center", flex: 1, paddingTop: 30, paddingBottom: 30}}>
  <TopElement style={{position: "absolute", top:5}}/>
  <Image resizeMode="contain" style={{flex: 1}} key={1}/>
  ...
  <Image resizeMode="contain" style={{flex: 1}} key={n}/>
  <BottomElement style={{position: "absolute", bottom:5}}/>
</View>
```

Use paddingTop & paddingBottom on parent <View />, with height of <TopElement /> and <BottomElement />. Makes Top / Bottom won't overlap with image.

Set <Image /> prop resizeMode to 'contain'. Make image auto resize with keeping original aspect ratio.

Body:
I have the following design:

<View style={{flexDirection: "column", justifyContent: "space-around", alignItems: "center", flex: 1}}>
  <TopElement style={{position: "absolute", top:5}}/>
  <Image key={1}/>
  <Image key={2}/>
  ...
  <Image key={n}/>
  <BottomElement style={{position: "absolute", bottom:5}}/>
</View>

My n Images are too big to fit the wrapper container (e.g. my screen). Would it be possible to resize them (keeping aspect ratio) without touching TopElement and BottomElement current dimensions? I would like those to stick at the borders of the container.

I am not sure if there is a builtin function, if using Layout FlexBox props is the solution or maybe computing manually each Image's dimension depending on the screen height, or maybe adding another View to wrap them all...?

Body:
You can do it as below:

<View style={{flexDirection: "column", justifyContent: "space-around",
      alignItems: "center", flex: 1, paddingTop: 30, paddingBottom: 30}}>
  <TopElement style={{position: "absolute", top:5}}/>
  <Image resizeMode="contain" style={{flex: 1}} key={1}/>
  ...
  <Image resizeMode="contain" style={{flex: 1}} key={n}/>
  <BottomElement style={{position: "absolute", bottom:5}}/>
</View>

Use paddingTop & paddingBottom on parent <View />, with height of <TopElement /> and <BottomElement />. Makes Top / Bottom won't overlap with image.

Set <Image /> prop resizeMode to 'contain'. Make image auto resize with keeping original aspect ratio.


问:
Dagger2 annotation processor is not working
I try to use Dagger2 in my Android project;
When I use apt, every things is right.But apt is not supported in AndroidStudio 3.0, so I use annotation processor.But no Dagger2 code created after I click "Make Project";
And I'm sure the annotetion processing is enable in AndroidStudio,because the Butterknife annotation processor is all right.
the follow is the build.gradle:</p>

```<code>dependencies {
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.13'
    compile 'com.google.dagger:dagger-android:2.13'
    compile 'com.google.dagger:dagger-android-support:2.13'
    compile 'com.jakewharton:butterknife:8.6.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}
</code>```

答:
It is one of the breaking changes coming with gradle:3.0 that Google announced at IO17 gradle:3.0

the compile configuration is now deprecated and should be replaced by implementation or api
From the gradle docs :

Dependencies appearing in the api configurations will be transitively exposed  to consumers of the library, and as such will appear on the compile classpath  of consumers.

Dependencies found in the implementation configuration will, on the other  hand, not be exposed to consumers, and therefore not leak into the consumers'  compile classpath. This comes with several benefits:

List item dependencies do not leak into the compile classpath of consumers anymore, so you will never accidentally depend on a transitive dependency

faster compilation thanks to reduced classpath size

less recompilations when implementation dependencies change: consumers would not need to be recompiled

cleaner publishing: when used in conjunction with the new maven-publish plugin, Java libraries produce POM files that distinguish exactly between what is required to compile against the library and what is required to use the library at runtime (in other words, don't mix what is needed to compile the library itself and what is needed to compile against the library).

The compile configuration still exists but should not be used as it will not offer the guarantees that the api and implementation configurations provide.

Body:
I try to use Dagger2 in my Android project;
When I use apt, every things is right.But apt is not supported in AndroidStudio 3.0, so I use annotation processor.But no Dagger2 code created after I click "Make Project";
And I'm sure the annotetion processing is enable in AndroidStudio,because the Butterknife annotation processor is all right.
the follow is the build.gradle:

dependencies {
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.13'
    compile 'com.google.dagger:dagger-android:2.13'
    compile 'com.google.dagger:dagger-android-support:2.13'
    compile 'com.jakewharton:butterknife:8.6.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}


问:
laravel project storing data in database does not work
I have a laravel project that is using a mysql database with a few tables.Lets start by showing you all my files that are being used.My problem is that when I try to create the 'Conseillere' into the database, I get error:

```<code>'SQLSTATE[HY000]: General error: 1364 Field 'date_anniversaire' doesn't have a default value (SQL: insert into `conseilleres` () values ())'
</code>```

Plus I dont know if what I did REALLY save it properly in the database. Basically, The conseillere model only has 2 date, but also have nom,prenom,adresse and adresse_courriel. Nom and Prenom are in another table called Personne.Adresse and ville are in another table named Adresse.Adresse_courriel is in another table called Courriel. Conseillere has all these attributes but they are referenced/contained in other tables/models.Conseillere model only contain date_anniversaire and date_entree column.Conseillere is a Personne. I am going to include some files that are needed, but im not sure if it would need more to help solve my issue.

First the usercontroller function that store the Conseillere into the database:

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

    $input = Input::all();
    $unepersonne = Personne::create([]);
    $uncourriel = new Courriel;
    $adresse = new Adresse;
    $conseillere = Conseillere::create([]);

    $uncourriel->adresse_courriel = $input['adresse_courriel'];
    $unepersonne->nom = $input['nom'];
    $unepersonne->prenom = $input['prenom'];

    $adresse->adresse = $input['adresse'];
    $adresse->ville = $input['ville'];

    //the following function are creating drop downs to input a date. for translation purpose, annee=year  mois=months and jour=day
    $conseillere->date_anniversaire = ConseillereController::construire_date($input['annee_anniversaire']-1, $input['mois_anniversaire']-1, $input['jour_anniversaire']-1);
    $conseillere->date_entree = ConseillereController::construire_date($input['annee_entree']-1, $input['mois_entree']-1, $input['jour_entree']-1);

    if ($unepersonne->save()){

    } else {

        return Redirect::back()->withInput()->withErrors($conseillere->validationMessages());
    }

}
</code>```

construire_date function:

```<code>    private function construire_date($annee, $mois, $jour)
{
    if (checkdate($mois, $jour, $annee)) {
        $dateTest = new DateTime;
        $dateTest->setDate($annee, $mois, $jour);
        return $dateTest->format('Y-m-d');
    } else {
        return "invalide";
    }
}
</code>```

}

Conseillere model:

```<code><?php

namespace App\Models;

class Conseillere extends EloquentValidating {
protected $guarded = array('id');

public $timestamps = false;

public function conseillere() {
    return $this->belongsTo('App\Models\Conseillere');
}

protected $fillable = [
        'nom',
        'prenom',
        'adresse',
        'ville',
        'adresse_courriel',
        'date_anniversaire',
        'date_entree'
    ];

/**
 * Validation
 */

public $validationMessages;

public function validationRules() {
    return [
            'date_anniversaire' => 'nullable|date',
            'date_entree' => 'nullable|date'
    ];
}
</code>```

}

Personne model:

```<code><?php

namespace App\Models;

class Personne extends EloquentValidating
{

protected $table = 'personnes';

public $timestamps = false;

protected $fillable = [

    'nom',
    'prenom',
];

public $validationMessages;

public function validationRules() {
    return
    [
            'personne' => 'required',
    ];
}

public function utilisateurs(){

    return $this->belongsToMany('App\Utilisateur');
}

public function adresse() {
    return $this->hasMany('App\Models\Adresse');
}

public function carte_credits(){

    return $this->belongsToMany('App\Carte_credit');
}

public function courriels(){
    return $this->hasMany('App\Models\Courriel');
}
</code>```

}

Migrations of Conseillere:

```<code>    public function up()
{
    Schema::create('conseilleres', function (Blueprint $table) {

        $table->increments('id');
        $table->dateTime('date_anniversaire');
        $table->dateTime('date_entree');

        $table->integer('personne_id')
                        ->unsigned();
        $table->foreign('personne_id')
                        ->references('id')
                        ->on('personnes')
                        ->onDelete('cascade');

    });
}
</code>```

Migrations of Personne:

```<code>    public function up()
{
    Schema::create('personnes', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nom');
        $table->string('prenom');
        $table->timestamps();
    });
}
</code>```

Ive been searching for a while and cant figure why the store function isnt working and not saving into the db.

答:
If understand Your problem clearly or if you are using laravel 5.4 or 5.5... You need to open config/database.php here you need to change the value of strict to false. Something Like this:-

```<code>'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,  // replace true to false here
        'engine' => null,
    ],
</code>```

Hope it helps!

Body:
I have a laravel project that is using a mysql database with a few tables.Lets start by showing you all my files that are being used.My problem is that when I try to create the 'Conseillere' into the database, I get error:

'SQLSTATE[HY000]: General error: 1364 Field 'date_anniversaire' doesn't have a default value (SQL: insert into `conseilleres` () values ())'

Plus I dont know if what I did REALLY save it properly in the database. Basically, The conseillere model only has 2 date, but also have nom,prenom,adresse and adresse_courriel. Nom and Prenom are in another table called Personne.Adresse and ville are in another table named Adresse.Adresse_courriel is in another table called Courriel. Conseillere has all these attributes but they are referenced/contained in other tables/models.Conseillere model only contain date_anniversaire and date_entree column.Conseillere is a Personne. I am going to include some files that are needed, but im not sure if it would need more to help solve my issue.

First the usercontroller function that store the Conseillere into the database:

public function store(){

    $input = Input::all();
    $unepersonne = Personne::create([]);
    $uncourriel = new Courriel;
    $adresse = new Adresse;
    $conseillere = Conseillere::create([]);

    $uncourriel->adresse_courriel = $input['adresse_courriel'];
    $unepersonne->nom = $input['nom'];
    $unepersonne->prenom = $input['prenom'];

    $adresse->adresse = $input['adresse'];
    $adresse->ville = $input['ville'];

    //the following function are creating drop downs to input a date. for translation purpose, annee=year  mois=months and jour=day
    $conseillere->date_anniversaire = ConseillereController::construire_date($input['annee_anniversaire']-1, $input['mois_anniversaire']-1, $input['jour_anniversaire']-1);
    $conseillere->date_entree = ConseillereController::construire_date($input['annee_entree']-1, $input['mois_entree']-1, $input['jour_entree']-1);

    if ($unepersonne->save()){

    } else {

        return Redirect::back()->withInput()->withErrors($conseillere->validationMessages());
    }

}

construire_date function:

    private function construire_date($annee, $mois, $jour)
{
    if (checkdate($mois, $jour, $annee)) {
        $dateTest = new DateTime;
        $dateTest->setDate($annee, $mois, $jour);
        return $dateTest->format('Y-m-d');
    } else {
        return "invalide";
    }
}

}

Conseillere model:

<?php

namespace App\Models;

class Conseillere extends EloquentValidating {
protected $guarded = array('id');

public $timestamps = false;

public function conseillere() {
    return $this->belongsTo('App\Models\Conseillere');
}

protected $fillable = [
        'nom',
        'prenom',
        'adresse',
        'ville',
        'adresse_courriel',
        'date_anniversaire',
        'date_entree'
    ];

/**
 * Validation
 */

public $validationMessages;

public function validationRules() {
    return [
            'date_anniversaire' => 'nullable|date',
            'date_entree' => 'nullable|date'
    ];
}

}

Personne model:

<?php

namespace App\Models;

class Personne extends EloquentValidating
{

protected $table = 'personnes';

public $timestamps = false;

protected $fillable = [

    'nom',
    'prenom',
];

public $validationMessages;

public function validationRules() {
    return
    [
            'personne' => 'required',
    ];
}

public function utilisateurs(){

    return $this->belongsToMany('App\Utilisateur');
}

public function adresse() {
    return $this->hasMany('App\Models\Adresse');
}

public function carte_credits(){

    return $this->belongsToMany('App\Carte_credit');
}

public function courriels(){
    return $this->hasMany('App\Models\Courriel');
}

}

Migrations of Conseillere:

    public function up()
{
    Schema::create('conseilleres', function (Blueprint $table) {

        $table->increments('id');
        $table->dateTime('date_anniversaire');
        $table->dateTime('date_entree');

        $table->integer('personne_id')
                        ->unsigned();
        $table->foreign('personne_id')
                        ->references('id')
                        ->on('personnes')
                        ->onDelete('cascade');

    });
}

Migrations of Personne:

    public function up()
{
    Schema::create('personnes', function (Blueprint $table) {
        $table->increments('id');
        $table->string('nom');
        $table->string('prenom');
        $table->timestamps();
    });
}

Ive been searching for a while and cant figure why the store function isnt working and not saving into the db.

Body:
If understand Your problem clearly or if you are using laravel 5.4 or 5.5... You need to open config/database.php here you need to change the value of strict to false. Something Like this:-

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,  // replace true to false here
        'engine' => null,
    ],

Hope it helps!


问:
material-ui.dropzone: You may need an appropriate loader to handle this file type
Integrating material-ui-dropzone in my React app, I got this error:

./~/material-ui-dropzone/src/index.jsx Module parse failed:
  ...\client\node_modules\material-ui-dropzone\src\index.jsx Unexpected
  token (123:26) You may need an appropriate loader to handle this file
  type. SyntaxError: Unexpected token (123:26)

Here is my webpack configuration:

```<code>const Path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const Webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = (options) => {   const ExtractSASS = new ExtractTextPlugin(`/styles/${options.cssFileName}`);

  const webpackConfig = {
    devtool: options.devtool,
    entry: [
      `webpack-dev-server/client?http://localhost:${+ options.port}`,
      'webpack/hot/dev-server',
      Path.join(__dirname, '../src/app/index'),
    ],
    output: {
      path: Path.join(__dirname, '../dist'),
      filename: `/scripts/${options.jsFileName}`,
    },
    resolve: {
      extensions: ['', '.js', '.jsx'],
    },
    module: {
      loaders: [{
        test: /.jsx?$/,
        include: Path.join(__dirname, '../src/app'),
        loader: 'babel',
      }],
    },
    plugins: [
      new Webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(options.isProduction ? 'production' : 'development'),
        },
        "global.GENTLY": false
      }),
      new HtmlWebpackPlugin({
        template: Path.join(__dirname, '../src/index.html'),
      }),
    ],
    node: {
      __dirname: true,
    },

  };

  if (options.isProduction) {
    webpackConfig.entry = [Path.join(__dirname, '../src/app/index')];

    webpackConfig.plugins.push(
      new Webpack.optimize.OccurenceOrderPlugin(),
      new Webpack.optimize.UglifyJsPlugin({
        compressor: {
          warnings: false,
        },
      }),
      ExtractSASS
    );

    webpackConfig.module.loaders.push({
      test: /\.scss$/,
      loader: ExtractSASS.extract(['css', 'sass']),
    });   } else {
    webpackConfig.plugins.push(
      new Webpack.HotModuleReplacementPlugin()
    );

    webpackConfig.module.loaders.push({
      test: /\.scss$/,
      loaders: ['style', 'css', 'sass'],
    });

    webpackConfig.devServer = {
      contentBase: Path.join(__dirname, '../'),
      hot: true,
      port: options.port,
      inline: true,
      progress: true,
      historyApiFallback: true,
      stats: 'errors-only',
    };   }

  return webpackConfig;

};
</code>```

Babel config file is:

```<code>{
  "presets": ["react", "es2015", "stage-1"]
}
</code>```

It is the only library I had problems with. Any idea where might be the problem?

答:
if you are using webapck@3.x
Try to modify your babel loader to

```<code>module: {
  rules: [
    {
      test: /\.jsx?$/,
      include: Path.join(__dirname, '../src/app'),
      use: {
        loader: 'babel-loader',
        options: {
          presets: ["react", "es2015", "stage-1"],
        }
      }
    }
  ]
}
</code>```

You can reference here https://webpack.js.org/loaders/babel-loader/

Noted that in your loader config, write babel-loader instead of just babel. Also make sure if you have npm install the right babel npm packages to the devDependencies, which depends on your webpack version.

If it does not solve your problem, paste your package.json file so i can get to know your webpack version.

Cheers.

Body:
Integrating material-ui-dropzone in my React app, I got this error:

./~/material-ui-dropzone/src/index.jsx Module parse failed:
  ...\client\node_modules\material-ui-dropzone\src\index.jsx Unexpected
  token (123:26) You may need an appropriate loader to handle this file
  type. SyntaxError: Unexpected token (123:26)

Here is my webpack configuration:

const Path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const Webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = (options) => {   const ExtractSASS = new ExtractTextPlugin(`/styles/${options.cssFileName}`);

  const webpackConfig = {
    devtool: options.devtool,
    entry: [
      `webpack-dev-server/client?http://localhost:${+ options.port}`,
      'webpack/hot/dev-server',
      Path.join(__dirname, '../src/app/index'),
    ],
    output: {
      path: Path.join(__dirname, '../dist'),
      filename: `/scripts/${options.jsFileName}`,
    },
    resolve: {
      extensions: ['', '.js', '.jsx'],
    },
    module: {
      loaders: [{
        test: /.jsx?$/,
        include: Path.join(__dirname, '../src/app'),
        loader: 'babel',
      }],
    },
    plugins: [
      new Webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(options.isProduction ? 'production' : 'development'),
        },
        "global.GENTLY": false
      }),
      new HtmlWebpackPlugin({
        template: Path.join(__dirname, '../src/index.html'),
      }),
    ],
    node: {
      __dirname: true,
    },

  };

  if (options.isProduction) {
    webpackConfig.entry = [Path.join(__dirname, '../src/app/index')];

    webpackConfig.plugins.push(
      new Webpack.optimize.OccurenceOrderPlugin(),
      new Webpack.optimize.UglifyJsPlugin({
        compressor: {
          warnings: false,
        },
      }),
      ExtractSASS
    );

    webpackConfig.module.loaders.push({
      test: /\.scss$/,
      loader: ExtractSASS.extract(['css', 'sass']),
    });   } else {
    webpackConfig.plugins.push(
      new Webpack.HotModuleReplacementPlugin()
    );

    webpackConfig.module.loaders.push({
      test: /\.scss$/,
      loaders: ['style', 'css', 'sass'],
    });

    webpackConfig.devServer = {
      contentBase: Path.join(__dirname, '../'),
      hot: true,
      port: options.port,
      inline: true,
      progress: true,
      historyApiFallback: true,
      stats: 'errors-only',
    };   }

  return webpackConfig;

};

Babel config file is:

{
  "presets": ["react", "es2015", "stage-1"]
}

It is the only library I had problems with. Any idea where might be the problem?

Body:
if you are using webapck@3.x
Try to modify your babel loader to

module: {
  rules: [
    {
      test: /\.jsx?$/,
      include: Path.join(__dirname, '../src/app'),
      use: {
        loader: 'babel-loader',
        options: {
          presets: ["react", "es2015", "stage-1"],
        }
      }
    }
  ]
}

You can reference here https://webpack.js.org/loaders/babel-loader/

Noted that in your loader config, write babel-loader instead of just babel. Also make sure if you have npm install the right babel npm packages to the devDependencies, which depends on your webpack version.

If it does not solve your problem, paste your package.json file so i can get to know your webpack version.

Cheers.


问:
Yii2 Mask Sender Email
I used yii2 application by sending email. Everything is fine. All I want to achieve is to mask the email of sender.

For example the sender email was xxx@sample.com with name of xsample. The receiver can only see the sender as xsample  instead of real email.

I tried to change it from:

```<code>->setFrom(['unknown@sample.com' => 'xsample'])
</code>```

Here is my mailer configuration:

```<code>'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'useFileTransport' => false,
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' =>  'mail.sample.com',
            'username' =>  'xxxsample@sample.com',
            'password' =>  'xxx',
            'port' =>  '587',
            'encryption' => 'tls',
        ],
        'viewPath' => '@common/mail',
    ],
</code>```

But it still read the real email from the config of mailer. Thank you for any help.

答:
Try add messageConfig in mailer component</p>

```<code> 'messageConfig'    => [
                'charset' => 'UTF-8',
                'from'    => ['xxx@sample.com' => 'xsample'],
            ],
</code>```

Title: Yii2 Mask Sender Email

Body:
I used yii2 application by sending email. Everything is fine. All I want to achieve is to mask the email of sender.

For example the sender email was xxx@sample.com with name of xsample. The receiver can only see the sender as xsample  instead of real email.

I tried to change it from:

->setFrom(['unknown@sample.com' => 'xsample'])

Here is my mailer configuration:

'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'useFileTransport' => false,
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' =>  'mail.sample.com',
            'username' =>  'xxxsample@sample.com',
            'password' =>  'xxx',
            'port' =>  '587',
            'encryption' => 'tls',
        ],
        'viewPath' => '@common/mail',
    ],

But it still read the real email from the config of mailer. Thank you for any help.

Body:
Try add messageConfig in mailer component

 'messageConfig'    => [
                'charset' => 'UTF-8',
                'from'    => ['xxx@sample.com' => 'xsample'],
            ],


答:
selectfilter($('table'),$('#select').val());

$('#select').change(function() {
    var selection = $(this).val();
    $('table').find('tr').show();
    selectfilter($('table'),selection);
  });

function selectfilter(table ,selection)
{
  table.find('tr').filter(function(index, item) {
      return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
    }).hide();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>

<table border="2">

<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>

</table></code>```

Title: How to use select dropdown to filter table td value

Body:
I have a table which its td value is corresponding to the value of the select dropdown. So when the dropdown is being selected, i would like the table to filter its table row according to the selected value. eg If One is selected,
the table will conduct filter and only show two table row which its td value is 1. Currently,the code isn't working for some reason.

$(document).ready(function($) {

  $('#select').change(function() {

    var selection = $(this).val();
    var dataset = $('#select').find('tr');

    dataset.show();

    dataset.filter(function(index, item) {
      return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
    }).hide();

  });
});

<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>

1

2

2

3

1

Body:
selectfilter($('table'),$('#select').val());

$('#select').change(function() {
    var selection = $(this).val();
    $('table').find('tr').show();
    selectfilter($('table'),selection);
  });

function selectfilter(table ,selection)
{
  table.find('tr').filter(function(index, item) {
      return $(item).find('td:first-child').text().split(',').indexOf(selection) === -1;
    }).hide();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='select'>
<option value="1"> One </option>
<option value="2"> Two </option>
<option value="3"> Three </option>
<option value="4"> Four </option>
</select>

<table border="2">

<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>1</td></tr>

</table>


问:
Materialize CDN for a few components
Is there a way to have a Materialize CSS CDN link that requests a css file containing styling for only the components that I need?

Thanks!

答:
There is no way to use the cdn links for only specific parts as they link to the full files.

If you're trying to cut down on load time i'd copy just the part you need to your own file and reference it locally.

Good luck!

Title: Materialize CDN for a few components


问:
Not able to parse variable other than string using Moya in swift
I am working on an iOS project in Swift. I used Moya framework for API handling and parsing. It works perfectly. But when I try to parse varibles other than string it shows me en error:

"Missing argument for parameter 'transformation' in call"

Here is my mapper class

```<code>import Mapper

class MyMapperClaa:Mappable {
    var dateVariable: NSDate?

    required init(map: Mapper) throws{
        try dateVariable = map.from("date")
    }
}
</code>```

答:
sorry, you are using this lib: https://github.com/lyft/mapper. from example there:</p>

```<code>private func extractDate(object: Any?) throws -> Date {
  guard let rawDate = object as? String else {
    throw MapperError.convertibleError(value: object, type: Date.self)
  }
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "your date format"

    if let date = dateFormatter.date(from: rawDate)  {
        return date
    } else {
      throw MapperError.convertibleError(value: object, type: Date.self)
    }

}

struct DateModel: Mappable {
  let date: Date

  init(map: Mapper) throws {
    try date = map.from("date", transformation: extractDate)
  }
}
</code>```

Body:
I am working on an iOS project in Swift. I used Moya framework for API handling and parsing. It works perfectly. But when I try to parse varibles other than string it shows me en error:

"Missing argument for parameter 'transformation' in call"

Here is my mapper class

import Mapper

class MyMapperClaa:Mappable {
    var dateVariable: NSDate?

    required init(map: Mapper) throws{
        try dateVariable = map.from("date")
    }
}

Body:
sorry, you are using this lib: https://github.com/lyft/mapper. from example there:

private func extractDate(object: Any?) throws -> Date {
  guard let rawDate = object as? String else {
    throw MapperError.convertibleError(value: object, type: Date.self)
  }
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "your date format"

    if let date = dateFormatter.date(from: rawDate)  {
        return date
    } else {
      throw MapperError.convertibleError(value: object, type: Date.self)
    }

}

struct DateModel: Mappable {
  let date: Date

  init(map: Mapper) throws {
    try date = map.from("date", transformation: extractDate)
  }
}


问:
Using JdbcTokenStore for JWT
for my REST API I am using JWT's for OAuth2 authorization. Currently I am extending JwtTokenStore to store the refresh tokens in memory so that I am able to revoke them.

```<code>// TODO: This is a temporary in memory solution that needs to be replaced with a concrete persistent implementation.
public class MyJwtTokenStore extends JwtTokenStore {

    private List<OAuth2RefreshToken> refreshTokens;

    public MyJwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer) {
        super(jwtTokenEnhancer);
        refreshTokens = new ArrayList<>();
    }

    @Override
    public OAuth2RefreshToken readRefreshToken(String tokenValue) {
        OAuth2RefreshToken refreshToken = super.readRefreshToken(tokenValue);
        if (!refreshTokens.contains(refreshToken)) {
            throw new InvalidGrantException("Invalid refresh token: " + tokenValue);
        }
        return refreshToken;
    }

    @Override
    public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
        refreshTokens.add(refreshToken);
    }

    @Override
    public void removeRefreshToken(OAuth2RefreshToken token) {
        refreshTokens.remove(token);
    }
}
</code>```

I would like start storing these refresh tokens in a database rather than in memory. Spring provides us with JdbcTokenStore, but if I extend that class then I am unable to set a JwtAccessTokenConverter in the constructor. I know that I could just implement my own method of saving/retrieving the JWTs but I would like to take advantage of the out of the box support for the schema at https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql which the JdbcTokenStore provides.

```<code>create table oauth_refresh_token (
  token_id VARCHAR(256),
  token LONGVARBINARY,
  authentication LONGVARBINARY
);
</code>```

Does Spring support storing JWT in a data source? I need something like a "JwtJdbcTokenStore". What is a good way to go about doing this but still use the predefined queries and operations from JdbcTokenStore?

答:
No, Spring doesn't supports this. Refer to this thread
https://github.com/spring-projects/spring-security-oauth/issues/687

Persisting JWT tokens is irrelevant since JWT tokens are self contained, everything you need to know is already available in that token.

Having said that, if you have requirement for persisting them, then you will have to write custom logic for the same.

Title: Using JdbcTokenStore for JWT

Body:
for my REST API I am using JWT's for OAuth2 authorization. Currently I am extending JwtTokenStore to store the refresh tokens in memory so that I am able to revoke them.

// TODO: This is a temporary in memory solution that needs to be replaced with a concrete persistent implementation.
public class MyJwtTokenStore extends JwtTokenStore {

    private List<OAuth2RefreshToken> refreshTokens;

    public MyJwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer) {
        super(jwtTokenEnhancer);
        refreshTokens = new ArrayList<>();
    }

    @Override
    public OAuth2RefreshToken readRefreshToken(String tokenValue) {
        OAuth2RefreshToken refreshToken = super.readRefreshToken(tokenValue);
        if (!refreshTokens.contains(refreshToken)) {
            throw new InvalidGrantException("Invalid refresh token: " + tokenValue);
        }
        return refreshToken;
    }

    @Override
    public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
        refreshTokens.add(refreshToken);
    }

    @Override
    public void removeRefreshToken(OAuth2RefreshToken token) {
        refreshTokens.remove(token);
    }
}

I would like start storing these refresh tokens in a database rather than in memory. Spring provides us with JdbcTokenStore, but if I extend that class then I am unable to set a JwtAccessTokenConverter in the constructor. I know that I could just implement my own method of saving/retrieving the JWTs but I would like to take advantage of the out of the box support for the schema at https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql which the JdbcTokenStore provides.

create table oauth_refresh_token (
  token_id VARCHAR(256),
  token LONGVARBINARY,
  authentication LONGVARBINARY
);

Does Spring support storing JWT in a data source? I need something like a "JwtJdbcTokenStore". What is a good way to go about doing this but still use the predefined queries and operations from JdbcTokenStore?


问:
Pass an output of stdout(jmeter) and pass it as variable string to another sampler
This  is my scenario I'm running a java program in bean shell sampler in j meter and getting the required string in STD OUT console. Even i have successfully wrote the required string to a output file. I need to extract the string from the file or console and pass it to other samples(the required string is present along with lot of information in the output so i need to extract string like "Required String:following Character"   Thanks in advance</p>

答:
When ever You need to direct a output Use this following code

```<code>System.setOut(new PrintStream(new BufferedOutputStream(new
FileOutputStream("path/to/file/output.txt")), true));
</code>```

Say I'm Calling a external java file which is included in test plan (as some jar file)

Write This code in Beanshell Sampler

```<code>import userdir.UserClass;

UserClass obj1 =new UserClass(); obj1.method1();

System.setOut(new PrintStream(new BufferedOutputStream(new
FileOutputStream("path/to/file/output.txt")), true));
</code>```

Now whatever ouput is produced by Userclass in STD OUT will be directed to the ouput.txt

Code to Extract the required string in Beanshell Post Processor from the file ouput.txt

```<code>import java.io.FileNotFoundException;
import java.util.Scanner;
import org.apache.jmeter.samplers.SampleResult;

File file = new File("path/to/file/output.txt");
String word = "Req String1";
String word2 = "Req String2";
Scanner scanner = null;
String line;
String s1;
String s2;
try {
   scanner = new Scanner(file); }
  catch(FileNotFoundException e) {     //handle this }

 //now read the file line by line

 while (scanner.hasNextLine()) {
line = scanner.nextLine();

if(line.contains(word)) {
   log.info(line);
   s1=line;
  //now the entire line along with Req String1 will be stored in s1
}

if(line.contains(word2)) {
  log.info(line);
   s2=line;
}
 }

log.info("The value in Encrypt str  ="+s1);
log.info("The value in Signatr str  ="+s2);
String[] s1 = s1.split(":");
String[] s2 =s2.split(":");
//since my value in the line is Req String1:needed data

props.put("s1",s1[1]);
props.put("s2",s2[1]);

log.info("The value in ORIGINAL Req String1  ="+props.get("s1"));
log.info("The value in ORIGINAL Req String2  ="+props.get("s2"));
scanner.close();
</code>```

Hope this is useful to all

Body:
When ever You need to direct a output Use this following code

System.setOut(new PrintStream(new BufferedOutputStream(new
FileOutputStream("path/to/file/output.txt")), true));

Say I'm Calling a external java file which is included in test plan (as some jar file)

Write This code in Beanshell Sampler

import userdir.UserClass;

UserClass obj1 =new UserClass(); obj1.method1();

System.setOut(new PrintStream(new BufferedOutputStream(new
FileOutputStream("path/to/file/output.txt")), true));

Now whatever ouput is produced by Userclass in STD OUT will be directed to the ouput.txt

Code to Extract the required string in Beanshell Post Processor from the file ouput.txt

import java.io.FileNotFoundException;
import java.util.Scanner;
import org.apache.jmeter.samplers.SampleResult;

File file = new File("path/to/file/output.txt");
String word = "Req String1";
String word2 = "Req String2";
Scanner scanner = null;
String line;
String s1;
String s2;
try {
   scanner = new Scanner(file); }
  catch(FileNotFoundException e) {     //handle this }

 //now read the file line by line

 while (scanner.hasNextLine()) {
line = scanner.nextLine();

if(line.contains(word)) {
   log.info(line);
   s1=line;
  //now the entire line along with Req String1 will be stored in s1
}

if(line.contains(word2)) {
  log.info(line);
   s2=line;
}
 }

log.info("The value in Encrypt str  ="+s1);
log.info("The value in Signatr str  ="+s2);
String[] s1 = s1.split(":");
String[] s2 =s2.split(":");
//since my value in the line is Req String1:needed data

props.put("s1",s1[1]);
props.put("s2",s2[1]);

log.info("The value in ORIGINAL Req String1  ="+props.get("s1"));
log.info("The value in ORIGINAL Req String2  ="+props.get("s2"));
scanner.close();

Hope this is useful to all