问:
Running R from cmd in windows
I'm trying to install rtools, so that I can install another package (Google's causalimpact)  and the process has indicated I have a problem with my path environment for R.

Main issue

I can't run R from the cmd window.

The expected behaviour is to output below and give > prompt:

```<code>R version 3.1.1 (blah blah)

...

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
</code>```

However the actual result is:

```<code>'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Additional info

I can however run Rcmd and Rgui (everything apart from R) from cmd without error.

Where R prints output C:\Program Files\R\R-3.1.1\bin\x64\R.exe

Where Rcmd prints output C:\Program Files\R\R-3.1.1\bin\x64\Rcmd.exe

Where Rgui prints output C:\Program Files\R\R-3.1.1\bin\x64\Rgui.exe

Return the same paths pointing to their respective exe files.

This is clearly a problem with my global environment paths, but I cant see why it would produce this error

The paths look like (the R path on the last line) :

```<code>     c:\Rtools\bin
     c:\Rtools\gcc-4.6.3\bin
     C:\RBuildTools\3.1\bin
     C:\RBuildTools\3.1\gcc-4.6.3\bin
     c:\Rtools\bin
     c:\Rtools\gcc-4.6.3\bin
     C:\Python27\
     C:\Python34\
     C:\Python34\Scripts
     C:\Program Files (x86)\Intel\iCLS Client\
     C:\Program Files\Intel\iCLS Client\
     C:\windows\system32
     C:\windows
     C:\windows\System32\Wbem
     C:\windows\System32\WindowsPowerShell\v1.0\
     C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x86
     C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x64
     C:\Program Files\Intel\Intel(R) Management Engine Components\DAL
     C:\Program Files\Intel\Intel(R) Management Engine Components\IPT
     C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL
     C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT
     C:\Program Files (x86)\QuickTime\QTSystem\
     c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\
     c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\
     c:\Program Files\Microsoft SQL Server\100\Tools\Binn\
     c:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\
     C:\strawberry\c\bin
     C:\strawberry\perl\site\bin
     C:\strawberry\perl\bin
     C:\Program Files\MiKTeX 2.9\miktex\bin\x64\
     C:\Program Files\MiKTeX 2.9\miktex\bin\x64\
     C:\Program Files\R\R-3.1.1\bin\x64
</code>```

I can run Python and Perl from just typing either's name into the cmd window, and as R is pointed to in the same way I can't understand the above error.

If anyone has any suggestions on how I can fix this error I would be very grateful.

I've not asked a question of this nature on here before so any editing / pointers greatly appreciated too.

The raw path:

```<code>PATH=C:\Program Files\R\R-3.1.1\bin\x64;C:\Program Files\R\R-3.1.1\bin\x64;c:\Rt
ools\bin;c:\Rtools\gcc-4.6.3\bin;C:\RBuildTools\3.1\bin;C:\RBuildTools\3.1\gcc-4
.6.3\bin;c:\Rtools\bin;c:\Rtools\gcc-4.6.3\bin;C:\Python27\;C:\Python34\;C:\Pyth
on34\Scripts;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iC
LS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\Sy
stem32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x
86;C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x64;C:\Program Files\Intel\In
tel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Manageme
nt Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine
 Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Componen
ts\IPT;C:\Program Files (x86)\QuickTime\QTSystem\;c:\Program Files (x86)\Microso
ft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;c:\Program Files (x86)\Microso
ft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Bi
nn\;c:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\;C:\strawberry\c\bi
n;C:\strawberry\perl\site\bin;C:\strawberry\perl\bin;C:\Program Files\MiKTeX 2.9
\miktex\bin\x64\;C:\Program Files\MiKTeX 2.9\miktex\bin\x64\;C:\Users\Tariq.Muma
n\AppData\Local\Pandoc\
</code>```

答:
It's really simple. Just like how you set JDK Path variable for Java , you set R path as :

Path="C:\Program Files\R\R-3.4.2\bin\"

in the Edit System Environment variables in Control Panel.

Check if it works!

Title: Running R from cmd in windows

Body:
I'm trying to install rtools, so that I can install another package (Google's causalimpact)  and the process has indicated I have a problem with my path environment for R.

Main issue

I can't run R from the cmd window.

The expected behaviour is to output below and give > prompt:

R version 3.1.1 (blah blah)

...

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

However the actual result is:

'C:\Program' is not recognized as an internal or external command,
operable program or batch file.

Additional info

I can however run Rcmd and Rgui (everything apart from R) from cmd without error.

Where R prints output C:\Program Files\R\R-3.1.1\bin\x64\R.exe

Where Rcmd prints output C:\Program Files\R\R-3.1.1\bin\x64\Rcmd.exe

Where Rgui prints output C:\Program Files\R\R-3.1.1\bin\x64\Rgui.exe

Return the same paths pointing to their respective exe files.

This is clearly a problem with my global environment paths, but I cant see why it would produce this error

The paths look like (the R path on the last line) :

     c:\Rtools\bin
     c:\Rtools\gcc-4.6.3\bin
     C:\RBuildTools\3.1\bin
     C:\RBuildTools\3.1\gcc-4.6.3\bin
     c:\Rtools\bin
     c:\Rtools\gcc-4.6.3\bin
     C:\Python27\
     C:\Python34\
     C:\Python34\Scripts
     C:\Program Files (x86)\Intel\iCLS Client\
     C:\Program Files\Intel\iCLS Client\
     C:\windows\system32
     C:\windows
     C:\windows\System32\Wbem
     C:\windows\System32\WindowsPowerShell\v1.0\
     C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x86
     C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x64
     C:\Program Files\Intel\Intel(R) Management Engine Components\DAL
     C:\Program Files\Intel\Intel(R) Management Engine Components\IPT
     C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL
     C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT
     C:\Program Files (x86)\QuickTime\QTSystem\
     c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\
     c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\
     c:\Program Files\Microsoft SQL Server\100\Tools\Binn\
     c:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\
     C:\strawberry\c\bin
     C:\strawberry\perl\site\bin
     C:\strawberry\perl\bin
     C:\Program Files\MiKTeX 2.9\miktex\bin\x64\
     C:\Program Files\MiKTeX 2.9\miktex\bin\x64\
     C:\Program Files\R\R-3.1.1\bin\x64

I can run Python and Perl from just typing either's name into the cmd window, and as R is pointed to in the same way I can't understand the above error.

If anyone has any suggestions on how I can fix this error I would be very grateful.

I've not asked a question of this nature on here before so any editing / pointers greatly appreciated too.

The raw path:

PATH=C:\Program Files\R\R-3.1.1\bin\x64;C:\Program Files\R\R-3.1.1\bin\x64;c:\Rt
ools\bin;c:\Rtools\gcc-4.6.3\bin;C:\RBuildTools\3.1\bin;C:\RBuildTools\3.1\gcc-4
.6.3\bin;c:\Rtools\bin;c:\Rtools\gcc-4.6.3\bin;C:\Python27\;C:\Python34\;C:\Pyth
on34\Scripts;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iC
LS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\Sy
stem32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x
86;C:\Program Files (x86)\Intel\OpenCL SDK\3.0\bin\x64;C:\Program Files\Intel\In
tel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Manageme
nt Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine
 Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Componen
ts\IPT;C:\Program Files (x86)\QuickTime\QTSystem\;c:\Program Files (x86)\Microso
ft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;c:\Program Files (x86)\Microso
ft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Bi
nn\;c:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\;C:\strawberry\c\bi
n;C:\strawberry\perl\site\bin;C:\strawberry\perl\bin;C:\Program Files\MiKTeX 2.9
\miktex\bin\x64\;C:\Program Files\MiKTeX 2.9\miktex\bin\x64\;C:\Users\Tariq.Muma
n\AppData\Local\Pandoc\


来源: stackexchange

问:
Uploading venv folder on github
Is it necessary to upload venv folder that itself contains 100's of files along with other folders and files of the same project to GitHub?  </p>

答: Simple answer no. In your gitignore file add the venv to ignore all the files inside your venv fold. Basically your venv fold store all the dependency for your projects, you could use pip freeze to generate the requirement.txt which others can use this file to reproduce the same environment as you did. Plus, the files inside your venv will be huge because it contains entire packages you installed. </p>

ContentLicense: CC BY-SA 3.0

Title: Uploading venv folder on github


问:
Cross-Process Mutex Read/Write Locking
I'm trying to make inter-process communication in C/C++ on Windows environment.

I am creating a shared memory page file and two processes get the handle to that file. It's like this:

Process1: Initialize shared memory area. Wait for Process2 to fill it.

Process2: Get handle to shared memory area. Put stuff in it.

I am creating a named mutex in process1 as well. Now process1 acquires the ownership of the mutex soon after creating it (using WaitSingleObject). Obviously, there is nothing in the memory area so I need to release the mutex. Now I need to wait until the memory is filled instead of trying to acquire the mutex again.

I was thinking of conditional variables. Process2 signals the condition variable once it fills in the memory area and process1 will acquire the information immediately.

However, as per MS Documentation on Condition Variables, they are not shared across processes which is clear from their initialization as they are not named.

Furthermore, the shared memory area can hold up to one element at any given moment which means process2 cannot refill after filling it unless process1 extracts its information.

From the given description it's clear that condition variables are the best for this purpose (or Monitors). So is there a way around this?

答:
Conditional variables can be used with in the process, but not across the processes.

Try NamedPipe with PIPE_ACCESS_DUPLEX as open mode. So that you have communication options from both process.

https://msdn.microsoft.com/en-us/library/windows/desktop/aa365150(v=vs.85).aspx

Title: Cross-Process Mutex Read/Write Locking


问:
Click on a specific button or refresh page if button doesn't appear after a while
I have followed this thread and it's excellent: How do I click on this button with Greasemonkey?

But I need a script on Greasemonkey to:

Start script

Each 1 minute script reloads page (so, *setTimeout(function(){ location.reload(); }, 60*1000);* )

IF, after reload, on the page appears the button with text "Eureka", click on button and end script

IF NOT appears the button with text "Eureka", again reload page, check for button with that specific text, if still not appears reload page etc

Code script to click on button when text appears, and it works without problems:

```<code>// ==UserScript==
// @name     _Click on a specific link
// @include  http://www.mypage.com*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design change
introduced in GM 1.0.
It restores the sandbox.
*/

