问:
How to find file name exist in svn committed directory list
I want to trigger the jenkins build in post-commit hook.if file is committed on directory "SOURCE/databasescript" and file name is "update.sql".

post-commit

```<code>set "REPOS=%~1"
set "TXN=%~3"
set "REV=%~2"
echo "repos %REPOS%." >> C:\test.log
echo "REV %REV%." >> C:\test.log
echo "txn %TXN%." >> C:\test.log
"%VISUALSVN_SERVER%\bin\svnlook.exe" changed -r %2 %1 >>C:\test.log
</code>```

Output

```<code>"repos D:\Repositories\TestNAPFServer."
"REV 82."
"txn 81-2e."
U   SOURCE/databasescript/basedb.sql
U   SOURCE/databasescript/update.sql
</code>```

I do not know how to write condition to find the filename in directory list in batch file.Please suggest.

答:
Below solution work for me:

Post-commit.cmd

```<code>setlocal enabledelayedexpansion
@echo off
REM Get the current path
set mypath=%cd%

set "REPOS=%~1"
set "TXN=%~3"
set "REV=%~2"
REM create log folder
IF NOT EXIST %REPOS%\log (
    md %REPOS%\log\
)
REM Delete the file log file
del /F /Q %REPOS%\log\napfposthook.log
echo "Current path-%mypath%" >> %REPOS%\log\napfposthook.log
echo "repos %REPOS%." >> %REPOS%\log\napfposthook.log
echo "REV %REV%." >> %REPOS%\log\napfposthook.log
echo "txn %TXN%." >> %REPOS%\log\napfposthook.log
set SVNLOOK="%VISUALSVN_SERVER%\bin\svnlook.exe"
%SVNLOOK% changed -r %2 %1 >> %REPOS%\log\napfposthook.log

Set SEPARATOR=,
SET COMMENT=

REM Concatenate all the lines in the commit message
fOR /F "tokens=2 delims= " %%g IN ('%SVNLOOK% changed -r %REV% %REPOS%') do (
    set currentline=%%g
    set COMMENT=!COMMENT!%SEPARATOR%!currentline!
)

REM Delete the file before insert the directory list
del /F /Q  %REPOS%\log\napfsearch.txt

REM Write the all directory list into file
echo %COMMENT% >> %REPOS%\log\napfsearch.txt

REM Find the string into file
find /I "update.sql" "%REPOS%\log\napfsearch.txt">nul
set findStatus=%errorlevel%
echo %findStatus% >> %REPOS%\log\napfposthook.log

SET CSCRIPT=%windir%\system32\cscript.exe
SET VBSCRIPT=D:\Repositories\post-commit-hook-jenkins-sam.vbs
"%CSCRIPT%" "%VBSCRIPT%" "NAPF_PRODB" "f23338c8b8f7216fad54dd34da7a2a5d" "%findStatus%"
</code>```

post-commit-hook-jenkins-sam.vbs

```<code>Set args = WScript.Arguments
JobName = args.Item(0)
Token = args.Item(1)
updateDbScript=args.Item(2)
JenkinsServerUrl="http://10.254.6.206:8080/jenkins/"

If updateDbScript = 0 Then
    Wscript.Echo "Triggered the update job..."
    updateUrl = JenkinsServerUrl+"/buildByToken/buildWithParameters?job=" + JobName + "&token=" + Token+ "&Type=1"
    updateRequest = ""
    'Sending rest request to jenkins
    HTTPPost updateUrl, updateRequest
else
     Wscript.Echo "Triggered the jenkins main job..."
     sUrl = JenkinsServerUrl+"/buildByToken/buildWithParameters?job=" + JobName + "&token=" + Token+ "&Type=0"
    'POST Request to send....
    sRequest = ""
    'Sending rest request to jenkins
    HTTPPost sUrl, sRequest
End If

Function HTTPPost(sUrl, sRequest)
  set oHTTP = CreateObject("Microsoft.XMLHTTP")
  oHTTP.open "POST", sUrl,false
  oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  oHTTP.setRequestHeader "Content-Length", Len(sRequest)
  oHTTP.send sRequest
  HTTPPost = oHTTP.responseText
 End Function
</code>```

Body:
I want to trigger the jenkins build in post-commit hook.if file is committed on directory "SOURCE/databasescript" and file name is "update.sql".

post-commit

set "REPOS=%~1"
set "TXN=%~3"
set "REV=%~2"
echo "repos %REPOS%." >> C:\test.log
echo "REV %REV%." >> C:\test.log
echo "txn %TXN%." >> C:\test.log
"%VISUALSVN_SERVER%\bin\svnlook.exe" changed -r %2 %1 >>C:\test.log

Output

"repos D:\Repositories\TestNAPFServer."
"REV 82."
"txn 81-2e."
U   SOURCE/databasescript/basedb.sql
U   SOURCE/databasescript/update.sql

I do not know how to write condition to find the filename in directory list in batch file.Please suggest.

Body:
Below solution work for me:

Post-commit.cmd

setlocal enabledelayedexpansion
@echo off
REM Get the current path
set mypath=%cd%

set "REPOS=%~1"
set "TXN=%~3"
set "REV=%~2"
REM create log folder
IF NOT EXIST %REPOS%\log (
    md %REPOS%\log\
)
REM Delete the file log file
del /F /Q %REPOS%\log\napfposthook.log
echo "Current path-%mypath%" >> %REPOS%\log\napfposthook.log
echo "repos %REPOS%." >> %REPOS%\log\napfposthook.log
echo "REV %REV%." >> %REPOS%\log\napfposthook.log
echo "txn %TXN%." >> %REPOS%\log\napfposthook.log
set SVNLOOK="%VISUALSVN_SERVER%\bin\svnlook.exe"
%SVNLOOK% changed -r %2 %1 >> %REPOS%\log\napfposthook.log

Set SEPARATOR=,
SET COMMENT=

REM Concatenate all the lines in the commit message
fOR /F "tokens=2 delims= " %%g IN ('%SVNLOOK% changed -r %REV% %REPOS%') do (
    set currentline=%%g
    set COMMENT=!COMMENT!%SEPARATOR%!currentline!
)

REM Delete the file before insert the directory list
del /F /Q  %REPOS%\log\napfsearch.txt

REM Write the all directory list into file
echo %COMMENT% >> %REPOS%\log\napfsearch.txt

REM Find the string into file
find /I "update.sql" "%REPOS%\log\napfsearch.txt">nul
set findStatus=%errorlevel%
echo %findStatus% >> %REPOS%\log\napfposthook.log

SET CSCRIPT=%windir%\system32\cscript.exe
SET VBSCRIPT=D:\Repositories\post-commit-hook-jenkins-sam.vbs
"%CSCRIPT%" "%VBSCRIPT%" "NAPF_PRODB" "f23338c8b8f7216fad54dd34da7a2a5d" "%findStatus%"

post-commit-hook-jenkins-sam.vbs

Set args = WScript.Arguments
JobName = args.Item(0)
Token = args.Item(1)
updateDbScript=args.Item(2)
JenkinsServerUrl="http://10.254.6.206:8080/jenkins/"

If updateDbScript = 0 Then
    Wscript.Echo "Triggered the update job..."
    updateUrl = JenkinsServerUrl+"/buildByToken/buildWithParameters?job=" + JobName + "&token=" + Token+ "&Type=1"
    updateRequest = ""
    'Sending rest request to jenkins
    HTTPPost updateUrl, updateRequest
else
     Wscript.Echo "Triggered the jenkins main job..."
     sUrl = JenkinsServerUrl+"/buildByToken/buildWithParameters?job=" + JobName + "&token=" + Token+ "&Type=0"
    'POST Request to send....
    sRequest = ""
    'Sending rest request to jenkins
    HTTPPost sUrl, sRequest
End If

Function HTTPPost(sUrl, sRequest)
  set oHTTP = CreateObject("Microsoft.XMLHTTP")
  oHTTP.open "POST", sUrl,false
  oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  oHTTP.setRequestHeader "Content-Length", Len(sRequest)
  oHTTP.send sRequest
  HTTPPost = oHTTP.responseText
 End Function


来源: stackexchange

问:
Open Python IDLE with flags
I am currently working through MIT's OpenCourseWare subject "Introduction to Electrical Engineering and Computer Science 1", and am up to the module on the Signals class.

I am having trouble with using the plotting method in the class. The course material states:

"Be sure to start idle with the -n flag, if you want to make plots of signals from inside idle."

This is the first time in my coding education that I have come across starting a program with a flag. I think I understand the general gist of what it entails and have played around with opening IDLE using the windows command prompt.

However, I have had no luck so far and notwithstanding my guesses don't really know what I'm doing.

Would someone be able to explain how exactly I can do this and more generally how opening programs with flags works?

I have done some google/stack searches but have only come up with stack overflow material assuming the knowledge I'm looking for in answering other questions or information discussing flags in the context of coding functions in python itself (myFlag=False or whatever).

I am using python 2.6.

Many thanks in advance. Apologies if the question is silly or obvious, I'm quite new to coding.

答:
idle is just another program run by the OS.  just like grep or ls can have flags so can idle.  flags just make it easier and more efficient to parse the parameters on the command line.  on macos hre are the options.  windows will be similar</p>

```<code>└─╼ idle -h

USAGE: idle  [-deins] [-t title] [file]*
       idle  [-dns] [-t title] (-c cmd | -r file) [arg]*
       idle  [-dns] [-t title] - [arg]*

  -h         print this help message and exit
  -n         run IDLE without a subprocess (see Help/IDLE Help for details)

The following options will override the IDLE 'settings' configuration:

  -e         open an edit window
  -i         open a shell window

The following options imply -i and will open a shell:

  -c cmd     run the command in a shell, or
  -r file    run script from file

  -d         enable the debugger
  -s         run $IDLESTARTUP or $PYTHONSTARTUP before anything else
  -t title   set title of shell window

A default edit window will be bypassed when -c, -r, or - are used.

[arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].

Examples:

idle
        Open an edit window or shell depending on IDLE's configuration.

idle foo.py foobar.py
        Edit the files, also open a shell if configured to start with shell.

idle -est "Baz" foo.py
        Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
        window with the title "Baz".

idle -c "import sys; print sys.argv" "foo"
        Open a shell window and run the command, passing "-c" in sys.argv[0]
        and "foo" in sys.argv[1].

idle -d -s -r foo.py "Hello World"
        Open a shell window, run a startup script, enable the debugger, and
        run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
        sys.argv[1].

echo "import sys; print sys.argv" | idle - "foobar"
        Open a shell window, run the script piped in, passing '' in sys.argv[0]
        and "foobar" in sys.argv[1].
</code>```

