问:
Colored output without Perl
I have a mailing script to send colored output, but I can't use it on a Unix machine as the MIME::Lite module is not installed on it.

Can anyone suggest an alternative to get the desired output in color?

```<code>use MIME::Lite;

my (@page_html, @sujet);

my $file = 'rpt.html';

open my $ifh, '<', $file
     or die "Cannot open '$file' for reading: $!";

local $/ = "";

my $contents = <$ifh>;

close( $ifh );

my $msg = new MIME::Lite;
</code>```

Output:

```<code><tr><td>test1</td><td bgcolor=red>NOK</td></tr>
<tr><td>test2</td><td bgcolor=green>OK</td></tr>
<tr><td>test3</td><td bgcolor=green>OK</td></tr>
</code>```

OK Should be in green

NOK should be red

答:
The coloured output seems to be a complete red herring (hah!) here. You have a file which you want to send as an attachment to a MIME email.

If you're going to be using Perl, then you need to be in an environment where you can install modules from CPAN. Without CPAN, you're missing most of the power of modern Perl. I suggest that it's worth having whatever discussions you need to have in order to remove that major block to your Perl programming career.

If you really can't install modules into the system libraries, then you can install them into your home directory and use use lib or PERL5LIB to adjust the Perl library path as appropriate.

When you've solved the problem of how to use CPAN modules, can we talk about your choice of modules? MIME::Lite isn't exactly deprecated, but there have been better alternatives available for over ten years. Take a look at Email::Stuffer.

But if you're determined not to have the CPAN module installation discussion, the other approach is to use the command-line program mailx to send your message.

```<code>$ mailx -a rpt.html someone@example.com
</code>```

Title: Colored output without Perl

Body:
I have a mailing script to send colored output, but I can't use it on a Unix machine as the MIME::Lite module is not installed on it.

Can anyone suggest an alternative to get the desired output in color?

use MIME::Lite;

my (@page_html, @sujet);

my $file = 'rpt.html';

open my $ifh, '<', $file
     or die "Cannot open '$file' for reading: $!";

local $/ = "";

my $contents = <$ifh>;

close( $ifh );

my $msg = new MIME::Lite;

Output:

test1	NOK

test2	OK

test3	OK

OK Should be in green

NOK should be red

Body:
The coloured output seems to be a complete red herring (hah!) here. You have a file which you want to send as an attachment to a MIME email.

If you're going to be using Perl, then you need to be in an environment where you can install modules from CPAN. Without CPAN, you're missing most of the power of modern Perl. I suggest that it's worth having whatever discussions you need to have in order to remove that major block to your Perl programming career.

If you really can't install modules into the system libraries, then you can install them into your home directory and use use lib or PERL5LIB to adjust the Perl library path as appropriate.

When you've solved the problem of how to use CPAN modules, can we talk about your choice of modules? MIME::Lite isn't exactly deprecated, but there have been better alternatives available for over ten years. Take a look at Email::Stuffer.

But if you're determined not to have the CPAN module installation discussion, the other approach is to use the command-line program mailx to send your message.

$ mailx -a rpt.html someone@example.com


来源: stackexchange

问:
perl <file.pl> gets executed with no output at all
I downloaded a perl script (http://www.speech.cs.cmu.edu/tools/download/quick_lm.pl) for generating language models.

When I do perl quick_lm.pl, it simply terminates. No output at all.

Yes, I have perl installed and perl -v works perfectly.

I made a simple hello-world perl script and it executes just fine. [attached at the end]

So, I included print "hello"; in the first line of the quick_lm.pl and tried perl quick_lm.pl, still nothing happens.

I even tried giving the quick_lm.pl all permissions using chmod 777 quick_lm.pl. Now when I do ./quick_lm.pl it gives an error :

```<code>-bash: ./quick_lm.pl: /usr/local/bin/perl: bad interpreter: No such file or directory
</code>```

I searched this error and almost all the solutions pointed to windows CLRF, but unlike them I do not have ^M in /usr/local/bin/perl. Also, still perl quick_lm.pl should work, right?

[bash.log]

```<code>someone@something:~/dictionary$ perl quick_lm.pl
someone@something:~/dictionary$ perl quick_lm.pl -s words.txt
someone@something:~/dictionary$ nano quick_lm.pl
someone@something:~/dictionary$ perl quick_lm.pl -s words.txt
someone@something:~/dictionary$ chmod 777 quick_lm.pl
someone@something:~/dictionary$ ./quick_lm.pl
-bash: ./quick_lm.pl: /usr/local/bin/perl: bad interpreter: No such file or directory
someone@something:~/dictionary$ cat new.pl
#!/usr/bin/perl -w
use strict;

print "Hello World\n";
someone@something:~/dictionary$ perl new.pl
Hello World
someone@something:~/dictionary$
</code>```

[After adding print in the beginning of quick_lm.pl and reducing it to a minimal, runable demonstration of the problem.]

```<code>#!/usr/local/bin/perl -w
=POD

...license...

=END

use Getopt::Std;

print "hello world";
$VERBOSE = 1;

sub handler { local($sig) = @_;
          print STDERR "quick_lm caught a SIG$sig -- dying\n";

          exit(0);
        }
foreach (qw(XCPU KILL TERM STOP)) { $SIG{$_} = \&handler; }
</code>```

This is not full script, full script is in the link mentioned in the very first line. I am not sure if it's related to file as much as my perl configuration. As you might have guessed, I don't have much idea about perl.

I appreciate your time and help :)

答:
-bash: ./quick_lm.pl: /usr/local/bin/perl: bad interpreter: No such file or directory

Replace /usr/local/bin/perl with the correct path to perl. This path can be obtained from

```<code>perl -le'print $^X'
</code>```

it simply terminates. No output at all.

The =pod directive indicates the start of inlined documentation ("POD"). =cut marks the end of the block of POD.

The program incorrectly uses =END instead of =cut to mark the end of the block of POD, so Perl thinks the whole program is one big comment.. Replace =END with =cut.

ContentLicense: CC BY-SA 3.0

Body:
I downloaded a perl script (http://www.speech.cs.cmu.edu/tools/download/quick_lm.pl) for generating language models.

When I do perl quick_lm.pl, it simply terminates. No output at all.

Yes, I have perl installed and perl -v works perfectly.

I made a simple hello-world perl script and it executes just fine. [attached at the end]

So, I included print "hello"; in the first line of the quick_lm.pl and tried perl quick_lm.pl, still nothing happens.

I even tried giving the quick_lm.pl all permissions using chmod 777 quick_lm.pl. Now when I do ./quick_lm.pl it gives an error :

-bash: ./quick_lm.pl: /usr/local/bin/perl: bad interpreter: No such file or directory

I searched this error and almost all the solutions pointed to windows CLRF, but unlike them I do not have ^M in /usr/local/bin/perl. Also, still perl quick_lm.pl should work, right?

[bash.log]

someone@something:~/dictionary$ perl quick_lm.pl
someone@something:~/dictionary$ perl quick_lm.pl -s words.txt
someone@something:~/dictionary$ nano quick_lm.pl
someone@something:~/dictionary$ perl quick_lm.pl -s words.txt
someone@something:~/dictionary$ chmod 777 quick_lm.pl
someone@something:~/dictionary$ ./quick_lm.pl
-bash: ./quick_lm.pl: /usr/local/bin/perl: bad interpreter: No such file or directory
someone@something:~/dictionary$ cat new.pl
#!/usr/bin/perl -w
use strict;

print "Hello World\n";
someone@something:~/dictionary$ perl new.pl
Hello World
someone@something:~/dictionary$

[After adding print in the beginning of quick_lm.pl and reducing it to a minimal, runable demonstration of the problem.]

#!/usr/local/bin/perl -w
=POD

...license...

=END

use Getopt::Std;

print "hello world";
$VERBOSE = 1;

sub handler { local($sig) = @_;
          print STDERR "quick_lm caught a SIG$sig -- dying\n";

          exit(0);
        }
foreach (qw(XCPU KILL TERM STOP)) { $SIG{$_} = \&handler; }

This is not full script, full script is in the link mentioned in the very first line. I am not sure if it's related to file as much as my perl configuration. As you might have guessed, I don't have much idea about perl.

I appreciate your time and help :)

Body:
-bash: ./quick_lm.pl: /usr/local/bin/perl: bad interpreter: No such file or directory

Replace /usr/local/bin/perl with the correct path to perl. This path can be obtained from

perl -le'print $^X'

it simply terminates. No output at all.

The =pod directive indicates the start of inlined documentation ("POD"). =cut marks the end of the block of POD.

The program incorrectly uses =END instead of =cut to mark the end of the block of POD, so Perl thinks the whole program is one big comment.. Replace =END with =cut.


问:
How to fit a surface ((x,y,z) matrix) using Matlab?
I made AFM (Atomic Force Microscopy) measurements. I exported my data from Gwyddion to a text file (can be download here), such as I load it in Matlab like:

```<code>data = importdata('001_Zsensor.xyz');
x=data(:,1);y=data(:,2);z=data(:,3);
shading('interp');
tri = delaunay(x,y);
figure(1)
tsurf=trisurf(tri,x,y,z,'EdgeColor','none','Facecolor','interp');
</code>```

So now I have my surface. It corresponds to the rugosity of a bead, so I need to extract the spherical feature of this surface in order to recover the rugosity landscape over a plane surface (from which I can then compute my physical parameters).

