问:
Pass data to client-side JavaScript (preferably without view engine or cookies)
Part I: Problem introduction

The short story: I need to pass data from the server to the client, but this data will not need to be displayed on the client end. Instead, the data is used by the client socket to join the correct room. Move on to Part II: Solution attempt

The long story:

For my first web development project, I am attempting to create a remote presenter (i.e. using a mobile device to control a Google Slides presentation on desktop).

On the frontend, I have been using plain old HTMl, CSS and vanilla JS, while the backend has involved NodeJS, Express framework and Socket.io.

Here's a brief overview of the user flow: when a user is authenticated via Google sign-in on the desktop, the website will open a socket connection which is automatically joined to a room identified by the socket id. After the user has signed in on the desktop end, the user will (for now) see this socket id as a 'secret key' which he can use to login on the mobile end.

Hence, I have a server.js which handles the routing and form action (i.e. the secret key submitted on the mobile end) like so:

```<code>// Store all the currently connected web clients
var webClients = [];

// Index route -- home page for website and mobile site
app.get('/', function (req, res) {
  // Basic user agent check - test for mobiles
  var userAgent = req.headers['user-agent'];
  if (/mobile/i.test(userAgent)) {
      // Send mobile to the mobile login site
      res.sendFile(__dirname + '/pages/mobile.html');
  } else {
      // Send desktop to the main site
      res.sendFile(__dirname + '/pages/index.html');
  }
});

// Dealing with secret key input
app.post('/secretKey', function(req, res) {

    // Store the secret key in a variable first
    var secretKey = req.body.secretKey;

    // Check if the secret key matches with any key in the database (current session)
    var index = webClients.indexOf(secretKey);

    // Send the user to the mobile controls if there is something that matches
    if (index != -1) {
        res.sendFile(__dirname + '/pages/mobileControl.html');
    } else {
        res.redirect('/');
    }
  }

});
</code>```

Unfortunately, I have hit a snag. After the mobile controls page is loaded, another socket instance will be opened on the mobile end. In order to ensure that the mobile is controlling the right presentation, I need to let the socket on the mobile end join the same room as the desktop socket (i.e. the room with the desktop socket's id). Hence, I need to pass the desktop socket Id to the mobile side, so that the mobile socket can connect to the right room.

Part II: Solution attempt

I know that several other users have already asked similar questions on SO. For example:

res.sendfile in Node Express with passing data along

res.sendFile send static file + object

Basic Ajax send/receive with node.js

From these, I can summarise several prominent recommendations:

Using a template system such as Jade, ejs etc

I looked into Jade and ejs, and I am reluctant to use these template systems because I suspect that they might be overkill for what I am trying to achieve here - simply pass a string from the server to client side JavaScript without rendering the string in the view. Additionally, I do not really need the partials offered by these template systems, further reinforcing my belief that these may be overkill.

Storing data in a cookie, and accessing the cookie on client-side JavaScript

Currently, this solution appeals the most to me simply because it seems to be the easy way out. I can simply do something like:

```<code>var options = {
     headers: {
          'set-cookie' : roomId=secretKey
     }
  };
res.sendFile(__dirname + '/pages/mobileControl.html', options);
</code>```

Then, I can access the data in the cookie within mobileControl.js by doing something like document.cookie. However, I have read that there are security issues associated with this method, such as cross-site scripting (XSS) attacks. Hence, I am reluctant to use this method as well.

Send the data to another route, and use an XMLHttpRequest to retrieve the data after rendering the html

Aside from these three methods, I have also looked into implementing user sessions, but I do not think that that is the solution for me since user sessions will likely come in at a later stage to allow for logins to persist.

So, which method do you think I should use in this case? Should I just go along with 2, and tweak the HttpOnly field of the cookie? Any other recommendations? Thanks a lot!

答:
If you don't want to use a full blown template engine (even though I think this would not be over the top for this - that's what template engines are for), how about just doing a single string replace?

Put something like

```<code><script>var SECRET_KEY = '{{{SECRET_KEY}}}';</script>
</code>```

in your HTML file, stream the file instead of sending it and use something like stream-replace to replace the {{{SECRET_KEY}}} string with your secret key.

Untested example:

```<code>var fs = require('fs');
var replace = require('stream-replace');

app.post('/secretKey', function(req, res) {

    // Store the secret key in a variable first
    var secretKey = req.body.secretKey;

    // Check if the secret key matches with any key in the database (current session)
    var index = webClients.indexOf(secretKey);

    // Send the user to the mobile controls if there is something that matches
    if (index != -1) {
        fs.createReadStream(__dirname + '/pages/mobileControl.html')
            .pipe(replace('{{{SECRET_KEY}}}', secretKey))
            .pipe(res);
    } else {
        res.redirect('/');
    }
});
</code>```

Then you'll be able to use the SECRET_KEY variable in your script.

Body:
Part I: Problem introduction

The short story: I need to pass data from the server to the client, but this data will not need to be displayed on the client end. Instead, the data is used by the client socket to join the correct room. Move on to Part II: Solution attempt

The long story:

For my first web development project, I am attempting to create a remote presenter (i.e. using a mobile device to control a Google Slides presentation on desktop).

On the frontend, I have been using plain old HTMl, CSS and vanilla JS, while the backend has involved NodeJS, Express framework and Socket.io.

Here's a brief overview of the user flow: when a user is authenticated via Google sign-in on the desktop, the website will open a socket connection which is automatically joined to a room identified by the socket id. After the user has signed in on the desktop end, the user will (for now) see this socket id as a 'secret key' which he can use to login on the mobile end.

Hence, I have a server.js which handles the routing and form action (i.e. the secret key submitted on the mobile end) like so:

// Store all the currently connected web clients
var webClients = [];

// Index route -- home page for website and mobile site
app.get('/', function (req, res) {
  // Basic user agent check - test for mobiles
  var userAgent = req.headers['user-agent'];
  if (/mobile/i.test(userAgent)) {
      // Send mobile to the mobile login site
      res.sendFile(__dirname + '/pages/mobile.html');
  } else {
      // Send desktop to the main site
      res.sendFile(__dirname + '/pages/index.html');
  }
});

// Dealing with secret key input
app.post('/secretKey', function(req, res) {

    // Store the secret key in a variable first
    var secretKey = req.body.secretKey;

    // Check if the secret key matches with any key in the database (current session)
    var index = webClients.indexOf(secretKey);

    // Send the user to the mobile controls if there is something that matches
    if (index != -1) {
        res.sendFile(__dirname + '/pages/mobileControl.html');
    } else {
        res.redirect('/');
    }
  }

});

Unfortunately, I have hit a snag. After the mobile controls page is loaded, another socket instance will be opened on the mobile end. In order to ensure that the mobile is controlling the right presentation, I need to let the socket on the mobile end join the same room as the desktop socket (i.e. the room with the desktop socket's id). Hence, I need to pass the desktop socket Id to the mobile side, so that the mobile socket can connect to the right room.

Part II: Solution attempt

I know that several other users have already asked similar questions on SO. For example:

res.sendfile in Node Express with passing data along

res.sendFile send static file + object

Basic Ajax send/receive with node.js

From these, I can summarise several prominent recommendations:

Using a template system such as Jade, ejs etc

I looked into Jade and ejs, and I am reluctant to use these template systems because I suspect that they might be overkill for what I am trying to achieve here - simply pass a string from the server to client side JavaScript without rendering the string in the view. Additionally, I do not really need the partials offered by these template systems, further reinforcing my belief that these may be overkill.

Storing data in a cookie, and accessing the cookie on client-side JavaScript

Currently, this solution appeals the most to me simply because it seems to be the easy way out. I can simply do something like:

var options = {
     headers: {
          'set-cookie' : roomId=secretKey
     }
  };
res.sendFile(__dirname + '/pages/mobileControl.html', options);

Then, I can access the data in the cookie within mobileControl.js by doing something like document.cookie. However, I have read that there are security issues associated with this method, such as cross-site scripting (XSS) attacks. Hence, I am reluctant to use this method as well.

Send the data to another route, and use an XMLHttpRequest to retrieve the data after rendering the html

Aside from these three methods, I have also looked into implementing user sessions, but I do not think that that is the solution for me since user sessions will likely come in at a later stage to allow for logins to persist.

So, which method do you think I should use in this case? Should I just go along with 2, and tweak the HttpOnly field of the cookie? Any other recommendations? Thanks a lot!

Body:
If you don't want to use a full blown template engine (even though I think this would not be over the top for this - that's what template engines are for), how about just doing a single string replace?

Put something like

<script>var SECRET_KEY = '{{{SECRET_KEY}}}';</script>

in your HTML file, stream the file instead of sending it and use something like stream-replace to replace the {{{SECRET_KEY}}} string with your secret key.

Untested example:

var fs = require('fs');
var replace = require('stream-replace');

app.post('/secretKey', function(req, res) {

    // Store the secret key in a variable first
    var secretKey = req.body.secretKey;

    // Check if the secret key matches with any key in the database (current session)
    var index = webClients.indexOf(secretKey);

    // Send the user to the mobile controls if there is something that matches
    if (index != -1) {
        fs.createReadStream(__dirname + '/pages/mobileControl.html')
            .pipe(replace('{{{SECRET_KEY}}}', secretKey))
            .pipe(res);
    } else {
        res.redirect('/');
    }
});

Then you'll be able to use the SECRET_KEY variable in your script.


来源: stackexchange

问:
replaceing innerHTML of div with some html code
I have  a  div with id xyz.Now i have avariable which has some html code like follows

```<code>var mycode = "<br>jajaj<b>jjja</b> ";
</code>```

Now i want to replace content of div with this html code by using following

```<code>document.getElementbyid("xyz").innerHTML = mycode
</code>```

This doenot work.I am not getting why.mycode is dynamicallly created in my code.

if i do simple document.getElementById("xyz").innerHTML ="some text"  this works

答: getElementById() is case sensitive.

ContentLicense: CC BY-SA 2.5

