问:
Get data from ignite cache using Cassandra querying
I have a Cassandra database table which is cached to ignite cache. I want to use some select query to this table. Is it possible to achieve this using SqlFieldsQuery & QueryFieldsCursor in c++ ? or is there any other option for doing this?
I just done a try using this

```<code>SqlFieldsQuery sql ("select * from user_permission");
QueryFieldsCursor cursor = cache.Query(qry);
while (cursor.HasNext())
    {
        QueryFieldsRow row = cursor.GetNext();
        std::cout << row.GetNext<std::string>() << row.GetNext<std::string>() << std::endl;
    }
</code>```

But got an error like this " Failed to parse query: select * from user_permission"

答:
First of all, you don't query Cassandra using query API, you query data that is already in Ignite. So prior to executing queries, you have to preload data from Cassandra to Ignite. For this you need to configure Cassandra persistence store [1] and then use cache.LoadCache method.

Second of all, you need to make sure that SQL is configured properly as well [2].

[1] https://apacheignite-mix.readme.io/docs/ignite-with-apache-cassandra

[2] https://apacheignite-cpp.readme.io/docs/sql-queries

Body:
I have a Cassandra database table which is cached to ignite cache. I want to use some select query to this table. Is it possible to achieve this using SqlFieldsQuery & QueryFieldsCursor in c++ ? or is there any other option for doing this?
I just done a try using this

SqlFieldsQuery sql ("select * from user_permission");
QueryFieldsCursor cursor = cache.Query(qry);
while (cursor.HasNext())
    {
        QueryFieldsRow row = cursor.GetNext();
        std::cout << row.GetNext<std::string>() << row.GetNext<std::string>() << std::endl;
    }

But got an error like this " Failed to parse query: select * from user_permission"


来源: stackexchange

问:
Java CSV Formatting Issues
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

```<code>HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);
</code>```

It produces

```<code>Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,
</code>```

Expected Output (without comma at the end of each line):

```<code>Feature2,Feature1
2,1
</code>```

Which is  a wrong formatting

This is the code I use. How to fix it ?

```<code>public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}
</code>```

答:
Java 8 has String.join():

Having collected the keys and values into lists:

```<code> csvReport.append(String.join(",", keys));
 csvReport.append(String.join(",", values));
</code>```

The Streams API has Collectors.joining() which helps even more:

```<code> List<Entry> entries = new ArrayList<>(map.entrySet());
 csvReport.append(entries.stream()
     .map(e -> e.getKey())
     .collect(Collectors.joining(","));
 csvReport.append("\n");
      csvReport.append(entries.stream()
     .map(e -> e.getValue())
     .collect(Collectors.joining(","));
 csvReport.append("\n");
</code>```

Both of these ultimately use StringJoiner. If you have an academic interest in how to build a joined string without a delimiter at the end, it's worth looking at the code for StringJoiner for an elegant example.

However - There are subtleties to writing CSV and it's a good idea to use a library unless there are reasons (legal, academic) not to. Apache Commons CSV is one.

ContentLicense: CC BY-SA 3.0

Title: Java CSV Formatting Issues

Body:
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);

It produces

Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,

Expected Output (without comma at the end of each line):

Feature2,Feature1
2,1

Which is  a wrong formatting

This is the code I use. How to fix it ?

public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}

Body:
Java 8 has String.join():

Having collected the keys and values into lists:

 csvReport.append(String.join(",", keys));
 csvReport.append(String.join(",", values));

The Streams API has Collectors.joining() which helps even more:

 List<Entry> entries = new ArrayList<>(map.entrySet());
 csvReport.append(entries.stream()
     .map(e -> e.getKey())
     .collect(Collectors.joining(","));
 csvReport.append("\n");
      csvReport.append(entries.stream()
     .map(e -> e.getValue())
     .collect(Collectors.joining(","));
 csvReport.append("\n");

Both of these ultimately use StringJoiner. If you have an academic interest in how to build a joined string without a delimiter at the end, it's worth looking at the code for StringJoiner for an elegant example.

However - There are subtleties to writing CSV and it's a good idea to use a library unless there are reasons (legal, academic) not to. Apache Commons CSV is one.


问:
Suppress Invoke-SQLCMD Warnings
I have the following code:

```<code>invoke-sqlcmd -ServerInstance $server\$instance -InputFile "$Path\checkDBEncryption.sql" -ErrorAction Ignore -ErrorVariable var | Format-Table;
</code>```

I need any error from invoke-sqlcmd to be hidden from the powershell output since I'm already logging the errors in a separate file. The problem is,        -ErrorAction Ignore (or SilentlyContinue) isn't working, and setting $ErrorActionPreference isn't an option.

答:
if you want to send stuff to the bit-bucket as it were, use one of the following three techniques:

```<code>cmdlet | out-null
</code>```

or...

```<code>[void]cmdlet
</code>```

or... (and pertienent to your case):

```<code>cmdlet -ErrorVariable $errorvar
cmdlet -WarningVariable $warningvar
</code>```

"I/O" in all modern shells is done via streams.  The most common are standard-out (STDOUT), standard-error (STDERR), and standard-in (STDIN).  PowerShell has a bunch more (e.g. debug, verbose, etc.).  Most of the time, normal output comes into one of the 3 main streams.  However, data can also be emmited out of the verbose stream or debug stream.  Most interactions are based off of the 3 primary types so when trying to assign output from a cmdlet, you're essentially trying to assign something from STDOUT but the data is coming from STDERR...

Just in case your question relates to actually handling the error, you need to trap it and the syntax for that is thus:

```<code>try {
   cmdlet -ERRORACTION STOP
} catch {
   ## Do something with $_ or $error[0] or nothing at all
}
</code>```

the -erroraction stop is in all caps because it is essential.  Error trapping catches terminating errors, only.  PowerShell defaults to non-terminating (with the error action preference variable you talked about above) errors which is why we need to explicity define that this cmdlet should terminate on error.  This allows our error trapping logic to handle the different possible error conditions, as necessary.

EDIT -- Including an example from the comments:

```<code>try {
   $sql = invoke-sqlcmd -ServerInstance $server\$instance -InputFile "$Path\checkDBEncryption.sql" -ErrorAction Stop
} catch {
   ## do nothing, leave this blank or leave this comment
}
</code>```

Title: Suppress Invoke-SQLCMD Warnings

Body:
I have the following code:

invoke-sqlcmd -ServerInstance $server\$instance -InputFile "$Path\checkDBEncryption.sql" -ErrorAction Ignore -ErrorVariable var | Format-Table;

I need any error from invoke-sqlcmd to be hidden from the powershell output since I'm already logging the errors in a separate file. The problem is,        -ErrorAction Ignore (or SilentlyContinue) isn't working, and setting $ErrorActionPreference isn't an option.

Body:
if you want to send stuff to the bit-bucket as it were, use one of the following three techniques:

cmdlet | out-null

or...

[void]cmdlet

or... (and pertienent to your case):

cmdlet -ErrorVariable $errorvar
cmdlet -WarningVariable $warningvar

"I/O" in all modern shells is done via streams.  The most common are standard-out (STDOUT), standard-error (STDERR), and standard-in (STDIN).  PowerShell has a bunch more (e.g. debug, verbose, etc.).  Most of the time, normal output comes into one of the 3 main streams.  However, data can also be emmited out of the verbose stream or debug stream.  Most interactions are based off of the 3 primary types so when trying to assign output from a cmdlet, you're essentially trying to assign something from STDOUT but the data is coming from STDERR...

Just in case your question relates to actually handling the error, you need to trap it and the syntax for that is thus:

try {
   cmdlet -ERRORACTION STOP
} catch {
   ## Do something with $_ or $error[0] or nothing at all
}

the -erroraction stop is in all caps because it is essential.  Error trapping catches terminating errors, only.  PowerShell defaults to non-terminating (with the error action preference variable you talked about above) errors which is why we need to explicity define that this cmdlet should terminate on error.  This allows our error trapping logic to handle the different possible error conditions, as necessary.

EDIT -- Including an example from the comments:

try {
   $sql = invoke-sqlcmd -ServerInstance $server\$instance -InputFile "$Path\checkDBEncryption.sql" -ErrorAction Stop
} catch {
   ## do nothing, leave this blank or leave this comment
}


问:
Video.js : show big play button at the end
I would like to show the big play button at the end of the video, so user can replay it easily.

It seems that this big play button is shown by default (every posts I read are for hidding it instead of showing it...), but it is not the case for me...

I have tried to edit the following function (in video.dev.js file) but nothing has changed :

```<code>vjs.Player.prototype.onEnded = function(){
  if (this.options_['loop']) {
      this.currentTime(0);
      this.play();
  }
  else {  // I am not using loop mode
      this.bigPlayButton.show();
      this.pause();
  }
};
</code>```

Thanks for your responses.

答:
I don't know why but I cant get the answers mentioned here to work, maybe it's because I am on a newer version of the player, so doing things like vid.posterImage.show() is not doing anything for me.

On version 5.19.2 (current release), I was able to reset the player to it's default state (before the play button is pressed by the first time) by setting hasStarted to false on the event listener "ended".

example:

```<code>var player = videojs('player');

player.on("ended",function(){

    player.hasStarted(false);
});
</code>```

That brings back the big button, the poster, and hides the controls.

Body:
I would like to show the big play button at the end of the video, so user can replay it easily.

It seems that this big play button is shown by default (every posts I read are for hidding it instead of showing it...), but it is not the case for me...

I have tried to edit the following function (in video.dev.js file) but nothing has changed :

vjs.Player.prototype.onEnded = function(){
  if (this.options_['loop']) {
      this.currentTime(0);
      this.play();
  }
  else {  // I am not using loop mode
      this.bigPlayButton.show();
      this.pause();
  }
};

Thanks for your responses.

Body:
I don't know why but I cant get the answers mentioned here to work, maybe it's because I am on a newer version of the player, so doing things like vid.posterImage.show() is not doing anything for me.

On version 5.19.2 (current release), I was able to reset the player to it's default state (before the play button is pressed by the first time) by setting hasStarted to false on the event listener "ended".

example:

var player = videojs('player');

player.on("ended",function(){

    player.hasStarted(false);
});

That brings back the big button, the poster, and hides the controls.


问:
Why can't I see datetime fields in rails_admin show view?
I'm adding a new model to rails_admin.  The list page displays datetime fields correctly, even without any configuration.  But the detail (show) page for a given object does not display datetimes. How do I configure rails_admin to show datetime fields on the show page?

Model file: alert_recording.rb:

```<code>class AlertRecording < ActiveRecord::Base
  attr_accessible :user_id, :admin_id, :message, :sent_at, :acknowledged_at, :created_at, :updated_at
end
</code>```

Rails_admin initializer file:

```<code>...
config.included_models = [
  AlertRecording
]

...

config.model AlertRecording do
  field :sent_at, :datetime
  field :acknowledged_at, :datetime
  field :message
  field :user
  field :admin
  field :created_at, :datetime
  field :updated_at, :datetime
  list do; end
  show do; end
end
</code>```

What's the correct way to configure the datetime fields so I see them on the show view?

答:
These fields are hidden by default as you can see here:

https://github.com/sferik/rails_admin/blob/ead1775c48754d6a99c25e4d74494a60aee9b4d1/lib/rails_admin/config.rb#L277

You can overwrite this setting on your config initializer, just open the file config/initializers/rails_admin.rb and add this line to it:

config.default_hidden_fields = []

or something like this:

config.default_hidden_fields = [:id, :my_super_top_secret_field]

That way you doesn't need to do a config to every model in your app ;)

BUT!!! This will show these fields in edit action, so it's a good idea to hide id, created_at and updated_at in this case.

To do this you can assign a hash on this setting, like so:

```<code>config.default_hidden_fields = {
  show: [],
  edit: [:id, :created_at, :updated_at]
}
</code>```

And voilà, you have what you want. ;)

Body:
I'm adding a new model to rails_admin.  The list page displays datetime fields correctly, even without any configuration.  But the detail (show) page for a given object does not display datetimes. How do I configure rails_admin to show datetime fields on the show page?

Model file: alert_recording.rb:

class AlertRecording < ActiveRecord::Base
  attr_accessible :user_id, :admin_id, :message, :sent_at, :acknowledged_at, :created_at, :updated_at
end

Rails_admin initializer file:

...
config.included_models = [
  AlertRecording
]

...

config.model AlertRecording do
  field :sent_at, :datetime
  field :acknowledged_at, :datetime
  field :message
  field :user
  field :admin
  field :created_at, :datetime
  field :updated_at, :datetime
  list do; end
  show do; end
end

What's the correct way to configure the datetime fields so I see them on the show view?

Body:
These fields are hidden by default as you can see here:

https://github.com/sferik/rails_admin/blob/ead1775c48754d6a99c25e4d74494a60aee9b4d1/lib/rails_admin/config.rb#L277

You can overwrite this setting on your config initializer, just open the file config/initializers/rails_admin.rb and add this line to it:

config.default_hidden_fields = []

or something like this:

config.default_hidden_fields = [:id, :my_super_top_secret_field]

That way you doesn't need to do a config to every model in your app ;)

BUT!!! This will show these fields in edit action, so it's a good idea to hide id, created_at and updated_at in this case.

To do this you can assign a hash on this setting, like so:

config.default_hidden_fields = {
  show: [],
  edit: [:id, :created_at, :updated_at]
}

And voilà, you have what you want. ;)