//--- Note that contains() is CASE-SENSITIVE.
waitForKeyElements ("span:contains('Eureka')", clickOnFollowButton);

function clickOnFollowButton (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}
</code>```

I think I need use conditionals; but I don't know where and how. :(

I tried:

```<code>// ==UserScript==
// @name     _Click on a specific link
// @include  http://www.mypage.com*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design change
introduced in GM 1.0.
It restores the sandbox.
*/
//--- Note that contains() is CASE-SENSITIVE.

var FREQUENCY = 60*1000;

function clickOnFollowButton (jNode) {
    if ("span:contains('Eureka')") {
        var clickEvent  = document.createEvent ('MouseEvents');
        clickEvent.initEvent ('click', true, true);
        jNode[0].dispatchEvent (clickEvent);
    }
    else {
        window.setTimeout(window.location.reload, FREQUENCY);
    }
}
</code>```

答:
I can boil the question's stated logic down to:

Wait for the button for 1 minute.

If it's found, click it.

Otherwise reload the page.

If that's true, then simplified logic can be used.

BUT, If clicking the button also causes the page itself to reload, or if something else is going on, then you will need to use GM_setValue to transmit state information from one script instance to the next. (Each reload starts the script over, same as a new page load.)

Next, the second code-block doesn't work for a few reasons, and it checks for the element right away, not allowing it to AJAX-in.  It needs to check at the end of the timer run.

The simplest way to do that is with a global state variable.

Code like this should work, based on the question, and provided you haven't omitted "But" criteria as listed above:

```<code>// ==UserScript==
// @name     _Click on a specific link, refresh if it doesn't appear
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

const reloadFrequency   = 60*1000;  //  60 seconds
let buttonWasFound      = false;

//--- Note that contains() is CASE-SENSITIVE.
waitForKeyElements ("span:contains('Eureka')", clickOnFollowButton);

setTimeout (reloadOnlyIfButtonMissing, reloadFrequency);

function clickOnFollowButton (jNode) {
    buttonWasFound  = true;

    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

function reloadOnlyIfButtonMissing () {
    if ( ! buttonWasFound) {
        location.reload;  //  This kills script instance.
    }
}
</code>```

Body:
I have followed this thread and it's excellent: How do I click on this button with Greasemonkey?

But I need a script on Greasemonkey to:

Start script

Each 1 minute script reloads page (so, *setTimeout(function(){ location.reload(); }, 60*1000);* )

IF, after reload, on the page appears the button with text "Eureka", click on button and end script

IF NOT appears the button with text "Eureka", again reload page, check for button with that specific text, if still not appears reload page etc

Code script to click on button when text appears, and it works without problems:

// ==UserScript==
// @name     _Click on a specific link
// @include  http://www.mypage.com*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design change
introduced in GM 1.0.
It restores the sandbox.
*/

//--- Note that contains() is CASE-SENSITIVE.
waitForKeyElements ("span:contains('Eureka')", clickOnFollowButton);

function clickOnFollowButton (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

I think I need use conditionals; but I don't know where and how. :(

I tried:

// ==UserScript==
// @name     _Click on a specific link
// @include  http://www.mypage.com*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design change
introduced in GM 1.0.
It restores the sandbox.
*/
//--- Note that contains() is CASE-SENSITIVE.

var FREQUENCY = 60*1000;

function clickOnFollowButton (jNode) {
    if ("span:contains('Eureka')") {
        var clickEvent  = document.createEvent ('MouseEvents');
        clickEvent.initEvent ('click', true, true);
        jNode[0].dispatchEvent (clickEvent);
    }
    else {
        window.setTimeout(window.location.reload, FREQUENCY);
    }
}

Body:
I can boil the question's stated logic down to:

Wait for the button for 1 minute.

If it's found, click it.

Otherwise reload the page.

If that's true, then simplified logic can be used.

BUT, If clicking the button also causes the page itself to reload, or if something else is going on, then you will need to use GM_setValue to transmit state information from one script instance to the next. (Each reload starts the script over, same as a new page load.)

Next, the second code-block doesn't work for a few reasons, and it checks for the element right away, not allowing it to AJAX-in.  It needs to check at the end of the timer run.

The simplest way to do that is with a global state variable.

Code like this should work, based on the question, and provided you haven't omitted "But" criteria as listed above:

// ==UserScript==
// @name     _Click on a specific link, refresh if it doesn't appear
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

const reloadFrequency   = 60*1000;  //  60 seconds
let buttonWasFound      = false;

//--- Note that contains() is CASE-SENSITIVE.
waitForKeyElements ("span:contains('Eureka')", clickOnFollowButton);

setTimeout (reloadOnlyIfButtonMissing, reloadFrequency);

function clickOnFollowButton (jNode) {
    buttonWasFound  = true;

    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

function reloadOnlyIfButtonMissing () {
    if ( ! buttonWasFound) {
        location.reload;  //  This kills script instance.
    }
}


问:
Functions from external source in CPP not being found(Qt)
In Qt, I want a particular function to run when I click a button. So I made a button and used the "connect()" function to run some subroutine "initializeButtonPushed"

```<code>void MainWindow::initializeButtonPushed(){
    initializePlatform();
}
</code>```

simple enough. In the file "mainwindow.h" there is a line

```<code>#include "platform.h"
</code>```

and inside platform.h is the definition "void initializePlatform(void);"

also in my c sources I have a platform.c file which has the actual code for this function.

In addition to this, I can already see that the .pro file for my Qt project has those files included.

So given this, it seems like the compiler should be able to find those files, but when I try compiling my code, I get error:

```<code>undefined reference to 'initializePlatform()'
collect2:error: ld returned 1 exit status
</code>```

I don't know much about cpp, I usually use C but needed Qt for this program, so maybe I am missing something, but I don't see why it says my function is undefined when I can see the source file as part of my project and know the code for it is in that file.

答:
you need this

```<code>extern "C"{

#include "platform.h"
}
</code>```

this allows the c++ compiler and linker to correctly link function written in c

Body:
In Qt, I want a particular function to run when I click a button. So I made a button and used the "connect()" function to run some subroutine "initializeButtonPushed"

void MainWindow::initializeButtonPushed(){
    initializePlatform();
}

simple enough. In the file "mainwindow.h" there is a line

#include "platform.h"

and inside platform.h is the definition "void initializePlatform(void);"

also in my c sources I have a platform.c file which has the actual code for this function.

In addition to this, I can already see that the .pro file for my Qt project has those files included.

So given this, it seems like the compiler should be able to find those files, but when I try compiling my code, I get error:

undefined reference to 'initializePlatform()'
collect2:error: ld returned 1 exit status

I don't know much about cpp, I usually use C but needed Qt for this program, so maybe I am missing something, but I don't see why it says my function is undefined when I can see the source file as part of my project and know the code for it is in that file.

Body:
you need this

extern "C"{

#include "platform.h"
}

this allows the c++ compiler and linker to correctly link function written in c


问:
How to select a button beside the gradient filter
I met a project that set the gradient filter to whole web page.

So I have implemented the filter like this.jsfiddle

HTML

```<code><div class="container">
   <button class="tag">Featured</button>
   <div id="grad1">
</div>
</code>```

CSS

```<code>#grad1 {
    height: 200px;
    background: red; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(red, yellow); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(red, yellow); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(red, yellow); /* For Firefox 3.6 to 15 */
    background: linear-gradient(red, yellow); /* Standard syntax (must be last) */
    opacity: 0.5;
}
.container {
   border: 1px solid #DDDDDD;
   width: 200px;
   height: 200px;
   position: relative;
}
.tag {
   float: left;
   position: absolute;
   left: 0px;
   top: 0px;
   background-color: #92AD40;
   padding: 5px;
   color: #FFFFFF;
   font-weight: bold;
}
</code>```

But the problem is button is not selectable in this case.
I have no sense how to make the button work.
How can I make button selectable and also show gradient above the button?

Finally UI should look like this.

答:
its seems you are looking for pointer-events: none;

Demo http://jsfiddle.net/r6tdc3Lh/5/

Body:
I met a project that set the gradient filter to whole web page.

So I have implemented the filter like this.jsfiddle

HTML

   <button class="tag">Featured</button>

CSS

#grad1 {
    height: 200px;
    background: red; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(red, yellow); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(red, yellow); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(red, yellow); /* For Firefox 3.6 to 15 */
    background: linear-gradient(red, yellow); /* Standard syntax (must be last) */
    opacity: 0.5;
}
.container {
   border: 1px solid #DDDDDD;
   width: 200px;
   height: 200px;
   position: relative;
}
.tag {
   float: left;
   position: absolute;
   left: 0px;
   top: 0px;
   background-color: #92AD40;
   padding: 5px;
   color: #FFFFFF;
   font-weight: bold;
}

But the problem is button is not selectable in this case.
I have no sense how to make the button work.
How can I make button selectable and also show gradient above the button?

Finally UI should look like this.


问:
Bash script check time differnce between two directory
I am looking for a bash script to who check time difference between two directory? But in $oldtime i can`t get only 20:09:24 i get this "20:09:24.660157390".
How can i get only hours:min only.</p>

```<code>#!/bin/bash

oldtime=$(stat -c %y /mnt/dir1| awk '{print $2}' )
ctime=$(date | awk '{print $4}')

DIFF=$($oldtime-$ctime)
if [ $DIFF > 600 ]; then
    echo "This directory have more that 10 min"
fi
</code>```

答:
Use epoch timestamp and date for converting to that format.

```<code>$ date +%H:%M -d @`stat -c %Y /tmp/`
19:19
</code>```

But it's not recommended to use this format for comparing. Use unix timestamps instead:

```<code>if [ $(( $(date +%s) - $(stat -c %Y /tmp) )) -gt 600 ]; then
    echo "This directory have more that 10 min"
fi
</code>```

