问:
Hide subview of different view controller
I have a view that acts as a background (light grey 0.5 alpha) for for another custom alert view.

When the user taps my OK button on the custom alert, i want to hide the custom alert and the background view also.

Both views are subviews of the same superview...

I do this in the buttonTapped: method to hide the views, and it works for the first attempt, but from the second time onwards, the background views never dismiss... the alerts hide correctly every time.

```<code>[UIView animateWithDuration:0.5f animations:^{
    self.view.alpha=0.0f; //hide alert
    [self.view.superview viewWithTag:1].alpha=0.0f; //hide background
}];
</code>```

They are added as subviews, as follows:

```<code>ResultDialogController *dialogController = [[[ResultDialogController alloc] initWithNibName:@"ResultDialogController_" bundle:nil] retain];
ResultBackgroundViewController *bgViewController = [[[ResultBackgroundViewController alloc] initWithNibName:@"ResultView" bundle:nil] retain];

dialogController.view.alpha=0;
bgViewController.view.alpha=0;
bgViewController.view.tag=1;

[UIView animateWithDuration:0.5f animations:^{
    bgViewController.view.alpha=0.5f;
    dialogController.view.alpha=1.0f;
    }];

[self.view addSubview:bgViewController.view];
[self.view addSubview:dialogController.view];
[dialogController release];
[bgViewController release];
</code>```

How can i always dismiss the background view?

Thanks

答: You can hide them by setting HIDE property for the views to be true.</p>

Body:
I have a view that acts as a background (light grey 0.5 alpha) for for another custom alert view.

When the user taps my OK button on the custom alert, i want to hide the custom alert and the background view also.

Both views are subviews of the same superview...

I do this in the buttonTapped: method to hide the views, and it works for the first attempt, but from the second time onwards, the background views never dismiss... the alerts hide correctly every time.

[UIView animateWithDuration:0.5f animations:^{
    self.view.alpha=0.0f; //hide alert
    [self.view.superview viewWithTag:1].alpha=0.0f; //hide background
}];

They are added as subviews, as follows:

ResultDialogController *dialogController = [[[ResultDialogController alloc] initWithNibName:@"ResultDialogController_" bundle:nil] retain];
ResultBackgroundViewController *bgViewController = [[[ResultBackgroundViewController alloc] initWithNibName:@"ResultView" bundle:nil] retain];

dialogController.view.alpha=0;
bgViewController.view.alpha=0;
bgViewController.view.tag=1;

[UIView animateWithDuration:0.5f animations:^{
    bgViewController.view.alpha=0.5f;
    dialogController.view.alpha=1.0f;
    }];

[self.view addSubview:bgViewController.view];
[self.view addSubview:dialogController.view];
[dialogController release];
[bgViewController release];

How can i always dismiss the background view?

Thanks


来源: stackexchange

问:
R Apply - need to retrieve values in previous row
I am modeling the charge state of a battery over time. The best (only) working solution I have found is with a for-loop. I want to use "apply" or another solution if possible as this for-loop is slowing my code down considerably.

'df' is my data frame. 'df$batteryBeginCharge' is the beginning charge of the battery in each time step (row). 'df$Charge.Discharge' is the amount of charge entering or leaving the battery in each time step.

```<code>for(i in 1:nrow(df))
  {
    if(i!=1) df$batteryBeginCharge[i] <<- df$batteryBeginCharge[i-1] + df$Charge.Discharge[i-1]

    df$Charge.Discharge[i] <<- df$electricDemand[i] - df$electricSupply[i] #function of other columns of df, all in row 'i'
  }
</code>```

This seems like a perfect situation to use the "apply" family, but I cannot find a way to retrieve values of previous rows within "apply", which I need for my  'df$batteryBeginCharge' parameter.

I don't think I can use vectorization on 'df$batteryBeginCharge' and 'df$Charge.Discharge' separately, as they are obviously linked on a row-by-row basis.

Thanks in advance for any ideas.

答:
You could have several options here e.g. using apply, or dplyr or data.table. Here the example using data.table. Is this what you want?

```<code>library(data.table)
df <- data.table(batteryBeginCharge = c(10,25,40), Charge.Discharge = c(20,30,50))
df[ , x := shift(batteryBeginCharge, 1L, type="lag")  + shift(Charge.Discharge, 1L, type="lag")]
</code>```

Note that this part of the code is missing (df$Charge.Discharge[i] <<- ), hence your example can't not be reproduced completely.

ContentLicense: CC BY-SA 3.0

Body:
I am modeling the charge state of a battery over time. The best (only) working solution I have found is with a for-loop. I want to use "apply" or another solution if possible as this for-loop is slowing my code down considerably.

'df' is my data frame. 'df$batteryBeginCharge' is the beginning charge of the battery in each time step (row). 'df$Charge.Discharge' is the amount of charge entering or leaving the battery in each time step.

for(i in 1:nrow(df))
  {
    if(i!=1) df$batteryBeginCharge[i] <<- df$batteryBeginCharge[i-1] + df$Charge.Discharge[i-1]

    df$Charge.Discharge[i] <<- df$electricDemand[i] - df$electricSupply[i] #function of other columns of df, all in row 'i'
  }

This seems like a perfect situation to use the "apply" family, but I cannot find a way to retrieve values of previous rows within "apply", which I need for my  'df$batteryBeginCharge' parameter.

I don't think I can use vectorization on 'df$batteryBeginCharge' and 'df$Charge.Discharge' separately, as they are obviously linked on a row-by-row basis.

Thanks in advance for any ideas.

Body:
You could have several options here e.g. using apply, or dplyr or data.table. Here the example using data.table. Is this what you want?

library(data.table)
df <- data.table(batteryBeginCharge = c(10,25,40), Charge.Discharge = c(20,30,50))
df[ , x := shift(batteryBeginCharge, 1L, type="lag")  + shift(Charge.Discharge, 1L, type="lag")]

Note that this part of the code is missing (df$Charge.Discharge[i] <<- ), hence your example can't not be reproduced completely.


问:
How to setup Gitlab hook to validate a git push to remote
We have a DevOps process where people checkout or update from the remote master branch, create a new local working branch from the master and begin work in the local branch.

1) I need to put in restrictions that will keep people from pushing straight to the remote master branch directly. Instead, people need to push changes to their local branches to the same branch on the remote, after which an admin or code reviewer will merge it into the remote master.

2) I need a hook that will ensure that there is a valid Gitlab ticket or issue number in the form, say for example #PROJECTNAME123 before allowing their push to proceed to their remote branches (prior to code review and merging into remote master). Additionally, they must not be able to push if the ticket does not exist or is not yet open.

I have already created a Bash pre-receive hook using information from both the following websites but they get called but still allow the git push to get to the server even when I do not pass a Gitlab ticket/issue number.

https://github.com/Praqma/git-hooks/commit/2aa087fada0b0da51724f37a902362ddd78e168f

http://blog.hgomez.net/2015/03/02/Gitlab-custom-hooks-Bash-Way.html

The following is the pre-receive script and a bash function script that it calls.

pre-receive (No extension)

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

source /var/opt/gitlab/git-data/repositories/Product-common/ProductCommonParent.git/custom_hooks/pre-receive-functions.sh

# enforced custom commit message format
while read old_revision new_revision refname ; do
        process_revision
done

exit 0
</code>```

pre-receive-functions.sh

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

regexp="#[0-9]\+"

grep_msg()
{
        grepped=$( echo $message | grep -i $regexp )
}

process_revision ()
{
  #revisions=$(git rev-list $old_revision..$new_revision)
echo "In pre-receive hook. Just before retrieving the revisions"
if [ "$old_revision" -eq 0 ]; then
    # list everything reachable from new_revision but not any heads
   revisions=$(git rev-list $(git for-each-ref --format='%(refname)' refs/heads/* | sed 's/^/\^/') $new_revision)
else
   revisions=$(git rev-list $old_revision..$new_revision)
fi

echo "In pre-receive hook. Just before IFS"
  IFS='\n' read -ra array <<< "$revisions"
  for rid in "${!array[@]}"; do
        revision=${array[rid]}
    message=$(git cat-file commit $revision | sed '1,/^$/d')
        grepped=$(echo $message | grep -i "#[0-9]\+")
    grep_msg()
    if [ -z "$grepped" ] ; then
                grepped_none=$(echo $message | grep -i "#none")
                if [ -n "$grepped_none" ] ; then
                        echo "Warning, you are committing without a ticket reference" >&1
                else
                        echo "You have not included a ticket reference" >&2
                        exit 1
                fi
    fi
  done

}
</code>```

The following is the output when I try to push (I am pushing from a Git Bash shell on Windows 8.1 to a Fedora Core 24 having Gitlab installed):

```<code>xxx@xxxxx-HP MINGW64 ~/Documents/DevOps Re-Engineering/ProductCommonParent (ProductCommonParent002)
$ git push
Counting objects: 3, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 369 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: In pre-receive hook. Just before retrieving the revisions
remote: In pre-receive hook. Just before IFS
remote:
remote: To create a merge request for ProductCommonParent002, visit:
remote:   http://localhost/Product-common/ProductCommonParent/merge_requests/new?merge_request%5Bsource_branch%5D=ProductCommonParent002
remote:
To http://192.168.56.101/Product-common/ProductCommonParent.git
 * [new branch]      ProductCommonParent002 -> ProductCommonParent002
</code>```

Note: Gitlab and its dependencies, including git, are installed on the same Fedora Core 24 Linux System.

I will appreciate speedy help in getting past this. Thank you very much in advance for your help.

答:
1) Restrictions are already available by default for every default restricted branch of any new project or git repo. These restrictions apply to non-admin and non-root users of Gitlab.

2) We implemented the rules for checking that our developers comply with our development policies and processes by writing a Java spring boot CommandLineRunner application that called the Gitlab API. This application was packaged as a jar file.

We ensured that a developer must have a valid ticket number as part of his git commit message before he/she can push successfully to the remote counterpart of his working branch. This valid ticket must be assigned to him, have a valid milestone, and have the right label (either of NEW FEATURE, BUG, TASK etc.) selected for the push to be successful.

We integrated with the git hooks on the Gitlab Server by using a bash shell script that executed the jar file and allowed or failed the push request based on the output from the java application. This shell script, which is an adaptation of http://blog.hgomez.net/2015/03/02/Gitlab-custom-hooks-Bash-Way.html, can be found below:

```<code>#!/bin/bash
#
# pre-receive hook for Commit Check
#
COMPANY_EMAIL="mycorp.org"

readonly PROGNAME=$(basename $0)
readonly PROGDIR=$(readlink -m $(dirname $0))
IS_MERGE=0

check_single_commit()
{
  COMMIT_CHECK_STATUS=1
    echo "Repo >> $REPOSITORY_BASENAME"

    if [[ "$COMMIT_MESSAGE" == "Merge branch"* ]]; then
      COMMIT_CHECK_STATUS=0
      IS_MERGE=1
    else
    workFlowResult=`java -jar -Dspring.config.location=/home/gitlab/gitlab_custom_hooks/application.properties /home/gitlab/gitlab_custom_hooks/gitlab-tool.jar -prercv "$COMMIT_AUTHOR" "$COMMIT_MESSAGE" "$REPOSITORY_BASENAME"`
    echo "COMMIT_AUTHOR=$COMMIT_AUTHOR, COMMIT_MESSAGE=$COMMIT_MESSAGE, REPOSITORY_BASE=$REPOSITORY_BASENAME"

      echo " >>>>>>>>>>>>>>>>> $workFlowResult >>>>>>>>>>>>>>>>>" >&2
    if [[ "$workFlowResult" == *"PRE_RECEIVE_OK"* ]]; then
      echo " >>>>>>>>>>>>>>>>> $workFlowResult >>>>>>>>>>>>>>>>>" >&2
      COMMIT_CHECK_STATUS=0
    fi

    fi
}

check_all_commits()
{
  REVISIONS=$(git rev-list $OLD_REVISION..$NEW_REVISION)
  IFS='\n' read -ra LIST_OF_REVISIONS <<< "$REVISIONS"
if [ $(git rev-parse --is-bare-repository) = true ]
then
    REPOSITORY_BASENAME=$(basename "$PWD")
else
    REPOSITORY_BASENAME=$(basename $(readlink -nf "$PWD"/..))
fi
    echo REPOSITORY_BASENAME is $REPOSITORY_BASENAME
    REPOSITORY_BASENAME=$(basename "$PWD")
    REPOSITORY_BASENAME=${REPOSITORY_BASENAME%.git}

  for rid in "${!LIST_OF_REVISIONS[@]}"; do
    REVISION=${LIST_OF_REVISIONS[rid]}
    COMMIT_MESSAGE=$(git cat-file commit $REVISION | sed '1,/^$/d')
    COMMIT_AUTHOR=$(git cat-file commit $REVISION | grep committer | sed 's/^.* \([^@ ]\+@[^ ]\+\) \?.*$/\1/' | sed 's/<//' | sed 's/>//' | sed 's/@$COMPANY_EMAIL//')
    check_single_commit

    if [ "$COMMIT_CHECK_STATUS" != "0" ]; then
      echo "Commit validation failed for commit $REVISION" >&2
      exit 1
    fi

  done
}

# Get custom commit message format
while read OLD_REVISION NEW_REVISION REFNAME ; do
  check_all_commits
done

exit 0
</code>```

3) Although not part of the question, integrating PMD checks at the Server-side without the use of a PMD Jenkins plugins, required the download of the PMD executable startup dependencies, the execution of PMD from within a python script to statically analyze source files being pushed by developers to the git server (Gitlab server). The python script that bootstraps PMD could be easily integrated into the above bash shell script. The python script, which is an adaptation of http://bluec0re.blogspot.com.ng/2012/05/git-pre-receive-hook-with-checkstyle.html, can be found below:

```<code>#!/usr/bin/env python

import subprocess
import sys
import tempfile
import shutil
import os
import errno

# variables for checkstyle
#checkstyle = '/var/opt/gitlab/git-data/repositories/product-common/ProductCommonParent.git/custom_hooks/checkstyle-7.5.1-all.jar'
#checkstyle_config = '/var/opt/gitlab/git-data/repositories/product-common/ProductCommonParent.git/custom_hooks/sun_checks.xml'
pmd = '/home/gitlab/gitlab_custom_hooks/pmd-bin-5.5.4/bin/run.sh'

# implementing check_output for python < 2.7
if not hasattr(subprocess, 'check_output'):
    def check_output(*popenargs, **kwargs):
        if 'stdout' in kwargs:
            raise ValueError('stdout argument not allowed, it will be overridden.')
        process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
        output, unused_err = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            er = subprocess.CalledProcessError(retcode, cmd)
            er.output = output
            raise er
        return output
    subprocess.check_output = check_output

# helper for calling executables
def call(*args, **kwargs):
    return subprocess.check_output(*args, **kwargs).strip()

# helper for calling git
def call_git(cmd, *args, **kwargs):
    return call(['git'] + cmd, *args, **kwargs)

# get all new commits from stdin
def get_commits():
    commits = {}
    for line in sys.stdin:
        old, new, ref = line.strip().split(' ')
        if old == '0000000000000000000000000000000000000000':
            old = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'

        if ref not in commits:
            commits[ref] = []
        commits[ref].append({
            'old': old,
            'new': new,
            'files': get_changed_files(old, new)
            })

    return commits

# get a list of changed files between to commits
def get_changed_files(old, new):
    return call_git(['diff', '--name-only', old, new]).split('\n')

# get filemode, object type (blob,tree,commit), hash for the given file at the
# given commit
def get_change_type(commit, filename):
    return call_git(['ls-tree', commit, filename]).split('\t')[0].split(' ')

commits = get_commits()

# use the latest file commit only
print "Cleaning up file list..."

files = {}
count = 0
for ref, data in commits.iteritems():
    files[ref] = {}
    for commit in data:
        for filename in commit['files']:
            if not filename.lower().endswith('.java'): continue
            files[ref][filename] = get_change_type(commit['new'], filename)
    count += len(files[ref])

print "%d Files to check in %d branches" % (count, len(files))

# create temporary dir and save a copy of the new files
tempdir = tempfile.mkdtemp('git_hook')
for ref, files in files.iteritems():
    for filename, data in files.iteritems():
        dname = os.path.dirname(filename)
        bname = os.path.basename(filename)
        try:
            os.makedirs(os.path.join(tempdir, dname))
        except OSError, exc:
            if exc.errno == errno.EEXIST:  # directory exists already
                pass
            else:
                raise

        with open(os.path.join(tempdir, dname, bname), 'w') as fp:
            fp.write(call_git(['cat-file', data[1], data[2]]))

try:
    # call checkstyle and/or pmd and print output
    # print call(['java', '-jar', checkstyle, '-c', checkstyle_config, tempdir])
    # print call(['java', '-jar', '/var/opt/gitlab/git-data/repositories/product-common/ProductCommonParent.git/custom_hooks/hooks-0.0.1-SNAPSHOT.jar', '-prercv', '79', 'developer-email-id', "I am now done with issue #500 #501 #502"])
    print call([pmd, 'pmd', '-d', tempdir, '-f', 'text', '-R', 'rulesets/java/basic.xml,rulesets/java/unusedcode.xml,rulesets/java/imports.xml,rulesets/java/strings.xml,rulesets/java/braces.xml,rulesets/java/clone.xml,rulesets/java/design.xml,rulesets/java/clone.xml,rulesets/java/finalizers.xml,rulesets/java/junit.xml,rulesets/java/migrating.xml,rulesets/java/optimizations.xml,rulesets/java/strictexception.xml,rulesets/java/sunsecure.xml,rulesets/java/typeresolution.xml'])
    print "SUCCESS"
except subprocess.CalledProcessError, ex:
    print ex.output  # print checkstyle and/or pmd messages
    exit(1)
finally:
    # remove temporary directory
    shutil.rmtree(tempdir)
</code>```

Body:
We have a DevOps process where people checkout or update from the remote master branch, create a new local working branch from the master and begin work in the local branch.

1) I need to put in restrictions that will keep people from pushing straight to the remote master branch directly. Instead, people need to push changes to their local branches to the same branch on the remote, after which an admin or code reviewer will merge it into the remote master.

2) I need a hook that will ensure that there is a valid Gitlab ticket or issue number in the form, say for example #PROJECTNAME123 before allowing their push to proceed to their remote branches (prior to code review and merging into remote master). Additionally, they must not be able to push if the ticket does not exist or is not yet open.

I have already created a Bash pre-receive hook using information from both the following websites but they get called but still allow the git push to get to the server even when I do not pass a Gitlab ticket/issue number.

https://github.com/Praqma/git-hooks/commit/2aa087fada0b0da51724f37a902362ddd78e168f

http://blog.hgomez.net/2015/03/02/Gitlab-custom-hooks-Bash-Way.html

The following is the pre-receive script and a bash function script that it calls.

pre-receive (No extension)

#!/usr/bin/env bash
#

source /var/opt/gitlab/git-data/repositories/Product-common/ProductCommonParent.git/custom_hooks/pre-receive-functions.sh

# enforced custom commit message format
while read old_revision new_revision refname ; do
        process_revision
done

exit 0

pre-receive-functions.sh

#!/usr/bin/env bash
#

regexp="#[0-9]\+"

grep_msg()
{
        grepped=$( echo $message | grep -i $regexp )
}