Basically, I want to fit a ellipsoid to the surface I previously defined (tsurf). I tried using cftool (even though I'd rather use command so I can put this in a Matlab script) but as the equation should be of form

z=f(x,y)

and the ellipsoid's equation is

((x-x0)/a)^2 + ((y-y0)/b)^2 + ((z-z0)/c)^2 = 1,

I did not manage to get the fit to work.
How can I do so?

Thank you very much.

答:
Ok, found it! Here it is:

Following the previous code lines I wrote (see the question of this post):

```<code>ffit = fit([x y],z,'poly22')
figure(1)
hold on
plot(ffit)
</code>```

Of course, the fit can be more constrained if needed.

Body:
I made AFM (Atomic Force Microscopy) measurements. I exported my data from Gwyddion to a text file (can be download here), such as I load it in Matlab like:

data = importdata('001_Zsensor.xyz');
x=data(:,1);y=data(:,2);z=data(:,3);
shading('interp');
tri = delaunay(x,y);
figure(1)
tsurf=trisurf(tri,x,y,z,'EdgeColor','none','Facecolor','interp');

So now I have my surface. It corresponds to the rugosity of a bead, so I need to extract the spherical feature of this surface in order to recover the rugosity landscape over a plane surface (from which I can then compute my physical parameters).

Basically, I want to fit a ellipsoid to the surface I previously defined (tsurf). I tried using cftool (even though I'd rather use command so I can put this in a Matlab script) but as the equation should be of form

z=f(x,y)

and the ellipsoid's equation is

((x-x0)/a)^2 + ((y-y0)/b)^2 + ((z-z0)/c)^2 = 1,

I did not manage to get the fit to work.
How can I do so?

Thank you very much.

Body:
Ok, found it! Here it is:

Following the previous code lines I wrote (see the question of this post):

ffit = fit([x y],z,'poly22')
figure(1)
hold on
plot(ffit)

Of course, the fit can be more constrained if needed.

ContentLicense: CC BY-SA 4.0


问:
Table '/tmp/#sql_1_0.MAI' is read only
When I try to use SHOW FULL FIELDS FROM or some other SHOW COLUMNS syntax query I get this strange error message:

```<code>MariaDB [mysql]> show full fields from user;
ERROR 1036 (HY000): Table '/tmp/#sql_126_0.MAI' is read only
</code>```

Tmp dir is present and has 777 permissions.
Changing tmp dir in my.cnf doesn't help.

Chowning that dir to mysql user doesn't help either.

Steps to reproduce:

Install CentOS 7 into VM (or any sufficiently old kernel)

Install Docker on CentOS 7 (so that we can use alpine)

Create alpine-based image with MariaDB 10.1.28 (apk add mysql mysql-client) or use readily available image

Run mysql container docker run --name mariadb_container mariadb_image

Connect to mysql using docker exec -ti mariadb_container mysql -A

Run SHOW FULL FIELDS FROM some_table query

Any suggestions on how to trace that problem?

答: You should try to downgrade your Mariadb to version 10.1.17 (worked for me)

Title: Table '/tmp/#sql_1_0.MAI' is read only

Body:
When I try to use SHOW FULL FIELDS FROM or some other SHOW COLUMNS syntax query I get this strange error message:

MariaDB [mysql]> show full fields from user;
ERROR 1036 (HY000): Table '/tmp/#sql_126_0.MAI' is read only

Tmp dir is present and has 777 permissions.
Changing tmp dir in my.cnf doesn't help.

Chowning that dir to mysql user doesn't help either.

Steps to reproduce:

Install CentOS 7 into VM (or any sufficiently old kernel)

Install Docker on CentOS 7 (so that we can use alpine)

Create alpine-based image with MariaDB 10.1.28 (apk add mysql mysql-client) or use readily available image

Run mysql container docker run --name mariadb_container mariadb_image

Connect to mysql using docker exec -ti mariadb_container mysql -A

Run SHOW FULL FIELDS FROM some_table query

Any suggestions on how to trace that problem?


问:
How send SIGUSR1 signal with a keyboard shortcut?
I want to send SIGUSR1 signal to my node.js application for debugging via terminal. I know command kill -SIGUSR1 <pid>

How can I setup keyboard shortcut for this? If it matters, I use MacOs

答:
To get the pid of your node.js application:

How to get the PID of a process by giving the process name in Mac OS X ?

To create a global shortcut for your command:

https://apple.stackexchange.com/questions/24063/create-global-shortcut-to-run-command-line-applications


问:
Javascript Canvas Animation with requestAnimationFrame becomes faster by path change
I have a Canvas animation where serveral litle objekt(with objekt i mean picture aso a img element)come from up to down.

After i make 2 themes for this animation(i mean that the objekt have different picture depending on theme) the animation becomes faster after every path change respectively theme change.

And i dont have any idea what can be the reason.If anyone can help me i would be very glad.

```<code><!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>index</title>
  <script type="text/javascript" src="../javascript/liabary.js"></script>
  <link rel="stylesheet" href="../css/CSS.css">
</head>

<body class="body2">
    <center class="font2"><h2>Cookie Clicker</h2></center>
  <canvas  id="canvas" style="border: 1px solid; width: 800px; height: 810px;">no support</canvas>

            <img onclick="AnimationGroßCookie(); myFunctionAdd()" onMousedown="AnimationKleinCookie()" id="cookie" src="../img/cookie.png"  alt="cookie">
            <p class="font2" id="p1"></p><p class="font2" id="p2">gesammelte cookies:</p>

            <div onclick="DoubleClicker()" class="font2" id="buyMenu">
                    <p id="DoubleClicker" style="font-size: 19px; margin-left:30px;">Double Clicker</p>
                    <p style="font-size: 19px; margin-left:55px; margin-top:-15px;">kosten 20</p>
            </div>

            <div onclick="GeheimesVideo(); " class="font2" id="buyMenu2">
                    <p>Super Geheimes Video</p> <!--wennn gekauft langsam größer werdenes video-->
                    <p>kosten: 10.000</p>
            </div>

            <div onclick="AddPerSecond()" class="font2" id="Platzhalter">
                    <p>Platzhalter: 1cookie per second</p>
                    <p>kosten: 100</p>
            </div>

            <div onclick="ThemeÄndern0(); ThemeÄndernPath();" class="font2" id="Theme1">
                    <p>Cookie Theme:ändern per click</p>
            </div>

            <div onclick="ThemeÄndern1(); ThemeÄndernPath();" class="font2" id="Theme2">
                    <p>Donut Theme:ändern per click</p>
            </div>

<script>
console.log("Start");
var counter = 0;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d'); //ctx = contex
var img = new Image();
var add1 = 10;
var rAF;//raf = requestAnimationFrame
Theme = 0;

                canvas.width = canvas.scrollWidth;
                canvas.height = canvas.scrollHeight;

                img.onload = function() {
                   console.log("Loaded image");
                     if (rAF) cancelAnimationFrame(rAF); //cancel prev animation frame
                   Hallo();
                };

function ThemeÄndernPath() {
    var cookie = document.getElementById('cookie');
                if (Theme == 0) {
                        img.src="../img/cookie.png";
                        cookie.src="../img/cookie.png";
                } else {
                        img.src="../img/donut2.png";
                        cookie.src="../img/donut2.png";
                }

}

                ThemeÄndernPath();
                //var CookieClickSound = Math.floor((Math.random() * 6) + 0);

                var cookieArrayBreite =[];
                cookieArrayBreite[0]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[1]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[2]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[3]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[4]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[5]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[6]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[7]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[8]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[9]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[10]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[11]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[12]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[13]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[14]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayBreite[15]  =  Math.floor((Math.random() * 810) + 0);

                var cookieArrayHöhe =[];
                cookieArrayHöhe[0]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[1]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[2]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[3]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[4]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[5]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[6]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[7]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[8]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[9]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[10]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[11]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[12]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[13]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[14]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[15]  =  Math.floor((Math.random() * 810) + 0);

                setTimeout(function() { cookieCanvas(); },3000); //dont work
                window.setInterval(myCallback, 13200);

                    function myCallback() {
                                cookieArrayBreite[0]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[1]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[2]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[3]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[4]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[5]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[6]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[7]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[8]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[9]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[10]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[11]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[12]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[13]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[14]  =  Math.floor((Math.random() * 810) + 0);
                                cookieArrayBreite[15]  =  Math.floor((Math.random() * 810) + 0);

             console.log(cookieArrayBreite);
}

window.setInterval(myCallback, 13200);

    function myCallback() {
                cookieArrayHöhe[0]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[1]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[2]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[3]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[4]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[5]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[6]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[7]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[8]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[9]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[10]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[11]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[12]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[13]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[14]  =  Math.floor((Math.random() * 810) + 0);
                cookieArrayHöhe[15]  =  Math.floor((Math.random() * 810) + 0);

console.log(cookieArrayHöhe);
}

                function Hallo() {

                   if (add1 == 800) {

                      add1 = 10; // need to reset add's value

                      console.log("resetet");

                      ctx.clearRect(0, 0, canvas.width, canvas.height);

                      ctx.beginPath();
                      ctx.rect(0, 0, 1000, 1000);
                      ctx.fillStyle = "lightblue";
                      ctx.fill();

                            ctx.drawImage(img, cookieArrayBreite[0], cookieArrayHöhe[0] + add1, 50, 50);
                      ctx.drawImage(img, cookieArrayBreite[1], cookieArrayHöhe[1] + add1, 50, 50);
                      ctx.drawImage(img, cookieArrayBreite[2], cookieArrayHöhe[2] + add1, 50, 50);
                      ctx.drawImage(img, cookieArrayBreite[3], cookieArrayHöhe[3] + add1, 50, 50);
                      ctx.drawImage(img, cookieArrayBreite[4], cookieArrayHöhe[4] + add1, 50, 50);
                      ctx.drawImage(img, cookieArrayBreite[5], cookieArrayHöhe[5] + add1, 50, 50);
                      ctx.drawImage(img, cookieArrayBreite[6], cookieArrayHöhe[6] + add1, 50, 50);
                      ctx.drawImage(img, cookieArrayBreite[7], cookieArrayHöhe[7] + add1, 50, 50);
                            ctx.drawImage(img, cookieArrayBreite[8], cookieArrayHöhe[8] + add1, 50, 50);
                      ctx.drawImage(img, cookieArrayBreite[9], cookieArrayHöhe[9] + add1, 50, 50);
                            ctx.drawImage(img, cookieArrayBreite[10], cookieArrayHöhe[10] + add1, 50, 50);
                          ctx.drawImage(img, cookieArrayBreite[11], cookieArrayHöhe[11] + add1, 50, 50);
                          ctx.drawImage(img, cookieArrayBreite[12], cookieArrayHöhe[12] + add1, 50, 50);
                          ctx.drawImage(img, cookieArrayBreite[13], cookieArrayHöhe[13] + add1, 50, 50);

                   } else {
                      console.log("Animation begining");

                      ctx.clearRect(0, 0, canvas.width, canvas.height);

                      ctx.beginPath();
                      ctx.rect(0, 0, 1000, 1000);
                      ctx.fillStyle = "lightblue";
                      ctx.fill();

                         ctx.drawImage(img, cookieArrayBreite[0], cookieArrayHöhe[0] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[1], cookieArrayHöhe[1] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[2], cookieArrayHöhe[2] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[3], cookieArrayHöhe[3] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[4], cookieArrayHöhe[4] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[5], cookieArrayHöhe[5] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[6], cookieArrayHöhe[6] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[7], cookieArrayHöhe[7] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[8], cookieArrayHöhe[8] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[9], cookieArrayHöhe[9] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[10], cookieArrayHöhe[10] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[11], cookieArrayHöhe[11] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[12], cookieArrayHöhe[12] + add1, 50, 50);
                         ctx.drawImage(img, cookieArrayBreite[13], cookieArrayHöhe[13] + add1, 50, 50);

                      add1++;
                   }
                     rAF = requestAnimationFrame(Hallo);
                   requestAnimationFrame(Hallo);
                }
</script>
<audio controls autoplay id="AudioClick">
  <source src="" type="">
   Audio element is not supported by your browser
</audio>

</body>

</html>
</code>```

And her the liabarys:

```<code>function ThemeÄndern1(){
        Theme = 1;
}

function ThemeÄndern0(){
        Theme = 0;
}
</code>```

PS:pls forgive me gramatical errors in my text i am still Student :)

答:
You need to clear the previous animation frame before initiating a new one.

To accomplish so, first, declare a global variable, for instance ...

```<code>var rAF;
</code>```

then, assign the requestAnimationFrame to that variable ...

```<code>rAF = requestAnimationFrame(Hallo);
</code>```

and finally, cancel previous animation frame before calling the Hallo function ...

```<code>img.onload = function() {
   console.log("Loaded image");
   if (rAF) cancelAnimationFrame(rAF); //cancel prev animation frame
   Hallo();
};
</code>```

Body:
I have a Canvas animation where serveral litle objekt(with objekt i mean picture aso a img element)come from up to down.

After i make 2 themes for this animation(i mean that the objekt have different picture depending on theme) the animation becomes faster after every path change respectively theme change.

And i dont have any idea what can be the reason.If anyone can help me i would be very glad.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>index</title>

  <link rel="stylesheet" href="../css/CSS.css">

Cookie Clicker

  <canvas  id="canvas" style="border: 1px solid; width: 800px; height: 810px;">no support</canvas>

gesammelte cookies:

Double Clicker

kosten 20

Super Geheimes Video

kosten: 10.000

Platzhalter: 1cookie per second

kosten: 100

Cookie Theme:ändern per click

Donut Theme:ändern per click

<audio controls autoplay id="AudioClick">
  <source src="" type="">
   Audio element is not supported by your browser
</audio>

And her the liabarys:

function ThemeÄndern1(){
        Theme = 1;
}

function ThemeÄndern0(){
        Theme = 0;
}

PS:pls forgive me gramatical errors in my text i am still Student :)

