问:
how to extract the specific word from a string?
I have a file with multiple lines and want to extract the first three words of every line.

```<code>str = []

str = [
Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web1 journal: afg-prod-web1 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"]
</code>```

I want to extract the date ie.  Feb 17 07:10:07 from every line and put that in an array.

I tried applying a for loop but it gives error:

```<code>IndexError: list index out of range
</code>```

Code I tried :

```<code>for i in splitdata:
            abc  = splitdata[logcount]
            aa = abc.split()
            if(aa[0] == "Feb"):
                aaa = "".join([aa[0],' ',aa[1],' ',aa[2]])
                logtime.append(aaa)
                logcount += 2
            else:
                pass
        print logtime
</code>```

答:
You just check the len(splitted string) to avoid such error. There is lot of scope in improving your code.

Use method that can be reused

check the len of list before accessing by index

You dont need to have brackets for if condition in python

Use list comprehension in a smart way

Code you have used to join list shows you need to learn a lot in python. Best of luck!

In [1]: sample_text = """Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A
   ...:  \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime
   ...: -ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \
   ...: x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242a
   ...: c110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A
   ...: {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-A
   ...: CTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A
   ...: \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A
   ...:         }\x0A    ]\x0A}"""

In [2]: def get_time_from_log(log_text):
   ...:     log_text_split = log_text.split(" ")
   ...:     if len(log_text_split) < 3:
   ...:         pass
   ...:     elif log_text_split[0] == "Feb":
   ...:         return " ".join(log_text_split[0:3])
   ...:

In [3]: get_time_from_log(sample_text)
Out[3]: 'Feb 17 07:10:07'
```

Body:
I have a file with multiple lines and want to extract the first three words of every line.

str = []

str = [
Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web2 journal: afg-prod-web2 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"

Feb 17 07:10:07 afg-prod-web1 journal: afg-prod-web1 statistics: 192.168.28.12 - 200 - "{\x0A    \x22identifier\x22: {\x0A        \x22company_code\x22: \x22TSC\x22,\x0A        \x22product_type\x22: \x22airtime-ctg\x22,\x0A        \x22host_type\x22: \x22android\x22\x0A    },\x0A    \x22id\x22: {\x0A        \x22type\x22: \x22guest\x22,\x0A        \x22group\x22: \x22guest\x22,\x0A        \x22uuid\x22: \x22fd2dfcdc-ade2-11e6-8404-0242ac110003\x22,\x0A        \x22device_id\x22: \x222f504f5ed3c64934\x22\x0A    },\x0A    \x22stats\x22: [\x0A        {\x0A            \x22timestamp\x22: \x222017-02-16T23:29:57+0000\x22,\x0A            \x22software_id\x22: \x22A-ACTG\x22,\x0A            \x22action_id\x22: \x22open_app\x22,\x0A            \x22values\x22: {\x0A                \x22device_id\x22: \x222f504f5ed3c64934\x22,\x0A                \x22language\x22: \x22en\x22\x0A            }\x0A        }\x0A    ]\x0A}"]

I want to extract the date ie.  Feb 17 07:10:07 from every line and put that in an array.

I tried applying a for loop but it gives error:

IndexError: list index out of range

Code I tried :

for i in splitdata:
            abc  = splitdata[logcount]
            aa = abc.split()
            if(aa[0] == "Feb"):
                aaa = "".join([aa[0],' ',aa[1],' ',aa[2]])
                logtime.append(aaa)
                logcount += 2
            else:
                pass
        print logtime


来源: stackexchange

问:
Score corruption with DRL Score rule with HardSoftDoubleScore in OptaPlanner
Hellow.

I try to solve some optimization problem using optaplanner, some error is happened.

Version: Optaplanner 6.5.1 - Snapshot

Score Type: Hard Soft Double Score

Score Method: DRL

```<code>rule "Insert count collections per manager in same grade"
    salience 10
    when
        $gradeClass: GradeInfo($grade: grade)
        $managerClass: ManagerInfo()
        accumulate(
            CollectionInfo(
                manager == $managerClass,
                $recoveryGrade: recoveryGrade == $grade),
            $count : count($recoveryGrade))
    then
        insertLogical(new GradeStatic($gradeClass, $managerClass, $count.longValue()));
end

rule "Insert Compare total Receivables for each group"
    salience 10
    when
        $groupClass: GroupInfo($groupId: groupId)
        $managerClass: ManagerInfo($managerName: name, groupId == $groupId)
        accumulate(
            CollectionInfo(
                manager == $managerClass,
                $receivables : receivables),
            $sum : sum($receivables))
    then
        insertLogical(new GroupStatic($groupClass, $managerClass, $sum.doubleValue()));
end

// Hard constraints
rule "Hard Score 1 Weight And Receivables"
    when
        GroupStatic($highReceivable: totalReceivables, $weight: groupInfo.weight)
        GroupStatic(groupInfo.weight < $weight, $lowReceivable: totalReceivables)
        eval($highReceivable < $lowReceivable)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -$lowReceivable);
end

rule "Hard Score 2-3 There is a manager who is not arranged collecion"
    when
        accumulate(
            GradeStatic(
                $arrangedManagerName: managerInfo.name),
            $arrangedManagerCnt : count($arrangedManagerName))
        accumulate(
            ManagerInfo($managerName: name),
            $managerCnt : count($managerName))
        accumulate(
            GradeInfo($grade: grade),
            $gradeCnt : count($grade))
        eval($arrangedManagerCnt < $managerCnt * $gradeCnt)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -99999999.0);
end

// Soft constraints
rule "Calculate Soft Score"
    when
        GroupStatic($totalReceivables: totalReceivables, $weight: groupInfo.weight)
        accumulate(
            CollectionInfo(
                $receivables: receivables),
            $average: average($receivables))
    then
        System.out.println("Soft Score: "+ Math.abs($average.doubleValue() - ($totalReceivables / $weight))/1000000.0);
        scoreHolder.addSoftConstraintMatch(kcontext, -(Math.abs($average.doubleValue() - ($totalReceivables / $weight)))/1000000.0);
end
</code>```

Here is my Class Diagram

ClassDiagram

With above Setting, In Construction Heuristic Step, below error is happened

```<code>2017-03-30 17:59:44,853 [main] DEBUG     CH step (2), time spent (246), score (0.0hard/-34.78590672782874soft), selected move count (1), picked move (CollectionInfo-72 {null -> ManagerInfo-0}).
Soft Score: 4.969724770642201
...
Soft Score: 4.969724770642201
Soft Score: 4.966641437308868
Soft Score: 4.969724770642201
...
Soft Score: 4.969724770642201
Soft Score: 4.967558103975534
Soft Score: 4.969724770642201
...
Soft Score: 4.969724770642201
Soft Score: 4.967558103975534
Exception in thread "main" java.lang.IllegalStateException: Score corruption: the workingScore (0.0hard/-34.78590672782873soft) is not the uncorruptedScore (0.0hard/-34.785906727828745soft) after completedAction (Undo(CollectionInfo-39 {null -> ManagerInfo-0})):
  The corrupted scoreDirector has no ConstraintMatch(s) which are in excess.
  The corrupted scoreDirector has no ConstraintMatch(s) which are missing.
  The corrupted scoreDirector has no ConstraintMatch(s) in excess or missing. That could be a bug in this class (class org.optaplanner.core.impl.score.director.drools.DroolsScoreDirector).
  Check your score constraints.
    at org.optaplanner.core.impl.score.director.AbstractScoreDirector.assertWorkingScoreFromScratch(AbstractScoreDirector.java:378)
    at org.optaplanner.core.impl.phase.scope.AbstractPhaseScope.assertExpectedUndoMoveScore(AbstractPhaseScope.java:142)
    at org.optaplanner.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider.doMove(ConstructionHeuristicDecider.java:124)
    at org.optaplanner.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider.decideNextStep(ConstructionHeuristicDecider.java:93)
    at org.optaplanner.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase.solve(DefaultConstructionHeuristicPhase.java:72)
    at org.optaplanner.core.impl.solver.DefaultSolver.runPhases(DefaultSolver.java:215)
    at org.optaplanner.core.impl.solver.DefaultSolver.solve(DefaultSolver.java:176)
    at org.optaplanner.examples.collectionarrange2.app.CollectionArrangeHelloWorld.main(CollectionArrangeHelloWorld.java:51)