问:
When exporting reactjs components as node modules to npm, do I include jsx or js
I have been creating some React.js components and publishing them as modules to npm.

I am using the following gulp task to convert all of my jsx components into js, using gulp-react:

```<code>var react = require('gulp-react');

gulp.task('react', function () {
  return gulp.src('./jsx/*.jsx')
    .pipe(react({
      harmony: true
    }))
    .pipe(gulp.dest('./js/'));
});
</code>```

So in my published module I have components in the js and jsx folder.

My question is which is it better to point the main file to in my package.json?

js

```<code>"main": "js/todo.js",
</code>```

or jsx

```<code>"main": "jsx/todo.jsx",
</code>```

I would assume if I point them to the jsx then they will need to have gulp-react installed, so would I add that into peerDependencies?

答: Your .js, because then you can add something more in the pipeline and it'll be covered

Body:
I have been creating some React.js components and publishing them as modules to npm.

I am using the following gulp task to convert all of my jsx components into js, using gulp-react:

var react = require('gulp-react');

gulp.task('react', function () {
  return gulp.src('./jsx/*.jsx')
    .pipe(react({
      harmony: true
    }))
    .pipe(gulp.dest('./js/'));
});

So in my published module I have components in the js and jsx folder.

My question is which is it better to point the main file to in my package.json?

js

"main": "js/todo.js",

or jsx

"main": "jsx/todo.jsx",

I would assume if I point them to the jsx then they will need to have gulp-react installed, so would I add that into peerDependencies?


问:
Print data in next line when we found double space in our paragraph
$pro_spec = Gary Keller is co-founder and chairman of Keller Williams Realty, the largest real estate franchise in the world.  He is the New York Times bestselling author of numerous books, including The Millionaire Real Estate Agent,  The Millionaire Real Estate Investor, SHIFT: How Top Real Estate Agents Tackle Tough Times, and, most recently,  The ONE Thing: The Surprisingly Simple Truth Behind Extraordinary Results.

```<code>enter code <?php

                $result = str_split($pro_pros);

                $length = count($result);

                for($i=0;$i<$length-1;$i++)
                {
                    if($result[$i] == " " && $result[$i+1] == " ")
                    {
                        $substring = substr($pro_pros,isset($bun)? $bun+1 : 0 ,$i+1);

                            echo $substring

                            $bun = $i+1;
                     }

                 }

             ?>here
</code>```

I want to print data in next line when I got double space in $pro_spec.
But After I run above code I got output like this

Gary Keller is co-founder and chairman of Keller Williams Realty, the largest real estate franchise in the world.

He is the New York Times bestselling author of numerous books, including The Millionaire Real Estate Agent, The Millionaire Real Estate Investor, SHIFT: How Top Real Estate Agents Tackle Tough Times, and, most recently,
The Millionaire Real Estate Investor, SHIFT: How Top Real Estate Agents Tackle Tough Times, and, most recently, The ONE Thing: The Surprisingly Simple Truth Behind Extraordinary Results.

The ONE Thing: The Surprisingly Simple Truth Behind Extraordinary Results.

Same data occur in multiple line how can I solve this..

答:
You can use the explode function to split the string into an array when there are double spaces, and then echo each line with whatever line break you want in between.:</p>

```<code><?php

$result = explode('  ', $pro_pos);
foreach ($result as $line) {
    echo $line . '<br />';
}

?>
</code>```

Body:
$pro_spec = Gary Keller is co-founder and chairman of Keller Williams Realty, the largest real estate franchise in the world.  He is the New York Times bestselling author of numerous books, including The Millionaire Real Estate Agent,  The Millionaire Real Estate Investor, SHIFT: How Top Real Estate Agents Tackle Tough Times, and, most recently,  The ONE Thing: The Surprisingly Simple Truth Behind Extraordinary Results.

enter code <?php

                $result = str_split($pro_pros);

                $length = count($result);

                for($i=0;$i<$length-1;$i++)
                {
                    if($result[$i] == " " && $result[$i+1] == " ")
                    {
                        $substring = substr($pro_pros,isset($bun)? $bun+1 : 0 ,$i+1);

                            echo $substring

                            $bun = $i+1;
                     }

                 }

             ?>here

I want to print data in next line when I got double space in $pro_spec.
But After I run above code I got output like this

Gary Keller is co-founder and chairman of Keller Williams Realty, the largest real estate franchise in the world.

He is the New York Times bestselling author of numerous books, including The Millionaire Real Estate Agent, The Millionaire Real Estate Investor, SHIFT: How Top Real Estate Agents Tackle Tough Times, and, most recently,
The Millionaire Real Estate Investor, SHIFT: How Top Real Estate Agents Tackle Tough Times, and, most recently, The ONE Thing: The Surprisingly Simple Truth Behind Extraordinary Results.

The ONE Thing: The Surprisingly Simple Truth Behind Extraordinary Results.

Same data occur in multiple line how can I solve this..

Body:
You can use the explode function to split the string into an array when there are double spaces, and then echo each line with whatever line break you want in between.:

<?php

$result = explode('  ', $pro_pos);
foreach ($result as $line) {
    echo $line . '<br />';
}

?>


问:
how to render disabled button by if statement?
I want to disable a button in a react component when a state of checkedIds is empty, the code to disable button is just like this:

```<code><Button disabled> disabled </Button>
</code>```

But when I try this it don't work

```<code><Button {if(this.state.checkedIds.length===0) {
    return disabled;
  }}>
      Delete Selected
  </Button>
</code>```

Help?

答:
If-else doesn't directly work like that, you should make use of ternary operator and return a boolean value like</p>

```<code><Button disabled={(this.state.checkedIds.length == 0? true: false)}>
      Delete Selected
  </Button>
</code>```

Body:
I want to disable a button in a react component when a state of checkedIds is empty, the code to disable button is just like this:

<Button disabled> disabled </Button>

But when I try this it don't work

<Button {if(this.state.checkedIds.length===0) {
    return disabled;
  }}>
      Delete Selected
  </Button>

Help?

Body:
If-else doesn't directly work like that, you should make use of ternary operator and return a boolean value like

<Button disabled={(this.state.checkedIds.length == 0? true: false)}>
      Delete Selected
  </Button>


问:
How to get random value from specific ranges of dictionary content
If this way I can get random value from given range:

```<code> int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }
</code>```

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

```<code>Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};
</code>```

答:
Depending on what exactly is needed, the easiest might be to specify the possible numbers:

```<code>int[] a { 1, 2, 4, 5, 6 };

int r = a[ran.Next(a.Length)];
</code>```

or

```<code>int r = ran.Next(1, 6);

if (r == 3) r = 6;
</code>```

Body:
If this way I can get random value from given range:

 int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};

Body:
Depending on what exactly is needed, the easiest might be to specify the possible numbers:

int[] a { 1, 2, 4, 5, 6 };

int r = a[ran.Next(a.Length)];

or

int r = ran.Next(1, 6);

if (r == 3) r = 6;


问:
How to publish a jsx file to npm?
I just want to publish a react component to npm, but found out it's so difficult. The file is simple, but with es6 syntax. what is the steps or solution to publish it to npm so that we can just install and run it with locally installed react? I have read this article http://chadly.net/2015/04/publishing-react-to-npm/, but it seems outdated and I failed by following it.</p>

答: I wrote a full Medium story because I had the same issue as you and there is no information about it. Check it out: https://medium.com/@BrodaNoel/how-to-create-a-react-component-and-publish-it-in-npm-668ad7d363ce</p>

Title: How to publish a jsx file to npm?


问:
How can you integrate planck's law to get Stefan-Bolzmann using python?
I'm new to python and am trying to get the stefan boltzmann law by integrating analytically Plancks law. So far I plotted the black body radiation curves but I'm stuck on how to integrate it.This is my function:

```<code>import numpy as np
h=6.626e-34
c=3.0e+8
k=1.38e-23

def planck(x,T):
    a=2.0*h*c**2
    b=(h*c)/*x*k*T)
    intensity= a/( (x**5)*(np.exp(b)-1.0)
    return intensity
</code>```

to integrate it i tried using  SymPy like this:

```<code>from sympy import *
x=Symbol('x')
T=Symbol('T')
integrate((x**3)/(exp(x)-1))
</code>```

but it can't do the integration. I'm sure there is a simplification I'm supposed to do but I'm not sure how.

答:
To get from Plancks law to the Stefan-Boltzmann law you need to integrate over all frequencies (1). Thus you need a definite integral:

```<code>integrate((x**3)/(exp(x)-1),(x,0,oo))
</code>```

The integration is detailed here.
The Riemann zeta function can be used in sympy:

```<code>n = symbols('n')
riemann_zeta = functions.special.zeta_functions.zeta(n,1)
</code>```

but of course there is no dependency on x anymore. Unfortunately sympy can not transform the integral to the analytic expression:

```<code>x = symbols('x', real=True, negative=False)
pprint(simplify(integrate((x**3)/(exp(x)-1),(x,0, oo))))
</code>```

will just give $\int_0^\infty \frac{x^3}{e^x-1}dx$ and not $\zeta(4)\Gamma(4)=\frac{\pi^4}{15}$.
(Sorry about the LaTeX...)

Body:
I'm new to python and am trying to get the stefan boltzmann law by integrating analytically Plancks law. So far I plotted the black body radiation curves but I'm stuck on how to integrate it.This is my function:

import numpy as np
h=6.626e-34
c=3.0e+8
k=1.38e-23

def planck(x,T):
    a=2.0*h*c**2
    b=(h*c)/*x*k*T)
    intensity= a/( (x**5)*(np.exp(b)-1.0)
    return intensity

to integrate it i tried using  SymPy like this:

from sympy import *
x=Symbol('x')
T=Symbol('T')
integrate((x**3)/(exp(x)-1))

but it can't do the integration. I'm sure there is a simplification I'm supposed to do but I'm not sure how.

Body:
To get from Plancks law to the Stefan-Boltzmann law you need to integrate over all frequencies (1). Thus you need a definite integral:

integrate((x**3)/(exp(x)-1),(x,0,oo))

The integration is detailed here.
The Riemann zeta function can be used in sympy:

n = symbols('n')
riemann_zeta = functions.special.zeta_functions.zeta(n,1)

but of course there is no dependency on x anymore. Unfortunately sympy can not transform the integral to the analytic expression:

x = symbols('x', real=True, negative=False)
pprint(simplify(integrate((x**3)/(exp(x)-1),(x,0, oo))))

will just give $\int_0^\infty \frac{x^3}{e^x-1}dx$ and not $\zeta(4)\Gamma(4)=\frac{\pi^4}{15}$.
(Sorry about the LaTeX...)


问:
Inefficient JavaScript Algorithm, How do I make the following code more efficient?
Problem Statement: Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order.

My Solution:

```<code>function comp(array1, array2){

  var test;

  if( array1.length <= 0 || array2.length <= 0 || array1 == null || array2 == null || array2.length != array1.length || array1==undefined || array2==undefined){
    return false;
  }else{
    for(i=0; i<array2.length; i++){
      for(j=0; j<array1.length; j++){
        if(array2[i] === Math.pow(array1[j],2)){
          test = true;
          break;
        }else{
          test = false;
        }
      }
      if(test==false)
        return false;
    }

    if(test === true)
      return true;
    else
      return false;
  }
}
</code>```

Also any constructive criticism about the code is appreciated as I'm still just a wookie so always looking to improve.

Test Example:

```<code>var a1 = [80, 2, 65, 68];
var a2 = [6401, 4, 4225, 4624];
</code>```

For the end result all I want is for true to be returned if true and likewise for false. The program solves all the test cases however it times out.

答:
Here's my code

```<code>function comp(arr1, arr2)
{
    // make sure the arrays are set and are of equal length (if not they obivously don't match)
    if(arr1 == null || arr2 == null || arr1.length != arr2.length)
        return false;
    // sort arrays
    var intSorter = function(a,b){return a-b;};
    arr1.sort(intSorter);
    arr2.sort(intSorter);
    for(var i=0;i<arr1.length;i++)
    {
        var v = arr1[i];
        // if square of value in arr1 does not equal the value in arr2, arrays don't match
        if(v*v!=arr2[i])
            return false;
    }
    return true;
}
// test it!
console.info(comp([2,6,3,8,4,5], [25,64,16,36,4,9]));
console.info(comp([2,6,3,8,4,5], [25,64,17,36,4,9]));
console.info(comp([2,6,3,8,4,5], [25,64,16,36,4,9,9]));
</code>```

Prints true, false, false

I'm not calculating all squares first as a minor optimization, and i use a "custom" intSorter because JavaScript sorts numbers as strings, so 4 ends up after 36 ('3' is before '4')

About your code, you don't need a test variable, just use return whenever you know the function result, and don't use pow() for small values as it uses loops and may be more pricy than if you do it v*v as I did.

Body:
Problem Statement: Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order.

My Solution:

function comp(array1, array2){

  var test;

  if( array1.length <= 0 || array2.length <= 0 || array1 == null || array2 == null || array2.length != array1.length || array1==undefined || array2==undefined){
    return false;
  }else{
    for(i=0; i<array2.length; i++){
      for(j=0; j<array1.length; j++){
        if(array2[i] === Math.pow(array1[j],2)){
          test = true;
          break;
        }else{
          test = false;
        }
      }
      if(test==false)
        return false;
    }

    if(test === true)
      return true;
    else
      return false;
  }
}

Also any constructive criticism about the code is appreciated as I'm still just a wookie so always looking to improve.

Test Example:

var a1 = [80, 2, 65, 68];
var a2 = [6401, 4, 4225, 4624];

For the end result all I want is for true to be returned if true and likewise for false. The program solves all the test cases however it times out.

Body:
Here's my code

function comp(arr1, arr2)
{
    // make sure the arrays are set and are of equal length (if not they obivously don't match)
    if(arr1 == null || arr2 == null || arr1.length != arr2.length)
        return false;
    // sort arrays
    var intSorter = function(a,b){return a-b;};
    arr1.sort(intSorter);
    arr2.sort(intSorter);
    for(var i=0;i<arr1.length;i++)
    {
        var v = arr1[i];
        // if square of value in arr1 does not equal the value in arr2, arrays don't match
        if(v*v!=arr2[i])
            return false;
    }
    return true;
}
// test it!
console.info(comp([2,6,3,8,4,5], [25,64,16,36,4,9]));
console.info(comp([2,6,3,8,4,5], [25,64,17,36,4,9]));
console.info(comp([2,6,3,8,4,5], [25,64,16,36,4,9,9]));

Prints true, false, false

I'm not calculating all squares first as a minor optimization, and i use a "custom" intSorter because JavaScript sorts numbers as strings, so 4 ends up after 36 ('3' is before '4')

About your code, you don't need a test variable, just use return whenever you know the function result, and don't use pow() for small values as it uses loops and may be more pricy than if you do it v*v as I did.


问:
HttpWebRequest Cookie weirdness
I'm sure I must be doing something wrong. But can't for the life of me figure out what is going on.

I have a problem where it seems that the HttpWebRequest class in the framework is not correctly parsing the cookies from a web response.

I'm using Fiddler to see what is going on and after making a request, the headers of the response look as such:

```<code>HTTP/1.1 200 Ok
Connection: close
Date: Wed, 14 Jan 2009 18:20:31 GMT
Server: Microsoft-IIS/6.0
P3P: policyref="/w3c/p3p.xml", CP="CAO DSP IND COR ADM CONo CUR CUSi DEV PSA PSD DELi OUR COM NAV PHY ONL PUR UNI"
Set-Cookie: user=v.5,0,EX01E508801E$97$2E401000t$1BV6$A1$EC$104$A1$EC$104$A1$EC$104$21O001000$1E31!90$7CP$AE$3F$F3$D8$19o$BC$1Cd$23; Domain=.thedomain.com; path=/
Set-Cookie: minfo=v.4,EX019ECD28D6k$A3$CA$0C$CE$A2$D6$AD$D4!2$8A$EF$E8n$91$96$E1$D7$C8$0F$98$AA$ED$DC$40V$AB$9C$C1$9CF$C9$C1zIF$3A$93$C6$A7$DF$A1$7E$A7$A1$A8$BD$A6$94c$D5$E8$2F$F4$AF$A2$DF$80$89$BA$BBd$F6$2C$B6$A8; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: accttype=v.2,3,1,EX017E651B09k$A3$CA$0C$DB$A2$CB$AD$D9$8A$8C$EF$E8t$91$90$E1$DC$C89$98$AA$E0$DC$40O$A8$A4$C1$9C; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: tpid=v.1,20001; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: MC1=GUID=541977e04a341a2a4f4cdaaf49615487; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: linfo=v.4,EQC|0|0|255|1|0||||||||0|0|0||0|0|0|-1|-1; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: group=v.1,0; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Content-Type: text/html
</code>```

But when I look at the response.Cookies, I see far more cookies that I am expecting, with values of different cookies being split up into different cookies.

Manually getting the headers seems to result in more wierdness

eg: the code

```<code>foreach(string cookie in response.Headers.GetValues("Set-Cookie"))
{
    Console.WriteLine("Cookie found: " + cookie);
}
</code>```

produces the output:

```<code>Cookie found: user=v.5
Cookie found: 0
Cookie found: EX01E508801E$97$2E401000t$1BV6$A1$EC$104$A1$EC$104$A1$EC$104$21O00
1000$1E31!90$7CP$AE$3F$F3$D8$19o$BC$1Cd$23; Domain=.thedomain.com; path=/
Cookie found: minfo=v.4
Cookie found: EX019ECD28D6k$A3$CA$0C$CE$A2$D6$AD$D4!2$8A$EF$E8n$91$96$E1$D7$C8$0
F$98$AA$ED$DC$40V$AB$9C$C1$9CF$C9$C1zIF$3A$93$C6$A7$DF$A1$7E$A7$A1$A8$BD$A6$94c$
D5$E8$2F$F4$AF$A2$DF$80$89$BA$BBd$F6$2C$B6$A8; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: accttype=v.2
Cookie found: 3
Cookie found: 1
Cookie found: EX017E651B09k$A3$CA$0C$DB$A2$CB$AD$D9$8A$8C$EF$E8t$91$90$E1$DC$C89
$98$AA$E0$DC$40O$A8$A4$C1$9C; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: tpid=v.1
Cookie found: 20001; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: MC1=GUID=541977e04a341a2a4f4cdaaf49615487; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: linfo=v.4
Cookie found: EQC|0|0|255|1|0||||||||0|0|0||0|0|0|-1|-1; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: group=v.1
Cookie found: 0; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
</code>```

as you can see - the first cookie in the list raw response:

Set-Cookie: user=v.5,0,EX01E508801

is getting split into:

Cookie found: user=v.5

Cookie found: 0

Cookie found: EX01E508801E$..........

So - what's going on here?

Am I wrong?

Is the HttpWebRequest class incorrectly parsing the http headers?

Is the webserver that it spitting out the requests producing invalid http headers?

答:
Commas in cookie values are to be avoided - you may need to encode them differently.

The original netscape spec for cookies was a little vague on this issue, stating

NAME=VALUE :
      This string is a sequence of characters excluding semi-colon, comma
  and white space. If there is a need to
  place such data in the name or value,
  some encoding method such as URL style
  %XX encoding is recommended, though no
  encoding is defined or required.

recommended, but not required!

OwnerDisplayName: Lachman

ContentLicense: CC BY-SA 2.5

Title: HttpWebRequest Cookie weirdness

Body:
I'm sure I must be doing something wrong. But can't for the life of me figure out what is going on.

I have a problem where it seems that the HttpWebRequest class in the framework is not correctly parsing the cookies from a web response.

I'm using Fiddler to see what is going on and after making a request, the headers of the response look as such:

HTTP/1.1 200 Ok
Connection: close
Date: Wed, 14 Jan 2009 18:20:31 GMT
Server: Microsoft-IIS/6.0
P3P: policyref="/w3c/p3p.xml", CP="CAO DSP IND COR ADM CONo CUR CUSi DEV PSA PSD DELi OUR COM NAV PHY ONL PUR UNI"
Set-Cookie: user=v.5,0,EX01E508801E$97$2E401000t$1BV6$A1$EC$104$A1$EC$104$A1$EC$104$21O001000$1E31!90$7CP$AE$3F$F3$D8$19o$BC$1Cd$23; Domain=.thedomain.com; path=/
Set-Cookie: minfo=v.4,EX019ECD28D6k$A3$CA$0C$CE$A2$D6$AD$D4!2$8A$EF$E8n$91$96$E1$D7$C8$0F$98$AA$ED$DC$40V$AB$9C$C1$9CF$C9$C1zIF$3A$93$C6$A7$DF$A1$7E$A7$A1$A8$BD$A6$94c$D5$E8$2F$F4$AF$A2$DF$80$89$BA$BBd$F6$2C$B6$A8; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: accttype=v.2,3,1,EX017E651B09k$A3$CA$0C$DB$A2$CB$AD$D9$8A$8C$EF$E8t$91$90$E1$DC$C89$98$AA$E0$DC$40O$A8$A4$C1$9C; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: tpid=v.1,20001; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: MC1=GUID=541977e04a341a2a4f4cdaaf49615487; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: linfo=v.4,EQC|0|0|255|1|0||||||||0|0|0||0|0|0|-1|-1; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: group=v.1,0; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Content-Type: text/html

But when I look at the response.Cookies, I see far more cookies that I am expecting, with values of different cookies being split up into different cookies.

Manually getting the headers seems to result in more wierdness

eg: the code

foreach(string cookie in response.Headers.GetValues("Set-Cookie"))
{
    Console.WriteLine("Cookie found: " + cookie);
}

produces the output:

Cookie found: user=v.5
Cookie found: 0
Cookie found: EX01E508801E$97$2E401000t$1BV6$A1$EC$104$A1$EC$104$A1$EC$104$21O00
1000$1E31!90$7CP$AE$3F$F3$D8$19o$BC$1Cd$23; Domain=.thedomain.com; path=/
Cookie found: minfo=v.4
Cookie found: EX019ECD28D6k$A3$CA$0C$CE$A2$D6$AD$D4!2$8A$EF$E8n$91$96$E1$D7$C8$0
F$98$AA$ED$DC$40V$AB$9C$C1$9CF$C9$C1zIF$3A$93$C6$A7$DF$A1$7E$A7$A1$A8$BD$A6$94c$
D5$E8$2F$F4$AF$A2$DF$80$89$BA$BBd$F6$2C$B6$A8; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: accttype=v.2
Cookie found: 3
Cookie found: 1
Cookie found: EX017E651B09k$A3$CA$0C$DB$A2$CB$AD$D9$8A$8C$EF$E8t$91$90$E1$DC$C89
$98$AA$E0$DC$40O$A8$A4$C1$9C; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: tpid=v.1
Cookie found: 20001; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: MC1=GUID=541977e04a341a2a4f4cdaaf49615487; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: linfo=v.4
Cookie found: EQC|0|0|255|1|0||||||||0|0|0||0|0|0|-1|-1; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: group=v.1
Cookie found: 0; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/

as you can see - the first cookie in the list raw response:

Set-Cookie: user=v.5,0,EX01E508801

is getting split into:

Cookie found: user=v.5

Cookie found: 0

Cookie found: EX01E508801E$..........

So - what's going on here?

Am I wrong?

Is the HttpWebRequest class incorrectly parsing the http headers?

Is the webserver that it spitting out the requests producing invalid http headers?

LastEditorDisplayName: Paul Dixon

OwnerDisplayName: Paul Dixon


问:
Position of HTML element inside WKWebView
Given a WKWebView showing a web page, how can I get the position (into the frame of my WKWebView) of an HTML element identified by a specific css selector?

Example

Here the position of the highlighted DIV should be (0, 123)

And if a scroll the HTML content the position of the same DIV should be (0, 0)

Thanks

答:
The problem here is that WKWebView scales the the size of its content. The trick to finding the frame of an element in the scrollView is to find out how much the WKWebView is scaling the content by. You can find this scale by comparing the scroll view's content size with what javascript returns as the document size. Below is XCode playground content that I was able to run in XCode 8.3.2.

This will give you the position of images in the scroll view. To get the position in the web view, just subtract
    scrollview.contentOffset.y

TL;DR:

```<code>webView.evaluateJavaScript("document.documentElement.clientHeight;") { (value, error) in
    self.documentHeight = value as! CGFloat
    let zoom = webView.scollView.zoomScale
}
</code>```

_

```<code>import Foundation
import WebKit
import XCPlayground

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

let content = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mauris massa, ornare et ullamcorper a, tristique et odio. Nullam eleifend ex id ante placerat, sit amet feugiat arcu mollis. Sed iaculis lobortis lacus, in fermentum urna sodales at. Integer eget eleifend risus. Aenean feugiat turpis in odio sodales, id volutpat nisi pellentesque. Nunc eleifend nisl nunc, quis blandit nulla posuere ultricies. Nullam varius accumsan neque, vitae imperdiet ante consectetur vel. Fusce ullamcorper eu odio eleifend egestas. <img src=\"https://imgs.xkcd.com/comics/wisdom_of_the_ancients.png\" width=\"98%\"/> Proin elementum odio non massa pulvinar laoreet. Duis tincidunt augue vel placerat euismod. Mauris tincidunt felis at tellus convallis bibendum. Suspendisse purus dolor, lacinia eget tempor feugiat, vestibulum in risus. In non dui nec nisl porttitor pulvinar. Aliquam consectetur nisl at arcu consequat dapibus. Sed ex ante, condimentum vitae diam non, cursus dapibus ligula.<br /><img src=\"https://imgs.xkcd.com/comics/wisdom_of_the_ancients.png\" width=\"98%\"/></p>"

let jsImages = "var images = document.getElementsByTagName('img');" +
    "var values = [];" +
    "for (var i = 0; i < images.length; i++) {" +
        "var rect = images[i].getBoundingClientRect();" +
        "values = values.concat(rect.left, rect.top, rect.width, rect.height);" +
    "};" +
    "values;"

let jsHeight = "document.documentElement.clientHeight;"

class CustomWebView: WKWebView, WKNavigationDelegate {

    var imageLocations: [CGRect] = []
    var documentHeight: CGFloat?

    func getImages()  {
        self.evaluateJavaScript(jsImages) { (values, error) in
            print("=====\nValues from Javascript: \(values)")
            if let values = values as? [Any] {
                let numImages = values.count / 4 // jsImages returns four-value sets
                for set in 0..<numImages {
                    let offset = set * 4
                    let imageFrame = self.jsToSwift(x: values[offset] as! CGFloat, y: values[offset+1] as! CGFloat, w: values[offset+2] as! CGFloat, h: values[offset+3] as! CGFloat)
                    self.imageLocations.append(imageFrame)
                }
                print("=====\nScrollview content size: \(self.scrollView.contentSize)")
                print("=====\nFrames in WebView's ScrollView:\n\(self.imageLocations)\n=====")
            }
        }
    }

    func getHeight(callback: @escaping (() -> Void)) {
        // Evaluate document height
        self.evaluateJavaScript(jsHeight) { (value, error) in
            self.documentHeight = value as? CGFloat
            callback()
        }
    }

    func jsToSwift(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) -> CGRect {
        guard let documentHeight = documentHeight else {
            return CGRect.zero
        }
        let zoom = scollView.zoomScale
        let swiftX = x * zoom
        let swiftY = y * zoom
        let swiftW = w * zoom
        let swiftH = h * zoom
        return CGRect(x: swiftX, y: swiftY, width: swiftW, height: swiftH)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.getHeight { [weak self] (error) in
            self?.getImages()
        }
    }

}

let webView = CustomWebView(frame: CGRect.zero, configuration: WKWebViewConfiguration())
webView.navigationDelegate = webView
webView.loadHTMLString(content, baseURL: nil)
</code>```

Example output:

```<code>=====
Values from Javascript: Optional(<__NSArrayM 0x610000049510>(
8,
1528,
485,
270,
8,
2878,
485,
270
)
)
=====
Scrollview content size: (123.0, 791.0)
=====
Frames in WebView's ScrollView:
[(2.0, 382.0, 121.25, 67.5), (2.0, 719.5, 121.25, 67.5)]
=====
</code>```

Body:
The problem here is that WKWebView scales the the size of its content. The trick to finding the frame of an element in the scrollView is to find out how much the WKWebView is scaling the content by. You can find this scale by comparing the scroll view's content size with what javascript returns as the document size. Below is XCode playground content that I was able to run in XCode 8.3.2.

This will give you the position of images in the scroll view. To get the position in the web view, just subtract
    scrollview.contentOffset.y

TL;DR:

webView.evaluateJavaScript("document.documentElement.clientHeight;") { (value, error) in
    self.documentHeight = value as! CGFloat
    let zoom = webView.scollView.zoomScale
}

_

import Foundation
import WebKit
import XCPlayground

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

let content = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mauris massa, ornare et ullamcorper a, tristique et odio. Nullam eleifend ex id ante placerat, sit amet feugiat arcu mollis. Sed iaculis lobortis lacus, in fermentum urna sodales at. Integer eget eleifend risus. Aenean feugiat turpis in odio sodales, id volutpat nisi pellentesque. Nunc eleifend nisl nunc, quis blandit nulla posuere ultricies. Nullam varius accumsan neque, vitae imperdiet ante consectetur vel. Fusce ullamcorper eu odio eleifend egestas. <img src=\"https://imgs.xkcd.com/comics/wisdom_of_the_ancients.png\" width=\"98%\"/> Proin elementum odio non massa pulvinar laoreet. Duis tincidunt augue vel placerat euismod. Mauris tincidunt felis at tellus convallis bibendum. Suspendisse purus dolor, lacinia eget tempor feugiat, vestibulum in risus. In non dui nec nisl porttitor pulvinar. Aliquam consectetur nisl at arcu consequat dapibus. Sed ex ante, condimentum vitae diam non, cursus dapibus ligula.<br /><img src=\"https://imgs.xkcd.com/comics/wisdom_of_the_ancients.png\" width=\"98%\"/></p>"

let jsImages = "var images = document.getElementsByTagName('img');" +
    "var values = [];" +
    "for (var i = 0; i < images.length; i++) {" +
        "var rect = images[i].getBoundingClientRect();" +
        "values = values.concat(rect.left, rect.top, rect.width, rect.height);" +
    "};" +
    "values;"

let jsHeight = "document.documentElement.clientHeight;"

class CustomWebView: WKWebView, WKNavigationDelegate {

    var imageLocations: [CGRect] = []
    var documentHeight: CGFloat?

    func getImages()  {
        self.evaluateJavaScript(jsImages) { (values, error) in
            print("=====\nValues from Javascript: \(values)")
            if let values = values as? [Any] {
                let numImages = values.count / 4 // jsImages returns four-value sets
                for set in 0..<numImages {
                    let offset = set * 4
                    let imageFrame = self.jsToSwift(x: values[offset] as! CGFloat, y: values[offset+1] as! CGFloat, w: values[offset+2] as! CGFloat, h: values[offset+3] as! CGFloat)
                    self.imageLocations.append(imageFrame)
                }
                print("=====\nScrollview content size: \(self.scrollView.contentSize)")
                print("=====\nFrames in WebView's ScrollView:\n\(self.imageLocations)\n=====")
            }
        }
    }

    func getHeight(callback: @escaping (() -> Void)) {
        // Evaluate document height
        self.evaluateJavaScript(jsHeight) { (value, error) in
            self.documentHeight = value as? CGFloat
            callback()
        }
    }

    func jsToSwift(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) -> CGRect {
        guard let documentHeight = documentHeight else {
            return CGRect.zero
        }
        let zoom = scollView.zoomScale
        let swiftX = x * zoom
        let swiftY = y * zoom
        let swiftW = w * zoom
        let swiftH = h * zoom
        return CGRect(x: swiftX, y: swiftY, width: swiftW, height: swiftH)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.getHeight { [weak self] (error) in
            self?.getImages()
        }
    }

}

let webView = CustomWebView(frame: CGRect.zero, configuration: WKWebViewConfiguration())
webView.navigationDelegate = webView
webView.loadHTMLString(content, baseURL: nil)

Example output:

=====
Values from Javascript: Optional(<__NSArrayM 0x610000049510>(
8,
1528,
485,
270,
8,
2878,
485,
270
)
)
=====
Scrollview content size: (123.0, 791.0)
=====
Frames in WebView's ScrollView:
[(2.0, 382.0, 121.25, 67.5), (2.0, 719.5, 121.25, 67.5)]
=====


问:
Specifying provisioning profiles when export OS X app
I have an OS X app that contains a Network Extension bundle (VPN), which requires extended "Network Extension" entitlements that I specify when I create a provisioning profile (your team has to be authorized by Apple for this option to show up in their dev portal). So I have to manage provisioning profiles manually, rather than let Xcode handle everything, because the auto-generated "Managed by Xcode" profiles don't contain the extended entitlements. I use the PROVISIONING_PROFILE setting in my project to specify the correct ones.

When exporting my app from an xcarchive...

xcodebuild -exportArchive -archivePath path_to_xcarchive -exportPath $OUTDIR -exportOptionsPlist exportOptions.plist

xcodebuild embeds in my .app the auto-generated profiles rather than the profiles specified in my build settings. I've looked at the .app inside the .xcarchive and it does contain the correct profiles, but xcodebuild swaps them out on export. I see the same issue when exporting via Xcode's UI - I'm shown the profiles that will be used for the export, and they're the wrong ones, with no way to change them.

Anyone know how to prevent the use of managed profiles, or force Xcode to use specific ones?

答:
Xcode 9 -exportOptionsPlist now supports specifying certs and profiles via signingStyle, a signingCertificate, and provisioningProfiles options.</p>

```<code><key>signingStyle</key>
<string>manual</string>
<key>provisioningProfiles</key>
<dict>
    <key>com.your.bundleid</key>
    <string>Name of provisioning profile for app</string>
    <key>com.your.bundleid.extension</key>
    <string>Name of provisioning profile for extension</string>
</dict>
<key>signingCertificate</key>
<string>iOS Distribution</string>
</code>```

Body:
Xcode 9 -exportOptionsPlist now supports specifying certs and profiles via signingStyle, a signingCertificate, and provisioningProfiles options.

<key>signingStyle</key>
<string>manual</string>
<key>provisioningProfiles</key>
<dict>
    <key>com.your.bundleid</key>
    <string>Name of provisioning profile for app</string>
    <key>com.your.bundleid.extension</key>
    <string>Name of provisioning profile for extension</string>
</dict>
<key>signingCertificate</key>
<string>iOS Distribution</string>


问:
Wildfly 10.1 on Red Hat blocking web requests
Using Spring and Wildfly, I have noticed that my rest services can only handle one request at a time. I have tried a few different configurations to attempt to allow multiple requests run asynchronously from the same client machine. I am assuming that I missed a configuration in the Wildfly io subsystem, but my Google searching is not proving fruitful.

At first I thought it was a browser issue as I was using Chrome, IE, and Firefox. I then created a multithreaded java client to send multiple requests and still experienced the issue. I have created a multithreaded Perl script to send multiple requests, again same issue... the rest service will only process one request at a time and the rest are queued.

From my testing, it would appear the softwares are sending the requests as appropriate. I have used WireShark and see all the requests leaving the software and attempting to hit the servers.

I have tried eliminating factors such as load balancers and Apache from the mix further emphasizing the point that it must be Wildfly. In my local testing, I point directly at Wildfly and see the same behavior.

Without introducing any kind of additional frameworks for Rest or XML processing, I would like to call the same service simultaneously across X number of requests.

For reference, the entirety of the network architecture is
client -> (SSL) BigIP LB -> (SSL) Apache -> (AJP/SSL) Wildfly

I have updated the Wildfly io subsystem to increase the number of worker threads and increased the task-max-threads:

```<code>{
    "outcome" => "success",
    "result" => {
        "buffer-pool" => {"default" => {
            "buffer-size" => undefined,
            "buffers-per-slice" => undefined,
            "direct-buffers" => undefined
        }},
        "worker" => {"default" => {
            "io-threads" => 50,
            "stack-size" => 0L,
            "task-keepalive" => 60,
            "task-max-threads" => 300
        }}
    }
}
</code>```

Can anyone suggest if the issue is a Wildfly configuration issue, or is this a Java servlets issue, perhaps even a Spring issue?

Thank you.

答: This was an issue with my logging, I see the transactions processing simultaneously. After further analysis, all is working as designed. </p>

Body:
Using Spring and Wildfly, I have noticed that my rest services can only handle one request at a time. I have tried a few different configurations to attempt to allow multiple requests run asynchronously from the same client machine. I am assuming that I missed a configuration in the Wildfly io subsystem, but my Google searching is not proving fruitful.

At first I thought it was a browser issue as I was using Chrome, IE, and Firefox. I then created a multithreaded java client to send multiple requests and still experienced the issue. I have created a multithreaded Perl script to send multiple requests, again same issue... the rest service will only process one request at a time and the rest are queued.

From my testing, it would appear the softwares are sending the requests as appropriate. I have used WireShark and see all the requests leaving the software and attempting to hit the servers.

I have tried eliminating factors such as load balancers and Apache from the mix further emphasizing the point that it must be Wildfly. In my local testing, I point directly at Wildfly and see the same behavior.

Without introducing any kind of additional frameworks for Rest or XML processing, I would like to call the same service simultaneously across X number of requests.

For reference, the entirety of the network architecture is
client -> (SSL) BigIP LB -> (SSL) Apache -> (AJP/SSL) Wildfly

I have updated the Wildfly io subsystem to increase the number of worker threads and increased the task-max-threads:

{
    "outcome" => "success",
    "result" => {
        "buffer-pool" => {"default" => {
            "buffer-size" => undefined,
            "buffers-per-slice" => undefined,
            "direct-buffers" => undefined
        }},
        "worker" => {"default" => {
            "io-threads" => 50,
            "stack-size" => 0L,
            "task-keepalive" => 60,
            "task-max-threads" => 300
        }}
    }
}

Can anyone suggest if the issue is a Wildfly configuration issue, or is this a Java servlets issue, perhaps even a Spring issue?

Thank you.


问:
I am trying to build a website that has a file manager on it. Is there any way to pull file paths and files from Google Drive?
I would also like to pull from Dropbox, Box, and iCloud Drive. If there is no way, I will try to work around it but I was just wondering. I would like to be able to see the whole drive (all files and folders accessible). Thanks.</p>

答:
To display all the files including folders, use Files.list. If you want to specify which type of file you want to show, check Search Files.

To know more about working with folders and filepaths check Work with Folders


问:
Running Macro on Close of Table
I did not see any questions of this sort, so I thought I'd ask. I want users to update a table where they add their name to handling an issue. On the close of the table (or workbook), I'd like a macro to run to change the status of the issue with assignees to "In Process".

So, for example,

```<code>1b235d Jose "In Process"
1dhjfj      "New"
</code>```

答:
One approach would be to 'wrap' your table in a form.  Then you can respond to the Close event and do whatever logic you need.

```<code>Private Sub Form_Close()
   'put your code here to change the status
End Sub
</code>```

How would you do this?  Here are some steps to get you started:

Create a form and set the Default View to Datasheet

Set the Record Source to your table

Create the Event as shown above

Title: Running Macro on Close of Table

Body:
I did not see any questions of this sort, so I thought I'd ask. I want users to update a table where they add their name to handling an issue. On the close of the table (or workbook), I'd like a macro to run to change the status of the issue with assignees to "In Process".

So, for example,

1b235d Jose "In Process"
1dhjfj      "New"

Body:
One approach would be to 'wrap' your table in a form.  Then you can respond to the Close event and do whatever logic you need.

Private Sub Form_Close()
   'put your code here to change the status
End Sub

How would you do this?  Here are some steps to get you started:

Create a form and set the Default View to Datasheet

Set the Record Source to your table

Create the Event as shown above


问:
How do I use the bitwise operator XOR in Lua?
How can I implement bitwise operators in Lua language?

Specifically, I need a XOR operator/method.

答:
This is very simple. use NAND logic.
https://en.wikipedia.org/wiki/NAND_logic

```<code>function xor(a,b)
    return not( not( a and not( a and b ) ) and not( b and not( a and b ) ) )
end
</code>```

if you also need 1,0 inputs insert the following to the function

```<code>    a = a==1 or a == true   -- to accept nil, 1, 0, true or false
    b = b==1 or b == true   -- to accept nil, 1, 0, true or false
</code>```

Hope this helps someone.

ContentLicense: CC BY-SA 4.0

Body:
This is very simple. use NAND logic.
https://en.wikipedia.org/wiki/NAND_logic

function xor(a,b)
    return not( not( a and not( a and b ) ) and not( b and not( a and b ) ) )
end

if you also need 1,0 inputs insert the following to the function

    a = a==1 or a == true   -- to accept nil, 1, 0, true or false
    b = b==1 or b == true   -- to accept nil, 1, 0, true or false

Hope this helps someone.


问:
Woocommerce redirect to checkout page
I am trying to redirect to the checkout page after i check the quantity of total number of item in the cart. Given the condition if product is equal to 6 it should try to redirect to the checkout page.
I tried the below code but cant get it running or need some curl.</p>

```<code>function redirectcheck($url){
$tots = WC()->cart->cart_contents_count();

if($tots > 2){
header("Location: http://somepage.php",
 true, 301);
 exit();
}
}
</code>```

答:
Maybe it can be a good start...</p>

```<code>function check_quantity( $total, $cart ) {
    if( $cart->cart_contents_count = 6 ) {
            $url = get_permalink( get_option( 'woocommerce_checkout_page_id' ) );
    }
    return $url;
}
add_filter( 'woocommerce_calculated_total', 'check_quantity', 10, 2 );
</code>```

Title: Woocommerce redirect to checkout page

Body:
I am trying to redirect to the checkout page after i check the quantity of total number of item in the cart. Given the condition if product is equal to 6 it should try to redirect to the checkout page.
I tried the below code but cant get it running or need some curl.

function redirectcheck($url){
$tots = WC()->cart->cart_contents_count();

if($tots > 2){
header("Location: http://somepage.php",
 true, 301);
 exit();
}
}

Body:
Maybe it can be a good start...

function check_quantity( $total, $cart ) {
    if( $cart->cart_contents_count = 6 ) {
            $url = get_permalink( get_option( 'woocommerce_checkout_page_id' ) );
    }
    return $url;
}
add_filter( 'woocommerce_calculated_total', 'check_quantity', 10, 2 );


问:
JAXB element name based on object property
I have to create object model for following XMLs:

XML sample 1:

```<code><InvoiceAdd>
  <TxnDate>2009-01-21</TxnDate>
  <RefNumber>1</RefNumber>
  <InvoiceLineAdd>
  </InvoiceLineAdd>
</InvoiceAdd>
</code>```

XML Sample 2:

```<code><SalesOrderAdd>
  <TxnDate>2009-01-21</TxnDate>
  <RefNumber>1</RefNumber>
  <SalesOrderLineAdd>
  </SalesOrderLineAdd>
</SalesOrderAdd>
</code>```

The XML output will be based on a single string parameter or enum. String txnType = "Invoice"; (or "SalesOrder");

I would use single class TransactionAdd:

```<code>@XmlRootElement
public class TransactionAdd {
  public String txnDate;
  public String refNumber;

  private String txnType;
  ...

  public List<LineAdd> lines;
}
</code>```

instead of using subclasses or anything else. The code which creates the TransactionAdd instance is the same for both types of transaction it only differs on the type.

This XML is used by a rather known product called QuickBooks and is consumed by QuickBooks web service - so I can't change the XML, but I want to make it easy to be able to set element name based on property (txnType).

I would consider something like a method to determine target element name:

```<code>@XmlRootElement
public class TransactionAdd {
  public String txnDate;
  public String refNumber;

  private String txnType;
  ...

  public List<LineAdd> lines;

  public String getElementName() {
     return txnType + "Add";
  }
}
</code>```

Different transactions will be created using following code:

```<code>t = new TransactionAdd();
t.txnDate = "2010-12-15";
t.refNumber = "123";
t.txnType = "Invoice";
</code>```

The goal is to serialize t object with the top-level element name based on txnType. E.g.:

```<code><InvoiceAdd>
   <TxnDate>2009-01-21</TxnDate>
   <RefNumber>1</RefNumber>
</InvoiceAdd>
</code>```

In case of t.txnType = "SalesOrder" the result should be

```<code><SalesOrderAdd>
   <TxnDate>2009-01-21</TxnDate>
   <RefNumber>1</RefNumber>
</SalesOrderAdd>
</code>```

At the moment I see only one workaround with subclasses InvoiceAdd and SalesOrderAdd and using @XmlElementRef annotation to have a name based on class name. But it will need to instantiate different classes based on transaction type and also will need to have two other different classes InvoiceLineAdd and SalesOrderLineAdd which looks rather ugly.

Please suggest me any solution to handle this. I would consider something simple.

答:
You could use an XmlAdapter for this.  Based on the String value of the txnType property you would have the XmlAdapter marshal an instance of an Object corresponding to InvoiceLineAdd or SalesOrderLineAdd.

This is how it would look:

TransactionAdd

On the txnType property we will use a combination of @XmlJavaTypeAdapter and @XmlElementRef:

```<code>import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class TransactionAdd {

    private String txnType;

    @XmlJavaTypeAdapter(MyAdapter.class)
    @XmlElementRef
    public String getTxnType() {
        return txnType;
    }

    public void setTxnType(String txnType) {
        this.txnType = txnType;
    }

}
</code>```

The adapted objects will look like:

AbstractAdd

```<code>import javax.xml.bind.annotation.XmlSeeAlso;

@XmlSeeAlso({InvoiceAdd.class, SalesOrderAdd.class})
public class AbstractAdd {

}
</code>```

InvoiceAdd

```<code>import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class InvoiceAdd extends AbstractAdd {

}
</code>```

SalesOrderAdd

```<code>import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class SalesOrderAdd extends AbstractAdd {

}
</code>```

The XmlAdapter to convert between the String and the adapted objects will look like:

```<code>import javax.xml.bind.annotation.adapters.XmlAdapter;

public class MyAdapter extends XmlAdapter<AbstractAdd, String> {

    @Override
    public String unmarshal(AbstractAdd v) throws Exception {
        if(v instanceof SalesOrderAdd) {
            return "salesOrderAdd";
        }
        return "invoiceAdd";
    }

    @Override
    public AbstractAdd marshal(String v) throws Exception {
        if("salesOrderAdd".equals(v)) {
            return new SalesOrderAdd();
        }
        return new InvoiceAdd();
    }

}
</code>```

The following demo code can be used:

```<code>import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(TransactionAdd.class);

        File xml = new File("input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        TransactionAdd ta = (TransactionAdd) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(ta, System.out);
    }

}
</code>```

To produce/consume the following XML:

```<code><transactionAdd>
    <salesOrderAdd/>
</transactionAdd>
</code>```

For more information see:

http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html

Body:
I have to create object model for following XMLs:

XML sample 1:

<InvoiceAdd>
  <TxnDate>2009-01-21</TxnDate>
  <RefNumber>1</RefNumber>
  <InvoiceLineAdd>
  </InvoiceLineAdd>
</InvoiceAdd>

XML Sample 2:

<SalesOrderAdd>
  <TxnDate>2009-01-21</TxnDate>
  <RefNumber>1</RefNumber>
  <SalesOrderLineAdd>
  </SalesOrderLineAdd>
</SalesOrderAdd>

The XML output will be based on a single string parameter or enum. String txnType = "Invoice"; (or "SalesOrder");

I would use single class TransactionAdd:

@XmlRootElement
public class TransactionAdd {
  public String txnDate;
  public String refNumber;

  private String txnType;
  ...

  public List<LineAdd> lines;
}

instead of using subclasses or anything else. The code which creates the TransactionAdd instance is the same for both types of transaction it only differs on the type.

This XML is used by a rather known product called QuickBooks and is consumed by QuickBooks web service - so I can't change the XML, but I want to make it easy to be able to set element name based on property (txnType).

I would consider something like a method to determine target element name:

@XmlRootElement
public class TransactionAdd {
  public String txnDate;
  public String refNumber;

  private String txnType;
  ...

  public List<LineAdd> lines;

  public String getElementName() {
     return txnType + "Add";
  }
}

Different transactions will be created using following code:

t = new TransactionAdd();
t.txnDate = "2010-12-15";
t.refNumber = "123";
t.txnType = "Invoice";

The goal is to serialize t object with the top-level element name based on txnType. E.g.:

<InvoiceAdd>
   <TxnDate>2009-01-21</TxnDate>
   <RefNumber>1</RefNumber>
</InvoiceAdd>

In case of t.txnType = "SalesOrder" the result should be

<SalesOrderAdd>
   <TxnDate>2009-01-21</TxnDate>
   <RefNumber>1</RefNumber>
</SalesOrderAdd>

At the moment I see only one workaround with subclasses InvoiceAdd and SalesOrderAdd and using @XmlElementRef annotation to have a name based on class name. But it will need to instantiate different classes based on transaction type and also will need to have two other different classes InvoiceLineAdd and SalesOrderLineAdd which looks rather ugly.

Please suggest me any solution to handle this. I would consider something simple.

Body:
You could use an XmlAdapter for this.  Based on the String value of the txnType property you would have the XmlAdapter marshal an instance of an Object corresponding to InvoiceLineAdd or SalesOrderLineAdd.

This is how it would look:

TransactionAdd

On the txnType property we will use a combination of @XmlJavaTypeAdapter and @XmlElementRef:

import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class TransactionAdd {

    private String txnType;

    @XmlJavaTypeAdapter(MyAdapter.class)
    @XmlElementRef
    public String getTxnType() {
        return txnType;
    }

    public void setTxnType(String txnType) {
        this.txnType = txnType;
    }

}

The adapted objects will look like:

AbstractAdd

import javax.xml.bind.annotation.XmlSeeAlso;

@XmlSeeAlso({InvoiceAdd.class, SalesOrderAdd.class})
public class AbstractAdd {

}

InvoiceAdd

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class InvoiceAdd extends AbstractAdd {

}

SalesOrderAdd

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class SalesOrderAdd extends AbstractAdd {

}

The XmlAdapter to convert between the String and the adapted objects will look like:

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class MyAdapter extends XmlAdapter<AbstractAdd, String> {

    @Override
    public String unmarshal(AbstractAdd v) throws Exception {
        if(v instanceof SalesOrderAdd) {
            return "salesOrderAdd";
        }
        return "invoiceAdd";
    }

    @Override
    public AbstractAdd marshal(String v) throws Exception {
        if("salesOrderAdd".equals(v)) {
            return new SalesOrderAdd();
        }
        return new InvoiceAdd();
    }

}

The following demo code can be used:

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(TransactionAdd.class);

        File xml = new File("input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        TransactionAdd ta = (TransactionAdd) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(ta, System.out);
    }

}

To produce/consume the following XML:

<transactionAdd>
    <salesOrderAdd/>
</transactionAdd>

For more information see:

http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html


问:
How to Update JWT token from response header in ember-simple-auth session
I am using ember-simple-auth & ember-simple-auth-token to maintain session on Ember. I do not want to use the refresh-token approach, instead would like to receive a new jwt token in the response header from every service request.

how can i keep my session alive by updating the jwt token in the session every time I receive a response from the server?

答:
This can be done, but will require extending ember-simple-auth and ember-simple-auth-token. It's not exactly recommended to use your approach, the access token plus refresh token is definitely the preferred method. It also scales better since your resource servers don't need the ability to authenticate, just to authorize and validate tokens. It also adds a bit of overhead to generate a new token for every single request. While I don't recommend this course, here's how it can be done:

As you've discovered, you cannot update the session directly, but if you dive into the source code you will discover that ember-simple-auth uses an event to update it. However, this event will only work if you override/customize an authenticator. Likely ember-simple-auth-token's authenticators/jwt.js. If you look at their authenticator, you can see an example of how to update the session.

So, I would recommend creating your own custom JWT token authenticator that extends ember-simple-auth-token's. It will likely add a method to update the session or perhaps better to handle the raw request headers that contain a new access token.

After that's complete, you have a choice. You can either override your own adapter and call that function yourself from there, or perhaps the better choice would be to override ember-simple-auth's data-adapter-mixin mixin.

If you override ember-simple-auth data-adapter-mixin, this seems to be the best starting point: handleResponse. If you override that function, you should have access to your raw API response from which you can call your update session function.

As you can see though, this is not a trivial change. It's definitely going against the grain of what these libraries were originally designed to do, but if you put in a good bit of work, it should be possible.

Updates for OP's comment

I actually implemented both of those requirements before: "1) to have session timeout after a pre configured idle time. 2) allow certain set of users to proxy in and switch the context of login user on the fly". It turns out that it's actually pretty easy to accomplish with a refresh token model.

To support #1, the refresh token expiration should be set to the length of the idle time before logout. e.g. if the refresh token is set to expire in 30 minutes and the access token expires in 5 minutes. The client will automatically fetch new access tokens (and optionally a refresh token) every ~5 minutes, based on leeway. However, if the user leaves the page for over 30 minutes, the refresh token will be expired and they will need to re-authenticate.

For #2, unfortunately, it does take a bit of overriding of ember-simple-auth-token to work, but it's relatively easy and something I have already implemented. Basically you create create an custom authenticator that has an addition function to exchange and access token for a new one with updated context/state. See my implementation below:

ember-simple-auth-token overridden authenticator:

```<code> /**
    Provides a public method to call to exchange an access token for an
    updated access token with updated data encoded in it. This method
    essentially asks the backend to update an access token with different
    values. This is, at the moment, is only used to switch the company root
    attribute in the token (AKA switch companies for admins).

    @param {string} token - The valid access token
    @param {object} [headers] - An optional object which can add additional
    headers to the request

    @param {object} additionalData - An object which contains the data which should be updated on the token. It should look  something like this:
    ```
    {
        company_root_id: '<UUID of a valid company root>'
    }
    ```
    @return {Promise} A promise which is the request. It will either resolve
    with the updated session data or reject with the error.
  */
 exchangeAccessToken(token, headers, additionalData) {
     const data = this.makeRefreshData(token);
     Ember.merge(data, additionalData);

     return new Ember.RSVP.Promise((resolve, reject) => {
         this.makeRequest(this.serverTokenRefreshEndpoint, data, headers).then(response => {
             Ember.run(() => {
                 try {
                     const sessionData = this.handleAuthResponse(response);

                     this.trigger('sessionDataUpdated', sessionData);
                     resolve(sessionData);
                 } catch(error) {
                     reject(error);
                 }
             });
         }, (xhr, status, error) => {
             Ember.Logger.warn(`Access token could not be refreshed - server responded with ${error}.`);
             reject();
         });
     });
 }