Body:
I have  a  div with id xyz.Now i have avariable which has some html code like follows

var mycode = "
jajajjjja ";

Now i want to replace content of div with this html code by using following

document.getElementbyid("xyz").innerHTML = mycode

This doenot work.I am not getting why.mycode is dynamicallly created in my code.

if i do simple document.getElementById("xyz").innerHTML ="some text"  this works

Body: getElementById() is case sensitive.


问:
Laravel show last reply left on post
I'm trying to show the last reply that was left on a post. But only the name and date of it. I tried the following things

What I think this one should do is look at the replies to the post. Sort them by ID and then display the first one's username. But it doesn't work.
$topic->replies->sortBydesc('id')->first()->user->username }}

I also tried this one where I requested all the replies in the entire forum and displayed the last one. It worked but I wasn't the one related to the post.
{{ $allposts->sortBydesc('id')->first()->user->username }}

Does anyone know how I can make this work?
Currently, i'm passing these two into the view (There is nothing wrong with these, they work but I think there should be something added)

```<code>public function show($id)
{

    $topics = Topic::with('theme')->find($id);
    $theme = Theme::with('topics')->find($id);

    return view('themes.theme')->with('topics', $topics)->with('theme', $theme);
}
</code>```

Thanks in advance

答:
If you are trying to get topic's replies you need to eager load. Also if you have relation with user who replied eager load it as well.

Use latest() method for getting latest replies.

For only name and date we have select() .

```<code>public function show($id)
{
    $topics = $topic->with('replies' => function($query) {
        $query->with('user')->select('name', 'created_at')->latest();
    });
    $theme = Theme::with('topics')->find($id);

    return view('themes.theme', compact('topics', 'theme'));
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel show last reply left on post

Body:
I'm trying to show the last reply that was left on a post. But only the name and date of it. I tried the following things

What I think this one should do is look at the replies to the post. Sort them by ID and then display the first one's username. But it doesn't work.
$topic->replies->sortBydesc('id')->first()->user->username }}

I also tried this one where I requested all the replies in the entire forum and displayed the last one. It worked but I wasn't the one related to the post.
{{ $allposts->sortBydesc('id')->first()->user->username }}

Does anyone know how I can make this work?
Currently, i'm passing these two into the view (There is nothing wrong with these, they work but I think there should be something added)

public function show($id)
{

    $topics = Topic::with('theme')->find($id);
    $theme = Theme::with('topics')->find($id);

    return view('themes.theme')->with('topics', $topics)->with('theme', $theme);
}

Thanks in advance

Body:
If you are trying to get topic's replies you need to eager load. Also if you have relation with user who replied eager load it as well.

Use latest() method for getting latest replies.

For only name and date we have select() .

public function show($id)
{
    $topics = $topic->with('replies' => function($query) {
        $query->with('user')->select('name', 'created_at')->latest();
    });
    $theme = Theme::with('topics')->find($id);

    return view('themes.theme', compact('topics', 'theme'));
}


问:
:focus styling on custom radio input
I have a custom radio input style that is implemented more or less like this:

```<code><input type="radio" id="testradio" class="visuallyhidden custom-radio">
<label for="testradio">...</label>

.custom-radio + label:before {
  content: ""
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
]
</code>```

This works great except for one nagging detail: the focus style for keyboard navigation. I can tab-select the group of radio buttons and use the arrow keys to change the selected one, but the default :focus outline doesn't appear because the input tag is hidden.

I tried adding my own focus style as above, but this ends up behaving differently than the default browser styling. By default, Chrome (and other browsers I assume) will draw an outline only when you are keyboard-selecting the radio inputs, not when you click them. However, the CSS :focus style seems to apply when clicking the radio input as well (or in this case, clicking the label), which looks really bad.

Basically my question is this: how do I apply a :focus style to a radio input that fully simulates the default browser behavior, i.e. does not appear from a mouse click focus? Or is there another way I can customize this radio input that will help me preserve the default behavior?

Edit: Here's a JSFiddle demonstrating what I'm talking about. On the first row, you can click a radio button and then navigate with the arrow keys - the outline only appears when you use the keyboard. On the second row, clicking the radio button immediately triggers the focus style.

http://jsfiddle.net/7Ltcks3n/1/

答:
I put together the snippet below based on your original code, not the fiddle example you provided. From what I gather, you are trying to replace the default radio button with your own styled element (label:before).

Since it wasn't specified how the default radios are hidden, I just used opacity: 0 and adjusted the position of the label element to cover it. The same effect can be achieved by moving the radio off the screen: position: absolute; top: -999; left -999; (or something similar).

I tried using display: none and vibility: hidden on the radios, but this is a problem because apparently the focus action isn't triggered when they aren't visible.

I also gave the label:before element some styling just so that it shows up.

To address your issue:

```<code>.custom-radio:focus + label:before {
  outline: 1px solid black;
  outline: 1px auto -webkit-focus-ring-color;
}
</code>```

The outline:0 1px solid black; gives a default outline when the label is clicked. This works fine for FF and IE, but for Chrome, you need to change the color to -webkit-focus-ring-color because it uses a blue color for the radio outline.

.visuallyhidden {
  opacity: 0;
}
.custom-radio + label {
  position: relative;
  left: -25px;
  margin-right: -15px;
}
.custom-radio + label:before {
  content: "X";
  margin: 5px;
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
  outline: 1px auto -webkit-focus-ring-color;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" name="testradio" id="testradio1" class="visuallyhidden custom-radio">
<label for="testradio1">radio 1</label>
<input type="radio" name="testradio" id="testradio2" class="visuallyhidden custom-radio">
<label for="testradio2">radio 2</label>
<input type="radio" name="testradio" id="testradio3" class="visuallyhidden custom-radio">
<label for="testradio3">radio 3</label></code>```

Title: :focus styling on custom radio input

Body:
I have a custom radio input style that is implemented more or less like this:

<input type="radio" id="testradio" class="visuallyhidden custom-radio">
...

.custom-radio + label:before {
  content: ""
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
]

This works great except for one nagging detail: the focus style for keyboard navigation. I can tab-select the group of radio buttons and use the arrow keys to change the selected one, but the default :focus outline doesn't appear because the input tag is hidden.

I tried adding my own focus style as above, but this ends up behaving differently than the default browser styling. By default, Chrome (and other browsers I assume) will draw an outline only when you are keyboard-selecting the radio inputs, not when you click them. However, the CSS :focus style seems to apply when clicking the radio input as well (or in this case, clicking the label), which looks really bad.

Basically my question is this: how do I apply a :focus style to a radio input that fully simulates the default browser behavior, i.e. does not appear from a mouse click focus? Or is there another way I can customize this radio input that will help me preserve the default behavior?

Edit: Here's a JSFiddle demonstrating what I'm talking about. On the first row, you can click a radio button and then navigate with the arrow keys - the outline only appears when you use the keyboard. On the second row, clicking the radio button immediately triggers the focus style.

http://jsfiddle.net/7Ltcks3n/1/

Body:
I put together the snippet below based on your original code, not the fiddle example you provided. From what I gather, you are trying to replace the default radio button with your own styled element (label:before).

Since it wasn't specified how the default radios are hidden, I just used opacity: 0 and adjusted the position of the label element to cover it. The same effect can be achieved by moving the radio off the screen: position: absolute; top: -999; left -999; (or something similar).

I tried using display: none and vibility: hidden on the radios, but this is a problem because apparently the focus action isn't triggered when they aren't visible.

I also gave the label:before element some styling just so that it shows up.

To address your issue:

.custom-radio:focus + label:before {
  outline: 1px solid black;
  outline: 1px auto -webkit-focus-ring-color;
}

The outline:0 1px solid black; gives a default outline when the label is clicked. This works fine for FF and IE, but for Chrome, you need to change the color to -webkit-focus-ring-color because it uses a blue color for the radio outline.

.visuallyhidden {
  opacity: 0;
}
.custom-radio + label {
  position: relative;
  left: -25px;
  margin-right: -15px;
}
.custom-radio + label:before {
  content: "X";
  margin: 5px;
  // Styling goes here
}

.custom-radio:focus + label:before {
  outline: 1px solid black;
  outline: 1px auto -webkit-focus-ring-color;
}

<input type="radio" name="testradio" id="testradio1" class="visuallyhidden custom-radio">
<label for="testradio1">radio 1</label>
<input type="radio" name="testradio" id="testradio2" class="visuallyhidden custom-radio">
<label for="testradio2">radio 2</label>
<input type="radio" name="testradio" id="testradio3" class="visuallyhidden custom-radio">
<label for="testradio3">radio 3</label>


问:
ScrollView cuts off last object on the page
I built a view that is populated dynamically using array mapping.  After doing this, I realized that the View would be too large to contain all the array items on one screen.

Here is my code.

```<code>            <View style={[styles.flexColumn]}>
                {Characters.map((character, i) =>
                  <View key={i} style={[styles.flexRow]}>
                        <View>
                            <Text>
                                {character.Name}
                            </Text>
                       </View>
                  </View>
                )}
            </View>
</code>```

So I tried adding a scroll view as the parent like this:

```<code>    <ScrollView>
                <View style={[styles.flexColumn]}>
                    {Characters.map((character, i) =>
                       <View key={i} style={[styles.flexRow]}>
                            <View>
                                <Text>
                                    {character.Name}
                                </Text>
                            </View>
                       </View>
                   )}
                </View>
    </ScrollView>
</code>```

This does add some scrollability to the view, but it's still cutting off a portion of the last object in the array.

Is there a way to fix this?

Thanks!

答:
ScrollView is intended for showing scrollable content at once. Since you are populating content dynamically, you should be using FlatList. Something similar to the following would work:

...
_keyExtractor = character => character.Name

_renderItem = ({character}) => (
    <Text>
        {character.Name}
    </Text>
)

