问:
Java : My system for decrypt text doesn't work
I've a system for encrypt texts, but i've tried to create a system for decrypt texts, and it doesn't work. The system is :

initialize encrypted text to byte[]

initialize decrypted text with the encrypted text

He just return the encrypted text, but not the decrypted text. Have you an idea for debug this?

Thanks in advance.

byte[] getEncrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
{
    String key = "Bép12345Taruy'(";

    Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");

    cipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] encrypted = cipher.doFinal(text.getBytes());

    return encrypted;
}

String getDecrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
{
    String key = "Bép12345Taruy'(";

    Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");

    cipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] encrypted = cipher.doFinal(text.getBytes());

    cipher.init(Cipher.DECRYPT_MODE, aesKey);
    String decrypted = new String(cipher.doFinal(encrypted));

    return decrypted;
}
```

答:
I use jasypt to encrypt passwords. The method is very simple.

```<code>BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword("some_Password_Maybe_generated_At_random");
...
String myEncryptedText = textEncryptor.encrypt(myText);
...
String plainText = textEncryptor.decrypt(myEncryptedText);
</code>```

Normally I do not put the password in the source but i save it in a file in the user home dir.

The encryption is as strong as the user home dir is safe and private.

This method is good because it returns a string which can be put in a config file.

As I said before, it is not very safe, it will protect the encrypted text as long as the encryption password is safe.

Body:
I use jasypt to encrypt passwords. The method is very simple.

BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword("some_Password_Maybe_generated_At_random");
...
String myEncryptedText = textEncryptor.encrypt(myText);
...
String plainText = textEncryptor.decrypt(myEncryptedText);

Normally I do not put the password in the source but i save it in a file in the user home dir.

The encryption is as strong as the user home dir is safe and private.

This method is good because it returns a string which can be put in a config file.

As I said before, it is not very safe, it will protect the encrypted text as long as the encryption password is safe.


来源: stackexchange

问:
How in Java script to find the necessary number from three numbers?
I have four numbers 15 30 70 140. and "x", which can get any number, how to say if ()? that if x is equal to 15 30 70 140, then true, if not, then false.</p>

```<code>const x =....;
if(x===?){....}else{....}
</code>```

答:
You could use a switch and case statement:

// Get user input
var input = +prompt()

switch (input) {
  case 15:
  case 30:
  case 70:
  case 140:
    console.log(true)
    break;
  default:
    console.log(false)
    break;
}```

ContentLicense: CC BY-SA 4.0

Body:
I have four numbers 15 30 70 140. and "x", which can get any number, how to say if ()? that if x is equal to 15 30 70 140, then true, if not, then false.

const x =....;
if(x===?){....}else{....}


问:
How are variables transmitted in Prolog?
I have a function square which I would like to display a matrix like this:

```<code>XXX (newline)
XXX (newline)
XXX
</code>```

My result is false after first line is printed. Why? How are variables transmitted in Prolog and how are the lines executed(order)?

```<code>line(Rez,X) :- Rez>=1 , write(X) , line(Rez-1,X).

square(N,X) :- Rez = N,line(Rez,X),nl,N>1,square(N-1,X).
</code>```

答: There are several issue with your code. Notably, you're writing recursive predicate definitions without base cases. Another issue is that Prolog is not a functional language. When you write e.g. line(Rez-1,X), Prolog is not going to evaluate Rez-1 as an arithmetic expression. For Prolog, Rez-1 is just a '-'/2 compound term, i.e. a term with name - and two arguments. You will need to write something like NextRez is Rez-1, line(NextRez,X). The is/2 standard built-in predicate evaluates its second argument (as an arithmetic expression) and unifies the resulting with the first argument.

Body:
I have a function square which I would like to display a matrix like this:

XXX (newline)
XXX (newline)
XXX

My result is false after first line is printed. Why? How are variables transmitted in Prolog and how are the lines executed(order)?

line(Rez,X) :- Rez>=1 , write(X) , line(Rez-1,X).

square(N,X) :- Rez = N,line(Rez,X),nl,N>1,square(N-1,X).


问:
Regex remove first section and optional last section
I need to use a regular expression to match ci- which will always be there, but then match the optional -l, -s, -r, so then I can extract the middle part, but as you can see some of the below examples have got dashes separating other words, which I don't want to remove.

```<code>ci-star-l
ci-pound-sign
ci-pound-sign-r
</code>```

The above would become:

```<code>star
pound-sign
pound-sign
</code>```

This is my attempt, however it is wrong:

```<code>(ci-).*(-.)
</code>```

答:
I suggest replacing the matches of

```<code>^ci-|-[lsr]$
</code>```

with an empty string. Note the regex replace method/function must support multiple replacements.

See the regex demo.

Details

^ci- - ci- at the start

| - or

-[lsr]$ - - and l / s / r at the end of the string.

If you want to use your initial approach you may consider

```<code>^ci-(.*?)(?:-[lsr])?$
</code>```

See this regex demo. Here, (.*?) grabs any 0+ chars but as few as possible into Group 1 and (?:-[lsr])?$ matches an optional -l, -r, -s at the end of the string. The *? non-greedy quantifier and the $ anchor are crucial for this regex to work. Replacement must be done with the backreference to Group 1 (usually, $1 or \1).

Body:
I need to use a regular expression to match ci- which will always be there, but then match the optional -l, -s, -r, so then I can extract the middle part, but as you can see some of the below examples have got dashes separating other words, which I don't want to remove.

ci-star-l
ci-pound-sign
ci-pound-sign-r

The above would become:

star
pound-sign
pound-sign

This is my attempt, however it is wrong:

(ci-).*(-.)

Body:
I suggest replacing the matches of

^ci-|-[lsr]$

with an empty string. Note the regex replace method/function must support multiple replacements.

See the regex demo.

Details

^ci- - ci- at the start

| - or

-[lsr]$ - - and l / s / r at the end of the string.

If you want to use your initial approach you may consider

^ci-(.*?)(?:-[lsr])?$

See this regex demo. Here, (.*?) grabs any 0+ chars but as few as possible into Group 1 and (?:-[lsr])?$ matches an optional -l, -r, -s at the end of the string. The *? non-greedy quantifier and the $ anchor are crucial for this regex to work. Replacement must be done with the backreference to Group 1 (usually, $1 or \1).


问:
Laravel not sending email on my server but sends on localhost
Laravel is not send email on my server but sending on localhost. Below is my code

```<code>Mail::to($email)->send(new SendConfirmation($firstname, $phone));

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class sendConfirmation extends Mailable
{
    use Queueable, SerializesModels;
    private $userFirstname;
    private $userKey;

    public function __construct($userFirstname, $userKey)
    {
        $this->userFirstname = $userFirstname;
        $this->userKey = $userKey;
    }

    public function build()
    {
        return $this->from("kenny@gmail.com",'XYZ')
        ->subject("Registration Successful")
        ->with('userFirstname', $this->userFirstname)
        ->with('userKey', $this->userKey)
        ->view('email.confirm-account');
    }
}

view
<div>
Dear {{ $userFirstname }}, Thanks for signing up. Please click the
link below to verify your account.
</div>
</code>```

Expected output

Dear John, Thanks for signing up. Please click the link below to verify your account.

答:
My config/mail.php

return [

```<code>/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
|            "sparkpost", "log", "array"
|
*/

'driver' => env('MAIL_DRIVER', 'smtp'),

/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/

'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/

'port' => env('MAIL_PORT', 587),

/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/

'from' => [
    'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
    'name' => env('MAIL_FROM_NAME', 'Example'),
],

/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/

'encryption' => env('MAIL_ENCRYPTION', 'tls'),

/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/

'username' => env('MAIL_USERNAME'),

'password' => env('MAIL_PASSWORD'),

/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/

'sendmail' => '/usr/sbin/sendmail -bs',

/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/

'markdown' => [
    'theme' => 'default',

    'paths' => [
        resource_path('views/vendor/mail'),
    ],
],

/*
|--------------------------------------------------------------------------
| Log Channel
|--------------------------------------------------------------------------
|
| If you are using the "log" driver, you may specify the logging channel
| if you prefer to keep mail messages separate from other log entries
| for simpler reading. Otherwise, the default channel will be used.
|
*/

'log_channel' => env('MAIL_LOG_CHANNEL'),
</code>```

];

Body:
Laravel is not send email on my server but sending on localhost. Below is my code

Mail::to($email)->send(new SendConfirmation($firstname, $phone));

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class sendConfirmation extends Mailable
{
    use Queueable, SerializesModels;
    private $userFirstname;
    private $userKey;

    public function __construct($userFirstname, $userKey)
    {
        $this->userFirstname = $userFirstname;
        $this->userKey = $userKey;
    }

    public function build()
    {
        return $this->from("kenny@gmail.com",'XYZ')
        ->subject("Registration Successful")
        ->with('userFirstname', $this->userFirstname)
        ->with('userKey', $this->userKey)
        ->view('email.confirm-account');
    }
}

view

Dear {{ $userFirstname }}, Thanks for signing up. Please click the
link below to verify your account.

Expected output

Dear John, Thanks for signing up. Please click the link below to verify your account.

Body:
My config/mail.php

return [

/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
|            "sparkpost", "log", "array"
|
*/

'driver' => env('MAIL_DRIVER', 'smtp'),

/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/

'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/

'port' => env('MAIL_PORT', 587),

/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/

'from' => [
    'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
    'name' => env('MAIL_FROM_NAME', 'Example'),
],

/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/

'encryption' => env('MAIL_ENCRYPTION', 'tls'),

/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/

'username' => env('MAIL_USERNAME'),

'password' => env('MAIL_PASSWORD'),

/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/

'sendmail' => '/usr/sbin/sendmail -bs',

/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/

'markdown' => [
    'theme' => 'default',

    'paths' => [
        resource_path('views/vendor/mail'),
    ],
],

/*
|--------------------------------------------------------------------------
| Log Channel
|--------------------------------------------------------------------------
|
| If you are using the "log" driver, you may specify the logging channel
| if you prefer to keep mail messages separate from other log entries
| for simpler reading. Otherwise, the default channel will be used.
|
*/

'log_channel' => env('MAIL_LOG_CHANNEL'),

];