Body:
I am looking for a bash script to who check time difference between two directory? But in $oldtime i can`t get only 20:09:24 i get this "20:09:24.660157390".
How can i get only hours:min only.

#!/bin/bash

oldtime=$(stat -c %y /mnt/dir1| awk '{print $2}' )
ctime=$(date | awk '{print $4}')

DIFF=$($oldtime-$ctime)
if [ $DIFF > 600 ]; then
    echo "This directory have more that 10 min"
fi

Body:
Use epoch timestamp and date for converting to that format.

$ date +%H:%M -d @`stat -c %Y /tmp/`
19:19

But it's not recommended to use this format for comparing. Use unix timestamps instead:

if [ $(( $(date +%s) - $(stat -c %Y /tmp) )) -gt 600 ]; then
    echo "This directory have more that 10 min"
fi


问:
Make each button manipulate the content above it
I was practising with jQuery when I faced this obstacle.

I created 10 article tags with content inside each one. I wrote a function to automatically add an id for each article tag (id+1, id+2, etc.) and then I created a button tag after each article tag using JavaScript as well.

I cannot figure out the code that makes the first button manipulate article 1's tag, for example. I want each button to solely affect the article above it. How can I achieve this logically?

Here is my code:

$(function () {
    // Script begin ----

    const $articles = $(".siblings");

    const articlesManipulator = (function () {
        for (let i = 0; i < $articles.length; i++) {
            $articles[i].id = "sibling-" + (i+1);
            let $btn = document.createElement("button");
            $btn.textContent = "play with me :)";
            $btn.id = "player" + (i+1);
            $articles[i].after($btn);
        }
    }());

    // ---- Script end
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[class^='sibling'] {
    border: 1px solid;
    margin: 15px;
    padding: 10px;
    display: block;
}</code>```

Architecto minus, laboriosam vitae natus voluptatum debitis alias asperiores, voluptatibus repudiandae harum sed repellendus? Magni, possimus, ad! Quam perspiciatis praesentium, excepturi mollitia.

Ullam iusto praesentium minima, placeat nam, fugiat nulla suscipit impedit soluta, aliquid a eaque omnis perspiciatis animi officiis minus nesciunt nostrum quisquam?

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

```

答:
Use jQuery .prev() since you're using its pal .after():

```<code>function play(e) {
    var $article = $(this).prev();
    $article.html("played");
}
</code>```

Usage:

```<code>$($btn).click(play);
</code>```

Body:
I was practising with jQuery when I faced this obstacle.

I created 10 article tags with content inside each one. I wrote a function to automatically add an id for each article tag (id+1, id+2, etc.) and then I created a button tag after each article tag using JavaScript as well.

I cannot figure out the code that makes the first button manipulate article 1's tag, for example. I want each button to solely affect the article above it. How can I achieve this logically?

Here is my code:

$(function () {
    // Script begin ----

    const $articles = $(".siblings");

    const articlesManipulator = (function () {
        for (let i = 0; i < $articles.length; i++) {
            $articles[i].id = "sibling-" + (i+1);
            let $btn = document.createElement("button");
            $btn.textContent = "play with me :)";
            $btn.id = "player" + (i+1);
            $articles[i].after($btn);
        }
    }());

    // ---- Script end
});

[class^='sibling'] {
    border: 1px solid;
    margin: 15px;
    padding: 10px;
    display: block;
}

Architecto minus, laboriosam vitae natus voluptatum debitis alias asperiores, voluptatibus repudiandae harum sed repellendus? Magni, possimus, ad! Quam perspiciatis praesentium, excepturi mollitia.

Ullam iusto praesentium minima, placeat nam, fugiat nulla suscipit impedit soluta, aliquid a eaque omnis perspiciatis animi officiis minus nesciunt nostrum quisquam?

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Corporis neque sunt error quaerat, deserunt non suscipit quidem ducimus dolor libero. Laboriosam placeat minus, nobis explicabo consequatur aut culpa praesentium qui.

Body:
Use jQuery .prev() since you're using its pal .after():

function play(e) {
    var $article = $(this).prev();
    $article.html("played");
}

Usage:

$($btn).click(play);


问:
Replacing HTML entities in Go strings
This feels like one of those operations that must be common enough that this is a duplicate question, but since I was not able to find it anywhere:

What is the most straightforward way to replace HTML entities with their string representations in a Go string? That is, how would I turn the string Rø&d grød & fløde into Rød grød & fløde?

My own solutions have been either using strings.Replace on all relevant entities (which quickly becomes intractable), or wrapping the string into an XML document and decoding it with xml.Decoder (which seems silly and leads to numerous edge cases).

答:
Use the html.UnescapeString function:

```<code>fmt.Println(html.UnescapeString("Rø&d grød & fløde"))
</code>```

playground example

Title: Replacing HTML entities in Go strings

Body:
Use the html.UnescapeString function:

fmt.Println(html.UnescapeString("R&oslash;&d gr&oslash;d &amp; fl&oslash;de"))

playground example


问:
Sort JavaScript array of Objects by two properties and given order
I have this JavaScript array of Objects:

```<code>data = [
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
]
</code>```

and I would like to sort it both by 'provider' (the three "This" before the three "All") and by 'measure' (first quartile, median, third quartile), so the resulting array will look like:

```<code>data = [
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},
]
</code>```

I have written a function as an argument to .sort(), and it does return the array sorted by 'provider', but then when I feed it into the same function with measure as an argument (thankfully, first_quartile, median, third_quartile are already alphabetically sorted the way I want them) - the sorting gets broken. How can I go about doing it?

EDIT
The functions I have been using:

```<code>var compare_prv = function(a,b) {
  if (a.provider < b.provider){
    return 1;
  }
  return 0;
}