ContentLicense: CC BY-SA 3.0

Title: Open Python IDLE with flags

Body:
idle is just another program run by the OS.  just like grep or ls can have flags so can idle.  flags just make it easier and more efficient to parse the parameters on the command line.  on macos hre are the options.  windows will be similar

└─╼ idle -h

USAGE: idle  [-deins] [-t title] [file]*
       idle  [-dns] [-t title] (-c cmd | -r file) [arg]*
       idle  [-dns] [-t title] - [arg]*

  -h         print this help message and exit
  -n         run IDLE without a subprocess (see Help/IDLE Help for details)

The following options will override the IDLE 'settings' configuration:

  -e         open an edit window
  -i         open a shell window

The following options imply -i and will open a shell:

  -c cmd     run the command in a shell, or
  -r file    run script from file

  -d         enable the debugger
  -s         run $IDLESTARTUP or $PYTHONSTARTUP before anything else
  -t title   set title of shell window

A default edit window will be bypassed when -c, -r, or - are used.

[arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].

Examples:

idle
        Open an edit window or shell depending on IDLE's configuration.

idle foo.py foobar.py
        Edit the files, also open a shell if configured to start with shell.

idle -est "Baz" foo.py
        Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
        window with the title "Baz".

idle -c "import sys; print sys.argv" "foo"
        Open a shell window and run the command, passing "-c" in sys.argv[0]
        and "foo" in sys.argv[1].

idle -d -s -r foo.py "Hello World"
        Open a shell window, run a startup script, enable the debugger, and
        run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
        sys.argv[1].

echo "import sys; print sys.argv" | idle - "foobar"
        Open a shell window, run the script piped in, passing '' in sys.argv[0]
        and "foobar" in sys.argv[1].


问:
failed to connect to mail server in PHP
I have written a small piece of PHP code for sending mail:

```<code>   <?php
    //define the receiver of the email
    $to = 'rohaanthakare@gmail.com';
    //define the subject of the email
    $subject = 'Hishob email';
    //define the message to be sent. Each line should be separated with \n
    $message = "Hello World!\n\nThis is my first mail.";
    //define the headers we want passed. Note that they are separated with \r\n
    $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
    //send the email
    $mail_sent = mail( $to, $subject, $message, $headers );
    //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
    echo $mail_sent ? "Mail sent" : "Mail failed";
    ?>
</code>```

after executing it I got following warning:

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\NewHishob\PhpFiles\send_mail.php on line 11

  Mail failed

I am using a WAMP server and there are two files, INI-DIST and other is INI-RECOMENDED. Which one is important?

I had also gone through php.ini-dist file and for SMTP it contains the following:

```<code>[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =
</code>```

Please suggest what I should do? Thanks to all in advance.

答: Also you cannot guarantee that your mail have been sent, as the script doesn't wait for the mailserver to continue. </p>

ContentLicense: CC BY-SA 2.5

Title: failed to connect to mail server in PHP

Body:
I have written a small piece of PHP code for sending mail:

   <?php
    //define the receiver of the email
    $to = 'rohaanthakare@gmail.com';
    //define the subject of the email
    $subject = 'Hishob email';
    //define the message to be sent. Each line should be separated with \n
    $message = "Hello World!\n\nThis is my first mail.";
    //define the headers we want passed. Note that they are separated with \r\n
    $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
    //send the email
    $mail_sent = mail( $to, $subject, $message, $headers );
    //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
    echo $mail_sent ? "Mail sent" : "Mail failed";
    ?>

after executing it I got following warning:

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\NewHishob\PhpFiles\send_mail.php on line 11

  Mail failed

I am using a WAMP server and there are two files, INI-DIST and other is INI-RECOMENDED. Which one is important?

I had also gone through php.ini-dist file and for SMTP it contains the following:

[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =

Please suggest what I should do? Thanks to all in advance.


问:
Any way to convert my JSP project into Spring, though it has so many JSP files?
I have a project which is coded in JSP. It has about 60 jsp files. Now i want to change the code from jsp to spring. So is there any way to do this.
Should i write each jsp file in spring individually or any short cut for this transformation .
How to start please give any suggestion.
Note: There is DATABASE connectivity also.
Thanks

答: you can add spring dependencies in your project and can follow MVC pattern where your  (business logic) should move to Controllers and database related code (Connection to DB, Query to DB) should move into Services and you can use your JSP files for views only.


问:
How to upload file ( picture ) with selenium, python
How to upload a picture on a web application with the selenium testing tool? I am using python.

I tried many things, but nothing worked.

答:
Using splinter :

browser.attach_file('file_chooser_id',fully_qualified_file_path)

ContentLicense: CC BY-SA 4.0


问:
How can i get values from $stateChanges
Please Helpme How can i get values from $statechangeStart and $stateChaneSuccess

MyApp.js

```<code>app.run(function ($rootScope) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
          $scope.IsLoading = true;

    })
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams, options) {
           $scope.IsLoading = False;
    })
})
</code>```

Home.js

///Here How can i use IsLoading

答:
Use providers (generally a service or factory, maybe a .value) to define things that can be injected into controllers.

https://docs.angularjs.org/guide/providers

https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

Best practice for using $rootscope in an Angularjs application?

angular.module('myapp',[])
  .value('SharedObject', {isLoading:true})
  .run(function($timeout, SharedObject){
    $timeout(function(){SharedObject.isLoading = false}, 2000);
  })
  .controller('MyCtrl', function(SharedObject){
    this.SharedObject = SharedObject;
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="myapp">

  <head>
    <script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
  </head>

  <body ng-controller="MyCtrl as myctrl">
    {{myctrl.SharedObject}}
  </body>

</html></code>```

Title: How can i get values from $stateChanges

Body:
Please Helpme How can i get values from $statechangeStart and $stateChaneSuccess

MyApp.js

app.run(function ($rootScope) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
          $scope.IsLoading = true;

    })
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams, options) {
           $scope.IsLoading = False;
    })
})

Home.js

///Here How can i use IsLoading

Body:
Use providers (generally a service or factory, maybe a .value) to define things that can be injected into controllers.

https://docs.angularjs.org/guide/providers

https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

Best practice for using $rootscope in an Angularjs application?

angular.module('myapp',[])
  .value('SharedObject', {isLoading:true})
  .run(function($timeout, SharedObject){
    $timeout(function(){SharedObject.isLoading = false}, 2000);
  })
  .controller('MyCtrl', function(SharedObject){
    this.SharedObject = SharedObject;
  })

<!DOCTYPE html>
<html ng-app="myapp">

  <head>
    <script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
  </head>

  <body ng-controller="MyCtrl as myctrl">
    {{myctrl.SharedObject}}
  </body>

</html>


问:
ALM-PC - Can same license file/keys used from 12.20 to 12.55
We have working ALM-PC 12.20 setup. We are planning to move to latest HPE-PC 12.55 version. So, after clean install of 12.55, can same license file/keys will work on new version?

Also, if we removed old setup and installed latest 12.55 version on different VM(s). Is same license will be valid for the new machine? Or we need to get new license from HP?

答: Loadrunner 12.X all have the same license mechanism. You can use Loadrunner's 12.2 license on Loadrunner 12.55.</p>


问:
I have two regex in .net preRegex = "(?<=(^|[^A-Za-z0-9]+))" postRegex = "(?=([^A-Za-z0-9]+)|$)" . What is the alternate of it in python?
I have two regex strings in .net

```<code>preRegex = "(?<=(^|[^A-Za-z0-9]+))"
postRegex = "(?=([^A-Za-z0-9]+)|$)"
</code>```

I want their alternative in python. My problem is let say I have a string

```<code>s="I am in aeroplane."
</code>```

What I need is to replace "aeroplane with aeroPlain" so I want to make regex like

```<code>newKey = preRegex + aeroplane + postRegex
pattern = re.compile(newKey,re.IGNORECASE)
</code>```

new regex string look like

```<code>(?<=(^|[^A-Za-z0-9]+))aeroplane(?=([^A-Za-z0-9]+)|$)
</code>```

but it is giving me error "look-behind requires fixed-width pattern".
I am new to python, Help would be appreciated. Thanks

答:
You can use the following regex:

```<code>(^|[^A-Za-z0-9]+)aeroplane([^A-Za-z0-9]+|$)
</code>```

and when you replace, you can call the back reference to the first and second part of your regex to fetch their value.

Replacement string will be something like '\1aeroPlain\2'.
For more information on backref in python:https://docs.python.org/3/howto/regex.html

Good luck!

Body:
I have two regex strings in .net

preRegex = "(?<=(^|[^A-Za-z0-9]+))"
postRegex = "(?=([^A-Za-z0-9]+)|$)"

I want their alternative in python. My problem is let say I have a string

s="I am in aeroplane."

What I need is to replace "aeroplane with aeroPlain" so I want to make regex like

newKey = preRegex + aeroplane + postRegex
pattern = re.compile(newKey,re.IGNORECASE)

new regex string look like

(?<=(^|[^A-Za-z0-9]+))aeroplane(?=([^A-Za-z0-9]+)|$)

but it is giving me error "look-behind requires fixed-width pattern".
I am new to python, Help would be appreciated. Thanks

Body:
You can use the following regex:

(^|[^A-Za-z0-9]+)aeroplane([^A-Za-z0-9]+|$)

and when you replace, you can call the back reference to the first and second part of your regex to fetch their value.

Replacement string will be something like '\1aeroPlain\2'.
For more information on backref in python:https://docs.python.org/3/howto/regex.html

Good luck!


问:
How to limit a view to superuser only?
view.py

```<code>@login_required
@permission_required('is_superuser')
def score_reset(request):
   pass
</code>```

url.py

```<code>url(r'^score-reset/$', score_reset, name='score-reset'),
</code>```

I have the following code and to my surprise I still hit the function, despite being logged in with a non superuser. I was expecting to get a permission denied.

What am I missing?

答:
Above answers seems to be for very early versions of django.
They are bit complicated than for the more later version

for django 1.11 here is a bit similar but simpler strategy.

views.py

```<code>from django.contrib.auth.decorators import login_required

@login_required
def some_view(request):
if request.user.is_superuser:
    //allow access only to superuser
    return render(request, 'app/template1.html', args)
else:
    //allow access only to user
    return render(request, 'app/template2.html', args)
</code>```

Title: How to limit a view to superuser only?

Body:
view.py

@login_required
@permission_required('is_superuser')
def score_reset(request):
   pass

url.py

url(r'^score-reset/$', score_reset, name='score-reset'),

I have the following code and to my surprise I still hit the function, despite being logged in with a non superuser. I was expecting to get a permission denied.

What am I missing?

Body:
Above answers seems to be for very early versions of django.
They are bit complicated than for the more later version

for django 1.11 here is a bit similar but simpler strategy.

views.py

from django.contrib.auth.decorators import login_required

@login_required
def some_view(request):
if request.user.is_superuser:
    //allow access only to superuser
    return render(request, 'app/template1.html', args)
else:
    //allow access only to user
    return render(request, 'app/template2.html', args)


问:
If a then function doesn't return a promise, why the next then will be run immediately?
Inside of a then() function, if I didn't return a promise but calling the function directly.

```<code>doSomething().then(function () {
  doSomethingElse(); //I know I should return doSomethingElse()
}).then(finalHandler);
</code>```

I know doSomethingElse & finalHandler will run in parallel then instead of running sequentially. But I am still not sure why is that exactly?

```<code>doSomething
|-----------------|
                  doSomethingElse(undefined)
                  |------------------|
                  finalHandler(undefined)
                  |------------------|
</code>```

答:
The function does not need to return a Promise. If nothing was explicitly returned, by default undefined is returned. Functions in Javascript work like that. See the example

function doSomething() {

}

console.log(doSomething());```
</div>
</div>
</p>

<p>When you return a <code>Promise</code> from the function in the <code>then</code> chains, <code>then</code> will work only if the returned <code>Promise</code> is resolved. If an exception was occurred, the <code>catch</code> function will work if the last exists.
So actually your code is like</p>

```doSomething().then(function () {
  doSomethingElse();
  return undefined;
}).then(finalHandler); `undefined` is passed into the `finalHandler` function
```

What about the parallel, they will work not in parallel, but sequentially if the code is then(...).then(...). These then work sequentially. But if your doSomethingElse also returns a Promise, it will have its own sequence of chain. It's flow is independent from the doSomething flow.

Body:
Inside of a then() function, if I didn't return a promise but calling the function directly.

doSomething().then(function () {
  doSomethingElse(); //I know I should return doSomethingElse()
}).then(finalHandler);

I know doSomethingElse & finalHandler will run in parallel then instead of running sequentially. But I am still not sure why is that exactly?

doSomething
|-----------------|
                  doSomethingElse(undefined)
                  |------------------|
                  finalHandler(undefined)
                  |------------------|

Body:
The function does not need to return a Promise. If nothing was explicitly returned, by default undefined is returned. Functions in Javascript work like that. See the example

function doSomething() {

}

console.log(doSomething());

When you return a Promise from the function in the then chains, then will work only if the returned Promise is resolved. If an exception was occurred, the catch function will work if the last exists.
So actually your code is like

doSomething().then(function () {
  doSomethingElse();
  return undefined;
}).then(finalHandler); `undefined` is passed into the `finalHandler` function

What about the parallel, they will work not in parallel, but sequentially if the code is then(...).then(...). These then work sequentially. But if your doSomethingElse also returns a Promise, it will have its own sequence of chain. It's flow is independent from the doSomething flow.


问:
Sum the value of some hash keys inside an array
I try to search but any solution doesn't work.

I have this array of hashes

```<code>[{:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>1}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>1}, {:smartphone=>"iPhone X - Apple", :votes=>1}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>1}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>1}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>1}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>1}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}]
</code>```

And I want to sum the votes for every smartphone

I try with

```<code>results.group_by { |hash1| hash1[:smartphone] }.map do |_,v|
  v.inject do |ele_hash2,ele_hash1|
      puts ele_hash2
      puts ele_hash1
     ele_hash2.merge(ele_hash1) {|k,o,n| k == :vote ? o+n : o }
  end
end
</code>```

But it returns me

```<code>[{:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>1}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}]
</code>```

And it's not correct, Apple iPhone X has 1 vote for example.
Why?

答:
```<code>input.
  group_by { |h| h[:smartphone] }.
  map { |k, v| [k, v.reduce(0) { |acc, h| acc + h[:votes] }] }.
  to_h
#⇒ {
#  "Galaxy Note 8 - Samsung" => 1,
#     "Mate 10 Pro - Huawei" => 0,
#                  "Nokia 8" => 0,
#              "One Plus 5T" => 0,
#      "Pixel 2 XL - Google" => 1,
#                "U11 - HTC" => 1,
#                 "V30 - LG" => 1,
#        "Xperia XZ1 - Sony" => 0,
#          "Z2 Force - Moto" => 0,
#     "ZenFone 4 Pro - Asus" => 1,
#         "iPhone X - Apple" => 2
# }
</code>```

or, to receive the exact result as you wanted:

```<code>input.
  group_by { |h| h[:smartphone] }.
  map do |k, v|
    {smartphone: k, votes: v.reduce(0) { |acc, h| acc + h[:votes] }}
  end
</code>```

Your code does not work because inside Hash#merge you have a typo k == :vote should read k == :votes.

Body:
I try to search but any solution doesn't work.

I have this array of hashes

[{:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>1}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>1}, {:smartphone=>"iPhone X - Apple", :votes=>1}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>1}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>1}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>1}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>1}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}]

And I want to sum the votes for every smartphone

I try with

results.group_by { |hash1| hash1[:smartphone] }.map do |_,v|
  v.inject do |ele_hash2,ele_hash1|
      puts ele_hash2
      puts ele_hash1
     ele_hash2.merge(ele_hash1) {|k,o,n| k == :vote ? o+n : o }
  end
end

But it returns me

[{:smartphone=>"Galaxy Note 8 - Samsung", :votes=>0}, {:smartphone=>"ZenFone 4 Pro - Asus", :votes=>0}, {:smartphone=>"Xperia XZ1 - Sony", :votes=>0}, {:smartphone=>"Mate 10 Pro - Huawei", :votes=>0}, {:smartphone=>"V30 - LG", :votes=>0}, {:smartphone=>"One Plus 5T", :votes=>0}, {:smartphone=>"Pixel 2 XL - Google", :votes=>1}, {:smartphone=>"Nokia 8", :votes=>0}, {:smartphone=>"Z2 Force - Moto", :votes=>0}, {:smartphone=>"U11 - HTC", :votes=>0}, {:smartphone=>"iPhone X - Apple", :votes=>0}]

And it's not correct, Apple iPhone X has 1 vote for example.
Why?

Body:
input.
  group_by { |h| h[:smartphone] }.
  map { |k, v| [k, v.reduce(0) { |acc, h| acc + h[:votes] }] }.
  to_h
#⇒ {
#  "Galaxy Note 8 - Samsung" => 1,
#     "Mate 10 Pro - Huawei" => 0,
#                  "Nokia 8" => 0,
#              "One Plus 5T" => 0,
#      "Pixel 2 XL - Google" => 1,
#                "U11 - HTC" => 1,
#                 "V30 - LG" => 1,
#        "Xperia XZ1 - Sony" => 0,
#          "Z2 Force - Moto" => 0,
#     "ZenFone 4 Pro - Asus" => 1,
#         "iPhone X - Apple" => 2
# }

or, to receive the exact result as you wanted:

input.
  group_by { |h| h[:smartphone] }.
  map do |k, v|
    {smartphone: k, votes: v.reduce(0) { |acc, h| acc + h[:votes] }}
  end

Your code does not work because inside Hash#merge you have a typo k == :vote should read k == :votes.


问:
Get First 2 Characters In a String
I'm trying to get first 2 characters in a string. Here's my code:

```<code>$s = 'hello'; // line 4
printf("[%0.2s]\n", %s); // line 5: Gets first 2 characters [he]
</code>```

It's giving me an error:

Parse error: syntax error, unexpected '%' in
  C:\laragon\www\karakter_tamamlama.php on line 5

Why am I getting error?

答:
Second arg should be $s, see printf()

```<code>printf("[%0.2s]\n", $s);
</code>```

Title: Get First 2 Characters In a String

Body:
I'm trying to get first 2 characters in a string. Here's my code:

$s = 'hello'; // line 4
printf("[%0.2s]\n", %s); // line 5: Gets first 2 characters [he]

It's giving me an error:

Parse error: syntax error, unexpected '%' in
  C:\laragon\www\karakter_tamamlama.php on line 5

Why am I getting error?

Body:
Second arg should be $s, see printf()

printf("[%0.2s]\n", $s);


Title: Get First 2 Characters In a String

Body:
$s instead of %s

printf("[%0.2s]\n", $s);

or

substr($s, 0,2);


问:
Rails model and scaffold for Posts and Likes
I would like to generate a model and scaffold for a "Like" feature in my application. The application has a "Post" model and a "User" model. The users can "Like" the different posts (just like any other social network software)

I am using mongoid and ROR 5.

The User model:

```<code>class User
  include Mongoid::Document
  field :created_at, type: String
  field :updated_at, type: String

  has_many :posts
end
</code>```

The Post model:

```<code>class Post
  include Mongoid::Document
  field :created_at, type: String
  field :updated_at, type: String

  belongs_to :user
end
</code>```

What would be a proper "Like" model? My best guess was that the "Like" should be embedded in the User model, and "belongs_to" a Post.

How do I scaffold the Like model?
How would the "User" or the "Post" model change as a result?

答:
It really depends on how you use the collection.

When you embed the Like collection in User, but want to display like count on every posts, then the embedded solution seems redundant. And vice versa with embed to Post

The easiest way that you can create an independent collection Like without affecting User or Post

```<code>class Like
  include Mongoid::Document
  field :user_id, type: String
  field :post_id, type: String
end
</code>```

And use it as SQL relation ( same with the relation between User and Post )

```<code>class User
  # ...
  has_many :likes
end

class Post
  # ...
  has_many :likes
end
</code>```

You need some extra check when creating Like to make sure a user can like a post only once.

For extra speed ( without care about structure ), you can skip the Like collection and embed references directly to User and Post. Ofcourse this way need more extra check when do the like action

```<code>class User
  # ...
  field :liked_post_ids, type: Array, default: []
end

class Post
  # ...
  field :liked_user_ids, type: Array, default: []
end
</code>```

In NoSQL world, the structure depends on how you use the data, not how beautiful it is. But in my opinion, you should create the independent Like collection.

Body:
I would like to generate a model and scaffold for a "Like" feature in my application. The application has a "Post" model and a "User" model. The users can "Like" the different posts (just like any other social network software)

I am using mongoid and ROR 5.

The User model:

class User
  include Mongoid::Document
  field :created_at, type: String
  field :updated_at, type: String

  has_many :posts
end

The Post model:

class Post
  include Mongoid::Document
  field :created_at, type: String
  field :updated_at, type: String

  belongs_to :user
end

What would be a proper "Like" model? My best guess was that the "Like" should be embedded in the User model, and "belongs_to" a Post.

How do I scaffold the Like model?
How would the "User" or the "Post" model change as a result?

Body:
It really depends on how you use the collection.

When you embed the Like collection in User, but want to display like count on every posts, then the embedded solution seems redundant. And vice versa with embed to Post

The easiest way that you can create an independent collection Like without affecting User or Post

class Like
  include Mongoid::Document
  field :user_id, type: String
  field :post_id, type: String
end

And use it as SQL relation ( same with the relation between User and Post )

class User
  # ...
  has_many :likes
end

class Post
  # ...
  has_many :likes
end

You need some extra check when creating Like to make sure a user can like a post only once.

For extra speed ( without care about structure ), you can skip the Like collection and embed references directly to User and Post. Ofcourse this way need more extra check when do the like action

class User
  # ...
  field :liked_post_ids, type: Array, default: []
end

class Post
  # ...
  field :liked_user_ids, type: Array, default: []
end

In NoSQL world, the structure depends on how you use the data, not how beautiful it is. But in my opinion, you should create the independent Like collection.


问:
Is it possible to customize width of Picker in React Native?

Im a newbie using React Native.

I jus create an application as on the screenshot.

I want to make the dropdown or Picker component a bit smaller.

But I cant do it, Im looking for a guide to solve this.

Thanks.

My application:

import React, { Component } from 'react'
import { Item, Picker, TouchableOpacity, View, ListView, Text } from 'react-native'
import { connect } from 'react-redux'
import { Icon, Header } from 'react-native-elements'
import { Button, Container, Content, Footer, Title} from 'native-base'

// For empty lists
// import AlertMessage from '../Components/AlertMessage'

// Styles
import styles from './Styles/MainRestoStyles'

class MainRestoScreen extends React.Component {
  constructor (props) {
    super(props)

    /* ***********************************************************
    * STEP 1
    * This is an array of objects with the properties you desire
    * Usually this should come from Redux mapStateToProps
    *************************************************************/
    const dataObjects = {
      first: [
        {title: 'First Title', description: 'First Description'},
        {title: 'Second Title', description: 'Second Description'},
        {title: 'Third Title', description: 'Third Description'},
        {title: 'Fourth Title', description: 'Fourth Description'},
        {title: 'Fifth Title', description: 'Fifth Description'},
        {title: 'Sixth Title', description: 'Sixth Description'},
        {title: 'Seventh Title', description: 'Seventh Description'},
        {title: 'Eighth Title', description: 'Eighth Description'},
        {title: 'Ninth Title', description: 'Ninth Description'},
        {title: 'Tenth Title', description: 'Tenth Description'}
      ],
      second: [
        {title: 'Eleventh Title', description: 'Eleventh Description'},
        {title: '12th Title', description: '12th Description'},
        {title: '13th Title', description: '13th Description'},
        {title: '14th Title', description: '14th Description'},
        {title: '15th Title', description: '15th Description'},
        {title: '16th Title', description: '16th Description'},
        {title: '17th Title', description: '17th Description'},
        {title: '18th Title', description: '18th Description'},
        {title: '19th Title', description: '19th Description'},
        {title: '20th Title', description: '20th Description'},
        {title: 'BLACKJACK!', description: 'BLACKJACK! Description'}
      ]
    }
    /* ***********************************************************
    * STEP 2
    * Teach datasource how to detect if rows are different
    * Make this function fast!  Perhaps something like:
    *   (r1, r2) => r1.id !== r2.id}
    *   The same goes for sectionHeaderHasChanged
    *************************************************************/
    const rowHasChanged = (r1, r2) => r1 !== r2
    const sectionHeaderHasChanged = (s1, s2) => s1 !== s2

    // DataSource configured
    const ds = new ListView.DataSource({rowHasChanged, sectionHeaderHasChanged})

    // Datasource is always in state
    this.state = {
      dataSource: ds.cloneWithRowsAndSections(dataObjects)
    }
  }

  /* ***********************************************************
  * STEP 3
  * `renderRow` function -How each cell/row should be rendered
  * It's our best practice to place a single component here:
  *
  * e.g.
    return <MyCustomCell title={rowData.title} description={rowData.description} />
  *************************************************************/
  renderRow (rowData, sectionID) {
    // You can condition on sectionID (key as string), for different cells
    // in different sections
    return (
      <TouchableOpacity style={styles.row}>
        <Text style={styles.boldLabel}>Section {sectionID} - {rowData.title}</Text>
        <Text style={styles.label}>{rowData.description}</Text>
      </TouchableOpacity>
    )
  }

  /* ***********************************************************
  * STEP 4
  * If your datasource is driven by Redux, you'll need to
  * reset it when new data arrives.
  * DO NOT! place `cloneWithRowsAndSections` inside of render, since render
  * is called very often, and should remain fast!  Just replace
  * state's datasource on newProps.
  *
  * e.g.
    componentWillReceiveProps (newProps) {
      if (newProps.someData) {
        this.setState(prevState => ({
          dataSource: prevState.dataSource.cloneWithRowsAndSections(newProps.someData)
        }))
      }
    }
  *************************************************************/

  // Used for friendly AlertMessage
  // returns true if the dataSource is empty
  noRowData () {
    return this.state.dataSource.getRowCount() === 0
  }