问:
Simulate many datasets in tidyr
I want to end up with a tidy data structure like the one below:

```<code>N    | r     | data     | stat
---------------------------------
10   | 0.2   | <tibble> | 0.5
20   | 0.3   | <tibble> | 0.86
...
</code>```

data is generated from the parameters in the first columns and stat is computed on data. If I have the first two columns, how do I add tibbles of datasets?

As a minimal example, here is a function to create two correlated columns:

```<code>correlated_data = function(N, r) {
  MASS::mvrnorm(N, mu=c(0, 4), Sigma=matrix(c(1, r, r, 1), ncol=2))
}
</code>```

Running this for all combinations of N and r, I start by doing

```<code># Make parameter combinations
expand.grid(N=c(10,20,30), r=c(0, 0.1, 0.3)) %>%
  group_by(N, r) %>%
  expand(set=1:100) %>%  # create 100 of each combination

  # HERE! How to add a N x 2 tibble to each row?
  rowwise() %>%
  mutate(data=correlate_data( N, r))

  # Compute summary stats on each (for illustration only; not tested)
  mutate(
     stats = map(data, ~cor.test(.x[, 1], .x[, 2])),  # Correlation on each
     tidy_stats = map(stats, tidy))  # using broom package
</code>```

I do have more parameters (N, r, distribution) and I will be computing more summaries. If alternative workflows are better, I welcome that as well.

答:
This does it for two variables:

map2(N, r, correlated_data)
```

<p>For more variables, use</p>

<pre class="lang-r prettyprint-override"><code>pmap(list(N, r), correlated_data)
</code>```

So the full procedure in the original question becomes:

expand.grid(N=c(10, 20, 30), r=c(0, 0.1, 0.3)) %>%
  group_by(N, r) %>%
  expand(set=1:200) %>%  # create 100 of each combination

  # HERE! How to add a N x 2 tibble to each row?
  mutate(
    data = map2(N, r, correlated_data),
    stats = map(data, ~cor.test(.[, 1], .[,2])),
    tidy_stats = map(stats, tidy)
  ) %>%  # using broom package

  unnest(tidy_stats)
```

Title: Simulate many datasets in tidyr

Body:
I want to end up with a tidy data structure like the one below:

N    | r     | data     | stat
---------------------------------
10   | 0.2   | <tibble> | 0.5
20   | 0.3   | <tibble> | 0.86
...

data is generated from the parameters in the first columns and stat is computed on data. If I have the first two columns, how do I add tibbles of datasets?

As a minimal example, here is a function to create two correlated columns:

correlated_data = function(N, r) {
  MASS::mvrnorm(N, mu=c(0, 4), Sigma=matrix(c(1, r, r, 1), ncol=2))
}

Running this for all combinations of N and r, I start by doing

# Make parameter combinations
expand.grid(N=c(10,20,30), r=c(0, 0.1, 0.3)) %>%
  group_by(N, r) %>%
  expand(set=1:100) %>%  # create 100 of each combination

  # HERE! How to add a N x 2 tibble to each row?
  rowwise() %>%
  mutate(data=correlate_data( N, r))

  # Compute summary stats on each (for illustration only; not tested)
  mutate(
     stats = map(data, ~cor.test(.x[, 1], .x[, 2])),  # Correlation on each
     tidy_stats = map(stats, tidy))  # using broom package

I do have more parameters (N, r, distribution) and I will be computing more summaries. If alternative workflows are better, I welcome that as well.

Body:
This does it for two variables:

map2(N, r, correlated_data)

For more variables, use

pmap(list(N, r), correlated_data)

So the full procedure in the original question becomes:

expand.grid(N=c(10, 20, 30), r=c(0, 0.1, 0.3)) %>%
  group_by(N, r) %>%
  expand(set=1:200) %>%  # create 100 of each combination

  # HERE! How to add a N x 2 tibble to each row?
  mutate(
    data = map2(N, r, correlated_data),
    stats = map(data, ~cor.test(.[, 1], .[,2])),
    tidy_stats = map(stats, tidy)
  ) %>%  # using broom package

  unnest(tidy_stats)


问:
Remove duplicate elements by class with JQuery
I want to delete duplicate span.film-date elements using the secondary class. For example I only want to keep the first span with the classes of "film-date Wed29May" and the first span with the classes of "film-date Thur30May".

```<code><div class="film-time-list">
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">5.20pm</a>
<span class="film-date Thur30May">Thur 30 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Thur30May">Thur 30 May</span>
<a class="film-tickets" href="#">5.20pm</a>
</div>
</code>```

I thought this would be straight forward enough but as the class that is output dynamically could be any date this snippet won't work which was my initial thought.

```<code>$('.couldBeAnyClass').not(':first').remove();
</code>```

Any pointers would be great!

My output would be:

```<code>Wed 29 May 2.30pm 5.20pm
Thur 30 May 2.30pm 5.20pm
</code>```

答:
To achieve what you require you could loop through the span elements checking if the text is the same as the previous element, and if so, remove it:

var prev;
$('.film-time-list span').each(function() {
  var text = $(this).text().trim();
  if (prev == text)
    $(this).remove();

  prev = text;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="film-time-list">
  <span class="film-date Wed29May">Wed 29 May</span>
  2.30pm
  <span class="film-date Wed29May">Wed 29 May</span>
  5.20pm
  <span class="film-date Thur30May">Thur 30 May</span>
  2.30pm
  <span class="film-date Thur30May">Thur 30 May</span>
  5.20pm
</div></code>```

Body:
I want to delete duplicate span.film-date elements using the secondary class. For example I only want to keep the first span with the classes of "film-date Wed29May" and the first span with the classes of "film-date Thur30May".

Wed 29 May
2.30pm
Wed 29 May
5.20pm
Thur 30 May
2.30pm
Thur 30 May
5.20pm

I thought this would be straight forward enough but as the class that is output dynamically could be any date this snippet won't work which was my initial thought.

$('.couldBeAnyClass').not(':first').remove();

Any pointers would be great!

My output would be:

Wed 29 May 2.30pm 5.20pm
Thur 30 May 2.30pm 5.20pm

Body:
To achieve what you require you could loop through the span elements checking if the text is the same as the previous element, and if so, remove it:

var prev;
$('.film-time-list span').each(function() {
  var text = $(this).text().trim();
  if (prev == text)
    $(this).remove();

  prev = text;
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="film-time-list">
  <span class="film-date Wed29May">Wed 29 May</span>
  <a class="film-tickets" href="#">2.30pm</a>
  <span class="film-date Wed29May">Wed 29 May</span>
  <a class="film-tickets" href="#">5.20pm</a>
  <span class="film-date Thur30May">Thur 30 May</span>
  <a class="film-tickets" href="#">2.30pm</a>
  <span class="film-date Thur30May">Thur 30 May</span>
  <a class="film-tickets" href="#">5.20pm</a>
</div>


答:
(...) is a matching group, from which you can get the context later.

$ is the end of the string.

Therefore, I would use ci-(.*?)(?:-\w)?$ and your result is then the first matching group.

Title: Regex remove first section and optional last section


问:
Matplotlib to plotly offline
I have some matplotlib graphs that need to be viewed offline in a browser, I was using MPLD3 to render them before, but given the need to view the plots without an internet connection, I'm considering using plotly. Is there a way to view matplotlib plotly graphs offline?</p>

答:
```<code>import plotly.tools as tls
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot

x = np.random.random(100) ### toy data
y = np.random.random(100) ### toy data

## matplotlib fig
fig, axes = plt.subplots(2,1, figsize = (10,6))
axes[0].plot(x, label = 'x')
axes[1].scatter(x,y)

## convert and plot in plotly
plotly_fig = tls.mpl_to_plotly(fig) ## convert
iplot(plotly_fig)
</code>```

Title: Matplotlib to plotly offline


问:
error: libxml/parser.h: No such file or directory
I'm attempting to use XML (Chapter 10 in Professional iPhone and iPad Database Application Programming), and I've run into a bit of trouble.

Under Header Search Paths in Build Settings I have this path:

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/usr/include/libxml2/

That's all fine and well, but then:

```<code>#import <libxml/parser.h>
#import <libxml/tree.h>
error: libxml/parser.h: No such file or directory
</code>```

If I flip the imports:

```<code>#import <libxml/tree.h>
#import <libxml/parser.h>
error: libxml/tree.h: No such file or directory
</code>```

Weird.

For now I have this:

```<code>#import <libxml/catalog.h> // Dirty hack
#import <libxml/parser.h>
#import <libxml/tree.h>
error: libxml/catalog.h: No such file or directory
</code>```

But that's no good for a production app.

答: Try changing your header search path to ${SDK_DIR}/usr/include/libxml2.

ContentLicense: CC BY-SA 3.0

Body:
I'm attempting to use XML (Chapter 10 in Professional iPhone and iPad Database Application Programming), and I've run into a bit of trouble.

Under Header Search Paths in Build Settings I have this path:

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/usr/include/libxml2/

That's all fine and well, but then:

#import <libxml/parser.h>
#import <libxml/tree.h>
error: libxml/parser.h: No such file or directory

If I flip the imports:

#import <libxml/tree.h>
#import <libxml/parser.h>
error: libxml/tree.h: No such file or directory

Weird.

For now I have this:

#import <libxml/catalog.h> // Dirty hack
#import <libxml/parser.h>
#import <libxml/tree.h>
error: libxml/catalog.h: No such file or directory

But that's no good for a production app.


问:
Problems with routing in Angular
I am going to ask a question that I have seen many times and I have searched a lot about it, it seems that everyone has the same problem, but nobody is solved the same.

I'm doing a hello world with Angular and I'm on the routing side. I have generated the file as it says the docs of the framework, but when I start opening the application in the navigator it jumps to the following error:

```<code> Error: StaticInjectorError(AppModule)[RouterOutlet -> ChildrenOutletContexts]:
 StaticInjectorError(Platform: core)[RouterOutlet -> ChildrenOutletContexts]:
 NullInjectorError: No provider for ChildrenOutletContexts!
</code>```

I have followed the tutorial since the beginning several times, I have looked for solutions and nothing. To see if someone can help me, I show you my code, just as it is right now:

This is the app-routing.module.ts file:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HelloWorldComponent } from './hello-world/hello-
world.component';

const routes: Routes = [
  {
    path: '',
    component: HelloWorldComponent,
  },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }
</code>```

this is the app.modules file:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { MatButtonModule, MatDialogModule, MatTableModule,MatFormFieldModule, MatInputModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { UserCardComponent, DialogExampleComponent} from './usercard/user-card.component';
import { BrowserAnimationsModule } from '@angular/platformbrowser/animations';
import { HelloWorldComponent } from './hello-world/helloworld.component';

@NgModule({
  declarations: [
  AppComponent,
  UserCardComponent,
  DialogExampleComponent,
  HelloWorldComponent
],
entryComponents:[DialogExampleComponent],
imports: [
BrowserModule,
MatTableModule,
MatButtonModule,
MatDialogModule,
BrowserAnimationsModule,
MatFormFieldModule,
MatInputModule,
FormsModule,
RouterModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

And I do not think it's necessary, but this is the app.component.html file:

<router-outlet></router-outlet>

Can anyone see the problem?? Maybe I'm blind...

答:
Since you've already set up routing in your AppRoutingModule and you've also exported the RouterModule the AppRoutingModule, that's what you should be adding to the imports array of your AppModule.

Change this:

```<code>imports: [
  ...
  RouterModule,
],
</code>```

To this:

```<code>imports: [
  ...
  AppRoutingModule,
],
</code>```

Here's a Working Sample StackBlitz for your ref.

Title: Problems with routing in Angular

Body:
I am going to ask a question that I have seen many times and I have searched a lot about it, it seems that everyone has the same problem, but nobody is solved the same.

I'm doing a hello world with Angular and I'm on the routing side. I have generated the file as it says the docs of the framework, but when I start opening the application in the navigator it jumps to the following error:

 Error: StaticInjectorError(AppModule)[RouterOutlet -> ChildrenOutletContexts]:
 StaticInjectorError(Platform: core)[RouterOutlet -> ChildrenOutletContexts]:
 NullInjectorError: No provider for ChildrenOutletContexts!

I have followed the tutorial since the beginning several times, I have looked for solutions and nothing. To see if someone can help me, I show you my code, just as it is right now:

This is the app-routing.module.ts file:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HelloWorldComponent } from './hello-world/hello-
world.component';

const routes: Routes = [
  {
    path: '',
    component: HelloWorldComponent,
  },
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }

this is the app.modules file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { MatButtonModule, MatDialogModule, MatTableModule,MatFormFieldModule, MatInputModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { UserCardComponent, DialogExampleComponent} from './usercard/user-card.component';
import { BrowserAnimationsModule } from '@angular/platformbrowser/animations';
import { HelloWorldComponent } from './hello-world/helloworld.component';

@NgModule({
  declarations: [
  AppComponent,
  UserCardComponent,
  DialogExampleComponent,
  HelloWorldComponent
],
entryComponents:[DialogExampleComponent],
imports: [
BrowserModule,
MatTableModule,
MatButtonModule,
MatDialogModule,
BrowserAnimationsModule,
MatFormFieldModule,
MatInputModule,
FormsModule,
RouterModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

And I do not think it's necessary, but this is the app.component.html file:

<router-outlet></router-outlet>

Can anyone see the problem?? Maybe I'm blind...

Body:
Since you've already set up routing in your AppRoutingModule and you've also exported the RouterModule the AppRoutingModule, that's what you should be adding to the imports array of your AppModule.

Change this:

imports: [
  ...
  RouterModule,
],

To this:

imports: [
  ...
  AppRoutingModule,
],

Here's a Working Sample StackBlitz for your ref.


问:
Check if table exists in SQL Server
I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.

Here are two possible ways of doing it. Which one is the standard/best way of doing it?

First way:

```<code>IF EXISTS (SELECT 1
           FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_TYPE='BASE TABLE'
           AND TABLE_NAME='mytablename')
   SELECT 1 AS res ELSE SELECT 0 AS res;
</code>```

Second way:

```<code>IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL
   SELECT 1 AS res ELSE SELECT 0 AS res;
</code>```

MySQL provides the simple

```<code>SHOW TABLES LIKE '%tablename%';
</code>```

statement. I am looking for something similar.

答:
Run this query to check if the table exists in the database:</p>

```<code>IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL
PRINT 'Table Exists';
</code>```

OwnerDisplayName: Vincent

Title: Check if table exists in SQL Server

Body:
I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.

Here are two possible ways of doing it. Which one is the standard/best way of doing it?

First way:

IF EXISTS (SELECT 1
           FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_TYPE='BASE TABLE'
           AND TABLE_NAME='mytablename')
   SELECT 1 AS res ELSE SELECT 0 AS res;

Second way:

IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL
   SELECT 1 AS res ELSE SELECT 0 AS res;

MySQL provides the simple

SHOW TABLES LIKE '%tablename%';

statement. I am looking for something similar.

LastEditorDisplayName: Cade Roux

Body:
Run this query to check if the table exists in the database:

IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL
PRINT 'Table Exists';


问:
How to integrate nuxeo polymer 3 elements in angular app?
I've built an Angular 6 app, and I need to include my Nuxeo Polymer 3 Elements (like this one https://github.com/nuxeo/nuxeo-elements/blob/master/core/nuxeo-search.js).

How could I have something like:

<app>
   <dom-bind>
      <template>
        <nuxeo-connection
          id="nx"
          url="http://localhost:8080/nuxeo"
          username="Administrator"
          password="Administrator"
        ></nuxeo-connection>
        <nuxeo-search auto searches="{{searches}}"></nuxeo-search>

          <template is="dom-repeat" items="{{searches}}">

                id:
                [[item.id]]

          </template>

      </template>
    </dom-bind>
</app>
```

答:
After some times, I can answer my question like explained here. In brief:

Enabling JS in angular in tsconfig.json :

```<code>{
  compilerOptions: {
    "allowJs": true
  }
}
</code>```

Enabling custom elements schema in your app module:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
...
@NgModule({
...
schemas: [CUSTOM_ELEMENTS_SCHEMA],
...
})
```
<ol start="3">
<li><code>npm install</code> your components</li>
<li>Use a <code><nuxeo-connection></code> in the index.html file before any angular digest</li>
<li>Finally - in you app.component.html use your web components</li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><nuxeo-document-suggestion
        [router]="router"
        (selected-item-changed)="select($event.detail.value)"
        placeholder="Select a document">
</nuxeo-document-suggestion>

<div *ngIf="doc">
  <nuxeo-page-provider #pp
                     auto
                     provider="advanced_document_content"
                     enrichers="thumbnail"
                     page-size="5"
                     [params]="params"
                     (current-page-changed)="onResults($event.detail.value)">
  </nuxeo-page-provider>
</div></code>```

Cherry on the cake, Nuxeo web components are available for angular but also React and Vue.js.

Body:
After some times, I can answer my question like explained here. In brief:

Enabling JS in angular in tsconfig.json :

{
  compilerOptions: {
    "allowJs": true
  }
}

Enabling custom elements schema in your app module:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
...
@NgModule({
...
schemas: [CUSTOM_ELEMENTS_SCHEMA],
...
})

npm install your components

Use a <nuxeo-connection> in the index.html file before any angular digest

Finally - in you app.component.html use your web components

<nuxeo-document-suggestion
        [router]="router"
        (selected-item-changed)="select($event.detail.value)"
        placeholder="Select a document">
</nuxeo-document-suggestion>

<div *ngIf="doc">
  <nuxeo-page-provider #pp
                     auto
                     provider="advanced_document_content"
                     enrichers="thumbnail"
                     page-size="5"
                     [params]="params"
                     (current-page-changed)="onResults($event.detail.value)">
  </nuxeo-page-provider>
</div>

Cherry on the cake, Nuxeo web components are available for angular but also React and Vue.js.


问:
How to detect Microsoft Chromium Edge (chredge , edgium) in Javascript
'Edge 75' will be (is?) the first Chromium Based Edge browser. How can I check if this browser is Edge on Chrome ?

(What I really want to know is if the browser fully supports data-uri's - https://caniuse.com/#feat=datauri - so feature detection would even be better. If you know a way to do that, I can change the question)

答:
You could use the window.navigator userAgent to check whether the browser is Microsoft Chromium Edge or Chrome.

Code as below:

```

The Chrome browser userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
like gecko) chrome/74.0.3729.169 safari/537.36

The Edge browser userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
like gecko) chrome/64.0.3282.140 safari/537.36 edge/18.17763

The Microsoft Chromium Edge Dev userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
like gecko) chrome/76.0.3800.0 safari/537.36 edg/76.0.167.1

The Microsoft Chromium Edge Canary userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
like gecko) chrome/76.0.3800.0 safari/537.36 edg/76.0.167.1

As we can see that Microsoft Chromium Edge userAgent contains the "edg" keyword, we could use it to detect whether the browser is Chromium Edge browser or Chrome browser.

Body:
You could use the window.navigator userAgent to check whether the browser is Microsoft Chromium Edge or Chrome.

Code as below:

<script>
    var browser = (function (agent) {
        switch (true) {
            case agent.indexOf("edge") > -1: return "edge";
            case agent.indexOf("edg/") > -1: return "chromium based edge (dev or canary)"; // Match also / to avoid matching for the older Edge
            case agent.indexOf("opr") > -1 && !!window.opr: return "opera";
            case agent.indexOf("chrome") > -1 && !!window.chrome: return "chrome";
            case agent.indexOf("trident") > -1: return "ie";
            case agent.indexOf("firefox") > -1: return "firefox";
            case agent.indexOf("safari") > -1: return "safari";
            default: return "other";
        }
    })(window.navigator.userAgent.toLowerCase());
    document.body.innerHTML = window.navigator.userAgent.toLowerCase() + "<br>" + browser;
</script>

The Chrome browser userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
like gecko) chrome/74.0.3729.169 safari/537.36

The Edge browser userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
like gecko) chrome/64.0.3282.140 safari/537.36 edge/18.17763

The Microsoft Chromium Edge Dev userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
like gecko) chrome/76.0.3800.0 safari/537.36 edg/76.0.167.1

The Microsoft Chromium Edge Canary userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
like gecko) chrome/76.0.3800.0 safari/537.36 edg/76.0.167.1

As we can see that Microsoft Chromium Edge userAgent contains the "edg" keyword, we could use it to detect whether the browser is Chromium Edge browser or Chrome browser.


问:
How to properly unnest two arrays
I have two arrays: foo_array text[], bar_array text[] inside a function.
Each of them contain strings that will be split into array elements using 'string_to_array' function and type casted to bigint.

I want to return those arrays in a table(out1 bigint, out2 bigint).

For example, foo_array and bar_array each contain 10 elements and I expect the function to return 10 rows with those elements.
I am only able to produce output of 20 elements and don't really understand it.

```<code>CREATE OR REPLACE FUNCTION ___two_unnests()
RETURNS TABLE(out1 bigint, out2 bigint) AS $$
DECLARE
    foo_array text[];
    bar_array text[];

    foo1 text := array_to_string(ARRAY[1, 2, 3, 4, 5], ',');
    foo2 text := array_to_string(ARRAY[11, 22, 33, 44, 55], ',');

    bar1 text := array_to_string(ARRAY[6, 7, 8, 9, 10], ',');
    bar2 text := array_to_string(ARRAY[66, 77, 88, 99, 1010], ',');
BEGIN
    foo_array := (SELECT foo_array || foo1 || foo2);
    bar_array := (SELECT bar_array || bar1 || bar2);

    RAISE NOTICE 'foo_array: %', foo_array;
    RAISE NOTICE 'bar_array: %', bar_array;

    RETURN QUERY
    SELECT
      unnest(string_to_array(foo, ',')::bigint[]),
      unnest(string_to_array(bar, ',')::bigint[])
    FROM
      unnest(foo_array) as foo,
      unnest(bar_array) as bar;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM ___two_unnests();
</code>```

Actual output of the function.

```<code>out1 |  out2
-----+-----
1    |  6
2    |  7
3    |  8
4    |  9
5    |  10
1    |  11
2    |  22
3    |  33
4    |  44
5    |  55
11   |  6
22   |  7
33   |  8
44   |  9
55   |  10
11   |  11
22   |  22
33   |  33
44   |  44
55   |  55
</code>```

Output I want:

```<code>out1 |  out2
-----+-----
1    |  6
2    |  7
3    |  8
4    |  9
5    |  10
11   |  66
22   |  77
33   |  88
44   |  99
55   |  1010
</code>```

SOLUTION Using sticky-bit's suggestion

```<code>CREATE OR REPLACE FUNCTION ___two_unnests() RETURNS TABLE(out1 bigint, out2 bigint) AS $$
DECLARE
    foo_array text[];
    bar_array text[];

    foo_slice text;
    foo_text text := '';
    foo_firstiter boolean := true;

    bar_slice text;
    bar_text text := '';
    bar_firstiter boolean := true;

    out1_array bigint[];
    out2_array bigint[];

    foo1 text := array_to_string(ARRAY[1, 2, 3, 4, 5], ',');
    foo2 text := array_to_string(ARRAY[11, 22, 33, 44, 55], ',');

    bar1 text := array_to_string(ARRAY[6, 7, 8, 9, 10], ',');
    bar2 text := array_to_string(ARRAY[66, 77, 88, 99, 1010], ',');
BEGIN
    foo_array := (SELECT foo_array || foo1 || foo2);
    bar_array := (SELECT bar_array || bar1 || bar2);

    RAISE NOTICE 'foo_array: %', foo_array;
    RAISE NOTICE 'bar_array: %', bar_array;

    FOREACH foo_slice IN ARRAY foo_array LOOP
        IF foo_firstiter = true THEN
            foo_text := foo_text || foo_slice;
            foo_firstiter := false;
        ELSE
            foo_text := foo_text || ',' || foo_slice;
        END IF;
    END LOOP;

    FOREACH bar_slice IN ARRAY bar_array LOOP
        IF bar_firstiter = true THEN
            bar_text := bar_text || bar_slice;
            bar_firstiter := false;
        ELSE
            bar_text := bar_text || ',' || bar_slice;
        END IF;
    END LOOP;

    out1_array := (SELECT string_to_array(foo_text, ',')::bigint[]);
    out2_array := (SELECT string_to_array(bar_text, ',')::bigint[]);

    RAISE NOTICE 'out1_array: %', out1_array;
    RAISE NOTICE 'out2_array: %', out2_array;

    RETURN QUERY SELECT un1.val::bigint,
            un2.val::bigint
       FROM unnest(out1_array) WITH ORDINALITY un1 (val, ord)
            FULL JOIN unnest(out2_array) WITH ORDINALITY un2 (val, ord)
                      ON un2.ord = un1.ord;

END;
$$ LANGUAGE plpgsql;

SELECT * FROM ___two_unnests();
</code>```

答:
If you have a modern PostgreSQL, you can use multicolumn unnest function

```<code>SELECT * FROM unnest(ARRAY[1, 2, 3, 4, 5] || ARRAY[11, 22, 33, 44, 55],
                     ARRAY[6, 7, 8, 9, 10] || ARRAY[66, 77, 88, 99, 1010]);

┌────────┬────────┐
│ unnest │ unnest │
╞════════╪════════╡
│      1 │      6 │
│      2 │      7 │
│      3 │      8 │
│      4 │      9 │
│      5 │     10 │
│     11 │     66 │
│     22 │     77 │
│     33 │     88 │
│     44 │     99 │
│     55 │   1010 │
└────────┴────────┘
</code>```

Don't use subselects instead a expressions

It is bad (the code is less readable and slower)

```<code>var := (SELECT a || b || c); -- don't do this!
</code>```

instead

```<code>var := a || b || c;
</code>```

Title: How to properly unnest two arrays

Body:
I have two arrays: foo_array text[], bar_array text[] inside a function.
Each of them contain strings that will be split into array elements using 'string_to_array' function and type casted to bigint.

I want to return those arrays in a table(out1 bigint, out2 bigint).

For example, foo_array and bar_array each contain 10 elements and I expect the function to return 10 rows with those elements.
I am only able to produce output of 20 elements and don't really understand it.

CREATE OR REPLACE FUNCTION ___two_unnests()
RETURNS TABLE(out1 bigint, out2 bigint) AS $$
DECLARE
    foo_array text[];
    bar_array text[];

    foo1 text := array_to_string(ARRAY[1, 2, 3, 4, 5], ',');
    foo2 text := array_to_string(ARRAY[11, 22, 33, 44, 55], ',');

    bar1 text := array_to_string(ARRAY[6, 7, 8, 9, 10], ',');
    bar2 text := array_to_string(ARRAY[66, 77, 88, 99, 1010], ',');
BEGIN
    foo_array := (SELECT foo_array || foo1 || foo2);
    bar_array := (SELECT bar_array || bar1 || bar2);

    RAISE NOTICE 'foo_array: %', foo_array;
    RAISE NOTICE 'bar_array: %', bar_array;

    RETURN QUERY
    SELECT
      unnest(string_to_array(foo, ',')::bigint[]),
      unnest(string_to_array(bar, ',')::bigint[])
    FROM
      unnest(foo_array) as foo,
      unnest(bar_array) as bar;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM ___two_unnests();

Actual output of the function.

out1 |  out2
-----+-----
1    |  6
2    |  7
3    |  8
4    |  9
5    |  10
1    |  11
2    |  22
3    |  33
4    |  44
5    |  55
11   |  6
22   |  7
33   |  8
44   |  9
55   |  10
11   |  11
22   |  22
33   |  33
44   |  44
55   |  55

Output I want:

out1 |  out2
-----+-----
1    |  6
2    |  7
3    |  8
4    |  9
5    |  10
11   |  66
22   |  77
33   |  88
44   |  99
55   |  1010

SOLUTION Using sticky-bit's suggestion

CREATE OR REPLACE FUNCTION ___two_unnests() RETURNS TABLE(out1 bigint, out2 bigint) AS $$
DECLARE
    foo_array text[];
    bar_array text[];

    foo_slice text;
    foo_text text := '';
    foo_firstiter boolean := true;

    bar_slice text;
    bar_text text := '';
    bar_firstiter boolean := true;

    out1_array bigint[];
    out2_array bigint[];

    foo1 text := array_to_string(ARRAY[1, 2, 3, 4, 5], ',');
    foo2 text := array_to_string(ARRAY[11, 22, 33, 44, 55], ',');

    bar1 text := array_to_string(ARRAY[6, 7, 8, 9, 10], ',');
    bar2 text := array_to_string(ARRAY[66, 77, 88, 99, 1010], ',');
BEGIN
    foo_array := (SELECT foo_array || foo1 || foo2);
    bar_array := (SELECT bar_array || bar1 || bar2);

    RAISE NOTICE 'foo_array: %', foo_array;
    RAISE NOTICE 'bar_array: %', bar_array;

    FOREACH foo_slice IN ARRAY foo_array LOOP
        IF foo_firstiter = true THEN
            foo_text := foo_text || foo_slice;
            foo_firstiter := false;
        ELSE
            foo_text := foo_text || ',' || foo_slice;
        END IF;
    END LOOP;

    FOREACH bar_slice IN ARRAY bar_array LOOP
        IF bar_firstiter = true THEN
            bar_text := bar_text || bar_slice;
            bar_firstiter := false;
        ELSE
            bar_text := bar_text || ',' || bar_slice;
        END IF;
    END LOOP;

    out1_array := (SELECT string_to_array(foo_text, ',')::bigint[]);
    out2_array := (SELECT string_to_array(bar_text, ',')::bigint[]);

    RAISE NOTICE 'out1_array: %', out1_array;
    RAISE NOTICE 'out2_array: %', out2_array;

    RETURN QUERY SELECT un1.val::bigint,
            un2.val::bigint
       FROM unnest(out1_array) WITH ORDINALITY un1 (val, ord)
            FULL JOIN unnest(out2_array) WITH ORDINALITY un2 (val, ord)
                      ON un2.ord = un1.ord;

END;
$$ LANGUAGE plpgsql;

SELECT * FROM ___two_unnests();

Body:
If you have a modern PostgreSQL, you can use multicolumn unnest function

SELECT * FROM unnest(ARRAY[1, 2, 3, 4, 5] || ARRAY[11, 22, 33, 44, 55],
                     ARRAY[6, 7, 8, 9, 10] || ARRAY[66, 77, 88, 99, 1010]);

┌────────┬────────┐
│ unnest │ unnest │
╞════════╪════════╡
│      1 │      6 │
│      2 │      7 │
│      3 │      8 │
│      4 │      9 │
│      5 │     10 │
│     11 │     66 │
│     22 │     77 │
│     33 │     88 │
│     44 │     99 │
│     55 │   1010 │
└────────┴────────┘

Don't use subselects instead a expressions

It is bad (the code is less readable and slower)

var := (SELECT a || b || c); -- don't do this!

instead

var := a || b || c;


问:
Unable to configure the wifi open network programmatically android?
I have written code for adding open network to wifi configured list.It adds the open network to configured lists and displays the same SSID's in Wifi Settings.but it adds the same network with same name extra but it doesn't shows any open network When i press on the second on alert shows with Security WEP the following text i observed with those same networks

1) Open network
2) remembered , not in range
But i want to add open network into my list, why this extra one is added and if i connect the same network it is trying to connect to the (2) one programmatically.Actually I changed secured network to open network for this trial.It displays with open network text and when i press on that one it obtains the address and connects succesfully manually.Why this extra one is adding how can i add the open network to my list.For reference plz see the link for image.

http://www.freeimagehosting.net/uploads/3dbccfc2bd.png

Code snippet :

```<code>    String hotSpotSsid = hotSpot.SSID;
    String hotSpotBssid = hotSpot.BSSID;
    Log.i(TAG,"in RSSI Changed Acion SSID: "+hotSpotSsid+" BSSID: "+hotSpotBssid);
    StringBuffer sBuf = new StringBuffer("\"");
    sBuf.append(hotSpotSsid+"\"");
    hotSpotSsid = sBuf.toString();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.SSID = hotSpotSsid;
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.BSSID = hotSpotBssid;
    wifiConfiguration.hiddenSSID = false;
   // wifiConfiguration.priority = 1;

    // add this to the configured networks
    int inetId = wifiManager.addNetwork(wifiConfiguration);
    Log.i(TAG,"INetId :"+inetId);
    configs = wifiManager.getConfiguredNetworks();
    Log.e(TAG,"After adding config :"+configs);
    if(inetId < 0) {
        Log.i(TAG,"Unable to add network configuration for SSID: "+hotSpotSsid);
        return;
    }else {
        message="\t Successfully added to configured Networks";
        Log.i(TAG,message);
    }
</code>```

regards,
Rajendar

答: Give SSID as wifiConfiguration.SSID = "\"".concat(SSID_NAME).concat("\"");</p>

ContentLicense: CC BY-SA 2.5

Body:
I have written code for adding open network to wifi configured list.It adds the open network to configured lists and displays the same SSID's in Wifi Settings.but it adds the same network with same name extra but it doesn't shows any open network When i press on the second on alert shows with Security WEP the following text i observed with those same networks

1) Open network
2) remembered , not in range
But i want to add open network into my list, why this extra one is added and if i connect the same network it is trying to connect to the (2) one programmatically.Actually I changed secured network to open network for this trial.It displays with open network text and when i press on that one it obtains the address and connects succesfully manually.Why this extra one is adding how can i add the open network to my list.For reference plz see the link for image.

http://www.freeimagehosting.net/uploads/3dbccfc2bd.png

Code snippet :

    String hotSpotSsid = hotSpot.SSID;
    String hotSpotBssid = hotSpot.BSSID;
    Log.i(TAG,"in RSSI Changed Acion SSID: "+hotSpotSsid+" BSSID: "+hotSpotBssid);
    StringBuffer sBuf = new StringBuffer("\"");
    sBuf.append(hotSpotSsid+"\"");
    hotSpotSsid = sBuf.toString();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.SSID = hotSpotSsid;
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.BSSID = hotSpotBssid;
    wifiConfiguration.hiddenSSID = false;
   // wifiConfiguration.priority = 1;

    // add this to the configured networks
    int inetId = wifiManager.addNetwork(wifiConfiguration);
    Log.i(TAG,"INetId :"+inetId);
    configs = wifiManager.getConfiguredNetworks();
    Log.e(TAG,"After adding config :"+configs);
    if(inetId < 0) {
        Log.i(TAG,"Unable to add network configuration for SSID: "+hotSpotSsid);
        return;
    }else {
        message="\t Successfully added to configured Networks";
        Log.i(TAG,message);
    }

regards,
Rajendar


问:
Why azure cdn returns me the old version of file with custom domain
I have a file uploaded to my azure storage, and now I have replaced it with another version of this file.
The old file size was 22 mb.
now the new version is about 10 mb.
After replace when I try to download the file with my custom domain it still downloads the old file(22 mb).
But when I try to download with it's original url(storageName.blob.core.windows.net)
I get the correct file.

I have tried to set cache-control header 1 minutes using Microsoft azure storage explorer.

```<code>max-age=1
</code>```

But it didn't help.

Why is such kind of behavior? And how to solve this problem?

答:
When you have a CDN configured with Azure Storage and you updated the file in Storage, CDN will still serve the cached old file until the TTL expires.

So you should either do a Purge or you need to configure the caching rules to get desired rules.

You can read more about Caching rules in CDN here.

Body:
I have a file uploaded to my azure storage, and now I have replaced it with another version of this file.
The old file size was 22 mb.
now the new version is about 10 mb.
After replace when I try to download the file with my custom domain it still downloads the old file(22 mb).
But when I try to download with it's original url(storageName.blob.core.windows.net)
I get the correct file.

I have tried to set cache-control header 1 minutes using Microsoft azure storage explorer.

max-age=1

But it didn't help.

Why is such kind of behavior? And how to solve this problem?


问:
How to add point on polyline somewhere between two vertexes?
The goal is to have an editable polyline with customized markers at every vertex.

As I see Map API V3 does not allows that. So I made editable polyline like this:

```<code>let polyline = new self.google.maps.Polyline({
    strokeColor: '#000000',
    strokeOpacity: 0.3,
    strokeWeight: 3,
    editable: false,
    path: path,
    map: self.map
});

polyline.binder = new MVCArrayBinder(polyline.getPath());

let markers = [];
for (let i = 0; i < path.length; i++) {
    let marker = this.getBasicMarker(path[i]);
    marker.bindTo('position', polyline.binder, i.toString());
    markers.push(marker);
}
</code>```

```<code>getBasicMarker(position){
    return new this.google.maps.Marker({
        position: position,
        map: this.map,
        icon: {
            url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
            size: new google.maps.Size(7, 7),
            anchor: new google.maps.Point(3.5, 3.5)
        },
        draggable: true,
        visible: false
    });
}
</code>```

```<code>function MVCArrayBinder(mvcArray) {
    this.array_ = mvcArray;
}

MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function (key) {
    if (!isNaN(parseInt(key))) {
        return this.array_.getAt(parseInt(key));
    } else {
        this.array_.get(key);
    }
};

MVCArrayBinder.prototype.set = function (key, val) {
    if (!isNaN(parseInt(key))) {
        this.array_.setAt(parseInt(key), val);
    } else {
        this.array_.set(key, val);
    }
};
</code>```

Final polyline now looks like this: http://sandbox.rubera.ru/img/2019-05-28_17-04-25.jpg. I can drag any existing point. The polyline updating while dragging the point.

Now I have to add new vertex somewhere between two existing.

This is where I'm stuck.

May be there is another solution how to solve the task?

答:
In case anybody face similar task here is a few modifications to my code posted abowe. That helped me finally solve the problem.

```<code>MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function (key) {
    if (!isNaN(parseInt(key))) {
        return this.array_.getAt(parseInt(key));
    } else {
        this.array_.get(key);
    }
};

MVCArrayBinder.prototype.set = function (key, val) {
    if (!isNaN(parseInt(key))) {
        this.array_.setAt(parseInt(key), val);
    } else {
        this.array_.set(key, val);
    }
};

MVCArrayBinder.prototype.insertAt = function (key, val) {
    this.array_.insertAt(key, val);
};
</code>```

```<code>google.maps.event.addListener(this.activePoly, 'click', function (e) {
    let path = $this.activePoly.getPath(),
        inserted = false;

    // find line segment
    for (let i = 0; i < path.getLength() - 1, !inserted; i++) {
        let tempPoly = new google.maps.Polyline({
            path: [path.getAt(i), path.getAt(i + 1)]
        });

        if (google.maps.geometry.poly.isLocationOnEdge(e.latLng, tempPoly, 10e-2)) {
            $this.activeRoute.binder.insertAt(i + 1, e.latLng);
            inserted = true;

            let marker = $this.getBasicMarker(e.latLng);
            marker.setVisible(true);

            // Add new marker to array
            $this.activeRoute.markers.splice(i + 1, 0, marker);

            // Have to rebind all markers
            $this.activeRoute.markers.forEach((marker, index) => {
                marker.bindTo('position', $this.activeRoute.binder, index.toString());
            });
        }
    }
});
</code>```

My activeRoute is an object with following structure:

```<code>{polyline: polyline, markers: markers, binder: polyline.binder}
</code>```

Body:
The goal is to have an editable polyline with customized markers at every vertex.

As I see Map API V3 does not allows that. So I made editable polyline like this:

let polyline = new self.google.maps.Polyline({
    strokeColor: '#000000',
    strokeOpacity: 0.3,
    strokeWeight: 3,
    editable: false,
    path: path,
    map: self.map
});

polyline.binder = new MVCArrayBinder(polyline.getPath());

let markers = [];
for (let i = 0; i < path.length; i++) {
    let marker = this.getBasicMarker(path[i]);
    marker.bindTo('position', polyline.binder, i.toString());
    markers.push(marker);
}

getBasicMarker(position){
    return new this.google.maps.Marker({
        position: position,
        map: this.map,
        icon: {
            url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
            size: new google.maps.Size(7, 7),
            anchor: new google.maps.Point(3.5, 3.5)
        },
        draggable: true,
        visible: false
    });
}

function MVCArrayBinder(mvcArray) {
    this.array_ = mvcArray;
}

MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function (key) {
    if (!isNaN(parseInt(key))) {
        return this.array_.getAt(parseInt(key));
    } else {
        this.array_.get(key);
    }
};

MVCArrayBinder.prototype.set = function (key, val) {
    if (!isNaN(parseInt(key))) {
        this.array_.setAt(parseInt(key), val);
    } else {
        this.array_.set(key, val);
    }
};

Final polyline now looks like this: http://sandbox.rubera.ru/img/2019-05-28_17-04-25.jpg. I can drag any existing point. The polyline updating while dragging the point.

Now I have to add new vertex somewhere between two existing.

This is where I'm stuck.

May be there is another solution how to solve the task?

Body:
In case anybody face similar task here is a few modifications to my code posted abowe. That helped me finally solve the problem.

MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function (key) {
    if (!isNaN(parseInt(key))) {
        return this.array_.getAt(parseInt(key));
    } else {
        this.array_.get(key);
    }
};

MVCArrayBinder.prototype.set = function (key, val) {
    if (!isNaN(parseInt(key))) {
        this.array_.setAt(parseInt(key), val);
    } else {
        this.array_.set(key, val);
    }
};

MVCArrayBinder.prototype.insertAt = function (key, val) {
    this.array_.insertAt(key, val);
};

google.maps.event.addListener(this.activePoly, 'click', function (e) {
    let path = $this.activePoly.getPath(),
        inserted = false;

    // find line segment
    for (let i = 0; i < path.getLength() - 1, !inserted; i++) {
        let tempPoly = new google.maps.Polyline({
            path: [path.getAt(i), path.getAt(i + 1)]
        });

        if (google.maps.geometry.poly.isLocationOnEdge(e.latLng, tempPoly, 10e-2)) {
            $this.activeRoute.binder.insertAt(i + 1, e.latLng);
            inserted = true;

            let marker = $this.getBasicMarker(e.latLng);
            marker.setVisible(true);

            // Add new marker to array
            $this.activeRoute.markers.splice(i + 1, 0, marker);

            // Have to rebind all markers
            $this.activeRoute.markers.forEach((marker, index) => {
                marker.bindTo('position', $this.activeRoute.binder, index.toString());
            });
        }
    }
});

My activeRoute is an object with following structure:

{polyline: polyline, markers: markers, binder: polyline.binder}


问:
Generating angular/typescript class that specifies allowed values for property
Imagine I'm making a simple model that describes (for instance) the details of a query:

```<code>export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: string;
}
</code>```

That sortDirection is much more vague than necessary.  After all, the API accepts either asc or desc, and no other string values are allowed.  Therefore it would be nice to specify that only those two values are allowed, but I'm not quite sure how I would specify such a property, and the typescript docs haven't helped.  In essence I want to do this:

```<code>export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: 'asc' | 'desc';
}
</code>```

Except of course the union operator works with types, not values.  I could conceptually try something like this:

```<code>export class asc {
   direction = 'asc';
}
export class desc {
   direction = 'desc';
}
export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: asc | desc;
}
</code>```

But even if that works the structure of my model has changed (the sort direction is now model.sortDirection.direction instead of model.sortDirection)

Is there an obvious option that I'm missing?

答:
As others have mentioned, there are a variety of ways how to go about your requirement.

First and foremost, the simplest way is to do it like you actually suggestted

```<code>export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: 'asc' | 'desc';
}
</code>```

Second is to declare a type, and use it instead. This might be beneficial for reusability

```<code>export type SortDirection = 'asc' | 'desc';

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: SortDirection;
}
</code>```

The third option is to define an Enum. In addition to reusability, using an enum makes the code more maintainable; example in the case that the value asc and desc need to change in the future, you only need to change the value of the enum (instead of all going through all the places, as is the case with type definitions).

```<code>export enum SortDirection {
    ASC = 'asc',
    DESC = 'desc'
}

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: SortDirection;
}
</code>```

Body:
Imagine I'm making a simple model that describes (for instance) the details of a query:

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: string;
}

That sortDirection is much more vague than necessary.  After all, the API accepts either asc or desc, and no other string values are allowed.  Therefore it would be nice to specify that only those two values are allowed, but I'm not quite sure how I would specify such a property, and the typescript docs haven't helped.  In essence I want to do this:

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: 'asc' | 'desc';
}

Except of course the union operator works with types, not values.  I could conceptually try something like this:

export class asc {
   direction = 'asc';
}
export class desc {
   direction = 'desc';
}
export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: asc | desc;
}

But even if that works the structure of my model has changed (the sort direction is now model.sortDirection.direction instead of model.sortDirection)

Is there an obvious option that I'm missing?

Body:
As others have mentioned, there are a variety of ways how to go about your requirement.

First and foremost, the simplest way is to do it like you actually suggestted

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: 'asc' | 'desc';
}

Second is to declare a type, and use it instead. This might be beneficial for reusability

export type SortDirection = 'asc' | 'desc';

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: SortDirection;
}

The third option is to define an Enum. In addition to reusability, using an enum makes the code more maintainable; example in the case that the value asc and desc need to change in the future, you only need to change the value of the enum (instead of all going through all the places, as is the case with type definitions).

export enum SortDirection {
    ASC = 'asc',
    DESC = 'desc'
}

export class QueryModel {
    filters: FilterModel[];
    page: number;
    pageLength: number;
    sortField: string;
    sortDirection: SortDirection;
}


问:
Divide data into bins with inf Python
I'm having a problem with qcut function in python. My upper bounds and lower bounds are -Inf and Inf, but when I apply qcut with these bounds, Python return this error "cannot convert float infinity to integer".

My friends told me that I should change the Inf into 1e100 (a very large number represents ) so qcut could use. However, another error occur: "IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices"

Example:

a1 = [-Inf, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]
a2 = [-1e100, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]

cut_range = [-Inf, 27.0, 33.0, 40.0, Inf] #For a1

cut_range = [-1e+100, 27.0, 33.0, 40.0, 1e+100] #For a2

b = pd.qcut(a, cut_range, duplicates = 'drop')
```