process_revision ()
{
  #revisions=$(git rev-list $old_revision..$new_revision)
echo "In pre-receive hook. Just before retrieving the revisions"
if [ "$old_revision" -eq 0 ]; then
    # list everything reachable from new_revision but not any heads
   revisions=$(git rev-list $(git for-each-ref --format='%(refname)' refs/heads/* | sed 's/^/\^/') $new_revision)
else
   revisions=$(git rev-list $old_revision..$new_revision)
fi

echo "In pre-receive hook. Just before IFS"
  IFS='\n' read -ra array <<< "$revisions"
  for rid in "${!array[@]}"; do
        revision=${array[rid]}
    message=$(git cat-file commit $revision | sed '1,/^$/d')
        grepped=$(echo $message | grep -i "#[0-9]\+")
    grep_msg()
    if [ -z "$grepped" ] ; then
                grepped_none=$(echo $message | grep -i "#none")
                if [ -n "$grepped_none" ] ; then
                        echo "Warning, you are committing without a ticket reference" >&1
                else
                        echo "You have not included a ticket reference" >&2
                        exit 1
                fi
    fi
  done

}

The following is the output when I try to push (I am pushing from a Git Bash shell on Windows 8.1 to a Fedora Core 24 having Gitlab installed):

xxx@xxxxx-HP MINGW64 ~/Documents/DevOps Re-Engineering/ProductCommonParent (ProductCommonParent002)
$ git push
Counting objects: 3, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 369 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: In pre-receive hook. Just before retrieving the revisions
remote: In pre-receive hook. Just before IFS
remote:
remote: To create a merge request for ProductCommonParent002, visit:
remote:   http://localhost/Product-common/ProductCommonParent/merge_requests/new?merge_request%5Bsource_branch%5D=ProductCommonParent002
remote:
To http://192.168.56.101/Product-common/ProductCommonParent.git
 * [new branch]      ProductCommonParent002 -> ProductCommonParent002

Note: Gitlab and its dependencies, including git, are installed on the same Fedora Core 24 Linux System.

I will appreciate speedy help in getting past this. Thank you very much in advance for your help.

Body:
1) Restrictions are already available by default for every default restricted branch of any new project or git repo. These restrictions apply to non-admin and non-root users of Gitlab.

2) We implemented the rules for checking that our developers comply with our development policies and processes by writing a Java spring boot CommandLineRunner application that called the Gitlab API. This application was packaged as a jar file.

We ensured that a developer must have a valid ticket number as part of his git commit message before he/she can push successfully to the remote counterpart of his working branch. This valid ticket must be assigned to him, have a valid milestone, and have the right label (either of NEW FEATURE, BUG, TASK etc.) selected for the push to be successful.

We integrated with the git hooks on the Gitlab Server by using a bash shell script that executed the jar file and allowed or failed the push request based on the output from the java application. This shell script, which is an adaptation of http://blog.hgomez.net/2015/03/02/Gitlab-custom-hooks-Bash-Way.html, can be found below:

#!/bin/bash
#
# pre-receive hook for Commit Check
#
COMPANY_EMAIL="mycorp.org"

readonly PROGNAME=$(basename $0)
readonly PROGDIR=$(readlink -m $(dirname $0))
IS_MERGE=0

check_single_commit()
{
  COMMIT_CHECK_STATUS=1
    echo "Repo >> $REPOSITORY_BASENAME"

    if [[ "$COMMIT_MESSAGE" == "Merge branch"* ]]; then
      COMMIT_CHECK_STATUS=0
      IS_MERGE=1
    else
    workFlowResult=`java -jar -Dspring.config.location=/home/gitlab/gitlab_custom_hooks/application.properties /home/gitlab/gitlab_custom_hooks/gitlab-tool.jar -prercv "$COMMIT_AUTHOR" "$COMMIT_MESSAGE" "$REPOSITORY_BASENAME"`
    echo "COMMIT_AUTHOR=$COMMIT_AUTHOR, COMMIT_MESSAGE=$COMMIT_MESSAGE, REPOSITORY_BASE=$REPOSITORY_BASENAME"

      echo " >>>>>>>>>>>>>>>>> $workFlowResult >>>>>>>>>>>>>>>>>" >&2
    if [[ "$workFlowResult" == *"PRE_RECEIVE_OK"* ]]; then
      echo " >>>>>>>>>>>>>>>>> $workFlowResult >>>>>>>>>>>>>>>>>" >&2
      COMMIT_CHECK_STATUS=0
    fi

    fi
}

check_all_commits()
{
  REVISIONS=$(git rev-list $OLD_REVISION..$NEW_REVISION)
  IFS='\n' read -ra LIST_OF_REVISIONS <<< "$REVISIONS"
if [ $(git rev-parse --is-bare-repository) = true ]
then
    REPOSITORY_BASENAME=$(basename "$PWD")
else
    REPOSITORY_BASENAME=$(basename $(readlink -nf "$PWD"/..))
fi
    echo REPOSITORY_BASENAME is $REPOSITORY_BASENAME
    REPOSITORY_BASENAME=$(basename "$PWD")
    REPOSITORY_BASENAME=${REPOSITORY_BASENAME%.git}

  for rid in "${!LIST_OF_REVISIONS[@]}"; do
    REVISION=${LIST_OF_REVISIONS[rid]}
    COMMIT_MESSAGE=$(git cat-file commit $REVISION | sed '1,/^$/d')
    COMMIT_AUTHOR=$(git cat-file commit $REVISION | grep committer | sed 's/^.* \([^@ ]\+@[^ ]\+\) \?.*$/\1/' | sed 's/<//' | sed 's/>//' | sed 's/@$COMPANY_EMAIL//')
    check_single_commit

    if [ "$COMMIT_CHECK_STATUS" != "0" ]; then
      echo "Commit validation failed for commit $REVISION" >&2
      exit 1
    fi

  done
}

# Get custom commit message format
while read OLD_REVISION NEW_REVISION REFNAME ; do
  check_all_commits
done

exit 0

3) Although not part of the question, integrating PMD checks at the Server-side without the use of a PMD Jenkins plugins, required the download of the PMD executable startup dependencies, the execution of PMD from within a python script to statically analyze source files being pushed by developers to the git server (Gitlab server). The python script that bootstraps PMD could be easily integrated into the above bash shell script. The python script, which is an adaptation of http://bluec0re.blogspot.com.ng/2012/05/git-pre-receive-hook-with-checkstyle.html, can be found below:

#!/usr/bin/env python

import subprocess
import sys
import tempfile
import shutil
import os
import errno

# variables for checkstyle
#checkstyle = '/var/opt/gitlab/git-data/repositories/product-common/ProductCommonParent.git/custom_hooks/checkstyle-7.5.1-all.jar'
#checkstyle_config = '/var/opt/gitlab/git-data/repositories/product-common/ProductCommonParent.git/custom_hooks/sun_checks.xml'
pmd = '/home/gitlab/gitlab_custom_hooks/pmd-bin-5.5.4/bin/run.sh'

# implementing check_output for python < 2.7
if not hasattr(subprocess, 'check_output'):
    def check_output(*popenargs, **kwargs):
        if 'stdout' in kwargs:
            raise ValueError('stdout argument not allowed, it will be overridden.')
        process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
        output, unused_err = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            er = subprocess.CalledProcessError(retcode, cmd)
            er.output = output
            raise er
        return output
    subprocess.check_output = check_output

# helper for calling executables
def call(*args, **kwargs):
    return subprocess.check_output(*args, **kwargs).strip()

# helper for calling git
def call_git(cmd, *args, **kwargs):
    return call(['git'] + cmd, *args, **kwargs)

# get all new commits from stdin
def get_commits():
    commits = {}
    for line in sys.stdin:
        old, new, ref = line.strip().split(' ')
        if old == '0000000000000000000000000000000000000000':
            old = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'

        if ref not in commits:
            commits[ref] = []
        commits[ref].append({
            'old': old,
            'new': new,
            'files': get_changed_files(old, new)
            })

    return commits

# get a list of changed files between to commits
def get_changed_files(old, new):
    return call_git(['diff', '--name-only', old, new]).split('\n')

# get filemode, object type (blob,tree,commit), hash for the given file at the
# given commit
def get_change_type(commit, filename):
    return call_git(['ls-tree', commit, filename]).split('\t')[0].split(' ')

commits = get_commits()

# use the latest file commit only
print "Cleaning up file list..."

files = {}
count = 0
for ref, data in commits.iteritems():
    files[ref] = {}
    for commit in data:
        for filename in commit['files']:
            if not filename.lower().endswith('.java'): continue
            files[ref][filename] = get_change_type(commit['new'], filename)
    count += len(files[ref])

print "%d Files to check in %d branches" % (count, len(files))

# create temporary dir and save a copy of the new files
tempdir = tempfile.mkdtemp('git_hook')
for ref, files in files.iteritems():
    for filename, data in files.iteritems():
        dname = os.path.dirname(filename)
        bname = os.path.basename(filename)
        try:
            os.makedirs(os.path.join(tempdir, dname))
        except OSError, exc:
            if exc.errno == errno.EEXIST:  # directory exists already
                pass
            else:
                raise

        with open(os.path.join(tempdir, dname, bname), 'w') as fp:
            fp.write(call_git(['cat-file', data[1], data[2]]))

try:
    # call checkstyle and/or pmd and print output
    # print call(['java', '-jar', checkstyle, '-c', checkstyle_config, tempdir])
    # print call(['java', '-jar', '/var/opt/gitlab/git-data/repositories/product-common/ProductCommonParent.git/custom_hooks/hooks-0.0.1-SNAPSHOT.jar', '-prercv', '79', 'developer-email-id', "I am now done with issue #500 #501 #502"])
    print call([pmd, 'pmd', '-d', tempdir, '-f', 'text', '-R', 'rulesets/java/basic.xml,rulesets/java/unusedcode.xml,rulesets/java/imports.xml,rulesets/java/strings.xml,rulesets/java/braces.xml,rulesets/java/clone.xml,rulesets/java/design.xml,rulesets/java/clone.xml,rulesets/java/finalizers.xml,rulesets/java/junit.xml,rulesets/java/migrating.xml,rulesets/java/optimizations.xml,rulesets/java/strictexception.xml,rulesets/java/sunsecure.xml,rulesets/java/typeresolution.xml'])
    print "SUCCESS"
except subprocess.CalledProcessError, ex:
    print ex.output  # print checkstyle and/or pmd messages
    exit(1)
finally:
    # remove temporary directory
    shutil.rmtree(tempdir)


问:
Config emacs + erlang for wxErlang usage
Hello
Erlang requires -smp for using wxErlang. As I edit and compile with emacs, I modified the erlang.el file like this:
(defvar inferior-erlang-machine-options '("-smp")

But this has no effect when I run the program:
WX ERROR: SMP emulator required** exception error: not_smp

Do you see a syntax error or anything else ?

答:
The -smp option requires an argument (enable, disable or auto). If you always want to start an SMP-enabled emulator, add the following to your ~/.emacs file:

```<code> (add-hook 'erlang-mode-hook
     (lambda ()
         (setq inferior-erlang-machine-options '("-smp" "enable"))))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The -smp option requires an argument (enable, disable or auto). If you always want to start an SMP-enabled emulator, add the following to your ~/.emacs file:

 (add-hook 'erlang-mode-hook
     (lambda ()
         (setq inferior-erlang-machine-options '("-smp" "enable"))))


问:
Rx Java Android : How to convert this callback block to Observer
I'm trying to upload a file via Amazon's S3 Android SDK. I've used RX Java a bit but I'm not sure how to convert this method to a method that returns an Observable because I want to chain the result of this method to another Observable call. It confuses me I suppose because of the fact that this does not return right away and can't return until either OnError or OnState changes. How do I handle these situations in an RX way?

```<code>public void uploadFile(TransferObserver transferObserver){

    transferObserver.setTransferListener(new TransferListener() {
        @Override
        public void onStateChanged(int id, TransferState state) {

        }

        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

        }

        @Override
        public void onError(int id, Exception ex) {

        }
  });

}
</code>```

If someone could answer with RX Java 2 and lambdas that would be great because I just keep coming up short on this one

答:
This is generally the right approach to bridge between the async/callback workd to reactive, but using Observable.create() is now discouraged, as it's requires advanced knowledge in order to make it right.

You should use more recent create method Observable.fromEmitter(), which will look quite the same:

```<code>    return Observable.fromEmitter(new Action1<Emitter<Integer>>() {
        @Override
        public void call(Emitter<Integer> emitter) {

            transObs.setTransferListener(new TransferListener() {
                @Override
                public void onStateChanged(int id, TransferState state) {
                    if (state == TransferState.COMPLETED)
                        emitter.onCompleted();
                }

                @Override
                public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

                }

                @Override
                public void onError(int id, Exception ex) {
                    emitter.onError(ex);
                }
            });
            emitter.setCancellation(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    // Deal with unsubscription:
                    // 1. unregister the listener to avoid memory leak
                    // 2. cancel the upload
                }
            });
        }
    }, Emitter.BackpressureMode.DROP);
</code>```

What was added here is: dealing with unsusbcription: cancelling the upload, and unregistering to avoid memory leaks, and specifying backpressure strategy.

you can read more here.

additional notes:

if you interested with progress you can call onNext() with progress at onProgressChanged() and convert the Observable to Observable<Integer>.

if not, you might want to consider using Completable which is Observable with no onNext() emissions but only onCompleted() this can suits your case if your not interested with progress indications.

Body:
I'm trying to upload a file via Amazon's S3 Android SDK. I've used RX Java a bit but I'm not sure how to convert this method to a method that returns an Observable because I want to chain the result of this method to another Observable call. It confuses me I suppose because of the fact that this does not return right away and can't return until either OnError or OnState changes. How do I handle these situations in an RX way?

public void uploadFile(TransferObserver transferObserver){

    transferObserver.setTransferListener(new TransferListener() {
        @Override
        public void onStateChanged(int id, TransferState state) {

        }

        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

        }

        @Override
        public void onError(int id, Exception ex) {

        }
  });

}

If someone could answer with RX Java 2 and lambdas that would be great because I just keep coming up short on this one

Body:
This is generally the right approach to bridge between the async/callback workd to reactive, but using Observable.create() is now discouraged, as it's requires advanced knowledge in order to make it right.

You should use more recent create method Observable.fromEmitter(), which will look quite the same:

    return Observable.fromEmitter(new Action1<Emitter<Integer>>() {
        @Override
        public void call(Emitter<Integer> emitter) {

            transObs.setTransferListener(new TransferListener() {
                @Override
                public void onStateChanged(int id, TransferState state) {
                    if (state == TransferState.COMPLETED)
                        emitter.onCompleted();
                }

                @Override
                public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

                }

                @Override
                public void onError(int id, Exception ex) {
                    emitter.onError(ex);
                }
            });
            emitter.setCancellation(new Cancellable() {
                @Override
                public void cancel() throws Exception {
                    // Deal with unsubscription:
                    // 1. unregister the listener to avoid memory leak
                    // 2. cancel the upload
                }
            });
        }
    }, Emitter.BackpressureMode.DROP);

What was added here is: dealing with unsusbcription: cancelling the upload, and unregistering to avoid memory leaks, and specifying backpressure strategy.

you can read more here.

additional notes:

if you interested with progress you can call onNext() with progress at onProgressChanged() and convert the Observable to Observable<Integer>.

if not, you might want to consider using Completable which is Observable with no onNext() emissions but only onCompleted() this can suits your case if your not interested with progress indications.


问:
nltk.app.concordance() crashes IDLE on Mac OS
I'm going through Chapter 5 in the NLTK book and at the end of section 2.3 there's a mention of nltk.app.concordance(). I wanted to try this out but as soon as I went to execute the command in the IDLE Shell, the shell restarted and I got an error message to report the problem to Apple. I'm on a Mac using El Capitan and Python 3.6.0 with the all the appropriate software installed. Is this a common problem? Or something I'm doing? I've been following the book exactly.

答:
I got the same problem.
On Mac OS, for me, the only way to launch nltk.app.concordance() is from a jupyter notebook


问:
PHP : Is it possible to include a file from a sibling directory?
Hi so in my main home directory i have 2 sub directories : subDir_A and subDir_B. in subDir_A there is A file called file_a.php.in subDir_B I have a file file_b.php. in file_b.php i want in include file_a.php. is it posiible? i am using Xampp.

答:
yes it is.

in file_B.php : include('../subDir_A/file_A.php');

the ../ means you want to go up a directory.


问:
Best approach to listen to a dynamic array of refs generated for Firebase?
Here's the scenario: I get an initial payload from Firebase (eg. 5 objects) from firebaseRef_1 (using a .once callback). I then transform each received object into a new Firebase ref. That newly generated ref looks like this:

```<code> "data/ccccyyyyotKKiWC2xaV1WZ7H3/things/-KgXo121225H9_Nks1O"
</code>```

If for example I have 5 incoming objects on that .once call, then I'll create 5 refs (see code snippet below).

Once I've created/generated the ref(s) I want to:

a) Create a .on listener to each of those 5 refs.

b) If (lets say) some time later 1 'row' of new data arrives to firebaseRef_1, I want to generate a new ref, and then create a listener - but now, just for that newly added item. Otherwise if I try to loop through all of the (now 6) elements Firebase throws a promise error telling me that the original 5  elements (refs) already have a listener attached.

The reason that I was thinking to use a .once call initially, is so that I can get the whole payload "all at .once" (pun intended!) which makes populating a ListView (react native) faster. I tried using a .child_added approach but on the initial load (of those 5 rows) the .child_added gets called 5 times and so you can see the rows appear one by one in the ListView which I dont like.

How should I best structure this in code to achieve what I've described above? Should I just have a .once call like this:

```<code>generateTheRefs() {
  firebase.database()
    .ref('data/' + firebaseUID + '/initialPath')
    .once('value', (snapshot) => {

     snapshot.forEach(childSnapshot => {
        var childData = childSnapshot.val();
        let path = `data/${childData.item1}/things/${childData.item2}`;

        //now create a .on listener
        firebase.database()
        .ref(path)
        .on('value', (snapshot) => {
             //....
        });
    });
  });
 }
</code>```

答:
You could:

Read the entire initial set with once(), and display that. Store it in a variable somewhere.

Then immediately register a listener with on('child_added'), and only act on things you did not previously collect from once() as you initially stored it.

Body:
Here's the scenario: I get an initial payload from Firebase (eg. 5 objects) from firebaseRef_1 (using a .once callback). I then transform each received object into a new Firebase ref. That newly generated ref looks like this:

 "data/ccccyyyyotKKiWC2xaV1WZ7H3/things/-KgXo121225H9_Nks1O"

If for example I have 5 incoming objects on that .once call, then I'll create 5 refs (see code snippet below).

Once I've created/generated the ref(s) I want to:

a) Create a .on listener to each of those 5 refs.

b) If (lets say) some time later 1 'row' of new data arrives to firebaseRef_1, I want to generate a new ref, and then create a listener - but now, just for that newly added item. Otherwise if I try to loop through all of the (now 6) elements Firebase throws a promise error telling me that the original 5  elements (refs) already have a listener attached.

The reason that I was thinking to use a .once call initially, is so that I can get the whole payload "all at .once" (pun intended!) which makes populating a ListView (react native) faster. I tried using a .child_added approach but on the initial load (of those 5 rows) the .child_added gets called 5 times and so you can see the rows appear one by one in the ListView which I dont like.

How should I best structure this in code to achieve what I've described above? Should I just have a .once call like this:

generateTheRefs() {
  firebase.database()
    .ref('data/' + firebaseUID + '/initialPath')
    .once('value', (snapshot) => {

     snapshot.forEach(childSnapshot => {
        var childData = childSnapshot.val();
        let path = `data/${childData.item1}/things/${childData.item2}`;

        //now create a .on listener
        firebase.database()
        .ref(path)
        .on('value', (snapshot) => {
             //....
        });
    });
  });
 }


问:
how webrtc from mobile(Android) to PC(Web)
I conunter a problem,
   I want transfer video from mobile(Android) to PC(Web) using WebRTC, it works well when Both mobile and PC have camera, but it not work when PC don't have camera. Is the peerconnection means both side need the some source?
   is anyone can give me suggestions or some demos?
   Thanks a lot!</p>

答:
WebRTC and its PeerConnection don't mandate the use of a camera.

Something you are doing in your own code is forcing that and/or causing the session to fail.


问:
Object Oriented Design for a Chess game
I am trying to get a feel of how to design and think in an Object Oriented manner and want to get some feedback from the community on this topic. The following is an example of a chess game that I wish to design in an OO manner. This is a very broad design and my focus at this stage is just to identify who is responsible for what messages and how the objects interact each other to simulate the game. Please point out if there are elements of bad design (high coupling, bad cohesion etc.) and how to improve on them.

The Chess game has the following classes

Board

Player

Piece

Square

ChessGame

The Board is made up of squares and so Board can be made responsible for creating and managing Square objects. Each piece also is on a square so each piece also has a reference to the square it is on. (Does this make sense?). Each piece then is responsible to move itself from one square to another.
Player class holds references to all pieces he owns and is also responsible for their creation (Should player create Pieces?) . Player has a method takeTurn which in turn calls a method movePiece which belongs to the piece Class which changes the location of the piece from its current location to another location. Now I am confused on what exactly the Board class must be responsible for. I assumed it was needed to determine the current state of the game and know when the game is over. But when a piece changes it's location how should the board get updated? should it maintain a seperate array of squares on which pieces exist and that gets updates as pieces move?

Also, ChessGame intially creates the Board and player objects who in turn create squares and pieces respectively and start the simulation. Briefly, this might be what the code in ChessGame may look like

```<code>Player p1 =new Player();
Player p2 = new Player();

Board b = new Board();

while(b.isGameOver())
{
  p1.takeTurn(); // calls movePiece on the Piece object
  p2.takeTurn();

}
</code>```

I am unclear on how the state of the board will get updated. Should piece have a reference to board? Where should be the responsibility lie? Who holds what references? Please help me with your inputs and point out problems in this design. I am deliberately not focusing on any algorithms or further details of game play as I am only interested in the design aspect. I hope this community can provide valuable insights.

答:
Here is my idea, for a fairly basic chess game :  </p>

```<code>class GameBoard {
 IPiece config[8][8];

 init {
  createAndPlacePieces("Black");
  createAndPlacePieces("White");
  setTurn("Black");

 }

 createAndPlacePieces(color) {
   //generate pieces using a factory method
   //for e.g. config[1][0] = PieceFactory("Pawn",color);
 }

 setTurn(color) {
   turn = color;
 }

 move(fromPt,toPt) {
  if(getPcAt(fromPt).color == turn) {
    toPtHasOppositeColorPiece = getPcAt(toPt) != null && getPcAt(toPt).color != turn;
    possiblePath = getPcAt(fromPt).generatePossiblePath(fromPt,toPt,toPtHasOppositeColorPiece);
   if(possiblePath != NULL) {
      traversePath();
      changeTurn();
   }
  }
 }

}

Interface IPiece {
  function generatePossiblePath(fromPt,toPt,toPtHasEnemy);
}

class PawnPiece implements IPiece{
  function generatePossiblePath(fromPt,toPt,toPtHasEnemy) {
    return an array of points if such a path is possible
    else return null;
  }
}

class ElephantPiece implements IPiece {....}
</code>```

Title: Object Oriented Design for a Chess game

Body:
I am trying to get a feel of how to design and think in an Object Oriented manner and want to get some feedback from the community on this topic. The following is an example of a chess game that I wish to design in an OO manner. This is a very broad design and my focus at this stage is just to identify who is responsible for what messages and how the objects interact each other to simulate the game. Please point out if there are elements of bad design (high coupling, bad cohesion etc.) and how to improve on them.

The Chess game has the following classes

Board

Player

Piece

Square

ChessGame

The Board is made up of squares and so Board can be made responsible for creating and managing Square objects. Each piece also is on a square so each piece also has a reference to the square it is on. (Does this make sense?). Each piece then is responsible to move itself from one square to another.
Player class holds references to all pieces he owns and is also responsible for their creation (Should player create Pieces?) . Player has a method takeTurn which in turn calls a method movePiece which belongs to the piece Class which changes the location of the piece from its current location to another location. Now I am confused on what exactly the Board class must be responsible for. I assumed it was needed to determine the current state of the game and know when the game is over. But when a piece changes it's location how should the board get updated? should it maintain a seperate array of squares on which pieces exist and that gets updates as pieces move?

Also, ChessGame intially creates the Board and player objects who in turn create squares and pieces respectively and start the simulation. Briefly, this might be what the code in ChessGame may look like

Player p1 =new Player();
Player p2 = new Player();

Board b = new Board();

while(b.isGameOver())
{
  p1.takeTurn(); // calls movePiece on the Piece object
  p2.takeTurn();

}

I am unclear on how the state of the board will get updated. Should piece have a reference to board? Where should be the responsibility lie? Who holds what references? Please help me with your inputs and point out problems in this design. I am deliberately not focusing on any algorithms or further details of game play as I am only interested in the design aspect. I hope this community can provide valuable insights.

Body:
Here is my idea, for a fairly basic chess game :

class GameBoard {
 IPiece config[8][8];

 init {
  createAndPlacePieces("Black");
  createAndPlacePieces("White");
  setTurn("Black");

 }

 createAndPlacePieces(color) {
   //generate pieces using a factory method
   //for e.g. config[1][0] = PieceFactory("Pawn",color);
 }

 setTurn(color) {
   turn = color;
 }

 move(fromPt,toPt) {
  if(getPcAt(fromPt).color == turn) {
    toPtHasOppositeColorPiece = getPcAt(toPt) != null && getPcAt(toPt).color != turn;
    possiblePath = getPcAt(fromPt).generatePossiblePath(fromPt,toPt,toPtHasOppositeColorPiece);
   if(possiblePath != NULL) {
      traversePath();
      changeTurn();
   }
  }
 }

}

Interface IPiece {
  function generatePossiblePath(fromPt,toPt,toPtHasEnemy);
}

class PawnPiece implements IPiece{
  function generatePossiblePath(fromPt,toPt,toPtHasEnemy) {
    return an array of points if such a path is possible
    else return null;
  }
}

class ElephantPiece implements IPiece {....}


问:
Setting page duration in R Markdown presentations
I need to create an auto advancing presentation for a lightning talk.
Is there a way to use the \hypersetup{pdfpageduration=n} functionality from Beamer within R Markdown without editing the intermediate .tex file? If possible, I would like to be able to set a different time for each slide. I'm open to solutions that use the html presentation engines (ioslides or Slidy) if this is an easier alternative.

答:
I completely forgot about R Sweave!
Here's a functioning example that addresses my goals using the R Sweave format in RStudio.</p>

```<code>\documentclass[usepdftitle=false]{beamer}
\usetheme{boxes}
\usecolortheme{seahorse}

\title{Test}
\author{Silas Tittes}
\institute{\normalsize University of Colorado Boulder}
\date{\today}

\begin{document}
\SweaveOpts{concordance=TRUE}

\frame{
\hypersetup{pdfpageduration=2} %2 seconds
\titlepage
}

\begin{frame}[fragile]{Example Slide}
\hypersetup{pdfpageduration=2} %2 seconds
\begin{columns}
\begin{column}{0.4\linewidth}
\begin{itemize}
\item R includes a powerful and flexible system (Sweave) for creating dynamic reports and reproducible research using LaTeX.
\item Warning, more time will be spent tinkering with options than you ever thought would be possible.
\end{itemize}
\end{column}
\begin{column}{0.7\linewidth}

<<mtcarsplot, fig=TRUE, echo=FALSE>>=
par(cex.lab = 2.2, cex.axis = 1.5, mar = c(5,5,1,2))
plot(x = mtcars$mpg, y = mtcars$wt,
     cex = 2.5*mtcars$hp/max(mtcars$hp), pch = 19,
     xlab = "Car weight", ylab = "MPG")
@

\end{column}
\end{columns}
\end{frame}
\end{document}
</code>```

Body:
I completely forgot about R Sweave!
Here's a functioning example that addresses my goals using the R Sweave format in RStudio.

\documentclass[usepdftitle=false]{beamer}
\usetheme{boxes}
\usecolortheme{seahorse}

\title{Test}
\author{Silas Tittes}
\institute{\normalsize University of Colorado Boulder}
\date{\today}

\begin{document}
\SweaveOpts{concordance=TRUE}

\frame{
\hypersetup{pdfpageduration=2} %2 seconds
\titlepage
}

\begin{frame}[fragile]{Example Slide}
\hypersetup{pdfpageduration=2} %2 seconds
\begin{columns}
\begin{column}{0.4\linewidth}
\begin{itemize}
\item R includes a powerful and flexible system (Sweave) for creating dynamic reports and reproducible research using LaTeX.
\item Warning, more time will be spent tinkering with options than you ever thought would be possible.
\end{itemize}
\end{column}
\begin{column}{0.7\linewidth}

<<mtcarsplot, fig=TRUE, echo=FALSE>>=
par(cex.lab = 2.2, cex.axis = 1.5, mar = c(5,5,1,2))
plot(x = mtcars$mpg, y = mtcars$wt,
     cex = 2.5*mtcars$hp/max(mtcars$hp), pch = 19,
     xlab = "Car weight", ylab = "MPG")
@

\end{column}
\end{columns}
\end{frame}
\end{document}


问:
Special removal of duplicated rows in R data frame
Let's say I have the a data frame df as:

```<code>df<- data.frame(id1=c('A','B','C','D','P'), id2=c('P','H','Q','S','A'),weight=c(3,4,2,7,3))

  id1 id2 weight
1   A   P      3
2   B   H      4
3   C   Q      2
4   D   S      7
5   P   A      3
</code>```

This data frame is the edge list representation of a weighted-undirected graph. In this example, I want to remove either the first row or the last row since they are repeated edges. Of course, I want to do the same with all the repeated edges.

I tried this:

```<code>w=df[!duplicated(df[,c('id1', 'id2','weight')]),]
</code>```

but this is not enough.

答:
We can use pmin/pmax

```<code>df[!duplicated(cbind(pmin(df$id1, df$id2), pmax(df$id1, df$id2))),]
#   id1 id2 weight
#1   A   P      3
#2   B   H      4
#3   C   Q      2
#4   D   S      7
</code>```

data

```<code>df<- data.frame(id1=c('A','B','C','D','P'),
     id2=c('P','H','Q','S','A'),weight=c(3,4,2,7,3), stringsAsFactors=FALSE)
</code>```

Body:
Let's say I have the a data frame df as:

df<- data.frame(id1=c('A','B','C','D','P'), id2=c('P','H','Q','S','A'),weight=c(3,4,2,7,3))

  id1 id2 weight
1   A   P      3
2   B   H      4
3   C   Q      2
4   D   S      7
5   P   A      3

This data frame is the edge list representation of a weighted-undirected graph. In this example, I want to remove either the first row or the last row since they are repeated edges. Of course, I want to do the same with all the repeated edges.

I tried this:

w=df[!duplicated(df[,c('id1', 'id2','weight')]),]

but this is not enough.

Body:
We can use pmin/pmax

df[!duplicated(cbind(pmin(df$id1, df$id2), pmax(df$id1, df$id2))),]
#   id1 id2 weight
#1   A   P      3
#2   B   H      4
#3   C   Q      2
#4   D   S      7

data

df<- data.frame(id1=c('A','B','C','D','P'),
     id2=c('P','H','Q','S','A'),weight=c(3,4,2,7,3), stringsAsFactors=FALSE)


问:
Java Consider defining a bean of type in your configuration exception when add mongoDB support
I have a very simple Java Springboot project connect to the database. Still, I want a mongoDB connection and I could use mongoDB as well.

I read lots of document and I can't make it work. And my commits code is:

https://github.com/GuoJing/spb/commit/20c04ce38d43bb0ba229d0d3577fdccbd571062e

If adding @AutoWired annotation, application will not start. I think this should be same as official document.

in src/main/java/controller/UserController.java

```<code>@Autowired
private UserPropsRepository userPropsRepository;
</code>```

Here is my project, could anybody help me?

https://github.com/GuoJing/spb

My Exception is:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field userPropsRepository in controller.UserController required a bean of type 'repository.UserPropsRepository' that could not be found.

Action:

Consider defining a bean of type 'repository.UserPropsRepository' in your configuration.
</code>```

答:
suppose you are missing @Repository annotation in the UserPropsRepository interface.</p>

```<code>   @repository("userPropsRepository")
   public interface UserPropsRepository extends MongoRepository<UserProps, String> {
    UserProps findOne(String id);
    UserProps save(UserProps props);
    UserProps update(UserProps props);
    void delete(UserProps props);
}
</code>```

Body:
I have a very simple Java Springboot project connect to the database. Still, I want a mongoDB connection and I could use mongoDB as well.

I read lots of document and I can't make it work. And my commits code is:

https://github.com/GuoJing/spb/commit/20c04ce38d43bb0ba229d0d3577fdccbd571062e

If adding @AutoWired annotation, application will not start. I think this should be same as official document.

in src/main/java/controller/UserController.java

@Autowired
private UserPropsRepository userPropsRepository;

Here is my project, could anybody help me?

https://github.com/GuoJing/spb

My Exception is:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userPropsRepository in controller.UserController required a bean of type 'repository.UserPropsRepository' that could not be found.

Action:

Consider defining a bean of type 'repository.UserPropsRepository' in your configuration.

Body:
suppose you are missing @Repository annotation in the UserPropsRepository interface.

   @repository("userPropsRepository")
   public interface UserPropsRepository extends MongoRepository<UserProps, String> {
    UserProps findOne(String id);
    UserProps save(UserProps props);
    UserProps update(UserProps props);
    void delete(UserProps props);
}


答:
This is very easy to accomplish using one of 4 functions.

include, include_once, require or require_once, see the documentation for this http://php.net/manual/en/function.include.php (I won't expand on this as it's very basic PHP functionality)

You should do your include in the following fashion.

```<code># you could use any of the other keywords as well.
include __DIR__ . '/../subDir_A/file_A.php';
</code>```

The magic constant __DIR__ was used as it will consider the reference relative the the file it's called in. If you don't do this and just do include '../subDir_A/file_A.php'; it might not work if you included file_B.php somewhere else as it'll be relative to the parent file that called it.

Title: PHP : Is it possible to include a file from a sibling directory?

Body: Hi so in my main home directory i have 2 sub directories : subDir_A and subDir_B. in subDir_A there is A file called file_a.php.in subDir_B I have a file file_b.php. in file_b.php i want in include file_a.php. is it posiible? i am using Xampp.

Body:
This is very easy to accomplish using one of 4 functions.

include, include_once, require or require_once, see the documentation for this http://php.net/manual/en/function.include.php (I won't expand on this as it's very basic PHP functionality)

You should do your include in the following fashion.

# you could use any of the other keywords as well.
include __DIR__ . '/../subDir_A/file_A.php';

The magic constant __DIR__ was used as it will consider the reference relative the the file it's called in. If you don't do this and just do include '../subDir_A/file_A.php'; it might not work if you included file_B.php somewhere else as it'll be relative to the parent file that called it.


问:
npm install errors with window's CMD
I'm new to NODEjs trying to globally in using window 8.1 run as ADMINISTRATOR from CMD

install an npm module i.e. node-dev

Every time I try to npm install I get this error.

```<code>npm ERR! Windows_NT 6.3.9600

npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\
node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "node-dev"

npm ERR! node v6.10.1

npm ERR! npm  v3.10.10

npm ERR! code ENOTFOUND

npm ERR! errno ENOTFOUND

npm ERR! syscall getaddrinfo

npm ERR! network getaddrinfo ENOTFOUND registry.nmpjs.org registry.nmpjs.org:80

npm ERR! network This is most likely not a problem with npm itself

npm ERR! network and is related to network connectivity.

npm ERR! network In most cases you are behind a proxy or have bad network setti
gs.
npm ERR! network

npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'
</code>```

I did some searching around, and saw a couple of similar cases none of which have been resolved for the case of windows.

So what's the deal? Is this some weird fringe case bug that has no solution yet?

答:
try

```<code>npm cache clean
</code>```

then

```<code>npm install -g <package_name>
</code>```

If this does not work

```<code>npm config set registry=http://registry.npmjs.org
</code>```

and try, installing the package.

Title: npm install errors with window's CMD

Body:
I'm new to NODEjs trying to globally in using window 8.1 run as ADMINISTRATOR from CMD

install an npm module i.e. node-dev

Every time I try to npm install I get this error.

npm ERR! Windows_NT 6.3.9600

npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\
node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "node-dev"

npm ERR! node v6.10.1

npm ERR! npm  v3.10.10

npm ERR! code ENOTFOUND

npm ERR! errno ENOTFOUND

npm ERR! syscall getaddrinfo

npm ERR! network getaddrinfo ENOTFOUND registry.nmpjs.org registry.nmpjs.org:80

npm ERR! network This is most likely not a problem with npm itself

npm ERR! network and is related to network connectivity.

npm ERR! network In most cases you are behind a proxy or have bad network setti
gs.
npm ERR! network

npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

I did some searching around, and saw a couple of similar cases none of which have been resolved for the case of windows.

So what's the deal? Is this some weird fringe case bug that has no solution yet?

Body:
try

npm cache clean

then

npm install -g <package_name>

If this does not work

npm config set registry=http://registry.npmjs.org

and try, installing the package.


问:
PHP Error in my Server
Hey Guys I have this Java code in ANdroid studio:

```<code>private void loginUser(){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");
                    if (success) {
                        launchHomeScreen();
                        pd.dismiss();
                        Toast.makeText(LoginActivity.this,"Welcome back " + username,Toast.LENGTH_LONG).show();
                    }
                    else {
                        loginButton.setBackgroundColor(0x73000000);
                        Toast.makeText(LoginActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                        pd.dismiss();
                    }
                }
                catch (JSONException e) {
                    loginButton.setBackgroundColor(0x73000000);
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this,e.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loginButton.setBackgroundColor(0x73000000);
                Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                pd.dismiss();
            }
        }){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<>();
        params.put(KEY_USERNAME,username);
        params.put(KEY_PASSWORD,password);
        return params;
    }

};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
</code>```

}

And this at my Server as php code:

```<code><?php
$con = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUsername, $colPassword);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    if (password_verify($password, $colPassword)) {
        $response["success"] = true;
    }
}
header('Content-Type: application/json');
echo json_encode($response);
</code>```

?>

And that's the Error I get from my Server:

[29-Mar-2017 18:24:46 UTC] PHP Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement in /home/u371648055/public_html/login.php on line 11

SO I don't understand what's wrong in my Code. I know that the Javacode is correct....so....it's the phpcode..but what?

MY MySQL Database:

For the problem with the password = 0
Here is that what I send to Server:

```<code>private void registerUser(){
    pd = ProgressDialog.show(RegisterActivity.this, "", "Loading...");
    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if (success) {
                            launchHomeScreen();
                            pd.dismiss();
                        }
                        else {
                            Toast.makeText(RegisterActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                            pd.dismiss();
                            Intent loginActivity = new Intent (RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(loginActivity);
                            finish();
                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        pd.dismiss();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RegisterActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            params.put(KEY_MOBILENUMBER,mobileNumber);
            params.put(KEY_EMAIL, email);
            return params;
        }

    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
</code>```

}
ANd that's the register php code:

```<code><?php
$connect = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];
$mobilenumber = $_POST["mobilenumber"];
$email = $_POST["email"];

registerUser();

function registerUser() {
    global $connect, $username, $password, $mobilenumber, $email;
    $statement = mysqli_prepare($connect, "INSERT INTO user (username, password, mobilenumber, email) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "siss", $username, $password, $mobilenumber, $email);
    mysqli_stmt_execute($statement);
    mysqli_stmt_close($statement);

}
</code>```

How I get the $password:

```<code>public class RegisterActivity extends AppCompatActivity {

   public static final String KEY_PASSWORD = "password";
   private String password;

  //When clicking the Regsiter-Button:
   pwd = (EditText) findViewById(R.id.editText2);
   password = pwd.getText().toString().trim();
   registerUser();
}
</code>```

答:
you need to match the count of ? placeholders with the count of substitution variables; only then the statement can be prepared for execution:

```<code>SELECT * FROM user WHERE ? = ?;
</code>```

Title: PHP Error in my Server

Body:
Hey Guys I have this Java code in ANdroid studio:

private void loginUser(){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");
                    if (success) {
                        launchHomeScreen();
                        pd.dismiss();
                        Toast.makeText(LoginActivity.this,"Welcome back " + username,Toast.LENGTH_LONG).show();
                    }
                    else {
                        loginButton.setBackgroundColor(0x73000000);
                        Toast.makeText(LoginActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                        pd.dismiss();
                    }
                }
                catch (JSONException e) {
                    loginButton.setBackgroundColor(0x73000000);
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this,e.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loginButton.setBackgroundColor(0x73000000);
                Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                pd.dismiss();
            }
        }){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<>();
        params.put(KEY_USERNAME,username);
        params.put(KEY_PASSWORD,password);
        return params;
    }

};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

}

And this at my Server as php code:

<?php
$con = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUsername, $colPassword);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    if (password_verify($password, $colPassword)) {
        $response["success"] = true;
    }
}
header('Content-Type: application/json');
echo json_encode($response);

?>

And that's the Error I get from my Server:

[29-Mar-2017 18:24:46 UTC] PHP Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement in /home/u371648055/public_html/login.php on line 11

SO I don't understand what's wrong in my Code. I know that the Javacode is correct....so....it's the phpcode..but what?

MY MySQL Database:

For the problem with the password = 0
Here is that what I send to Server:

private void registerUser(){
    pd = ProgressDialog.show(RegisterActivity.this, "", "Loading...");
    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if (success) {
                            launchHomeScreen();
                            pd.dismiss();
                        }
                        else {
                            Toast.makeText(RegisterActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                            pd.dismiss();
                            Intent loginActivity = new Intent (RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(loginActivity);
                            finish();
                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        pd.dismiss();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RegisterActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            params.put(KEY_MOBILENUMBER,mobileNumber);
            params.put(KEY_EMAIL, email);
            return params;
        }

    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}
ANd that's the register php code:

<?php
$connect = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];
$mobilenumber = $_POST["mobilenumber"];
$email = $_POST["email"];

registerUser();

function registerUser() {
    global $connect, $username, $password, $mobilenumber, $email;
    $statement = mysqli_prepare($connect, "INSERT INTO user (username, password, mobilenumber, email) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "siss", $username, $password, $mobilenumber, $email);
    mysqli_stmt_execute($statement);
    mysqli_stmt_close($statement);

}

How I get the $password:

public class RegisterActivity extends AppCompatActivity {

   public static final String KEY_PASSWORD = "password";
   private String password;

  //When clicking the Regsiter-Button:
   pwd = (EditText) findViewById(R.id.editText2);
   password = pwd.getText().toString().trim();
   registerUser();
}

Body:
you need to match the count of ? placeholders with the count of substitution variables; only then the statement can be prepared for execution:

SELECT * FROM user WHERE ? = ?;


问:
Can I lookup an EJB from another EJB?
I have an EJB and it has a method that makes a lookup to another EJB.
I'm having a NameNotFoundException with this code.

ServiceEJBImpl :

```<code>@Stateless(name = "ServiceEJB", mappedName = "AppAcaAvaliacaoAtuarial-ModelAvaliacaoAtuarial-ServiceEJB")
public class ServiceEJBImpl implements ServiceEJB, ServiceEJBLocal{

public void persistConflicts(List<Conflict> conflicts)
{
    ConflictDAOLocal conflictDAO =  (ConflictDAOLocal) BeanLocator.lookup("java:comp/env/ejb/local/ConflictDAO");
    conflictDAO.persistAll(conflicts);
}
</code>```

ConflictDAOLocal:

```<code>@Local
public interface ConflitoDAOLocal{
   void persistAll(List<Conflict> conflicts);
}
</code>```

That's my lookupMethod:

```<code>public static Object lookup(String jndiName) {
    Context context = null;
    try {
        context = new InitialContext();
        return context.lookup(jndiName);
    } catch (NamingException ex) {
        throw new IllegalStateException("...",ex);
    } finally {
        try {
            context.close();
        } catch (NamingException ex) {
            throw new IllegalStateException("...",ex);
        }
    }
}
</code>```

web.xml:

```<code><ejb-local-ref>
    <ejb-ref-name>ejb/local/ConflictDAO</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
<local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ConflictDAOLocal</local>
    <ejb-link>ConflictDAO</ejb-link>
</ejb-local-ref>

 <ejb-local-ref>
    <ejb-ref-name>ejb/local/ServiceEJB</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ServiceEJBLocal</local>
    <ejb-link>ServiceEJB</ejb-link>
</ejb-local-ref>
</code>```

Is there a problem instantiating a new context when making a lookup to an EJB inside another EJB that already has a context instantiated?

I'm not considering @EJB annotation.

答:
In order to perform a JNDI lookup in an EJB for a dependent EJB, you need to specify your ejb-local-ref elements in an ejb-jar.xml file in you EJB jar:

```<code><ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
          http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd"
         version="3.2">

    <enterprise-beans>
        ...
        <session>
            <ejb-name>ServiceEJB</ejb-name>

            <ejb-local-ref>
                <ejb-ref-name>ejb/local/ConflictDAO</ejb-ref-name>
                <local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ConflictDAOLocal</local>
                <ejb-link>ConflitoDAO</ejb-link>
            </ejb-local-ref>
        </session>
        ...
    </enterprise-beans>
</ejb-jar>
</code>```

You must provide an ejb-local-ref element for each EJB that looks up another EJB.

Each EJB in an EJB jar has it's own java:comp/env namespace, whereas a webapp WAR file has a single java:comp/env namespace.

Title: Can I lookup an EJB from another EJB?

Body:
I have an EJB and it has a method that makes a lookup to another EJB.
I'm having a NameNotFoundException with this code.

ServiceEJBImpl :

@Stateless(name = "ServiceEJB", mappedName = "AppAcaAvaliacaoAtuarial-ModelAvaliacaoAtuarial-ServiceEJB")
public class ServiceEJBImpl implements ServiceEJB, ServiceEJBLocal{

public void persistConflicts(List<Conflict> conflicts)
{
    ConflictDAOLocal conflictDAO =  (ConflictDAOLocal) BeanLocator.lookup("java:comp/env/ejb/local/ConflictDAO");
    conflictDAO.persistAll(conflicts);
}

ConflictDAOLocal:

@Local
public interface ConflitoDAOLocal{
   void persistAll(List<Conflict> conflicts);
}

That's my lookupMethod:

public static Object lookup(String jndiName) {
    Context context = null;
    try {
        context = new InitialContext();
        return context.lookup(jndiName);
    } catch (NamingException ex) {
        throw new IllegalStateException("...",ex);
    } finally {
        try {
            context.close();
        } catch (NamingException ex) {
            throw new IllegalStateException("...",ex);
        }
    }
}

web.xml:

<ejb-local-ref>
    <ejb-ref-name>ejb/local/ConflictDAO</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
<local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ConflictDAOLocal</local>
    <ejb-link>ConflictDAO</ejb-link>
</ejb-local-ref>

 <ejb-local-ref>
    <ejb-ref-name>ejb/local/ServiceEJB</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ServiceEJBLocal</local>
    <ejb-link>ServiceEJB</ejb-link>
</ejb-local-ref>

Is there a problem instantiating a new context when making a lookup to an EJB inside another EJB that already has a context instantiated?

I'm not considering @EJB annotation.

Body:
In order to perform a JNDI lookup in an EJB for a dependent EJB, you need to specify your ejb-local-ref elements in an ejb-jar.xml file in you EJB jar:

<ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
          http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd"
         version="3.2">

    <enterprise-beans>
        ...
        <session>
            <ejb-name>ServiceEJB</ejb-name>

            <ejb-local-ref>
                <ejb-ref-name>ejb/local/ConflictDAO</ejb-ref-name>
                <local>br.gov.rj.rioprev.sigap.acompatuarial.avalatuarial.model.dao.ConflictDAOLocal</local>
                <ejb-link>ConflitoDAO</ejb-link>
            </ejb-local-ref>
        </session>
        ...
    </enterprise-beans>
</ejb-jar>

You must provide an ejb-local-ref element for each EJB that looks up another EJB.

Each EJB in an EJB jar has it's own java:comp/env namespace, whereas a webapp WAR file has a single java:comp/env namespace.


问:
problem with poco on snow leopard + eclipse
hey, i'm trying to work with poco on osx snow leopard, compiling via eclipse with the 64bit mac parser,

when trying to compile a simple code using Poco DateTime i get the following error :

"Poco::DateTime::DateTime()", referenced from:
      _main in Run.o
  "Poco::DateTime::~DateTime()", referenced from:
      _main in Run.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [assignment 2] Error 1

does anyone know why this is happening ?
i'm guessing something to do with me compiling 64bit, but installing poco i made sure it compiles to darwin 64bit as well..

SOLVED -- the error was i didn't really compile poco for 64bit..
thanks...

答: The linker can't find the Poco library. Like aschepler said, check the -l and -L flags. Try edit those flags on the project properties (search for the paths of the libraries)</p>


问:
8 Columns in Twitter Bootstrap
How can I set up 8 equal columns in the latest version of Twitter bootstrap.

I can create 4 equal columns by doing the following but don't get how I can get 8:

```<code>    <div class="col-sm-12">
        <div class="row">
            <div class="col-sm-3">
                <div class="col-sm-12 col-xs-6">
                    <a href="#"><img src="/image.png" class="img-responsive" alt="..."></a>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="col-sm-12 col-xs-6">
                    <a href="#"><img src="/image.png" class="img-responsive" alt="..."></a>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="col-sm-12 col-xs-6">
                    <a href="#"><img src="/image.png" class="img-responsive" alt="..."></a>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="col-sm-12 col-xs-6">
                    <a href="#"><img src="/image.png" class="img-responsive" alt="..."></a>
                </div>
            </div>
        </div>
    </div>
</code>```

答:
For 8 column grid you don't have to customize the css or html.

Simply create or copy this:

1

2

3

4

5

6

7

8

```

Title: 8 Columns in Twitter Bootstrap

Body:
For 8 column grid you don't have to customize the css or html.

Simply create or copy this:

<div class="col-md-6">
        <div class="col-md-3">1</div>
        <div class="col-md-3">2</div>
        <div class="col-md-3">3</div>
        <div class="col-md-3">4</div>
    </div>

    <div class="col-md-6">
        <div class="col-md-3">5</div>
        <div class="col-md-3">6</div>
        <div class="col-md-3">7</div>
        <div class="col-md-3">8</div>
    </div>


问:
Server polling with AngularJS
I'm trying to learn AngularJS.  My first attempt to get new data every second worked:

```<code>'use strict';

function dataCtrl($scope, $http, $timeout) {
    $scope.data = [];

    (function tick() {
        $http.get('api/changingData').success(function (data) {
            $scope.data = data;
            $timeout(tick, 1000);
        });
    })();
};
</code>```

When I simulate a slow server by sleeping the thread for 5 seconds it waits for the response before updating the UI and setting another timeout.  The problem is when I rewrote the above to use Angular modules and DI for module creation:

```<code>'use strict';

angular.module('datacat', ['dataServices']);

angular.module('dataServices', ['ngResource']).
    factory('Data', function ($resource) {
        return $resource('api/changingData', {}, {
            query: { method: 'GET', params: {}, isArray: true }
        });
    });

function dataCtrl($scope, $timeout, Data) {
    $scope.data = [];

    (function tick() {
        $scope.data = Data.query();
        $timeout(tick, 1000);
    })();
};
</code>```

This only works if the server response is fast. If there's any delay it spams out 1 request a second without waiting for a response and seems to clear the UI. I think I need to use a callback function. I tried:

```<code>var x = Data.get({}, function () { });
</code>```

but got an error: "Error: destination.push is not a function"  This was based on the docs for $resource but I didn't really understand the examples there.

How do I make the second approach work?

答:
We can do it polling easily using $interval service.
here is detail document about $interval

https://docs.angularjs.org/api/ng/service/$interval

Problem using $interval is that if you are doing $http service calling or server interaction and if delayed more than $interval time then before your one request completes, it starts another request.

Solution:

1. Polling should be simple status getting from server like a single bit or lightweight json so should not take longer then your defined interval time. You should also define time of interval appropriately to avoid this issue.

2. Somehow it is still happening due any reason, you should check a global flag that previous request finished or not before sending any other requests. It will miss that time interval but it won't send request prematurely.

Also if you wanted to set threshold value that after some value anyhow polling should be set then you can do it following way.

Here is working example. explained in detail here

```<code>angular.module('myApp.view2', ['ngRoute'])
.controller('View2Ctrl', ['$scope', '$timeout', '$interval', '$http', function ($scope, $timeout, $interval, $http) {
    $scope.title = "Test Title";

    $scope.data = [];

    var hasvaluereturnd = true; // Flag to check
    var thresholdvalue = 20; // interval threshold value

    function poll(interval, callback) {
        return $interval(function () {
            if (hasvaluereturnd) {  //check flag before start new call
                callback(hasvaluereturnd);
            }
            thresholdvalue = thresholdvalue - 1;  //Decrease threshold value
            if (thresholdvalue == 0) {
                $scope.stopPoll(); // Stop $interval if it reaches to threshold
            }
        }, interval)
    }

    var pollpromise = poll(1000, function () {
        hasvaluereturnd = false;
        //$timeout(function () {  // You can test scenario where server takes more time then interval
        $http.get('http://httpbin.org/get?timeoutKey=timeoutValue').then(
            function (data) {
                hasvaluereturnd = true;  // set Flag to true to start new call
                $scope.data = data;

            },
            function (e) {
                hasvaluereturnd = true; // set Flag to true to start new call
                //You can set false also as per your requirement in case of error
            }
        );
        //}, 2000);
    });

    // stop interval.
    $scope.stopPoll = function () {
        $interval.cancel(pollpromise);
        thresholdvalue = 0;     //reset all flags.
        hasvaluereturnd = true;
    }
}]);
</code>```

Title: Server polling with AngularJS

Body:
I'm trying to learn AngularJS.  My first attempt to get new data every second worked:

'use strict';

function dataCtrl($scope, $http, $timeout) {
    $scope.data = [];

    (function tick() {
        $http.get('api/changingData').success(function (data) {
            $scope.data = data;
            $timeout(tick, 1000);
        });
    })();
};

When I simulate a slow server by sleeping the thread for 5 seconds it waits for the response before updating the UI and setting another timeout.  The problem is when I rewrote the above to use Angular modules and DI for module creation:

'use strict';

angular.module('datacat', ['dataServices']);

angular.module('dataServices', ['ngResource']).
    factory('Data', function ($resource) {
        return $resource('api/changingData', {}, {
            query: { method: 'GET', params: {}, isArray: true }
        });
    });

function dataCtrl($scope, $timeout, Data) {
    $scope.data = [];

    (function tick() {
        $scope.data = Data.query();
        $timeout(tick, 1000);
    })();
};

This only works if the server response is fast. If there's any delay it spams out 1 request a second without waiting for a response and seems to clear the UI. I think I need to use a callback function. I tried:

var x = Data.get({}, function () { });

but got an error: "Error: destination.push is not a function"  This was based on the docs for $resource but I didn't really understand the examples there.

How do I make the second approach work?

Body:
We can do it polling easily using $interval service.
here is detail document about $interval

https://docs.angularjs.org/api/ng/service/$interval

Problem using $interval is that if you are doing $http service calling or server interaction and if delayed more than $interval time then before your one request completes, it starts another request.

Solution:

1. Polling should be simple status getting from server like a single bit or lightweight json so should not take longer then your defined interval time. You should also define time of interval appropriately to avoid this issue.

2. Somehow it is still happening due any reason, you should check a global flag that previous request finished or not before sending any other requests. It will miss that time interval but it won't send request prematurely.

Also if you wanted to set threshold value that after some value anyhow polling should be set then you can do it following way.

Here is working example. explained in detail here

angular.module('myApp.view2', ['ngRoute'])
.controller('View2Ctrl', ['$scope', '$timeout', '$interval', '$http', function ($scope, $timeout, $interval, $http) {
    $scope.title = "Test Title";

    $scope.data = [];

    var hasvaluereturnd = true; // Flag to check
    var thresholdvalue = 20; // interval threshold value

    function poll(interval, callback) {
        return $interval(function () {
            if (hasvaluereturnd) {  //check flag before start new call
                callback(hasvaluereturnd);
            }
            thresholdvalue = thresholdvalue - 1;  //Decrease threshold value
            if (thresholdvalue == 0) {
                $scope.stopPoll(); // Stop $interval if it reaches to threshold
            }
        }, interval)
    }

    var pollpromise = poll(1000, function () {
        hasvaluereturnd = false;
        //$timeout(function () {  // You can test scenario where server takes more time then interval
        $http.get('http://httpbin.org/get?timeoutKey=timeoutValue').then(
            function (data) {
                hasvaluereturnd = true;  // set Flag to true to start new call
                $scope.data = data;

            },
            function (e) {
                hasvaluereturnd = true; // set Flag to true to start new call
                //You can set false also as per your requirement in case of error
            }
        );
        //}, 2000);
    });

    // stop interval.
    $scope.stopPoll = function () {
        $interval.cancel(pollpromise);
        thresholdvalue = 0;     //reset all flags.
        hasvaluereturnd = true;
    }
}]);


问:
Solr: Multi-word synonyms
I'm developing a set of synonyms, where you can find some multi-word expressions, such as:

black berry => blackberry

At the analysis stage, and using the /admin/analysis.jsp tools, I can see that the results are correct.

A query such as "quiero una black berry" returns the following sequence:

The org.apache.solr.analysis.StandardTokenizerFactory {luceneMatchVersion=LUCENE_36}:

```<code>position    1   2   3   4
term text   quiero  una black   berry
startOffset 0   7   11  17
endOffset   6   10  16  22
type    <ALPHANUM>  <ALPHANUM>  <ALPHANUM>  <ALPHANUM>
</code>```

The org.apache.solr.analysis.SynonymFilterFactory {synonyms=lang/synonyms_es.txt, expand=false, ignoreCase=true, luceneMatchVersion=LUCENE_36}:

```<code>position    1   2   3
term text   quiero  una blackberry
type    <ALPHANUM>  <ALPHANUM>  SYNONYM
startOffset 0   7   11
endOffset   6   10  22
</code>```

However, if I try this sentence at a "real" query, the request handler (an evolution of the edismax handler), the tokens "black" and "berry" were not replaced by "blackberry".

I've seen here that you can solve this situation by modifying the FieldQParser plugin.

Anyway, since such post was made almost 3 years ago, I'd like to know if there's some way of solving this problem inside Solr, avoiding having to expand some plugin.

Thanks.

答:
In Solr-6.5.0 you can enables query-time multi-term synonyms by setting below parameter

From Documentation

The sow Parameter
 Split on whitespace: if set to false,
  whitespace-separated term sequences will be provided to text analysis
  in one shot, enabling proper function of analysis filters that operate
  over term sequences, e.g. multi-word synonyms and shingles. Defaults
  to true: text analysis is invoked separately for each individual
  whitespace-separated term.

[synonym.txt]

```<code>black berry => blackberry
</code>```

[Example]

```<code>q=black berry
&sow=false
&debug=query
</code>```

[Debug-Response]

```<code><lst name="debug">
<str name="rawquerystring">black berry</str>
<str name="querystring">black berry</str>
<str name="parsedquery">_text_:blackberry</str>
<str name="parsedquery_toString">_text_:blackberry</str>
<str name="QParser">LuceneQParser</str>
</lst>
</code>```

Now you can see from debug response that I have searched for black berry, but synonym filter factory maps to the word that I have mentioned in synonym.txt.

Title: Solr: Multi-word synonyms

Body:
I'm developing a set of synonyms, where you can find some multi-word expressions, such as:

black berry => blackberry

At the analysis stage, and using the /admin/analysis.jsp tools, I can see that the results are correct.

A query such as "quiero una black berry" returns the following sequence:

The org.apache.solr.analysis.StandardTokenizerFactory {luceneMatchVersion=LUCENE_36}:

position    1   2   3   4
term text   quiero  una black   berry
startOffset 0   7   11  17
endOffset   6   10  16  22
type    <ALPHANUM>  <ALPHANUM>  <ALPHANUM>  <ALPHANUM>

The org.apache.solr.analysis.SynonymFilterFactory {synonyms=lang/synonyms_es.txt, expand=false, ignoreCase=true, luceneMatchVersion=LUCENE_36}:

position    1   2   3
term text   quiero  una blackberry
type    <ALPHANUM>  <ALPHANUM>  SYNONYM
startOffset 0   7   11
endOffset   6   10  22

However, if I try this sentence at a "real" query, the request handler (an evolution of the edismax handler), the tokens "black" and "berry" were not replaced by "blackberry".

I've seen here that you can solve this situation by modifying the FieldQParser plugin.

Anyway, since such post was made almost 3 years ago, I'd like to know if there's some way of solving this problem inside Solr, avoiding having to expand some plugin.

Thanks.

Body:
In Solr-6.5.0 you can enables query-time multi-term synonyms by setting below parameter

From Documentation

The sow Parameter
 Split on whitespace: if set to false,
  whitespace-separated term sequences will be provided to text analysis
  in one shot, enabling proper function of analysis filters that operate
  over term sequences, e.g. multi-word synonyms and shingles. Defaults
  to true: text analysis is invoked separately for each individual
  whitespace-separated term.

[synonym.txt]

black berry => blackberry

[Example]

q=black berry
&sow=false
&debug=query

[Debug-Response]

<lst name="debug">
<str name="rawquerystring">black berry</str>
<str name="querystring">black berry</str>
<str name="parsedquery">_text_:blackberry</str>
<str name="parsedquery_toString">_text_:blackberry</str>
<str name="QParser">LuceneQParser</str>
</lst>

Now you can see from debug response that I have searched for black berry, but synonym filter factory maps to the word that I have mentioned in synonym.txt.


问:
Retrieve characters after nth occurrence of an another with Regex
I'm writing a simple bot that broadcasts messages to clients based on messages from a server. This will be done in JavaScript but I am trying to understand Regex. I've been Googling for the past hour and I've come so close but I am simply unable to solve this one.

Basically I need to retrieve everything between the second / and the first [. It sounds really simple but I cannot figure out how to do this.

Here's some sample code:

```<code>192.168.1.1:33291/76561198014386231/testName joined [linux/76561198014386231]
</code>```

Here's the Regex I've come up with:

```<code>\/(.*?)\[
</code>```

I've found lots of similar questions here on StackOverflow but most of them seem specific to a particular language or end up being too complex and I'm unable to whittle down the query.

I know this is a simple one, but I am totally stumped.

答:
Instead of .*?. Then you could match everything but a forward slash by doing [^\/]*.

```<code>([^\/]*)\s*\[
</code>```

Live preview

If it needs to be after the second slash. As in the contents between the second slash and the square bracket can contain slashes. Then you could do:

```<code>(?:.*?\/){2}(.*)\s*\[
</code>```

Live preview

Remove the \s* if you want to. I'm just assuming you don't care about that whitespace.

Body:
I'm writing a simple bot that broadcasts messages to clients based on messages from a server. This will be done in JavaScript but I am trying to understand Regex. I've been Googling for the past hour and I've come so close but I am simply unable to solve this one.

Basically I need to retrieve everything between the second / and the first [. It sounds really simple but I cannot figure out how to do this.

Here's some sample code:

192.168.1.1:33291/76561198014386231/testName joined [linux/76561198014386231]

Here's the Regex I've come up with:

\/(.*?)\[

I've found lots of similar questions here on StackOverflow but most of them seem specific to a particular language or end up being too complex and I'm unable to whittle down the query.

I know this is a simple one, but I am totally stumped.

Body:
Instead of .*?. Then you could match everything but a forward slash by doing [^\/]*.

([^\/]*)\s*\[

Live preview

If it needs to be after the second slash. As in the contents between the second slash and the square bracket can contain slashes. Then you could do:

(?:.*?\/){2}(.*)\s*\[

Live preview

Remove the \s* if you want to. I'm just assuming you don't care about that whitespace.