</code>```

Where is my correction point?

Please help me~~^^

答:
What's the difference between these two?

0.0hard/-34.78590672782873soft

0.0hard/-34.785906727828745soft

Answer: a rounding error due to floating point arithmetic.

Javadocs of HardSoftDoubleScore:

WARNING: NOT RECOMMENDED TO USE DUE TO ROUNDING ERRORS THAT CAUSE
  SCORE CORRUPTION. For example, this prints false:
  System.out.println((0.01 + 0.05) == (0.01 + 0.02 + 0.03));

See the documentation section Avoid Floating Point Numbers in Score Calculation on how to work around that.

ContentLicense: CC BY-SA 3.0

Body:
Hellow.

I try to solve some optimization problem using optaplanner, some error is happened.

Version: Optaplanner 6.5.1 - Snapshot

Score Type: Hard Soft Double Score

Score Method: DRL

rule "Insert count collections per manager in same grade"
    salience 10
    when
        $gradeClass: GradeInfo($grade: grade)
        $managerClass: ManagerInfo()
        accumulate(
            CollectionInfo(
                manager == $managerClass,
                $recoveryGrade: recoveryGrade == $grade),
            $count : count($recoveryGrade))
    then
        insertLogical(new GradeStatic($gradeClass, $managerClass, $count.longValue()));
end

rule "Insert Compare total Receivables for each group"
    salience 10
    when
        $groupClass: GroupInfo($groupId: groupId)
        $managerClass: ManagerInfo($managerName: name, groupId == $groupId)
        accumulate(
            CollectionInfo(
                manager == $managerClass,
                $receivables : receivables),
            $sum : sum($receivables))
    then
        insertLogical(new GroupStatic($groupClass, $managerClass, $sum.doubleValue()));
end

// Hard constraints
rule "Hard Score 1 Weight And Receivables"
    when
        GroupStatic($highReceivable: totalReceivables, $weight: groupInfo.weight)
        GroupStatic(groupInfo.weight < $weight, $lowReceivable: totalReceivables)
        eval($highReceivable < $lowReceivable)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -$lowReceivable);
end

rule "Hard Score 2-3 There is a manager who is not arranged collecion"
    when
        accumulate(
            GradeStatic(
                $arrangedManagerName: managerInfo.name),
            $arrangedManagerCnt : count($arrangedManagerName))
        accumulate(
            ManagerInfo($managerName: name),
            $managerCnt : count($managerName))
        accumulate(
            GradeInfo($grade: grade),
            $gradeCnt : count($grade))
        eval($arrangedManagerCnt < $managerCnt * $gradeCnt)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -99999999.0);
end

// Soft constraints
rule "Calculate Soft Score"
    when
        GroupStatic($totalReceivables: totalReceivables, $weight: groupInfo.weight)
        accumulate(
            CollectionInfo(
                $receivables: receivables),
            $average: average($receivables))
    then
        System.out.println("Soft Score: "+ Math.abs($average.doubleValue() - ($totalReceivables / $weight))/1000000.0);
        scoreHolder.addSoftConstraintMatch(kcontext, -(Math.abs($average.doubleValue() - ($totalReceivables / $weight)))/1000000.0);
end

Here is my Class Diagram

ClassDiagram

With above Setting, In Construction Heuristic Step, below error is happened

2017-03-30 17:59:44,853 [main] DEBUG     CH step (2), time spent (246), score (0.0hard/-34.78590672782874soft), selected move count (1), picked move (CollectionInfo-72 {null -> ManagerInfo-0}).
Soft Score: 4.969724770642201
...
Soft Score: 4.969724770642201
Soft Score: 4.966641437308868
Soft Score: 4.969724770642201
...
Soft Score: 4.969724770642201
Soft Score: 4.967558103975534
Soft Score: 4.969724770642201
...
Soft Score: 4.969724770642201
Soft Score: 4.967558103975534
Exception in thread "main" java.lang.IllegalStateException: Score corruption: the workingScore (0.0hard/-34.78590672782873soft) is not the uncorruptedScore (0.0hard/-34.785906727828745soft) after completedAction (Undo(CollectionInfo-39 {null -> ManagerInfo-0})):
  The corrupted scoreDirector has no ConstraintMatch(s) which are in excess.
  The corrupted scoreDirector has no ConstraintMatch(s) which are missing.
  The corrupted scoreDirector has no ConstraintMatch(s) in excess or missing. That could be a bug in this class (class org.optaplanner.core.impl.score.director.drools.DroolsScoreDirector).
  Check your score constraints.
    at org.optaplanner.core.impl.score.director.AbstractScoreDirector.assertWorkingScoreFromScratch(AbstractScoreDirector.java:378)
    at org.optaplanner.core.impl.phase.scope.AbstractPhaseScope.assertExpectedUndoMoveScore(AbstractPhaseScope.java:142)
    at org.optaplanner.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider.doMove(ConstructionHeuristicDecider.java:124)
    at org.optaplanner.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider.decideNextStep(ConstructionHeuristicDecider.java:93)
    at org.optaplanner.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase.solve(DefaultConstructionHeuristicPhase.java:72)
    at org.optaplanner.core.impl.solver.DefaultSolver.runPhases(DefaultSolver.java:215)
    at org.optaplanner.core.impl.solver.DefaultSolver.solve(DefaultSolver.java:176)
    at org.optaplanner.examples.collectionarrange2.app.CollectionArrangeHelloWorld.main(CollectionArrangeHelloWorld.java:51)

Where is my correction point?

Please help me~~^^


问:
Gradle 3.3 Error Need Java 7 or Later Unsolved
i just imported some project that i bought from my friend.
Once i import it to Android Studio 2.1.2 i just get this messages
"Error:Gradle 3.3 requires Java 7 or later to run. You are currently using Java 6."

I have install Java 7 and 8 in my mac. I have change the directory in Default Project Structure, but still that messages always appear and i can't do anything with the code.

Please master, help me.

答:
Use this path in the Default Project Structure by using the browse option go up to this Directory named home.

/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home

May it works for you.


问:
How do I access textField Value, which is created dynamically in Objective C using for loop?
I have created 4 UITextField using for loop in Objective C. Now I want to validate those text. whether those text field is empty or not.

```<code> for(int i=0;i<4; i++){

            UITextField   *textField = [[UITextField alloc] initWithFrame:CGRectMake(x, y, 211, 39)];
            UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
            [textField setTag:i];
            textField.leftView = paddingView;
            textField.leftViewMode = UITextFieldViewModeAlways;
            textField.backgroundColor = [UIColor colorWithRed:237.0/255.0 green:237.0/255.0 blue:237.0/255.0 alpha:1.0];
            textField.font = [UIFont systemFontOfSize:15];
            textField.placeholder = [placeholder objectAtIndex:i];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.keyboardType = UIKeyboardTypeDefault;
            textField.returnKeyType = UIReturnKeyDone;
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            if(i>=2){
                [textField setSecureTextEntry:YES];
            }
             [self.view addSubview:textField];
            y=y+69;
}
</code>```

答:
```<code>for(int i=0;i<4; i++) {
    UITextField   *textField = [self.view viewWithTag:i];
    if (textField.hasText) {
        //If this returns true then text field has text otherwise not
    }
}
</code>```

This will automatically manage whitespaces.

Body:
I have created 4 UITextField using for loop in Objective C. Now I want to validate those text. whether those text field is empty or not.

 for(int i=0;i<4; i++){

            UITextField   *textField = [[UITextField alloc] initWithFrame:CGRectMake(x, y, 211, 39)];
            UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
            [textField setTag:i];
            textField.leftView = paddingView;
            textField.leftViewMode = UITextFieldViewModeAlways;
            textField.backgroundColor = [UIColor colorWithRed:237.0/255.0 green:237.0/255.0 blue:237.0/255.0 alpha:1.0];
            textField.font = [UIFont systemFontOfSize:15];
            textField.placeholder = [placeholder objectAtIndex:i];
            textField.autocorrectionType = UITextAutocorrectionTypeNo;
            textField.keyboardType = UIKeyboardTypeDefault;
            textField.returnKeyType = UIReturnKeyDone;
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            if(i>=2){
                [textField setSecureTextEntry:YES];
            }
             [self.view addSubview:textField];
            y=y+69;
}

Body:
for(int i=0;i<4; i++) {
    UITextField   *textField = [self.view viewWithTag:i];
    if (textField.hasText) {
        //If this returns true then text field has text otherwise not
    }
}

This will automatically manage whitespaces.


问:
How to get the last x lines of a string in Java?
I get some result from an external command (semi-api) and want to parse the result.
I'm only interested in the last few lines of the result.

How can get the last x lines of a string in Java?

答:
A solution that gives the result without parsing the whole string:

```<code>/**
 * Created by alik on 3/31/17.
 */