<p>I want to have a final result like this:</p>

<pre class="lang-py prettyprint-override"><code>b = ['[-Inf,27]','(33,40]','(33,40],'(40, Inf]','(40, Inf]','(40, Inf]']
or with 1e100:
b = ['[-1e100,27]','(33,40]','(33,40],'(40, 1e100]','(40, 1e100]','(40, 1e100]']
</code>```

And someone could help me to explained how Inf works in Python and in R. They are both Infinite but how are they behave so different.

In R I tried function with Inf and it worked:

```<code>as.character(cut(a1,cut_range, include.lowest = TRUE))
</code>```

答:
searchsorted

Even though I commented that you need pd.cut.  I personally use searchsorted.

```<code>a = np.array([-np.inf, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7])
cut = np.array([27.0, 33.0, 40.0])

labels = np.array([
    f"({x:.1f}, {y:.1f}]"
    for x, y in zip([-np.inf] + list(cut), list(cut) + [np.inf])
])

labels[cut.searchsorted(a)]

array(['(-inf, 27.0]', '(-inf, 27.0]', '(33.0, 40.0]', '(33.0, 40.0]',
       '(40.0, inf]', '(40.0, inf]', '(40.0, inf]'], dtype='<U12')
</code>```

The result is either an array of codes cut.searchsorted(a) or of labels as I've shown above.  It could be tortured into a pandas.Categorical type but then you really should just use pd.cut.

Title: Divide data into bins with inf Python

Body:
I'm having a problem with qcut function in python. My upper bounds and lower bounds are -Inf and Inf, but when I apply qcut with these bounds, Python return this error "cannot convert float infinity to integer".

My friends told me that I should change the Inf into 1e100 (a very large number represents ) so qcut could use. However, another error occur: "IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices"

Example:

a1 = [-Inf, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]
a2 = [-1e100, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7]

cut_range = [-Inf, 27.0, 33.0, 40.0, Inf] #For a1

cut_range = [-1e+100, 27.0, 33.0, 40.0, 1e+100] #For a2

b = pd.qcut(a, cut_range, duplicates = 'drop')

I want to have a final result like this:

b = ['[-Inf,27]','(33,40]','(33,40],'(40, Inf]','(40, Inf]','(40, Inf]']
or with 1e100:
b = ['[-1e100,27]','(33,40]','(33,40],'(40, 1e100]','(40, 1e100]','(40, 1e100]']

And someone could help me to explained how Inf works in Python and in R. They are both Infinite but how are they behave so different.

In R I tried function with Inf and it worked:

as.character(cut(a1,cut_range, include.lowest = TRUE))

Body:
searchsorted

Even though I commented that you need pd.cut.  I personally use searchsorted.

a = np.array([-np.inf, 26.6, 36.2, 38.7, 42.1, 47.2, 117.7])
cut = np.array([27.0, 33.0, 40.0])

labels = np.array([
    f"({x:.1f}, {y:.1f}]"
    for x, y in zip([-np.inf] + list(cut), list(cut) + [np.inf])
])

labels[cut.searchsorted(a)]

array(['(-inf, 27.0]', '(-inf, 27.0]', '(33.0, 40.0]', '(33.0, 40.0]',
       '(40.0, inf]', '(40.0, inf]', '(40.0, inf]'], dtype='<U12')

The result is either an array of codes cut.searchsorted(a) or of labels as I've shown above.  It could be tortured into a pandas.Categorical type but then you really should just use pd.cut.


问:
Most optimized way to merge figures from multiple PDFs into one PDF page?
I'm the developer of NLS GNSS SOFAMESA (https://github.com/nlsfi/nls-gnss-sofamesa) and releasing a new version of it this week. There are many updates coming. However, I haven't figured out, what is the most optimized way to merge figures from multiple pdfs into one pdf page. I have utilized reportlab and pypdf2 libraries to produce the pdfs.

First pdf file: 18 figures on separate pages. Total 18 pages.

Second pdf file: 18 figures on separate pages. Total 18 pages.

Combined pdf file: 36 figures so that the first figure from the first pdf file matches with the first figure from the second pdf file. Thus, two figures per page. Total 18 pages.

Later on there should be maximum 5 figures per page from five different pdfs. ^ the two pdf file example is just an example.

Option 1: If the "Combined pdf file" can be produced by the help of merging the existing first and second pdf files, this would be the fastest way.

Option 2: The figures are saved to a specific folder location, so I could just make a new pdf from the figure locations. Not the fastest way.

Example, in merger1 "...Combined_Measurement_Report_plain.pdf" is uncorrectly created containing the figures:

def merger1(output_path, input_paths):
    pdf_merger = PdfFileMerger()

    for path in input_paths:
        pdf_merger.merge(position = 1, fileobj = path, pages = (5, 22))

    with open(output_path, 'wb') as fileobj:
        pdf_merger.write(fileobj)

    output_path = [output_path]
    return output_path

output_filepaths = merger1('{0}{3}{1}_{2}_Combined_Measurement_Report_plain.pdf'.format(number_of_visit_at_the_reference_point_folder_path, name_of_the_reference_point_folder, number_of_visit_at_the_reference_point, os.sep), filepaths)
```

As previously described, I expect:

Combined pdf file: 36 figures so that the first figure from the first pdf file matches with the first figure from the second pdf file. Thus, two figures per page. Total 18 pages.

Later on there should be maximum 5 figures per page from five different pdfs. ^ the two pdf file example is just an example.

答:
You can use PyPDF2 or pdfrw for this sort of thing. I would actually recommend pdfrw because you can specify a rectangle within the PDF to work with. It also has support for XObjects.

There are lots of examples on Github and the author is pretty responsive to questions as well.

Since I don't have access to the files in question, I can only guess at the answer. However my guess is that you will need to put together a mapping of the coordinates for the pieces you want to extract to the PDF file paths (i.e. a dict). Then iterate over your dictionary and extract the bits you want, writing them out to a new file as you go.

Body:
I'm the developer of NLS GNSS SOFAMESA (https://github.com/nlsfi/nls-gnss-sofamesa) and releasing a new version of it this week. There are many updates coming. However, I haven't figured out, what is the most optimized way to merge figures from multiple pdfs into one pdf page. I have utilized reportlab and pypdf2 libraries to produce the pdfs.

First pdf file: 18 figures on separate pages. Total 18 pages.

Second pdf file: 18 figures on separate pages. Total 18 pages.

Combined pdf file: 36 figures so that the first figure from the first pdf file matches with the first figure from the second pdf file. Thus, two figures per page. Total 18 pages.

Later on there should be maximum 5 figures per page from five different pdfs. ^ the two pdf file example is just an example.

Option 1: If the "Combined pdf file" can be produced by the help of merging the existing first and second pdf files, this would be the fastest way.

Option 2: The figures are saved to a specific folder location, so I could just make a new pdf from the figure locations. Not the fastest way.

Example, in merger1 "...Combined_Measurement_Report_plain.pdf" is uncorrectly created containing the figures:

def merger1(output_path, input_paths):
    pdf_merger = PdfFileMerger()

    for path in input_paths:
        pdf_merger.merge(position = 1, fileobj = path, pages = (5, 22))

    with open(output_path, 'wb') as fileobj:
        pdf_merger.write(fileobj)

    output_path = [output_path]
    return output_path

output_filepaths = merger1('{0}{3}{1}_{2}_Combined_Measurement_Report_plain.pdf'.format(number_of_visit_at_the_reference_point_folder_path, name_of_the_reference_point_folder, number_of_visit_at_the_reference_point, os.sep), filepaths)

As previously described, I expect:

Combined pdf file: 36 figures so that the first figure from the first pdf file matches with the first figure from the second pdf file. Thus, two figures per page. Total 18 pages.

Later on there should be maximum 5 figures per page from five different pdfs. ^ the two pdf file example is just an example.


问:
I can't run Docker ToolBox on Windows 7
I can't start docker toolbox on windows 7.
This are few steps i did.

1) I download Docker Toolbox from official site.

2) Installed it