Body:
You need to clear the previous animation frame before initiating a new one.

To accomplish so, first, declare a global variable, for instance ...

var rAF;

then, assign the requestAnimationFrame to that variable ...

rAF = requestAnimationFrame(Hallo);

and finally, cancel previous animation frame before calling the Hallo function ...

img.onload = function() {
   console.log("Loaded image");
   if (rAF) cancelAnimationFrame(rAF); //cancel prev animation frame
   Hallo();
};


问:
MVCGrid.Net How can I inject a service in the MVCGridConfig class using Ninject?
I use Ninject as a dependency injector for my ASP.Net MVC application.

However, MVCGridConfig is a static class.

How can I inject my ICoursesService in the MVCGridConfig class in order to retrieve the necessary data for the table?

Thank you very much!

答:
I doubt you'll be able to inject into a static class, but you could pull it using </p>

```<code>var svc = DependencyResolver.Current.GetService<ICoursesService>();
</code>```

Body:
I doubt you'll be able to inject into a static class, but you could pull it using

var svc = DependencyResolver.Current.GetService<ICoursesService>();


问:
how to copy .htaccess to all 0777 folders
The following command attempts to copy /.htaccess to all folders permission 0777

```<code>find /home/*/www/ -type d -perm 0777 \
| xargs -r -d '\n'  cp -rf /.htaccess
</code>```

am looking to run it with terminal ssh command

i search for all folders have 0777 and copy htaccess to all at once

答:
Rather than bothering with xargs, you can just use the -exec option to find:

```<code>$ find . -type d -perm \0777 -exec cp /.htaccess {} \;
</code>```

Body:
The following command attempts to copy /.htaccess to all folders permission 0777