render() {
  return (
    <FlatList
      data={Characters}
      keyExtractor={this._keyExtractor}
      renderItem={this._renderItem}
    />
  )
}
...```

Detailed explanation is available in the docs.

If you are by any reason still forced to stick to Scrollview, the problem is probably related to the styling. I suppose styles.flexColumn should be applied to the ScrollView itself via contentContainerStyle, rather than to its' child View.

Body:
I built a view that is populated dynamically using array mapping.  After doing this, I realized that the View would be too large to contain all the array items on one screen.

Here is my code.

            <View style={[styles.flexColumn]}>
                {Characters.map((character, i) =>
                  <View key={i} style={[styles.flexRow]}>
                        <View>
                            <Text>
                                {character.Name}
                            </Text>
                       </View>
                  </View>
                )}
            </View>

So I tried adding a scroll view as the parent like this:

    <ScrollView>
                <View style={[styles.flexColumn]}>
                    {Characters.map((character, i) =>
                       <View key={i} style={[styles.flexRow]}>
                            <View>
                                <Text>
                                    {character.Name}
                                </Text>
                            </View>
                       </View>
                   )}
                </View>
    </ScrollView>

This does add some scrollability to the view, but it's still cutting off a portion of the last object in the array.

Is there a way to fix this?

Thanks!

Body:
ScrollView is intended for showing scrollable content at once. Since you are populating content dynamically, you should be using FlatList. Something similar to the following would work:

...
_keyExtractor = character => character.Name

_renderItem = ({character}) => (
    <Text>
        {character.Name}
    </Text>
)

render() {
  return (
    <FlatList
      data={Characters}
      keyExtractor={this._keyExtractor}
      renderItem={this._renderItem}
    />
  )
}
...

Detailed explanation is available in the docs.

If you are by any reason still forced to stick to Scrollview, the problem is probably related to the styling. I suppose styles.flexColumn should be applied to the ScrollView itself via contentContainerStyle, rather than to its' child View.


问:
1st, 2nd, 3rd and 4th partial derivatives of real data obtained from FFTW are incorrect
I calculated the 1st, 2nd and 3rd derivatives of sin(2.0*pi*j/lambda) (j varying from 0 to 255) by using fftw, fourier transforming it, multiplying by the appropriate and taking an inverse fourier transform. Plans used were out of place, with dummy input and output arrays. The real part of the resulting array is half of that of the analytical result though. I took care of aliasing while taking the derivatives by choosing the appropriate value of kx/ky. Just taking fftw and inverse fftw gave back the original array correctly.

The value returned by fftw was half that of the analytical values for all the derivatives.

If I do the same thing in the x direction (i instead of j), the values obtained are right only for the 1st derivative with respect to x, y derivatives are non-zero(the should be zero as variation is only in x) and the laplacian and biharmonic (4th derivative wrt x and y) are wrong.

In both cases, the imaginary parts of the derivatives are non-zero and large.

I tried a different plan using r2c and c2r instead, but that is giving the wrong values too.

Any suggestions will be helpful!

```<code>    void psiderivcalc(double *psi, double *dx, double *dy, double *del2, double *dxdel2, double *dydel2, double *del4)
</code>```

{
    int i, j, ir, ir1, k;

```<code>fftw_complex *fdx, *fdy, *fdxdel2, *fdydel2, *fdel2, *fdel4, *out, *bt, *in;
fftw_plan p, q;

out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
bt = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
fdx = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
fdy = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
fdxdel2 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
fdydel2 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
fdel2 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
fdel4 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);

p = fftw_plan_dft_2d(lx, ly, in, bt, FFTW_FORWARD,FFTW_MEASURE);
q = fftw_plan_dft_2d(lx, ly, bt, out, FFTW_BACKWARD,FFTW_MEASURE);

for(i = 0; i < lx; i++)
{
    for(j = 0; j < ly; j++)
    {
        ir = j*lx + i;
        in[ir] = psi[ir] + 0.0*I;
    }
}

fftw_execute(p);

double kx, ky, pref;
int y1, x1, y2, x2;
kx = 2.0*pi/lx;
ky = 2.0*pi/ly;
for(i=0;i<lx;i++)
{
    for(j = 0; j < ly; j++)
    {
        ir = j*lx + i;
        if(i<lx/2)
        {
            x1 = i;
            x2 = i;
        }
        else if(i==lx/2.0)
        {
            x1 = 0;
            x2 = i;
        }
        else
        {
            x1 = i - lx;
            x2 = x1;
        }
        if(j<ly/2)
        {
            y1 = i;
            y2 = i;
        }
        else if(j==ly/2)
        {
            y1 = 0;
            y2 = j;
        }
        else
        {
            y1 = j - ly;
            y2 = y1;
        }
        pref = -1.0*(pow((kx*x2),2.0) + pow((ky*y2),2.0));
        fdx[ir] = -1.0*kx*x1*I*bt[ir];
        fdy[ir] = -1.0*ky*y1*I*bt[ir];
        fdel2[ir] = pref*bt[ir];
        fdxdel2[ir] = -1.0*kx*I*x1*pref*bt[ir];
        fdydel2[ir] = -1.0*ky*I*y1*pref*bt[ir];
        fdel4[ir] = pref*pref*bt[ir];
    }
}

for(i = 0;i < lx; i++)
{
    for(j = 0;j < ly; j++)
    {
        ir = j*lx + i;
        bt[ir] = fdx[ir];
    }
}

fftw_execute(q);

for(i = 0;i < lx; i++)
{
    for(j = 0;j < ly; j++)
    {
        ir = j*lx + i;
        dx[ir] = creal(out[ir]) / (double)N;
    }
}
</code>```

I found the other derivatives the same way as dx[ir](1st derivative wrt x) by changing bt[ir] each time before executing plan q, and out[ir] after execution. del2 is the laplacian, dxdel2 is derivative of the laplacian wrt x and del4 is the biharmonic.

psi[ir] was correctly initialised to a sine function in j before passing it on to the function.

```<code>    for(i = 0; i < lx; i++)
    {
        for(j = 0; j < ly; j++)
        {
            ir = j*lx + i;
            psi[ir] = sin(2.0*pi*j/lambda);
        }
    }
</code>```

This is an example of the output for del2(fftw), del2a(analytical), dx, dxa and ir(index). lambda = 8, lx = 16 and ly = 16, N = lx*ly, so sin function is periodic in this domain.

```<code>    0.308425    -0.616850   0.000000    0.000000    175
    -0.218090   -0.436179   0.000000    0.000000    191
    -0.000000   -0.000000   0.000000    0.000000    207
    0.218090    0.436179    0.000000    0.000000    223
    0.308425    0.616850    0.000000    0.000000    239
    0.218090    0.436179    0.000000    0.000000    255
</code>```

答:
The trouble is due to the following lines:

```<code>    if(j<ly/2)
    {
        y1 = i; // should be j !!!
        y2 = i; // should be j !!!
    }
</code>```

Also, watch the sign of the derivative:

```<code>    fdx[ir] = -1.0*kx*x1*I*bt[ir]; // should be a + !
    fdy[ir] = -1.0*ky*y1*I*bt[ir]; // should be a + !
</code>```

Body:
I calculated the 1st, 2nd and 3rd derivatives of sin(2.0*pi*j/lambda) (j varying from 0 to 255) by using fftw, fourier transforming it, multiplying by the appropriate and taking an inverse fourier transform. Plans used were out of place, with dummy input and output arrays. The real part of the resulting array is half of that of the analytical result though. I took care of aliasing while taking the derivatives by choosing the appropriate value of kx/ky. Just taking fftw and inverse fftw gave back the original array correctly.

The value returned by fftw was half that of the analytical values for all the derivatives.

If I do the same thing in the x direction (i instead of j), the values obtained are right only for the 1st derivative with respect to x, y derivatives are non-zero(the should be zero as variation is only in x) and the laplacian and biharmonic (4th derivative wrt x and y) are wrong.

In both cases, the imaginary parts of the derivatives are non-zero and large.

I tried a different plan using r2c and c2r instead, but that is giving the wrong values too.

Any suggestions will be helpful!

    void psiderivcalc(double *psi, double *dx, double *dy, double *del2, double *dxdel2, double *dydel2, double *del4)

{
    int i, j, ir, ir1, k;

fftw_complex *fdx, *fdy, *fdxdel2, *fdydel2, *fdel2, *fdel4, *out, *bt, *in;
fftw_plan p, q;

out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
bt = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
fdx = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
fdy = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
fdxdel2 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
fdydel2 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
fdel2 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) *N);
fdel4 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);

p = fftw_plan_dft_2d(lx, ly, in, bt, FFTW_FORWARD,FFTW_MEASURE);
q = fftw_plan_dft_2d(lx, ly, bt, out, FFTW_BACKWARD,FFTW_MEASURE);

for(i = 0; i < lx; i++)
{
    for(j = 0; j < ly; j++)
    {
        ir = j*lx + i;
        in[ir] = psi[ir] + 0.0*I;
    }
}

fftw_execute(p);

double kx, ky, pref;
int y1, x1, y2, x2;
kx = 2.0*pi/lx;
ky = 2.0*pi/ly;
for(i=0;i<lx;i++)
{
    for(j = 0; j < ly; j++)
    {
        ir = j*lx + i;
        if(i<lx/2)
        {
            x1 = i;
            x2 = i;
        }
        else if(i==lx/2.0)
        {
            x1 = 0;
            x2 = i;
        }
        else
        {
            x1 = i - lx;
            x2 = x1;
        }
        if(j<ly/2)
        {
            y1 = i;
            y2 = i;
        }
        else if(j==ly/2)
        {
            y1 = 0;
            y2 = j;
        }
        else
        {
            y1 = j - ly;
            y2 = y1;
        }
        pref = -1.0*(pow((kx*x2),2.0) + pow((ky*y2),2.0));
        fdx[ir] = -1.0*kx*x1*I*bt[ir];
        fdy[ir] = -1.0*ky*y1*I*bt[ir];
        fdel2[ir] = pref*bt[ir];
        fdxdel2[ir] = -1.0*kx*I*x1*pref*bt[ir];
        fdydel2[ir] = -1.0*ky*I*y1*pref*bt[ir];
        fdel4[ir] = pref*pref*bt[ir];
    }
}

for(i = 0;i < lx; i++)
{
    for(j = 0;j < ly; j++)
    {
        ir = j*lx + i;
        bt[ir] = fdx[ir];
    }
}

fftw_execute(q);

for(i = 0;i < lx; i++)
{
    for(j = 0;j < ly; j++)
    {
        ir = j*lx + i;
        dx[ir] = creal(out[ir]) / (double)N;
    }
}

I found the other derivatives the same way as dx[ir](1st derivative wrt x) by changing bt[ir] each time before executing plan q, and out[ir] after execution. del2 is the laplacian, dxdel2 is derivative of the laplacian wrt x and del4 is the biharmonic.

psi[ir] was correctly initialised to a sine function in j before passing it on to the function.

    for(i = 0; i < lx; i++)
    {
        for(j = 0; j < ly; j++)
        {
            ir = j*lx + i;
            psi[ir] = sin(2.0*pi*j/lambda);
        }
    }

This is an example of the output for del2(fftw), del2a(analytical), dx, dxa and ir(index). lambda = 8, lx = 16 and ly = 16, N = lx*ly, so sin function is periodic in this domain.

    0.308425    -0.616850   0.000000    0.000000    175
    -0.218090   -0.436179   0.000000    0.000000    191
    -0.000000   -0.000000   0.000000    0.000000    207
    0.218090    0.436179    0.000000    0.000000    223
    0.308425    0.616850    0.000000    0.000000    239
    0.218090    0.436179    0.000000    0.000000    255

Body:
The trouble is due to the following lines:

    if(j<ly/2)
    {
        y1 = i; // should be j !!!
        y2 = i; // should be j !!!
    }

Also, watch the sign of the derivative:

    fdx[ir] = -1.0*kx*x1*I*bt[ir]; // should be a + !
    fdy[ir] = -1.0*ky*y1*I*bt[ir]; // should be a + !


问:
How can I modify my Labels to make them transparent?
I have a Tkinter GUI that looks like the following:

As you can see, the labels have a background color that doesn't look very neat with the background image. I read here that I could change the labels to text objects to get rid of the background color, but I am unsure how to do that.

Does anyone know a way I can get the text on my GUI have a transparent background? Thanks in advance!

答:
From what I understand of my own research on this topic under a different context, this is not possible. It is possible to change the transparency of an entire window, but not individual widgets. The linked post mentions using a canvas as a background so that the text created has no background. You would also have to place all of your widgets on the canvas using the Canvas.create_window method:

```<code>root = Tk()
canvas = Canvas(width=, height=, bg=, ...)