public class Main {

    // TODO: Support other EndOfLines, like "\r\n".
    // One way is to just replace all "\r\n" with "\n" and then run the @getLastLines method.
    public static List<String> getLastLines(String string, int numLines) {
        List<String> lines = new ArrayList<>();
        int currentEndOfLine = string.length();
        if (string.endsWith("\n")) {
            currentEndOfLine = currentEndOfLine - "\n".length();
        }
        for (int i = 0; i < numLines; ++i) {
            int lastEndOfLine = currentEndOfLine;
            currentEndOfLine = string.lastIndexOf("\n", lastEndOfLine - 1);
            String lastLine = string.substring(currentEndOfLine + 1, lastEndOfLine);
            lines.add(0, lastLine);
        }
        return lines;
    }

    @Test
    public void test1() {
        String text = "111\n" +
                "222\n" +
                "333\n" +
                "444\n" +
                "555\n" +
                "666\n" +
                "777\n";
        List<String> lastLines = getLastLines(text, 4);
        Assert.assertEquals("777", lastLines.get(lastLines.size() - 1));
        Assert.assertEquals(4, lastLines.size());
    }

    @Test
    public void test2() {
        String text = "111\n" +
                "222\n" +
                "333\n" +
                "444\n" +
                "555\n" +
                "666\n" +
                "777";
        List<String> lastLines = getLastLines(text, 4);
        Assert.assertEquals("777", lastLines.get(lastLines.size() - 1));
        Assert.assertEquals(4, lastLines.size());
    }
}
</code>```

* Link to github gist

Body:
A solution that gives the result without parsing the whole string:

/**
 * Created by alik on 3/31/17.
 */
public class Main {

    // TODO: Support other EndOfLines, like "\r\n".
    // One way is to just replace all "\r\n" with "\n" and then run the @getLastLines method.
    public static List<String> getLastLines(String string, int numLines) {
        List<String> lines = new ArrayList<>();
        int currentEndOfLine = string.length();
        if (string.endsWith("\n")) {
            currentEndOfLine = currentEndOfLine - "\n".length();
        }
        for (int i = 0; i < numLines; ++i) {
            int lastEndOfLine = currentEndOfLine;
            currentEndOfLine = string.lastIndexOf("\n", lastEndOfLine - 1);
            String lastLine = string.substring(currentEndOfLine + 1, lastEndOfLine);
            lines.add(0, lastLine);
        }
        return lines;
    }

    @Test
    public void test1() {
        String text = "111\n" +
                "222\n" +
                "333\n" +
                "444\n" +
                "555\n" +
                "666\n" +
                "777\n";
        List<String> lastLines = getLastLines(text, 4);
        Assert.assertEquals("777", lastLines.get(lastLines.size() - 1));
        Assert.assertEquals(4, lastLines.size());
    }

    @Test
    public void test2() {
        String text = "111\n" +
                "222\n" +
                "333\n" +
                "444\n" +
                "555\n" +
                "666\n" +
                "777";
        List<String> lastLines = getLastLines(text, 4);
        Assert.assertEquals("777", lastLines.get(lastLines.size() - 1));
        Assert.assertEquals(4, lastLines.size());
    }
}

* Link to github gist


问:
FCM - Setting badge in onMessageReceived
I have an Android application, where I'm using some method to show notification number on app icon. Now I want to set that number when notification is received.

I thought that I should set the number when notification received so I set it inside onMessageReceived method. But, my problem is when my app is in background, onMessageReceived method not called, so the notification number isn't set.

Following is my code. I set the number inside onMessageReceived. I already tested setBadge method and can verify that it is working. The problem is onMessageReceived is not called so setBadge is also not called, which doesn't set the number.

```<code>@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    // TODO(developer): Handle FCM messages here.
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Conts.notificationCounter ++;
    //I am setting in here.
    setBadge(getApplicationContext(),Conts.notificationCounter  );
    Log.e("notificationNUmber",":"+ Conts.notificationCounter);

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]

public static void setBadge(Context context, int count) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
        Log.e("classname","null");
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", context.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    context.sendBroadcast(intent);
}

public static String getLauncherClassName(Context context) {

    PackageManager pm = context.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}
</code>```

When I searched this issue, I found that if the coming message is display message then onMessageReceived is called only if app is foreground. But if coming message is data message then onMessageReceived is called even if the app is background.

But my friend told me who is sending the notification(server side), the message already goes as both display and data message. He said that data object is filled.

Following is the JSON for coming message, it has data object.

```<code>{
   "to":"my_device_id",
   "priority":"high",

   "notification":{
      "body":"Notification Body",
      "title":"Notification Title",
      "icon":"myicon",
      "sound":"default"
   },

   "data":{
      "Nick":"DataNick",
      "Room":"DataRoom"
   }
}
</code>```

If I only use data object, onMessageReceived is called as they said but that time notification does not appear at the top.

Now why onMessageReceived is not called if the message is also data message. Should I do something different to handle data message? Is it working same with display messaging in client side.

Any help would be appreciated. Thanks in advance.

答:
To do stuff when receiving Notification-payloads in the background, just override zzE in FirebaseMessagingService. The method name might change between versions, just type @Override into the class and see what it suggests for you. In my case, I found zzD and zzE, and by trying them out I noticed that zzE has the data I wanted. zzD had some wakelock-stuff in its extras. The return value of zzE basically indicates whether the notification was handled, so if you return true, the OS won't show the notification. I prefer to return super.zzE(intent) after I've done my things, to let the OS handle the notification.

Updating the badge will only work on launchers supported by ShortcutBadger though. You can do pretty much whatever you want instead, though.

Here's my code (my notifications contain "badge" in the data payload):

```<code>public class PushNotificationService extends FirebaseMessagingService
{
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage)
    {
        // This is called when the app is in the foreground
        // Show a custom notification or send a broadcast to update the UI here
    }

    @Override
    public boolean zzE(Intent intent)
    {
        if(intent.hasExtra("badge"))
        {
            try
            {
                ShortcutBadger.applyCount(getApplicationContext(), Integer.parseInt(intent.getStringExtra("badge"));
            }
            catch (Exception e)
            {
                Log.e("failedToParse", "Badge!?");
            }
        }
        // pass the intent through to the non-overriden zzE
        // to show the default notification.
        return super.zzE(intent);

        // You could also show a custom notification here
        // and return true instead of this if you
        // don't want the default notifications.
    }

}
</code>```

Body:
I have an Android application, where I'm using some method to show notification number on app icon. Now I want to set that number when notification is received.

I thought that I should set the number when notification received so I set it inside onMessageReceived method. But, my problem is when my app is in background, onMessageReceived method not called, so the notification number isn't set.

Following is my code. I set the number inside onMessageReceived. I already tested setBadge method and can verify that it is working. The problem is onMessageReceived is not called so setBadge is also not called, which doesn't set the number.

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    // TODO(developer): Handle FCM messages here.
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Conts.notificationCounter ++;
    //I am setting in here.
    setBadge(getApplicationContext(),Conts.notificationCounter  );
    Log.e("notificationNUmber",":"+ Conts.notificationCounter);

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]

public static void setBadge(Context context, int count) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
        Log.e("classname","null");
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", context.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    context.sendBroadcast(intent);
}

public static String getLauncherClassName(Context context) {

    PackageManager pm = context.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}

When I searched this issue, I found that if the coming message is display message then onMessageReceived is called only if app is foreground. But if coming message is data message then onMessageReceived is called even if the app is background.

But my friend told me who is sending the notification(server side), the message already goes as both display and data message. He said that data object is filled.

Following is the JSON for coming message, it has data object.

{
   "to":"my_device_id",
   "priority":"high",

   "notification":{
      "body":"Notification Body",
      "title":"Notification Title",
      "icon":"myicon",
      "sound":"default"
   },

   "data":{
      "Nick":"DataNick",
      "Room":"DataRoom"
   }
}

If I only use data object, onMessageReceived is called as they said but that time notification does not appear at the top.

Now why onMessageReceived is not called if the message is also data message. Should I do something different to handle data message? Is it working same with display messaging in client side.

Any help would be appreciated. Thanks in advance.

Body:
To do stuff when receiving Notification-payloads in the background, just override zzE in FirebaseMessagingService. The method name might change between versions, just type @Override into the class and see what it suggests for you. In my case, I found zzD and zzE, and by trying them out I noticed that zzE has the data I wanted. zzD had some wakelock-stuff in its extras. The return value of zzE basically indicates whether the notification was handled, so if you return true, the OS won't show the notification. I prefer to return super.zzE(intent) after I've done my things, to let the OS handle the notification.

Updating the badge will only work on launchers supported by ShortcutBadger though. You can do pretty much whatever you want instead, though.

Here's my code (my notifications contain "badge" in the data payload):

public class PushNotificationService extends FirebaseMessagingService
{
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage)
    {
        // This is called when the app is in the foreground
        // Show a custom notification or send a broadcast to update the UI here
    }

    @Override
    public boolean zzE(Intent intent)
    {
        if(intent.hasExtra("badge"))
        {
            try
            {
                ShortcutBadger.applyCount(getApplicationContext(), Integer.parseInt(intent.getStringExtra("badge"));
            }
            catch (Exception e)
            {
                Log.e("failedToParse", "Badge!?");
            }
        }
        // pass the intent through to the non-overriden zzE
        // to show the default notification.
        return super.zzE(intent);

        // You could also show a custom notification here
        // and return true instead of this if you
        // don't want the default notifications.
    }

}


问:
Align button to the left side near ChartContainer default Icons
I have button (called BUTTON LEFT) in the sap.suite.ui.commons.ChartContainer:

```<code><ChartContainer
    id="chartContainer"
    showFullScreen="true"
    autoAdjustHeight="true">

    <dimensionSelectors>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:Button id="idButton" text="BUTTON LEFT"/>
    </dimensionSelectors>

    <content>
        <ChartContainerContent
            icon = "sap-icon://line-chart"
            title = "Line Chart">

            <content>
                <viz:VizFrame id="chartContainerVizFrame" height="700px" width="100%" uiConfig="{applicationSet:'fiori'}"></viz:VizFrame>
            </content>
        </ChartContainerContent>
    </content>