var compare_meas = function(a,b) {
  if (a.measure < b.measure){
    return -1;
  }
  return 0;
}
</code>```

答:
You could chain the sorting criteria with logical OR ||.

For a set of strings with a defined order, you could use an object for getting the wanted order.

```<code>{
    first_quartile: 1,
    median: 2,
    third_quartile: 3
}
</code>```

This lets you sort some item, if not in the order list ssort to start with default zero or to bottom with a huge value like Infinity.

In this case the pattern looks like

```<code>(order[a.measure] || 0) - (order[a.measure] || 0)                // to top
(order[a.measure] || Infinify ) - (order[a.measure] || Infinity) // to bottom
</code>```

var array = [{ deviation: 57.41, provider: "This", measure: "median" }, { deviation: 49.02, provider: "All", measure: "median" }, { deviation: 199.67, provider: "This", measure: "third_quartile" }, { deviation: 152.31, provider: "All", measure: "third_quartile" }, { deviation: 41.48, provider: "This", measure: "first_quartile" }, { deviation: -1.07, provider: "All", measure: "first_quartile" }],
   order = { first_quartile: 1, median: 2, third_quartile: 3 };

array.sort(function (a, b) {
    return b.provider.localeCompare(a.provider) || order[a.measure] - order[b.measure];
});

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have this JavaScript array of Objects:

data = [
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
]

and I would like to sort it both by 'provider' (the three "This" before the three "All") and by 'measure' (first quartile, median, third quartile), so the resulting array will look like:

data = [
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},
]

I have written a function as an argument to .sort(), and it does return the array sorted by 'provider', but then when I feed it into the same function with measure as an argument (thankfully, first_quartile, median, third_quartile are already alphabetically sorted the way I want them) - the sorting gets broken. How can I go about doing it?

EDIT
The functions I have been using:

var compare_prv = function(a,b) {
  if (a.provider < b.provider){
    return 1;
  }
  return 0;
}

var compare_meas = function(a,b) {
  if (a.measure < b.measure){
    return -1;
  }
  return 0;
}

Body:
You could chain the sorting criteria with logical OR ||.

For a set of strings with a defined order, you could use an object for getting the wanted order.

{
    first_quartile: 1,
    median: 2,
    third_quartile: 3
}

This lets you sort some item, if not in the order list ssort to start with default zero or to bottom with a huge value like Infinity.

In this case the pattern looks like

(order[a.measure] || 0) - (order[a.measure] || 0)                // to top
(order[a.measure] || Infinify ) - (order[a.measure] || Infinity) // to bottom

var array = [{ deviation: 57.41, provider: "This", measure: "median" }, { deviation: 49.02, provider: "All", measure: "median" }, { deviation: 199.67, provider: "This", measure: "third_quartile" }, { deviation: 152.31, provider: "All", measure: "third_quartile" }, { deviation: 41.48, provider: "This", measure: "first_quartile" }, { deviation: -1.07, provider: "All", measure: "first_quartile" }],
   order = { first_quartile: 1, median: 2, third_quartile: 3 };

array.sort(function (a, b) {
    return b.provider.localeCompare(a.provider) || order[a.measure] - order[b.measure];
});

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
checking if jquery hide has completed execution
I am trying to learn jQuery.I just tried to create a simple picture viewer with next and previous buttons using the basic show and hide.Hence the obvious flow of the script would be to first hide the previous image and then show the next image.But sometimes when I click the next button rapidly,it displays the next image without completing the .hide() of the previous.
I need an elegant method to check whether the .hide() execution is complete or not and wait while its being done.
Here's the code snippet</p>

```<code>var picArray = new Array('#test1','#test2','#test3','#test4');
var picArrayIndex = 0;
$(document).ready(function()
{

$(picArray[picArrayIndex]).show();
$(".next-btn").click(function(){

    picArrayIndex++;
    if(picArrayIndex > picArray.length - 1)
        {picArrayIndex = 0;
            $(picArray[picArray.length - 1]).hide();
        }

    $(picArray[picArrayIndex - 1]).hide();
      $(picArray[picArrayIndex]).animate({
opacity: 1,
hspace:80

 }, 1000, function() {
   // Animation complete.
 });
        $(picArray[picArrayIndex]).effect("bounce", { direction:'left', times:1 },   500);

    $(picArray[picArrayIndex]).show();
});
    $(".prev-btn").click(function(){

    picArrayIndex--;
    if(picArrayIndex < 0)
        {picArrayIndex = picArray.length - 1;
            $(picArray[0]).hide();}
    $(picArray[picArrayIndex + 1]).hide();
    $(picArray[picArrayIndex]).show();
});
});
</code>```

答:
For complicated solutions I needed to use promise to ensure that hide is done, you could use this implementation:</p>

```<code>$(obj).hide().promise().done(function (){ /* Your code goes here */ });
</code>```

Body:
I am trying to learn jQuery.I just tried to create a simple picture viewer with next and previous buttons using the basic show and hide.Hence the obvious flow of the script would be to first hide the previous image and then show the next image.But sometimes when I click the next button rapidly,it displays the next image without completing the .hide() of the previous.
I need an elegant method to check whether the .hide() execution is complete or not and wait while its being done.
Here's the code snippet

var picArray = new Array('#test1','#test2','#test3','#test4');
var picArrayIndex = 0;
$(document).ready(function()
{

$(picArray[picArrayIndex]).show();
$(".next-btn").click(function(){

    picArrayIndex++;
    if(picArrayIndex > picArray.length - 1)
        {picArrayIndex = 0;
            $(picArray[picArray.length - 1]).hide();
        }

    $(picArray[picArrayIndex - 1]).hide();
      $(picArray[picArrayIndex]).animate({
opacity: 1,
hspace:80

 }, 1000, function() {
   // Animation complete.
 });
        $(picArray[picArrayIndex]).effect("bounce", { direction:'left', times:1 },   500);

    $(picArray[picArrayIndex]).show();
});
    $(".prev-btn").click(function(){

    picArrayIndex--;
    if(picArrayIndex < 0)
        {picArrayIndex = picArray.length - 1;
            $(picArray[0]).hide();}
    $(picArray[picArrayIndex + 1]).hide();
    $(picArray[picArrayIndex]).show();
});
});

Body:
For complicated solutions I needed to use promise to ensure that hide is done, you could use this implementation:

$(obj).hide().promise().done(function (){ /* Your code goes here */ });


问:
How to create a class which uses member functions defined in another class C++
I'm new to object oriented programming and am struggling a bit with how best to write classes.

I am trying to abstract the idea of sorting to objects that are not just lists of numbers. I have an abstract base class, SortableContainer, which contains all the necessary virtual functions for comparing and swapping elements, along with some overloaded operators. I then have two classes derived from that, MVector and CoordinateArray. Both of these derived classes have proper definitions for all the virtual functions in the base class. Everything up to this point has worked just fine. MVector just stores vector-like objects and CoordinateArray stores vectors of coordinates onto which a notion of 'less than' has been defined.

My problem now is that I have created a new class, Life, which I want to use to implement the game of life using a CoordinateArray object to store the alive cells. The outline of my Life class looks like this:

```<code>class Life
{
public:
   CoordinateArray LiveCells;

   Life();
};
</code>```

When I create a Life object and initialise it with the coordinates of some alive cells, none of the member functions defined in the CoordinateArray derived class will work. How can I fix this? Do I have to derive the Life class from the SortableContainer class and then override all the pure virtual functions? Any help or direction to help will be much appreciated.

答:
To answer your question simply and in a pragmatical way, yes, if you want your Life object to have some member functions they need to come from somewhere, the most straight forward way is to derive it from a class containing those member functions, composition does not transfer members to the owner, inheritance does that:

```<code>class Life : public CoordinateArray
{
public:
   Life();
};
</code>```

Now you can use your Life objects as a CoordinateArray object. If anything is pure virtual in the parent class you will indeed need to implement it in the derived class, but even if something is not you can still reimplement it in the child class to overwrite the parent behaviour.

I avoided conception and design problematics on purpose, this is mainly a technical answer, judging this from a design point of view requires more context and has some subjective side too so that's another story altogether.

Body:
I'm new to object oriented programming and am struggling a bit with how best to write classes.

I am trying to abstract the idea of sorting to objects that are not just lists of numbers. I have an abstract base class, SortableContainer, which contains all the necessary virtual functions for comparing and swapping elements, along with some overloaded operators. I then have two classes derived from that, MVector and CoordinateArray. Both of these derived classes have proper definitions for all the virtual functions in the base class. Everything up to this point has worked just fine. MVector just stores vector-like objects and CoordinateArray stores vectors of coordinates onto which a notion of 'less than' has been defined.

My problem now is that I have created a new class, Life, which I want to use to implement the game of life using a CoordinateArray object to store the alive cells. The outline of my Life class looks like this:

class Life
{
public:
   CoordinateArray LiveCells;

   Life();
};

When I create a Life object and initialise it with the coordinates of some alive cells, none of the member functions defined in the CoordinateArray derived class will work. How can I fix this? Do I have to derive the Life class from the SortableContainer class and then override all the pure virtual functions? Any help or direction to help will be much appreciated.

Body:
To answer your question simply and in a pragmatical way, yes, if you want your Life object to have some member functions they need to come from somewhere, the most straight forward way is to derive it from a class containing those member functions, composition does not transfer members to the owner, inheritance does that:

class Life : public CoordinateArray
{
public:
   Life();
};

Now you can use your Life objects as a CoordinateArray object. If anything is pure virtual in the parent class you will indeed need to implement it in the derived class, but even if something is not you can still reimplement it in the child class to overwrite the parent behaviour.

I avoided conception and design problematics on purpose, this is mainly a technical answer, judging this from a design point of view requires more context and has some subjective side too so that's another story altogether.


问:
How can I check if string input is a number?
How do I check if a user's string input is a number (e.g., -1, 0, 1, etc.)?

```<code>user_input = input("Enter something:")

if type(user_input) == int:
    print("Is a number")
else:
    print("Not a number")
</code>```

The above won't work since input always returns a string.

答:
Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.

```<code>numList = [499, -486, 0.1255468, -0.21554, 'a', "this", "long string here", "455 street area", 0, ""]

for item in numList:

    try:
        print (item / 2) #You can divide by any number really, except zero
    except:
        print "Not A Number: " + item
</code>```

Result:

```<code>249
-243
0.0627734
-0.10777
Not A Number: a
Not A Number: this
Not A Number: long string here
Not A Number: 455 street area
0
Not A Number:
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I check if a user's string input is a number (e.g., -1, 0, 1, etc.)?

user_input = input("Enter something:")

if type(user_input) == int:
    print("Is a number")
else:
    print("Not a number")

The above won't work since input always returns a string.

Body:
Why not divide the input by a number? This way works with everything. Negatives, floats, and negative floats. Also Blank spaces and zero.

numList = [499, -486, 0.1255468, -0.21554, 'a', "this", "long string here", "455 street area", 0, ""]

for item in numList:

    try:
        print (item / 2) #You can divide by any number really, except zero
    except:
        print "Not A Number: " + item

Result:

249
-243
0.0627734
-0.10777
Not A Number: a
Not A Number: this
Not A Number: long string here
Not A Number: 455 street area
0
Not A Number:


问:
How to determine if a string is numeric in ksh
I'm trying to validate input in ksh, and would like to know the easiest way to determine if a string is a valid number.</p>

答:
You can use string operator in test like so:</p>

```<code>if [[ "${input%%*( )+([0-9])?(.)*([0-9])}" = "" ]]; then
   print "Is numeric"
fi
</code>```

Body:
You can use string operator in test like so:

if [[ "${input%%*( )+([0-9])?(.)*([0-9])}" = "" ]]; then
   print "Is numeric"
fi


问:
Vagrant not allowing NatNetwork on adapter 1
Vagrant is forcing network type nat on adapter 1 (eth0) even when I have the network set as natnetwork in Virutalbox.

I can set up everything through Virtualbox manually and all my VMs can communicate with each other via eth0 as desired and port forwarding works as well.  I would like to get Vagrant to work the same way for easy distribution among coworkers.

It looks like others have this problem and it's not being addressed by Vagrant:
https://github.com/mitchellh/vagrant/issues/2779

Anyone know of a workaround?

Details:

```<code>$ VBoxManage list natnetworks
NetworkName:    ff_mgmt
IP:             10.0.2.1
Network:        10.0.2.0/24
IPv6 Enabled:   No
IPv6 Prefix:    fd17:625c:f037:2::/64
DHCP Enabled:   No
Enabled:        Yes
Port-forwarding (ipv4)
    https1:tcp:[]:4441:[10.0.2.11]:443
    https2:tcp:[]:4442:[10.0.2.12]:443
    https3:tcp:[]:4443:[10.0.2.13]:443
    ssh1:tcp:[]:2221:[10.0.2.11]:22
    ssh2:tcp:[]:2222:[10.0.2.12]:22
    ssh3:tcp:[]:2223:[10.0.2.13]:22
loopback mappings (ipv4)
    127.0.0.1=2
</code>```

Relevant part of Vagrantfile:

```<code>boxes = [
{
    :name => "ff1",
    :ip => "10.0.2.11",
    :ssh_port => "2221",
    :https_port => "4441",
    :mac =>  "0800270fa302",
    :memory => "8192",
    :cpus => "4"
},
{
    :name => "ff2",
    :ip => "10.0.2.12",
    :ssh_port => "2222",
    :https_port => "4442",
    :mac =>  "0800270fb302",
    :memory => "8192",
    :cpus => "4"
},
{
    :name => "ff3",
    :ip => "10.0.2.13",
    :ssh_port => "2223",
    :https_port => "4443",
    :mac =>  "0800270fc302",
    :intnet2 => "seg5a",
    :memory => "8192",
    :cpus => "4"
}
]

Vagrant.configure(2) do |config|
boxes.each do |opts|
    config.vm.define opts[:name] do |config|

        config.vm.box = "ff"
        #config.vm.box_version = 402

        config.vm.hostname = opts[:name]

        config.ssh.username = 'niska'
        config.ssh.private_key_path = '/home/niska/.ssh/id_rsa'
        config.vm.network :private_network, ip: opts[:ip]
        config.vm.network :forwarded_port, guest: 22, guest_ip: opts[:ip], host: opts[:ssh_port], id: 'ssh'
        config.vm.network :forwarded_port, guest: 443, host: opts[:https_port]

        config.vm.provider "virtualbox" do |vb|
            vb.gui = false
            vb.memory = opts[:memory]
            vb.cpus = opts[:cpus]

            vb.customize ["modifyvm", :id, "--nic1", "natnetwork"]
            vb.customize ["modifyvm", :id, "--nictype1", "virtio"]
            vb.customize ["modifyvm", :id, "--macaddress1", opts[:mac]]
            #vb.customize ["modifyvm", :id, "--intnet1", "ff_mgmt"]

        end
    end
end
</code>```