find /home/*/www/ -type d -perm 0777 \
| xargs -r -d '\n'  cp -rf /.htaccess

am looking to run it with terminal ssh command

i search for all folders have 0777 and copy htaccess to all at once

Body:
Rather than bothering with xargs, you can just use the -exec option to find:

$ find . -type d -perm \0777 -exec cp /.htaccess {} \;


问:
How can I launch "bower install" then "spring-boot:run" using Maven?
I'm a studdent and I does not understand something with Maven in my project.

I use spring-boot and angular 1 within the same repository and I need a solution to first execute a "bower install" before using the maven pluggin "spring-boot:run".

I'd to know if it's possible to customize the maven command.

I use IntelliJ and all I do is pressing the start button in my main class

```<code>package fr.studionline;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAutoConfiguration
public class StudionlineBackApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudionlineBackApplication.class, args);
    }
}
</code>```

The bower_components directory is in another directory than the main class as described in the picture below :
tree view of my project

Thanks in advance if you can help me understand how it work.

I will respond to any questions if there is something missing in my question.

UPDATE:

I did try the front-end-maven pluggin with this pom configuration :

```<code><build>
        <resources>
            <resource>
                <directory>src/resources</directory>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>com.github.eirslett</groupId>
                <artifactId>frontend-maven-plugin</artifactId>
                <!-- Use the latest released version:
                https://repo1.maven.org/maven2/com/github/eirslett/frontend-maven-plugin/ -->
                <version>1.4</version>

                <executions>
                    <execution>
                        <id>bower install</id>
                        <goals>
                            <goal>bower</goal>
                        </goals>
                        <configuration>
                            <arguments>install</arguments>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <workingDirectory>src/main/resources/static</workingDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

and this was what happend when I execute the command frontend:bower

```<code>[INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building studionline-back 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO]
    [INFO] --- frontend-maven-plugin:1.4:bower (default-cli) @ studionline-back ---
    [INFO] Running 'bower install' in C:\Antoine\Ecole\Projet\ProjetAnu_5A\studionline-back\src\main\resources\static
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 1.071 s
    [INFO] Finished at: 2017-07-06T17:59:58+02:00
    [INFO] Final Memory: 11M/155M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal com.github.eirslett:frontend-maven-

    plugin:1.4:bower
    (default-cli) on project studionline-back: Failed to run task: 'bower install' failed.
    java.io.IOException:

Cannot run program "C:\Antoine\Ecole\Projet\ProjetAnu_5A\studionline-back\src\main\resources\static\node\node.exe"
(in directory "C:\Antoine\Ecole\Projet\ProjetAnu_5A\studionline-back\src\main\resources\static"):

    CreateProcess error=2, Le fichier spécifié est introuvable -> [Help 1]

    [ERROR]

    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

    [ERROR] Re-run Maven using the -X switch to enable full debug logging.

    [ERROR]

    [ERROR] For more information about the errors and possible solutions, please read the following articles:
        [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

        Process finished with exit code 1
</code>```

But I still doesn't understand how to launch it with Intellij. Should I do mvn run instead of clicking on the "Run" button ?

答:
Have a look at the frontend-maven-plugin. In particular it has a bower runner.

```<code><execution>
    <id>bower install</id>
    <goals>
        <goal>bower</goal>
    </goals>

    <configuration>
        <!-- optional: The default argument is actually
        "install", so unless you need to run some other bower command,
        you can remove this whole <configuration> section.
        -->
        <arguments>install</arguments>
    </configuration>
</execution>
</code>```

Check the "Optional Configuration" section to see how to configure your front end directory. In your case:

```<code><plugin>
    <groupId>com.github.eirslett</groupId>
    <artifactId>frontend-maven-plugin</artifactId>

    <!-- optional -->
    <configuration>
        <workingDirectory>src/main/resources/static</workingDirectory>
    </configuration>
</plugin>
</code>```

Body:
I'm a studdent and I does not understand something with Maven in my project.

I use spring-boot and angular 1 within the same repository and I need a solution to first execute a "bower install" before using the maven pluggin "spring-boot:run".

I'd to know if it's possible to customize the maven command.

I use IntelliJ and all I do is pressing the start button in my main class

package fr.studionline;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAutoConfiguration
public class StudionlineBackApplication {

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

The bower_components directory is in another directory than the main class as described in the picture below :
tree view of my project

Thanks in advance if you can help me understand how it work.

I will respond to any questions if there is something missing in my question.

UPDATE:

I did try the front-end-maven pluggin with this pom configuration :

<build>
        <resources>
            <resource>
                <directory>src/resources</directory>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>com.github.eirslett</groupId>
                <artifactId>frontend-maven-plugin</artifactId>

                <version>1.4</version>

                <executions>
                    <execution>
                        <id>bower install</id>
                        <goals>
                            <goal>bower</goal>
                        </goals>
                        <configuration>
                            <arguments>install</arguments>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <workingDirectory>src/main/resources/static</workingDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>

and this was what happend when I execute the command frontend:bower

[INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building studionline-back 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO]
    [INFO] --- frontend-maven-plugin:1.4:bower (default-cli) @ studionline-back ---
    [INFO] Running 'bower install' in C:\Antoine\Ecole\Projet\ProjetAnu_5A\studionline-back\src\main\resources\static
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 1.071 s
    [INFO] Finished at: 2017-07-06T17:59:58+02:00
    [INFO] Final Memory: 11M/155M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal com.github.eirslett:frontend-maven-

    plugin:1.4:bower
    (default-cli) on project studionline-back: Failed to run task: 'bower install' failed.
    java.io.IOException:

Cannot run program "C:\Antoine\Ecole\Projet\ProjetAnu_5A\studionline-back\src\main\resources\static\node\node.exe"
(in directory "C:\Antoine\Ecole\Projet\ProjetAnu_5A\studionline-back\src\main\resources\static"):

    CreateProcess error=2, Le fichier spécifié est introuvable -> [Help 1]

    [ERROR]

    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

    [ERROR] Re-run Maven using the -X switch to enable full debug logging.

    [ERROR]

    [ERROR] For more information about the errors and possible solutions, please read the following articles:
        [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

        Process finished with exit code 1

But I still doesn't understand how to launch it with Intellij. Should I do mvn run instead of clicking on the "Run" button ?

Body:
Have a look at the frontend-maven-plugin. In particular it has a bower runner.

<execution>
    <id>bower install</id>
    <goals>
        <goal>bower</goal>
    </goals>

    <configuration>
        <!-- optional: The default argument is actually
        "install", so unless you need to run some other bower command,
        you can remove this whole <configuration> section.
        -->
        <arguments>install</arguments>
    </configuration>
</execution>

Check the "Optional Configuration" section to see how to configure your front end directory. In your case:

<plugin>
    <groupId>com.github.eirslett</groupId>
    <artifactId>frontend-maven-plugin</artifactId>

    <!-- optional -->
    <configuration>
        <workingDirectory>src/main/resources/static</workingDirectory>
    </configuration>
</plugin>


问:
How to get to request parameters in Postman?
I'm writing tests for Postman which in general works pretty easily. However, I now want to access some of the data of the request, a query parameter to be exact.
You can access the request URL through the "request.url" object which returns a String. Is there an easy way in Postman to parse this URL string to access the query parameter(s)?</p>

答:
have a look in the console doing :

```<code>console.log(request);
</code>```

it'll show you all you can get from request. Then you shall access the different parameters using request., ie. request.name if you want the test name.
If you want a particular element in the url, I'm afraid you'll have to use some coding to obtain it (sorry I'm a beginner in javascript)

Hope this helps

Alexandre

Body:
have a look in the console doing :

console.log(request);

it'll show you all you can get from request. Then you shall access the different parameters using request., ie. request.name if you want the test name.
If you want a particular element in the url, I'm afraid you'll have to use some coding to obtain it (sorry I'm a beginner in javascript)

Hope this helps

Alexandre


问:
How to hide pagination if there is only one or few page result?
My page has 9 result per page and shows a pagination from 1-5, my problem is how can I hide the pagination number if the result of what I search is one or few entry result?

Sorry If I will not post all my code and thank you for helping me.

sidebar.php

```<code><div class="side-box-select cf">
<div class="side-select">
<select name="unit_size_x" class="side-box__select">
    <option value="0" selected>Minimum</option>
    <option value="10">10sqm</option>
    <option value="20">20sqm</option>
    <option value="30">30sqm</option>
    <option value="40">40sqm</option>
    <option value="50">50sqm</option>
    <option value="60">60sqm</option>
    <option value="70">70sqm</option>
    <option value="80">80sqm</option>
    <option value="90">90sqm</option>
    <option value="100">100sqm</option>
</select>
</div>
<div class="side-select">

<select name="unit_size_y" class="side-box__select">
    <option value="10">10sqm</option>
    <option value="20">20sqm</option>
    <option value="30">30sqm</option>
    <option value="40">40sqm</option>
    <option value="50">50sqm</option>
    <option value="60">60sqm</option>
    <option value="70">70sqm</option>
    <option value="80">80sqm</option>
    <option value="90">90sqm</option>
    <option value="100">100sqm</option>
   <option value="101" selected>Maximum</option>

</select>
</div>
</code>```

search.php

```<code>$metaquerysp[] = array(
'key'=>'unit_size',
'value'=>array( $unit_size_x, $unit_size_y ),
'compare'=>'BETWEEN',
'type'=>'NUMERIC',
);
<?php
    $paged = get_query_var('paged') ? get_query_var('paged') : 1;
    $args = array(
    'post_type' => 'property',
    'posts_per_page' => 9,
    'orderby' => 'DATE',
    'paged' => $paged,
    'meta_query' => $metaquerysp
     );?>
</code>```

答:
Hopefully this will make sense. Check $query->post_count for the number of posts returned by your query.

```<code>$paged          = get_query_var('paged') ? get_query_var('paged') : 1;
// Posts per page
$posts_per_page = 9;
// Should pagination show (default yes)
$pagination     = true;

$args = array(
    'post_type' => 'property',
    'posts_per_page' => $posts_per_page,
    'orderby' => 'DATE',
    'paged' => $paged,
    'meta_query' => $metaquerysp
);

// Run query
$query =  new WP_Query($args);

// If query has less than $posts_per_page results, no pagination
if($query->post_count<$posts_per_page) {
    $pagination = false;
}

// The loop
if($query->have_posts()) {
    while($query->have_posts()) {
        $query->the_post();

        // Stuff
    }
}

if($pagination) {
    // show pagination
}
</code>```

Body:
My page has 9 result per page and shows a pagination from 1-5, my problem is how can I hide the pagination number if the result of what I search is one or few entry result?

Sorry If I will not post all my code and thank you for helping me.

sidebar.php

<select name="unit_size_x" class="side-box__select">
    <option value="0" selected>Minimum</option>
    <option value="10">10sqm</option>
    <option value="20">20sqm</option>
    <option value="30">30sqm</option>
    <option value="40">40sqm</option>
    <option value="50">50sqm</option>
    <option value="60">60sqm</option>
    <option value="70">70sqm</option>
    <option value="80">80sqm</option>
    <option value="90">90sqm</option>
    <option value="100">100sqm</option>
</select>

<select name="unit_size_y" class="side-box__select">
    <option value="10">10sqm</option>
    <option value="20">20sqm</option>
    <option value="30">30sqm</option>
    <option value="40">40sqm</option>
    <option value="50">50sqm</option>
    <option value="60">60sqm</option>
    <option value="70">70sqm</option>
    <option value="80">80sqm</option>
    <option value="90">90sqm</option>
    <option value="100">100sqm</option>
   <option value="101" selected>Maximum</option>

</select>

search.php

$metaquerysp[] = array(
'key'=>'unit_size',
'value'=>array( $unit_size_x, $unit_size_y ),
'compare'=>'BETWEEN',
'type'=>'NUMERIC',
);
<?php
    $paged = get_query_var('paged') ? get_query_var('paged') : 1;
    $args = array(
    'post_type' => 'property',
    'posts_per_page' => 9,
    'orderby' => 'DATE',
    'paged' => $paged,
    'meta_query' => $metaquerysp
     );?>

Body:
Hopefully this will make sense. Check $query->post_count for the number of posts returned by your query.

$paged          = get_query_var('paged') ? get_query_var('paged') : 1;
// Posts per page
$posts_per_page = 9;
// Should pagination show (default yes)
$pagination     = true;

$args = array(
    'post_type' => 'property',
    'posts_per_page' => $posts_per_page,
    'orderby' => 'DATE',
    'paged' => $paged,
    'meta_query' => $metaquerysp
);

// Run query
$query =  new WP_Query($args);

// If query has less than $posts_per_page results, no pagination
if($query->post_count<$posts_per_page) {
    $pagination = false;
}

// The loop
if($query->have_posts()) {
    while($query->have_posts()) {
        $query->the_post();

        // Stuff
    }
}

if($pagination) {
    // show pagination
}


问:
arrange 2 array on ascending order - C programming
I got stuck when I am trying to arrange 2 arrays in ascending way.
for example, I have:

```<code>X[] = {4,2,8,2}
Y[] = {12,12,6,12}
</code>```

I would like to arrange X[] in ascending order, but if i change a value place on the array, the same value on Y[] array will change also to the same place.

result:

```<code>X[] = {8,4,2,2}
Y[] = {6,12,12,12}
</code>```

Thanks a lot!

答:
You juste have to, when sorting, moving 2 arrays element at the same time

Here is an exemple with Bubble sort: (with n the length of your array)

```<code>for(int last=0; last<n; last++)
{
    for(int new=0; new<n-1; new++)
    {
        if(X[new]>X[new+1])
        {
            int temp = X[new+1];
            X[new+1] = X[new];
            X[new] = temp;

            temp = Y[new+1];
            Y[new+1] = Y[new];
            Y[new] = temp;
        }
    }
}
</code>```

Just like this (so duplicated in the loop where moving the array's elements)

Body:
I got stuck when I am trying to arrange 2 arrays in ascending way.
for example, I have:

X[] = {4,2,8,2}
Y[] = {12,12,6,12}

I would like to arrange X[] in ascending order, but if i change a value place on the array, the same value on Y[] array will change also to the same place.

result:

X[] = {8,4,2,2}
Y[] = {6,12,12,12}

Thanks a lot!

Body:
You juste have to, when sorting, moving 2 arrays element at the same time

Here is an exemple with Bubble sort: (with n the length of your array)

for(int last=0; last<n; last++)
{
    for(int new=0; new<n-1; new++)
    {
        if(X[new]>X[new+1])
        {
            int temp = X[new+1];
            X[new+1] = X[new];
            X[new] = temp;

            temp = Y[new+1];
            Y[new+1] = Y[new];
            Y[new] = temp;
        }
    }
}

Just like this (so duplicated in the loop where moving the array's elements)


问:
Is it possible to specify that an options is required with boost::program_options?
I can use all other public members of the class typed_value define in value_semantic.hpp such as: default_value, implicit_value, zero_tokens, multitoken, notifier, etc.

But even if the member "required()" is also there, I cannot use it.

I got the error:

```<code>‘class boost::program_options::typed_value<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, char>’ has no member named ‘required’
</code>```

Any ideas?

答: Is your boost version maybe too old? I found required() in the docs for 1.45, but not in the ones for 1.34 - I don't know when it changed.</p>

ContentLicense: CC BY-SA 2.5

Body:
I can use all other public members of the class typed_value define in value_semantic.hpp such as: default_value, implicit_value, zero_tokens, multitoken, notifier, etc.

But even if the member "required()" is also there, I cannot use it.

I got the error:

‘class boost::program_options::typed_value<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, char>’ has no member named ‘required’

Any ideas?


答:
Pick an arbitrary sort function. For instance bubble sort. Modify the function so that the same operations are being made to both.</p>

```<code>void swap(long *a, long *b)
{
  int t=*a;
  *a=*b;
  *b=t;
}

void bubble_sort(long list[], long n, long extra[])
{
  long c, d, t;

  for (c = 0 ; c < ( n - 1 ); c++)
    for (d = 0 ; d < n - c - 1; d++)
      if (list[d] > list[d+1])
      {
        swap(list[d], list[d+1]);
        swap(extra[d], extra[d+1]);
      }
}
</code>```

Title: arrange 2 array on ascending order - C programming

Body:
Pick an arbitrary sort function. For instance bubble sort. Modify the function so that the same operations are being made to both.

void swap(long *a, long *b)
{
  int t=*a;
  *a=*b;
  *b=t;
}

void bubble_sort(long list[], long n, long extra[])
{
  long c, d, t;

  for (c = 0 ; c < ( n - 1 ); c++)
    for (d = 0 ; d < n - c - 1; d++)
      if (list[d] > list[d+1])
      {
        swap(list[d], list[d+1]);
        swap(extra[d], extra[d+1]);
      }
}


问:
Adding content to wordpress page
So, i finally got my css and js scripts to load on WP

Now there is but one thing i need to get done.

i have my own theme, including header.php, footer.php, page.php

header.php and footer.php is working just fine, loading scripts and showing properly, but now i need to add all the other content.

my page.php is currently:

```<code><?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php the_content(); ?>

<?php get_footer(); ?>
</code>```

I would need to somehow add html content to pages, i have about 20 ready made .php pages which needs to be transfered to WP.

Soooo how do i go about making new page (pages -> add new) and using page template while getting the html content to show up?

I've tried to just make new page and in text mode add up all the html into page, but it only shows empty page with header and footer, so the problem is most likely the page.php and i have no idea how to get it to work.

答:
```<code>you can make also a custom loop
 <?php
 $arg = array("post_type" => "services",
                "posts_per_page" => 9,
                "order_by" => "date",
                "order" => "ASC",

            );

            $services = new WP_Query($arg);
            if ($services->have_posts()):;

            while ($services->have_posts()):$services->the_post();
                the_content();
               endwhile;
            endif;
            ?>
</code>```

Title: Adding content to wordpress page

Body:
So, i finally got my css and js scripts to load on WP

Now there is but one thing i need to get done.

i have my own theme, including header.php, footer.php, page.php

header.php and footer.php is working just fine, loading scripts and showing properly, but now i need to add all the other content.

my page.php is currently:

<?php /* Template Name: CustomPageT1 */ ?>