</ChartContainer>
</code>```

I need to align this button to the left side near ChartContainer legend icon. Now it looks like:

But I would like to get something like this:

Here is working example, feel free to edit it.

I am looking for the solution which will be inside in the sap.suite.ui.commons.ChartContainer. I do not want to use css for this if possible. Also I can not use width property of ToolbalSpacer (e.g. width="100px"), because I need ToolbalSpacer changing width when the screen resolution is changed. I know that I can change ToolbarSpacer according to screen resolution but I would like to not use this approach.

Thanks for any hint.

答:
The ChartContainer control adds a ToolbarSpacer before the Chart controls(Personalization, Zoom, Fullscreen ..). This ToolbarSpacer comes between the Chart controls & the dimension Selectors. If you hide this spacer you could align you Button control next to the other control. Here is one way to do it

```<code>onAfterRendering : function() {
  oChart = this.getView().byId("chartContainer");
  oChart.getToolbar().getContent()[2].setVisible(false);
}
</code>```

Since you have one Toolbarspacer & a Button, the additional Spacer will be the third control in the ToolBar content.

Body:
I have button (called BUTTON LEFT) in the sap.suite.ui.commons.ChartContainer:

<ChartContainer
    id="chartContainer"
    showFullScreen="true"
    autoAdjustHeight="true">

    <dimensionSelectors>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:Button id="idButton" text="BUTTON LEFT"/>
    </dimensionSelectors>

    <content>
        <ChartContainerContent
            icon = "sap-icon://line-chart"
            title = "Line Chart">

            <content>
                <viz:VizFrame id="chartContainerVizFrame" height="700px" width="100%" uiConfig="{applicationSet:'fiori'}"></viz:VizFrame>
            </content>
        </ChartContainerContent>
    </content>
</ChartContainer>

I need to align this button to the left side near ChartContainer legend icon. Now it looks like:

But I would like to get something like this:

Here is working example, feel free to edit it.

I am looking for the solution which will be inside in the sap.suite.ui.commons.ChartContainer. I do not want to use css for this if possible. Also I can not use width property of ToolbalSpacer (e.g. width="100px"), because I need ToolbalSpacer changing width when the screen resolution is changed. I know that I can change ToolbarSpacer according to screen resolution but I would like to not use this approach.

Thanks for any hint.

Body:
The ChartContainer control adds a ToolbarSpacer before the Chart controls(Personalization, Zoom, Fullscreen ..). This ToolbarSpacer comes between the Chart controls & the dimension Selectors. If you hide this spacer you could align you Button control next to the other control. Here is one way to do it

onAfterRendering : function() {
  oChart = this.getView().byId("chartContainer");
  oChart.getToolbar().getContent()[2].setVisible(false);
}

Since you have one Toolbarspacer & a Button, the additional Spacer will be the third control in the ToolBar content.


问:
Can't clone gitlab repo via ssh on aws ec2
It seems that this problem is usual, but after a lot of searching, I didn't find any solutions.

I can't clone repositories on a gitlab instance hosted on aws ec2.

```<code>Clonage dans 'angular2'...
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

I tried to use a config file for my ssh without result.

Here is the output of ssh -vT command

```<code>OpenSSH_7.2p2 Ubuntu-4ubuntu2.1, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to gitlab.com [52.167.219.168] port 22.
debug1: Connection established.
debug1: identity file /home/chd/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
debug1: Remote protocol version 2.0, remote software version
OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH* compat 0x04000000
debug1: Authenticating to gitlab.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/chd/.ssh/known_hosts:3
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/chd/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/chd/.ssh/id_dsa
debug1: Trying private key: /home/chd/.ssh/id_ecdsa
debug1: Trying private key: /home/chd/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

I precise I don't have the hand on aws instance.

Thanks for helping.

答:
Your private key is not accepted by the server:

```<code>debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/chd/.ssh/id_rsa
debug1: Authentications that can continue: publickey
</code>```

Make sure the /home/chd/.ssh/id_rsa.pub is in the gitlab.com SSH keys.

Body:
It seems that this problem is usual, but after a lot of searching, I didn't find any solutions.

I can't clone repositories on a gitlab instance hosted on aws ec2.

Clonage dans 'angular2'...
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I tried to use a config file for my ssh without result.

Here is the output of ssh -vT command

OpenSSH_7.2p2 Ubuntu-4ubuntu2.1, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to gitlab.com [52.167.219.168] port 22.
debug1: Connection established.
debug1: identity file /home/chd/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/chd/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
debug1: Remote protocol version 2.0, remote software version
OpenSSH_7.2p2 Ubuntu-4ubuntu2.1
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.1 pat OpenSSH* compat 0x04000000
debug1: Authenticating to gitlab.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/chd/.ssh/known_hosts:3
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/chd/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/chd/.ssh/id_dsa
debug1: Trying private key: /home/chd/.ssh/id_ecdsa
debug1: Trying private key: /home/chd/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).

I precise I don't have the hand on aws instance.

Thanks for helping.

Body:
Your private key is not accepted by the server:

debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/chd/.ssh/id_rsa
debug1: Authentications that can continue: publickey

Make sure the /home/chd/.ssh/id_rsa.pub is in the gitlab.com SSH keys.


问:
Fatal error: Call to a member function prepare() on null
I'm getting this error and i can't find whats wrong.

I've read through the other posts about this error but none of them seemed to help.

Fatal error: Call to a member function prepare() on null on line 92

```<code>        <?php

  include 'config.php';

   $lengd = $_POST["lengd"];
      $height = $_POST["height"];
       $width = $_POST["width"];

     $min_lengd = $lengd * 0.9; $max_lengd = $lengd * 1.1;
              $min_height = $height * 0.9; $max_height= $height * 1.1;
                 $min_width = $width * 0.9; $max_width= $width * 1.1;

$sql = "SELECT lengd, height, width FROM filters;

      WHERE $lengd BETWEEN :min_lengd AND :max_lengd

        AND $height BETWEEN :min_height AND :max_height

            AND $width BETWEEN :min_width AND :max_width

             LIMIT 2";

            $params = [
            'min_lengd' => $min_lengd,
               'max_lengd' => $max_lengd,
                  'min_height' => $min_height,
                   'max_height' => $max_height,
                      'min_width' => $min_width,
                        'max_width' => $max_width, ];

  $stmt = $conn->prepare($sql);  // LINE 92
  $stmt->execute($params);