Output of vagrant up.  Notice override of natnetwork. Also port forwarding picks different ports and therefore fails to connect.

```<code>$ vagrant reload ff1
==> ff1: Attempting graceful shutdown of VM...
    ff1: Guest communication could not be established! This is usually because
    ff1: SSH is not running, the authentication information was changed,
    ff1: or some other networking issue. Vagrant will force halt, if
    ff1: capable.
==> ff1: Forcing shutdown of VM...
==> ff1: Clearing any previously set network interfaces...
==> ff1: Preparing network interfaces based on configuration...
->>>     ff1: Adapter 1: nat                       <<<--- (overrode w/ 'nat')
    ff1: Adapter 2: hostonly
==> ff1: Forwarding ports...
    ff1: 22 (guest) => 2221 (host) (adapter 1)
    ff1: 443 (guest) => 4441 (host) (adapter 1)
==> ff1: Running 'pre-boot' VM customizations...
==> ff1: Booting VM...
==> ff1: Waiting for machine to boot. This may take a few minutes...
    ff1: SSH address: 127.0.0.1:22
    ff1: SSH username: niska
    ff1: SSH auth method: private key
    ff1: Warning: Authentication failure. Retrying...
    ...
    Vagrant never connects
</code>```

答:
Don't set nic1 (eth0) to anything other than NAT. virtualbox requires the first interface to be NAT.

```<code>ff1: Warning: Authentication failure. Retrying...
</code>```

if you change the network type of the nic to natnetwork, then vagrant can't figure out how to ssh to the machine.

if you need vagrant at first to provision, change your network settings after you finish provisioning. however; after that point, you won't be able to use vagrant.

Body:
Vagrant is forcing network type nat on adapter 1 (eth0) even when I have the network set as natnetwork in Virutalbox.

I can set up everything through Virtualbox manually and all my VMs can communicate with each other via eth0 as desired and port forwarding works as well.  I would like to get Vagrant to work the same way for easy distribution among coworkers.

It looks like others have this problem and it's not being addressed by Vagrant:
https://github.com/mitchellh/vagrant/issues/2779

Anyone know of a workaround?

Details:

$ VBoxManage list natnetworks
NetworkName:    ff_mgmt
IP:             10.0.2.1
Network:        10.0.2.0/24
IPv6 Enabled:   No
IPv6 Prefix:    fd17:625c:f037:2::/64
DHCP Enabled:   No
Enabled:        Yes
Port-forwarding (ipv4)
    https1:tcp:[]:4441:[10.0.2.11]:443
    https2:tcp:[]:4442:[10.0.2.12]:443
    https3:tcp:[]:4443:[10.0.2.13]:443
    ssh1:tcp:[]:2221:[10.0.2.11]:22
    ssh2:tcp:[]:2222:[10.0.2.12]:22
    ssh3:tcp:[]:2223:[10.0.2.13]:22
loopback mappings (ipv4)
    127.0.0.1=2

Relevant part of Vagrantfile:

boxes = [
{
    :name => "ff1",
    :ip => "10.0.2.11",
    :ssh_port => "2221",
    :https_port => "4441",
    :mac =>  "0800270fa302",
    :memory => "8192",
    :cpus => "4"
},
{
    :name => "ff2",
    :ip => "10.0.2.12",
    :ssh_port => "2222",
    :https_port => "4442",
    :mac =>  "0800270fb302",
    :memory => "8192",
    :cpus => "4"
},
{
    :name => "ff3",
    :ip => "10.0.2.13",
    :ssh_port => "2223",
    :https_port => "4443",
    :mac =>  "0800270fc302",
    :intnet2 => "seg5a",
    :memory => "8192",
    :cpus => "4"
}
]

Vagrant.configure(2) do |config|
boxes.each do |opts|
    config.vm.define opts[:name] do |config|

        config.vm.box = "ff"
        #config.vm.box_version = 402

        config.vm.hostname = opts[:name]

        config.ssh.username = 'niska'
        config.ssh.private_key_path = '/home/niska/.ssh/id_rsa'
        config.vm.network :private_network, ip: opts[:ip]
        config.vm.network :forwarded_port, guest: 22, guest_ip: opts[:ip], host: opts[:ssh_port], id: 'ssh'
        config.vm.network :forwarded_port, guest: 443, host: opts[:https_port]

        config.vm.provider "virtualbox" do |vb|
            vb.gui = false
            vb.memory = opts[:memory]
            vb.cpus = opts[:cpus]

            vb.customize ["modifyvm", :id, "--nic1", "natnetwork"]
            vb.customize ["modifyvm", :id, "--nictype1", "virtio"]
            vb.customize ["modifyvm", :id, "--macaddress1", opts[:mac]]
            #vb.customize ["modifyvm", :id, "--intnet1", "ff_mgmt"]

        end
    end
end

Output of vagrant up.  Notice override of natnetwork. Also port forwarding picks different ports and therefore fails to connect.

$ vagrant reload ff1
==> ff1: Attempting graceful shutdown of VM...
    ff1: Guest communication could not be established! This is usually because
    ff1: SSH is not running, the authentication information was changed,
    ff1: or some other networking issue. Vagrant will force halt, if
    ff1: capable.
==> ff1: Forcing shutdown of VM...
==> ff1: Clearing any previously set network interfaces...
==> ff1: Preparing network interfaces based on configuration...
->>>     ff1: Adapter 1: nat                       <<<--- (overrode w/ 'nat')
    ff1: Adapter 2: hostonly
==> ff1: Forwarding ports...
    ff1: 22 (guest) => 2221 (host) (adapter 1)
    ff1: 443 (guest) => 4441 (host) (adapter 1)
==> ff1: Running 'pre-boot' VM customizations...
==> ff1: Booting VM...
==> ff1: Waiting for machine to boot. This may take a few minutes...
    ff1: SSH address: 127.0.0.1:22
    ff1: SSH username: niska
    ff1: SSH auth method: private key
    ff1: Warning: Authentication failure. Retrying...
    ...
    Vagrant never connects

Body:
Don't set nic1 (eth0) to anything other than NAT. virtualbox requires the first interface to be NAT.

ff1: Warning: Authentication failure. Retrying...

if you change the network type of the nic to natnetwork, then vagrant can't figure out how to ssh to the machine.

if you need vagrant at first to provision, change your network settings after you finish provisioning. however; after that point, you won't be able to use vagrant.


问:
PHP, SMTP - Subject in email shows International Characters as HTML_Entities
I've spent over half a day on this - just trying to get the email Subject to appear normal. But international characters appear as HTML_Entities when the email lands in the inbox.

For example: Tydzień o Jedność

Shows up as: Tydzień o Jedność

I already encode the email Subject for UTF-8:

$this->subject = "=?UTF-8?B?" . base64_encode($this->subject) . "?=";

When I get the email (Gmail), the header appears as:

Subject: =?UTF-8?B?VHlkemllJiMzMjQ7IG8gSmVkbm8mIzM0NzsmIzI2Mzs=?=

So it seems to encode properly. But for some reason, Gmail still displays the Subject with HTML_Entities.

Any ideas?

See code: SMTP mail class

答:
Is $this->subject a valid UTF-8 string? Are you working with UTF-8 encoded .php files (no BOM)?

Also, try doing:

```<code>$this->subject = "=?UTF-8?B?" . base64_encode(html_entity_decode($this->subject, ENT_COMPAT, 'UTF-8')) . "?=";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is $this->subject a valid UTF-8 string? Are you working with UTF-8 encoded .php files (no BOM)?

Also, try doing:

$this->subject = "=?UTF-8?B?" . base64_encode(html_entity_decode($this->subject, ENT_COMPAT, 'UTF-8')) . "?=";


问:
How to run filter on demand scala play framework
I'm developing a scala application with play frame work, i have created a filter that filters every request coming from outside server,but now i'm stuck on how can i run a filter on demand since two days,i have 80 APIs 30 of them needs to run a specific filter, how can i read the request route template while the requests like this

```<code> GET /api/v1/:locale/:uuid core.controllers.MyClass.myAction1(locale: String)
 GET /api/v1/:locale/:uuid/MyRoute core.controllers.MyClass.myAction2(locale: String)
 GET /api/v1/:locale/:uuid/Foo core.controllers.MyClass.myAction3(locale: String)
 GET /api/v1/:locale/orders/:orderId core.controllers.MyClass.myAction4(locale: String)
</code>```

well, those routes are placed in routes file,
in filter i need to check weather if the route has :uuid variable or :orderId in order to run its specific filter, because both of their ids, i getting them as uuid so i couldn't expect the request, could i read the route template ?

答:
You can access to some routing information from the RequestHeader#attrs:

```<code>// in your filter
val handlerDef: Option[HandlerDef] = request.attrs.get(Router.Attrs.HandlerDef)
</code>```

See HandlerDef api

Body:
I'm developing a scala application with play frame work, i have created a filter that filters every request coming from outside server,but now i'm stuck on how can i run a filter on demand since two days,i have 80 APIs 30 of them needs to run a specific filter, how can i read the request route template while the requests like this

 GET /api/v1/:locale/:uuid core.controllers.MyClass.myAction1(locale: String)
 GET /api/v1/:locale/:uuid/MyRoute core.controllers.MyClass.myAction2(locale: String)
 GET /api/v1/:locale/:uuid/Foo core.controllers.MyClass.myAction3(locale: String)
 GET /api/v1/:locale/orders/:orderId core.controllers.MyClass.myAction4(locale: String)

well, those routes are placed in routes file,
in filter i need to check weather if the route has :uuid variable or :orderId in order to run its specific filter, because both of their ids, i getting them as uuid so i couldn't expect the request, could i read the route template ?

Body:
You can access to some routing information from the RequestHeader#attrs:

// in your filter
val handlerDef: Option[HandlerDef] = request.attrs.get(Router.Attrs.HandlerDef)

See HandlerDef api


问:
PyQt: How to pass chosen Combobox value from QDialog to main window?
I have stuck at passing values from child class (QDialog) to its parent class (in my example MainApp).
Here is a QtDesigner derived file for main window. It consist of window, text label and pushbutton.

```<code># -*- coding: utf-8 -*-
# Created by: PyQt4 UI code generator 4.12
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(218, 184)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.verticalLayout.addWidget(self.pushButton)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.label.setText(_translate("MainWindow", "TextLabel", None))
        self.pushButton.setText(_translate("MainWindow", "PushButton", None))