3)Installed virtualbox.exe from docker directory.

4) When i run QUICKSTART DOCKER TERMINAL i get this after few settings:
Looks like something went wrong in step ´Setting env´... Press any key to continue...

So i can't run it. What shall i d0?
Also i can't start start.sh

I can see docker --version from git,cmd, and created by docker in vb linux.
Also i can run hello-world from linux console from vb.
But how can i start docker?

Basically i don't understand where i need to work with docker from.

From my windows termianl or only from vb linux terminal

答:
it will be from your vb linux terminal.. everything is present inside it to run your docker.
the purpose of toolbox is to use it on the unsupported version on your machine via the virtual box.. </p>

Title: I can't run Docker ToolBox on Windows 7


问:
CQL update query not working using Python
I am trying to update new password after reset to cassandra db. This is the query I have written where both username and password fields are dynamic. Is this right?

```<code>    def update_db(uname, pwd):
        query = session.prepare('update user.userdetails set "password"=%s where "username" = ? ALLOW FILTERING', pwd)
        session.execute(query, (uname,))

update_db(username, new_pwd)
</code>```

I am calling this through an API. But it doesn't seem to update.

答:
Alex is absolutely correct in that you need to provide the complete PRIMARY KEY for any write operation.  Remove ALLOW FILTERING and your query should work as long as your primary key definition is: PRIMARY KEY (username).