  render () {
    return (
      <Container>
        <View style={styles.toolbar}>
          <Text style={styles.toolbarButton}></Text>
          <Icon name='bowl' type='entypo' size={40} color='white'/>
          <Text style={styles.toolbarButton}></Text>
        </View>
        <Content>
        <Picker>
            <Picker.Item
              label='Hello'
              value='hello'
            />
          </Picker>
          <ListView
            contentContainerStyle={styles.listContent}
            dataSource={this.state.dataSource}
            onLayout={this.onLayout}
            renderRow={this.renderRow}
            enableEmptySections
          />
        </Content>

          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='location' type='entypo' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='heart' type='foundation' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='bell' type='entypo' color='white' size={30}/>
          </Button>

      </Container>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    // ...redux state to props here
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(MainRestoScreen)```
</div>
</div>
</p>

<p>update:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><View>
  <Picker style={{ marginLeft: 80, marginRight: 80 }}>
    <Picker.Item
      label='Hello'
      value='hello'
    />
  </Picker>
</View></code>```

it's just affect the text, I want to make the whole Pikcer become smaller.

答:
You need to wrap your Picker inside a View Tag. Then you can add margins.  e.g. </p>

```<code><View style={{ marginLeft: 80, marginRight: 80 }}>
  <Picker>
    <Picker.Item
      label='Hello'
      value='hello'
    />
  </Picker>
</View>
</code>```

Body:
Im a newbie using React Native.

I jus create an application as on the screenshot.

I want to make the dropdown or Picker component a bit smaller.

But I cant do it, Im looking for a guide to solve this.

Thanks.

My application:

import React, { Component } from 'react'
import { Item, Picker, TouchableOpacity, View, ListView, Text } from 'react-native'
import { connect } from 'react-redux'
import { Icon, Header } from 'react-native-elements'
import { Button, Container, Content, Footer, Title} from 'native-base'

// For empty lists
// import AlertMessage from '../Components/AlertMessage'

// Styles
import styles from './Styles/MainRestoStyles'

class MainRestoScreen extends React.Component {
  constructor (props) {
    super(props)

    /* ***********************************************************
    * STEP 1
    * This is an array of objects with the properties you desire
    * Usually this should come from Redux mapStateToProps
    *************************************************************/
    const dataObjects = {
      first: [
        {title: 'First Title', description: 'First Description'},
        {title: 'Second Title', description: 'Second Description'},
        {title: 'Third Title', description: 'Third Description'},
        {title: 'Fourth Title', description: 'Fourth Description'},
        {title: 'Fifth Title', description: 'Fifth Description'},
        {title: 'Sixth Title', description: 'Sixth Description'},
        {title: 'Seventh Title', description: 'Seventh Description'},
        {title: 'Eighth Title', description: 'Eighth Description'},
        {title: 'Ninth Title', description: 'Ninth Description'},
        {title: 'Tenth Title', description: 'Tenth Description'}
      ],
      second: [
        {title: 'Eleventh Title', description: 'Eleventh Description'},
        {title: '12th Title', description: '12th Description'},
        {title: '13th Title', description: '13th Description'},
        {title: '14th Title', description: '14th Description'},
        {title: '15th Title', description: '15th Description'},
        {title: '16th Title', description: '16th Description'},
        {title: '17th Title', description: '17th Description'},
        {title: '18th Title', description: '18th Description'},
        {title: '19th Title', description: '19th Description'},
        {title: '20th Title', description: '20th Description'},
        {title: 'BLACKJACK!', description: 'BLACKJACK! Description'}
      ]
    }
    /* ***********************************************************
    * STEP 2
    * Teach datasource how to detect if rows are different
    * Make this function fast!  Perhaps something like:
    *   (r1, r2) => r1.id !== r2.id}
    *   The same goes for sectionHeaderHasChanged
    *************************************************************/
    const rowHasChanged = (r1, r2) => r1 !== r2
    const sectionHeaderHasChanged = (s1, s2) => s1 !== s2

    // DataSource configured
    const ds = new ListView.DataSource({rowHasChanged, sectionHeaderHasChanged})

    // Datasource is always in state
    this.state = {
      dataSource: ds.cloneWithRowsAndSections(dataObjects)
    }
  }

  /* ***********************************************************
  * STEP 3
  * `renderRow` function -How each cell/row should be rendered
  * It's our best practice to place a single component here:
  *
  * e.g.
    return <MyCustomCell title={rowData.title} description={rowData.description} />
  *************************************************************/
  renderRow (rowData, sectionID) {
    // You can condition on sectionID (key as string), for different cells
    // in different sections
    return (
      <TouchableOpacity style={styles.row}>
        <Text style={styles.boldLabel}>Section {sectionID} - {rowData.title}</Text>
        <Text style={styles.label}>{rowData.description}</Text>
      </TouchableOpacity>
    )
  }

  /* ***********************************************************
  * STEP 4
  * If your datasource is driven by Redux, you'll need to
  * reset it when new data arrives.
  * DO NOT! place `cloneWithRowsAndSections` inside of render, since render
  * is called very often, and should remain fast!  Just replace
  * state's datasource on newProps.
  *
  * e.g.
    componentWillReceiveProps (newProps) {
      if (newProps.someData) {
        this.setState(prevState => ({
          dataSource: prevState.dataSource.cloneWithRowsAndSections(newProps.someData)
        }))
      }
    }
  *************************************************************/

  // Used for friendly AlertMessage
  // returns true if the dataSource is empty
  noRowData () {
    return this.state.dataSource.getRowCount() === 0
  }

  render () {
    return (
      <Container>
        <View style={styles.toolbar}>
          <Text style={styles.toolbarButton}></Text>
          <Icon name='bowl' type='entypo' size={40} color='white'/>
          <Text style={styles.toolbarButton}></Text>
        </View>
        <Content>
        <Picker>
            <Picker.Item
              label='Hello'
              value='hello'
            />
          </Picker>
          <ListView
            contentContainerStyle={styles.listContent}
            dataSource={this.state.dataSource}
            onLayout={this.onLayout}
            renderRow={this.renderRow}
            enableEmptySections
          />
        </Content>

          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='location' type='entypo' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='heart' type='foundation' color='white' size={30}/>
          </Button>
          <Button transparent style={ styles.buttonsMenu }>
            <Icon name='bell' type='entypo' color='white' size={30}/>
          </Button>

      </Container>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    // ...redux state to props here
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(MainRestoScreen)

update:

<View>
  <Picker style={{ marginLeft: 80, marginRight: 80 }}>
    <Picker.Item
      label='Hello'
      value='hello'
    />
  </Picker>
</View>

it's just affect the text, I want to make the whole Pikcer become smaller.

Body:
You need to wrap your Picker inside a View Tag. Then you can add margins.  e.g.

<View style={{ marginLeft: 80, marginRight: 80 }}>
  <Picker>
    <Picker.Item
      label='Hello'
      value='hello'
    />
  </Picker>
</View>


问:
How to trim string from right in PHP?
I have a string example

```<code>this-is-the-example/exa
</code>```

I want to trim /exa from the above line

```<code>$string1 = "this-is-the-example/exa";
$string2 = "/exa";
</code>```

I am using rtrim($string1, $sting2)

But the output is this-is-the-exampl

I want to this-is-the-example as output.

Both string are dynamic and may have multiple occurrences within the string. But I only want to remove the last part. Also its not compulsory that the string2 has / in it. this may be normal string too. like a, abc too..

答:
You can use explode</p>

```<code><?php

$x = "this-is-the-example/exa";

$y = explode('/', $x);

echo $y[0];
</code>```

Title: How to trim string from right in PHP?

Body:
I have a string example

this-is-the-example/exa

I want to trim /exa from the above line

$string1 = "this-is-the-example/exa";
$string2 = "/exa";

I am using rtrim($string1, $sting2)

But the output is this-is-the-exampl

I want to this-is-the-example as output.

Both string are dynamic and may have multiple occurrences within the string. But I only want to remove the last part. Also its not compulsory that the string2 has / in it. this may be normal string too. like a, abc too..

Body:
You can use explode

<?php

$x = "this-is-the-example/exa";

$y = explode('/', $x);

echo $y[0];


问:
Fetch json response inside array of array
My Json response is as follows.I want to get the individual array item from the response like static website,dynamic website.Can you help me please?</p>

```<code>{
  "data": [
    [
      "Static Website"
    ],
    [
      "Dynamic Website"
    ],
    [
      "E-Commerce Website"
    ],
    [
      "ERP"
    ],
    [
      "IOS Application"
    ],
    [
      "Social Networking"
    ],
    [
      "Web Application"
    ],
    [
      "Graphic Design"
    ]
  ],
  "status": 200
}
</code>```

答:
Try this</p>

```<code>JSONObject jsonObject=new JSONObject("Your Json String");

try {
       JSONArray jsonArray = jsonObject.getJSONArray("data");
       String status = jsonObject.getString("status");
       Log.d("Status","Status"+ status);

       for (int i = 0; i < jsonArray.length(); i++) {
           JSONArray jsonArray1 = (JSONArray) jsonArray.get(i);
            Log.d("Value", "Json Array Value" + jsonArray1);
       }
} catch (JSONException e) {
   e.printStackTrace();

}
</code>```

Body:
My Json response is as follows.I want to get the individual array item from the response like static website,dynamic website.Can you help me please?

{
  "data": [
    [
      "Static Website"
    ],
    [
      "Dynamic Website"
    ],
    [
      "E-Commerce Website"
    ],
    [
      "ERP"
    ],
    [
      "IOS Application"
    ],
    [
      "Social Networking"
    ],
    [
      "Web Application"
    ],
    [
      "Graphic Design"
    ]
  ],
  "status": 200
}

Body:
Try this

JSONObject jsonObject=new JSONObject("Your Json String");

try {
       JSONArray jsonArray = jsonObject.getJSONArray("data");
       String status = jsonObject.getString("status");
       Log.d("Status","Status"+ status);

       for (int i = 0; i < jsonArray.length(); i++) {
           JSONArray jsonArray1 = (JSONArray) jsonArray.get(i);
            Log.d("Value", "Json Array Value" + jsonArray1);
       }
} catch (JSONException e) {
   e.printStackTrace();

}


问:
iPython notebook - configuring to shut down the kernel on closing the tab
On the official site it is said:

When a notebook is opened, its “computational engine” (called the kernel) is automatically started. Closing the notebook browser tab, will not shut down the kernel, instead the kernel will keep running until is explicitly shut down."

Is it possible to configure the iPython server so that the kernel is killed together with the associated tab?

答:
I think IPython.notebook.session.delete() is better than IPython.notebook.kernel.kill().

```<code>window.addEventListener('unload', function() {
    // For Firefox
    IPython.notebook.session.delete();
});

window.onbeforeunload = function () {
    // For Chrome
    IPython.notebook.session.delete();
};
</code>```

Reason

Because kernel.kill() will just kill kernel. It won't tell notebook's sessionmanager about killing it.
So after killing, sessionmanager will raise KernelError when you'll reopen the same ipynb file which you closed by kernel.kill() (closed tabs or windows).

About unload

On GoogleChrome, unload events won't be fired on moving pages.
So, I think you should also hook beforeunload event

But hooking by addEventListener('beforeunload', ...) didn't work.
So I tried window.onbeforeunload = and it works fine.

Body:
I think IPython.notebook.session.delete() is better than IPython.notebook.kernel.kill().

window.addEventListener('unload', function() {
    // For Firefox
    IPython.notebook.session.delete();
});

window.onbeforeunload = function () {
    // For Chrome
    IPython.notebook.session.delete();
};

Reason

Because kernel.kill() will just kill kernel. It won't tell notebook's sessionmanager about killing it.
So after killing, sessionmanager will raise KernelError when you'll reopen the same ipynb file which you closed by kernel.kill() (closed tabs or windows).

About unload

On GoogleChrome, unload events won't be fired on moving pages.
So, I think you should also hook beforeunload event

But hooking by addEventListener('beforeunload', ...) didn't work.
So I tried window.onbeforeunload = and it works fine.


问:
How maven-compiler-plugin work with different jdk?
```<code>$ mvn --version
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T03:58:13-04:00)
Maven home: /usr/local/apache-maven
Java version: 1.8.0_151, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-oracle/jre
Default locale: en_CA, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-98-generic", arch: "amd64", family: "unix"
</code>```

Only jvm version installed on the machine.

In pom.xml, on setting source & target version as 1.4,

```<code>  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.0.2</version>
        <configuration>
          <source>1.4</source>
          <target>1.4</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</code>```

Here is the output of mvn package,

```<code>$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building mywebapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-compiler-plugin/2.0.2/maven-compiler-plugin-2.0.2.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-compiler-plugin/2.0.2/maven-compiler-plugin-2.0.2.pom (2.4 kB at 934 B/s)
....
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mywebapp ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/mohet01/git/Projects/myapp/mywebapp/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ mywebapp ---
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/1.5.3/plexus-compiler-api-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/1.5.3/plexus-compiler-api-1.5.3.pom (624 B at 700 B/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler/1.5.3/plexus-compiler-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler/1.5.3/plexus-compiler-1.5.3.pom (1.5 kB at 1.8 kB/s)
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/1.5.3/plexus-compiler-manager-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/1.5.3/plexus-compiler-manager-1.5.3.pom (634 B at 732 B/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/1.5.3/plexus-compiler-javac-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/1.5.3/plexus-compiler-javac-1.5.3.pom (797 B at 871 B/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compilers/1.5.3/plexus-compilers-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compilers/1.5.3/plexus-compilers-1.5.3.pom (7.6 kB at 9.4 kB/s)
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/1.5.3/plexus-compiler-api-1.5.3.jar
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/1.5.3/plexus-compiler-manager-1.5.3.jar
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/1.5.3/plexus-compiler-api-1.5.3.jar (20 kB at 20 kB/s)
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/1.5.3/plexus-compiler-javac-1.5.3.jar
...
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/1.5.3/plexus-compiler-javac-1.5.3.jar (14 kB at 8.2 kB/s)
...

Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/1.5.3/plexus-compiler-manager-1.5.3.jar (5.3 kB at 2.1 kB/s)
.....

[INFO] Packaging webapp
[INFO] Assembling webapp [mywebapp] in [/home/mohet01/git/Projects/myapp/mywebapp/target/mywebapp-1.0-SNAPSHOT]
[INFO] Processing war project
[INFO] Copying webapp resources [/home/mohet01/git/Projects/myapp/mywebapp/src/main/webapp]
[INFO] Webapp assembled in [79 msecs]
[INFO] Building war: /home/mohet01/git/Projects/myapp/mywebapp/target/mywebapp-1.0-SNAPSHOT.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 36.643 s
[INFO] Finished at: 2017-12-07T01:56:43-05:00
[INFO] Final Memory: 14M/140M
[INFO] ------------------------------------------------------------------------
$
</code>```

Does maven pull 1.4 version of javac compiler from online maven repo before compiling java source code? How to point to corresponding jdk?

答: No, javac has the ability to compile to backward compalibile code (with slight exceptions)

Body:
$ mvn --version
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T03:58:13-04:00)
Maven home: /usr/local/apache-maven
Java version: 1.8.0_151, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-oracle/jre
Default locale: en_CA, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-98-generic", arch: "amd64", family: "unix"

Only jvm version installed on the machine.

In pom.xml, on setting source & target version as 1.4,

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.0.2</version>
        <configuration>
          <source>1.4</source>
          <target>1.4</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

Here is the output of mvn package,

$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building mywebapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-compiler-plugin/2.0.2/maven-compiler-plugin-2.0.2.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-compiler-plugin/2.0.2/maven-compiler-plugin-2.0.2.pom (2.4 kB at 934 B/s)
....
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mywebapp ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/mohet01/git/Projects/myapp/mywebapp/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ mywebapp ---
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/1.5.3/plexus-compiler-api-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/1.5.3/plexus-compiler-api-1.5.3.pom (624 B at 700 B/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler/1.5.3/plexus-compiler-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler/1.5.3/plexus-compiler-1.5.3.pom (1.5 kB at 1.8 kB/s)
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/1.5.3/plexus-compiler-manager-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/1.5.3/plexus-compiler-manager-1.5.3.pom (634 B at 732 B/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/1.5.3/plexus-compiler-javac-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/1.5.3/plexus-compiler-javac-1.5.3.pom (797 B at 871 B/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compilers/1.5.3/plexus-compilers-1.5.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compilers/1.5.3/plexus-compilers-1.5.3.pom (7.6 kB at 9.4 kB/s)
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/1.5.3/plexus-compiler-api-1.5.3.jar
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/1.5.3/plexus-compiler-manager-1.5.3.jar
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-api/1.5.3/plexus-compiler-api-1.5.3.jar (20 kB at 20 kB/s)
...
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/1.5.3/plexus-compiler-javac-1.5.3.jar
...
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-javac/1.5.3/plexus-compiler-javac-1.5.3.jar (14 kB at 8.2 kB/s)
...

Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-compiler-manager/1.5.3/plexus-compiler-manager-1.5.3.jar (5.3 kB at 2.1 kB/s)
.....

[INFO] Packaging webapp
[INFO] Assembling webapp [mywebapp] in [/home/mohet01/git/Projects/myapp/mywebapp/target/mywebapp-1.0-SNAPSHOT]
[INFO] Processing war project
[INFO] Copying webapp resources [/home/mohet01/git/Projects/myapp/mywebapp/src/main/webapp]
[INFO] Webapp assembled in [79 msecs]
[INFO] Building war: /home/mohet01/git/Projects/myapp/mywebapp/target/mywebapp-1.0-SNAPSHOT.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 36.643 s
[INFO] Finished at: 2017-12-07T01:56:43-05:00
[INFO] Final Memory: 14M/140M
[INFO] ------------------------------------------------------------------------
$

Does maven pull 1.4 version of javac compiler from online maven repo before compiling java source code? How to point to corresponding jdk?


问:
Communication between client and server in Angular 2+
I am using NodeMailer for mail service. I have to get an email address from a field in client side and send that value to app.js where my nodemailer code resides.

client side

```<code>ngOnInit() {
  this.forgotForm = this.formBuilder.group({
    email: this.email,
  });
}

sendmail() {
}
</code>```

app.js, Nodemailer code (I have to get email id for to address here)

```<code>let mailOptions = {
    from: 'xyz@gmail.com',
    to: '',
    subject: 'Test Mailer',
    text: 'I am testing Nodemailer to send email.',
};
</code>```

答:
You need to use services in angular in order to do this. in terminal set the path to a folder where you want create service, and then use the command ng generate service <service_name> . This will create a file service_name.service.ts. You can refer https://codecraft.tv/courses/angular/http/overview/ or https://angular.io/tutorial/toh-pt4 for more details.

You can use APIs along with http methods get, post, put, delete etc. to complete your task.

In respective component.ts file create a variable email like:

```<code>email =string;
</code>```

In the html file bind the input field with ngModel as:

```<code>[(ngModel)]="email"
</code>```

Then make a function in service.ts that accepts email as arguments

```<code>endMail(email) {
//make api call using http method(say post)
// supply email
  let url = <APIURL>
  return http.post(url, {email: email});
}
</code>```

Again in component.ts import this service and instantiate in constructor and use a method to call service

Body:
I am using NodeMailer for mail service. I have to get an email address from a field in client side and send that value to app.js where my nodemailer code resides.

client side

ngOnInit() {
  this.forgotForm = this.formBuilder.group({
    email: this.email,
  });
}

sendmail() {
}

app.js, Nodemailer code (I have to get email id for to address here)

let mailOptions = {
    from: 'xyz@gmail.com',
    to: '',
    subject: 'Test Mailer',
    text: 'I am testing Nodemailer to send email.',
};

Body:
You need to use services in angular in order to do this. in terminal set the path to a folder where you want create service, and then use the command ng generate service <service_name> . This will create a file service_name.service.ts. You can refer https://codecraft.tv/courses/angular/http/overview/ or https://angular.io/tutorial/toh-pt4 for more details.

You can use APIs along with http methods get, post, put, delete etc. to complete your task.

In respective component.ts file create a variable email like:

email =string;

In the html file bind the input field with ngModel as:

[(ngModel)]="email"

Then make a function in service.ts that accepts email as arguments

endMail(email) {
//make api call using http method(say post)
// supply email
  let url = <APIURL>
  return http.post(url, {email: email});
}

Again in component.ts import this service and instantiate in constructor and use a method to call service


答:
the second parameter of rtrim is a character mask and not a string, your last "e" is trimed and that's normal.

COnsider using something else,  regexp for example (preg_replace) to fit your needs

This keeps everything before "/" char :

```<code>$str = preg_replace('/^([^\/]*).*/','$1', 'this-is-the-example/exa');
</code>```

This removes the last part.

```<code>$str = preg_replace('/^(.*)\/.*$/','$1', 'this-is-the-example/exa/mple');
</code>```

Title: How to trim string from right in PHP?

Body:
the second parameter of rtrim is a character mask and not a string, your last "e" is trimed and that's normal.

COnsider using something else,  regexp for example (preg_replace) to fit your needs

This keeps everything before "/" char :

$str = preg_replace('/^([^\/]*).*/','$1', 'this-is-the-example/exa');

This removes the last part.

$str = preg_replace('/^(.*)\/.*$/','$1', 'this-is-the-example/exa/mple');


问:
What does to_ms = -1 do on winpcap and linux libpcap?
I am trying to port a libpcap based program to macos, and it seems to be written for windows and linux. In the pcap_open_live function, the read timeout was set to -1, same with PacketOpen, and on macOS, this causes an error when trying to open the interface, BIOCSRTIMEOUT: Invalid Argument. I am unable to find any documentation on what a -1 read timeout actually does. Additonally, is there a version of this which will allow me to do the same thing on a BPF based libpcap?</p>

答:
What does to_ms = -1 do on winpcap and linux libpcap?

Nothing predictable.  To quote the tip-of-the-master-branch pcap(3pcap) man page:

```<code>   packet buffer timeout
      If,  when  capturing,  packets  are  delivered  as  soon as they
      arrive, the application capturing the packets will be  woken  up
      for  each  packet  as  it arrives, and might have to make one or
      more calls to the operating system to fetch each packet.

      If, instead, packets are not delivered as soon as  they  arrive,
      but  are  delivered after a short delay (called a "packet buffer
      timeout"), more than one packet can be  accumulated  before  the
      packets are delivered, so that a single wakeup would be done for
      multiple packets, and each set of calls made  to  the  operating
      system  would  supply  multiple  packets,  rather  than a single
      packet.  This reduces the per‐packet CPU overhead if packets are
      arriving  at  a  high rate, increasing the number of packets per
      second that can be captured.

      The packet buffer timeout is required  so  that  an  application
      won’t  wait for the operating system’s capture buffer to fill up
      before packets are delivered; if packets  are  arriving  slowly,
      that wait could take an arbitrarily long period of time.

      Not  all platforms support a packet buffer timeout; on platforms
      that don’t, the packet buffer timeout is ignored.  A zero  value
      for the timeout, on platforms that support a packet buffer time‐
      out, will cause a read to wait forever to allow  enough  packets
      to arrive, with no timeout.

      NOTE:  the  packet  buffer timeout cannot be used to cause calls
      that read packets to return within a  limited  period  of  time,
      because, on some platforms, the packet buffer timeout isn’t sup‐
      ported, and, on other platforms, the timer doesn’t  start  until
      at  least one packet arrives.  This means that the packet buffer
      timeout should NOT be  used,  for  example,  in  an  interactive
      application  to  allow  the  packet capture loop to ‘‘poll’’ for
      user input periodically, as there’s no  guarantee  that  a  call
      reading packets will return after the timeout expires even if no
      packets have arrived.
</code>```

Nothing is said there about a negative timeout; I'll update it to explicitly say that a negative value should not be used.  (Not on Windows, not on macOS, not on Linux, not on *BSD, not on Solaris, not on AIX, not on HP-UX, not on Tru64 UNIX, not on IRIX, not on anything.)

By setting the timeout to -1, they probably intended to put the pcap_t into "non-blocking mode", where an attempt to read will return immediately if there are no packets waiting to be read, rather than waiting for a packet to arrive.  So, instead, provide a timeout of, for example, 100 (meaning 1/10 second) and use pcap_setnonblock() after the pcap_open_live() call to put the pcap_t into non-blocking mode.  That should work on all platforms.

Body:
What does to_ms = -1 do on winpcap and linux libpcap?

Nothing predictable.  To quote the tip-of-the-master-branch pcap(3pcap) man page:

   packet buffer timeout
      If,  when  capturing,  packets  are  delivered  as  soon as they
      arrive, the application capturing the packets will be  woken  up
      for  each  packet  as  it arrives, and might have to make one or
      more calls to the operating system to fetch each packet.

      If, instead, packets are not delivered as soon as  they  arrive,
      but  are  delivered after a short delay (called a "packet buffer
      timeout"), more than one packet can be  accumulated  before  the
      packets are delivered, so that a single wakeup would be done for
      multiple packets, and each set of calls made  to  the  operating
      system  would  supply  multiple  packets,  rather  than a single
      packet.  This reduces the per‐packet CPU overhead if packets are
      arriving  at  a  high rate, increasing the number of packets per
      second that can be captured.

      The packet buffer timeout is required  so  that  an  application
      won’t  wait for the operating system’s capture buffer to fill up
      before packets are delivered; if packets  are  arriving  slowly,
      that wait could take an arbitrarily long period of time.

      Not  all platforms support a packet buffer timeout; on platforms
      that don’t, the packet buffer timeout is ignored.  A zero  value
      for the timeout, on platforms that support a packet buffer time‐
      out, will cause a read to wait forever to allow  enough  packets
      to arrive, with no timeout.

      NOTE:  the  packet  buffer timeout cannot be used to cause calls
      that read packets to return within a  limited  period  of  time,
      because, on some platforms, the packet buffer timeout isn’t sup‐
      ported, and, on other platforms, the timer doesn’t  start  until
      at  least one packet arrives.  This means that the packet buffer
      timeout should NOT be  used,  for  example,  in  an  interactive
      application  to  allow  the  packet capture loop to ‘‘poll’’ for
      user input periodically, as there’s no  guarantee  that  a  call
      reading packets will return after the timeout expires even if no
      packets have arrived.

Nothing is said there about a negative timeout; I'll update it to explicitly say that a negative value should not be used.  (Not on Windows, not on macOS, not on Linux, not on *BSD, not on Solaris, not on AIX, not on HP-UX, not on Tru64 UNIX, not on IRIX, not on anything.)

By setting the timeout to -1, they probably intended to put the pcap_t into "non-blocking mode", where an attempt to read will return immediately if there are no packets waiting to be read, rather than waiting for a packet to arrive.  So, instead, provide a timeout of, for example, 100 (meaning 1/10 second) and use pcap_setnonblock() after the pcap_open_live() call to put the pcap_t into non-blocking mode.  That should work on all platforms.


问:
How to make an HTML anchor tag (or link) look like a button?
I have this button image:

I was wondering whether it would be possible to make a simple

```<code><a href="">some words</a>
</code>```

and style that link to appear as that button?

If it is possible, how do I do that?

答:
You have got two options for consistency.

Use framework-specific tags, and use them throughout the website.

Use JavaScript to emulate a link on a button element, and then have the button consistent with browser's buttons look. Those css button-look hacks will never be accurate.

.

```<code><button onclick="location.href = 'Homepage.html'; return false;">My Button</button>
</code>```

return false; is to prevent the default behavior of the button being clicked.

Body:
I have this button image:

I was wondering whether it would be possible to make a simple

some words

and style that link to appear as that button?

If it is possible, how do I do that?

Body:
You have got two options for consistency.

Use framework-specific tags, and use them throughout the website.

Use JavaScript to emulate a link on a button element, and then have the button consistent with browser's buttons look. Those css button-look hacks will never be accurate.

.

<button onclick="location.href = 'Homepage.html'; return false;">My Button</button>

return false; is to prevent the default behavior of the button being clicked.


问:
Removing images by clicking on delete button
How can I remove specific image with complete division by clicking on the respective DELETE button, below is the source code. kindly assist me on this.

```<code><div class="slide">
   <img class="photo" src="img001.jpg">
   <p>image description</p>
   <button id="del">Delete</button>
</div>
<div class="slide">
   <img src="img002.jpg">
   <p>image description</p>
   <button>Delete</button>
</div>
</code>```

答:
Bind a click event onto the button under the slide, and remove the slide on clicking of the button.

$(function() {

  $(".slide button").click(function() {
    $(this).parent().remove();
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slide">
  <img class="photo" src="img001.jpg">
  <p>image description</p>
  <button id="del">Delete</button>
</div>
<div class="slide">
  <img src="img002.jpg">
  <p>image description</p>
  <button>Delete</button>
</div></code>```

Body:
How can I remove specific image with complete division by clicking on the respective DELETE button, below is the source code. kindly assist me on this.

image description

   <button id="del">Delete</button>

image description

   <button>Delete</button>

Body:
Bind a click event onto the button under the slide, and remove the slide on clicking of the button.

$(function() {

  $(".slide button").click(function() {
    $(this).parent().remove();
  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slide">
  <img class="photo" src="img001.jpg">
  <p>image description</p>
  <button id="del">Delete</button>
</div>
<div class="slide">
  <img src="img002.jpg">
  <p>image description</p>
  <button>Delete</button>
</div>


问:
How can I format an address so that it will turn into an apple maps link
I am working for a company that requires calendar events be sent to the iPhones of field service engineers.

Included in the Event is the customer address.

```<code>123 Fake St
Fakeville Town
NSW 2500 AUSTRALIA
</code>```

is there a way to print this address into the event so that an iphone can click on the address and open it in maps.

The following have been tested:
(only the italicized section of the address becomes the link, and will always default to 123 fake street - somewhere in America.)

123 Fake St, Fakefille

123 Fake St Fakefille

any help would be greatly appreciated, cheers!

答:
Take a look at this documentation :
https://developer.apple.com/library/content/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html

Your URL could look something like this :
http://maps.apple.com/?address=123,Fake,St,Fakefille+Town,AUSTRALIA

Clicking this link will open the maps app.

Body:
I am working for a company that requires calendar events be sent to the iPhones of field service engineers.

Included in the Event is the customer address.

123 Fake St
Fakeville Town
NSW 2500 AUSTRALIA

is there a way to print this address into the event so that an iphone can click on the address and open it in maps.

The following have been tested:
(only the italicized section of the address becomes the link, and will always default to 123 fake street - somewhere in America.)

123 Fake St, Fakefille

123 Fake St Fakefille

any help would be greatly appreciated, cheers!


答:
First explode the string, remove last element from exploded array using array_pop, then implode it back again with /.

```<code>$str = "this-is-the-example/exa";
if(strpos($str, '/') !== false)
{
    $arr = explode('/', $str);
    array_pop($arr);
    $str = implode('/', $arr);
    // output this-is-the-example
}
</code>```

This will work event if you have multiple / in the URL and will remove last element only.

```<code>$str = "this-is-the-example/somevalue/exa";

if(strpos($str, '/') !== false)
{
    $arr = explode('/', $str);
    array_pop($arr);
    $str = implode('/', $arr);
    // output this-is-the-example
}
</code>```

Title: How to trim string from right in PHP?

Body:
First explode the string, remove last element from exploded array using array_pop, then implode it back again with /.

$str = "this-is-the-example/exa";
if(strpos($str, '/') !== false)
{
    $arr = explode('/', $str);
    array_pop($arr);
    $str = implode('/', $arr);
    // output this-is-the-example
}

This will work event if you have multiple / in the URL and will remove last element only.

$str = "this-is-the-example/somevalue/exa";

if(strpos($str, '/') !== false)
{
    $arr = explode('/', $str);
    array_pop($arr);
    $str = implode('/', $arr);
    // output this-is-the-example
}


问:
ngx-permissions error with directive *ngxPermissionsOnly
I have a problem with the directive of the library ngx-permissions.
These are the versions of my angular's dependency:

```<code>    "@angular/animations": "^5.0.3",
    "@angular/common": "^5.0.3",
    "@angular/compiler": "^5.0.3",
    "@angular/core": "^5.0.3",
    "@angular/forms": "^5.0.3",
    "@angular/http": "^5.0.3",
    "@angular/platform-browser": "^5.0.3",
    "@angular/platform-browser-dynamic": "^5.0.3",
    "@angular/router": "^5.0.3",
</code>```

And I am following this example.

I am using the version of module:

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

import { AppComponent } from './app.component';

import { NgxPermissionsModule } from 'ngx-permissions';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,

    // Specify your library as an import
     NgxPermissionsModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

I can use the services without problem, but I have an error only with the directive.
The error is the next:

```<code>Can't bind to 'ngxPermissionsOnly' since it isn't a known property of 'div'. ("
    </div>
            </div>
                <div [ERROR ->]*ngxPermissionsOnly="['ADMIN', 'GUEST']" class="m-portlet__head-tools">
                    <ul class="nav nav-pil"): ng:///DashboardModule/DashboardComponent.html@35:10
Property binding ngxPermissionsOnly not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("
                    </div>
                </div>
                [ERROR ->]<div *ngxPermissionsOnly="['ADMIN', 'GUEST']" class="m-portlet__head-tools">
                    <ul class="nav na"): ng:///DashboardModule/DashboardComponent.html@35:5
</code>```

答:
I would like to say that I was also facing same issue. but in my case; I had a shared module and I did same as wiki says but solutions was just exports NgxPermissionsModule.

My issue went out and code is working fine.Check if you might have same case and my fix works for you.

Thanks

Body:
I have a problem with the directive of the library ngx-permissions.
These are the versions of my angular's dependency:

    "@angular/animations": "^5.0.3",
    "@angular/common": "^5.0.3",
    "@angular/compiler": "^5.0.3",
    "@angular/core": "^5.0.3",
    "@angular/forms": "^5.0.3",
    "@angular/http": "^5.0.3",
    "@angular/platform-browser": "^5.0.3",
    "@angular/platform-browser-dynamic": "^5.0.3",
    "@angular/router": "^5.0.3",

And I am following this example.

I am using the version of module:

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

import { AppComponent } from './app.component';

import { NgxPermissionsModule } from 'ngx-permissions';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,

    // Specify your library as an import
     NgxPermissionsModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I can use the services without problem, but I have an error only with the directive.
The error is the next:

Can't bind to 'ngxPermissionsOnly' since it isn't a known property of 'div'. ("

]*ngxPermissionsOnly="['ADMIN', 'GUEST']" class="m-portlet__head-tools">
                    ]

                    <ul class="nav na"): ng:///DashboardModule/DashboardComponent.html@35:5


问:
Azure Iot hub client communication with multiple devices
I have a node.js server application that communicates with Iot devices using Azure IoT Hub service.

When I examine the sample code sample code from Azure repository about cloud to device message. I see that one client was created. If there are multiple devices and multiple messages to be sent to multiple devices, is it okay to create multiple Iot hub clients, or should I stick to one client solution. What could be the cons and pros of two approach?

答: Have a look at the Azure IoT Hub feature for your scenario such as a Schedule and broadcast jobs. This feature enables a cloud back-end to schedule and update millions of devices based on your needs.</p>


问:
jQuery & fullPage.js - Not working in mobile
I am creating a site with the fullPage.js plugin. I got it to work on the desktop browser but it's not working as expected in mobile.

this is my HTML

```<code><div id="fullpage">
    <section id="red" class="section"></section>
    <section id="blue" class="section"></section>
    <section id="green" class="section"></section>
</div>
</code>```

and this is my jquery

```<code>$(document).ready(function(){
   $('#fullpage').fullpage({
       navigation: true,
   });
});
</code>```

while navigation:true I can skip (i wouldn't say scroll) to different sections by touching the navigation dots. I can swipe to scroll up from there as seen in this video. it works in the chrome device emulator though

video of scroll in the works

P.S. I don't think scrollOverflow:true would serve my purpose as there is not much content to scroll in the site.

答:
make it your code like this and try with that jquery</p>

```<code><div id="fullpage">
    <div class="section">
        <div class="slide"></div>
        <div class="slide"></div>
        <div class="slide"></div>
    </div>
</div>
</code>```

Body:
I am creating a site with the fullPage.js plugin. I got it to work on the desktop browser but it's not working as expected in mobile.

this is my HTML

and this is my jquery

$(document).ready(function(){
   $('#fullpage').fullpage({
       navigation: true,
   });
});

while navigation:true I can skip (i wouldn't say scroll) to different sections by touching the navigation dots. I can swipe to scroll up from there as seen in this video. it works in the chrome device emulator though

video of scroll in the works

P.S. I don't think scrollOverflow:true would serve my purpose as there is not much content to scroll in the site.

Body:
make it your code like this and try with that jquery

<div id="fullpage">
    <div class="section">
        <div class="slide"></div>
        <div class="slide"></div>
        <div class="slide"></div>
    </div>
</div>


问:
How to open an local pdf using InAppBrowser
I have downloaded an pdf file from the server using Transfer Plugin and i am trying to open the file using InAppBrower plugin i am not getting anything. i mean nothing is happening.

```<code>fileTransfer.download(url, this.file.dataDirectory + file.filename,false,{
        headers: {
            'authorization': 'bearer xxxx'
        }
    }).then((entry) => {
      console.log('download complete: ' + entry.toURL());
      console.log(entry.nativeURL);
      const browser = this.iab.create(entry.nativeURL, '_system', 'location=yes'); //here the inappbrowser plugin code.
    }, (error) => {
      // handle error
      console.log(error);
      console.log('ERROR');
    });
</code>```

my console.log(entry.nativeURL); prints this path file:///data/user/0/com.schneider.and/files/Attendance_Policy_Ver_1.0.pdf

答:
i use this code and its works for me</p>

```<code>showDocument(){
      const options: DocumentViewerOptions = {
        title: 'My PDF'
      }
      const imgeLocation = `${cordova.file.applicationDirectory}www/assets/imgs/${'Jainbhajan-Jeevan-Saar-By-Nirmal-Gangwal-1-ilovepdf-compressed (1).pdf'}`;
      this.document.viewDocument(imgeLocation, 'application/pdf', options)
    }
</code>```

Body:
I have downloaded an pdf file from the server using Transfer Plugin and i am trying to open the file using InAppBrower plugin i am not getting anything. i mean nothing is happening.

fileTransfer.download(url, this.file.dataDirectory + file.filename,false,{
        headers: {
            'authorization': 'bearer xxxx'
        }
    }).then((entry) => {
      console.log('download complete: ' + entry.toURL());
      console.log(entry.nativeURL);
      const browser = this.iab.create(entry.nativeURL, '_system', 'location=yes'); //here the inappbrowser plugin code.
    }, (error) => {
      // handle error
      console.log(error);
      console.log('ERROR');
    });

my console.log(entry.nativeURL); prints this path file:///data/user/0/com.schneider.and/files/Attendance_Policy_Ver_1.0.pdf

Body:
i use this code and its works for me

showDocument(){
      const options: DocumentViewerOptions = {
        title: 'My PDF'
      }
      const imgeLocation = `${cordova.file.applicationDirectory}www/assets/imgs/${'Jainbhajan-Jeevan-Saar-By-Nirmal-Gangwal-1-ilovepdf-compressed (1).pdf'}`;
      this.document.viewDocument(imgeLocation, 'application/pdf', options)
    }


问:
How to write this PHP regex?
I have a string of numbers surrounded by parenthesis:

```<code>(2)(56)(9)(12)(2)
</code>```

I was given the following regex by someone to split the numbers out of their parentheses:

```<code><?php

$string = '(2)(56)(9)(12)(2)';

$pattern = "/\\)\\(|\\(|\\)?/";

$numbers = preg_split($pattern, $string);

foreach ($numbers as $number) {
    echo $number.'<br />';
}

?>
</code>```

This outputs:

```<code><br />
<br />
2<br />
<br />
5<br />
6<br />
<br />
9<br />
<br />
1<br />
2<br />
<br />
2<br />
<br />
<br />
</code>```

When I really need it to output:

```<code>2<br />
56<br />
9<br />
12<br />
2<br />
</code>```

How can the regex be altered to make it work?

p.s. each number in between the parenthesis can be of an unlimited length.

答:
You just need the PREG_SPLIT_NO_EMPTY option of preg_split, and a small change in the pattern:

```<code>$pattern = "/\\)\\(|\\(|\\)/"; // removed the "?"
$numbers = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY); // added PREG_SPLIT_NO_EMPTY
</code>```

Or use preg_match:

```<code>$string = '(2)(56)(9)(12)(2)';

preg_match_all('#\d+#', $string, $matches);

foreach ($matches[0] as $number) {
    echo "$number<br />\n";
}
</code>```

Output:

```<code>2<br />
56<br />
9<br />
12<br />
2<br />
</code>```

Title: How to write this PHP regex?

Body:
I have a string of numbers surrounded by parenthesis:

(2)(56)(9)(12)(2)

I was given the following regex by someone to split the numbers out of their parentheses:

<?php

$string = '(2)(56)(9)(12)(2)';

$pattern = "/\\)\\(|\\(|\\)?/";

$numbers = preg_split($pattern, $string);

foreach ($numbers as $number) {
    echo $number.'
';
}

?>

This outputs:

2

5

6

9

1

2

2

When I really need it to output:

2

56

9

12

2

How can the regex be altered to make it work?

p.s. each number in between the parenthesis can be of an unlimited length.

Body:
You just need the PREG_SPLIT_NO_EMPTY option of preg_split, and a small change in the pattern:

$pattern = "/\\)\\(|\\(|\\)/"; // removed the "?"
$numbers = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY); // added PREG_SPLIT_NO_EMPTY

Or use preg_match:

$string = '(2)(56)(9)(12)(2)';

preg_match_all('#\d+#', $string, $matches);

foreach ($matches[0] as $number) {
    echo "$number<br />\n";
}

Output:

2<br />
56<br />
9<br />
12<br />
2<br />