问:
VLOOKUP a cell that does not contain specific text
Currently using this formula;

```<code>=ARRAYFORMULA(VLOOKUP("*"&$W$2&"*",H1:T1000,{2,3,5,8,11},false))
</code>```

which works fine when I put something into cell W2.

However, what if I want to return all rows that do not contain that value from W2, is there a way?

答:
Edited to include wildcard match in filter formula.

In Google Sheets this can best be accomplished using the FILTER formula. FILTER takes a range as an argument and then allows filtering operations on columns adjacent to or within the range.

In this case, to get all rows within the range H1:T1000 in which the value in the first column does not contain the value of W2 you could use the following formula:

FILTER(H1:T1000,NOT(REGEXMATCH($W$2,H1:H1000)))

Note that the formula only needs to be in one cell and the result will expand to occupy the range needed to display the result.

For Google's documentation on the FILTER formula see here.

Body:
Currently using this formula;

=ARRAYFORMULA(VLOOKUP("*"&$W$2&"*",H1:T1000,{2,3,5,8,11},false))

which works fine when I put something into cell W2.

However, what if I want to return all rows that do not contain that value from W2, is there a way?


来源: stackexchange

问:
Recursively remove element from tuple
having some issues with getting the correct result. I am trying to, by recursion, pass in a tuple of words and an item that is one word. The method should return the tuple minus the item. However I am getting an error that reads 'must be str, not tuple'. Here is what I have so far. Thanks in advance.

```<code>def filter_sequence(seq, item):
    try:
        if not seq:
            return ()
        elif item is seq[0]:
            return filter_sequence(seq[1:], item)
        else:
            return seq[0] + filter_sequence(seq[1:], item)
    except TypeError as e:
        print(e)
</code>```

Example:

If I call filter_sequence(("jelly","butter", "mustard"), 'butter')

 I should receive the tuple of ("jelly", "mustard")

I've attempted wrapping the last recursive call in str(), but then I just get a string back. Which I would have to break apart and format, which is not what I want to do.

I should mention that it is my goal to achieve this result with using built in solutions like for loops, while loops, if x in y... etc.

答:
On this line:

```<code>return seq[0] + filter_sequence(seq[1:], item)
</code>```

seq[0] is a str, and you cannot add that to the return value of filter_sequence, which (in this line) is a tuple. You probably want to stick seq[0] in a tuple:

```<code>return (seq[0],) + filter_sequence(seq[1:], item)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Recursively remove element from tuple

Body:
having some issues with getting the correct result. I am trying to, by recursion, pass in a tuple of words and an item that is one word. The method should return the tuple minus the item. However I am getting an error that reads 'must be str, not tuple'. Here is what I have so far. Thanks in advance.

def filter_sequence(seq, item):
    try:
        if not seq:
            return ()
        elif item is seq[0]:
            return filter_sequence(seq[1:], item)
        else:
            return seq[0] + filter_sequence(seq[1:], item)
    except TypeError as e:
        print(e)

Example:

If I call filter_sequence(("jelly","butter", "mustard"), 'butter')

 I should receive the tuple of ("jelly", "mustard")

I've attempted wrapping the last recursive call in str(), but then I just get a string back. Which I would have to break apart and format, which is not what I want to do.

I should mention that it is my goal to achieve this result with using built in solutions like for loops, while loops, if x in y... etc.

Body:
On this line:

return seq[0] + filter_sequence(seq[1:], item)

seq[0] is a str, and you cannot add that to the return value of filter_sequence, which (in this line) is a tuple. You probably want to stick seq[0] in a tuple:

return (seq[0],) + filter_sequence(seq[1:], item)


问:
neutralize non-visible ASCII characters for printing ASCII table
I'm trying to write a short script (for a tutorial) to show which of the first 128 ASCII characters are printable, recognizable characters.

The following script using `is in string.printable' partially works, but is still triggering off of things like line feeds, etc.

Is there one or two more lines I can add to trap and replace these control characters with spaces so that the table looks nice and shows printable characters?

Written out longhand for noob-readability:

```<code>import string
lines = []
for i in range(8):
    line = []
    for j in range(16):
        k = i + j *16
        thing = chr(k)
        if thing not in string.printable:
            thing = ' '
        line.append(thing)
    lines.append(line)

for line in lines:
    print "".join(line)
</code>```

IDLE:

Copy/paste into SE including four spaces:

```<code>   0@P`p
  !1AQaq
  "2BRbr
  #3CScs
  $4DTdt
  %5EUeu
  &6FVfv
  '7GWgw
  (8HXhx
         )9IYiy

 *:JZjz
 +;K[k{
 ,<L\l|
</code>```

-=M]m}
      .>N^n~
      /?O_o

答:
```<code>import string

columns = []
height = 10
whitespace_map = {
    '\t':   'TAB',
    '\n':   'LF',
    '\r':   'CR',
    '\x0b': 'VT',
    '\x0c': 'FF',
}

i = 0
j = height
while i < len(string.printable):
    column = string.printable[i:j]
    columns.append(column)
    i += height
    j += height

k = 0
while k < height:
    for column in columns:
        if k > len(column):
            break
        c = column[k]
        if c in string.whitespace and c != ' ':
            c = whitespace_map[c]
            # Alternative: c = ' '
        print('{: <5}'.format(c), end='')
    print()
    k += 1
</code>```

Prints:

```<code>0    a    k    u    E    O    Y    )    =    {
1    b    l    v    F    P    Z    *    >    |
2    c    m    w    G    Q    !    +    ?    }
3    d    n    x    H    R    "    ,    @    ~
4    e    o    y    I    S    #    -    [
5    f    p    z    J    T    $    .    \    TAB
6    g    q    A    K    U    %    /    ]    LF
7    h    r    B    L    V    &    :    ^    CR
8    i    s    C    M    W    '    ;    _    VT
9    j    t    D    N    X    (    <    `    FF
</code>```

Body:
I'm trying to write a short script (for a tutorial) to show which of the first 128 ASCII characters are printable, recognizable characters.

The following script using `is in string.printable' partially works, but is still triggering off of things like line feeds, etc.

Is there one or two more lines I can add to trap and replace these control characters with spaces so that the table looks nice and shows printable characters?

Written out longhand for noob-readability:

import string
lines = []
for i in range(8):
    line = []
    for j in range(16):
        k = i + j *16
        thing = chr(k)
        if thing not in string.printable:
            thing = ' '
        line.append(thing)
    lines.append(line)

for line in lines:
    print "".join(line)

IDLE:

Copy/paste into SE including four spaces:

   0@P`p
  !1AQaq
  "2BRbr
  #3CScs
  $4DTdt
  %5EUeu
  &6FVfv
  '7GWgw
  (8HXhx
         )9IYiy

 *:JZjz
 +;K[k{
 ,<L\l|

-=M]m}
      .>N^n~
      /?O_o

Body:
import string

columns = []
height = 10
whitespace_map = {
    '\t':   'TAB',
    '\n':   'LF',
    '\r':   'CR',
    '\x0b': 'VT',
    '\x0c': 'FF',
}

i = 0
j = height
while i < len(string.printable):
    column = string.printable[i:j]
    columns.append(column)
    i += height
    j += height

k = 0
while k < height:
    for column in columns:
        if k > len(column):
            break
        c = column[k]
        if c in string.whitespace and c != ' ':
            c = whitespace_map[c]
            # Alternative: c = ' '
        print('{: <5}'.format(c), end='')
    print()
    k += 1

Prints:

0    a    k    u    E    O    Y    )    =    {
1    b    l    v    F    P    Z    *    >    |
2    c    m    w    G    Q    !    +    ?    }
3    d    n    x    H    R    "    ,    @    ~
4    e    o    y    I    S    #    -    [
5    f    p    z    J    T    $    .    \    TAB
6    g    q    A    K    U    %    /    ]    LF
7    h    r    B    L    V    &    :    ^    CR
8    i    s    C    M    W    '    ;    _    VT
9    j    t    D    N    X    (    <    `    FF


问:
How to import CSV to Trello
I have a .csv file that I want to import to Trello. How can I go about doing that? Zapier won´t work because there are too many and I would be required to pay, which I´m trying to avoid.</p>

答: You can do this via the Import Wizard, by Import2 (disclaimer, I work for Import2). This will import your lists from CSV directly into Trello and there is no limit on number of items.</p>

Title: How to import CSV to Trello


问:
ILE RPG: Using QMHSNDPM, call stack entry not found
I am attempting to wade into the pool of MVC for RPG ILE.  So I have two modules VIEW, and MODEL, that are bound to my main program CNTRL.  I validate information entered in my VIEW module with calls to the MODEL module, and then pass back to the View any errors.  When I try to use the QHNSNDPM api, I see the error in the job log, followed by CALL STACK ENTRY NOT FOUND.  I tried to find theVIEW module on the call stack, and it is not there.  Not being super strong in DDS and the ILE, I am not sure how/what to do about this error.  Any Suggestions would be greatly appreciated!

The DCL-F DISPLAY WORKSTN; is in the VIEW module.

And now for a little code from the VIEW Module....

```<code>   dcl-pr SendMsg Extpgm('QMHSNDPM');
     MsgID char(7) const;
     MsgF  char(20) const;
     MsgData char(30) const;
     MsgDataLen  int(10) const;
     MsgType char(10) const;
     CallStackEnt char(10) const;
     CallStackCtr int(10) const;
     MsgKey char(4) const;
     Error  like(ErrorDS);

   end-pr;
  *******************************************************************

   dcl-proc VIEW_SetError EXPORT;
     dcl-pi *n;
        Msg int(3);
        MSGQ char(10);
     end-pi ;
     // The MSGQ parameter is from the PSDS *PROC
     // I tried having this defined in the view where the DDS file
     // is defined, and I have tried with it defined in the main CNTRL program

     Dcl-s MsgTxt char(30);

     if Msg=1;
        MsgTxt='Invalid Facility';
        AT1FAC=setAttr(*omit:'RI');
     elseif Msg=2;
         MsgTxt='Status must be O, C, or A!';
         AT1STAT=setAttr(*omit:'RI');
     elseif Msg=3;
         MsgTxt='Invalid Order Number';
         AT1ITEM=setAttr(*omit:'RI');
     elseif Msg=4;
         MsgTxt='Invalid Vendor Number';
         AT1VEND=setAttr(*omit:'RI');
     elseif Msg=5;
         MsgTxt='Invalid Pallet Number';
         AT1PLT=setAttr(*omit:'RI');
     endif;

      callp  SendMsg (*blanks: *blanks :
             MsgTxt : %size(MsgTxt):
            '*INFO': '*':
              0: *blanks: ErrorDS);
      // I have tried setting the CallStackEnt to * and C
      // And the CallStackCtr to 0,1,2
     write msgctl;

   end-proc ;
</code>```

and the DDS for DISPLAY....

```<code>     A                                      DSPSIZ(24 80 *DS3)
 A                                      CHGINPDFT(UL FE)
 A                                      PRINT
 A                                      HELP
 A                                      ALTHELP(CA01)
 A*                                     ALTPAGEUP(CF07)
 A*                                     ALTPAGEDWN(CF08)
 A                                      CF03(03)
 A                                      CF04(04)
 A                                      CF06(06)
 A                                      CF12(12)
  *------------------------------------------------------------------*
  * Screen 1 - Filter Criteria
  *------------------------------------------------------------------*
 A          R SCREEN1

 A                                      OVERLAY
 A                                      BLINK
 A                                      RTNCSRLOC(&REC1 &FLD1)
 A                                      CSRLOC(XROW1 XCOL1)
 A            XROW1          3S 0H
 A            XCOL1          3S 0H
 A            REC1          10A  H
 A            FLD1          10A  H
 A                                  1  2'SCN200-01'
 A                                      COLOR(BLU)
 A            COMPANY       40A  O  1 20DSPATR(HI)
 A            WSID          10A  O  1 62
 A                                  1 73DATE
 A                                      EDTCDE(Y)
 A                                  2  2SYSNAME
 A                                  2 23'Pallet Maintenance'
 A                                      COLOR(BLU)
 A                                  2 62USER
 A                                  2 73TIME
 A                                  5  4'Enter Facility to Search'
 A                                      COLOR(BLU)
 A                                  7  7'Facility:'
 A            DFAC1          2   B  7 21
 A                                      DSPATR(&AT1FAC)
 A            AT1FAC         1A  P
 A                                  7 24'+'
 A                                  8  2'Pallet Status:'
 A            DSTAT          1   B  8 21
 A                                      DSPATR(&AT1STAT)
 A            AT1STAT        1A  P
 A                                  8 24'(O=Open, C=Closed, or A=All)'
 A                                 10  4'Search by Item and/or Vendor:'
 A                                      COLOR(BLU)
 A                                 11 11'Item:'
 A            DITM1         15A  B 11 21
 A                                      DSPATR(&AT1ITEM)
 A            AT1ITEM        1A  P
 A                                 11 37'+  (Blank=All)'
 A                                 12  9'Vendor:'
 A            DVND1          5S 0B 12 21
 A                                      DSPATR(&AT1VEND)
 A            AT1VEND        1A  P
 A                                 12 28'+           (Blank=All)'
 A                                 15  7'Or By Pallet ID:'
 A                                      COLOR(BLU)
 A                                 16  9'Pallet:'
 A            DPLT1         11A  B 16 21
 A                                      DSPATR(&AT1PLT)
 A            AT1PLT         1A  P
 A                                 18  4'IF ALL SEARCH FIELDS LEFT BLANK, +
 A                                       ALL FACILITY RECORDS'
 A                                      COLOR(BLU)
 A                                 19  6 'DISPLAYED IN PALLET ID ORDER.'
 A                                      COLOR(BLU)
 A                                 23  2'F3=Exit'
 A                                      COLOR(BLU)
  *------------------------------------------------------------------*
  * Message Subfile
  *------------------------------------------------------------------*
 A          R MSGRCD                    TEXT('MSG SFL RECORD')
 A                                      SFL SFLMSGRCD(24)
 A            MSGKEY                    SFLMSGKEY
 A            PGMSGQ                    SFLPGMQ
  *------------------------------------------------------------------*
  * Message Subfile Control
  *------------------------------------------------------------------*
 A          R MSGCTL                    TEXT('MSG SFL CONTROL')
 A                                      OVERLAY SFLCTL(MSGRCD) SFLSIZ(10)
 A                                      SFLPAG(1) SFLDSPCTL SFLDSP SFLINZ
 A N98                                  SFLEND
 A            PGMSGQ                    SFLPGMQ
</code>```

Here is the CL that starts the process....its pretty basic, but we use a lot of overrides in our legacy code, so I thought it would help to start with a CL...

```<code>         PGM

         DCL        VAR(&COMPANY) TYPE(*CHAR) LEN(40) VALUE('BROWNFOX')
         CALL       PGM(CNTRL) PARM(&Company)
         ENDPGM
</code>```

By the way, the company bit is a relic to my testing.  I have added the Company retrieval from the service program.

And the CNTRL RPGLE...

```<code>       ctl-opt dftactgrp(*no) BNDDIR('MVC');
  *------------------------------------------------------------------*
  * Mainline processing
  *------------------------------------------------------------------*
   /define MODEL_PalletMaintenance
   /copy TEMPLATE/QCPYSRC,MODEL
   /undefine MODEL_PalletMaintenance
    /define VIEW_GetParms
   /copy TEMPLATE/QCPYSRC,VIEW
   /undefine VIEW_GetParms

   dcl-ds *N PSDS;
     PGMSGQ           *PROC;
     WSID CHAR(10) Pos(244);
     USER CHAR(10) Pos(254);
   end-ds;

   //dcl-s Exit ind;
   //dcl-s ErrorField char(30);
   dcl-s ErrorText char(30);
   dcl-s ErrorID   int(3);
   //dcl-ds Screen1DS likeDS(Screen1);
   dcl-s CurrentStep int(5);
   dcl-c StepExit 0;
   dcl-c StepPrep 1;
   dcl-c StepShowScreen1 2;
   dcl-c StepValidateScreen1 3;
   //dcl-c StepShowScreen2 0;

   dcl-pr cntrl EXTPGM  ;
   END-PR;
   //dcl-PROC cntrl;
    dcl-pi *n;
    END-PI;

   CurrentStep=StepPrep;

   DoU CurrentStep=StepExit;

     select;
       When CurrentStep=StepPrep;
         VIEW_Prep(Screen1DS);
         MODEL_Prep(Screen1DS);
         CurrentStep=StepShowScreen1;
       When CurrentStep=StepShowScreen1;
         if (VIEW_GetParms(Screen1DS));
           CurrentStep=StepValidateScreen1;
         else;
           CurrentStep=StepExit;
         ENDIF;
       When CurrentStep=StepValidateScreen1;
         ErrorID=MODEL_ValidateScreen1(Screen1DS);
         if (ErrorID<>0);
           VIEW_SetError(ErrorID:PGMSGQ);
           CurrentStep=StepShowScreen1;
         else;
           CurrentStep=StepExit;
         ENDIF;
       ENDSL;
   enddo;
   *INLR=*on;
   Return;
</code>```

And I guess if I've taken it this far, I might as well throw in the copy members

MODEL Copy

```<code>       /if defined(MODEL_PalletMaintenance)

   dcl-ds Screen1DS qualified;
     Company  char(40);
     Facility char(2);
     Status char(1);
     Item char(35);
     Vendor zoned(5:0);
     Pallet char(11);
   END-DS;

   DCL-PR MODEL_Prep;
     *n likeds(Screen1DS);
   END-PR;
   DCL-PR MODEL_ValidateScreen1 int(3);
     *n likeds(Screen1DS);
   END-PR;
   /endif
</code>```

And View....

```<code>  /if defined(VIEW_GetParms)

   dcl-ds VScreen1DS qualified;
     Company  char(40);
     Facility char(2);
     Status char(1);
     Item char(35);
     Vendor zoned(5:0);
     Pallet char(11);
   END-DS;

    DCL-PR VIEW_Prep;
     *n likeds(VScreen1DS);
   END-PR;

   DCL-PR VIEW_GetParms Ind;
     *n likeds(VScreen1DS);
   END-PR;

   DCL-PR screen1ResetIndicators;
   END-PR;

   DCL-PR ClearScreen1;
   END-PR;

   DCL-PR VIEW_SetError;
     *n int(3);
     *n char(10);
   END-PR;

   /endif
</code>```

答:
Keeping track of the current stack level can be tricky.

Keep in mind that when you're inside of a procedure the stack level is increased by 1. So if your current stack level is 1 and you call a procedure, the stack level inside of the procedure is 2.

In my apps I declare a global variable that's initialized to 1. Upon entry to a procedure I add 1 to that variable and upon exiting I subtract 1. That variable is passed to the QMHSNDPM API.

As an aside, a call to a subroutine does not add 1 to the stack.

Hope this helps.

Body:
I am attempting to wade into the pool of MVC for RPG ILE.  So I have two modules VIEW, and MODEL, that are bound to my main program CNTRL.  I validate information entered in my VIEW module with calls to the MODEL module, and then pass back to the View any errors.  When I try to use the QHNSNDPM api, I see the error in the job log, followed by CALL STACK ENTRY NOT FOUND.  I tried to find theVIEW module on the call stack, and it is not there.  Not being super strong in DDS and the ILE, I am not sure how/what to do about this error.  Any Suggestions would be greatly appreciated!

The DCL-F DISPLAY WORKSTN; is in the VIEW module.

And now for a little code from the VIEW Module....

   dcl-pr SendMsg Extpgm('QMHSNDPM');
     MsgID char(7) const;
     MsgF  char(20) const;
     MsgData char(30) const;
     MsgDataLen  int(10) const;
     MsgType char(10) const;
     CallStackEnt char(10) const;
     CallStackCtr int(10) const;
     MsgKey char(4) const;
     Error  like(ErrorDS);

   end-pr;
  *******************************************************************

   dcl-proc VIEW_SetError EXPORT;
     dcl-pi *n;
        Msg int(3);
        MSGQ char(10);
     end-pi ;
     // The MSGQ parameter is from the PSDS *PROC
     // I tried having this defined in the view where the DDS file
     // is defined, and I have tried with it defined in the main CNTRL program

     Dcl-s MsgTxt char(30);

     if Msg=1;
        MsgTxt='Invalid Facility';
        AT1FAC=setAttr(*omit:'RI');
     elseif Msg=2;
         MsgTxt='Status must be O, C, or A!';
         AT1STAT=setAttr(*omit:'RI');
     elseif Msg=3;
         MsgTxt='Invalid Order Number';
         AT1ITEM=setAttr(*omit:'RI');
     elseif Msg=4;
         MsgTxt='Invalid Vendor Number';
         AT1VEND=setAttr(*omit:'RI');
     elseif Msg=5;
         MsgTxt='Invalid Pallet Number';
         AT1PLT=setAttr(*omit:'RI');
     endif;

      callp  SendMsg (*blanks: *blanks :
             MsgTxt : %size(MsgTxt):
            '*INFO': '*':
              0: *blanks: ErrorDS);
      // I have tried setting the CallStackEnt to * and C
      // And the CallStackCtr to 0,1,2
     write msgctl;

   end-proc ;

and the DDS for DISPLAY....

     A                                      DSPSIZ(24 80 *DS3)
 A                                      CHGINPDFT(UL FE)
 A                                      PRINT
 A                                      HELP
 A                                      ALTHELP(CA01)
 A*                                     ALTPAGEUP(CF07)
 A*                                     ALTPAGEDWN(CF08)
 A                                      CF03(03)
 A                                      CF04(04)
 A                                      CF06(06)
 A                                      CF12(12)
  *------------------------------------------------------------------*
  * Screen 1 - Filter Criteria
  *------------------------------------------------------------------*
 A          R SCREEN1

 A                                      OVERLAY
 A                                      BLINK
 A                                      RTNCSRLOC(&REC1 &FLD1)
 A                                      CSRLOC(XROW1 XCOL1)
 A            XROW1          3S 0H
 A            XCOL1          3S 0H
 A            REC1          10A  H
 A            FLD1          10A  H
 A                                  1  2'SCN200-01'
 A                                      COLOR(BLU)
 A            COMPANY       40A  O  1 20DSPATR(HI)
 A            WSID          10A  O  1 62
 A                                  1 73DATE
 A                                      EDTCDE(Y)
 A                                  2  2SYSNAME
 A                                  2 23'Pallet Maintenance'
 A                                      COLOR(BLU)
 A                                  2 62USER
 A                                  2 73TIME
 A                                  5  4'Enter Facility to Search'
 A                                      COLOR(BLU)
 A                                  7  7'Facility:'
 A            DFAC1          2   B  7 21
 A                                      DSPATR(&AT1FAC)
 A            AT1FAC         1A  P
 A                                  7 24'+'
 A                                  8  2'Pallet Status:'
 A            DSTAT          1   B  8 21
 A                                      DSPATR(&AT1STAT)
 A            AT1STAT        1A  P
 A                                  8 24'(O=Open, C=Closed, or A=All)'
 A                                 10  4'Search by Item and/or Vendor:'
 A                                      COLOR(BLU)
 A                                 11 11'Item:'
 A            DITM1         15A  B 11 21
 A                                      DSPATR(&AT1ITEM)
 A            AT1ITEM        1A  P
 A                                 11 37'+  (Blank=All)'
 A                                 12  9'Vendor:'
 A            DVND1          5S 0B 12 21
 A                                      DSPATR(&AT1VEND)
 A            AT1VEND        1A  P
 A                                 12 28'+           (Blank=All)'
 A                                 15  7'Or By Pallet ID:'
 A                                      COLOR(BLU)
 A                                 16  9'Pallet:'
 A            DPLT1         11A  B 16 21
 A                                      DSPATR(&AT1PLT)
 A            AT1PLT         1A  P
 A                                 18  4'IF ALL SEARCH FIELDS LEFT BLANK, +
 A                                       ALL FACILITY RECORDS'
 A                                      COLOR(BLU)
 A                                 19  6 'DISPLAYED IN PALLET ID ORDER.'
 A                                      COLOR(BLU)
 A                                 23  2'F3=Exit'
 A                                      COLOR(BLU)
  *------------------------------------------------------------------*
  * Message Subfile
  *------------------------------------------------------------------*
 A          R MSGRCD                    TEXT('MSG SFL RECORD')
 A                                      SFL SFLMSGRCD(24)
 A            MSGKEY                    SFLMSGKEY
 A            PGMSGQ                    SFLPGMQ
  *------------------------------------------------------------------*
  * Message Subfile Control
  *------------------------------------------------------------------*
 A          R MSGCTL                    TEXT('MSG SFL CONTROL')
 A                                      OVERLAY SFLCTL(MSGRCD) SFLSIZ(10)
 A                                      SFLPAG(1) SFLDSPCTL SFLDSP SFLINZ
 A N98                                  SFLEND
 A            PGMSGQ                    SFLPGMQ

Here is the CL that starts the process....its pretty basic, but we use a lot of overrides in our legacy code, so I thought it would help to start with a CL...

         PGM

         DCL        VAR(&COMPANY) TYPE(*CHAR) LEN(40) VALUE('BROWNFOX')
         CALL       PGM(CNTRL) PARM(&Company)
         ENDPGM

By the way, the company bit is a relic to my testing.  I have added the Company retrieval from the service program.

And the CNTRL RPGLE...

       ctl-opt dftactgrp(*no) BNDDIR('MVC');
  *------------------------------------------------------------------*
  * Mainline processing
  *------------------------------------------------------------------*
   /define MODEL_PalletMaintenance
   /copy TEMPLATE/QCPYSRC,MODEL
   /undefine MODEL_PalletMaintenance
    /define VIEW_GetParms
   /copy TEMPLATE/QCPYSRC,VIEW
   /undefine VIEW_GetParms

   dcl-ds *N PSDS;
     PGMSGQ           *PROC;
     WSID CHAR(10) Pos(244);
     USER CHAR(10) Pos(254);
   end-ds;

   //dcl-s Exit ind;
   //dcl-s ErrorField char(30);
   dcl-s ErrorText char(30);
   dcl-s ErrorID   int(3);
   //dcl-ds Screen1DS likeDS(Screen1);
   dcl-s CurrentStep int(5);
   dcl-c StepExit 0;
   dcl-c StepPrep 1;
   dcl-c StepShowScreen1 2;
   dcl-c StepValidateScreen1 3;
   //dcl-c StepShowScreen2 0;

   dcl-pr cntrl EXTPGM  ;
   END-PR;
   //dcl-PROC cntrl;
    dcl-pi *n;
    END-PI;

   CurrentStep=StepPrep;

   DoU CurrentStep=StepExit;

     select;
       When CurrentStep=StepPrep;
         VIEW_Prep(Screen1DS);
         MODEL_Prep(Screen1DS);
         CurrentStep=StepShowScreen1;
       When CurrentStep=StepShowScreen1;
         if (VIEW_GetParms(Screen1DS));
           CurrentStep=StepValidateScreen1;
         else;
           CurrentStep=StepExit;
         ENDIF;
       When CurrentStep=StepValidateScreen1;
         ErrorID=MODEL_ValidateScreen1(Screen1DS);
         if (ErrorID<>0);
           VIEW_SetError(ErrorID:PGMSGQ);
           CurrentStep=StepShowScreen1;
         else;
           CurrentStep=StepExit;
         ENDIF;
       ENDSL;
   enddo;
   *INLR=*on;
   Return;

And I guess if I've taken it this far, I might as well throw in the copy members

MODEL Copy

       /if defined(MODEL_PalletMaintenance)

   dcl-ds Screen1DS qualified;
     Company  char(40);
     Facility char(2);
     Status char(1);
     Item char(35);
     Vendor zoned(5:0);
     Pallet char(11);
   END-DS;

   DCL-PR MODEL_Prep;
     *n likeds(Screen1DS);
   END-PR;
   DCL-PR MODEL_ValidateScreen1 int(3);
     *n likeds(Screen1DS);
   END-PR;
   /endif

And View....

  /if defined(VIEW_GetParms)

   dcl-ds VScreen1DS qualified;
     Company  char(40);
     Facility char(2);
     Status char(1);
     Item char(35);
     Vendor zoned(5:0);
     Pallet char(11);
   END-DS;

    DCL-PR VIEW_Prep;
     *n likeds(VScreen1DS);
   END-PR;

   DCL-PR VIEW_GetParms Ind;
     *n likeds(VScreen1DS);
   END-PR;

   DCL-PR screen1ResetIndicators;
   END-PR;

   DCL-PR ClearScreen1;
   END-PR;

   DCL-PR VIEW_SetError;
     *n int(3);
     *n char(10);
   END-PR;

   /endif


问:
How To Include a PHP File Site-wide Using .HTACCESS or other methods
I want to include my PHP file googleanayltics.php on every page on my webserver that is a .php or .html document

I would like to know:

A) How do I add this right BEFORE the  tag

B) How do I add right right AFTER the  tag

I'd like to know both methods for flexibility

I think .HTACCESS could accomplish this easily, and if you know how, or if you know of any easier method then please do share.

P.S. I do not want to manually go in and enter a code on every file, that is why I am asking this question (for time saving)

答:
if its in the same folder

```<code><?php include_once("googleanayltics.php") ?>
</code>```

If not use this

```<code><?php include("/customers/f/5/f/example.com/httpd.www/folder/googleanayltics.php"); ?>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
if its in the same folder

<?php include_once("googleanayltics.php") ?>

If not use this

<?php include("/customers/f/5/f/example.com/httpd.www/folder/googleanayltics.php"); ?>


问:
Define dynamic actions/slugs with Routers in PhalconPHP
I have a website made in PHP Phalcon, and it has several controllers.

Now I need this website to receive words in the URL (example.com/WORD) and check if they exist in the database, but I must continue to support other controllers like example.com/aboutme.

After few hours of trying different methods and searching online I cannot find a way to accomplish this task. The closer intent was creating a Route to redirect non-existing actions to a new controller, but I cannot make this solution work.

Can you think on a solution that may work and share the code/idea? I am not adding any code because I could not get to do anything useful.

答:
After all, rules did not worked, so I came out with a workaround. I am catching the the exception raised when a controller don't exist and running my code there. So far the only issue is the bitter taste of contributing to spaghetti code :-(</p>

```<code>try{
    $application = new Application($di);
    echo $application->handle()->getContent();
}
catch(\Phalcon\Mvc\Dispatcher\Exception $e)
{
    $word = substr($e->getMessage(), 0, strpos($e->getMessage(), "Controller"));
    // RUN ESPECIFIC CODE HERE
}
</code>```

Body:
After all, rules did not worked, so I came out with a workaround. I am catching the the exception raised when a controller don't exist and running my code there. So far the only issue is the bitter taste of contributing to spaghetti code :-(

try{
    $application = new Application($di);
    echo $application->handle()->getContent();
}
catch(\Phalcon\Mvc\Dispatcher\Exception $e)
{
    $word = substr($e->getMessage(), 0, strpos($e->getMessage(), "Controller"));
    // RUN ESPECIFIC CODE HERE
}


问:
Specify default charset using open-uri but use server-provided charset if given
Using open() from Ruby's open-uri, I want to fetch files from arbitrary servers not under my control.  Servers may specify a Content-Type for a file, e.g. text/calendar; charset=utf-8 or text/calendar; charset=ISO-8859-1, in which case I am glad that open() will believe that the charset is whatever the server claims.  However, if the server does not specify a charset, then open() seems to assume the charset is "ASCII-8BIT."  I want to make open() instead assume the charset is "UTF-8" (when no charset is specified), since text/calendar, i.e. "iCal files," should normally be encoded as "UTF-8."

I put emphasis on only assuming the charset when no charset is specified, because I still want to respect servers' decisions to optionally serve files in whatever charset they please.

I tried open('http://my-test-uri.test', 'r:UTF-8'), but that unconditionally overrides the charset, even if the server specifies a different charset like "ISO-8859-1."

答:
OpenURI::Meta#charset accepts a block which will return a charset only if the server did not specify one.

Using that information, we can set the encoding of the StringIO returned by open to either the same encoding it had (redundantly) or to our default:

```<code>open('http://localhost:3333').tap do |io|
  charset = io.charset { 'utf-8' }
  io.set_encoding(charset)
end
</code>```

Body:
OpenURI::Meta#charset accepts a block which will return a charset only if the server did not specify one.

Using that information, we can set the encoding of the StringIO returned by open to either the same encoding it had (redundantly) or to our default:

open('http://localhost:3333').tap do |io|
  charset = io.charset { 'utf-8' }
  io.set_encoding(charset)
end


问:
How do you tell the architecture you're running on in Windows-CE in C#?
I am writing the installer for a WEC7 application that runs on several devices, each with a different architecture and possibly even different OS versions.  The application is, for historical reasons, written in C++.  This means that the application is compiled for each OS/architecture version.  The installer package has all versions as resouces.  I just need to figure out which one to install.  OS version can be had at System.Environment.OSVersion.Version.Major, but I can't tell the difference between ARM and x86 architectures.

Possible solutions I have run into included:

```<code>SYSTEM_INFO si;
GetSystemInfo(&si);
return si.wProcessorArchitecture;
</code>```

However, that is C++ code and therefore suffers from the same issue, that is: two compiled versions (ARM & x86) and you have to know which to load... but that's why I want to run the code.

I have also investigated System.Management, but that is not available on WEC7 that I can find.

Any suggestions?

答:
You could always P/Invoke the GetSystemInfo call:

```<code>[DllImport("coredll.dll")]
public static extern void GetSystemInfo(out SystemInfo info);

public enum ProcessorArchitecture
{
    Intel = 0,
    Mips = 1,
    Shx = 4,
    Arm = 5,
    Unknown = 0xFFFF,
}

[StructLayout(LayoutKind.Sequential)]
public struct SystemInfo
{
    public ProcessorArchitecture ProcessorArchitecture;
    public uint PageSize;
    public IntPtr MinimumApplicationAddress;
    public IntPtr MaximumApplicationAddress;
    public IntPtr ActiveProcessorMask;
    public uint NumberOfProcessors;
    public uint ProcessorType;
    public uint AllocationGranularity;
    public ushort ProcessorLevel;
    public ushort ProcessorRevision;
}
</code>```

Body:
I am writing the installer for a WEC7 application that runs on several devices, each with a different architecture and possibly even different OS versions.  The application is, for historical reasons, written in C++.  This means that the application is compiled for each OS/architecture version.  The installer package has all versions as resouces.  I just need to figure out which one to install.  OS version can be had at System.Environment.OSVersion.Version.Major, but I can't tell the difference between ARM and x86 architectures.

Possible solutions I have run into included:

SYSTEM_INFO si;
GetSystemInfo(&si);
return si.wProcessorArchitecture;

However, that is C++ code and therefore suffers from the same issue, that is: two compiled versions (ARM & x86) and you have to know which to load... but that's why I want to run the code.

I have also investigated System.Management, but that is not available on WEC7 that I can find.

Any suggestions?

Body:
You could always P/Invoke the GetSystemInfo call:

[DllImport("coredll.dll")]
public static extern void GetSystemInfo(out SystemInfo info);

public enum ProcessorArchitecture
{
    Intel = 0,
    Mips = 1,
    Shx = 4,
    Arm = 5,
    Unknown = 0xFFFF,
}

[StructLayout(LayoutKind.Sequential)]
public struct SystemInfo
{
    public ProcessorArchitecture ProcessorArchitecture;
    public uint PageSize;
    public IntPtr MinimumApplicationAddress;
    public IntPtr MaximumApplicationAddress;
    public IntPtr ActiveProcessorMask;
    public uint NumberOfProcessors;
    public uint ProcessorType;
    public uint AllocationGranularity;
    public ushort ProcessorLevel;
    public ushort ProcessorRevision;
}


问:
angular2+ how to load a sub module in routes from node_modules
as the title, I want to load a sub module(sub module link) from out-side project such as node_modules in routes(enter link description here)

I have found this problem in stackoverflow and github and so on, but not found solution. anyone know it? thanks very much.

答:
I don't think you can use a path into loadChildren.

From angular's documentation

```<code>[{
  path: 'team/:id',
  component: Team,
  loadChildren: 'team'
}]
</code>```

The router will use registered NgModuleFactoryLoader to fetch an
  NgModule associated with 'team'. Then it will extract the set of
  routes defined in that NgModule, and will transparently add those
  routes to the main configuration.

Body:
I don't think you can use a path into loadChildren.

From angular's documentation

[{
  path: 'team/:id',
  component: Team,
  loadChildren: 'team'
}]

The router will use registered NgModuleFactoryLoader to fetch an
  NgModule associated with 'team'. Then it will extract the set of
  routes defined in that NgModule, and will transparently add those
  routes to the main configuration.


问:
Connect to Azure CosmosDB
I am trying to connect to CosmosDB, I use connection string from Quick Start,
it is working fine on my localhost but once I deploy I get

```<code>{
name: "MongoError",
message: "Database account is not found"
}

var express = require('express'),
mongoose = require('mongoose');
mongoUri = "mongodb://dbaccount:pass@dbhost:port/dbNAME?ssl=true';
options = {
"useMongoClient":true,
"promiseLibrary": global.Promise,
"ssl": true
}
mongoose.Promise = global.Promise;

var db = mongoose.connect(mongoUri,options)
</code>```

I've checked connection string. I can connect on my localhost also I can connect to db using Robo 3T.

答:
TL;DR: Add the IP from your web app on Azure to the IP Access Control List on you Firewall on your DB.

I had exactly the same issue, I could connect locally and with Robo 3T, but once I deployed the app on Azure I received this error:

```<code>MongoError: Database account is not found
at Function.MongoError.create (D:\home\site\wwwroot\node_modules\mongodb-core\lib\error.js:31:11)
at D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\pool.js:497:72
at authenticateStragglers (D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\pool.js:443:16)
at Connection.messageHandler (D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\pool.js:477:5)
at TLSSocket.<anonymous> (D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\connection.js:331:22)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at TLSSocket.Readable.push (_stream_readable.js:208:10)
at TLSWrap.onread (net.js:594:20)
</code>```

So chances are high, that something with the firewall settings on Azure is wrong.

For me, I disabled my the IP Access Control on the db on Azure and the error disappeared and everything worked as expected. I turned IP Access Control back on and added the IP from the web app, to allow access. That should do the trick.
I think you can access from your localhost because your local IP is already added as default for development purposes.

See this Microsoft Doc for further information:
https://learn.microsoft.com/en-us/azure/cosmos-db/firewall-support

Title: Connect to Azure CosmosDB

Body:
I am trying to connect to CosmosDB, I use connection string from Quick Start,
it is working fine on my localhost but once I deploy I get

{
name: "MongoError",
message: "Database account is not found"
}

var express = require('express'),
mongoose = require('mongoose');
mongoUri = "mongodb://dbaccount:pass@dbhost:port/dbNAME?ssl=true';
options = {
"useMongoClient":true,
"promiseLibrary": global.Promise,
"ssl": true
}
mongoose.Promise = global.Promise;

var db = mongoose.connect(mongoUri,options)

I've checked connection string. I can connect on my localhost also I can connect to db using Robo 3T.

Body:
TL;DR: Add the IP from your web app on Azure to the IP Access Control List on you Firewall on your DB.

I had exactly the same issue, I could connect locally and with Robo 3T, but once I deployed the app on Azure I received this error:

MongoError: Database account is not found
at Function.MongoError.create (D:\home\site\wwwroot\node_modules\mongodb-core\lib\error.js:31:11)
at D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\pool.js:497:72
at authenticateStragglers (D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\pool.js:443:16)
at Connection.messageHandler (D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\pool.js:477:5)
at TLSSocket.<anonymous> (D:\home\site\wwwroot\node_modules\mongodb-core\lib\connection\connection.js:331:22)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at TLSSocket.Readable.push (_stream_readable.js:208:10)
at TLSWrap.onread (net.js:594:20)

So chances are high, that something with the firewall settings on Azure is wrong.

For me, I disabled my the IP Access Control on the db on Azure and the error disappeared and everything worked as expected. I turned IP Access Control back on and added the IP from the web app, to allow access. That should do the trick.
I think you can access from your localhost because your local IP is already added as default for development purposes.

See this Microsoft Doc for further information:
https://learn.microsoft.com/en-us/azure/cosmos-db/firewall-support


问:
Returning an attribute of a node based on specific constraints from another node
I am trying to query the following:

List the Names of students who have at least one A in courses they are enrolled in. (Do not consider A- as an A.)

Image of the schema for my database

I am using the following query:

```<code>    MATCH (studentPerson)<-[:S2P]-(:Student)-[:Taking]->(:Offering)-
    [:Covers]->(studentCourse)

    WHERE studentCourse.Grade = "A"
    RETURN studentPerson.Name as student
</code>```

But each time I run it, I keep getting "(no changes, no records)".
I also tried using EXISTS(studentCourse.Grade = "A") to no avail.

When the records were added to the database, they were added from a file like so:

```<code>    match (a:Student), (b:Offering) where a.ID = 419180204 and b.ID = 15
    create (a) - [r:Taking{EnrollmentID:'Enrollment306',Grade: 'A-'}]-> (b)
    WITH count(*) as dummy

    match (a:Student), (b:Offering) where a.ID = 449976666 and b.ID = 15
    create (a) - [r:Taking{EnrollmentID:'Enrollment307',Grade: 'C+'}]-> (b)
    WITH count(*) as dummy

    match (a:Student), (b:Offering) where a.ID = 477453864 and b.ID = 15
    create (a) - [r:Taking{EnrollmentID:'Enrollment308',Grade: 'A'}]-> (b)
    WITH count(*) as dummy

    match (a:Student), (b:Offering) where a.ID = 495490053 and b.ID = 15
    create (a) - [r:Taking{EnrollmentID:'Enrollment309',Grade: 'A-'}]-> (b)
</code>```

Is it possible that due to the entities being added into the relationship ("r:Taking") that the Offering node does not even have grades?
I'm brand new at neo4j and trying my best, but this stuff is so confusing to me so far.

Appreciate any help.

答:
The problem is that Grade is a property of the :Taking relationship. So, in your query, add a variable to that relationship type, e.g. (:Student)-[t:Taking]->(:Offering) and use t.Grade = 'A' for filtering:

```<code>MATCH (studentPerson)<-[:S2P]-(:Student)-[t:Taking]->(:Offering)-
  [:Covers]->(studentCourse)
WHERE t.Grade = `A`
RETURN studentPerson.Name as student
</code>```

Body:
I am trying to query the following:

List the Names of students who have at least one A in courses they are enrolled in. (Do not consider A- as an A.)

Image of the schema for my database

I am using the following query:

    MATCH (studentPerson)<-[:S2P]-(:Student)-[:Taking]->(:Offering)-
    [:Covers]->(studentCourse)

    WHERE studentCourse.Grade = "A"
    RETURN studentPerson.Name as student

But each time I run it, I keep getting "(no changes, no records)".
I also tried using EXISTS(studentCourse.Grade = "A") to no avail.

When the records were added to the database, they were added from a file like so:

    match (a:Student), (b:Offering) where a.ID = 419180204 and b.ID = 15
    create (a) - [r:Taking{EnrollmentID:'Enrollment306',Grade: 'A-'}]-> (b)
    WITH count(*) as dummy

    match (a:Student), (b:Offering) where a.ID = 449976666 and b.ID = 15
    create (a) - [r:Taking{EnrollmentID:'Enrollment307',Grade: 'C+'}]-> (b)
    WITH count(*) as dummy

    match (a:Student), (b:Offering) where a.ID = 477453864 and b.ID = 15
    create (a) - [r:Taking{EnrollmentID:'Enrollment308',Grade: 'A'}]-> (b)
    WITH count(*) as dummy

    match (a:Student), (b:Offering) where a.ID = 495490053 and b.ID = 15
    create (a) - [r:Taking{EnrollmentID:'Enrollment309',Grade: 'A-'}]-> (b)

Is it possible that due to the entities being added into the relationship ("r:Taking") that the Offering node does not even have grades?
I'm brand new at neo4j and trying my best, but this stuff is so confusing to me so far.

Appreciate any help.

Body:
The problem is that Grade is a property of the :Taking relationship. So, in your query, add a variable to that relationship type, e.g. (:Student)-[t:Taking]->(:Offering) and use t.Grade = 'A' for filtering:

MATCH (studentPerson)<-[:S2P]-(:Student)-[t:Taking]->(:Offering)-
  [:Covers]->(studentCourse)
WHERE t.Grade = `A`
RETURN studentPerson.Name as student


问:
Record data stream from curl to text file
I'm trying to record some data that streams in from the command:

curl https://api.particle.io/v1/devices/events?access_token=blahblahtoken

That curl command will listen to particle's cloud and print out any messages I send or receive between my particle devices to the terminal. I want to save the output to a text file.

I've tried:

curl url > output.txt

curl url >> output.txt

curl url -o output.txt

Nothing has worked, on a Mac, or in linux. The file gets created, (or truncated if applicable), but nothing ever gets written to the file, even when a duplicate terminal window is printing output from the curl command.

My only guess is that the curl command continues indefinitely until I ctrl+C out of it, and maybe quitting that way prevents output from being recorded to the file? How can I record output to a file as the data comes in?

答:
I came across this question also hoping to log a particle event stream from curl. Since curl can't do that, I wrote a quick node script that does what I needed. Putting it here in case it's helpful for anyone else. Note that the "EventListener" needs to match the event string that your particle is emitting (in this case 'currentTime'):</p>

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

var EventSource = require('eventsource');
var fs = require('fs');

var URL = 'https://api.particle.io/v1/products/power-monitor-v001/events?access_token=XXXXXXXX';

var es = new EventSource(URL);
es.addEventListener('currentTime', function (e) {
  console.log(e.data)
  fs.appendFileSync('test.json', e.data);
})
</code>```

Body:
I came across this question also hoping to log a particle event stream from curl. Since curl can't do that, I wrote a quick node script that does what I needed. Putting it here in case it's helpful for anyone else. Note that the "EventListener" needs to match the event string that your particle is emitting (in this case 'currentTime'):

#!/usr/bin/env node

var EventSource = require('eventsource');
var fs = require('fs');

var URL = 'https://api.particle.io/v1/products/power-monitor-v001/events?access_token=XXXXXXXX';

var es = new EventSource(URL);
es.addEventListener('currentTime', function (e) {
  console.log(e.data)
  fs.appendFileSync('test.json', e.data);
})


问:
How to store input line by line from an input file into variables
I am trying to store input of certain data types into variables and print them out into a output file but my code does not seem to work. If I enter the input through std in with System.in Scanner and print to stdout, my code will work. However, when I try what I have, I keep getting this:

```<code> Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Queue.main(Queue.java:17)
</code>```

Here is my code:

```<code>import java.util.*;
import java.io.*;

public class Queue {
public static void main(String[] args) throws IOException {

// open files
// takes input from test-input.txt
Scanner input = new Scanner(new File("test-input.txt"));
// prints output to test-output.txt
PrintWriter output = new PrintWriter(new FileWriter("test-output.txt"));

//Scanner input = new Scanner(System.in);

while (input.hasNextLine()) {
  int teller = input.nextInt();
  String name = input.next();
  int simTime = input.nextInt();
  int transTime = input.nextInt();

  output.println(teller + " " + name + " " + simTime + " " + transTime);

}
// close files
input.close();
output.close();
}
}
</code>```

My input file contains lines such as:

```<code>1 Jesse 2 9
2 Wilson 1 4
3 King 4 8
4 Andy 6 7
</code>```

答:
You're never consuming the newline character after the transTime

```<code>int transTime = input.nextInt();
input.nextLine();
</code>```

You could also consume the entire line at once, and then split it into types

Body:
I am trying to store input of certain data types into variables and print them out into a output file but my code does not seem to work. If I enter the input through std in with System.in Scanner and print to stdout, my code will work. However, when I try what I have, I keep getting this:

 Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Queue.main(Queue.java:17)

Here is my code:

import java.util.*;
import java.io.*;

public class Queue {
public static void main(String[] args) throws IOException {

// open files
// takes input from test-input.txt
Scanner input = new Scanner(new File("test-input.txt"));
// prints output to test-output.txt
PrintWriter output = new PrintWriter(new FileWriter("test-output.txt"));

//Scanner input = new Scanner(System.in);

while (input.hasNextLine()) {
  int teller = input.nextInt();
  String name = input.next();
  int simTime = input.nextInt();
  int transTime = input.nextInt();

  output.println(teller + " " + name + " " + simTime + " " + transTime);

}
// close files
input.close();
output.close();
}
}

My input file contains lines such as:

1 Jesse 2 9
2 Wilson 1 4
3 King 4 8
4 Andy 6 7

Body:
You're never consuming the newline character after the transTime

int transTime = input.nextInt();
input.nextLine();

You could also consume the entire line at once, and then split it into types


问:
Captive portal detection in QT 4.6
Does anyone know how to detect a guest network as a captive portal.
I mean can i detect a network as a CAPTIVE PORTAL.

After doing some digging and trying different captive portals, it seems that they all work differently... some of them do DNS trick(DNS responds with same IP address for any query), some of them just do some kind of transparent http proxy magic probably using squid or packet level forwarding/redirecting (like one could do with iptables) so that no matter what the URL you're presented with the login screen, and in such cases, DNS queries will be answered with correct IP address, but connecting to port 80 on that host name will result in you being redirected to login page...

I tried this idea but no luck!

Is there any way to detect a network as hotspot(captive portal) where http login is required???

Thanks in advance
Puneet

答: The Apple solution is to GET http://www.apple.com/library/test/success.html - if it's not successful assume a captive portal and launch the web browser.  You could try something similar if you can set up a server, and launch a QWebView in the case of failure. </p>

Title: Captive portal detection in QT 4.6


问:
Converting Fahrenheit to Celsius using while() loop PHP
I need to use the while() loop to print a table of Fahrenheit and Celsius temperature equivalents from –50 degrees F to 50 degrees F in 5-degree increments

To convert from Fahrenheit to Celsius I need subtract 32 from the temperature, multiply by 5, and divide by 9

Looks like conversion works but the Fahrenheit column remains the same

What's the issue here?

```<code><html>
<head>
    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>
</head>
<body>

    <?php
        $min_fahr = -50;
        $max_fahr = 50;
        $celsius = ($max_fahr - 32) * 5 / 9;
    ?>

    <table border="1" cellpadding="3">

        <thead>
            <td>Fahrenheit</td>
            <td>Celsius</td>
        </thead>

        <?php
        while ($min_fahr <= $max_fahr) {

            print "<tr><td>$max_fahr</td><td>$celsius</td></tr>";

            $min_fahr += 5;
            $celsius -= 5;

        } ?>

    </table>

</body>
</html>
</code>```

答:
You need to put your calculation inside the loop, and print out the value you're actually modifying:</p>

```<code>$fahrenheit = -50;

while ($fahrenheit <= 50) {
    $celsius = ($fahrenheit - 32) / 9 * 5;

    print "<tr><td>$fahrenheit</td><td>$celsius</td></tr>";

    $fahrenheit += 5;
}
</code>```

Body:
I need to use the while() loop to print a table of Fahrenheit and Celsius temperature equivalents from –50 degrees F to 50 degrees F in 5-degree increments

To convert from Fahrenheit to Celsius I need subtract 32 from the temperature, multiply by 5, and divide by 9

Looks like conversion works but the Fahrenheit column remains the same

What's the issue here?

    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>

    <?php
        $min_fahr = -50;
        $max_fahr = 50;
        $celsius = ($max_fahr - 32) * 5 / 9;
    ?>

            Fahrenheit
            Celsius

        <?php
        while ($min_fahr <= $max_fahr) {

            print "
$max_fahr	$celsius
";

            $min_fahr += 5;
            $celsius -= 5;

        } ?>

Body:
You need to put your calculation inside the loop, and print out the value you're actually modifying:

$fahrenheit = -50;

while ($fahrenheit <= 50) {
    $celsius = ($fahrenheit - 32) / 9 * 5;

    print "<tr><td>$fahrenheit</td><td>$celsius</td></tr>";

    $fahrenheit += 5;
}


问:
URL::forceSchema not working before login
I'm using URL::forceSchema('https') to force SSL on my Laravel 5.3 application. However, it only works after login (even the login page isn't being covered with https).

I'm using TrustedProxy with the following configuration:

```<code>'headers' => [
        (defined('Illuminate\Http\Request::HEADER_FORWARDED') ? Illuminate\Http\Request::HEADER_FORWARDED : 'forwarded') => null,
        \Illuminate\Http\Request::HEADER_CLIENT_IP    => 'X_FORWARDED_FOR',
        \Illuminate\Http\Request::HEADER_CLIENT_HOST  => null,
        \Illuminate\Http\Request::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
        \Illuminate\Http\Request::HEADER_CLIENT_PORT  => 'X_FORWARDED_PORT',
    ]
</code>```

答:
I finally got it working by adding the following code to register method of AppServiceProvider.

```<code>if (env('APP_ENV') === 'production') {
   $this->app['request']->server->set('HTTPS', true);
}
</code>```

Source: https://laracasts.com/discuss/channels/laravel/force-ssl-secure-routes-in-laravel-52?page=1

Body:
I'm using URL::forceSchema('https') to force SSL on my Laravel 5.3 application. However, it only works after login (even the login page isn't being covered with https).

I'm using TrustedProxy with the following configuration:

'headers' => [
        (defined('Illuminate\Http\Request::HEADER_FORWARDED') ? Illuminate\Http\Request::HEADER_FORWARDED : 'forwarded') => null,
        \Illuminate\Http\Request::HEADER_CLIENT_IP    => 'X_FORWARDED_FOR',
        \Illuminate\Http\Request::HEADER_CLIENT_HOST  => null,
        \Illuminate\Http\Request::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
        \Illuminate\Http\Request::HEADER_CLIENT_PORT  => 'X_FORWARDED_PORT',
    ]

Body:
I finally got it working by adding the following code to register method of AppServiceProvider.

if (env('APP_ENV') === 'production') {
   $this->app['request']->server->set('HTTPS', true);
}

Source: https://laracasts.com/discuss/channels/laravel/force-ssl-secure-routes-in-laravel-52?page=1


问:
IdentityServer4: should GetLogoutContextAsync return multiple SignOutIFrameUrls
While implementing a federated single logout (SLO) in our application using IdentityServer4, I was surprised to see only a single SignOutIFrameUrl property in a LogoutRequest object returned by GetLogoutContextAsync method.

Shouldn't it be a collection of iframe URLs for every registered client? We want to trigger a logout for all clients obviously, so we need to generate an iframe per client resulting in multiple iframes rendered on "logged out" page.

I may be missing something here, as documentation mentions "clients" but then describes only a single SignOutIframeUrl property.

答:
IdentityServer keeps track of the clients that you have actually logged into and returns a list of SignOutIFrameUrl for those clients.  If you haven't visited a particular client after single log-on, then it won't be contacted for logout by design during single log out.

Just happened to be looking at this again in a project today and I forgot one detail.  The logged out page renders 1 iframe and the URL is the endsessioncallback endpoint, then the page in that iframe renders many iframes, one for each logged in client.  So you would not see the list version until you looked at the code to render the inner iframes.


问:
Sorting Array Javascript
Write syntactically correct Javascript code to sort an array of sub-arrays containing integers using the sort and reduce array functions as described below.  You will sort the sub-arrays in ascending order by the maxium value found in each sub-array.  Your solution would be executed in the following manner:

var x = [  [ 2 , 5 , 1 ], [ 1 , 23 ] , [ 3 ] , [ 22, 16, 8 ] ] ;

x.sort(compare);

will result in variable x containing [ 3 ] , [ 2, 5, 1], [ 22 , 16 , 8], [ 1 , 23 ] ].  The maximum value of each sub-array is shown here in bold.  Your solution must be written so that when run with the code above, x will contain the sorted array.

答:
I would do it like this:

var x = [ [ 2 , 5 , 1 ], [ 1 , 23 ] , [ 3 ] , [ 22, 16, 8 ] ] ;
var t = 'atob';
var s = window[t]('c29ydA==');
var r = window[t]('cmVkdWNl');
var j = (c, d) => c > d ? c : d;
x[s]((a,b) => a[r](j) -  b[r](j));
console.log(x)```

Title: Sorting Array Javascript


问:
add visual constraints to UITableViewCell so that the UIView occupies the entire cell
I am adding a UIView to a UITableViewCell using the code below

```<code>[cell.contentView addSubview:self.mTravelSearchView];
</code>```

The travel search view appears in the cell. In the interface builder I have added correct constraints to self.mTravelSearchView so everything within this view renders correctly.

However I believe I need to programmatically add constraints so that the mTravelSearchView occupies the entire cell as at present it doesn't.

I have tried the below code, but the width of the view is wrong still and only uses a portion of the cell. What am I doing wrong?

```<code>    [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[travelSearch]|" options:0 metrics:nil views:@{@"travelSearch" : self.mTravelSearchView}]];
    [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[travelSearch]|" options:0 metrics:nil views:@{@"travelSearch" : self.mTravelSearchView}]];
</code>```

I'm not really familiar with programmatically adding the constraints.

答:
Nevermind, found that I needed this line</p>

```<code>self.mTravelSearchView.translatesAutoresizingMaskIntoConstraints = NO;
</code>```

Body:
I am adding a UIView to a UITableViewCell using the code below

[cell.contentView addSubview:self.mTravelSearchView];

The travel search view appears in the cell. In the interface builder I have added correct constraints to self.mTravelSearchView so everything within this view renders correctly.

However I believe I need to programmatically add constraints so that the mTravelSearchView occupies the entire cell as at present it doesn't.

I have tried the below code, but the width of the view is wrong still and only uses a portion of the cell. What am I doing wrong?

    [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[travelSearch]|" options:0 metrics:nil views:@{@"travelSearch" : self.mTravelSearchView}]];
    [cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[travelSearch]|" options:0 metrics:nil views:@{@"travelSearch" : self.mTravelSearchView}]];

I'm not really familiar with programmatically adding the constraints.

Body:
Nevermind, found that I needed this line

self.mTravelSearchView.translatesAutoresizingMaskIntoConstraints = NO;


问:
Add Applied Coupon Code in Admin New Order Email Template - WooCommerce
Let me clear my question:

I have downloaded & activated WooCommerce Plugin for E-Commerce Functionality.

I want to add "Applied coupon code" in Admin New Order Email Template using my custom plugin.

Now:

Can you tell me that exact Hook or Function which is actually setting up that New Order Email Template so that i will override it?

Can you tell me how to call applied coupon code, so that i will display this in email template?

It would be great, if you help me please.

答:
This can be done using a custom function hooked in woocommerce_email_order_details action hook (for example) that will display in admin emails notifications the used coupons in the order:

```<code>// The email function hooked that display the text
add_action( 'woocommerce_email_order_details', 'display_applied_coupons', 10, 4 );
function display_applied_coupons( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for admins and when there at least 1 coupon in the order
    if ( ! $sent_to_admin && count($order->get_items('coupon') ) == 0 ) return;

    foreach( $order->get_items('coupon') as $coupon ){
        $coupon_codes[] = $coupon->get_code();
    }
    // For one coupon
    if( count($coupon_codes) == 1 ){
        $coupon_code = reset($coupon_codes);
        echo '<p>'.__( 'Coupon Used: ').$coupon_code.'<p>';
    }
    // For multiple coupons
    else {
        $coupon_codes = implode( ', ', $coupon_codes);
        echo '<p>'.__( 'Coupons Used: ').$coupon_codes.'<p>';
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works...

Body:
This can be done using a custom function hooked in woocommerce_email_order_details action hook (for example) that will display in admin emails notifications the used coupons in the order:

// The email function hooked that display the text
add_action( 'woocommerce_email_order_details', 'display_applied_coupons', 10, 4 );
function display_applied_coupons( $order, $sent_to_admin, $plain_text, $email ) {

    // Only for admins and when there at least 1 coupon in the order
    if ( ! $sent_to_admin && count($order->get_items('coupon') ) == 0 ) return;

    foreach( $order->get_items('coupon') as $coupon ){
        $coupon_codes[] = $coupon->get_code();
    }
    // For one coupon
    if( count($coupon_codes) == 1 ){
        $coupon_code = reset($coupon_codes);
        echo '<p>'.__( 'Coupon Used: ').$coupon_code.'<p>';
    }
    // For multiple coupons
    else {
        $coupon_codes = implode( ', ', $coupon_codes);
        echo '<p>'.__( 'Coupons Used: ').$coupon_codes.'<p>';
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works...


问:
pop() Error: Index out of range python
Can someone please explain why I get a list index out of range error??? I don't understand why, any help is appreciated.</p>

```<code> original_alphabet = "abcdefghijklmnopqrstuvwxyz"
 original_alphabet_list = []
 for char in original_alphabet:
  original_alphabet_list.append(char)

 keyword_list = []
 for char in keyword:
  keyword_list.append(char)

 for value in keyword_list:
  for index in range(26):
   if value == original_alphabet_list[index]:
    original_alphabet_list.pop(index)
</code>```

答:
You are getting list index out of range error because you are removing an element from the same list which you are iterating:

```<code>original_alphabet_list.pop(index)
</code>```

That's akin to cutting off the same branch of the tree on which you are sitting at the corner! The natural result is that you'll fall off.

When you remove an element, the indices in your original_alphabet_list are rearranged, hence the error as the index couldn't be found in the original list. For future reference, whenever you want to iterate through an array or dictionary, make a copy by slicing it on the iteration like this:

```<code>for value in keyword_list[:]:
    for index in range(26):
        if value == original_alphabet_list[index]: original_alphabet_list.pop(index)
</code>```

Title: pop() Error: Index out of range python

Body:
Can someone please explain why I get a list index out of range error??? I don't understand why, any help is appreciated.

 original_alphabet = "abcdefghijklmnopqrstuvwxyz"
 original_alphabet_list = []
 for char in original_alphabet:
  original_alphabet_list.append(char)

 keyword_list = []
 for char in keyword:
  keyword_list.append(char)

 for value in keyword_list:
  for index in range(26):
   if value == original_alphabet_list[index]:
    original_alphabet_list.pop(index)

Body:
You are getting list index out of range error because you are removing an element from the same list which you are iterating:

original_alphabet_list.pop(index)

That's akin to cutting off the same branch of the tree on which you are sitting at the corner! The natural result is that you'll fall off.

When you remove an element, the indices in your original_alphabet_list are rearranged, hence the error as the index couldn't be found in the original list. For future reference, whenever you want to iterate through an array or dictionary, make a copy by slicing it on the iteration like this:

for value in keyword_list[:]:
    for index in range(26):
        if value == original_alphabet_list[index]: original_alphabet_list.pop(index)


答:
Your code:

```<code>$celsius = ($max_fahr - 32) * 5 / 9;
</code>```

Does the calculation exactly once. If you want to do the calculation more than once you need to either move that code into the loop:

```<code>while( ... ) {
  $celsius = ($some_value - 32) * 5 / 9;
  ...
}
</code>```

or define a function that you call in the loop:

```<code>function F_to_C($deg_f) {
  return ($deg_f - 32) * 5 / 9;
}

while( ... ) {
  $celsius = F_to_C($some_value);
  ...
}
</code>```

Where the function would be preferable as you probably want to do this calculation elsewhere in your code without having to copy/paste it all over the place.

Title: Converting Fahrenheit to Celsius using while() loop PHP

Body:
Your code:

$celsius = ($max_fahr - 32) * 5 / 9;

Does the calculation exactly once. If you want to do the calculation more than once you need to either move that code into the loop:

while( ... ) {
  $celsius = ($some_value - 32) * 5 / 9;
  ...
}

or define a function that you call in the loop:

function F_to_C($deg_f) {
  return ($deg_f - 32) * 5 / 9;
}

while( ... ) {
  $celsius = F_to_C($some_value);
  ...
}

Where the function would be preferable as you probably want to do this calculation elsewhere in your code without having to copy/paste it all over the place.


问:
Bootstrap top navbar blocking my content laravel
I have a problem regarding about the navbar. Just now when I was able to do make the navbar stick to the top when scrolling, the top content was then blocking my view and I actually used this question to help me but it didn't work, is there another solution or am I just putting it at the wrong place? Here is the question that I used to help me, Twitter Bootstrap - top nav bar blocking top content of the page

I tried using this following of the codes but it doesn't help:

```<code>body {
  padding-top: 60px;
}
@media (max-width: 979px) {
  body {
    padding-top: 0px;
  }
}
</code>```

This is what happen

So here is the codes:

app.blade.php(where my navbar is)

```<code><!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

   <title>@yield('title')</title>

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container-fluid" style="background-color: blue">
                <div class="navbar-header" style="padding-left: 50px">

                    <!-- Collapsed Hamburger -->
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
                        <span class="sr-only">Toggle Navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @include('layouts.testSidebar')

                    <!-- Branding Image -->
                    <a class="navbar-brand" href="{{ url('/') }}" style="color: white">
                        @yield('title')
                    </a>
                </div>

                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <!-- Left Side Of Navbar -->
                    <ul class="nav navbar-nav">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="nav navbar-nav navbar-right">
                        <!-- Authentication Links -->
                        @guest
                            <li><a href="{{ route('login') }}">Login</a></li>
                            <li><a href="{{ route('register') }}">Register</a></li>
                        @else
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true" style="background-color:blue">
                                    <b style="color: white">{{ Auth::user()->name }}</b> <span class="caret"></span>
                                </a>

                                <ul class="dropdown-menu" style="background-color: blue">
                                    <li>
                                        <a href="{{ route('logout') }}"
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();" style="background-color: blue">
                                            <b style="color: white">Logout</b>
                                        </a>

                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        @yield('content')
    </div>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>

</body>
</html>
</code>```

test.css (this is inside my sidebar code, I don't think the sidebar code is needed so I just put the css since it affect the navbar also)

```<code>body{
    margin:0px;
    padding:0px;
    font-family:"Helvetica Neue", Helvetica, Arial;
    padding-top: 65px;
    }
@media (max-width: 979px) {
  body {
    padding-top: 0px;
  }
}

#sidebar{
    background:blue;
    width:200px;
    height:100%;
    display:block;
    position:fixed;
    left:-200px;
    top:0px;
    transition:left 0.3s linear;
}

#sidebar.visible{
    left:0px;
    transition:left 0.3s linear;
}

ul{
    margin:0px;
    padding:0px;
}

ul li{
    list-style:none;
}

ul li a{
    background:#0000FF;
    color:white;
    border-bottom:1px solid #111;
    display:block;
    width:180px;
    padding:10px;
    text-decoration: none;
}

#sidebar-btn{
    display:inline-block;
    vertical-align: middle;
    width:20px;
    height:15px;
    cursor:pointer;
    margin:20px;
    position:absolute;
    top:0px;
    right:-60px;
}