<?php get_header(); ?>

<?php the_content(); ?>

<?php get_footer(); ?>

I would need to somehow add html content to pages, i have about 20 ready made .php pages which needs to be transfered to WP.

Soooo how do i go about making new page (pages -> add new) and using page template while getting the html content to show up?

I've tried to just make new page and in text mode add up all the html into page, but it only shows empty page with header and footer, so the problem is most likely the page.php and i have no idea how to get it to work.


问:
GZip Compression For JQuery Without Server Access
all. I am required to build a website with each page under 130kb. I know that JQuery 1.4.4 is ~28kb when it's g-zipped, but it's 77kb minified, which is just too much for this particular assignment. I have already built the entire site using JQuery in one implementation or another on each page, so scrapping it would mean days of wasted time.

With that in mind,

1) Can I add content headers to a javascript file to add "Content-Encoding: gzip" without modifying config files on the server end? I'm uploading them to the university server, but I don't have access to the configuration. From the response header, the server is: Apache/1.3.26 (UnitedLinux) mod_ssl/2.8.10 OpenSSL/0.9.6g PHP/4.2.2 mod_perl/1.27

2) From the phpinfo file, I know that ZLIB compression is enabled, but "zlib.output_compression" is not.

3) I realize this can be done using .htaccess. However, I'd like to do it any other way, if possible, since I don't want the school thinking I'm trying to modify their server configuration.

4) Will XHR's setrequestheader method work here, or is that only good for asynchronous files?

I know this is short notice and all, but my Final presentation is tomorrow, and I'll lose a ton of points if my site is over the size limit. Any help would be much appreciated!

答:
You have two options

Use jquery hosted somewhere else
that supports gzip. The file is here
that you need to include
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js
This gives you a lot more advantages
such as parallel downloading of
files and quicker page load times.

Other options is to use PHP code to
    zip the jquery js and return it.
    Here is an example
    http://www.lateralcode.com/gzip-files-with-htaccess-and-php/


问:
How do I space out the child elements of a StackPanel?
Given a StackPanel:

```<code><StackPanel>
  <TextBox Height="30">Apple</TextBox>
  <TextBox Height="80">Banana</TextBox>
  <TextBox Height="120">Cherry</TextBox>
</StackPanel>
</code>```

What's the best way to space out the child elements so that there are equally-sized gaps between them, even though the child elements themselves are of different sizes? Can it be done without setting properties on each of the individual children?

答:
Grid.ColumnSpacing, Grid.RowSpacing, StackPanel.Spacing are now on UWP preview, all will allow to better acomplish what is requested here.

These properties are currently only available with the Windows 10 Fall Creators Update Insider SDK, but should make it to the final bits!

Body:
Given a StackPanel:

<StackPanel>
  <TextBox Height="30">Apple</TextBox>
  <TextBox Height="80">Banana</TextBox>
  <TextBox Height="120">Cherry</TextBox>
</StackPanel>

What's the best way to space out the child elements so that there are equally-sized gaps between them, even though the child elements themselves are of different sizes? Can it be done without setting properties on each of the individual children?


问:
Grouping switch statement cases together?
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:

```<code>SELECT CASE Answer
CASE 1, 2, 3, 4
</code>```

Example in C++ (For those that need it):

```<code>#include <iostream.h>
#include <stdio.h>
int main()
{
   int Answer;
   cout << "How many cars do you have?";
   cin >> Answer;
   switch (Answer)
      {
      case 1:
      case 2:
      case 3:
      case 4:
         cout << "You need more cars. ";
         break;
      case 5:
      case 6:
      case 7:
      case 8:
         cout << "Now you need a house. ";
         break;
      default:
         cout << "What are you? A peace-loving hippie freak? ";
      }
      cout << "\nPress ENTER to continue... " << endl;
      getchar();
      return 0;
}
</code>```

答:
gcc has a so-called "case range" extension:

http://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Case-Ranges.html#Case-Ranges

I used to use this when I was only using gcc. Not much to say about it really -- it does sort of what you want, though only for ranges of values.

The biggest problem with this is that only gcc supports it; this may or may not be a problem for you.

(I suspect that for your example an if statement would be a more natural fit.)

Body:
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:

SELECT CASE Answer
CASE 1, 2, 3, 4

Example in C++ (For those that need it):

#include <iostream.h>
#include <stdio.h>
int main()
{
   int Answer;
   cout << "How many cars do you have?";
   cin >> Answer;
   switch (Answer)
      {
      case 1:
      case 2:
      case 3:
      case 4:
         cout << "You need more cars. ";
         break;
      case 5:
      case 6:
      case 7:
      case 8:
         cout << "Now you need a house. ";
         break;
      default:
         cout << "What are you? A peace-loving hippie freak? ";
      }
      cout << "\nPress ENTER to continue... " << endl;
      getchar();
      return 0;
}

OwnerDisplayName: please delete me


问:
Referencing a char* that went out of scope
I recently started programming in C again after having programmed in C++ for a while, and my understanding of pointers is a bit rusty.

I would like to ask why this code is not causing any errors:

```<code>char* a = NULL;
{
    char* b = "stackoverflow";
    a = b;
}

puts(a);
</code>```

I thought that because b went out of scope, a should reference a non-existing memory location, and thus their would be a runtime error when calling printf.

I ran this code in MSVC about 20 times, and no errors were shown.

答:
Other people have explained that this code is perfectly valid.  This answer is about your expectation that, if the code had been invalid, there would have been a runtime error when calling printf.  It isn't necessarily so.

Let's look at this variation on your code, which is invalid:

```<code>#include <stdio.h>
int main(void)
{
    int *a;
    {
        int b = 42;
        a = &b;
    }
    printf("%d\n", *a); // undefined behavior
    return 0;
}
</code>```

This program has undefined behavior, but it happens to be fairly likely that it will, in fact, print 42, for several different reasons — many compilers will leave the stack slot for b allocated for the entire body of main, because nothing else needs the space and minimizing the number of stack adjustments simplifies code generation; even if the compiler did formally deallocate the stack slot, the number 42 probably remains in memory until something else overwrites it, and there's nothing in between a = &b and *a to do that; standard optimizations ("constant and copy propagation") could eliminate both variables and write the last-known value for *a directly into the printf statement (as if you had written printf("%d\n", 42)).

It's absolutely vital to understand that "undefined behavior" does not mean "the program will crash predictably".  It means "anything can happen", and anything includes appearing to work as the programmer probably intended (on this computer, with this compiler, today).

As a final note, none of the aggressive debugging tools I have convenient access to (Valgrind, ASan, UBSan) track "auto" variable lifetimes in sufficient detail to trap this error, but GCC 6 does produce this amusing warning:

```<code>$ gcc -std=c11 -O2 -W -Wall -pedantic test.c
test.c: In function ‘main’:
test.c:9:5: warning: ‘b’ is used uninitialized in this function
    printf("%d\n", *a); // undefined behavior
    ^~~~~~~~~~~~~~~~~~
</code>```

I believe what happened here was, it did the optimization I described above — copying the last known value of b into *a and then into the printf — but its "last known value" for b was a "this variable is uninitialized" sentinel rather than 42.  (It then generates code equivalent to printf("%d\n", 0).)

Body:
I recently started programming in C again after having programmed in C++ for a while, and my understanding of pointers is a bit rusty.

I would like to ask why this code is not causing any errors:

char* a = NULL;
{
    char* b = "stackoverflow";
    a = b;
}

puts(a);