</code>```

Below is dialog.py definition. It contains Combobox and pushbutton.

```<code># -*- coding: utf-8 -*-

# Created by: PyQt4 UI code generator 4.12
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(400, 284)
        self.buttonBox = QtGui.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(Qt.Gui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.comboBox = QtGui.QComboBox(Dialog)
        self.comboBox.setGeometry(QtCore.QRect(100, 40, 201, 22))
        self.comboBox.setObjectName(_fromUtf8("comboBox"))

        self.retranslateUi(Dialog)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
</code>```

Below is main class with its methods:

```<code>from PyQt4 import QtGui #import the PyQt4 module we need
from PyQt4.Qt import QDialog
import sys #sys needed so we can pass argv to QApplication
import mainwin
import dialog

class MainApp(QtGui.QMainWindow, mainwin.Ui_MainWindow):
    '''Main window of the application'''
    def __init__(self, parent=None):
        super(MainApp, self).__init__(parent)

        self.setupUi(self) # This is defined in design.py file automatically
                           # It sets up layout and widgets that are defined
        self.label.setText("I am unchanged text")
        self.pushButton.clicked.connect(self.openDialog)#button binding - call openDialog method

    def openDialog(self): # Opening a new popup window...
        self.dialog = MyDialog()
        self.a = self.dialog.exec_() #exec_() for python2.x, before python3

        if self.a == self.dialog.Accepted:
            self.label.setText("Accepted") #<-----HERE--
        elif self.a == self.dialog.Rejected: #0
            self.label.setText("Rejected")

class MyDialog(QtGui.QDialog, dialog.Ui_Dialog):

    def __init__(self, parent = MainApp):
        QDialog.__init__(self)
        self.setupUi(self) #takes ui from my-defined dialog.py

        self.comboBox.addItem('item 1');#adding items to the QCombobox to be displayed
        self.comboBox.addItem('item 2');
        self.comboBox.addItem('item 3');
        self.comboBox.addItem('special1');

        self.comboBox.activated[str].connect(self.my_method)

    def my_method(self, my_text):
        print my_text
        #return my_text

def main():
    app = QtGui.QApplication(sys.argv)# A new instance of QApplication
    form = MainApp() # We set the form to be our ExampleApp (design)
    form.show() # Show the form
    app.exec_() # and execute the app

if __name__ == '__main__': #if the app is running directly, and is not imported
    main()
</code>```

I want to pass selected text from Combobox ('item1' or 'item2' and so on...) which is placed on Dialog to MainApp window and  print it from the place marked <-----HERE--.
I would prefer not to use global variables.
Can anyone point me in to good direction? Shall I try to manipulate slot-signal mechanism? Or try to overload accept() method?

答:
thanks to ekhumoro, answer is:</p>

```<code>self.label.setText(self.dialog.comboBox.currentText())
</code>```

Body:
I have stuck at passing values from child class (QDialog) to its parent class (in my example MainApp).
Here is a QtDesigner derived file for main window. It consist of window, text label and pushbutton.

# -*- coding: utf-8 -*-
# Created by: PyQt4 UI code generator 4.12
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(218, 184)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.verticalLayout.addWidget(self.pushButton)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.label.setText(_translate("MainWindow", "TextLabel", None))
        self.pushButton.setText(_translate("MainWindow", "PushButton", None))

Below is dialog.py definition. It contains Combobox and pushbutton.

# -*- coding: utf-8 -*-

# Created by: PyQt4 UI code generator 4.12
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(400, 284)
        self.buttonBox = QtGui.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(Qt.Gui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.comboBox = QtGui.QComboBox(Dialog)
        self.comboBox.setGeometry(QtCore.QRect(100, 40, 201, 22))
        self.comboBox.setObjectName(_fromUtf8("comboBox"))

        self.retranslateUi(Dialog)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))

Below is main class with its methods:

from PyQt4 import QtGui #import the PyQt4 module we need
from PyQt4.Qt import QDialog
import sys #sys needed so we can pass argv to QApplication
import mainwin
import dialog

class MainApp(QtGui.QMainWindow, mainwin.Ui_MainWindow):
    '''Main window of the application'''
    def __init__(self, parent=None):
        super(MainApp, self).__init__(parent)

        self.setupUi(self) # This is defined in design.py file automatically
                           # It sets up layout and widgets that are defined
        self.label.setText("I am unchanged text")
        self.pushButton.clicked.connect(self.openDialog)#button binding - call openDialog method

    def openDialog(self): # Opening a new popup window...
        self.dialog = MyDialog()
        self.a = self.dialog.exec_() #exec_() for python2.x, before python3

        if self.a == self.dialog.Accepted:
            self.label.setText("Accepted") #<-----HERE--
        elif self.a == self.dialog.Rejected: #0
            self.label.setText("Rejected")

class MyDialog(QtGui.QDialog, dialog.Ui_Dialog):

    def __init__(self, parent = MainApp):
        QDialog.__init__(self)
        self.setupUi(self) #takes ui from my-defined dialog.py

        self.comboBox.addItem('item 1');#adding items to the QCombobox to be displayed
        self.comboBox.addItem('item 2');
        self.comboBox.addItem('item 3');
        self.comboBox.addItem('special1');

        self.comboBox.activated[str].connect(self.my_method)

    def my_method(self, my_text):
        print my_text
        #return my_text

def main():
    app = QtGui.QApplication(sys.argv)# A new instance of QApplication
    form = MainApp() # We set the form to be our ExampleApp (design)
    form.show() # Show the form
    app.exec_() # and execute the app

if __name__ == '__main__': #if the app is running directly, and is not imported
    main()

I want to pass selected text from Combobox ('item1' or 'item2' and so on...) which is placed on Dialog to MainApp window and  print it from the place marked <-----HERE--.
I would prefer not to use global variables.
Can anyone point me in to good direction? Shall I try to manipulate slot-signal mechanism? Or try to overload accept() method?

Body:
thanks to ekhumoro, answer is:

self.label.setText(self.dialog.comboBox.currentText())


问:
MySQL: Counting number of staff
I'm very new to programming in sql and I'm having an issue with a question.

I have to find the department with the largest number of staff, and I'm not at all sure how to do it.

The tables i can use are

I think the end result would have the columns, Department_no and Max(Count(Department_no)) but I'm not sure how I'd get this? Or is there a simpler way that I'm just not seeing?

EDIT So far I have

SELECT Department_no, Count(Department_no)
 FROM ManagerOrBoss
 GROUP BY Department_no;

But I ideally want to find the maximum of the count, but SQL keeps giving a 'Invalid use of group function error'.

答:
You can use below query to get the department(s) who have higher no. of staff

```<code>select a.Department_no ,count(a.Staff_id) maxstaffa
from table a
cross join (
    select count(Staff_id) maxstaffb
    from table
    group by Department_no
    order by maxstaffb desc
    limit 1
) b
group by a.Department_no
having maxstaffa = b.maxstaffb
</code>```

Note above query can return more than one departments if they all have same max count of staff members

Title: MySQL: Counting number of staff

Body:
You can use below query to get the department(s) who have higher no. of staff

select a.Department_no ,count(a.Staff_id) maxstaffa
from table a
cross join (
    select count(Staff_id) maxstaffb
    from table
    group by Department_no
    order by maxstaffb desc
    limit 1
) b
group by a.Department_no
having maxstaffa = b.maxstaffb

Note above query can return more than one departments if they all have same max count of staff members


问:
How can i seperate/split part of string messege in node red
I received this message:

```<code> "data: "{"cmd":"gw","seqno":515816,"EUI":"000DB53113683569","ts":1510584501221,"fcnt":1,"port":2,"freq":868100000,"toa":1482,"dr":"SF12 BW125 4/5","ack":false,"gws":[{"rssi":-71,"snr":9.5,"ts":1510584501221,"time":"2017-11-13T14:48:21.218869Z","gweui":"B827EBFFFF6A14DD","lat":50.0751806,"lon":14.4022641}],"bat":255,"data":"0002560000000000000000"}""
</code>```

I need to put away the "data: " and on the end the "

I need just the JSON message if I use JSON node it just writes me an error because of the "data: "

答:
You can use a function node to chop the string up. Something like this:

```<code>msg.payload = msg.payload.substring(7,msg.payload.length - 1);
return msg;
</code>```

And then wire this to a JSON node.

Body:
I received this message:

 "data: "{"cmd":"gw","seqno":515816,"EUI":"000DB53113683569","ts":1510584501221,"fcnt":1,"port":2,"freq":868100000,"toa":1482,"dr":"SF12 BW125 4/5","ack":false,"gws":[{"rssi":-71,"snr":9.5,"ts":1510584501221,"time":"2017-11-13T14:48:21.218869Z","gweui":"B827EBFFFF6A14DD","lat":50.0751806,"lon":14.4022641}],"bat":255,"data":"0002560000000000000000"}""

I need to put away the "data: " and on the end the "

I need just the JSON message if I use JSON node it just writes me an error because of the "data: "

Body:
You can use a function node to chop the string up. Something like this:

msg.payload = msg.payload.substring(7,msg.payload.length - 1);
return msg;

And then wire this to a JSON node.


问:
How can I make "or" searches using the rest api?
I am integrating querydsl to spring data rest as explained here:
https://gist.github.com/olivergierke/decf03d4948cd58a51bc
How can I make "or" searches using the rest api? Where can I find documentation for other operators?

?name=Fred&name=Joe&name=Jack works with or but I am looking for the case where one can or different fields of the entity like: ?name=fred+or+email=fred

答:
If I recall correctly, it's just a case of passing multiple parameters:

```<code>?name=Fred&name=Joe&name=Jack //name = Fred or Joe or Jack
</code>```

For customizing the binding to, for example, use a partial match you can use the QueryDslBinderCustomizer:

```<code>?name=Fr&name=J
</code>```

See (Java 8):

https://gist.github.com/olivergierke/decf03d4948cd58a51bc

and (Java 7)

Customizing Param Binding for QueryDSL Support

Body:
If I recall correctly, it's just a case of passing multiple parameters:

?name=Fred&name=Joe&name=Jack //name = Fred or Joe or Jack

For customizing the binding to, for example, use a partial match you can use the QueryDslBinderCustomizer:

?name=Fr&name=J

See (Java 8):

https://gist.github.com/olivergierke/decf03d4948cd58a51bc

and (Java 7)

Customizing Param Binding for QueryDSL Support


问:
Why does Canvas::drawArc method draw incorrect angles?
I'm trying to draw a 180° arc within an android view.
In the onDraw method I'm using Canvas::drawArc like this:

```<code>canvas.drawArc(arcRect, 180.0f, 180.0f, false, arcBackgroundPaint);
</code>```

The Paint that is being used has a strokeCap of type BUTT. As you can see in the image below, the ends of the arc do not look quite right. The ends are angled up slightly from the inner diameter to the outer diameter.

Does anyone know why this is happening? Is there a way to fix it other than changing the values passed to drawArc so that it actually draws more than 180 degrees? That seems like a nasty hack that I'd rather avoid.

UPDATE:
As requested, I added code to draw a straight line at the bottom of the arc. I draw the line before I draw the arc so the line is behind. I also made the arc black to get better contrast with the line. Here is the outcome:

Yuck.

Here's one with anti-aliasing turned off for the line and arc...

答:
drawArc incorrect angles problem will occur if hardware acceleration is on.

Reproduced with real phone (Nexus 5, Android 6.0.1).

How to test:

Add android:hardwareAccelerated="false" to application tag in AndroidManifest.xml.

NB:

First supported API level of drawArc() is not found in the document, but scaling function of it is from API17.

Hardware Acceleration > Canvas Scaling

https://developer.android.com/guide/topics/graphics/hardware-accel.html

First supported API level

  Simple Shapes: 17

  Note: 'Simple' shapes are drawRect(), drawCircle(), drawOval(), drawRoundRect(), and drawArc() (with useCenter=false) ...

Updated:
As PICyourBrain wrote in another answer, drawArc() is a part of reasons this problem occurs.

With drawPath(), this problem does not occur.

For information:

Not a same shape but drawArc() with useCenter=true also seems safe to use, as hardware acceleration is not used for it. (Ends of the arc and center of it are connected with line, and the line seems straight.)

Canvas Scaling (same link above)

First supported API level

  Complex Shapes: x

Other Q&As related to drawArc()

Canvas.drawArc() artefacts

What's this weird drawArc() / arcTo() bug (graphics glitch) in Android?

[Old]

I'll leave these for your information.

Here are some test results I've tried.

Updated 1-1:

With emulator Nexus5 API10, with arcRect = new RectF(100, 100, 1500, 1400);.

With emulator Nexus5 API16, this does not happen.

(The difference is existence of (host side) hardware acceleration.)

I thought this seems to be an anti-alias related problem, but this happens no matter arcBackgroundPaint.setAntiAlias(true) or setDither(true) are set or not.

NB: This is caused by typo, sorry. Aspect ratio of arcRect should be 1:1 for this test.

With arcRect = new RectF(100, 100, 1400, 1400); and arcPenWidth = 200f;

With arcRect = new RectF(100, 100, 1500, 1300);

1-2: for comparison

With emulator NexusOne (480x800, HDPI) API10, with arcRect = new RectF(100, 100, 500, 500);

Updated 2: Line extended.

I first thought drawing out of view may cause this, but this is also a emulator bug. (Not a drawArc() specific behavior.)

With emulator API10 in landscape(horizontal) orientation, this occurs.

Calculation of line position seems broken.

Please see the right end of the straight line.

```<code>final float lineStartX = arcRect.left - 250f;
final float lineEndX = arcRect.right + 250f;
</code>```

emulator Nexus5 API10

horizontal (API10)

vertical (API10)

2-2: Just for a information

View odd behavior sample of view position (or drawing position) out of range.

Updated 3: Emulator bug

Please see the bottom of the image.

Blue line is a background image of desktop.

emulator Nexus5 API10

Update 4: The result seems to depend on style.

With title bar

Without title bar

Update 5: The result seems to depend on line width.

With arcPenWidth = 430f (API10, horizontal)

Slight notch on the right side is seen.

With 440f

With 450f

Here's my (first) test code.

```<code>import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

final class TestView extends View
{
    RectF arcRect;
    Paint arcBackgroundPaint;
    Paint linePaint;

    public TestView(final Context context, final AttributeSet attrs)
    {
        super(context, attrs);
        //arcRect = new RectF(100, 100, 500, 500);
        arcRect = new RectF(100, 100, 1500, 1500); // fixed (old: 1500, 1400)
        arcBackgroundPaint = new Paint();
        arcBackgroundPaint.setColor(0xFFFFFFFF);
        arcBackgroundPaint.setStyle(Paint.Style.STROKE);
        arcBackgroundPaint.setStrokeCap(Paint.Cap.BUTT);
        arcBackgroundPaint.setStrokeWidth(200f);
        linePaint = new Paint();
        linePaint.setColor(0xFF00FF00);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setStrokeCap(Paint.Cap.BUTT);
        linePaint.setStrokeWidth(2f);
    }

    @Override
    protected void onDraw(final Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawArc(arcRect, 180.0f, 180.0f, false, arcBackgroundPaint);
        final float lineStartX = arcRect.left - 50f;
        final float lineEndX = arcRect.right + 50f;
        final float lineY = arcRect.centerY();
        canvas.drawLine(lineStartX, lineY, lineEndX, lineY, linePaint);
    }
}
</code>```

Body:
I'm trying to draw a 180° arc within an android view.
In the onDraw method I'm using Canvas::drawArc like this:

canvas.drawArc(arcRect, 180.0f, 180.0f, false, arcBackgroundPaint);

The Paint that is being used has a strokeCap of type BUTT. As you can see in the image below, the ends of the arc do not look quite right. The ends are angled up slightly from the inner diameter to the outer diameter.

Does anyone know why this is happening? Is there a way to fix it other than changing the values passed to drawArc so that it actually draws more than 180 degrees? That seems like a nasty hack that I'd rather avoid.

UPDATE:
As requested, I added code to draw a straight line at the bottom of the arc. I draw the line before I draw the arc so the line is behind. I also made the arc black to get better contrast with the line. Here is the outcome:

Yuck.

Here's one with anti-aliasing turned off for the line and arc...

Body:
drawArc incorrect angles problem will occur if hardware acceleration is on.

Reproduced with real phone (Nexus 5, Android 6.0.1).

How to test:

Add android:hardwareAccelerated="false" to application tag in AndroidManifest.xml.

NB:

First supported API level of drawArc() is not found in the document, but scaling function of it is from API17.

Hardware Acceleration > Canvas Scaling

https://developer.android.com/guide/topics/graphics/hardware-accel.html

First supported API level

  Simple Shapes: 17

  Note: 'Simple' shapes are drawRect(), drawCircle(), drawOval(), drawRoundRect(), and drawArc() (with useCenter=false) ...

Updated:
As PICyourBrain wrote in another answer, drawArc() is a part of reasons this problem occurs.

With drawPath(), this problem does not occur.

For information:

Not a same shape but drawArc() with useCenter=true also seems safe to use, as hardware acceleration is not used for it. (Ends of the arc and center of it are connected with line, and the line seems straight.)

Canvas Scaling (same link above)

First supported API level

  Complex Shapes: x

Other Q&As related to drawArc()

Canvas.drawArc() artefacts

What's this weird drawArc() / arcTo() bug (graphics glitch) in Android?

[Old]

I'll leave these for your information.

Here are some test results I've tried.

Updated 1-1:

With emulator Nexus5 API10, with arcRect = new RectF(100, 100, 1500, 1400);.

With emulator Nexus5 API16, this does not happen.

(The difference is existence of (host side) hardware acceleration.)

I thought this seems to be an anti-alias related problem, but this happens no matter arcBackgroundPaint.setAntiAlias(true) or setDither(true) are set or not.

NB: This is caused by typo, sorry. Aspect ratio of arcRect should be 1:1 for this test.

With arcRect = new RectF(100, 100, 1400, 1400); and arcPenWidth = 200f;

With arcRect = new RectF(100, 100, 1500, 1300);

1-2: for comparison

With emulator NexusOne (480x800, HDPI) API10, with arcRect = new RectF(100, 100, 500, 500);

Updated 2: Line extended.

I first thought drawing out of view may cause this, but this is also a emulator bug. (Not a drawArc() specific behavior.)

With emulator API10 in landscape(horizontal) orientation, this occurs.

Calculation of line position seems broken.

Please see the right end of the straight line.

final float lineStartX = arcRect.left - 250f;
final float lineEndX = arcRect.right + 250f;

emulator Nexus5 API10

horizontal (API10)

vertical (API10)

2-2: Just for a information

View odd behavior sample of view position (or drawing position) out of range.

Updated 3: Emulator bug

Please see the bottom of the image.

Blue line is a background image of desktop.

emulator Nexus5 API10

Update 4: The result seems to depend on style.

With title bar

Without title bar

Update 5: The result seems to depend on line width.

With arcPenWidth = 430f (API10, horizontal)

Slight notch on the right side is seen.

With 440f

With 450f

Here's my (first) test code.

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

final class TestView extends View
{
    RectF arcRect;
    Paint arcBackgroundPaint;
    Paint linePaint;

    public TestView(final Context context, final AttributeSet attrs)
    {
        super(context, attrs);
        //arcRect = new RectF(100, 100, 500, 500);
        arcRect = new RectF(100, 100, 1500, 1500); // fixed (old: 1500, 1400)
        arcBackgroundPaint = new Paint();
        arcBackgroundPaint.setColor(0xFFFFFFFF);
        arcBackgroundPaint.setStyle(Paint.Style.STROKE);
        arcBackgroundPaint.setStrokeCap(Paint.Cap.BUTT);
        arcBackgroundPaint.setStrokeWidth(200f);
        linePaint = new Paint();
        linePaint.setColor(0xFF00FF00);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setStrokeCap(Paint.Cap.BUTT);
        linePaint.setStrokeWidth(2f);
    }

    @Override
    protected void onDraw(final Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawArc(arcRect, 180.0f, 180.0f, false, arcBackgroundPaint);
        final float lineStartX = arcRect.left - 50f;
        final float lineEndX = arcRect.right + 50f;
        final float lineY = arcRect.centerY();
        canvas.drawLine(lineStartX, lineY, lineEndX, lineY, linePaint);
    }
}


问:
Use properties in gradle liquibase
I'm trying to run liquibase scripts to create Posgresql DB + schemas.

Here're some pieces of liquibase .groovy configs and scripts and build.gradle.

build.gradle

```<code>apply plugin: 'liquibase'
buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath 'org.liquibase:liquibase-gradle-plugin:1.2.0'
        classpath "org.postgresql:postgresql:${postgreJdbcDriverVersion}"
    }
}