</code>```

Action to trigger the token exchange:

```<code> switchCompany(companyId) {
     let session = this.get('_session.session');

     if(!this.get('isAdministrator')) {
         throw new Error('Logged in user is not an administrator, they cannot switch companies.');
     }

     let token = session.get('authenticated.access_token');
     let appInstance = Ember.getOwner(this);
     let authorizerName = session.get('authenticator');
     let authorizer = appInstance.lookup(authorizerName);
     if(!authorizer) {
         throw new Error(`Authorizer (${authorizerName}) does not exist`);
     }
     if(typeof authorizer.exchangeAccessToken !== 'function') {
         throw new Error(`Authorizer (${authorizerName}) does not have an \`exchangeAccessToken\` method.`);
     }
     return authorizer.exchangeAccessToken(token, null, {
         company_root_id: companyId
     });
 }
</code>```

The backend would obviously need to be extended to accept additional parameters on the refresh token endpoint which allows the user to switch roles, if authorized.

Body:
This can be done, but will require extending ember-simple-auth and ember-simple-auth-token. It's not exactly recommended to use your approach, the access token plus refresh token is definitely the preferred method. It also scales better since your resource servers don't need the ability to authenticate, just to authorize and validate tokens. It also adds a bit of overhead to generate a new token for every single request. While I don't recommend this course, here's how it can be done:

As you've discovered, you cannot update the session directly, but if you dive into the source code you will discover that ember-simple-auth uses an event to update it. However, this event will only work if you override/customize an authenticator. Likely ember-simple-auth-token's authenticators/jwt.js. If you look at their authenticator, you can see an example of how to update the session.

So, I would recommend creating your own custom JWT token authenticator that extends ember-simple-auth-token's. It will likely add a method to update the session or perhaps better to handle the raw request headers that contain a new access token.

After that's complete, you have a choice. You can either override your own adapter and call that function yourself from there, or perhaps the better choice would be to override ember-simple-auth's data-adapter-mixin mixin.

If you override ember-simple-auth data-adapter-mixin, this seems to be the best starting point: handleResponse. If you override that function, you should have access to your raw API response from which you can call your update session function.

As you can see though, this is not a trivial change. It's definitely going against the grain of what these libraries were originally designed to do, but if you put in a good bit of work, it should be possible.

Updates for OP's comment

I actually implemented both of those requirements before: "1) to have session timeout after a pre configured idle time. 2) allow certain set of users to proxy in and switch the context of login user on the fly". It turns out that it's actually pretty easy to accomplish with a refresh token model.

To support #1, the refresh token expiration should be set to the length of the idle time before logout. e.g. if the refresh token is set to expire in 30 minutes and the access token expires in 5 minutes. The client will automatically fetch new access tokens (and optionally a refresh token) every ~5 minutes, based on leeway. However, if the user leaves the page for over 30 minutes, the refresh token will be expired and they will need to re-authenticate.

For #2, unfortunately, it does take a bit of overriding of ember-simple-auth-token to work, but it's relatively easy and something I have already implemented. Basically you create create an custom authenticator that has an addition function to exchange and access token for a new one with updated context/state. See my implementation below:

ember-simple-auth-token overridden authenticator:

 /**
    Provides a public method to call to exchange an access token for an
    updated access token with updated data encoded in it. This method
    essentially asks the backend to update an access token with different
    values. This is, at the moment, is only used to switch the company root
    attribute in the token (AKA switch companies for admins).

    @param {string} token - The valid access token
    @param {object} [headers] - An optional object which can add additional
    headers to the request

    @param {object} additionalData - An object which contains the data which should be updated on the token. It should look  something like this:
    ```
    {
        company_root_id: '<UUID of a valid company root>'
    }
    ```
    @return {Promise} A promise which is the request. It will either resolve
    with the updated session data or reject with the error.
  */
 exchangeAccessToken(token, headers, additionalData) {
     const data = this.makeRefreshData(token);
     Ember.merge(data, additionalData);

     return new Ember.RSVP.Promise((resolve, reject) => {
         this.makeRequest(this.serverTokenRefreshEndpoint, data, headers).then(response => {
             Ember.run(() => {
                 try {
                     const sessionData = this.handleAuthResponse(response);

                     this.trigger('sessionDataUpdated', sessionData);
                     resolve(sessionData);
                 } catch(error) {
                     reject(error);
                 }
             });
         }, (xhr, status, error) => {
             Ember.Logger.warn(`Access token could not be refreshed - server responded with ${error}.`);
             reject();
         });
     });
 }

Action to trigger the token exchange:

 switchCompany(companyId) {
     let session = this.get('_session.session');

     if(!this.get('isAdministrator')) {
         throw new Error('Logged in user is not an administrator, they cannot switch companies.');
     }

     let token = session.get('authenticated.access_token');
     let appInstance = Ember.getOwner(this);
     let authorizerName = session.get('authenticator');
     let authorizer = appInstance.lookup(authorizerName);
     if(!authorizer) {
         throw new Error(`Authorizer (${authorizerName}) does not exist`);
     }
     if(typeof authorizer.exchangeAccessToken !== 'function') {
         throw new Error(`Authorizer (${authorizerName}) does not have an \`exchangeAccessToken\` method.`);
     }
     return authorizer.exchangeAccessToken(token, null, {
         company_root_id: companyId
     });
 }