?>
</code>```

答: It looks like your $conn variable is not initilazied. I can't see in the code you've uploaded where you are initializing it..

Body:
I'm getting this error and i can't find whats wrong.

I've read through the other posts about this error but none of them seemed to help.

Fatal error: Call to a member function prepare() on null on line 92

        <?php

  include 'config.php';

   $lengd = $_POST["lengd"];
      $height = $_POST["height"];
       $width = $_POST["width"];

     $min_lengd = $lengd * 0.9; $max_lengd = $lengd * 1.1;
              $min_height = $height * 0.9; $max_height= $height * 1.1;
                 $min_width = $width * 0.9; $max_width= $width * 1.1;

$sql = "SELECT lengd, height, width FROM filters;

      WHERE $lengd BETWEEN :min_lengd AND :max_lengd

        AND $height BETWEEN :min_height AND :max_height

            AND $width BETWEEN :min_width AND :max_width

             LIMIT 2";

            $params = [
            'min_lengd' => $min_lengd,
               'max_lengd' => $max_lengd,
                  'min_height' => $min_height,
                   'max_height' => $max_height,
                      'min_width' => $min_width,
                        'max_width' => $max_width, ];

  $stmt = $conn->prepare($sql);  // LINE 92
  $stmt->execute($params);

?>

ContentLicense: CC BY-SA 4.0


问:
I have got an error On SQL query - PHP-SQLWarning: mssql_query(): message: Incorrect syntax near '='. (severity 15)
I am running this php code with sql query but it keeps showing this error and i couldn't find where the mistake is? Can you help please.THANKS IN ADVANCE

Warning: mssql_query(): message: Incorrect syntax near '='. (severity 15)

Warning: mssql_query(): General SQL Server error: Check messages from the SQL Server (severity 15)

Warning: mssql_query(): Query failed

I have this on my user.php

```<code>if(isset($_POST['refresh'])){
    $mssql_real = db_connect_real();
    $sql = "UPDATE TOP(1) click_users_phones SET pin_failed = 0, status = 1, pin_blocked_time = NULL WHERE phone_num = $phone_num";
    mssql_query($sql, $mssql_real);
}
</code>```

I have this on another php file

```<code><form action="user.php" method="post">
    <button class="#" name="refresh">Refresh</button>
</form>
</code>```

答:
update this statement

```<code>$sql = "UPDATE TOP(1) click_users_phones SET pin_failed = 0, status = 1, pin_blocked_time = NULL WHERE phone_num = $phone_num";
</code>```

to

```<code>$sql = "UPDATE TOP(1) click_users_phones SET pin_failed = 0, status = 1, pin_blocked_time = NULL WHERE phone_num =".$phone_num;
</code>```

Body:
I am running this php code with sql query but it keeps showing this error and i couldn't find where the mistake is? Can you help please.THANKS IN ADVANCE

Warning: mssql_query(): message: Incorrect syntax near '='. (severity 15)

Warning: mssql_query(): General SQL Server error: Check messages from the SQL Server (severity 15)

Warning: mssql_query(): Query failed

I have this on my user.php

if(isset($_POST['refresh'])){
    $mssql_real = db_connect_real();
    $sql = "UPDATE TOP(1) click_users_phones SET pin_failed = 0, status = 1, pin_blocked_time = NULL WHERE phone_num = $phone_num";
    mssql_query($sql, $mssql_real);
}

I have this on another php file

<form action="user.php" method="post">
    <button class="#" name="refresh">Refresh</button>
</form>

Body:
update this statement

$sql = "UPDATE TOP(1) click_users_phones SET pin_failed = 0, status = 1, pin_blocked_time = NULL WHERE phone_num = $phone_num";

to

$sql = "UPDATE TOP(1) click_users_phones SET pin_failed = 0, status = 1, pin_blocked_time = NULL WHERE phone_num =".$phone_num;


问:
Flattening arrays in CoffeeScript
How does one go about flattening a nested multidimension array in CoffeeScript?
I'd like to go from

```<code>A = [1, [1,2] , [1,[1,[1,2],3],2] , 3]
</code>```

to

```<code>B = [1, 1, 2, 1, 1, 1, 2, 3, 2, 3]
</code>```

Is there an efficient way of doing this without a loop?

What I have now is:

```<code>flatten = (array) ->
  flat = []
  for element in array
    if Array.isArray(element)
      flat = flat.concat flatten element
    else
      flat.push element
  flat
</code>```

答:
You can use reduce method to make recursive solution like following.

```<code>flat = (r, a) ->
  if (Array.isArray(a))
      return a.reduce(flat, r)

  r.push(a)
  return r

array = [1, [1,2] , [1,[1,[1,2,[10, 11, [23, 34, [100]]]],3],2] , 3]
console.log array.reduce(flat, []) # [ 1, 1, 2, 1, 1, 1, 2, 10, 11, 23, 34, 100, 3, 2, 3 ]
</code>```

I am not sure whether it is efficient or not, it just another way to solve your problem. Hope it will help someone.

Title: Flattening arrays in CoffeeScript

Body:
How does one go about flattening a nested multidimension array in CoffeeScript?
I'd like to go from

A = [1, [1,2] , [1,[1,[1,2],3],2] , 3]

to

B = [1, 1, 2, 1, 1, 1, 2, 3, 2, 3]

Is there an efficient way of doing this without a loop?

What I have now is:

flatten = (array) ->
  flat = []
  for element in array
    if Array.isArray(element)
      flat = flat.concat flatten element
    else
      flat.push element
  flat

Body:
You can use reduce method to make recursive solution like following.

flat = (r, a) ->
  if (Array.isArray(a))
      return a.reduce(flat, r)

  r.push(a)
  return r

array = [1, [1,2] , [1,[1,[1,2,[10, 11, [23, 34, [100]]]],3],2] , 3]
console.log array.reduce(flat, []) # [ 1, 1, 2, 1, 1, 1, 2, 10, 11, 23, 34, 100, 3, 2, 3 ]

I am not sure whether it is efficient or not, it just another way to solve your problem. Hope it will help someone.


问:
C# two classes one serilog file
I have a problem I have two classes and I want to write both classes into a Serilog file.

```<code>class Program
    {
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                    .WriteTo.RollingFile(logs\\log.txt)
                    .CreateLogger();
            Log.Information("TEST");
        }
    }
</code>```

```<code>public class data: IData
    {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.RollingFile(logs\\log.txt)
                .CreateLogger();
            Log.Information("_________________________________________________");
            Log.Information("I'm right now in the Class", DateTime.Now);
    }
</code>```

If I were to write this, I would create two log objects and the log information, would be written in different files.
So my question is how can I create only one log object that I can use in both classes and that the log information write in only one file.

答: There is no need to create new log file. This log file is already exists you can append it. </p>

Title: C# two classes one serilog file

Body:
I have a problem I have two classes and I want to write both classes into a Serilog file.

class Program
    {
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                    .WriteTo.RollingFile(logs\\log.txt)
                    .CreateLogger();
            Log.Information("TEST");
        }
    }

public class data: IData
    {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.RollingFile(logs\\log.txt)
                .CreateLogger();
            Log.Information("_________________________________________________");
            Log.Information("I'm right now in the Class", DateTime.Now);
    }

If I were to write this, I would create two log objects and the log information, would be written in different files.
So my question is how can I create only one log object that I can use in both classes and that the log information write in only one file.


问:
angularjs unit testing (cannot find propery of 'resolve' undefined angularjs testing)
I am trying to do unit test of my angular app with karma. I am getting some error. Am i missing something? A
This my controller

```<code>(function () {
"use strict"
angular
    .module("myApp")

.controller("userCtrl",['$scope', '$state', 'userService', 'appSettings','md5','currentUser','$rootScope',
    function ($scope, $state, userService, appSettings,md5,currentUser, $rootScope) {

    $scope.login = function() {
        $scope.loading = true;
        if($scope.password != null){
        var user ={
            username:$scope.username,
            password:md5.createHash($scope.password)
        }

            var getData = userService.login(user);
            getData.then(function (response) {
                console.log(response);
                $scope.loading = false;

                currentUser.setProfile(user.username, response.data.sessionId);

                $state.go('videos');
            }, function (response) {
                console.log(response.data);
            });
        }else{
            $scope.msg = "Password field is empty!"
        }
    }
 }])
}());
</code>```

This is my test codes

```<code>'use strict';