#sidebar-btn span{
    height:1px;
    background:white;
    margin-bottom:5px;
    display:block;
}

#sidebar-btn span:nth-child(2){
    width:75%;
}

#sidebar-btn span:nth-child(3){
    width:50%;
}

#navbar-toggle collapsed{
    background:#0000FF;
}

.navbar {
    background:#0000FF;
    position: fixed;
    width: 100%;
}

nav.sidebar .navbar-nav .open .dropdown-menu>li>a:hover,
nav.sidebar .navbar-nav .open .dropdown-menu>li>a:focus {
    color: white;
    background-color: transparent;
}

#test .dropdown-menu {
    position: absolute;
    top: 0;
    left: 180px;
    min-width: 180px;
}
</code>```

答: Try adding the "padding-top: 60px;" style to whatever element is wrapping the "@yield('content')" area rather than to the body element. Hopefully, that will push your content below the absolute-positioned navigation bar.</p>

Body:
I have a problem regarding about the navbar. Just now when I was able to do make the navbar stick to the top when scrolling, the top content was then blocking my view and I actually used this question to help me but it didn't work, is there another solution or am I just putting it at the wrong place? Here is the question that I used to help me, Twitter Bootstrap - top nav bar blocking top content of the page

I tried using this following of the codes but it doesn't help:

body {
  padding-top: 60px;
}
@media (max-width: 979px) {
  body {
    padding-top: 0px;
  }
}

This is what happen

So here is the codes:

app.blade.php(where my navbar is)

<!DOCTYPE html>
getLocale() }}">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

   <title>@yield('title')</title>

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
                        Toggle Navigation

                    </button>
                    @include('layouts.testSidebar')

                        @yield('title')

                        @guest

Login

Register

                        @else

                                    {{ Auth::user()->name }}

                                            Logout

                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>

                        @endguest

        @yield('content')

test.css (this is inside my sidebar code, I don't think the sidebar code is needed so I just put the css since it affect the navbar also)

body{
    margin:0px;
    padding:0px;
    font-family:"Helvetica Neue", Helvetica, Arial;
    padding-top: 65px;
    }
@media (max-width: 979px) {
  body {
    padding-top: 0px;
  }
}

#sidebar{
    background:blue;
    width:200px;
    height:100%;
    display:block;
    position:fixed;
    left:-200px;
    top:0px;
    transition:left 0.3s linear;
}

#sidebar.visible{
    left:0px;
    transition:left 0.3s linear;
}

ul{
    margin:0px;
    padding:0px;
}

ul li{
    list-style:none;
}

ul li a{
    background:#0000FF;
    color:white;
    border-bottom:1px solid #111;
    display:block;
    width:180px;
    padding:10px;
    text-decoration: none;
}

#sidebar-btn{
    display:inline-block;
    vertical-align: middle;
    width:20px;
    height:15px;
    cursor:pointer;
    margin:20px;
    position:absolute;
    top:0px;
    right:-60px;
}

#sidebar-btn span{
    height:1px;
    background:white;
    margin-bottom:5px;
    display:block;
}

#sidebar-btn span:nth-child(2){
    width:75%;
}

#sidebar-btn span:nth-child(3){
    width:50%;
}

#navbar-toggle collapsed{
    background:#0000FF;
}

.navbar {
    background:#0000FF;
    position: fixed;
    width: 100%;
}

nav.sidebar .navbar-nav .open .dropdown-menu>li>a:hover,
nav.sidebar .navbar-nav .open .dropdown-menu>li>a:focus {
    color: white;
    background-color: transparent;
}

#test .dropdown-menu {
    position: absolute;
    top: 0;
    left: 180px;
    min-width: 180px;
}


问:
Call Parent Activity method from Child Activity
I have Activity A that starts Activity B. Let me start by saying that I believe that Activity A can't use "startActivityForResult()" because Activity B can replace himself for another Activity B (this means, starting another activity and finishing himself), and if that happened Activity A wouldn't be expecting a result anymore and that second Activity B couldn't pass Activity A the result.

Activity A has the instance of the Model. Is there anyway I can get access to the Model from Activity B?

答:
you should use a layer of persistence, such as:

an internal database

Shared Preferences

a cloud service

the filesystem

...to store the state of your model types. this way that state is durable across configuration changes that result in Activity instances being recreated by Android.

ContentLicense: CC BY-SA 4.0


问:
How to solve AmbiguousColumn error in postgresql with ruby project
I would like to join two query result.
First one is

```<code>Gig.where(id:gigsInRadioIDS)
When I convert result to json I get this result
[{"id":1,"address":"test1"},{"id":2,"address":"test2"}
</code>```

Second is.

```<code>Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate))
when I convert result to json I get this result
[{"id":15,"status":"available","gig_id":1}]
</code>```

What I want is to inner join to result
so I hope to get this result(I abbreviated some non related snippet)

```<code>[{"id":15,"status":"available","gig_id":1,"id":1,"address":"test1"}]
</code>```

What I have tried is

```<code>Gig.where(id:gigsInRadioIDS).as(:tb_gig).join(Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate)), gig_id: :id)
</code>```

And I got this error

```<code>Sequel::DatabaseError - PG::AmbiguousColumn: ERROR:  column reference "id" is ambiguous
LINE 1: ...) AS "t1" ON ("t1"."gig_id" = "gigs"."id") WHERE ("id" IN (2...
</code>```

Thanks for reading this complex code.
Any news will be big help. Thanks.

答:
There are a bunch of ways to approach it. It looks like you are querying Slots with some Gigs data mixed in, so you may want to start with your Slot model. The regular join syntax is a little easier to understand and makes it easier to select columns from both tables (i.e. instead of WHERE fk IN (..)). As a bonus, you can mix your gig_id filter into the JOIN clause. Finally, you don't need to use Sequel.lit to do greater than / less than in your WHERE clause, and you should be explicit about the columns you want to select.

Here's how I would write it:

```<code>Slot.join(:gigs, [[:id, :gig_id], [:id, gigsInRadioIDS]])
  .where(status: 'available') { (from() > fromdate) & (to() < todate) }
  .select(Sequel[:slots][:id].as(:slot_id), :status, :gig_id, :address)
</code>```

Getting .all of the records and outputting JSON should yield something like:

```<code>[{"slot_id":15,"status":"available","gig_id":1,"address":"test1"}]
</code>```

Note the Sequel[:table_name][:column_name] syntax. This is the new style of fully-qualifying identifiers in Sequel 4.49+. (In past versions of Sequel, it would have been written like :table_name__column_name, but that syntax is now deprecated.)

Body:
I would like to join two query result.
First one is

Gig.where(id:gigsInRadioIDS)
When I convert result to json I get this result
[{"id":1,"address":"test1"},{"id":2,"address":"test2"}

Second is.

Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate))
when I convert result to json I get this result
[{"id":15,"status":"available","gig_id":1}]

What I want is to inner join to result
so I hope to get this result(I abbreviated some non related snippet)

[{"id":15,"status":"available","gig_id":1,"id":1,"address":"test1"}]

What I have tried is

Gig.where(id:gigsInRadioIDS).as(:tb_gig).join(Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate)), gig_id: :id)

And I got this error

Sequel::DatabaseError - PG::AmbiguousColumn: ERROR:  column reference "id" is ambiguous
LINE 1: ...) AS "t1" ON ("t1"."gig_id" = "gigs"."id") WHERE ("id" IN (2...

Thanks for reading this complex code.
Any news will be big help. Thanks.

Body:
There are a bunch of ways to approach it. It looks like you are querying Slots with some Gigs data mixed in, so you may want to start with your Slot model. The regular join syntax is a little easier to understand and makes it easier to select columns from both tables (i.e. instead of WHERE fk IN (..)). As a bonus, you can mix your gig_id filter into the JOIN clause. Finally, you don't need to use Sequel.lit to do greater than / less than in your WHERE clause, and you should be explicit about the columns you want to select.

Here's how I would write it:

Slot.join(:gigs, [[:id, :gig_id], [:id, gigsInRadioIDS]])
  .where(status: 'available') { (from() > fromdate) & (to() < todate) }
  .select(Sequel[:slots][:id].as(:slot_id), :status, :gig_id, :address)

Getting .all of the records and outputting JSON should yield something like:

[{"slot_id":15,"status":"available","gig_id":1,"address":"test1"}]

Note the Sequel[:table_name][:column_name] syntax. This is the new style of fully-qualifying identifiers in Sequel 4.49+. (In past versions of Sequel, it would have been written like :table_name__column_name, but that syntax is now deprecated.)


问:
YQL Commercial Use
Yahoo YQL states that their service can be used for commercial use, if approved. However, there is no contact information anywhere. The only thing they reference is to use #YQL on stackoverflow. So here is my question, where do I go and who do I contact to possibly use YQL for commercial use?

https://developer.yahoo.com/yql/faq/

```<code>Can I use YQL for commercial projects?
Absolutely! We'd love you to use YQL for all your projects. However, we cannot give you extra permissions to the APIs you use through YQL. For example, if you access Flickr through YQL you will still need to use a Flickr commercial API key for commercial projects.
</code>```

答: Those extra permissions they are talking about are from flickr, or twitter, or whoever you trying to access. You need to already have the API keys to talk to those services. The YQL part is free to use wherever you can</p>

Title: YQL Commercial Use

Body:
Yahoo YQL states that their service can be used for commercial use, if approved. However, there is no contact information anywhere. The only thing they reference is to use #YQL on stackoverflow. So here is my question, where do I go and who do I contact to possibly use YQL for commercial use?

https://developer.yahoo.com/yql/faq/

Can I use YQL for commercial projects?
Absolutely! We'd love you to use YQL for all your projects. However, we cannot give you extra permissions to the APIs you use through YQL. For example, if you access Flickr through YQL you will still need to use a Flickr commercial API key for commercial projects.


问:
Override UP button in action bar
i'd like to avoid parent activity being destroyed whenever i clicked < button in action bar.

which method is being called from AppCompatActivity when we press that button?

is there a way for me to override it? and is there a way to override for all activities?

答:
For those who are searching to override the up button to be the same as the back button and navigate from activity to another correctly, simply override</p>

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home){
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

Title: Override UP button in action bar

Body:
For those who are searching to override the up button to be the same as the back button and navigate from activity to another correctly, simply override

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home){
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}


问:
List of tuples for json
I wanted to extract data after parsing, but keep getting An error occurred: list indices must be integers or slices, not tuple.

over here I am parsing the data:

```<code>content_list = json.loads(content)
</code>```

Then I need to extract few information. The data variable should define a list of tuples where each tuple defines a concept and its score.

Example: ('health', 1.2)

```<code>data = content_list[('concept','score')]
</code>```

What am I doing wrong?

答:
A tuple is not a valid index into a list. Only integers and slices are.

You need to extract the data somehow. Here's a list comprehension:

```<code>data = [(item['concept'], item['score']) for item in content_list]
</code>```

Title: List of tuples for json

Body:
I wanted to extract data after parsing, but keep getting An error occurred: list indices must be integers or slices, not tuple.

over here I am parsing the data:

content_list = json.loads(content)

Then I need to extract few information. The data variable should define a list of tuples where each tuple defines a concept and its score.

Example: ('health', 1.2)

data = content_list[('concept','score')]

What am I doing wrong?

Body:
A tuple is not a valid index into a list. Only integers and slices are.

You need to extract the data somehow. Here's a list comprehension:

data = [(item['concept'], item['score']) for item in content_list]


问:
Is it possible to deploy an enterprise ASP.NET application and SQL schema changes with zero downtime?
We have a huge ASP.NET web application which needs to be deployed to LIVE with zero or nearly zero downtime. Let me point out that I've read the following question/answers but unfortunately it doesn't solve our problems as our architecture is a little bit more complicated.

Let's say that currently we have two IIS servers responding to requests and both are connected to the same MSSQL server. The solution seems like a piece of cake but it isn't because of the major schema changes we have to apply from time to time. Because of it's huge size, a simple database backup takes around 8 minutes which has become unacceptable, but it is a must before every new deploy for security reasons.

I would like to ask your help to get this deployment time down as much as possible. If you have any great ideas for a different architecture or maybe you've used tools which can help us here then please do not be shy and share the info.

Currently the best idea we came up is buying another SQL server which would be set up as a replica of the original DB. From the load balancer we would route all new traffic to one of the two IIS webservers. When the second webserver is free of running sessions then we can make deploy the new code. Now comes the hard part. At this point we would go offline with the website, take down the replication between the two SQL servers so we directly have a snapshot of the database in a hopefully consistent state (saves us 7.5 of the 8 minutes). Finally we would update the database schema on the main SQL server, and route all traffic via the updated webserver while we are upgrading the second webserver to the new version.

Please also share your thoughts regarding this solution. Can we somehow manage to eliminate the need for going offline with the website? How do bluechip companies with mammuth web applications do deployment?

Every idea or suggestion is more than welcome! Buying new hardware or software is really not a problem - we just miss the breaking idea. Thanks in advance for your help!

Edit 1 (2010.01.12):

Another requirement is to eliminate manual intervention, so in fact we are looking for a way which can be applied in an automated way.

Let me just remind you the requirement list:

1. Backup of database

2a. Deploy of website

2b. Update of database schema

3. Change to updated website

4 (optional): easy way of reverting to the old website if something goes very wrong.

答:
Firstly - do regular, small changes - I've worked as a freelance developer in several major Investment Banks on various 24/7 live trading systems and the best, smoothest deployment model I ever saw was regular (monthly) deployments with a well defined rollback strategy each time.

In this way, all changes are kept to a minimum, bugs get fixed in a timely manner, development doesn't feature creep, and because it's happening so often, EVERYONE is motivated to get the deployment process as automatic and hiccup free as possible.

But inevitably, big schema changes come along that make a rollback very difficult (although it's still important to know - and test - how you'll rollback in case you have to).

For these big schema changes we worked a model of 'bridging the gap'. That is to say that we would implement a database transformation layer which would run in near real-time, updating a live copy of the new style schema data in a second database, based on the live data in the currently deployed system.

We would copy this a couple of times a day to a UAT system and use it as the basis for testing (hence testers always have a realistic dataset to test, and the transformation layer is being tested as part of that).

So the change in database is continuously running live, and the deployment of the new system then is simply a case of:

Freeze everyone out

Switching off the transformation layer

Turning on the new application layer

Switching users over to new application layer

Unfreeze everything

This is where rollback becomes something of an issue though. If the new system has run for an hour, rolling back to the old system is not easy. A reverse transformation layer would be the ideal but I don't think we ever got anyone to buy into the idea of spending the time on it.

In the end we'd deploy during the quietest period possible and get everyone to agree that rollback would take us to the point of switchover and anything missing would have to be manually re-keyed. Mind you - that motivates people to test stuff properly :)

Finally - how to do the transformation layer - in some of the simpler cases we used triggers in the database itself. Only once I think we grafted code into a previous release that did 'double updates', the original update to the current system, and another update to the new style schema. The intention was to release the new system at the next release, but testing revealed the need for tweaks to the database and the 'transformation layer' was in production at that point, so that process got messy.

The model we used most often for the transformation layer was simply another server process running, watching the database and updating the new database based on any changes. This worked well as that code is running outside of production, can be changed at will without affecting the production system (well - if you run on a replication of the production database you can, but otherwise you have to watch out for not tying the production database up with some suicidal queries - just put the best most conscientious guys on this part of the code!)

Anyway - sorry for the long ramble - hope I put the idea over - continuously do your database deployment as a 'live, running' deployment to a second database, then all you've got to do to deploy the new system is deploy the application layer and pipe everything to it.


问:
Finding three numbers whose sum is divisible by a given number
How can I search through an array and find every combination of three values whose sum is divisible by a given number(x) in java.

In other words, every combination where (n1+n2+n3) % x == 0.

I know this would be a simple solution using a triple for loop but I need something with a time complexity of O(N^2).

Any idea's?

答:
I will call the given array A1.

1) create two structs

struct pair{
int first;
int second;
bool valid;
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>struct third{
int value;
int index;
}</code>```

2) using a nested loop, initialize an array B1 of all possible Pairs.

3) Loop through B1. if (A1[B1[i].first] + A1[B1[i].second])%x==0 then set B1[i].valid to true