The backend would obviously need to be extended to accept additional parameters on the refresh token endpoint which allows the user to switch roles, if authorized.


问:
How to set domain for a local html file?
I have a local html file. I can open it with a browser at file:///a.html

I want to see it at http://example.com/a.html.

I am not going to run a server.

I tried to edit the hosts file, add a line:

file:///  example.com

it dosn't work.
how to do it?

答:
You cannot access the "http" protocol any other way. Without a web-server of some sort, your only option is to use the file protocol.

With regard to the hosts file, it is used to define mappings from IP addresses to a host name. As such, trying to define a URL will not work.


问:
(click) event throwing Error in angular2, typescript
(click) event in typescript causes error given below.

```<code>EXCEPTION: Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: Cannot read property 'appendChild' of undefined
angular2.dev.js:23877 ORIGINAL STACKTRACE:
angular2.dev.js:23877 TypeError: Cannot read property 'appendChild' of undefined
at Playlist.addVideo (playlist.component.ts:53)
at ChangeDetector_Playlist_0.handleEventInternal (viewFactory_Playlist:62)
at ChangeDetector_Playlist_0.AbstractChangeDetector.handleEvent (angular2.dev.js:9568)
at AppView.triggerEventHandlers (angular2.dev.js:10246)
at eval (viewFactory_Playlist:361)
at angular2.dev.js:14068
at angular2.dev.js:13496
at ZoneDelegate.invoke (angular2-polyfills.js:332)
at Object.onInvoke (angular2.dev.js:2111)
at ZoneDelegate.invoke (angular2-polyfills.js:331)
ERROR CONTEXT:
BrowserDomAdapter.logError @ angular2.dev.js:23877
ExceptionHandler.call @ angular2.dev.js:1333
(anonymous) @ angular2.dev.js:12763
schedulerFn @ angular2.dev.js:13167
SafeSubscriber.__tryOrUnsub @ Rx.js:10775
SafeSubscriber.next @ Rx.js:10730
Subscriber._next @ Rx.js:10690
Subscriber.next @ Rx.js:10667
Subject._finalNext @ Rx.js:11191
Subject._next @ Rx.js:11183
Subject.next @ Rx.js:11142
EventEmitter.emit @ angular2.dev.js:13148
onError @ angular2.dev.js:13566
onHandleError @ angular2.dev.js:2128
ZoneDelegate.handleError @ angular2-polyfills.js:336
Zone.runGuarded @ angular2-polyfills.js:244
NgZoneImpl.runInner @ angular2.dev.js:2140
NgZone.run @ angular2.dev.js:13649
outsideHandler @ angular2.dev.js:13495
ZoneDelegate.invokeTask @ angular2-polyfills.js:365
Zone.runTask @ angular2-polyfills.js:263
ZoneTask.invoke @ angular2-polyfills.js:431
angular2.dev.js:23877 EventEvaluationErrorContext {element: button.btn.btn-success, componentElement: playlist, context: Playlist, locals: Object, injector: Injector}
</code>```