Additionally, it's best practice to parameterize your entire prepared statement, instead of relying on string formatting for password.

```<code>    query = session.prepare('update user.userdetails set "password"=? where "username"=?')
    session.execute(query,[pwd,uname])
</code>```

Note: If at any point you find yourself needing the ALLOW FILTERING directive, you're doing it wrong.

Body:
I am trying to update new password after reset to cassandra db. This is the query I have written where both username and password fields are dynamic. Is this right?

    def update_db(uname, pwd):
        query = session.prepare('update user.userdetails set "password"=%s where "username" = ? ALLOW FILTERING', pwd)
        session.execute(query, (uname,))

update_db(username, new_pwd)

I am calling this through an API. But it doesn't seem to update.

Body:
Alex is absolutely correct in that you need to provide the complete PRIMARY KEY for any write operation.  Remove ALLOW FILTERING and your query should work as long as your primary key definition is: PRIMARY KEY (username).

Additionally, it's best practice to parameterize your entire prepared statement, instead of relying on string formatting for password.

    query = session.prepare('update user.userdetails set "password"=? where "username"=?')
    session.execute(query,[pwd,uname])

Note: If at any point you find yourself needing the ALLOW FILTERING directive, you're doing it wrong.


问:
Using SVNKit, how can I switch a directory to a different branch?
I have a working directory in trunk and would like to switch it to a specified branch. How can I do that?