canvas.create_text(x, y, ...) # for text

entry = Entry(root, ...)
canvas.create_window(window=entry) # to place widgets on canvas
...
</code>```

You would have to modify much of your code to accommodate for the canvas acting as your root, but I believe it can be done.

Documentation for Canvas

Body:
From what I understand of my own research on this topic under a different context, this is not possible. It is possible to change the transparency of an entire window, but not individual widgets. The linked post mentions using a canvas as a background so that the text created has no background. You would also have to place all of your widgets on the canvas using the Canvas.create_window method:

root = Tk()
canvas = Canvas(width=, height=, bg=, ...)

canvas.create_text(x, y, ...) # for text

entry = Entry(root, ...)
canvas.create_window(window=entry) # to place widgets on canvas
...

You would have to modify much of your code to accommodate for the canvas acting as your root, but I believe it can be done.

Documentation for Canvas


问:
Adding a method to a Rails ActiveRecord class
In plain Ruby, this works just fine:

```<code>class TestSuper
  def foo
    puts "In TestSuper.foo"
  end
end

class TestClass < TestSuper
  def foo
    super
    puts "In TestClass.bar"
  end
end

class TestClass
  def bar
    puts "In TestClass.bar, second definition"
    puts "Calling foo:"
    foo
  end
end

t = TestClass.new
t.foo
t.bar
</code>```

I can call foo() and bar() on a TestClass instance and get exactly what I expect:

```<code>In TestSuper.foo
In TestClass.bar
In TestClass.bar, second definition
Calling foo:
In TestSuper.foo
In TestClass.bar
</code>```

However, when I try something very similar in a Rails migration, I get errors:

```<code>#### my_model.rb ####
puts "In my_model.rb"
class MyModel
  has_many :foo
end

#### my_migration.rb ####
puts "In my_migration.rb"
class MyModel
  def bar
    foo.each{ |f| f.baz }
  end
end

class MyMigration < ActiveRecord::Migration
  def self.up
    MyModel.find(1).bar
  end

  def self.down
    # Not applicable
  end
end
</code>```

The first problem is that MyModel.find() disappears unless I explicitly have it extend ActiveRecord in my_migration.rb. Otherwise, it drops the superclass.

If I do that, I then get an error on the foo call in MyModel.bar().

If I comment out the class (re)definition in my_migration.rb, find() and bar() both work just fine.

During the course of my debugging, I added the puts statements to see when each file & class was being executed. It appears that my_model.rb doesn't even get loaded if MyModel is already defined (which I'm doing in my_migration.rb).

So: why does this happen in Rails, and how can I work around it?

答:
You need to reference a constant for your model first, that will load your model class. Then you can alter that class. The following are 3 ways of doing the same thing:</p>

```
MyModel
class MyModel
  def bar
    foo.each{ |f| f.baz }
  end
end
```

```
MyModel.module_eval do
  def bar
    foo.each{ |f| f.baz }
  end
end
```

```
MyModel.send :include, Module.new {
  def bar
    foo.each{ |f| f.baz }
  end
}
```

Body:
In plain Ruby, this works just fine:

class TestSuper
  def foo
    puts "In TestSuper.foo"
  end
end

class TestClass < TestSuper
  def foo
    super
    puts "In TestClass.bar"
  end
end

class TestClass
  def bar
    puts "In TestClass.bar, second definition"
    puts "Calling foo:"
    foo
  end
end

t = TestClass.new
t.foo
t.bar

I can call foo() and bar() on a TestClass instance and get exactly what I expect:

In TestSuper.foo
In TestClass.bar
In TestClass.bar, second definition
Calling foo:
In TestSuper.foo
In TestClass.bar

However, when I try something very similar in a Rails migration, I get errors:

#### my_model.rb ####
puts "In my_model.rb"
class MyModel
  has_many :foo
end

#### my_migration.rb ####
puts "In my_migration.rb"
class MyModel
  def bar
    foo.each{ |f| f.baz }
  end
end

class MyMigration < ActiveRecord::Migration
  def self.up
    MyModel.find(1).bar
  end

  def self.down
    # Not applicable
  end
end

The first problem is that MyModel.find() disappears unless I explicitly have it extend ActiveRecord in my_migration.rb. Otherwise, it drops the superclass.

If I do that, I then get an error on the foo call in MyModel.bar().

If I comment out the class (re)definition in my_migration.rb, find() and bar() both work just fine.

During the course of my debugging, I added the puts statements to see when each file & class was being executed. It appears that my_model.rb doesn't even get loaded if MyModel is already defined (which I'm doing in my_migration.rb).

So: why does this happen in Rails, and how can I work around it?

Body:
You need to reference a constant for your model first, that will load your model class. Then you can alter that class. The following are 3 ways of doing the same thing:

MyModel
class MyModel
  def bar
    foo.each{ |f| f.baz }
  end
end

MyModel.module_eval do
  def bar
    foo.each{ |f| f.baz }
  end
end

MyModel.send :include, Module.new {
  def bar
    foo.each{ |f| f.baz }
  end
}


问:
Android: How to change the Mobile hotspot broadcast channel by programmatically?
I tried to change mobile hotsport broadcast channel in android by programmatically by using following code but it not changing any value/channel.

Note: I able to change the SSID and Password by programmatically.

I tried to set channel 11,
Still it not working...

Thanks in advance

My code is

```<code>public void HotspotChannelWrite() {
    WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);

    if(wifiManager.isWifiEnabled())
    {
        wifiManager.setWifiEnabled(false);
    }
    netConfig = new WifiConfiguration();
    netConfig.SSID = "TipturInfo";
    netConfig.preSharedKey = "Sharath";
    netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    try {

        Method setWifiApMethod = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        boolean apstatus=(Boolean) setWifiApMethod.invoke(wifiManager, netConfig,true);

        Method isWifiApEnabledmethod = wifiManager.getClass().getMethod("isWifiApEnabled");
        while(!(Boolean)isWifiApEnabledmethod.invoke(wifiManager)){};

        Method getWifiApStateMethod = wifiManager.getClass().getMethod("getWifiApState");
        int apstate=(Integer)getWifiApStateMethod.invoke(wifiManager);

        Method getWifiApConfigurationMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
        netConfig=(WifiConfiguration)getWifiApConfigurationMethod.invoke(wifiManager);

        Log.i("Writing HotspotData", "\nSSID:"+netConfig.SSID+"\nPassword:"+netConfig.preSharedKey+"\n");

        // For Channel change
        Field wcAdhocFreq = WifiConfiguration.class.getField("frequency");
        int freq = 2462; // default to channel 11
        wcAdhocFreq.setInt(netConfig, freq);
        Log.i("HotspotData Channel", "\n Frequence:"+freq );
        Log.i("HotspotData Channel", "\n Frequence:"+wcAdhocFreq );

        // For Saving Data
        wifiManager.saveConfiguration();

    } catch (IllegalFormatException ife) {
        ife.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    wifiManager.saveConfiguration();
}
</code>```

I tried alternative way as well:

```<code>Field wcFreq = WifiConfiguration.class.getField("channel");
       wcFreq.setInt(netConfig,11);