I want that when I click on add Video button a dynamically generated new editable row will append to table, whose value I want to pass to another class.

```<code>inputTitle: HTMLInputElement;
inputLink: HTMLInputElement;
td: HTMLTableCellElement;
tdTitle: HTMLTableCellElement;
tdLink: HTMLTableCellElement;
tr: HTMLTableRowElement;
tBody: HTMLElement = document.getElementsByTagName("tbody")[0];

addVideo()
{
    this.inputTitle = document.createElement("input");
    this.inputLink = document.createElement("input");
    this.td = document.createElement("td");
    this.tdTitle = document.createElement("td");
    this.tdLink = document.createElement("td");
    this.tr = document.createElement("tr");

    this.inputTitle.setAttribute("type", "text");
    this.div.appendChild(this.inputTitle);
    this.inputLink.setAttribute("type", "text");

    this.tdTitle.appendChild(this.inputTitle);
    this.tdLink.appendChild(this.inputLink);

    this.tr.appendChild(this.td);
    this.tr.appendChild(this.tdTitle);
    this.tr.appendChild(this.tdLink);

    this.tBody.appendChild(this.tr);
}
</code>```

And also the above method works fine. But this addVideo() cause problem.

Click here to see what I want. If anyone got other suggestion kindly tell me. Thanks.