I thought that because b went out of scope, a should reference a non-existing memory location, and thus their would be a runtime error when calling printf.

I ran this code in MSVC about 20 times, and no errors were shown.

Body:
Other people have explained that this code is perfectly valid.  This answer is about your expectation that, if the code had been invalid, there would have been a runtime error when calling printf.  It isn't necessarily so.

Let's look at this variation on your code, which is invalid:

#include <stdio.h>
int main(void)
{
    int *a;
    {
        int b = 42;
        a = &b;
    }
    printf("%d\n", *a); // undefined behavior
    return 0;
}

This program has undefined behavior, but it happens to be fairly likely that it will, in fact, print 42, for several different reasons — many compilers will leave the stack slot for b allocated for the entire body of main, because nothing else needs the space and minimizing the number of stack adjustments simplifies code generation; even if the compiler did formally deallocate the stack slot, the number 42 probably remains in memory until something else overwrites it, and there's nothing in between a = &b and *a to do that; standard optimizations ("constant and copy propagation") could eliminate both variables and write the last-known value for *a directly into the printf statement (as if you had written printf("%d\n", 42)).

It's absolutely vital to understand that "undefined behavior" does not mean "the program will crash predictably".  It means "anything can happen", and anything includes appearing to work as the programmer probably intended (on this computer, with this compiler, today).

As a final note, none of the aggressive debugging tools I have convenient access to (Valgrind, ASan, UBSan) track "auto" variable lifetimes in sufficient detail to trap this error, but GCC 6 does produce this amusing warning:

$ gcc -std=c11 -O2 -W -Wall -pedantic test.c
test.c: In function ‘main’:
test.c:9:5: warning: ‘b’ is used uninitialized in this function
    printf("%d\n", *a); // undefined behavior
    ^~~~~~~~~~~~~~~~~~

I believe what happened here was, it did the optimization I described above — copying the last known value of b into *a and then into the printf — but its "last known value" for b was a "this variable is uninitialized" sentinel rather than 42.  (It then generates code equivalent to printf("%d\n", 0).)


问:
Initially set all checkboxes to checked
I have jquery code that has the ability to set all checkboxes to 'checked' state on the click of a 'check all' checkbox. However, I would like to initially, start a html page by already having all checkboxes checked without having to click on that 'check all' checkbox. Please bear in mind, though, that I would like to keep the 'check all' checkbox since it has the ability to uncheck all checkboxes as well.

Here's my jquery code :

```<code>$('.chk_boxes').click(function(){
    var chk = $(this).attr('checked')?true:false;
    $('.chk_boxes1').attr('checked',chk);
});
</code>```

答:
Change your original function to:

```<code>$('.chk_boxes').click(chkAll());
</code>```

Create a new function:

```<code>function chkAll(){
    var chk = $(this).attr('checked')?true:false;
    $('.chk_boxes1').attr('checked',chk);
}
</code>```

Call the new function when document are ready:

```<code>$(document).ready(function(){
     chkAll();
})
</code>```

Title: Initially set all checkboxes to checked

Body:
I have jquery code that has the ability to set all checkboxes to 'checked' state on the click of a 'check all' checkbox. However, I would like to initially, start a html page by already having all checkboxes checked without having to click on that 'check all' checkbox. Please bear in mind, though, that I would like to keep the 'check all' checkbox since it has the ability to uncheck all checkboxes as well.

Here's my jquery code :

$('.chk_boxes').click(function(){
    var chk = $(this).attr('checked')?true:false;
    $('.chk_boxes1').attr('checked',chk);
});

Body:
Change your original function to:

$('.chk_boxes').click(chkAll());

Create a new function:

function chkAll(){
    var chk = $(this).attr('checked')?true:false;
    $('.chk_boxes1').attr('checked',chk);
}

Call the new function when document are ready:

$(document).ready(function(){
     chkAll();
})


问:
How to delete duplicates in line of text?
I can't find anything on how to do this. I read the documentation on uniq but it only deals with duplicate lines, I need to remove duplicate strings in the same line.

Let's say I have

```<code>TodayToday is an an array
</code>```

I need it to ouput

```<code>Today is an array
</code>```

Thanks!

答:
You can do this with Ruby:

```<code>$ echo 'TodayToday is an an array' | ruby -lape 'gsub(/\b([a-zA-Z ]+)\1/, "\\1")'
Today is an array
</code>```

Given the word boundary, it works with banana:

```<code>$ echo 'TodayToday is an an banana' | ruby -lape 'gsub(/\b([a-zA-Z ]+)\1/, "\\1")'
Today is an banana
</code>```

Similarly with Perl:

```<code>$ echo 'TodayToday is an an banana' | perl -lape 's/\b([a-zA-Z ]+)\1/\1/g'
Today is an banana
</code>```

Since it is essentially the same pattern as Tardis' GNU sed answer, the same observations apply.

Body:
I can't find anything on how to do this. I read the documentation on uniq but it only deals with duplicate lines, I need to remove duplicate strings in the same line.

Let's say I have

TodayToday is an an array

I need it to ouput

Today is an array

Thanks!

Body:
You can do this with Ruby:

$ echo 'TodayToday is an an array' | ruby -lape 'gsub(/\b([a-zA-Z ]+)\1/, "\\1")'
Today is an array

Given the word boundary, it works with banana:

$ echo 'TodayToday is an an banana' | ruby -lape 'gsub(/\b([a-zA-Z ]+)\1/, "\\1")'
Today is an banana

Similarly with Perl:

$ echo 'TodayToday is an an banana' | perl -lape 's/\b([a-zA-Z ]+)\1/\1/g'
Today is an banana

Since it is essentially the same pattern as Tardis' GNU sed answer, the same observations apply.


问:
Blocked loading resource from Open Weather
working on AngularJs application and calling the Open Weather API through $resource, facing the following issue.

Blocked loading resource from url not allowed by $sceDelegate policy.  URL: http://samples.openweathermap.org/data/2.5/forecast

Code

```<code>$scope.weatherAPI = $resource('http://samples.openweathermap.org/data/2.5/forecast',
    { callback: 'JSON_CALLBACK' },
    { get: { method: 'JSONP' } }
);

$scope.weatherResul = $scope.weatherAPI.get({ q: $scope.srchCityName
</code>```

Any Idea, how to fix?

答:
I believe you have to enable the URL as a trusted resource. I never use $resource, so the mechanics might be a bit different, but basically you have to inject $sce and then call  $sce.getTrustedResourceUrl('http://samples.openweathermap.org/data/2.5/forecast'). With $resource you may be able to do this:

```<code>$scope.weatherAPI = $resource($sce.getTrustedResourceUrl('http://samples.openweathermap.org/data/2.5/forecast'),
    { callback: 'JSON_CALLBACK' },
    { get: { method: 'JSONP' } }
);
</code>```

If that doesn't work, then see this answer: $sce.trustAsResourceUrl() globally for a global whitelist solution.

Body:
working on AngularJs application and calling the Open Weather API through $resource, facing the following issue.

Blocked loading resource from url not allowed by $sceDelegate policy.  URL: http://samples.openweathermap.org/data/2.5/forecast

Code

$scope.weatherAPI = $resource('http://samples.openweathermap.org/data/2.5/forecast',
    { callback: 'JSON_CALLBACK' },
    { get: { method: 'JSONP' } }
);