</code>```

答:
Try this, works for Android 7.0</p>

```<code>                Method getWifiApConfigurationMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
                netConfig=(WifiConfiguration)getWifiApConfigurationMethod.invoke(wifiManager);

                //Log.i("Writing HotspotData", "\nSSID:" + netConfig.SSID + "\nPassword:" + netConfig.preSharedKey + "\n");

                Field wcBand = WifiConfiguration.class.getField("apBand");
                int vb = wcBand.getInt(netConfig);
                Log.i("Band was", "val=" + vb);
                wcBand.setInt(netConfig, 2); // 2Ghz

                // For Channel change
                Field wcFreq = WifiConfiguration.class.getField("apChannel");
                int val = wcFreq.getInt(netConfig);
                Log.i("Config was", "val=" + val);
                wcFreq.setInt(netConfig,11); // channel 11

                Method setWifiApConfigurationMethod = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
                setWifiApConfigurationMethod.invoke(wifiManager, netConfig);

                // For Saving Data
                wifiManager.saveConfiguration();
</code>```

Body:
I tried to change mobile hotsport broadcast channel in android by programmatically by using following code but it not changing any value/channel.

Note: I able to change the SSID and Password by programmatically.

I tried to set channel 11,
Still it not working...

Thanks in advance

My code is

public void HotspotChannelWrite() {
    WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);

    if(wifiManager.isWifiEnabled())
    {
        wifiManager.setWifiEnabled(false);
    }
    netConfig = new WifiConfiguration();
    netConfig.SSID = "TipturInfo";
    netConfig.preSharedKey = "Sharath";
    netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    try {

        Method setWifiApMethod = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        boolean apstatus=(Boolean) setWifiApMethod.invoke(wifiManager, netConfig,true);

        Method isWifiApEnabledmethod = wifiManager.getClass().getMethod("isWifiApEnabled");
        while(!(Boolean)isWifiApEnabledmethod.invoke(wifiManager)){};

        Method getWifiApStateMethod = wifiManager.getClass().getMethod("getWifiApState");
        int apstate=(Integer)getWifiApStateMethod.invoke(wifiManager);

        Method getWifiApConfigurationMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
        netConfig=(WifiConfiguration)getWifiApConfigurationMethod.invoke(wifiManager);

        Log.i("Writing HotspotData", "\nSSID:"+netConfig.SSID+"\nPassword:"+netConfig.preSharedKey+"\n");

        // For Channel change
        Field wcAdhocFreq = WifiConfiguration.class.getField("frequency");
        int freq = 2462; // default to channel 11
        wcAdhocFreq.setInt(netConfig, freq);
        Log.i("HotspotData Channel", "\n Frequence:"+freq );
        Log.i("HotspotData Channel", "\n Frequence:"+wcAdhocFreq );

        // For Saving Data
        wifiManager.saveConfiguration();

    } catch (IllegalFormatException ife) {
        ife.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    wifiManager.saveConfiguration();
}

I tried alternative way as well:

Field wcFreq = WifiConfiguration.class.getField("channel");
       wcFreq.setInt(netConfig,11);

Body:
Try this, works for Android 7.0

                Method getWifiApConfigurationMethod = wifiManager.getClass().getMethod("getWifiApConfiguration");
                netConfig=(WifiConfiguration)getWifiApConfigurationMethod.invoke(wifiManager);

                //Log.i("Writing HotspotData", "\nSSID:" + netConfig.SSID + "\nPassword:" + netConfig.preSharedKey + "\n");

                Field wcBand = WifiConfiguration.class.getField("apBand");
                int vb = wcBand.getInt(netConfig);
                Log.i("Band was", "val=" + vb);
                wcBand.setInt(netConfig, 2); // 2Ghz

                // For Channel change
                Field wcFreq = WifiConfiguration.class.getField("apChannel");
                int val = wcFreq.getInt(netConfig);
                Log.i("Config was", "val=" + val);
                wcFreq.setInt(netConfig,11); // channel 11

                Method setWifiApConfigurationMethod = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
                setWifiApConfigurationMethod.invoke(wifiManager, netConfig);

                // For Saving Data
                wifiManager.saveConfiguration();


问:
Writing a prepared statement to insert data into table from a form (fatal error)
using prepared statement and mysqli I'm trying to insert the bellow data into a table. When I run the code I get this error even though I'm following a tutorial from w3school.

here is my code:

```<code>$dbServerName = "localhost";
    $dbUserName = "root";
    $dbPassword = "";
    $dbName = "candiadateDB";
    $conn = mysqli_connect($dbServerName,$dbUserName,$dbPassword,$dbName);
    $stmt_values = $conn->prepare("INSERT INTO candidates (username, firstname, lastname, password, coalition,program, starting_year, slogan, email) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                                $stmt_values->bind_param("sssssssss",$username, $firstname, $lastname, $password, $coalition,$program, $starting_year, $slogan, $email);
                                $stmt_values->execute();
                                $stmt_values->close();
                                $conn->close();
</code>```

I'm retrieving the variables $username, $fname,.. like so from a form:

```<code>$fname = mysqli_real_escape_string($conn,$_POST['fname']);
</code>```

here is the error:
Fatal error: Call to a member function bind_param() on a non-object in

答:
bind_param does not accept non-variables as parameters

They must be variables. Store meee as $meee = 'meee' for example

See the manual: http://php.net/manual/en/mysqli-stmt.bind-param.php

Example:

```<code>$value1 = 'mee';
$value2 = 'youu';
.
.
.
$stmt->bind_param("ss",$value1,$value2);
</code>```

See the point of bound parameters is to not allow invalid/unsafe data to be used in a query. You're hard coding string/parameters in so in this case, there's no reason to USE a prepared statement because you could do the same with INSERT INTO X (col1,col2) VALUES ('val1',val2').

Body:
using prepared statement and mysqli I'm trying to insert the bellow data into a table. When I run the code I get this error even though I'm following a tutorial from w3school.

here is my code:

$dbServerName = "localhost";
    $dbUserName = "root";
    $dbPassword = "";
    $dbName = "candiadateDB";
    $conn = mysqli_connect($dbServerName,$dbUserName,$dbPassword,$dbName);
    $stmt_values = $conn->prepare("INSERT INTO candidates (username, firstname, lastname, password, coalition,program, starting_year, slogan, email) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                                $stmt_values->bind_param("sssssssss",$username, $firstname, $lastname, $password, $coalition,$program, $starting_year, $slogan, $email);
                                $stmt_values->execute();
                                $stmt_values->close();
                                $conn->close();

I'm retrieving the variables $username, $fname,.. like so from a form:

$fname = mysqli_real_escape_string($conn,$_POST['fname']);

here is the error:
Fatal error: Call to a member function bind_param() on a non-object in

Body:
bind_param does not accept non-variables as parameters

They must be variables. Store meee as $meee = 'meee' for example

See the manual: http://php.net/manual/en/mysqli-stmt.bind-param.php

Example:

$value1 = 'mee';
$value2 = 'youu';
.
.
.
$stmt->bind_param("ss",$value1,$value2);

See the point of bound parameters is to not allow invalid/unsafe data to be used in a query. You're hard coding string/parameters in so in this case, there's no reason to USE a prepared statement because you could do the same with INSERT INTO X (col1,col2) VALUES ('val1',val2').


问:
When can we NOT specify type parameter
Given the following test case, there are 3 scenarios in it. I would ask what's the rules here that govern when we must and when we don't have to specify the type parameter

```<code>  @Test
  def testTypeParamter(): Unit = {

    class Cat[A]

    //1. Don't need to specify the type parameter for Cat
    def getCat() = new Cat
    println(getCat())

    import scala.collection.mutable.ArrayBuffer

    //2. Don't need to specify the type parameter for ArrayBuffer

    val bf = new ArrayBuffer()
    println(bf)

    //3. Do need to specify the type parameter for ArrayBuffer to make bf2 += 1 work
    val bf2 = new ArrayBuffer[Int]()
    bf2 += 1

    println(getCat())
  }
</code>```

Compared with #2 and #3, what can we do if we create an empty ArrayBuffer without type parameter

答:
You don't need to specify the type parameter when Scala infers the type you want. This inference is based both on arguments to method/constructor (none in your case) and on expected type (none in your case). You could also have e.g.

```<code>val buffer: ArrayBuffer[Long] = new ArrayBuffer()
</code>```

Title: When can we NOT specify type parameter

Body:
Given the following test case, there are 3 scenarios in it. I would ask what's the rules here that govern when we must and when we don't have to specify the type parameter

  @Test
  def testTypeParamter(): Unit = {

    class Cat[A]

    //1. Don't need to specify the type parameter for Cat
    def getCat() = new Cat
    println(getCat())

    import scala.collection.mutable.ArrayBuffer

    //2. Don't need to specify the type parameter for ArrayBuffer

    val bf = new ArrayBuffer()
    println(bf)

    //3. Do need to specify the type parameter for ArrayBuffer to make bf2 += 1 work
    val bf2 = new ArrayBuffer[Int]()
    bf2 += 1

    println(getCat())
  }

Compared with #2 and #3, what can we do if we create an empty ArrayBuffer without type parameter

Body:
You don't need to specify the type parameter when Scala infers the type you want. This inference is based both on arguments to method/constructor (none in your case) and on expected type (none in your case). You could also have e.g.

val buffer: ArrayBuffer[Long] = new ArrayBuffer()


问:
select query to display result and the parameter that got the result when using OR clause in where (Oracle)
I have a query

```<code>select columnX from tableA
  where (columnY like '%string1%' or columnY like '%string2%');
</code>```

but I also want to know what parameter (string1 or string2) got matched because of which I got my result, so I modify my query to

```<code>  select columnX value,'string1' pattern from tableA
  where columnY like '%string1%'
  union
  select columnX,'string2' from tableA
  where columnY like '%string2%'
</code>```

This gives me my result but makes the query huge (as I have hundreds of patterns to match against so basically I write the entire query for each parameter), I highly doubt this would be the best way to do this, is there some other way to do this where I do not have to write a new query for all the patterns that I want to match ?
Can this be done by simply modifying the query or will I have to use any advanced construct of Oracle SQL to perform what I need ?

答:
You could return a new column with that logic: </p>

```<code>    CASE WHEN columnY like '%string1%' THEN 'string1'
         WHEN columnY like '%string2%' THEN 'string2'
    END
</code>```

Body:
I have a query

select columnX from tableA
  where (columnY like '%string1%' or columnY like '%string2%');

but I also want to know what parameter (string1 or string2) got matched because of which I got my result, so I modify my query to

  select columnX value,'string1' pattern from tableA
  where columnY like '%string1%'
  union
  select columnX,'string2' from tableA
  where columnY like '%string2%'

This gives me my result but makes the query huge (as I have hundreds of patterns to match against so basically I write the entire query for each parameter), I highly doubt this would be the best way to do this, is there some other way to do this where I do not have to write a new query for all the patterns that I want to match ?
Can this be done by simply modifying the query or will I have to use any advanced construct of Oracle SQL to perform what I need ?

Body:
You could return a new column with that logic:

    CASE WHEN columnY like '%string1%' THEN 'string1'
         WHEN columnY like '%string2%' THEN 'string2'
    END


问:
How to extend inner nested objects into multiple objects
In Node.js, I want to convert to extend the nested objects into an array, details as follwing:

```<code> {
"topic":"myTopic",
"content":{
    "name": {
        "tom1" : {
            "value": "String",
        },
        "tom2" : {
            "value": "String",
        },
        "tom3" : {
            "value": "String",
        }
    }
}
}
</code>```

convert and extend to following format

```<code>[{
"topic":"myTopic",
"content":{
    "name": {
        "tom1" : {
            "value": "String",
        }
    }
}
},

{
"topic":"myTopic",
"content":{
    "name": {
        "tom2" : {
            "value": "String",
        }
    }
 }
 },
{
"topic":"myTopic",
"content":{
    "name": {
        "tom3" : {
            "value": "String",
        }
    }
}
}]
</code>```

答:
x = { "topic":"myTopic", "content":{ "name": { "tom1" : { "value": "String", }, "tom2" : { "value": "String", }, "tom3" : { "value": "String", } } } };

console.log(Object.keys(x.content.name).map((n) => {
let y = JSON.parse(JSON.stringify(x));
y.content.name = {};
y.content.name[n] = x.content.name[n];
return y;
}))```

Body:
In Node.js, I want to convert to extend the nested objects into an array, details as follwing:

 {
"topic":"myTopic",
"content":{
    "name": {
        "tom1" : {
            "value": "String",
        },
        "tom2" : {
            "value": "String",
        },
        "tom3" : {
            "value": "String",
        }
    }
}
}

convert and extend to following format

[{
"topic":"myTopic",
"content":{
    "name": {
        "tom1" : {
            "value": "String",
        }
    }
}
},

{
"topic":"myTopic",
"content":{
    "name": {
        "tom2" : {
            "value": "String",
        }
    }
 }
 },
{
"topic":"myTopic",
"content":{
    "name": {
        "tom3" : {
            "value": "String",
        }
    }
}
}]


问:
Bigdecimal low value
I have really low values stored in a mysql db, something like that:

```<code>0.00000070
0.00000097
</code>```

I'm using spring boot to serve this values as a rest api, my model is mapped like this:

```<code>public class Account extends BaseEntity {

    @Column(name = "VALUATION", precision = 15, scale = 8)
    @JsonView({ ViewsUtil.Ticker.class, ViewsUtil.Chart.class })
    @Setter @Getter
    private BigDecimal valuation;

    // others fields
</code>```

In the db it's stored correctly, like i showed up, but to display, it's showing just like this:

```<code>{
   "valuation": 9.7e-7
}
</code>```

There's a way to display like it's stored?

Thanks

---- EDIT

Changed my model to this

```<code>    @Column(name = "VALUATION", precision = 15, scale = 8)
    @JsonView({ ViewsUtil.Ticker.class, ViewsUtil.Chart.class })
    @JsonDeserialize(using = LowValueDeserializer.class)
    @Setter @Getter
    private BigDecimal valuation;
</code>```

And my custom deserializer like this:

```<code>@JsonComponent
public class LowValueDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        System.out.println(parser.getDecimalValue());

        return parser.getDecimalValue().toPlainString();
    }
}
</code>```

The system out is never invoked and the result still the same.

答:
Update:
As JB Nizet says in his comment, you must use:

WRITE_BIGDECIMAL_AS_PLAIN

Since Jackson 2.2 the WRITE_BIGDECIMAL_AS_PLAIN is available under the Datatype-specific serialization and in default set as false.

You can set it to true with the method enable() from ObjectMapper, like the following:

```<code>ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN);
</code>```

At the point you convert the BigDecimal to String, you must use the .toPlainString() method, like the following:

```<code>String theWholeNumber = YourBigDecimalNumber.toPlainString();
</code>```

I think your problem is, that the value is shown with exponents in your JSON-String. I think it's not a problem, because you use the same model on client and server side (hopefully). If you want to work with it, it is not necessary to change the format. Only, if you want to display it, you need to convert it to String with the .toPlainString() method.

Title: Bigdecimal low value

Body:
I have really low values stored in a mysql db, something like that:

0.00000070
0.00000097

I'm using spring boot to serve this values as a rest api, my model is mapped like this:

public class Account extends BaseEntity {

    @Column(name = "VALUATION", precision = 15, scale = 8)
    @JsonView({ ViewsUtil.Ticker.class, ViewsUtil.Chart.class })
    @Setter @Getter
    private BigDecimal valuation;

    // others fields

In the db it's stored correctly, like i showed up, but to display, it's showing just like this:

{
   "valuation": 9.7e-7
}

There's a way to display like it's stored?

Thanks

---- EDIT

Changed my model to this

    @Column(name = "VALUATION", precision = 15, scale = 8)
    @JsonView({ ViewsUtil.Ticker.class, ViewsUtil.Chart.class })
    @JsonDeserialize(using = LowValueDeserializer.class)
    @Setter @Getter
    private BigDecimal valuation;

And my custom deserializer like this:

@JsonComponent
public class LowValueDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        System.out.println(parser.getDecimalValue());

        return parser.getDecimalValue().toPlainString();
    }
}