Here's playlist.component.ts file

```<code>import {Component, Input} from "angular2/core";
import {Video} from "./video";
@Component(
{
selector: "playlist",
templateUrl: "app/ts/playlist.component.html",
inputs: ["videos"]
})
export class Playlist
{
iframe: HTMLIFrameElement;
div: HTMLDivElement = document.getElementsByTagName("div")[0];
inputTitle: HTMLInputElement;
inputLink: HTMLInputElement;
td: HTMLTableCellElement;
tdTitle: HTMLTableCellElement;
tdLink: HTMLTableCellElement;
tr: HTMLTableRowElement;
tBody: HTMLElement = document.getElementsByTagName("tbody")[0];
onSelect(vid: Video)
{
    if(this.iframe)
        this.div.removeChild(this.iframe);
    this.iframe = document.createElement("iframe");
    this.iframe.setAttribute("width", "800");
    this.iframe.setAttribute("height", "500");
    this.iframe.setAttribute("src", "https://www.youtube.com/embed/" + vid.link);
    this.div.appendChild(this.iframe);
}
addVideo()
{
    this.inputTitle = document.createElement("input");
    this.inputLink = document.createElement("input");
    this.td = document.createElement("td");
    this.tdTitle = document.createElement("td");
    this.tdLink = document.createElement("td");
    this.tr = document.createElement("tr");

    this.inputTitle.setAttribute("type", "text");
    this.div.appendChild(this.inputTitle);
    this.inputLink.setAttribute("type", "text");

    this.tdTitle.appendChild(this.inputTitle);
    this.tdLink.appendChild(this.inputLink);

    this.tr.appendChild(this.td);
    this.tr.appendChild(this.tdTitle);
    this.tr.appendChild(this.tdLink);

    this.tBody.appendChild(this.tr);
}
</code>```

}