sourceSets {
    main {
        java {
            srcDir 'src/main/liquibase'
        }
    }
}

liquibase {
    activities {
        main {
            File propsFile = new File("src/main/resources/database.properties")
            Properties properties = new Properties()
            properties.load(new FileInputStream(propsFile))
            changeLogFile 'src/main/liquibase/com/freemmy/sample/spring/acl/sample/db/main-changelog.groovy'
            url "${dbUrl}"
            username "${dbUsername}"
            password "${dbPassword}"
        }
    }
    runList = 'main'
}
</code>```

For example I have the following changeset in main-changelog.groovy:

```<code>changeSet(id: '2016-12-10-a', author: 'Dzmitry Dziokin', runInTransaction: false, runAlways: true, runOnChange: true, failOnError: false, dbms: 'postgresql') {
        comment('Create the database role/login')
        // Ok if the role exists
        preConditions(onFail: 'CONTINUE', onFailMessage: 'Role already exists, continue') {
            sqlCheck(expectedResult: '0')
                    { "select count(*) from pg_roles where rolname= '${dbUsername}'" }
        }
        sql(stripComments: true, splitStatements: false, endDelimiter: ';') {
            "CREATE ROLE ${dbUsername} LOGIN PASSWORD '${dbPassword}'"
        }
    }