The system out is never invoked and the result still the same.

Body:
Update:
As JB Nizet says in his comment, you must use:

WRITE_BIGDECIMAL_AS_PLAIN

Since Jackson 2.2 the WRITE_BIGDECIMAL_AS_PLAIN is available under the Datatype-specific serialization and in default set as false.

You can set it to true with the method enable() from ObjectMapper, like the following:

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN);

At the point you convert the BigDecimal to String, you must use the .toPlainString() method, like the following:

String theWholeNumber = YourBigDecimalNumber.toPlainString();

I think your problem is, that the value is shown with exponents in your JSON-String. I think it's not a problem, because you use the same model on client and server side (hopefully). If you want to work with it, it is not necessary to change the format. Only, if you want to display it, you need to convert it to String with the .toPlainString() method.


问:
How to get remote file size from a shell script?
Is there a way to get the size of a remote file like

```<code>http://api.twitter.com/1/statuses/public_timeline.json
</code>```

in shell script?

答:
You can download the file and get its size. But we can do better.

Use curl to get only the response header using the -I option.

In the response header look for Content-Length: which will be followed by the size of the file in bytes.

```<code>$ URL="http://api.twitter.com/1/statuses/public_timeline.json"
$ curl -sI $URL | grep -i Content-Length
Content-Length: 134
</code>```

To get the size use a filter to extract the numeric part from the output above:

```<code>$ curl -sI $URL | grep -i Content-Length | awk '{print $2}'
134
</code>```

Body:
Is there a way to get the size of a remote file like

http://api.twitter.com/1/statuses/public_timeline.json

in shell script?

Body:
You can download the file and get its size. But we can do better.

Use curl to get only the response header using the -I option.

In the response header look for Content-Length: which will be followed by the size of the file in bytes.

$ URL="http://api.twitter.com/1/statuses/public_timeline.json"
$ curl -sI $URL | grep -i Content-Length
Content-Length: 134

To get the size use a filter to extract the numeric part from the output above:

$ curl -sI $URL | grep -i Content-Length | awk '{print $2}'
134

ContentLicense: CC BY-SA 4.0


问:
In JPA Query, can I pass the order by property and DESC/ASC order as parameters in the method signature?
I am using spring framework and working repository level implementations.

I have a class:

@Repository
public interface MyClassReadRepository extends ReadRepository<MyClass, Integer>

In this class there is a method that looks like this:

@Query("SELECT a FROM MyClass a WHERE a.type IN :myType ORDER BY :someProperty :someOrder")
Page<MyClass> findByTypeAndOrder(@Param("myType") List<MyType> myType, @Param("someProperty")String someProperty, @Param("someOrder")String someOrder, Pageable pageable)

But apparently the Query structure is wrong: ":someProperty" should be an identifier...

My question is: how to pass order and sort parameters in the example above?

Thanks in advance!

答:
My question is: how to pass order and sort parameters in the example above?

In JPA (and JDBC) parameters are placeholders for values, not for more general query text.  You cannot use them in place of identifiers such as column or table names, nor in place of keywords such as ASC / DESC.

Queries that have similar form but differ in one or more identifiers or keywords are fundamentally different queries.  You need different Querys to represent them.


问:
spring boot @Value always null
I am using spring boot 1.5.3 and trying to inject the properties from an application-dev.properties file into a Service bean but the value is always coming as null. The value does get loaded in my DevConfiguration class though.

I have a application class as below in my base package

```<code>package com.me;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
</code>```

I have a configuration class as follows in

```<code>package com.me.print.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@Profile("dev")
@PropertySources({
    @PropertySource("classpath:application.properties"),
    @PropertySource("classpath:application-dev.properties")
})
@ComponentScan(value = {"com.me.print.client"})
public class DevConfiguration {

    @Value("${app.service.url}")
    private String rootUri;

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}
</code>```