$scope.weatherResul = $scope.weatherAPI.get({ q: $scope.srchCityName

Any Idea, how to fix?

Body:
I believe you have to enable the URL as a trusted resource. I never use $resource, so the mechanics might be a bit different, but basically you have to inject $sce and then call  $sce.getTrustedResourceUrl('http://samples.openweathermap.org/data/2.5/forecast'). With $resource you may be able to do this:

$scope.weatherAPI = $resource($sce.getTrustedResourceUrl('http://samples.openweathermap.org/data/2.5/forecast'),
    { callback: 'JSON_CALLBACK' },
    { get: { method: 'JSONP' } }
);

If that doesn't work, then see this answer: $sce.trustAsResourceUrl() globally for a global whitelist solution.


问:
Which default IdentityType type does the UserPrincipal.FindByIdentity use?
UserPrincipal.FindByIdentity has two overloads. One of these do no specify an IdentityType (but the other does).

Which default IdentityType does this overload actually use underneath?

答:
I believe it searches all identity types.  Of course this means it could find multiple matches in which case a MultipleMatchesException is thrown.

ETA: Confirmed that it does search all of them.  Digging into the code, around line 605:

```<code>                // This is the tricky case.  They didn't specify a UrnScheme, so we need to
                // try all of them.

                string[] urnSchemesToTry = new string[]
                {
                    UrnScheme.SamAccountScheme,
                    UrnScheme.UpnScheme,
                    UrnScheme.DistinguishedNameScheme,
                    UrnScheme.SidScheme,
                    UrnScheme.GuidScheme,
                    UrnScheme.NameScheme
               };
</code>```

Body:
I believe it searches all identity types.  Of course this means it could find multiple matches in which case a MultipleMatchesException is thrown.

ETA: Confirmed that it does search all of them.  Digging into the code, around line 605:

                // This is the tricky case.  They didn't specify a UrnScheme, so we need to
                // try all of them.

                string[] urnSchemesToTry = new string[]
                {
                    UrnScheme.SamAccountScheme,
                    UrnScheme.UpnScheme,
                    UrnScheme.DistinguishedNameScheme,
                    UrnScheme.SidScheme,
                    UrnScheme.GuidScheme,
                    UrnScheme.NameScheme
               };


问:
Can chisel print macros into the RTL
Could you enlight whether there is a way to print macros like

```<code>`synthesis_on
`synthesis_keep_hiear
</code>```

into the RTL?

答: There currently is not. Would you mind filing an issue on the Firrtl repository with more details about your use case?</p>

Title: Can chisel print macros into the RTL

Body:
Could you enlight whether there is a way to print macros like

`synthesis_on
`synthesis_keep_hiear

into the RTL?


问:
Joomla backend, where are the articles and how can I embed php in it?
I have been trying to figure this out for a while now. I'm the head of marketing for an insurance office and I also am in charge of the website. I have meager skills in C and Python, but was handed a webpage with a Joomla backend. Simple enough, it wasn't any trouble. However, joomla doesn't support php in its articles and I have a php email form written I need to embed in an article for an application for insurance. Does anyone know how I could accomplish this? I searched all over the ftp server and there is no area for articles. All I can figure out is that to call the article it is ourwebsite/index.php?option=com_content&view=article&id=86&Itemid=98
Is there any way I can do this? The developer we paid to do the setup did this with a few articles but I need to get more in there. Any help is much appreciated. </p>

答:
Download this extension, and install it via the Extensions > Install link in the admin menu.

http://extensions.joomla.org/extensions/edition/custom-code-in-content/5051

This extension will add a button below the article editor. Clicking the 'Sourcer' button will allow you to paste in the php code. It will then insert the php code in the article.

Before inserting the code, make sure you click in the editor to place the cursor where you would like code to be placed.


问:
Finding the last different position in an array
I have a vector A of dimension 1xn composed of zeros and ones. I want a very efficient way to find the position j of the last element of A such that A(j)~=A(n). If the elements of A are all equal then the code should return n.

Example:

If A=[1 0 1 1 1], I should get 2.

If A=[0 0 0 0 0], I should get 5.

If A=[1 0 0 0 0], I should get 1.

答:
Use find with the last flag. Add a condition if find results in an empty matrix.

```<code>req= find(A~=A(end),1,'last');
if isempty(req) req=length(A); end
</code>```

Body:
Use find with the last flag. Add a condition if find results in an empty matrix.

req= find(A~=A(end),1,'last');
if isempty(req) req=length(A); end


问:
My custom block doesn't show up in the block library
I am developing a custom module in Drupal 8. It shows data regarding some organizations that make use of our service. For this I have created a Controller that shows data from the database, which is put there by another module. From the scarce information and tutorials available on Drupal 8 developement I've been able to create the following. In the .routing.yml file I have created a path to this overview table like so (it doesn't properly copy here but the indents are okay):

```<code>   OrganizationOverview.world:
     path: '/world'
     defaults:
       _controller:      'Drupal\OrganizationOverview\Controller\OrganizationOverviewController::overview'
    _title: 'World'
  requirements:
    _role: 'administrator'
    _permission: 'access content'
</code>```

So now the overview is accessible with the URL site.com/world. But what we want is to show it on the frontpage or show it anywhere else on the site. For this it needs to be a Block. For this I have created an OrganizationOverviewBlock class in OrganizationOverview/src/Plugin/Block/OrganizationOverviewBlock.php which is the proper way according to the PSR-4 standard. The class looks like this:

```<code><?php

namespace Drupal\OrganizationOverview\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a 'OrganizationOverviewBlock' block.
 *
 * @Block(
 *  id = "organization_overview_block",
 *  admin_label = @Translation("OrganizationOverviewBlock"),
 *  category = @Translation("Custom")
 * )
 */
class OrganizationOverviewBlock extends BlockBase
{

    public function build()
    {
        return array(
            '#markup' => 'Hello World',
        );
    }

    public function blockAccess(AccountInterface $account)
    {
        return $account->hasPermission('access content');
    }

}
</code>```

So now it should show up in the Blocks Layout page (after flushing cache, which I do consistently) at site.com/admin/structure/block/ as "Organization Overview Block" where I should enable it, according to plenty sources (Create custom Block, Block API Drupal 8). But it doesn't show up there. I've tried implementing ContainerFactoryPluginInterface with some of those methods but that changes nothing. It does not show up. I've tried making a new test module with a block with the same code but a simpler name and it does not show up. I've copied the code to another platform (the production site) but it also doesn't show up there. What am I doing wrong? Can someone help me? I know Drupal 8 is new but this module really needs to be published soon.

答:
Not require routing file for custom block.

```<code>```
class TestBlock extends BlockBase {

/*
** {@inheritdoc}
*/

public function build() {
   return array(
     '#markup' => $this->t('Welcome page!'),
   );
   }
}
```
</code>```

http://drupalasia.com/article/drupal-8-how-create-custom-block-programatically

Body:
I am developing a custom module in Drupal 8. It shows data regarding some organizations that make use of our service. For this I have created a Controller that shows data from the database, which is put there by another module. From the scarce information and tutorials available on Drupal 8 developement I've been able to create the following. In the .routing.yml file I have created a path to this overview table like so (it doesn't properly copy here but the indents are okay):

   OrganizationOverview.world:
     path: '/world'
     defaults:
       _controller:      'Drupal\OrganizationOverview\Controller\OrganizationOverviewController::overview'
    _title: 'World'
  requirements:
    _role: 'administrator'
    _permission: 'access content'

So now the overview is accessible with the URL site.com/world. But what we want is to show it on the frontpage or show it anywhere else on the site. For this it needs to be a Block. For this I have created an OrganizationOverviewBlock class in OrganizationOverview/src/Plugin/Block/OrganizationOverviewBlock.php which is the proper way according to the PSR-4 standard. The class looks like this:

<?php

namespace Drupal\OrganizationOverview\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a 'OrganizationOverviewBlock' block.
 *
 * @Block(
 *  id = "organization_overview_block",
 *  admin_label = @Translation("OrganizationOverviewBlock"),
 *  category = @Translation("Custom")
 * )
 */
class OrganizationOverviewBlock extends BlockBase
{

    public function build()
    {
        return array(
            '#markup' => 'Hello World',
        );
    }

    public function blockAccess(AccountInterface $account)
    {
        return $account->hasPermission('access content');
    }

}

So now it should show up in the Blocks Layout page (after flushing cache, which I do consistently) at site.com/admin/structure/block/ as "Organization Overview Block" where I should enable it, according to plenty sources (Create custom Block, Block API Drupal 8). But it doesn't show up there. I've tried implementing ContainerFactoryPluginInterface with some of those methods but that changes nothing. It does not show up. I've tried making a new test module with a block with the same code but a simpler name and it does not show up. I've copied the code to another platform (the production site) but it also doesn't show up there. What am I doing wrong? Can someone help me? I know Drupal 8 is new but this module really needs to be published soon.

Body:
Not require routing file for custom block.

<pre>
class TestBlock extends BlockBase {

/*
** {@inheritdoc}
*/

public function build() {
   return array(
     '#markup' => $this->t('Welcome page!'),
   );
   }
}
</pre>

http://drupalasia.com/article/drupal-8-how-create-custom-block-programatically


问:
Exclude files from build in Angular 2
How to exclude files from the Angular build using Angular-CLI. I've just added the path to exclude in the tsconfig.json and tsconfig.app.json files,  but when I run ng serve, Angular is still trying to compile the files.

Any ideas?

答:
Using exclude property of tsconfig.json (at root level), i.e.:

{
   "exclude": [
       "node_modules",
       "**/*.spec.ts"
   ]
}
```

Title: Exclude files from build in Angular 2


问:
iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)
On our internal network, we use a self-signed CA certificate. This has worked fine for years, in both Safari and our iOS product, all the way through iOS 10. We simply install the CA certificate on any new device or simulator and everything works, even with ATS. This allows access to all of our internal test servers without having to trust each server individually.

Starting with iOS 11 the installed CA certificate no longer allows Safari or our app to trust the certificate for any of the servers. We receive the following relevant details with CFNETWORK_DIAGNOSTICS enabled for our app:

Error Domain=kCFErrorDomainCFNetwork Code=-1200

_kCFNetworkCFStreamSSLErrorOriginalValue=-9802

_kCFStreamErrorDomainKey=3

_kCFStreamErrorCodeKey=-9802

NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made.

NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?

I spent considerable time trying to resolve this issue, scouring StackOverflow and the rest of the web. Although we use AFNetworking in our app, that seems to be irrelevant, as Safari no longer trusts these servers via the CA. Disabling ATS via NSAllowsArbitraryLoads allows access to the servers, but obviously isn't a solution.

No changes have been made to our -URLSession:didReceiveChallenge:completionHandler code, and we have a proper (worked for years) implementation of challenge response via challenge.protectionSpace.serverTrust.

I have re-evaluated and tested both the CA and server certificates every way I can think of, and they work everywhere except iOS 11. What might have changed in ATS for iOS 11 that could cause this issue?

答:
While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).

I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.

I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.

If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.

Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.

Update 2: Same solution seems to be needed on iOS 13 beta builds as well.


问:
Send Biztalk message context to WCF service
When using the WCF adapter, I have the message body part being send as the body of the WCF message, but can I do to get the Biztalk message context to be sent as well (hopefully within the WCF message header)?</p>

答:
The following page in MSDN succinctly explains how you can use custom SOAP headers when sending messages outside BizTalk with the WCF adapters.

Basically, you cannot directly send the context of your BizTalk messages outside BizTalk. This would be meaningless. Rather, you can select a subset of the properties in the context of your BizTalk messages to be sent to the WCF adapter through custom SOAP headers.

Handling Custom SOAP Headers Outgoing WCF Request

SOAP headers associated with an outgoing request must explicitly be written to the context of the outgoing message.

When using the WCF Adapters, SOAP Headers are defined with the built-in WCF.OutboundCustomHeaders context property. This property holds all custom SOAP headers, wrapped inside an additional <headers> tag.

Headers can be specified from within an orchestration with the following syntax in an Expression shape:

```<code>OutboundMessage(WCF.OutboundCustomHeaders) = "" +
  "<headers>"
  "<tns1:Header1 xmlns:tns1='http://tns1'>" +
  "</tns1:Header1>" +
  "<tns2:Header2 xmlns:tns2='http://tns2'>" +
  "</tns2:Header2>" +
  "</headers>" +
  "";
</code>```

Please, note that the custom SOAP Headers <tns1:Header1> and <tns2:Header2> used for illustration purposes above must be part of your WCF service contract. When you create a service reference for the consumed WCF service, those custom SOAP headers will be available as generated schemas in your orchestration.

How to Send Specific Context Properties in Custom SOAP Header

Now that you know how to specify custom SOAP Headers, you can use this syntax to send specific properties from the context of your messages to the custom SOAP headers like so:

```<code>OutboundMessage(WCF.OutboundCustomHeaders) =
  System.String.Format(
    "" +
    "<headers>"
    "<tns1:Header1 xmlns:tns1='http://tns1'>" +
    "  <tns1:Property1>{0}</tns1:Property1>" +
    "  <tns1:Property2>{1}</tns1:Property2>" +
    "</tns1:Header1>" +
    "</headers>" +
    ""
  , InboundMessage(FILE.ReceivedFileName)
  , InboundMessage(BTS.MessageType)
  ));