</code>```

And I have properties dbUsername and dbPassword.

But when I run, for instance, gradlew status I see the following:

```<code>Execution failed for task ':spring-acl-sample-db:status'.
</code>```

liquibase.exception.LiquibaseException: Unexpected error running Liquibase: No such property: dbUsername for class: org.liquibase.groovy.delegate.PreconditionDelegate

I asked Google, but I haven't found any solution or suggestion.

Does someone know what is happening?

答:
You should probably use the properties prefix in the interpolation.

```<code>url "${properties.dbUrl}"
username "${properties.dbUsername}"
password "${properties.dbPassword}"
</code>```

Title: Use properties in gradle liquibase

Body:
I'm trying to run liquibase scripts to create Posgresql DB + schemas.

Here're some pieces of liquibase .groovy configs and scripts and build.gradle.

build.gradle

apply plugin: 'liquibase'
buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath 'org.liquibase:liquibase-gradle-plugin:1.2.0'
        classpath "org.postgresql:postgresql:${postgreJdbcDriverVersion}"
    }
}

sourceSets {
    main {
        java {
            srcDir 'src/main/liquibase'
        }
    }
}

liquibase {
    activities {
        main {
            File propsFile = new File("src/main/resources/database.properties")
            Properties properties = new Properties()
            properties.load(new FileInputStream(propsFile))
            changeLogFile 'src/main/liquibase/com/freemmy/sample/spring/acl/sample/db/main-changelog.groovy'
            url "${dbUrl}"
            username "${dbUsername}"
            password "${dbPassword}"
        }
    }
    runList = 'main'
}

For example I have the following changeset in main-changelog.groovy:

changeSet(id: '2016-12-10-a', author: 'Dzmitry Dziokin', runInTransaction: false, runAlways: true, runOnChange: true, failOnError: false, dbms: 'postgresql') {
        comment('Create the database role/login')
        // Ok if the role exists
        preConditions(onFail: 'CONTINUE', onFailMessage: 'Role already exists, continue') {
            sqlCheck(expectedResult: '0')
                    { "select count(*) from pg_roles where rolname= '${dbUsername}'" }
        }
        sql(stripComments: true, splitStatements: false, endDelimiter: ';') {
            "CREATE ROLE ${dbUsername} LOGIN PASSWORD '${dbPassword}'"
        }
    }

And I have properties dbUsername and dbPassword.

But when I run, for instance, gradlew status I see the following:

Execution failed for task ':spring-acl-sample-db:status'.

liquibase.exception.LiquibaseException: Unexpected error running Liquibase: No such property: dbUsername for class: org.liquibase.groovy.delegate.PreconditionDelegate

I asked Google, but I haven't found any solution or suggestion.

Does someone know what is happening?

Body:
You should probably use the properties prefix in the interpolation.

url "${properties.dbUrl}"
username "${properties.dbUsername}"
password "${properties.dbPassword}"


问:
How to change calendar color with Google Calendar API v3?
I've got this code snippet, which edits the calendar summary with google calendar API v3:

```<code>com.google.api.services.calendar.model.Calendar calendar = mService.calendars().get(CalendarActivity.this.editid).execute();
calendar.setSummary(CalendarActivity.this.title);
com.google.api.services.calendar.model.Calendar updatedCalendar = mService.calendars().update(calendar.getId(), calendar).execute();
</code>```

But how to change the color of calendar?

There is no setColorId() method. Don't know how to do that.

答:
You can use this one:

```<code>import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.model.CalendarListEntry;

// ...

// Initialize Calendar service with valid OAuth credentials
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credentials)
    .setApplicationName("applicationName").build();

// Retrieve the calendar list entry
CalendarListEntry calendarListEntry = service.calendarList().get("calendarId").execute();

// Make a change
calendarListEntry.setColorId("0");

// Update the altered entry
CalendarListEntry updatedCalendarListEntry =
    service.calendarList().update(calendarListEntry.getId(), calendarListEntry).execute();

System.out.println(updatedCalendarListEntry.getEtag());
</code>```

https://developers.google.com/google-apps/calendar/v3/reference/calendarList/update

Body:
I've got this code snippet, which edits the calendar summary with google calendar API v3:

com.google.api.services.calendar.model.Calendar calendar = mService.calendars().get(CalendarActivity.this.editid).execute();
calendar.setSummary(CalendarActivity.this.title);
com.google.api.services.calendar.model.Calendar updatedCalendar = mService.calendars().update(calendar.getId(), calendar).execute();

But how to change the color of calendar?

There is no setColorId() method. Don't know how to do that.

Body:
You can use this one:

import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.model.CalendarListEntry;

// ...

// Initialize Calendar service with valid OAuth credentials
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credentials)
    .setApplicationName("applicationName").build();

// Retrieve the calendar list entry
CalendarListEntry calendarListEntry = service.calendarList().get("calendarId").execute();

// Make a change
calendarListEntry.setColorId("0");

// Update the altered entry
CalendarListEntry updatedCalendarListEntry =
    service.calendarList().update(calendarListEntry.getId(), calendarListEntry).execute();

System.out.println(updatedCalendarListEntry.getEtag());

https://developers.google.com/google-apps/calendar/v3/reference/calendarList/update


问:
How can I remove rows from a postgres table that all have the same value in a column, if any of those rows contains a certain value in another column?
I have a table that looks like this:

```<code>Teacher   | Class | Number of students
Ms. Smith | 101   | 101
Mr. Frank | 300   | 20
Mr. Frank | 401   | 0
Mr. Smith | 102   | 20
Ms. Date  | 300   | 0
Mr. First | 100   | 10
</code>```

I want to query and get back a table that has removed any teacher (all of their rows) who has a class of zero students, so the result I'm looking for is:

```<code>Teacher   | Class | Number of students
Ms. Smith | 101   | 101
Mr. Smith | 102   | 20
Mr. First | 100   | 10
</code>```

Any idea how I can do this? I am stumped.

答:
If you can't use subqueries:</p>

```<code>SELECT t1.Teacher, t1.Class, t1.number_of_students
FROM yourTable t1
LEFT JOIN yourTable t2
  ON t1.teacher = t2.teacher
 AND t2.number_of_students = 0
WHERE t2.teacher IS NULL
</code>```

Body:
I have a table that looks like this:

Teacher   | Class | Number of students
Ms. Smith | 101   | 101
Mr. Frank | 300   | 20
Mr. Frank | 401   | 0
Mr. Smith | 102   | 20
Ms. Date  | 300   | 0
Mr. First | 100   | 10

I want to query and get back a table that has removed any teacher (all of their rows) who has a class of zero students, so the result I'm looking for is:

Teacher   | Class | Number of students
Ms. Smith | 101   | 101
Mr. Smith | 102   | 20
Mr. First | 100   | 10

Any idea how I can do this? I am stumped.

Body:
If you can't use subqueries:

SELECT t1.Teacher, t1.Class, t1.number_of_students
FROM yourTable t1
LEFT JOIN yourTable t2
  ON t1.teacher = t2.teacher
 AND t2.number_of_students = 0
WHERE t2.teacher IS NULL


问:
Being as DRY as possible in a Ruby on Rails App
I'm currently using the awesome attachment-fu plugin for a Rails app, but as a novice developer, I've never encountered a scenario like the one I've found myself in.

Essentially, I'm using the attachment-fu plugin on two levels.

Is for user avatars in the user class.

Is to allow file attachments (PDFs, etc) in a messaging system.

My question is what the best use practice would be in these situations to remain DRY, clear, and consistent.

Clearly it would make no sense to define and execute the plugin in both classes, but there's something deeply strange to me (possibly unfounded) about just going ahead and setting it all up in the godly Application class.

Is there something in between, or is the parent class the way to go?

Thanks!

答:
For what it's worth, I think Patrick Berkeley has done a good job with handling multiple attachments through the Paperclip plugin. He's outlined his work here:

http://gist.github.com/33011

OwnerDisplayName: Bryan Woods

OwnerDisplayName: The Pied Pipes