I'd like to have a method

```<code>public static void switchToBranch(File baseDir, String branchUrl){
}
</code>```

How could I implement that?

答:
[Update] Better version:

```<code>public static void switchToBranch(final String branchUrl,
    final File basedir,
    final ISVNDebugLog log) throws SVNException, IOException{
    final SVNUpdateClient updateClient =
        SVNClientManager
            .newInstance().getUpdateClient();
    if(log != null) updateClient.setDebugLog(log);
    updateClient.doSwitch(basedir,
        SVNURL.parseURIEncoded(branchUrl),
        SVNRevision.HEAD,
        SVNRevision.HEAD,
        SVNDepth.INFINITY,
        false,
        false);
}
</code>```

Credentials are apparently automatically picked up from the ~/.subversion directory.

(And of course it doesn't have to be a branch, SVN doesn't make a difference between tags, branches or any other path)

Body:
I have a working directory in trunk and would like to switch it to a specified branch. How can I do that?

I'd like to have a method

public static void switchToBranch(File baseDir, String branchUrl){
}

How could I implement that?

Body:
[Update] Better version:

public static void switchToBranch(final String branchUrl,
    final File basedir,
    final ISVNDebugLog log) throws SVNException, IOException{
    final SVNUpdateClient updateClient =
        SVNClientManager
            .newInstance().getUpdateClient();
    if(log != null) updateClient.setDebugLog(log);
    updateClient.doSwitch(basedir,
        SVNURL.parseURIEncoded(branchUrl),
        SVNRevision.HEAD,
        SVNRevision.HEAD,
        SVNDepth.INFINITY,
        false,
        false);
}