My Service bean that I am trying to load the value into is below

```<code>package com.me.print.client;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.me.print.model.zitResponse;

@Service
public class zitPrintClient {

    private final RestTemplate restTemplate;

    @Value("${app.service.url}")
    private String rootUri;

    public zitPrintClient(RestTemplateBuilder restTemplateBuilder) {
        restTemplate = restTemplateBuilder
                //.rootUri(rootUri)
                .build();
    }

    public zitResponse getpooltatus(String poolId) {
        return restTemplate.getForObject("/pool/{poolId}/@status",
                  zitResponse.class, poolId);
    }

}
</code>```

In the above class the rootURI is always null. Does anyone have any suggestions as to what I am missing

in my application-dev.properties file I have the following

```<code>app.service.url=http://localhost:8080/zitprint/v1
</code>```

Thanks

UPDATE:

does anyone have any suggestions here as I tried to inject properties into my controller as follows:

```<code>@Value("${allowedVendors}") String allowedVendors
</code>```

and if i put the above into a constructor it finds the value but does not find it otherwise:

```<code>public PController(@Value("${allowedVendors}") String allowedVendors) {

}
</code>```

I cant use the property further in the code as with the constructor I have created two instances of the bean 1 via the constructor and the other created by spring DI. Any ideas why the value doesnt inject without the constructor

Thanks

答:
You need to put it as a parameter in the constructor:

```<code>public zitPrintClient(RestTemplateBuilder restTemplateBuilder,
     @Value("${app.service.url}") rootUri) {
         this.rootUri = rootUri; // if you are only using this once,
                                 // no need to keep this member variable around
         restTemplate = restTemplateBuilder
                .rootUri(rootUri)
                .build();
    }
</code>```

The constructor gets called first when you are creating the object. The member variable, rootUri, would have it's value injected after the object is created. So, rootUri member variable would be null at the time the constructor is called.