describe('userCtrl', function() {
  beforeEach(module('myApp'));
  var scope, userCtrl, apiService,q, deferred, currentUser;

describe('$scope.login', function(){
  beforeEach(function(){
        apiService = {
              login: function () {
                  deferred = q.defer();
                  return deferred.promise;
              };
            };
        });

beforeEach(inject(function($controller, $rootScope, $q, _currentUser_){
    var user ={name:'ali',password:'password'};
    scope = $rootScope.$new();
    q = $q;

    // The injector unwraps the underscores (_) from around the parameter names when matching
    userCtrl = $controller('userCtrl', {
        $scope:scope,
        userService:apiService
      });
    //userService = _userService_;
    currentUser = _currentUser_;
  }));

    it('should call user service login', function() {
      spyOn(apiService, 'login').and.callThrough();
      scope.login();
      deferred.resolve(user);

      expect(apiService.login).toHaveBeenCalled();
    });

    it('checks the password field', function() {
      scope.login();
      expect(scope.msg).toEqual('Password field is empty!');
    });

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

And i am getting this error
enter image description here

答:
If you have to test controller then use to spyon for service method and in case of service then use HttpBackend

```<code>    describe('Testing a Controller that uses a Promise', function() {
      var $scope;
      var $q;
      var deferred;

      beforeEach(module('search'));

      beforeEach(inject(function($controller, _$rootScope_, _$q_, searchService) {
        $q = _$q_;
        $scope = _$rootScope_.$new();

        // We use the $q service to create a mock instance of defer
        deferred = _$q_.defer();

        // Use a Jasmine Spy to return the deferred promise
        spyOn(searchService, 'search').and.returnValue(deferred.promise);

        // Init the controller, passing our spy service instance
        $controller('SearchController', {
          $scope: $scope,
          searchService: searchService
        });
      }));

      it('should resolve promise', function() {
        // Setup the data we wish to return for the .then function in the controller
        deferred.resolve([{
          id: 1
        }, {
          id: 2
        }]);

        // We have to call apply for this to work
        $scope.$apply();

        // Since we called apply, not we can perform our assertions
        expect($scope.results).not.toBe(undefined);
        expect($scope.error).toBe(undefined);
      });
    });
</code>```

This for same using spyon for service method then use $appy method to make it work.

Body:
I am trying to do unit test of my angular app with karma. I am getting some error. Am i missing something? A
This my controller

(function () {
"use strict"
angular
    .module("myApp")

.controller("userCtrl",['$scope', '$state', 'userService', 'appSettings','md5','currentUser','$rootScope',
    function ($scope, $state, userService, appSettings,md5,currentUser, $rootScope) {

    $scope.login = function() {
        $scope.loading = true;
        if($scope.password != null){
        var user ={
            username:$scope.username,
            password:md5.createHash($scope.password)
        }

            var getData = userService.login(user);
            getData.then(function (response) {
                console.log(response);
                $scope.loading = false;

                currentUser.setProfile(user.username, response.data.sessionId);

                $state.go('videos');
            }, function (response) {
                console.log(response.data);
            });
        }else{
            $scope.msg = "Password field is empty!"
        }
    }
 }])
}());

This is my test codes

'use strict';

describe('userCtrl', function() {
  beforeEach(module('myApp'));
  var scope, userCtrl, apiService,q, deferred, currentUser;

describe('$scope.login', function(){
  beforeEach(function(){
        apiService = {
              login: function () {
                  deferred = q.defer();
                  return deferred.promise;
              };
            };
        });

beforeEach(inject(function($controller, $rootScope, $q, _currentUser_){
    var user ={name:'ali',password:'password'};
    scope = $rootScope.$new();
    q = $q;

    // The injector unwraps the underscores (_) from around the parameter names when matching
    userCtrl = $controller('userCtrl', {
        $scope:scope,
        userService:apiService
      });
    //userService = _userService_;
    currentUser = _currentUser_;
  }));

    it('should call user service login', function() {
      spyOn(apiService, 'login').and.callThrough();
      scope.login();
      deferred.resolve(user);

      expect(apiService.login).toHaveBeenCalled();
    });

    it('checks the password field', function() {
      scope.login();
      expect(scope.msg).toEqual('Password field is empty!');
    });

});
});

And i am getting this error
enter image description here

Body:
If you have to test controller then use to spyon for service method and in case of service then use HttpBackend

    describe('Testing a Controller that uses a Promise', function() {
      var $scope;
      var $q;
      var deferred;

      beforeEach(module('search'));

      beforeEach(inject(function($controller, _$rootScope_, _$q_, searchService) {
        $q = _$q_;
        $scope = _$rootScope_.$new();

        // We use the $q service to create a mock instance of defer
        deferred = _$q_.defer();

        // Use a Jasmine Spy to return the deferred promise
        spyOn(searchService, 'search').and.returnValue(deferred.promise);

        // Init the controller, passing our spy service instance
        $controller('SearchController', {
          $scope: $scope,
          searchService: searchService
        });
      }));

      it('should resolve promise', function() {
        // Setup the data we wish to return for the .then function in the controller
        deferred.resolve([{
          id: 1
        }, {
          id: 2
        }]);

        // We have to call apply for this to work
        $scope.$apply();

        // Since we called apply, not we can perform our assertions
        expect($scope.results).not.toBe(undefined);
        expect($scope.error).toBe(undefined);
      });
    });

This for same using spyon for service method then use $appy method to make it work.


问:
gulp-npm-test running Jest tests (all passing), but claiming to fail
I've installed gulp-npm-test following their documentation, that is, in my gulp directory I've got a file test.js that looks like this:

```<code>var gulp = require('gulp')
require('gulp-npm-test')(gulp)

var gulp = require('gulp-npm-test')(gulp, {
  withoutNpmRun: false
})
</code>```

But when I run gulp test I get the output like the following:

```<code>[17:12:41] Using gulpfile ~/my-project/gulpfile.js
[17:12:41] Starting 'test'...

> my-project@0.0.1 test /Users/wogsland/my-project
> jest

 PASS  frontend/tests/components/atoms/InputText.test.js
 .
 .
 (many more Jest test passes, no fails)
 .
 .
 FAIL  gulp/tasks/test.js
  ● Test suite failed to run

    Your test suite must contain at least one test.

      at onResult (node_modules/jest/node_modules/jest-cli/build/TestRunner.js:192:18)

Test Suites: 1 failed, 135 passed, 136 total
Tests:       135 passed, 135 total
Snapshots:   209 passed, 209 total
Time:        92.237s
Ran all test suites.
npm ERR! Test failed.  See above for more details.
</code>```

What am I missing here? I've go a bunch of tests

答: Looks like the matcher that figures out which files are tests, matches everything that includes in the filename test.js. The default is [ '**/__tests__/**/*.js?(x)', '**/?(*.)(spec|test).js?(x)' ]. So either adapt this one, its testMatch in your jest settings. Or use testPathIgnorePatterns to exclude the /gulp folder.

Body:
I've installed gulp-npm-test following their documentation, that is, in my gulp directory I've got a file test.js that looks like this:

var gulp = require('gulp')
require('gulp-npm-test')(gulp)

var gulp = require('gulp-npm-test')(gulp, {
  withoutNpmRun: false
})

But when I run gulp test I get the output like the following:

[17:12:41] Using gulpfile ~/my-project/gulpfile.js
[17:12:41] Starting 'test'...

> my-project@0.0.1 test /Users/wogsland/my-project
> jest

 PASS  frontend/tests/components/atoms/InputText.test.js
 .
 .
 (many more Jest test passes, no fails)
 .
 .
 FAIL  gulp/tasks/test.js
  ● Test suite failed to run

    Your test suite must contain at least one test.

      at onResult (node_modules/jest/node_modules/jest-cli/build/TestRunner.js:192:18)

Test Suites: 1 failed, 135 passed, 136 total
Tests:       135 passed, 135 total
Snapshots:   209 passed, 209 total
Time:        92.237s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

What am I missing here? I've go a bunch of tests


问:
Paypal as payment gateway?
i have to choose between several payment gateways. I heard that PayPal is quite a mess and there were several fraud-issues? Does some of you have experiences with PayPal?

Thanks in advance

答:
Tronic,

Pay pal is a Secure Transaction payment gateway used globally. Transaction is secured by VeriSign Identity Protection. It means your information is secure when you are going for the transaction. Paypal is easy to use and integration with programming language is very easy. Paypal provide a sendbox account for test your code once developed. Make sure you have to follow the terms and conditions for transaction with paypal e.g. transfer limit etc. For detailed information of integration, payment methods and creating sand box account visit to PayPal Developer

ContentLicense: CC BY-SA 2.5

Title: Paypal as payment gateway?


问:
Read and save list of Object using list of interface

I have seen someone's code and unable to understand how it works.

As the code save List of object in list of Interfaces and can read it back.

Please explain how it works. And can we save Object in interface (where Object implements it). AFAIK interface doesn't have members. How this code save and retrieve please explain.

ContactBO implementing BusinessObject

```<code>public class ContactBO implements BusinessObject {

    private String id, fullName, department, ;

    public String getId() {
        return id;
    }

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

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public boolean isSection() {
        // TODO Auto-generated method stub
        return false;
    }

}
</code>```

Where BussinessObject

```<code>public interface BusinessObject {
    boolean isSection();
}
</code>```

Saving list of Contact code

```<code>List<ContactBO> contactList = new Gson().fromJson(jsonArray.toString(),
                new TypeToken<List<ContactBO>>() {}.getType());
        List<BusinessObject> list = new ArrayList<BusinessObject>();
        list.addAll(contactList);
</code>```

read List of ContactBO using List of Interface

```<code>List<ContactBO> contactListItems = (List<ContactBO>) (List<?>) result.list;//where list is public List<BusinessObject> list;
</code>```

答: When you cast an object of a class into an interface, which that class implements you can only access implemented method(s) that the interface has.</p>

Body:
I have seen someone's code and unable to understand how it works.

As the code save List of object in list of Interfaces and can read it back.

Please explain how it works. And can we save Object in interface (where Object implements it). AFAIK interface doesn't have members. How this code save and retrieve please explain.

ContactBO implementing BusinessObject

public class ContactBO implements BusinessObject {

    private String id, fullName, department, ;

    public String getId() {
        return id;
    }

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

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public boolean isSection() {
        // TODO Auto-generated method stub
        return false;
    }

}

Where BussinessObject

public interface BusinessObject {
    boolean isSection();
}

Saving list of Contact code

List<ContactBO> contactList = new Gson().fromJson(jsonArray.toString(),
                new TypeToken<List<ContactBO>>() {}.getType());
        List<BusinessObject> list = new ArrayList<BusinessObject>();
        list.addAll(contactList);

read List of ContactBO using List of Interface

List<ContactBO> contactListItems = (List<ContactBO>) (List<?>) result.list;//where list is public List<BusinessObject> list;


问:
Jquery custom trigger anchor tag
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html></code>```

答:
I have done some changes to Parvez Rahman's answer. You don't need to click internally on an element through javascript. I guess that's like an antipattern.

You could use bootstrap functionality to show the next tab with tab function instead of doing a click on the element.

$(function() {
  $("#nextBtn").click(function() {
    $('li.active').next().find('a').tab("show"); //show tab of the next li
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active">Home</li>
    <li>Menu 1</li>
    <li>Menu 2</li>
    <li>Menu 3</li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html></code>```

Title: Jquery custom trigger anchor tag

Body:
Hello every one I am creating custom multistep form but when I click on next button it can't trigger related  anchor tag ( auto click )

Please help me to resolve my issue

Thanks in Advance

$(function() {
  $("#nextBtn").click(function() {
    var $tabs = $("li");
    $tabs.each(function() {

      var activeTab = $(this).hasClass("active");
      if (activeTab == true) {
        //var activeAnch = $(this).children().attr("href");
        alert($(this).next('li').children().attr("href"));
        var nextId = $(this).next('li').children().attr("id");
        //$("#"+nextId).click();// trigger click to #menu 1
      }
    });
  });
});

<!DOCTYPE html>

  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Home

Menu 1

Menu 2

Menu 3

HOME

      Form 1

Menu 1

      Form 2

Menu 2

      Form 3

Menu 3

      Form 4

  <button id="nextBtn">Next</button>

Body:
I have done some changes to Parvez Rahman's answer. You don't need to click internally on an element through javascript. I guess that's like an antipattern.

You could use bootstrap functionality to show the next tab with tab function instead of doing a click on the element.

$(function() {
  $("#nextBtn").click(function() {
    $('li.active').next().find('a').tab("show"); //show tab of the next li
  });
});

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <ul class="nav nav-pills">
    <li class="active"><a data-toggle="pill" href="#home">Home</a></li>
    <li><a data-toggle="pill" href="#menu1">Menu 1</a></li>
    <li><a data-toggle="pill" href="#menu2">Menu 2</a></li>
    <li><a data-toggle="pill" href="#menu3">Menu 3</a></li>
  </ul>

  <div class="tab-content">
    <div id="home" class="tab-pane fade in active">
      <h3>HOME</h3>
      <span>Form 1</span>
    </div>
    <div id="menu1" class="tab-pane fade">
      <h3>Menu 1</h3>
      <span>Form 2</span>
    </div>
    <div id="menu2" class="tab-pane fade">
      <h3>Menu 2</h3>
      <span>Form 3</span>
    </div>
    <div id="menu3" class="tab-pane fade">
      <h3>Menu 3</h3>
      <span>Form 4</span>
    </div>
  </div>

  <button id="nextBtn">Next</button>

</body>

</html>


问:
Toggle accordion using button and if open, keep it open
My scope looks something like this

```<code>$scope.audit = [{
    "specification": "Test1",
    "username":"user1",
    "lastname":"lastname1"
},
{
    "specification": "Test1",
    "username":"user2",
    "lastname":"lastname2"
},
{
    "specification": "Test2",
    "username":"user1",
    "lastname":"lastname1"
},
{
    "specification": "Test2",
    "username":"user2"
    "lastname":"lastname2"
}]
</code>```

I groupBy specification and have two buttons as filters, username and lastname, which can be clicked to filter the data. The specification and the filters are part of accordion heading.

Now when I click on specification heading, the panel opens up well. But how do I open an accordion using filter buttons? And if the panel is open, how can I keep it open and not toggle the data?

HTML

```<code><div class="modal-body" style="max-width: 1600px; margin: 0 auto; overflow: hidden;">
    <accordion close-others=false>
        <accordion-group is-open="open" data-ng-repeat="(spec,value) in audit | orderBy: 'specification' | groupBy: 'specification'">
            <accordion-heading>
                <i class="glyphicon" ng-class="{'glyphicon-chevron-down': open, 'glyphicon-chevron-right': !open}"></i>
                <b>{{spec}}</b>

                <div class="btn-toolbar pull-right" ng-click="$event.stopPropagation();$event.preventDefault();" >
                    <div class="btn-group pull-right" >
                        <button data-style="slide-right" ng-click="Activate(this,'username')" type="button" class="btn btn-xs">
                            <i title="Filter" class="fa fa-filter" style="color:#006b24"></i>
                            Username
                        </button>
                    </div>

                    <div class="btn-group pull-right" >
                        <button data-style="slide-right" ng-click="Activate(this,'lastname')" type="button" class="btn btn-xs">
                            <i title="Filter" class="fa fa-filter" style="color:#006b24"></i>
                            Lastname
                        </button>
                    </div>
                </div>
            <accordion-heading>

            <div data-ng-repeat="val in value">
                {{val.username}} -- {{val.lastname}}
            </div>
        <accordion-group>
    <accordion>
</div>
</code>```

With my current approach on clicking the Activate(), I set the value of open to true, but this opens up all the accordions.

Javascript:

```<code>$scope.Activate = function(val,filter) {
    if (!$scope.open) {
        $scope.open = true;
    }
}
</code>```

答:
are you looking for something like this?

HTML Code

```<code><div class="modal-body" style="max-width: 1600px; margin: 0 auto; overflow: hidden;">
    <accordion close-others=false>
        <accordion-group is-open="open" data-ng-repeat="(spec,value) in audit | groupBy:'specification'">
            <accordion-heading class="col-lg-12">
                <i class="glyphicon" ng-class="{'glyphicon-chevron-down': open[$index], 'glyphicon-chevron-right': !open[$index]}"></i>
                <b ng-click="Activate($index)">{{spec}}</b>
                <div class="btn-toolbar pull-right" ng-click="$event.stopPropagation();$event.preventDefault();">
                    <div class="btn-group pull-right">
                        <button data-style="slide-right" ng-click="Activate($index)" type="button" class="btn btn-xs">
                            <i title="Filter" class="fa fa-filter" style="color:#006b24"></i>
                            Username
                        </button>
                    </div>

                    <div class="btn-group pull-right">
                        <button data-style="slide-right" ng-click="Activate($index)" type="button" class="btn btn-xs">
                            <i title="Filter" class="fa fa-filter" style="color:#006b24"></i>
                            Lastname
                        </button>
                    </div>
                </div>
            </accordion-heading>
            <div ng-show="open[$index]" ng-hide="!open[$index]">
                <span class="col-lg-12" data-ng-repeat="val in value">{{val.username}} -- {{val.lastname}}</span>
            </div>
        </accordion-group>
    </accordion>
</div>
</code>```

JavaScript

```<code>$scope.open = [];
$scope.Activate = function (ind) {

    if (!$scope.open[ind]) {
        $scope.open[ind] = true;
    }
    else
    {
        $scope.open[ind] = false;
    }
}
</code>```

Body:
My scope looks something like this

$scope.audit = [{
    "specification": "Test1",
    "username":"user1",
    "lastname":"lastname1"
},
{
    "specification": "Test1",
    "username":"user2",
    "lastname":"lastname2"
},
{
    "specification": "Test2",
    "username":"user1",
    "lastname":"lastname1"
},
{
    "specification": "Test2",
    "username":"user2"
    "lastname":"lastname2"
}]

I groupBy specification and have two buttons as filters, username and lastname, which can be clicked to filter the data. The specification and the filters are part of accordion heading.

Now when I click on specification heading, the panel opens up well. But how do I open an accordion using filter buttons? And if the panel is open, how can I keep it open and not toggle the data?

HTML

    <accordion close-others=false>
        <accordion-group is-open="open" data-ng-repeat="(spec,value) in audit | orderBy: 'specification' | groupBy: 'specification'">
            <accordion-heading>

                {{spec}}

                        <button data-style="slide-right" ng-click="Activate(this,'username')" type="button" class="btn btn-xs">

                            Username
                        </button>

                        <button data-style="slide-right" ng-click="Activate(this,'lastname')" type="button" class="btn btn-xs">

                            Lastname
                        </button>

            <accordion-heading>

                {{val.username}} -- {{val.lastname}}

        <accordion-group>
    <accordion>

With my current approach on clicking the Activate(), I set the value of open to true, but this opens up all the accordions.

Javascript:

$scope.Activate = function(val,filter) {
    if (!$scope.open) {
        $scope.open = true;
    }
}

Body:
are you looking for something like this?

HTML Code

<div class="modal-body" style="max-width: 1600px; margin: 0 auto; overflow: hidden;">
    <accordion close-others=false>
        <accordion-group is-open="open" data-ng-repeat="(spec,value) in audit | groupBy:'specification'">
            <accordion-heading class="col-lg-12">
                <i class="glyphicon" ng-class="{'glyphicon-chevron-down': open[$index], 'glyphicon-chevron-right': !open[$index]}"></i>
                <b ng-click="Activate($index)">{{spec}}</b>
                <div class="btn-toolbar pull-right" ng-click="$event.stopPropagation();$event.preventDefault();">
                    <div class="btn-group pull-right">
                        <button data-style="slide-right" ng-click="Activate($index)" type="button" class="btn btn-xs">
                            <i title="Filter" class="fa fa-filter" style="color:#006b24"></i>
                            Username
                        </button>
                    </div>

                    <div class="btn-group pull-right">
                        <button data-style="slide-right" ng-click="Activate($index)" type="button" class="btn btn-xs">
                            <i title="Filter" class="fa fa-filter" style="color:#006b24"></i>
                            Lastname
                        </button>
                    </div>
                </div>
            </accordion-heading>
            <div ng-show="open[$index]" ng-hide="!open[$index]">
                <span class="col-lg-12" data-ng-repeat="val in value">{{val.username}} -- {{val.lastname}}</span>
            </div>
        </accordion-group>
    </accordion>
</div>

JavaScript

$scope.open = [];
$scope.Activate = function (ind) {

    if (!$scope.open[ind]) {
        $scope.open[ind] = true;
    }
    else
    {
        $scope.open[ind] = false;
    }
}


问:
onchange without losing focus?
I'm creating a form with a select dropdown. One of the options is "other - please specify", which is supposed to display an extra text field for more details.

I managed to do it using onChange event + some simple value check (as I can't rely on the position).

I started testing it and realized that while it works perfectly when using a mouse (onChange is ran after the control loses focus), it doesn't when I use the keyboard (since it didn't lose focus yet) - only after I press tab do the changes appear (which looks weird).

It seems to me like I'm missing something obvious, I looked for other events and the closest I've found is onclick, but that's not it either.

So the question is, is there a better way of solving this?

答:
You can simply add this to the <select> tag:

```<code>onkeyup="this.onchange();"
</code>```

Title: onchange without losing focus?

Body:
You can simply add this to the <select> tag:

onkeyup="this.onchange();"


问:
Regex to add # after domain name
I need a regex to change the url from

```<code>http://example.com/page > https://example.com/#/page
</code>```

and

```<code>https://example.com/page > https://example.com/#/page
</code>```

I created this one and I added in 80 and 443 port virtualhosts apache and first redirect works but the second one doesn't

```<code>RewriteCond %{REQUEST_URI} !^.*%23.*$
RewriteRule ^(.*)$ https://%{HTTP_HOST}#%{REQUEST_URI} [R=301,L]
</code>```

答:
You can get even more complicated, depending what you are looking for but here is an example match.

```<code>^(https?:\/\/[^\/]+)\/?(.*)
</code>```

Which you would replace with $1/#$2/

https://regex101.com/r/mAES1b/3

Title: Regex to add # after domain name

Body:
I need a regex to change the url from

http://example.com/page > https://example.com/#/page

and

https://example.com/page > https://example.com/#/page

I created this one and I added in 80 and 443 port virtualhosts apache and first redirect works but the second one doesn't

RewriteCond %{REQUEST_URI} !^.*%23.*$
RewriteRule ^(.*)$ https://%{HTTP_HOST}#%{REQUEST_URI} [R=301,L]

Body:
You can get even more complicated, depending what you are looking for but here is an example match.

^(https?:\/\/[^\/]+)\/?(.*)

Which you would replace with $1/#$2/

https://regex101.com/r/mAES1b/3


问:
Why the python regex pattern fails to match when append a dollar($)?
Here's a small code, using python 3.4

```<code>import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern+'$','./').string
</code>```

It will report AttributeError: 'NoneType' object has no attribute 'string' on execution.

If I remove the +'$' in the code, It works,

```<code>import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern,'./').string
</code>```

As far as I know, $ is for matching the end of string, but why isn't it working here?

答:
Your regex cannot match the / character in your string, and only . is matched.

When you use $ in your regex, it cannot match at all. When you remove it, it matches but only with ".".

Body:
Here's a small code, using python 3.4

import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern+'$','./').string

It will report AttributeError: 'NoneType' object has no attribute 'string' on execution.

If I remove the +'$' in the code, It works,

import re
path_pattern=r'(([^\W]|[.~%$])+)'
re.search(path_pattern,'./').string

As far as I know, $ is for matching the end of string, but why isn't it working here?


问:
Split a text in excel containing text and number in brackets
I want to split a cell into multiple columns with each own.
Please see below for example.

```<code>Currrent Cell:
Mobile Users (300)
Want to Split into two more cells:
Device Category        Number of Users
Mobile Users           300
</code>```

I have used LEFT formula to separate Mobile Users one but cannot split 300 number successfully out of brackets.

答:
In B2 and C2,

```<code>=TRIM(LEFT(A2, FIND("(", A2)-1))
=--REPLACE(REPLACE(A2, FIND(")", A2), LEN(A2), TEXT(, )), 1, FIND("(", A2), TEXT(, ))
</code>```

Don't play with text-that-look-like-numbers. Whenever possible, convert the text to a true number with the VALUE function or a double-unary (aka double minus or --).

Body:
I want to split a cell into multiple columns with each own.
Please see below for example.

Currrent Cell:
Mobile Users (300)
Want to Split into two more cells:
Device Category        Number of Users
Mobile Users           300

I have used LEFT formula to separate Mobile Users one but cannot split 300 number successfully out of brackets.

Body:
In B2 and C2,

=TRIM(LEFT(A2, FIND("(", A2)-1))
=--REPLACE(REPLACE(A2, FIND(")", A2), LEN(A2), TEXT(, )), 1, FIND("(", A2), TEXT(, ))

Don't play with text-that-look-like-numbers. Whenever possible, convert the text to a true number with the VALUE function or a double-unary (aka double minus or --).