Credentials are apparently automatically picked up from the ~/.subversion directory.

(And of course it doesn't have to be a branch, SVN doesn't make a difference between tags, branches or any other path)


问:
Sending emails using office 365 via php, connection refused (GoDaddy)
I'm at my wits end. We were having issues with sending email on a GoDaddy hosting, mostly that it was too unreliable (sometimes it worked flawlessly, sometimes I have to send several emails for one to go through, long queues, and so on. This is not the first time I've had these issues with them, by the way). So, I called them and their recommended solution was to set up an office 365 account and use that instead. I passed that information to my client, and he did it (albeit not via Godaddy's office 365 product, but directly with Microsoft, which certainly helps explain the difficulty), but I still cannot connect. I started to research this issue, but at this point I can say I am just lost. Here's everything I tried / learned, as well as the connections I'm trying.

My PHP setup is laravel 5.2, sending email via swiftmailer. The connection data is on an .env file:

```<code>MAIL_DRIVER=smtp

MAIL_HOST=smtp.office365.com

MAIL_PORT=587

MAIL_USERNAME=myaccount@mydomain.onmicrosoft.com

MAIL_PASSWORD=password

MAIL_ENCRYPTION=tls

And a sample php script sending emails

$logger = new \Swift_Plugins_Loggers_EchoLogger();
        Mail::getSwiftMailer()->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));

        $master_email = "foo@bar.com";
        Mail::send('emails.contact_us', $data, function ($message) use ($master_email, $request) {
            $message->from("myaccount@mydomain.onmicrosoft.com");
            $message->to($master_email)->subject('Subject');
        });
</code>```

And it fails with the message

++ Starting Swift_SmtpTransport
!! Connection could not be established with host smtp.office365.com [Connection refused #111] (code: 0)

There are plenty of comments saying that GoDaddy simply blocks outgoing smtp connections and forces you to use their relay service. However, all sources mentioning this seem to be outdated (2014 and earlier), not to mention I'm trying the setup that their support suggested on phone.

I've already did everything instructed on this microsoft article. On my office 365 admin account I can validate DNS to check if everything is okay, it says so. Microsoft support also says everything is correct. Domains are set up as "authoritative"

I've also tried setting up a connector and trying to connect to mydomain-com.mail.protection.outlook.com, fails with same error, so for now I've deleted that connector

I've called GoDaddy support to see if it was something like a firewall blocking my connection, and they said that's not it. They recommended deleting my workspace email account, I did so, still fails after that.

And so, I'm lost. I need this to work somehow, sending emails via microsoft's smtp server (and not godaddy's) specially because my client already set up his office 365 account and paid for it, so...yeah. Am I missing some configuration beyond the DNS changes? Should I connect to some other smtp server? Change hosts? Am I missing some parameter on my PHP scripts?

This seems to be fairly common issue, but it is surprisingly hard to find some definite answer. Hopefully my case will help others attempting something similar.

答:
I had with the same problem in Laravel OctoberCMS on Godaddy.
The only config that worked for me is:

```<code>MAIL_DRIVER=sendmail

MAIL_HOST=smtp.office365.com

MAIL_PORT=587

MAIL_USERNAME=myaccount@mydomain.com

MAIL_PASSWORD=password

MAIL_ENCRYPTION=tls
</code>```

I hope this helps

Body:
I'm at my wits end. We were having issues with sending email on a GoDaddy hosting, mostly that it was too unreliable (sometimes it worked flawlessly, sometimes I have to send several emails for one to go through, long queues, and so on. This is not the first time I've had these issues with them, by the way). So, I called them and their recommended solution was to set up an office 365 account and use that instead. I passed that information to my client, and he did it (albeit not via Godaddy's office 365 product, but directly with Microsoft, which certainly helps explain the difficulty), but I still cannot connect. I started to research this issue, but at this point I can say I am just lost. Here's everything I tried / learned, as well as the connections I'm trying.

My PHP setup is laravel 5.2, sending email via swiftmailer. The connection data is on an .env file:

MAIL_DRIVER=smtp

MAIL_HOST=smtp.office365.com

MAIL_PORT=587

MAIL_USERNAME=myaccount@mydomain.onmicrosoft.com

MAIL_PASSWORD=password

MAIL_ENCRYPTION=tls

And a sample php script sending emails

$logger = new \Swift_Plugins_Loggers_EchoLogger();
        Mail::getSwiftMailer()->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));

        $master_email = "foo@bar.com";
        Mail::send('emails.contact_us', $data, function ($message) use ($master_email, $request) {
            $message->from("myaccount@mydomain.onmicrosoft.com");
            $message->to($master_email)->subject('Subject');
        });

And it fails with the message

++ Starting Swift_SmtpTransport
!! Connection could not be established with host smtp.office365.com [Connection refused #111] (code: 0)

There are plenty of comments saying that GoDaddy simply blocks outgoing smtp connections and forces you to use their relay service. However, all sources mentioning this seem to be outdated (2014 and earlier), not to mention I'm trying the setup that their support suggested on phone.

I've already did everything instructed on this microsoft article. On my office 365 admin account I can validate DNS to check if everything is okay, it says so. Microsoft support also says everything is correct. Domains are set up as "authoritative"

I've also tried setting up a connector and trying to connect to mydomain-com.mail.protection.outlook.com, fails with same error, so for now I've deleted that connector

I've called GoDaddy support to see if it was something like a firewall blocking my connection, and they said that's not it. They recommended deleting my workspace email account, I did so, still fails after that.

And so, I'm lost. I need this to work somehow, sending emails via microsoft's smtp server (and not godaddy's) specially because my client already set up his office 365 account and paid for it, so...yeah. Am I missing some configuration beyond the DNS changes? Should I connect to some other smtp server? Change hosts? Am I missing some parameter on my PHP scripts?

This seems to be fairly common issue, but it is surprisingly hard to find some definite answer. Hopefully my case will help others attempting something similar.

Body:
I had with the same problem in Laravel OctoberCMS on Godaddy.
The only config that worked for me is:

MAIL_DRIVER=sendmail

MAIL_HOST=smtp.office365.com

MAIL_PORT=587

MAIL_USERNAME=myaccount@mydomain.com

MAIL_PASSWORD=password

MAIL_ENCRYPTION=tls

I hope this helps


问:
How to get the bipartite complement graph in networkx/python?
I have bipartite graph and I would like to extract the bipartite complement of this graph. This is the G' graph explained in this link :

https://www.quora.com/Given-a-bipartite-graph-how-can-I-find-its-subgraph-that-is-a-complete-bipartite-graph-and-has-the-most-vertices

I tried to do it in using the complement algorithm of the Networkx library but I got edges between my vertices A and B that shouldn't be connected because in bipartite graph there are no edges between a same group of vertices.

Here is the code that I tried :

from networkx.algorithms.operators.unary import complement

B = bipartite.random_graph(5, 7, 0.2)
B = complement(B)
```

But I have got connections into same group of vertices. Is there a networkx function or Python function that handle it ?

答:
Try this:

```<code>import networkx as nx
B = nx.bipartite.random_graph(5, 7, 0.2)
G = nx.bipartite.complete_bipartite_graph(5,7)   #or use random_graph with probability 1
H = nx.difference(G,B)
</code>```

This uses difference, which returns a graph whose edges are the edges in G but not B.

The problem with what you were doing is that complement does not return the bipartite complement, but rather the full complement.  It contains edges between all pairs that were not joined in the original graph.

Body:
I have bipartite graph and I would like to extract the bipartite complement of this graph. This is the G' graph explained in this link :

https://www.quora.com/Given-a-bipartite-graph-how-can-I-find-its-subgraph-that-is-a-complete-bipartite-graph-and-has-the-most-vertices

I tried to do it in using the complement algorithm of the Networkx library but I got edges between my vertices A and B that shouldn't be connected because in bipartite graph there are no edges between a same group of vertices.

Here is the code that I tried :

from networkx.algorithms.operators.unary import complement

B = bipartite.random_graph(5, 7, 0.2)
B = complement(B)

But I have got connections into same group of vertices. Is there a networkx function or Python function that handle it ?

Body:
Try this:

import networkx as nx
B = nx.bipartite.random_graph(5, 7, 0.2)
G = nx.bipartite.complete_bipartite_graph(5,7)   #or use random_graph with probability 1
H = nx.difference(G,B)

This uses difference, which returns a graph whose edges are the edges in G but not B.

The problem with what you were doing is that complement does not return the bipartite complement, but rather the full complement.  It contains edges between all pairs that were not joined in the original graph.


问:
Convert url to secure url link can be recognized by iframe
How to convert url to secure url link that can be recognized by iframe in angular</p>

```<code>  <iframe src="{{url}}"></iframe>
</code>```

答:
Try like this below

secure-pipe.ts

```<code>import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

@Pipe({ name: 'secure' })
export class SecurePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}
</code>```

app.module.ts

```<code>@NgModule({
   declarations : [
     ...
     SecurePipe
   ],
})
</code>```

In Html

```<code><iframe [src]="url | secure"></iframe>
</code>```

Body:
Try like this below

secure-pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

@Pipe({ name: 'secure' })
export class SecurePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

app.module.ts

@NgModule({
   declarations : [
     ...
     SecurePipe
   ],
})

In Html

<iframe [src]="url | secure"></iframe>