</code>```

In the example above, the two builtin context properties FILE.ReceivedFileName and BTS.MessageType have been selected and written inside the custom SOAP header. In a real world scenario, you would want to check whether the properties exist in the context before using them.

You can also use any custom context property, provided they have been declared in an appropriate Property Schema.

Body:
The following page in MSDN succinctly explains how you can use custom SOAP headers when sending messages outside BizTalk with the WCF adapters.

Basically, you cannot directly send the context of your BizTalk messages outside BizTalk. This would be meaningless. Rather, you can select a subset of the properties in the context of your BizTalk messages to be sent to the WCF adapter through custom SOAP headers.

Handling Custom SOAP Headers Outgoing WCF Request

SOAP headers associated with an outgoing request must explicitly be written to the context of the outgoing message.

When using the WCF Adapters, SOAP Headers are defined with the built-in WCF.OutboundCustomHeaders context property. This property holds all custom SOAP headers, wrapped inside an additional <headers> tag.

Headers can be specified from within an orchestration with the following syntax in an Expression shape:

OutboundMessage(WCF.OutboundCustomHeaders) = "" +
  "<headers>"
  "<tns1:Header1 xmlns:tns1='http://tns1'>" +
  "</tns1:Header1>" +
  "<tns2:Header2 xmlns:tns2='http://tns2'>" +
  "</tns2:Header2>" +
  "</headers>" +
  "";

Please, note that the custom SOAP Headers <tns1:Header1> and <tns2:Header2> used for illustration purposes above must be part of your WCF service contract. When you create a service reference for the consumed WCF service, those custom SOAP headers will be available as generated schemas in your orchestration.

How to Send Specific Context Properties in Custom SOAP Header

Now that you know how to specify custom SOAP Headers, you can use this syntax to send specific properties from the context of your messages to the custom SOAP headers like so:

OutboundMessage(WCF.OutboundCustomHeaders) =
  System.String.Format(
    "" +
    "<headers>"
    "<tns1:Header1 xmlns:tns1='http://tns1'>" +
    "  <tns1:Property1>{0}</tns1:Property1>" +
    "  <tns1:Property2>{1}</tns1:Property2>" +
    "</tns1:Header1>" +
    "</headers>" +
    ""
  , InboundMessage(FILE.ReceivedFileName)
  , InboundMessage(BTS.MessageType)
  ));

In the example above, the two builtin context properties FILE.ReceivedFileName and BTS.MessageType have been selected and written inside the custom SOAP header. In a real world scenario, you would want to check whether the properties exist in the context before using them.

You can also use any custom context property, provided they have been declared in an appropriate Property Schema.


问:
what regular expression can extract data I need?
I have a string

```<code>url = '//item.taobao.com/item.htm?id\u003d528341191030\u0026ns\u003d1\u0026abbucket\u003d0#detail'
</code>```

I like to extract the number 528341191030 between the first two \u. I tried this,

```<code>m = re.search('\?id\u\d+d(\d+?)\u', url)
if m:
  print m.group(1)
</code>```

But it doesn't work. What is wrong with my solution?

答:
Are you sure you need regex?
Here is a solution using split:

```<code>url.split("\u")[1].split("d")[-1]
'528341191030'
</code>```

In terms of what is wrong with your regex, "\" is a special character, so you should use "\\" for backslash (so " \\\u" instead of "\u"):

```<code>m = re.search('\?id\\\u\d+d(\d+?)\\\u', url)
if m:
  print m.group(1)
</code>```

Gives: 528341191030

Docs:

Regular expressions use the backslash character ('\') to indicate
  special forms or to allow special characters to be used without
  invoking their special meaning. This collides with Python’s usage of
  the same character for the same purpose in string literals; for
  example, to match a literal backslash, one might have to write '\\'
  as the pattern string, because the regular expression must be \, and
  each backslash must be expressed as \ inside a regular Python string
  literal.

Or,use Raw String Notation

```<code>m = re.search(r"\?id\\u\d+d(\d+?)\\u", url)
if m:
    print m.group(1)
</code>```

Body:
I have a string

url = '//item.taobao.com/item.htm?id\u003d528341191030\u0026ns\u003d1\u0026abbucket\u003d0#detail'

I like to extract the number 528341191030 between the first two \u. I tried this,

m = re.search('\?id\u\d+d(\d+?)\u', url)
if m:
  print m.group(1)

But it doesn't work. What is wrong with my solution?

Body:
Are you sure you need regex?
Here is a solution using split:

url.split("\u")[1].split("d")[-1]
'528341191030'

In terms of what is wrong with your regex, "\" is a special character, so you should use "\\" for backslash (so " \\\u" instead of "\u"):

m = re.search('\?id\\\u\d+d(\d+?)\\\u', url)
if m:
  print m.group(1)

Gives: 528341191030

Docs:

Regular expressions use the backslash character ('\') to indicate
  special forms or to allow special characters to be used without
  invoking their special meaning. This collides with Python’s usage of
  the same character for the same purpose in string literals; for
  example, to match a literal backslash, one might have to write '\\'
  as the pattern string, because the regular expression must be \, and
  each backslash must be expressed as \ inside a regular Python string
  literal.

Or,use Raw String Notation

m = re.search(r"\?id\\u\d+d(\d+?)\\u", url)
if m:
    print m.group(1)


问:
why cannot using POI to manipute excel?
```<code>result = cell.getRichStringCellValue().toString();
</code>```

<p>If there is a line breaks in one cell. How to handle this result? </p>

Title: why cannot using POI to manipute excel?

Body:
result = cell.getRichStringCellValue().toString();

If there is a line breaks in one cell. How to handle this result?

Body: row.Cells[i].SetCellValue(MyValues[i].Replace("\r\n", " "));


问:
Spring-data-mongodb generic type
Let's say we have a simple document type defined in mongodb：

```<code>{
  _id : OjbectId(xxx),
  value : A
}
</code>```

But the value A here could be float, integer, boolean or string. How can I map it into a java entity?

Here's a template which only mapped _id:

```<code>@Document(collection = "my_document")
public class MyDocument {
  @Id
  private String id;

  public String getId() {
    return this.id;
  }

  public void setId(String id) {
    this.id = id;
  }
}
</code>```

Thanks.

答:
As @titogeo said in a comment, you could use Object like a generic type as it's the super type of all types.

You can read more about data mapping conversion in
Spring Data MongoDB - Reference Documentation - Mapping.

Title: Spring-data-mongodb generic type

Body:
Let's say we have a simple document type defined in mongodb：

{
  _id : OjbectId(xxx),
  value : A
}

But the value A here could be float, integer, boolean or string. How can I map it into a java entity?

Here's a template which only mapped _id:

@Document(collection = "my_document")
public class MyDocument {
  @Id
  private String id;

  public String getId() {
    return this.id;
  }

  public void setId(String id) {
    this.id = id;
  }
}

Thanks.


问:
How to make SearchView always expanded in android?
I have SearchView in the top of the layout (not in the action bar), is there anyway to force this View to be always expanded (opened)?

If not, i wish to place fancy image near it, is there anyway to make SearchView hide this image when expanded (clicked/expanded)?

答:
I am doing this into fragment ,
i done it by using

```<code>searchItem.expandActionView();
</code>```

but when user press back button it collapse so in collapse method i used

```<code>getActivity().getSupportFragmentManager().popBackStack();
// when it collapsed i am going back
</code>```

Below is my solution in detail:

search_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/search_contacts"
        android:title="search"
        android:icon="@drawable/search2"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView" >
    </item>
</menu>
</code>```

in fragment i used below code :

```<code>@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.search_menu, menu);

        // Define the listener
        MenuItemCompat.OnActionExpandListener expandListener = new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item)
            {
                getActivity().getSupportFragmentManager().popBackStack();
                // Do something when action item collapses
                return true;  // Return true to collapse action view
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item)
            {

                // Do something when expanded
                return true;  // Return true to expand action view
            }
        };

        MenuItem searchItem = menu.findItem(R.id.search_contacts);

        // Assign the listener to that action item
        MenuItemCompat.setOnActionExpandListener(searchItem, expandListener);

        // Any other things you have to do when creating the options menu…

        SearchView searchView =
                (SearchView) MenuItemCompat.getActionView(searchItem);
        //searchView.setIconifiedByDefault(false);
        searchItem.expandActionView(); // when fragment opens it expanded auto

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText)
            {
                seachViewFunction(newText); // in searchViewFunction(newText); i am doing my things
                return false;
            }
        });

        super.onCreateOptionsMenu(menu, inflater);
    }
</code>```

Body:
I am doing this into fragment ,
i done it by using

searchItem.expandActionView();

but when user press back button it collapse so in collapse method i used

getActivity().getSupportFragmentManager().popBackStack();
// when it collapsed i am going back

Below is my solution in detail:

search_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/search_contacts"
        android:title="search"
        android:icon="@drawable/search2"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView" >
    </item>
</menu>

in fragment i used below code :

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.search_menu, menu);

        // Define the listener
        MenuItemCompat.OnActionExpandListener expandListener = new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item)
            {
                getActivity().getSupportFragmentManager().popBackStack();
                // Do something when action item collapses
                return true;  // Return true to collapse action view
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item)
            {

                // Do something when expanded
                return true;  // Return true to expand action view
            }
        };

        MenuItem searchItem = menu.findItem(R.id.search_contacts);

        // Assign the listener to that action item
        MenuItemCompat.setOnActionExpandListener(searchItem, expandListener);

        // Any other things you have to do when creating the options menu…

        SearchView searchView =
                (SearchView) MenuItemCompat.getActionView(searchItem);
        //searchView.setIconifiedByDefault(false);
        searchItem.expandActionView(); // when fragment opens it expanded auto

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText)
            {
                seachViewFunction(newText); // in searchViewFunction(newText); i am doing my things
                return false;
            }
        });

        super.onCreateOptionsMenu(menu, inflater);
    }