Here's playlist.component.html file

```<code><div>
<div style = "position: relative;" class = "btn-group">
    <button class = "btn btn-success" (click) = "addVideo()">Add Video</button>
    <button class = "btn">Edit <span class = "glyphicon glyphicon-pencil"></span></button>
</div>
<div class = "table-responsive">
    <table class = "table table-striped table-hover" border = "0">
        <thead>
            <tr style ="font-weight: bold">
                <td>ID</td>
                <td>Title</td>
                <td>Video Code</td>
            </tr>
        </thead>
        <tbody id = "VideoEntries">
            <tr *ngFor = "#v of videos" (click) = "onSelect(v)">
                <td>{{v.id}}</td>
                <td>{{v.title}}</td>
                <td>{{v.link}}</td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

Here's app.component.ts file

```<code>import {Component} from "angular2/core";
import {Video} from "./video";
import {Config} from "./config.service";
import {Playlist} from "./playlist.component";
@Component(
{
selector: "my-app",
templateUrl: "app/ts/app.component.html",
directives: [Playlist]
})

export class AppComponent
{
Heading = Config.HEADING;
videos: Array<Video>;
constructor()
{
    this.videos =
    [
        new Video(1, "Angular1", "hXfigUyeHaY"),
        new Video(2, "Angular2", "MyqcsnbH820")
    ]
}
</code>```

}

答:
you are trying to use undefined variable.

you have declared those parameters:

```<code>inputTitle: HTMLInputElement;
inputLink: HTMLInputElement;
td: HTMLTableCellElement;
tdTitle: HTMLTableCellElement;
tdLink: HTMLTableCellElement;
tr: HTMLTableRowElement;
tBody: HTMLElement = document.getElementsByTagName("tbody")[0];
</code>```

you need also to declare your 'div'.

```<code>this.div.appendChild(this.inputTitle);
</code>```

but note you do not have any 'div' defined.

Body:
(click) event in typescript causes error given below.

EXCEPTION: Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: Cannot read property 'appendChild' of undefined
angular2.dev.js:23877 ORIGINAL STACKTRACE:
angular2.dev.js:23877 TypeError: Cannot read property 'appendChild' of undefined
at Playlist.addVideo (playlist.component.ts:53)
at ChangeDetector_Playlist_0.handleEventInternal (viewFactory_Playlist:62)
at ChangeDetector_Playlist_0.AbstractChangeDetector.handleEvent (angular2.dev.js:9568)
at AppView.triggerEventHandlers (angular2.dev.js:10246)
at eval (viewFactory_Playlist:361)
at angular2.dev.js:14068
at angular2.dev.js:13496
at ZoneDelegate.invoke (angular2-polyfills.js:332)
at Object.onInvoke (angular2.dev.js:2111)
at ZoneDelegate.invoke (angular2-polyfills.js:331)
ERROR CONTEXT:
BrowserDomAdapter.logError @ angular2.dev.js:23877
ExceptionHandler.call @ angular2.dev.js:1333
(anonymous) @ angular2.dev.js:12763
schedulerFn @ angular2.dev.js:13167
SafeSubscriber.__tryOrUnsub @ Rx.js:10775
SafeSubscriber.next @ Rx.js:10730
Subscriber._next @ Rx.js:10690
Subscriber.next @ Rx.js:10667
Subject._finalNext @ Rx.js:11191
Subject._next @ Rx.js:11183
Subject.next @ Rx.js:11142
EventEmitter.emit @ angular2.dev.js:13148
onError @ angular2.dev.js:13566
onHandleError @ angular2.dev.js:2128
ZoneDelegate.handleError @ angular2-polyfills.js:336
Zone.runGuarded @ angular2-polyfills.js:244
NgZoneImpl.runInner @ angular2.dev.js:2140
NgZone.run @ angular2.dev.js:13649
outsideHandler @ angular2.dev.js:13495
ZoneDelegate.invokeTask @ angular2-polyfills.js:365
Zone.runTask @ angular2-polyfills.js:263
ZoneTask.invoke @ angular2-polyfills.js:431
angular2.dev.js:23877 EventEvaluationErrorContext {element: button.btn.btn-success, componentElement: playlist, context: Playlist, locals: Object, injector: Injector}

I want that when I click on add Video button a dynamically generated new editable row will append to table, whose value I want to pass to another class.

inputTitle: HTMLInputElement;
inputLink: HTMLInputElement;
td: HTMLTableCellElement;
tdTitle: HTMLTableCellElement;
tdLink: HTMLTableCellElement;
tr: HTMLTableRowElement;
tBody: HTMLElement = document.getElementsByTagName("tbody")[0];

addVideo()
{
    this.inputTitle = document.createElement("input");
    this.inputLink = document.createElement("input");
    this.td = document.createElement("td");
    this.tdTitle = document.createElement("td");
    this.tdLink = document.createElement("td");
    this.tr = document.createElement("tr");

    this.inputTitle.setAttribute("type", "text");
    this.div.appendChild(this.inputTitle);
    this.inputLink.setAttribute("type", "text");

    this.tdTitle.appendChild(this.inputTitle);
    this.tdLink.appendChild(this.inputLink);

    this.tr.appendChild(this.td);
    this.tr.appendChild(this.tdTitle);
    this.tr.appendChild(this.tdLink);

    this.tBody.appendChild(this.tr);
}

And also the above method works fine. But this addVideo() cause problem.

Click here to see what I want. If anyone got other suggestion kindly tell me. Thanks.

Here's playlist.component.ts file

import {Component, Input} from "angular2/core";
import {Video} from "./video";
@Component(
{
selector: "playlist",
templateUrl: "app/ts/playlist.component.html",
inputs: ["videos"]
})
export class Playlist
{
iframe: HTMLIFrameElement;
div: HTMLDivElement = document.getElementsByTagName("div")[0];
inputTitle: HTMLInputElement;
inputLink: HTMLInputElement;
td: HTMLTableCellElement;
tdTitle: HTMLTableCellElement;
tdLink: HTMLTableCellElement;
tr: HTMLTableRowElement;
tBody: HTMLElement = document.getElementsByTagName("tbody")[0];
onSelect(vid: Video)
{
    if(this.iframe)
        this.div.removeChild(this.iframe);
    this.iframe = document.createElement("iframe");
    this.iframe.setAttribute("width", "800");
    this.iframe.setAttribute("height", "500");
    this.iframe.setAttribute("src", "https://www.youtube.com/embed/" + vid.link);
    this.div.appendChild(this.iframe);
}
addVideo()
{
    this.inputTitle = document.createElement("input");
    this.inputLink = document.createElement("input");
    this.td = document.createElement("td");
    this.tdTitle = document.createElement("td");
    this.tdLink = document.createElement("td");
    this.tr = document.createElement("tr");

    this.inputTitle.setAttribute("type", "text");
    this.div.appendChild(this.inputTitle);
    this.inputLink.setAttribute("type", "text");

    this.tdTitle.appendChild(this.inputTitle);
    this.tdLink.appendChild(this.inputLink);

    this.tr.appendChild(this.td);
    this.tr.appendChild(this.tdTitle);
    this.tr.appendChild(this.tdLink);

    this.tBody.appendChild(this.tr);
}

}

Here's playlist.component.html file

    <button class = "btn btn-success" (click) = "addVideo()">Add Video</button>
    <button class = "btn">Edit </button>

                ID
                Title
                Video Code

                {{v.id}}
                {{v.title}}
                {{v.link}}

Here's app.component.ts file

import {Component} from "angular2/core";
import {Video} from "./video";
import {Config} from "./config.service";
import {Playlist} from "./playlist.component";
@Component(
{
selector: "my-app",
templateUrl: "app/ts/app.component.html",
directives: [Playlist]
})

export class AppComponent
{
Heading = Config.HEADING;
videos: Array<Video>;
constructor()
{
    this.videos =
    [
        new Video(1, "Angular1", "hXfigUyeHaY"),
        new Video(2, "Angular2", "MyqcsnbH820")
    ]
}

}

Body:
you are trying to use undefined variable.

you have declared those parameters:

inputTitle: HTMLInputElement;
inputLink: HTMLInputElement;
td: HTMLTableCellElement;
tdTitle: HTMLTableCellElement;
tdLink: HTMLTableCellElement;
tr: HTMLTableRowElement;
tBody: HTMLElement = document.getElementsByTagName("tbody")[0];

you need also to declare your 'div'.

this.div.appendChild(this.inputTitle);

but note you do not have any 'div' defined.


问:
DBVisualizer background colour
I have DB Visualizer 9.5.7 on Windows 10 64-bit, using Java 1.8.
I am not able to change the 'Normal' Background Color from the default White to another colour such as Grey (for example).
I am using the Free version.
Should this work?
Thanks!</p>

答:
no this will not work, you need the premium version to do this.

https://www.dbvis.com/features/tour/connection-management/

under "Borders and Colors"

Title: DBVisualizer background colour