(And, imho, for better readability, your class should start with a capital letter, i.e. ZitPrintClient, but it's your code ...)

Title: spring boot @Value always null

Body:
I am using spring boot 1.5.3 and trying to inject the properties from an application-dev.properties file into a Service bean but the value is always coming as null. The value does get loaded in my DevConfiguration class though.

I have a application class as below in my base package

package com.me;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

I have a configuration class as follows in

package com.me.print.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@Profile("dev")
@PropertySources({
    @PropertySource("classpath:application.properties"),
    @PropertySource("classpath:application-dev.properties")
})
@ComponentScan(value = {"com.me.print.client"})
public class DevConfiguration {

    @Value("${app.service.url}")
    private String rootUri;

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

My Service bean that I am trying to load the value into is below

package com.me.print.client;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.me.print.model.zitResponse;

@Service
public class zitPrintClient {

    private final RestTemplate restTemplate;

    @Value("${app.service.url}")
    private String rootUri;

    public zitPrintClient(RestTemplateBuilder restTemplateBuilder) {
        restTemplate = restTemplateBuilder
                //.rootUri(rootUri)
                .build();
    }

    public zitResponse getpooltatus(String poolId) {
        return restTemplate.getForObject("/pool/{poolId}/@status",
                  zitResponse.class, poolId);
    }

}

In the above class the rootURI is always null. Does anyone have any suggestions as to what I am missing

in my application-dev.properties file I have the following

app.service.url=http://localhost:8080/zitprint/v1

Thanks

UPDATE:

does anyone have any suggestions here as I tried to inject properties into my controller as follows:

@Value("${allowedVendors}") String allowedVendors

and if i put the above into a constructor it finds the value but does not find it otherwise:

public PController(@Value("${allowedVendors}") String allowedVendors) {

}

I cant use the property further in the code as with the constructor I have created two instances of the bean 1 via the constructor and the other created by spring DI. Any ideas why the value doesnt inject without the constructor

Thanks

Body:
You need to put it as a parameter in the constructor:

public zitPrintClient(RestTemplateBuilder restTemplateBuilder,
     @Value("${app.service.url}") rootUri) {
         this.rootUri = rootUri; // if you are only using this once,
                                 // no need to keep this member variable around
         restTemplate = restTemplateBuilder
                .rootUri(rootUri)
                .build();
    }

The constructor gets called first when you are creating the object. The member variable, rootUri, would have it's value injected after the object is created. So, rootUri member variable would be null at the time the constructor is called.

(And, imho, for better readability, your class should start with a capital letter, i.e. ZitPrintClient, but it's your code ...)


问:
Form.Close isnt working in Windows CE 7
I have windows application that used to run on a Motorola Scanner that used Windows Mobile 6.1. We upgraded the scanner to a newer model which uses Window CE 7. The application has a login form and a main form. One the user is authenticated, the login form closes and the main form opens up as expected but whenever a date is changed on the main form , the login screen reappears. Its as though login.Close() isn't really closing the login form but actually pushing it to the background and its reappearing. This application used to work fine in the older scan gun. I tried searching for specific issues but to no use. </p>

答: I am not sure this is what you are looking for but you can try to set the minimizebox property to false on the form as winmobile tends to not close application but send them to background instead. With that property to false, it will close it. Although it would be interesting to see your code because calling the close() statement on the form should close it...</p>

Title: Form.Close isnt working in Windows CE 7


问:
type of object while implementing interface
Below is my code...

Its not that much complex.

Here I want to understand that In class D, b is an interface type variable and in that variable we are storing reference to new object of class(C) which implements that interface(B). How we are able to assign object of type C to interface B type variable b..? Class and Interface both are of different types then what makes it special when we implements a interface on class and we are able to do it which is my question

```<code>public interface A {

}

public interface B {

    public A methodABCD();
}

public class C implements B {

    final A typeA;

    public A methodABCD() {
        return typeA;
    }
}

public class D {
  static private B b;

  static public A methodABCD() {
    if (b == null) {
        b = new C();-------------->How..?
    }
    return b.methodABCD();
  }
}
</code>```

答:
It is because of one of the design principles, Liskov Substituion Principles, L out of SOLID,
if B is a subtype of P, then objects of type P  can be replaced with instantiations of type B. Search SOLID design principles on google for more details. An object oriented language follows this </p>

Body:
Below is my code...

Its not that much complex.

Here I want to understand that In class D, b is an interface type variable and in that variable we are storing reference to new object of class(C) which implements that interface(B). How we are able to assign object of type C to interface B type variable b..? Class and Interface both are of different types then what makes it special when we implements a interface on class and we are able to do it which is my question

public interface A {

}

public interface B {

    public A methodABCD();
}

public class C implements B {

    final A typeA;

    public A methodABCD() {
        return typeA;
    }
}

public class D {
  static private B b;

  static public A methodABCD() {
    if (b == null) {
        b = new C();-------------->How..?
    }
    return b.methodABCD();
  }
}


问:
Does shadow for directional light even work in SceneKit?
I can only get shadows to work for spotlight, but not for directional light.
Has anyone out there ever gotten it to work? (Using Swift, if that should matter.)</p>

答:
You need to set the scale property of the light e.g.</p>

```<code>lightNode.light?.orthographicScale = 50
</code>```

Body:
You need to set the scale property of the light e.g.

lightNode.light?.orthographicScale = 50


问:
Should I explicitly send the Refresh Token to get a new Access Token - JWT
In my application, I return an access token and a refresh token when a user logs in successfully. The expiration times for access and refresh token have been set to 10 and 40 minutes respectively. (I should do some more research on those values. This is just for testing)

I used the implementation described in following article

http://www.svlada.com/jwt-token-authentication-with-spring-boot/

Let's say I invoke a request to the server after 10 minutes of the login in. Since the access token is expired, I am getting 401 error response.

However, as a beginner, I find it difficult to understand whether I need to send the refresh token explicitly in order to obtain a new access token. If I should do so, how to do that? I should send the refresh token as what? a header?

Or else, when my request is rejected by the server since the access token is expired, should the refresh token itself send a request automatically to the server in order to obtain a new access token?

I found it hard to understand the nature of the behavior of refresh token from the resources I found on the net. Kindly clarify me on these questions.

答:
Yes, the refresh token is used to obtain a new access token.

When you request the access token for the first time, you usually start by sending a token request to the token endpoint, in case of the so called Resource Owner Password Credentials Grant with user credentials in the request header, e.g.

```<code>grant_type=password&username=user1&passowrd=very_secret
</code>```

when the access token is expired, you have to request a new access token. This time, with a refresh token which is still valid, you don't need the user credentials again but send

```<code>grant_type=refresh_token&refresh_token=<your refresh token>
</code>```

instead.
This way you don't need to store the user credential on client side and don't need to bother the user again with a login procedure.
As you know the expiry time, you can also implement a mechanism to refresh your token before the access_token is expired.

Additionally you can read this for further information about the topic: https://auth0.com/learn/refresh-tokens/

In the following tutorial is also a screenshot of how to use refresh token in postman: http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/ (scroll down to step 6)
Generally I can recommend reading Taiseer Joudeh's tutorial, esp. for C#, ASP.NET uand Angular programmers.

Body:
Yes, the refresh token is used to obtain a new access token.

When you request the access token for the first time, you usually start by sending a token request to the token endpoint, in case of the so called Resource Owner Password Credentials Grant with user credentials in the request header, e.g.

grant_type=password&username=user1&passowrd=very_secret

when the access token is expired, you have to request a new access token. This time, with a refresh token which is still valid, you don't need the user credentials again but send

grant_type=refresh_token&refresh_token=<your refresh token>

instead.
This way you don't need to store the user credential on client side and don't need to bother the user again with a login procedure.
As you know the expiry time, you can also implement a mechanism to refresh your token before the access_token is expired.

Additionally you can read this for further information about the topic: https://auth0.com/learn/refresh-tokens/

In the following tutorial is also a screenshot of how to use refresh token in postman: http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/ (scroll down to step 6)
Generally I can recommend reading Taiseer Joudeh's tutorial, esp. for C#, ASP.NET uand Angular programmers.


问:
Angular material autocomplete does not auto close on document blur
Natural behaviour of an input field when you click on the 'body' of the document, is to blur the element. However with the autocomplete directive on desktop this works, but on mobile it never lets you close the menu unless you pick an item or refresh the page.

I thought this was just my setup, however if you run chrome and emulate an iphone 5 it does not close the autocomplete dropdown list when you click outside it.

Is this possible out of the box?

答:
One option is set your css with rule under:</p>

```<code>.md-scroll-mask{
    display none
}
</code>```

Body:
One option is set your css with rule under:

.md-scroll-mask{
    display none
}


问:
Get the total number of permutations in python
Okay i have written a function/method in which I do some operations after a certain if condition is failed mostly but only 1-2 times it will be true.

Here is my code:

```<code>def solve_current_level(self):
    self.remaining_possibilities = list(self.remaining_possibilities)
    if len(self.remaining_possibilities) > 10 ** 6:
        #self.reduce_weapon_options()
        pass

    guess = list(random.choice(self.remaining_possibilities))
    response = self.client.solve_level(self.current_level.levelNum, guess)

    if 'roundsLeft' in response:
        self.reset_remaining_possibilities()
        return None
    elif 'response' not in response:
        return response

    self.remaining_possibilities=[possibility for possibility in self.remaining_possibilities if game.Game_evaluate(guess, list(possibility)) == response['response']]
    return None
</code>```

Now the problem happens when very large permutations is generated and then converted into a list to check if the length is over 10**6 then do something else and come back. This is my current solution but issue is when it gets very huge script gets killed. I converted this piece of code from ruby and in ruby one can get the size of enumerator without converting to list as well and this issue never happens there.

Here is the code in ruby:

```<code>def solve_current_level
  reduce_weapon_options if @remaining_possibilities.size > 10 ** 6
  if !@remaining_possibilities.kind_of?(Array)
    @remaining_possibilities = @remaining_possibilities.to_a
  end

  guess = @remaining_possibilities.sample
  response = @client.solve_level(@current_level.levelNum, guess)

  if response['roundsLeft']
    reset_remaining_possibilities
    return Nil
  elsif !response['response']
    return response
  end

  @remaining_possibilities.select! do |possibility|
    Game.evaluate(guess, possibility) == response['response']
  end
  return Nil
end
</code>```

Now you see in ruby code the length of permutations is calculated before it is converted to array/hash to continue processing and if the number is bigger than 10**6 then it calls another method "reduce_weapon_options". While in python there is not way to get the length of generator without converting to list before everything, I need it to work that way as at this moment when i get some bigger range with big size, it stucks and gets killed by my server. I cannot extend ram as I need to use less ram exactly like ruby and i absolutely want to avoid

self.remaining_possibilities = list(self.remaining_possibilities)

this in python before if condition is passed/failed.

NOTE: I am using itertools.permutations to calculate permutations that later gets saved in "self.remaining_possibilities"

Here is that code both in python and ruby:

```<code>return (0...@numWeapons).to_a.permutation(@numGladiators)
(THIS RETURNS AN ENUMERATOR OBJECT)

return it.permutations(range(0, self.numWeapons), self.numGladiators)
(THIS RETURNS A GENERATOR OBJECT)
</code>```

答:
The simplest way to solve this is probably to calculate the number of permutations generated, using the permutations formula, which can be defined as:

```<code>from math import factorial
def nPr(n, r):
    return int(factorial(n)/factorial(n-r))
</code>```

This, however, requires that this data is available or that the length is passed along from the place where the original permutations generator was created. If this is not the case, for some reason, it is possible to use itertools.tee() to generate a second generator from the first, and use it only for counting:

```<code>def solve_current_level(self):
    self.remaining_possibilities, perm_count = itertools.tee(self.remaining_possibilities)
    # exhausting the 'teed' generator, leaving the 'original' intact:
    num_perm = sum(1 for _ in perm_count)
    if num_perm > 10 ** 6:
        #self.reduce_weapon_options()
        pass
    # here we can still use self.remaining_possibilities
    .
    .
    .
</code>```

Since you are already using itertools this is not a too heavy solution, I guess, but it still requires you to go through the whole list. The memory footprint is considerably smaller, though.

Body:
Okay i have written a function/method in which I do some operations after a certain if condition is failed mostly but only 1-2 times it will be true.

Here is my code:

def solve_current_level(self):
    self.remaining_possibilities = list(self.remaining_possibilities)
    if len(self.remaining_possibilities) > 10 ** 6:
        #self.reduce_weapon_options()
        pass

    guess = list(random.choice(self.remaining_possibilities))
    response = self.client.solve_level(self.current_level.levelNum, guess)

    if 'roundsLeft' in response:
        self.reset_remaining_possibilities()
        return None
    elif 'response' not in response:
        return response

    self.remaining_possibilities=[possibility for possibility in self.remaining_possibilities if game.Game_evaluate(guess, list(possibility)) == response['response']]
    return None

Now the problem happens when very large permutations is generated and then converted into a list to check if the length is over 10**6 then do something else and come back. This is my current solution but issue is when it gets very huge script gets killed. I converted this piece of code from ruby and in ruby one can get the size of enumerator without converting to list as well and this issue never happens there.

Here is the code in ruby:

def solve_current_level
  reduce_weapon_options if @remaining_possibilities.size > 10 ** 6
  if !@remaining_possibilities.kind_of?(Array)
    @remaining_possibilities = @remaining_possibilities.to_a
  end

  guess = @remaining_possibilities.sample
  response = @client.solve_level(@current_level.levelNum, guess)

  if response['roundsLeft']
    reset_remaining_possibilities
    return Nil
  elsif !response['response']
    return response
  end

  @remaining_possibilities.select! do |possibility|
    Game.evaluate(guess, possibility) == response['response']
  end
  return Nil
end

Now you see in ruby code the length of permutations is calculated before it is converted to array/hash to continue processing and if the number is bigger than 10**6 then it calls another method "reduce_weapon_options". While in python there is not way to get the length of generator without converting to list before everything, I need it to work that way as at this moment when i get some bigger range with big size, it stucks and gets killed by my server. I cannot extend ram as I need to use less ram exactly like ruby and i absolutely want to avoid

self.remaining_possibilities = list(self.remaining_possibilities)

this in python before if condition is passed/failed.

NOTE: I am using itertools.permutations to calculate permutations that later gets saved in "self.remaining_possibilities"

Here is that code both in python and ruby:

return (0...@numWeapons).to_a.permutation(@numGladiators)
(THIS RETURNS AN ENUMERATOR OBJECT)

return it.permutations(range(0, self.numWeapons), self.numGladiators)
(THIS RETURNS A GENERATOR OBJECT)

Body:
The simplest way to solve this is probably to calculate the number of permutations generated, using the permutations formula, which can be defined as:

from math import factorial
def nPr(n, r):
    return int(factorial(n)/factorial(n-r))

This, however, requires that this data is available or that the length is passed along from the place where the original permutations generator was created. If this is not the case, for some reason, it is possible to use itertools.tee() to generate a second generator from the first, and use it only for counting:

def solve_current_level(self):
    self.remaining_possibilities, perm_count = itertools.tee(self.remaining_possibilities)
    # exhausting the 'teed' generator, leaving the 'original' intact:
    num_perm = sum(1 for _ in perm_count)
    if num_perm > 10 ** 6:
        #self.reduce_weapon_options()
        pass
    # here we can still use self.remaining_possibilities
    .
    .
    .

Since you are already using itertools this is not a too heavy solution, I guess, but it still requires you to go through the whole list. The memory footprint is considerably smaller, though.


问:
AD Saml login with an OAuth 2 protected webapi?
Need some help understanding this, we have a webapi protected with AAD OAuth 2 token using OWIN middleware. Now the vendor is asking to use SAML for authenticate and OAuth for authorization,'OAuth is supported for API calls but it uses SAML for app login', very confused by this and not know where to look for references for configuration and if any change to the existing API, could someone please help with some pointers? Thanks!</p>

答:
You won't find step by step instructions about this, as SAML isn't really designed to handle web API scenario. Please also note that
- We have no middleware supporting the SAML protocol out of the box. Do you mean SAML tokens and WS-Fed protocol perhaps?
- SAML and WS-Fed describe apps as resources, but in order to call an API you need a client; that means that you would need to use two different set of config coordinates for the app, the SAML/WS-Fed one for auth and the OAuth2 one for the call. You might be able to make this work with Azure AD (as the session cookie issued at sign in time is the same regardless of the web sso protocol) but it will require extra configuration - and per the above, there won't be documentation helping you to stitch the flows together


问:
Open URL on phone from watch face
I have a watch face that I've created and I was looking into adding an "About" screen in the watch settings (on the watch). This screen would show the current version and show a button to open a URL leading to a changelog. I want the user to be able to click the button on their watch, and have it open the specified URL on the phone.

Is this possible without me creating a mobile companion application?

答:
You can do this if the watch is running Android Wear 2 using a RemoteIntent, as such:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW)
                .addCategory(Intent.CATEGORY_BROWSABLE)
                .setData(Uri.parse("http://www.google.com"));

RemoteIntent.startRemoteActivity(context, intent, null);
</code>```

...replacing http://www.google.com with your desired URL, of course.

AFAIK, there's no way to accomplish this on Wear 1.x without sending a message to your handheld app and programming it to open the URL itself.

Title: Open URL on phone from watch face

Body:
You can do this if the watch is running Android Wear 2 using a RemoteIntent, as such:

Intent intent = new Intent(Intent.ACTION_VIEW)
                .addCategory(Intent.CATEGORY_BROWSABLE)
                .setData(Uri.parse("http://www.google.com"));

RemoteIntent.startRemoteActivity(context, intent, null);

...replacing http://www.google.com with your desired URL, of course.

AFAIK, there's no way to accomplish this on Wear 1.x without sending a message to your handheld app and programming it to open the URL itself.