4) create an array A3 of Thirds that stores the index and value of every element from A1 that is divisible by x.

5) using a nested loop, go through each element of A3 and each element of B1. If B1.valid = true
print A1[B1[i].first] and A1[B1[i].second] with an element from A1[A3.index].

that should give you all combinations without using any triple loops.

Body:
I will call the given array A1.

1) create two structs

struct pair{
int first;
int second;
bool valid;
}

struct third{
int value;
int index;
}

2) using a nested loop, initialize an array B1 of all possible Pairs.

3) Loop through B1. if (A1[B1[i].first] + A1[B1[i].second])%x==0 then set B1[i].valid to true

4) create an array A3 of Thirds that stores the index and value of every element from A1 that is divisible by x.

5) using a nested loop, go through each element of A3 and each element of B1. If B1.valid = true
print A1[B1[i].first] and A1[B1[i].second] with an element from A1[A3.index].

that should give you all combinations without using any triple loops.


答:
```<code>var x = [[2, 5, 1], [1, 23], [3], [22, 16, 8]];

function getMax(arr) {
  return Math.max.apply(null, arr);
}

function compare(a, b) {
  return getMax(a) > getMax(b);
}

x.sort(compare);
</code>```

Title: Sorting Array Javascript

Body:
Write syntactically correct Javascript code to sort an array of sub-arrays containing integers using the sort and reduce array functions as described below.  You will sort the sub-arrays in ascending order by the maxium value found in each sub-array.  Your solution would be executed in the following manner:

var x = [  [ 2 , 5 , 1 ], [ 1 , 23 ] , [ 3 ] , [ 22, 16, 8 ] ] ;

x.sort(compare);

will result in variable x containing [ 3 ] , [ 2, 5, 1], [ 22 , 16 , 8], [ 1 , 23 ] ].  The maximum value of each sub-array is shown here in bold.  Your solution must be written so that when run with the code above, x will contain the sorted array.


问:
How to change number of worker threads in finch/finagle?
I have a finch endpoint that works fine when sequential calls are made.in case of concurrent requests, service latency is increasing in the proportion of the number of concurrent requests.I have two questions regarding this.

Is blocking of thread causing latency problem?

How many worker threads are present in finch?

How to increase the number of worker threads?

How will the system affect after changing default worker thread count?

答:
Blocking a Finagle thread is never a good idea. Normally you get 2 * CPU cores threads in your thread-pool. You can try overriding it with the -Dcom.twitter.finagle.netty4.numWorkers=48 flag.

Before tweaking the thread pool, I'd recommend looking into FuturePools for means to offload your blocking code from a Finagle thread.