问:
CSS3: Nested flexbox form messes up spacing
I am trying to make a flexbox form with label and input on the same line. Using flex-basis and and other flex properties gives the expected and desired result.

However, if one has to nest that flexbox inside another element with a set width, the whole thing falls apart.

E.g. see the attached fiddle and run it with and without the div {width:30%}

How can I get around this?

fiddle

答:
You are trying to make flexbox behave as a grid/table, and as it is not made for that you need to help it a little by setting some constraint, like min-width, though as you stated you don't want that, use a proper display type.

Since CSS Grid still has no reasonable browser support, here is the second best, CSS Table

div.lesswide {
  width: 30%;
  margin-top: 20px;
}
form  {
  display: table;
  width: 100%;
}
form div {
  display: table-row;
}
form label {
  display: table-cell;
  width: 30%;
}
form input {
  display: table-cell;
  width: 60%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <form>
    <div>
      <label>A</label>
      <input type="text">
    </div>

    <div>
      <label>LONG</label>
      <input type="text">
    </div>

    <div>
      <label>SOMEWHAT LONGER</label>
      <input type="text">
    </div>

    <div>
      <label>INTHEMIDDLE</label>
      <input type="text">
    </div>
  </form>
</div>

<div class="lesswide">
  <form>
    <div>
      <label>A</label>
      <input type="text">
    </div>

    <div>
      <label>LONG</label>
      <input type="text">
    </div>

    <div>
      <label>SOMEWHAT LONGER</label>
      <input type="text">
    </div>

    <div>
      <label>INTHEMIDDLE</label>
      <input type="text">
    </div>
  </form>
</div></code>```

An updated version based on comments

form {
  display: table;
  width: 100%;
}
form > div {
  display: table-row;
}
form label {
  display: table-cell;
  width: 30%;
}
form input {
  width: 100%;
  box-sizing: border-box;
}

form div div:first-child {
  display: table-cell;
  width: 30%;
}
form div div:last-child {
  display: table-cell;
  width: 70%;
}

form div .side-by-side input[type=button] {
  width: 30%;
}
form div .side-by-side input[type=submit] {
  width: 70%;
}

@media screen and (max-width: 550px) {
  form div div:first-child,
  form div div:last-child,
  form label {
    display: block;
    width: auto;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <form>
    <div>
      <label>A</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>LONG</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>SOMEWHAT LONGER</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>INTHEMIDDLE</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <div>
        <input type="button" value="Button">
      </div>
      <div>
        <input type="submit">
      </div>
    </div>
  </form>
</div>
<br>
<div>
  <form>
    <div>
      <label>A</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>LONG</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>SOMEWHAT LONGER</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>INTHEMIDDLE</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <div>
      </div>
      <div class="side-by-side">
        <input type="button" value="Button"><input type="submit">
      </div>
    </div>
  </form>
</div></code>```

Body:
You are trying to make flexbox behave as a grid/table, and as it is not made for that you need to help it a little by setting some constraint, like min-width, though as you stated you don't want that, use a proper display type.

Since CSS Grid still has no reasonable browser support, here is the second best, CSS Table

div.lesswide {
  width: 30%;
  margin-top: 20px;
}
form  {
  display: table;
  width: 100%;
}
form div {
  display: table-row;
}
form label {
  display: table-cell;
  width: 30%;
}
form input {
  display: table-cell;
  width: 60%;
}

<div>
  <form>
    <div>
      <label>A</label>
      <input type="text">
    </div>

    <div>
      <label>LONG</label>
      <input type="text">
    </div>

    <div>
      <label>SOMEWHAT LONGER</label>
      <input type="text">
    </div>

    <div>
      <label>INTHEMIDDLE</label>
      <input type="text">
    </div>
  </form>
</div>

<div class="lesswide">
  <form>
    <div>
      <label>A</label>
      <input type="text">
    </div>

    <div>
      <label>LONG</label>
      <input type="text">
    </div>

    <div>
      <label>SOMEWHAT LONGER</label>
      <input type="text">
    </div>

    <div>
      <label>INTHEMIDDLE</label>
      <input type="text">
    </div>
  </form>
</div>

An updated version based on comments

form {
  display: table;
  width: 100%;
}
form > div {
  display: table-row;
}
form label {
  display: table-cell;
  width: 30%;
}
form input {
  width: 100%;
  box-sizing: border-box;
}

form div div:first-child {
  display: table-cell;
  width: 30%;
}
form div div:last-child {
  display: table-cell;
  width: 70%;
}

form div .side-by-side input[type=button] {
  width: 30%;
}
form div .side-by-side input[type=submit] {
  width: 70%;
}

@media screen and (max-width: 550px) {
  form div div:first-child,
  form div div:last-child,
  form label {
    display: block;
    width: auto;
  }
}

<div>
  <form>
    <div>
      <label>A</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>LONG</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>SOMEWHAT LONGER</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>INTHEMIDDLE</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <div>
        <input type="button" value="Button">
      </div>
      <div>
        <input type="submit">
      </div>
    </div>
  </form>
</div>
<br>
<div>
  <form>
    <div>
      <label>A</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>LONG</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>SOMEWHAT LONGER</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <label>INTHEMIDDLE</label>
      <div>
        <input type="text">
      </div>
    </div>

    <div>
      <div>
      </div>
      <div class="side-by-side">
        <input type="button" value="Button"><input type="submit">
      </div>
    </div>
  </form>
</div>


来源: stackexchange

问:
Add value of playing cards - with pointers and structures
I'm going through some c programming questions and I'm currently stuck on a pointer related question

Q: Write a function that takes the values of a two-card blackjack HAND as input, and returns the point total of the hand. The value
 of the cards '2' through '9' is equal to their face value, the cards 'T', 'K', 'Q', 'J' are worth 10 points and the ace ('A') is worth 11 points
 unless it comes with another ace, then that second ace is worth 1 point. The program should be able to catch incorrect input.

Examples:
Enter cards: A Q
 The score is 21

Enter cards: A A
 The score is 12

I've tackled this question before, but this time I'd have to use pointers which I'm still fairly new towards. Getting card values and calculating cards must be done in one function. Here's what i have so far:

```<code>#include <stdio.h>
#define HAND 2
struct player_hand
{
     char card1;
     char card2;
};

void getHandValue(struct player_hand * hnd_ptr, char size, char size2)
{
    int first_card;
    int second_card;

    //get cards from user
    scanf("%c %c",&hnd_ptr->card1, &hnd_ptr->card2);
    printf("Enter Cards: %c %c", &hnd_ptr->card1, &hnd_ptr->card2);

    //check value of first card in hand
    if(hnd_ptr->card1<='9' && hnd_ptr->card1>='2')
    {
        first_card=(int)hnd_ptr->card1 -48;

    }
    //check for special cards: king, queen, jack, ten
    else if(hnd_ptr->card1=='T'||hnd_ptr->card1=='K'||hnd_ptr->card1=='Q'||hnd_ptr->card1=='J')
    {
        first_card=10;
    }
    //if first card is Ace
    else if(hnd_ptr->card1=='A')
    {
        first_card=11;
    }
    else
    {
        //card not valid
        printf("Not a valid card: %c",hnd_ptr->card1);
        return;
    }

    //check value of 2nd card
    if(hnd_ptr->card2<='9' && hnd_ptr->card2>='2')
    {
        second_card=(int)hnd_ptr->card2 -48;

    }
    //if 2nd card is a special kind
    else if(hnd_ptr->card2=='T'||hnd_ptr->card2=='K'||hnd_ptr->card2=='Q'||hnd_ptr->card2=='J')
    {
        second_card=10;
    }
    //if 2nd card is Ace
    else if(hnd_ptr->card2=='A')
    {
        if(hnd_ptr->card1=='A')
        second_card=1;
        else
        second_card=11;
    }
    else
    {
        //if 2nd card not valid
        printf("Not a valid card: %c",hnd_ptr->card2);
        return;
    }

    add cards
    printf("\nThe total card value is: %d",first_card+second_card);

}

//call function, test if works
//calling it wrong?
int main(void)
{
    struct player_hand hnd [HAND]  =  { {'A', 'A'}};
    getHandValue (hnd, HAND);
    return;
}
</code>```

答:
If, in addition to the other answers, your intent was to pass a 2-hand array, you would need to handle both hands within a loop in your scoring function. For example:

```<code>#include <stdio.h>

#define HAND 2

struct player_hand
{
    char card1;
    char card2;
};

void getHandValue (struct player_hand *hnd_ptr, int size)
{
    int first_card;
    int second_card;

    /* get cards from user */
    for (int i = 0; i < size; i++) {
        printf ("\nenter cards for hand %d (card1 card2): ", i);

        /* you must handle the '\n' that remains after last char */
        if (scanf ("%c %c%*c", &hnd_ptr[i].card1,  &hnd_ptr[i].card2) != 2) {
            fprintf (stderr, "error: invalid entry.\n");
            return;
        }
        printf ("you entered: %c %c\n", hnd_ptr[i].card1, hnd_ptr[i].card2);
    }

    for (int i = 0; i < size; i++)
    {
        /* check value of first card in hand */
        if(hnd_ptr[i].card1 <= '9' && hnd_ptr[i].card1 >= '2')
        {
            first_card = (int)hnd_ptr[i].card1 - '0';

        }
        /* check for special cards: king, queen, jack, ten */
        else if (hnd_ptr[i].card1 == 'T' || hnd_ptr[i].card1 == 'K' ||
                hnd_ptr[i].card1 == 'Q' || hnd_ptr[i].card1 == 'J')
        {
            first_card = 10;
        }
        /* if first card is Ace */
        else if (hnd_ptr[i].card1 == 'A')
        {
            first_card = 11;
        }
        else
        {
            /* card not valid */
            printf("Not a valid card: %c",hnd_ptr[i].card1);
            return;
        }

        /* check value of 2nd card */
        if(hnd_ptr[i].card2 <= '9' && hnd_ptr[i].card2 >= '2')
        {
            second_card=(int)hnd_ptr[i].card2 - '0';

        }
        /* if 2nd card is a special kind */
        else if (hnd_ptr[i].card2 == 'T' || hnd_ptr[i].card2 == 'K' ||
                hnd_ptr[i].card2 == 'Q' || hnd_ptr[i].card2 == 'J')
        {
            second_card = 10;
        }
        /* if 2nd card is Ace */
        else if (hnd_ptr[i].card2 == 'A')
        {
            if (hnd_ptr[i].card1 == 'A')
                second_card = 1;
            else
                second_card = 11;
        }
        else
        {
            /* if 2nd card not valid */
            printf ("Not a valid card: %c", hnd_ptr[i].card2);
            return;
        }

        /* add cards */
        printf ("\nThe total cards value (hand %d) is: %d\n",
                i, first_card + second_card);
    }
}

int main(void)
{
    struct player_hand hnd[HAND]  =  { {'A', 'A'}, {'A', 'A'} };
    getHandValue (hnd, HAND);

    return 0;
}
</code>```

Example Use/Output

```<code>$ ./bin/cards

enter cards for hand 0 (card1 card2): A A
you entered: A A

enter cards for hand 1 (card1 card2): 8 K
you entered: 8 K

The total cards value (hand 0) is: 12

The total cards value (hand 1) is: 18
</code>```

If your intent was not to pass an array of struct, then obviously looping would not be necessary. Note: two loops were used. The first to get the cards for both hands, the second to compute the scores for both. (you could do it with one, but it looked as if you intended to have all cards entered before scoring) Look things over and let me know if you have further questions.

ContentLicense: CC BY-SA 3.0

Body:
I'm going through some c programming questions and I'm currently stuck on a pointer related question

Q: Write a function that takes the values of a two-card blackjack HAND as input, and returns the point total of the hand. The value
 of the cards '2' through '9' is equal to their face value, the cards 'T', 'K', 'Q', 'J' are worth 10 points and the ace ('A') is worth 11 points
 unless it comes with another ace, then that second ace is worth 1 point. The program should be able to catch incorrect input.

Examples:
Enter cards: A Q
 The score is 21

Enter cards: A A
 The score is 12

I've tackled this question before, but this time I'd have to use pointers which I'm still fairly new towards. Getting card values and calculating cards must be done in one function. Here's what i have so far:

#include <stdio.h>
#define HAND 2
struct player_hand
{
     char card1;
     char card2;
};

void getHandValue(struct player_hand * hnd_ptr, char size, char size2)
{
    int first_card;
    int second_card;

    //get cards from user
    scanf("%c %c",&hnd_ptr->card1, &hnd_ptr->card2);
    printf("Enter Cards: %c %c", &hnd_ptr->card1, &hnd_ptr->card2);

    //check value of first card in hand
    if(hnd_ptr->card1<='9' && hnd_ptr->card1>='2')
    {
        first_card=(int)hnd_ptr->card1 -48;

    }
    //check for special cards: king, queen, jack, ten
    else if(hnd_ptr->card1=='T'||hnd_ptr->card1=='K'||hnd_ptr->card1=='Q'||hnd_ptr->card1=='J')
    {
        first_card=10;
    }
    //if first card is Ace
    else if(hnd_ptr->card1=='A')
    {
        first_card=11;
    }
    else
    {
        //card not valid
        printf("Not a valid card: %c",hnd_ptr->card1);
        return;
    }

    //check value of 2nd card
    if(hnd_ptr->card2<='9' && hnd_ptr->card2>='2')
    {
        second_card=(int)hnd_ptr->card2 -48;

    }
    //if 2nd card is a special kind
    else if(hnd_ptr->card2=='T'||hnd_ptr->card2=='K'||hnd_ptr->card2=='Q'||hnd_ptr->card2=='J')
    {
        second_card=10;
    }
    //if 2nd card is Ace
    else if(hnd_ptr->card2=='A')
    {
        if(hnd_ptr->card1=='A')
        second_card=1;
        else
        second_card=11;
    }
    else
    {
        //if 2nd card not valid
        printf("Not a valid card: %c",hnd_ptr->card2);
        return;
    }

    add cards
    printf("\nThe total card value is: %d",first_card+second_card);

}

//call function, test if works
//calling it wrong?
int main(void)
{
    struct player_hand hnd [HAND]  =  { {'A', 'A'}};
    getHandValue (hnd, HAND);
    return;
}

Body:
If, in addition to the other answers, your intent was to pass a 2-hand array, you would need to handle both hands within a loop in your scoring function. For example:

#include <stdio.h>

#define HAND 2

struct player_hand
{
    char card1;
    char card2;
};

void getHandValue (struct player_hand *hnd_ptr, int size)
{
    int first_card;
    int second_card;

    /* get cards from user */
    for (int i = 0; i < size; i++) {
        printf ("\nenter cards for hand %d (card1 card2): ", i);

        /* you must handle the '\n' that remains after last char */
        if (scanf ("%c %c%*c", &hnd_ptr[i].card1,  &hnd_ptr[i].card2) != 2) {
            fprintf (stderr, "error: invalid entry.\n");
            return;
        }
        printf ("you entered: %c %c\n", hnd_ptr[i].card1, hnd_ptr[i].card2);
    }

    for (int i = 0; i < size; i++)
    {
        /* check value of first card in hand */
        if(hnd_ptr[i].card1 <= '9' && hnd_ptr[i].card1 >= '2')
        {
            first_card = (int)hnd_ptr[i].card1 - '0';

        }
        /* check for special cards: king, queen, jack, ten */
        else if (hnd_ptr[i].card1 == 'T' || hnd_ptr[i].card1 == 'K' ||
                hnd_ptr[i].card1 == 'Q' || hnd_ptr[i].card1 == 'J')
        {
            first_card = 10;
        }
        /* if first card is Ace */
        else if (hnd_ptr[i].card1 == 'A')
        {
            first_card = 11;
        }
        else
        {
            /* card not valid */
            printf("Not a valid card: %c",hnd_ptr[i].card1);
            return;
        }

        /* check value of 2nd card */
        if(hnd_ptr[i].card2 <= '9' && hnd_ptr[i].card2 >= '2')
        {
            second_card=(int)hnd_ptr[i].card2 - '0';

        }
        /* if 2nd card is a special kind */
        else if (hnd_ptr[i].card2 == 'T' || hnd_ptr[i].card2 == 'K' ||
                hnd_ptr[i].card2 == 'Q' || hnd_ptr[i].card2 == 'J')
        {
            second_card = 10;
        }
        /* if 2nd card is Ace */
        else if (hnd_ptr[i].card2 == 'A')
        {
            if (hnd_ptr[i].card1 == 'A')
                second_card = 1;
            else
                second_card = 11;
        }
        else
        {
            /* if 2nd card not valid */
            printf ("Not a valid card: %c", hnd_ptr[i].card2);
            return;
        }

        /* add cards */
        printf ("\nThe total cards value (hand %d) is: %d\n",
                i, first_card + second_card);
    }
}

int main(void)
{
    struct player_hand hnd[HAND]  =  { {'A', 'A'}, {'A', 'A'} };
    getHandValue (hnd, HAND);

    return 0;
}

Example Use/Output

$ ./bin/cards

enter cards for hand 0 (card1 card2): A A
you entered: A A

enter cards for hand 1 (card1 card2): 8 K
you entered: 8 K

The total cards value (hand 0) is: 12

The total cards value (hand 1) is: 18

If your intent was not to pass an array of struct, then obviously looping would not be necessary. Note: two loops were used. The first to get the cards for both hands, the second to compute the scores for both. (you could do it with one, but it looked as if you intended to have all cards entered before scoring) Look things over and let me know if you have further questions.


问:
SQL giving me headache - multiple joins
First I'll explain my scenario. Here's the 2 general tables in use:

Accounts:

LegacyID = The identifer of the
account

InvoiceAccount = An account can have
multiple subaccounts in the same
table. This    field is the LegacyID
of its parent account

Customer = There can be two different
types of accounts, and they can share
ID's - so this column differentiates
between the 2. For the purposes of my
SQL I always want it to be true rather
than false

AllocatedUser = The username of the
person who needs to see this
deliveries. This is only populated on
the parent account, so I need to link
back to get this for the subaccounts

Deliveries:

LegacyID = The deliveries identifier

Customer = The LegacyID of the account
related to the delivery (can be a
subaccount)

OnHold = A flag which for the purposes
of my query needs to be 'true'

Now that's explained, basically I need an SQL which returns any deliveries that are 'OnHold', but only for deliveries for accounts that are allocated the logged in user. The query for selecting the AllocatedUser if the delivery links to a parent account was simple, but I'm having issues with returning rows if the delivery is linked to a subaccount - it's simply not returning any. Here is the SQL below:

```<code>SELECT     Deliveries_1.LegacyID, Deliveries_1.TripDate, Deliveries_1.OnHoldReason, Account_2.AllocatedUser
FROM         Deliveries AS Deliveries_1 INNER JOIN
                      Account AS Account_1 ON Deliveries_1.Customer = Account_1.InvoiceAccount INNER JOIN
                      Account AS Account_2 ON Account_1.InvoiceAccount = Account_2.LegacyID
WHERE     (Deliveries_1.OnHold = @OnHold) AND (Account_2.Customer = 'True') AND (Account_2.AllocatedUser = @AllocatedUser)
</code>```

My mind is frazzled from trying to work out why it don't work at the moment - I'd really appreciate any advice.

Thanks!

答:
It sounds like you're looking for records in the Deliveries table that are associated with a user's account, the user's direct parent's account, and the user's direct child's account.  If this is true modifying your query as follows should do the trick.

```<code>SELECT DISTINCT d.LegacyID, d.TripDate, d.OnHoldReason,
       case
          when child.LegacyID = d.Customer then child.AllocatedUser
          when parent.LegacyID = d.Customer then parent.AllocatedUser
          else this.AllocatedUser
       end as 'Delivery_AllocatedUser'
FROM Account this
  LEFT JOIN Account parent on parent.LegacyID = this.InvoiceAccount
  LEFT JOIN Account child on this.LegacyID = child.InvoiceAccount
  JOIN Deliveries d on (d.Customer = this.LegacyID AND this.Customer = 'True')
                    OR (d.Customer = parent.LegacyID AND parent.Customer = 'True')
                    OR (d.Customer = child.LegacyID AND child.Customer = 'True')
WHERE d.OnHold = @OnHold
  AND this.AllocatedUser = @AllocatedUser
</code>```

ContentLicense: CC BY-SA 2.5

Title: SQL giving me headache - multiple joins

Body:
First I'll explain my scenario. Here's the 2 general tables in use:

Accounts:

LegacyID = The identifer of the
account

InvoiceAccount = An account can have
multiple subaccounts in the same
table. This    field is the LegacyID
of its parent account

Customer = There can be two different
types of accounts, and they can share
ID's - so this column differentiates
between the 2. For the purposes of my
SQL I always want it to be true rather
than false

AllocatedUser = The username of the
person who needs to see this
deliveries. This is only populated on
the parent account, so I need to link
back to get this for the subaccounts

Deliveries:

LegacyID = The deliveries identifier

Customer = The LegacyID of the account
related to the delivery (can be a
subaccount)

OnHold = A flag which for the purposes
of my query needs to be 'true'

Now that's explained, basically I need an SQL which returns any deliveries that are 'OnHold', but only for deliveries for accounts that are allocated the logged in user. The query for selecting the AllocatedUser if the delivery links to a parent account was simple, but I'm having issues with returning rows if the delivery is linked to a subaccount - it's simply not returning any. Here is the SQL below:

SELECT     Deliveries_1.LegacyID, Deliveries_1.TripDate, Deliveries_1.OnHoldReason, Account_2.AllocatedUser
FROM         Deliveries AS Deliveries_1 INNER JOIN
                      Account AS Account_1 ON Deliveries_1.Customer = Account_1.InvoiceAccount INNER JOIN
                      Account AS Account_2 ON Account_1.InvoiceAccount = Account_2.LegacyID
WHERE     (Deliveries_1.OnHold = @OnHold) AND (Account_2.Customer = 'True') AND (Account_2.AllocatedUser = @AllocatedUser)

My mind is frazzled from trying to work out why it don't work at the moment - I'd really appreciate any advice.

Thanks!

Body:
It sounds like you're looking for records in the Deliveries table that are associated with a user's account, the user's direct parent's account, and the user's direct child's account.  If this is true modifying your query as follows should do the trick.

SELECT DISTINCT d.LegacyID, d.TripDate, d.OnHoldReason,
       case
          when child.LegacyID = d.Customer then child.AllocatedUser
          when parent.LegacyID = d.Customer then parent.AllocatedUser
          else this.AllocatedUser
       end as 'Delivery_AllocatedUser'
FROM Account this
  LEFT JOIN Account parent on parent.LegacyID = this.InvoiceAccount
  LEFT JOIN Account child on this.LegacyID = child.InvoiceAccount
  JOIN Deliveries d on (d.Customer = this.LegacyID AND this.Customer = 'True')
                    OR (d.Customer = parent.LegacyID AND parent.Customer = 'True')
                    OR (d.Customer = child.LegacyID AND child.Customer = 'True')
WHERE d.OnHold = @OnHold
  AND this.AllocatedUser = @AllocatedUser


问:
How can I add a username and password to Jenkins?
When I go to mydomain.example:8080 there is no authorization mechanism by default. I have had look at the configuration area but cannot find anywhere to add a basic username and password

答:
Try deleting the .jenkins folder from your system which is located ate the below path.
C:\Users\"Your PC Name"\.jenkins

Now download a fresh and a stable version of .war file from official website of jenkins. For eg. 2.1 and follow the steps to install.

You will be able to do via this method

ContentLicense: CC BY-SA 4.0


问:
for loop & while loop not working in asynctask doInBackground in android?
I am facing a very silly problem in my project and not able to resolve it. I am using AsyncTask for fetching current location of user. In that i used one counter to work as timer. Inside doInBackground I am incrementing that counter and if its greater than x value then i cancel the async task.

Here is the code snippet : -

```<code>class CurrentPositionTask extends AsyncTask<String, Void, Void> {
        long counter = 0;
        boolean flag = true;

        @Override
        public void onPreExecute() {
            // TODO Auto-generated method stub
        }

        @Override
        public Void doInBackground(String... params) {
            // TODO Auto-generated method stub
            do {
                counter++;
                if (latitude != 0 && longitude != 0) {
                    flag = false;
                }
            } while (counter <= 100000);
            return null;
        }

        @Override
        public void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
        }

    }
</code>```

But here the while condition is not working. I also tried the for loop instead of while but that is not also working for me. Also face very strange problem, when i print the counter using sysout its working fine but without it its not working..

All suggestions are welcome.

答:
Just use

```<code>Looper.prepare();
</code>```

before while loop in doInBackground method

Body:
I am facing a very silly problem in my project and not able to resolve it. I am using AsyncTask for fetching current location of user. In that i used one counter to work as timer. Inside doInBackground I am incrementing that counter and if its greater than x value then i cancel the async task.

Here is the code snippet : -

class CurrentPositionTask extends AsyncTask<String, Void, Void> {
        long counter = 0;
        boolean flag = true;

        @Override
        public void onPreExecute() {
            // TODO Auto-generated method stub
        }

        @Override
        public Void doInBackground(String... params) {
            // TODO Auto-generated method stub
            do {
                counter++;
                if (latitude != 0 && longitude != 0) {
                    flag = false;
                }
            } while (counter <= 100000);
            return null;
        }

        @Override
        public void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
        }

    }

But here the while condition is not working. I also tried the for loop instead of while but that is not also working for me. Also face very strange problem, when i print the counter using sysout its working fine but without it its not working..

All suggestions are welcome.

Body:
Just use

Looper.prepare();

before while loop in doInBackground method


问:
Not able to redirect page using Angular Routing
I am trying to learn Angular but stuck with the routing issue. I have tried looking at other questions but couldn't find an answer.

This is my index page

```<code> <!DOCTYPE html>
 <html data-ng-app = 'myFirstApp'>
 <head>
      <title>View</title>
 </head>

 <body>
 <div>
     <div ng-view></div>
 </div>
 <script src="Scripts/angular.min.js"></script>
 <script src="Scripts/angular-route.min.js"></script>

 <script>
     var demoApp = angular.module('myFirstApp', ['ngRoute']);

     demoApp.config(['$routeProvider', function($routeProvider){
        $routeProvider
            .when('/view1', {
                templateUrl: 'demoPartials/view1.html',
                controller: 'SimpleController'
            })
            .when('/view2', {
                templateUrl: 'demoPartials/view2.html',
                controller: 'SimpleController'
            })
            .otherwise({redirectTo: '/view1'});
     }]);

     demoApp.controller('SimpleController', function($scope){
        $scope.customers = [
            {name:'A F', city:'M'},
            {name:'D D', city:'B'},
            {name:'S J', city:'I'}
        ];
        $scope.addCustomer = function(){
            $scope.cutomers.push(
                {
                    name: $scope.newCustomer.name,
                    city: $scope.newCustomer.city
                }
            );
        };
     });
 </script>
 </body>
 </html>
</code>```

The issue of routing is that whenever I click the view2 link it doesn't route to the View2.html page. How should I fix it?

The View1 page

```<code><div class="container">
    <h2>View 1</h2>
    Name:
    <br>
    <input type="text" data-ng-model="filter.name">
    <br>
    <ul>
        <li data-ng-repeat="cust in customers | filter:filter.name | orderBy:'city'">
            {{ cust.name }} - {{ cust.city }}
        </li>
    </ul>
    <br>
    Customer Name: <br>
    <input type="text" data-ng-model="newCustomer.name">
    <br>
    Customer City: <br>
    <input type="text" data-ng-model="newCustomer.city">
    <br>
    <button data-ng-click="addCustomer()">Add Cutomer</button>
    <br>
    <a href="#/view2.html">View 2</a>
</div>
</code>```

And view 2 page

```<code><div class="container">
    <h2>View 2</h2>
    City:
    <br>
    <input type="text" data-ng-model="city">
    <br>
    <ul>
        <li data-ng-repeat="cust in customers | filter:city | orderBy:'city'">
            {{ cust.name }} - {{ cust.city }}
        </li>
    </ul>
</div>
</code>```

Do check at the images once.

normal view of page: https://s15.postimg.org/3jrg76nsb/image.png

after clicking view2: https://s7.postimg.org/7xazbqqij/image.png

答:
Update href to name of route

```<code><a href="#/view2">View 2</a>
</code>```

Body:
I am trying to learn Angular but stuck with the routing issue. I have tried looking at other questions but couldn't find an answer.

This is my index page

 <!DOCTYPE html>

      <title>View</title>

The issue of routing is that whenever I click the view2 link it doesn't route to the View2.html page. How should I fix it?

The View1 page

View 1

    Name:

    <input type="text" data-ng-model="filter.name">

            {{ cust.name }} - {{ cust.city }}

    Customer Name:

    <input type="text" data-ng-model="newCustomer.name">

    Customer City:

    <input type="text" data-ng-model="newCustomer.city">

    <button data-ng-click="addCustomer()">Add Cutomer</button>

    View 2

And view 2 page

View 2

    City:

    <input type="text" data-ng-model="city">

            {{ cust.name }} - {{ cust.city }}

Do check at the images once.

normal view of page: https://s15.postimg.org/3jrg76nsb/image.png

after clicking view2: https://s7.postimg.org/7xazbqqij/image.png

Body:
Update href to name of route

<a href="#/view2">View 2</a>


问:
converting a curl to a fetch
I'm looking at this influx documentation (https://docs.influxdata.com/influxdb/v1.2/guides/querying_data/) on the api and I can run a curl like this:

```<code>curl -G 'http://10.111.11.11:9050/query?db=sdp_metrics' --data-urlencode "q=select distinct(host) from jmx where time > now() - 180m"
</code>```

I'm trying to convert that structure to a fetch in reactjs but can't seem to get it to work. In react, I have this:

```<code>return fetch('http://10.111.11.11:9050/query?db=sdp_metrics&q=' + 'select distinct(host) from jmx where time > now() - 180m'
            ).then(infltest => { does stuff })
</code>```

the browser comes back with a 200 but I don't get any data back.

答:
Try:</p>

```<code>'http://10.111.11.11:9050/query?db=sdp_metrics&q='
  + encodeURIComponent('select distinct(host) from jmx where time > now() - 180m')
</code>```

Title: converting a curl to a fetch

Body:
I'm looking at this influx documentation (https://docs.influxdata.com/influxdb/v1.2/guides/querying_data/) on the api and I can run a curl like this:

curl -G 'http://10.111.11.11:9050/query?db=sdp_metrics' --data-urlencode "q=select distinct(host) from jmx where time > now() - 180m"

I'm trying to convert that structure to a fetch in reactjs but can't seem to get it to work. In react, I have this:

return fetch('http://10.111.11.11:9050/query?db=sdp_metrics&q=' + 'select distinct(host) from jmx where time > now() - 180m'
            ).then(infltest => { does stuff })

the browser comes back with a 200 but I don't get any data back.

Body:
Try:

'http://10.111.11.11:9050/query?db=sdp_metrics&q='
  + encodeURIComponent('select distinct(host) from jmx where time > now() - 180m')


问:
Trying To Create a Slidebar Menu in IOS
I want to create a slidebar menu in my app (As shown in the image below)

When I click that hamburger icon, it should show a menu as shown below.

I am currently using the SWRevealController, a lib written in Objective C. I created a bridging header and imported the class. This is my current Set up

My initial view which branches to a Menu Controller or the UIViewTable is a SWRevealController, and the segues are subclasses of SWRevealViewControllerSegueSetController. In my Food Item View Controller (the controller where the hamburger navigation exist), I added the following code to activate the slidebar action.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        //Creating the slidebar Navigation using SWRevealViewController
        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

}
</code>```

However, when I click the button, it is still not responding. When I did this with my other application, it worked fine. I am not sure why it is not working here

This is the source I used as reference: http://www.appcoda.com/sidebar-menu-swift/

View Controller Full Code

```<code>@IBOutlet weak var thumbnail_image: UIImageView!
    //@IBOutlet weak var food_detail: UITextView!
    @IBOutlet weak var testing: UILabel!

    @IBOutlet weak var menuButton: UIBarButtonItem!
    var jsonResponseFood: NSArray = NSArray() //API for types of food available
    var jsonResponseRecipe: NSArray = NSArray() // API for recipes in food
    var selectedFood: foodItem?
    var postStr: String?

    //Initializing API
    let FullRecipeAPIModel = fullRecipeAPIModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        //Creating the slidebar Navigation using SWRevealViewController
        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

        print(selectedFood?.name as String!)
        //testing.text = self.selectedFood?.name

        let APIModel = apiModel()

        APIModel.delegate = self
        FullRecipeAPIModel.delegate = self
        APIModel.downloadItems(postString: postStr!)

        // Do any additional setup after loading the view.
    }
</code>```

Thank you StackOverflow.

答: I am also working on this today, is that the best choice available to use SWRevealController, isn't there an Apple built in way of doing this?. I am eager to see options instead of getting something form Github, unless that is my last resort.</p>

Title: Trying To Create a Slidebar Menu in IOS

Body:
I want to create a slidebar menu in my app (As shown in the image below)

When I click that hamburger icon, it should show a menu as shown below.

I am currently using the SWRevealController, a lib written in Objective C. I created a bridging header and imported the class. This is my current Set up

My initial view which branches to a Menu Controller or the UIViewTable is a SWRevealController, and the segues are subclasses of SWRevealViewControllerSegueSetController. In my Food Item View Controller (the controller where the hamburger navigation exist), I added the following code to activate the slidebar action.

override func viewDidLoad() {
        super.viewDidLoad()

        //Creating the slidebar Navigation using SWRevealViewController
        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

}

However, when I click the button, it is still not responding. When I did this with my other application, it worked fine. I am not sure why it is not working here

This is the source I used as reference: http://www.appcoda.com/sidebar-menu-swift/

View Controller Full Code

@IBOutlet weak var thumbnail_image: UIImageView!
    //@IBOutlet weak var food_detail: UITextView!
    @IBOutlet weak var testing: UILabel!

    @IBOutlet weak var menuButton: UIBarButtonItem!
    var jsonResponseFood: NSArray = NSArray() //API for types of food available
    var jsonResponseRecipe: NSArray = NSArray() // API for recipes in food
    var selectedFood: foodItem?
    var postStr: String?

    //Initializing API
    let FullRecipeAPIModel = fullRecipeAPIModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        //Creating the slidebar Navigation using SWRevealViewController
        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }

        print(selectedFood?.name as String!)
        //testing.text = self.selectedFood?.name

        let APIModel = apiModel()

        APIModel.delegate = self
        FullRecipeAPIModel.delegate = self
        APIModel.downloadItems(postString: postStr!)

        // Do any additional setup after loading the view.
    }

Thank you StackOverflow.


问:
Combine RGB colors from several images
I've several images with different color values, each value is 8-bit value.
Every image represents the same frame. I'm trying to sum all images together to get a better picture.
I've tried combining the colors using the average of the colors, however the combined picture is too dark.
Is there a known algorithm that combines the colors?

Thanks

答: You have to average colors of each pixel corresponding to each other. Just sum images to each other and then element-wise divide it by number of images. If you want to take some area from one image and others from other you have to slice your matrices and then fill its values to new empty array or array of zeros.</p>

Title: Combine RGB colors from several images


问:
I need to split an array of data into cells in excel
I have a spreadsheet that queries a data source and returns an array of about 230 rows of comma separated results. The data looks like this:

I need to have all those comma separated values that are now in one cell (column B) split into separate cells. There are typically 21 results for each row. So the result should look like this:

The row the data starts on could vary, but typically starts around row 80. The top rows are used for displaying results from the data below it. The starting point could be fixed at say row 120 (if that makes scripting easier), which would leave plenty of room for future dev.

I've tried modifying a few different solutions I've found on here, but none worked. Any help is supremely appreciated!

答:
I would suggest a very simple way of doing this.

Cut all the comma separated data and paste it into a txt file. In your case it should start from Column B (row 120 or whatever it is)

In data tab, click "From Text" and open your text file

Select delimited with comma separated option and click next

When you click finish, excel asks for the cell in which the data has to be pasted. Give the required cell name that you want your data. In your case it can be B120.

Now you got what you wanted. Better take a backup of your worksheet in case you corrupt the data accidentally


问:
Override default behaviour for link ('a') objects in Javascript
I don't know if what I'm trying to accomplish is possible at all. I would like to override the default behaviour for all the anchor objects (A tag) for a given HTML page. I know I can loop through all the A elements and dynamically add an onclick call to each one of them from the body element onload method, but I'm looking for a more absolute solution. What I need is that all A elements get assigned an onclick action which calls a method that passes the element href property as an argument, so the following:

```<code><a href="http://domain.tld/page.html">
</code>```

Dynamically becomes:

```<code><a href="http://domain.tld/page.html" onclick="someMethodName('http://domain.tld/page.html'); return false;">
</code>```

Like I said, the ideal way to do this would be to somehow override the Anchor class altogether when the document loads. If it's not possible then I'll resort to the loop-through-all A elements method (which I already know how to do).

答:
CMS's solution is the best solution. Be sure to note that you can get better performance if you reference the function or check that needs to be run from a string stored within a protype property set on base anchor/element or declaratively on the anchor/element. By using this property the function you want to call can be found and be called from one decision branch as opposed to writing a new decision branch for every possibility. If you break or use a case statement with more than one or two cases you should start considering this, today may be a good day to spot for inversion of control and injection style of coding.

Again, Do not use a case if there are multiple events you need to handle. Use instead string composition to construct the path to the function that needs to be called. This requires a prototype to be added to your "A" elements that define the default and string to be composed. A data-attribute on the element should be able to override the default. Essentially we just want a message and an action to pass by default and be changed declaritively in the markup. The action specified should be published somewhere as an API or other accessable library function and be callable by lib['funName']. Just give it an attribute, no worry of name or id. The prototype and attribute will be usefull for debounce, because you will have to debounce.

There is some guys working on clientside routers that are trying to perfect this.

Body:
I don't know if what I'm trying to accomplish is possible at all. I would like to override the default behaviour for all the anchor objects (A tag) for a given HTML page. I know I can loop through all the A elements and dynamically add an onclick call to each one of them from the body element onload method, but I'm looking for a more absolute solution. What I need is that all A elements get assigned an onclick action which calls a method that passes the element href property as an argument, so the following:

Dynamically becomes:

Like I said, the ideal way to do this would be to somehow override the Anchor class altogether when the document loads. If it's not possible then I'll resort to the loop-through-all A elements method (which I already know how to do).


问:
SpriteKit not playing audio file?
I have made a custom class, SoundNode, to handle the playing of audio files. For now, it only plays the default "A2.mp3"

```<code>class SoundNode : SKSpriteNode{
func playSound(){
    run(SKAction.playSoundFileNamed("A2", waitForCompletion: false))
    }
}
</code>```

I then call the playSound method in my SKScene like so:

```<code>SoundNode().playSound()
</code>```

But, the sound never plays?? I have made sure the file exists within my project and have also double checked the file name to make sure it is correct. What is the problem here?

答:
SoundNode is a kind of node. Every node only works when it is in a scene. Just creating a SoundNode and calling playSound does not do anything because the node has not been added to the scene!

To make this work, just add it to the scene:

```<code>let node = SoundNode()
self.addChild(node)
node.playSound()
</code>```

Also, I suggest that SoundNode should not inherit SKSpriteNode because it is obviously not a sprite i.e. something that can be seen on screen. Just make it inherit SKNode.

Title: SpriteKit not playing audio file?

Body:
I have made a custom class, SoundNode, to handle the playing of audio files. For now, it only plays the default "A2.mp3"

class SoundNode : SKSpriteNode{
func playSound(){
    run(SKAction.playSoundFileNamed("A2", waitForCompletion: false))
    }
}

I then call the playSound method in my SKScene like so:

SoundNode().playSound()

But, the sound never plays?? I have made sure the file exists within my project and have also double checked the file name to make sure it is correct. What is the problem here?

Body:
SoundNode is a kind of node. Every node only works when it is in a scene. Just creating a SoundNode and calling playSound does not do anything because the node has not been added to the scene!

To make this work, just add it to the scene:

let node = SoundNode()
self.addChild(node)
node.playSound()

Also, I suggest that SoundNode should not inherit SKSpriteNode because it is obviously not a sprite i.e. something that can be seen on screen. Just make it inherit SKNode.


问:
How to access text from a webpage where url does not change after choosing a dropdown value?
I have a website - http://kjc-sv013.kjc.uni-heidelberg.de/dcs/index.php?contents=texte

Upon selecting a text from the dropdown menu, the text appears on screen but the url does not update.

How do I get this text using beautiful soup?

答:
Looking at the source of the webpage I can see you're using AJAX to load content. If you want to change the URL then you either have to navigate to a new URL using window.location or use history rewrite:

```<code>var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
</code>```

Keep in mind that you will need to add some additional hooks so that when the user navigates forward and back, your javascript reloads the content of the page.

https://developer.mozilla.org/en-US/docs/Web/API/History_API

Body:
Looking at the source of the webpage I can see you're using AJAX to load content. If you want to change the URL then you either have to navigate to a new URL using window.location or use history rewrite:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

Keep in mind that you will need to add some additional hooks so that when the user navigates forward and back, your javascript reloads the content of the page.

https://developer.mozilla.org/en-US/docs/Web/API/History_API


问:
Android Studio calling Argos WebService using ksoap Library error
I'm newbie.
Im trying to call the Argos web services from Android Studio.

The url : http://ws-argos.cls.fr/argosDws/services/DixService?wsdl

But when I want to call the function, I'll threw the xml

```<code><soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:typ="http://service.dataxmldistribution.argos.cls.fr/types">
  <soap:Body>
  <typ:xmlRequest>
     <typ:username>*****</typ:username>
     <typ:password>*****</typ:password>
     <typ:platformId>149343</typ:platformId>
     <typ:nbDaysFromNow>10</typ:nbDaysFromNow>
  </typ:xmlRequest>
 </soap:Body>
</soap:Envelope>
</code>```

to http://ws-argos.cls.fr/argosDws/services/DixService?getXml to get the web services responses.
I don't know why but I'll get the web services schema instead of the response if I threw the Xml to http://ws-argos.cls.fr/argosDws/services/DixService?wsdl

In my Android Studio, my code will be

```<code>private static final String SOAP_ACTION = "getXml";
    private static final String NAMESPACE = "http://service.dataxmldistribution.argos.cls.fr/types";
    private static final String MAIN_REQUEST_URL = "http://ws-argos.cls.fr/argosDws/services/DixService?wsdl";

public String getXml(String username, String password, String PlatformId, String nbDaysFromNow) {
        String data = null;
        String methodname = "xmlRequest";

        SoapObject request = new SoapObject(NAMESPACE, methodname);
        request.addProperty("username", username);
        request.addProperty("password", password);
        request.addProperty("platformId", PlatformId);
        request.addProperty("nbDaysFromNow", nbDaysFromNow);

        SoapSerializationEnvelope envelope = getSoapSerializationEnvelope(request);

        HttpTransportSE ht = getHttpTransportSE();
        try {
            ht.call(SOAP_ACTION, envelope);
            SoapPrimitive resultsString = (SoapPrimitive)envelope.getResponse();

            data = resultsString.toString();

        } catch (SocketTimeoutException t) {
            t.printStackTrace();
        } catch (IOException i) {
            i.printStackTrace();
        } catch (Exception q) {
            q.printStackTrace();
        }
        return data;
    }

    private final SoapSerializationEnvelope getSoapSerializationEnvelope(SoapObject request) {
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.implicitTypes = true;
        envelope.setAddAdornments(false);
        envelope.setOutputSoapObject(request);

        return envelope;
    }

    private final HttpTransportSE getHttpTransportSE() {
        HttpTransportSE ht = new HttpTransportSE(Proxy.NO_PROXY,MAIN_REQUEST_URL,60000);
        ht.debug = true;
        return ht;
    }
</code>```

But I always get error on ht.call(SOAP_ACTION, envelope);

```<code>07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ android.os.NetworkOnMainThreadException
07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:215)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at org.ksoap2.transport.ServiceConnectionSE.openOutputStream(ServiceConnectionSE.java:126)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:185)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
07-22 14:02:43.564    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)
</code>```

Is the namespace, main url, soap_action and method name already correct ?
Sorry for my english. I'm not english native.

答:
you should try to pass parameters as below

String methodname = "typ:xmlRequest";

```<code>    SoapObject request = new SoapObject(NAMESPACE, methodname);
    request.addProperty("typ:username", username);
    request.addProperty("typ:password", password);
    request.addProperty("typ:platformId", PlatformId);
    request.addProperty("typ:nbDaysFromNow", nbDaysFromNow);
</code>```

Body:
I'm newbie.
Im trying to call the Argos web services from Android Studio.

The url : http://ws-argos.cls.fr/argosDws/services/DixService?wsdl

But when I want to call the function, I'll threw the xml

<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:typ="http://service.dataxmldistribution.argos.cls.fr/types">
  <soap:Body>
  <typ:xmlRequest>
     <typ:username>*****</typ:username>
     <typ:password>*****</typ:password>
     <typ:platformId>149343</typ:platformId>
     <typ:nbDaysFromNow>10</typ:nbDaysFromNow>
  </typ:xmlRequest>
 </soap:Body>
</soap:Envelope>

to http://ws-argos.cls.fr/argosDws/services/DixService?getXml to get the web services responses.
I don't know why but I'll get the web services schema instead of the response if I threw the Xml to http://ws-argos.cls.fr/argosDws/services/DixService?wsdl

In my Android Studio, my code will be

private static final String SOAP_ACTION = "getXml";
    private static final String NAMESPACE = "http://service.dataxmldistribution.argos.cls.fr/types";
    private static final String MAIN_REQUEST_URL = "http://ws-argos.cls.fr/argosDws/services/DixService?wsdl";

public String getXml(String username, String password, String PlatformId, String nbDaysFromNow) {
        String data = null;
        String methodname = "xmlRequest";

        SoapObject request = new SoapObject(NAMESPACE, methodname);
        request.addProperty("username", username);
        request.addProperty("password", password);
        request.addProperty("platformId", PlatformId);
        request.addProperty("nbDaysFromNow", nbDaysFromNow);

        SoapSerializationEnvelope envelope = getSoapSerializationEnvelope(request);

        HttpTransportSE ht = getHttpTransportSE();
        try {
            ht.call(SOAP_ACTION, envelope);
            SoapPrimitive resultsString = (SoapPrimitive)envelope.getResponse();

            data = resultsString.toString();

        } catch (SocketTimeoutException t) {
            t.printStackTrace();
        } catch (IOException i) {
            i.printStackTrace();
        } catch (Exception q) {
            q.printStackTrace();
        }
        return data;
    }

    private final SoapSerializationEnvelope getSoapSerializationEnvelope(SoapObject request) {
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.implicitTypes = true;
        envelope.setAddAdornments(false);
        envelope.setOutputSoapObject(request);

        return envelope;
    }

    private final HttpTransportSE getHttpTransportSE() {
        HttpTransportSE ht = new HttpTransportSE(Proxy.NO_PROXY,MAIN_REQUEST_URL,60000);
        ht.debug = true;
        return ht;
    }

But I always get error on ht.call(SOAP_ACTION, envelope);

07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ android.os.NetworkOnMainThreadException
07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
07-22 14:02:43.562    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:215)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at org.ksoap2.transport.ServiceConnectionSE.openOutputStream(ServiceConnectionSE.java:126)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:185)
07-22 14:02:43.563    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
07-22 14:02:43.564    2846-2846/com.ecocean.ecoceansharkrace W/System.err﹕ at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)

Is the namespace, main url, soap_action and method name already correct ?
Sorry for my english. I'm not english native.

Body:
you should try to pass parameters as below

String methodname = "typ:xmlRequest";

    SoapObject request = new SoapObject(NAMESPACE, methodname);
    request.addProperty("typ:username", username);
    request.addProperty("typ:password", password);
    request.addProperty("typ:platformId", PlatformId);
    request.addProperty("typ:nbDaysFromNow", nbDaysFromNow);


问:
When is it appropriate to use synchronous ajax?
I was just reading another question about jQuery's synchronous ajax call, and I got to wondering:

What circumstances make a synchronous version of an ajax call beneficial/necessary?

Ideally I'd like an example, and why synchronous is better than standard ajax.

答:
synchronous ajax is often used to retrieve a valued from the server which is required to further continue processing of client side code. in such case, the ajax call will block until the call returns with the desired value. example:

a javascript function needs to compute salary for an employee:
step1 : get the employee id from the form
step2 : make a sync server call passing the emp.id to get his salary/hour
step3 : multiply salary rate by number of working hours

as you can see, total salary cannot be computed unless the server call is finished so this should be a sync function, although if using jquery, one could handle onSuccess to compute the salary asynchronously but processing will continue in this if you have a message box to display the salary, it will appear empty...


问:
How to insert value using textfield to get data in sqlite using appcelerator
I beginner in using appcelerator to develop android apps. I tried to insert data using textfield to retrieve data in sqlite. but if I use example "doc_num.value" with query. I will get error "[ERROR] :  V8Exception: Exception occurred at test/csv.js:61: Uncaught TypeError: Cannot read property 'value' of undefined"

```<code>var currentWin = Ti.UI.currentWindow;

var label_export = Ti.UI.createLabel({
color:'#fffdfd',
text: 'Please insert document number to export :',
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
top: 20, //200
width: 300,
font:{fontFamily:'Arial',fontSize:14}
});

currentWin.add(label_export);

var doc_num = Ti.UI.createTextField({
color:'#fffdfd',
top:60,
left:10,
width:'80%',
height:40,
hintText:'Document Number',
keyboardType:Ti.UI.KEYBOARD_DEFAULT,
borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
currentWin.add(doc_num);

// btn search
var btn_search = Ti.UI.createButton({
title:'Export CSV',
top:55, //355
right:5,
width:'15%',
height:50,
color:'green',
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:8}

});

btn_search.addEventListener('click',function(e) {

var db = Ti.Database.install('../products.sqlite','products');
var dbName = db.execute('SELECT doc_num,barcode,    product_name,oum,rack_loc,qty FROM products WHERE doc_num = ?',doc_num.value);
while (dbName.isValidRow()) {

var doc_num = dbName.fieldByName('doc_num');
var barcode = dbName.fieldByName('barcode');
var product_name = dbName.fieldByName('product_name');
var rack_loc = dbName.fieldByName('rack_loc');
var oum = dbName.fieldByName('oum');
var qty = dbName.fieldByName('qty');
dbName.next();
Ti.API.info(doc_num + ' ' + barcode + ' ' + product_name+' ' + rack_loc +' '+ oum +' '+qty);

}

dbName.close();
});

currentWin.add(label_warning);

currentWin.add(btn_search);
</code>```

And this my table structure that I use for my database.Database name products and tape name also products

CREATE TABLE products (id INTEGER PRIMARY KEY, doc_num VARCHAR, product_name VARCHAR, barcode VARCHAR, rack_loc VARCHAR, oum VARCHAR, qty NUMERIC)

答:
You just need to use this line of code instead of yours:

```<code>var dbName = db.execute('SELECT doc_num,barcode, product_name,oum,rack_loc,qty FROM products WHERE doc_num = ?', doc_num.value);
</code>```

You cannot concatenate strings in execute method, you will need to standard approach of passing parameters in SQL query using '?' sign.

Also note that you cannot do this something like this also:

```<code>var query = 'select * from products where doc_num = ' + doc_num.value;
</code>```

This query will fail in case where there are spaces in doc_num.value

So the recommended and safest way of passing values to queries is this:

```<code>var query = 'select * from products where doc_num = ? and someother_condition = ?';
db.execute(query, doc_num.value, someother_value);
</code>```

db.execute method can take any number of parameters starting from 2nd parameter.

Body:
I beginner in using appcelerator to develop android apps. I tried to insert data using textfield to retrieve data in sqlite. but if I use example "doc_num.value" with query. I will get error "[ERROR] :  V8Exception: Exception occurred at test/csv.js:61: Uncaught TypeError: Cannot read property 'value' of undefined"

var currentWin = Ti.UI.currentWindow;

var label_export = Ti.UI.createLabel({
color:'#fffdfd',
text: 'Please insert document number to export :',
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
top: 20, //200
width: 300,
font:{fontFamily:'Arial',fontSize:14}
});

currentWin.add(label_export);

var doc_num = Ti.UI.createTextField({
color:'#fffdfd',
top:60,
left:10,
width:'80%',
height:40,
hintText:'Document Number',
keyboardType:Ti.UI.KEYBOARD_DEFAULT,
borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
currentWin.add(doc_num);

// btn search
var btn_search = Ti.UI.createButton({
title:'Export CSV',
top:55, //355
right:5,
width:'15%',
height:50,
color:'green',
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:8}

});

btn_search.addEventListener('click',function(e) {

var db = Ti.Database.install('../products.sqlite','products');
var dbName = db.execute('SELECT doc_num,barcode,    product_name,oum,rack_loc,qty FROM products WHERE doc_num = ?',doc_num.value);
while (dbName.isValidRow()) {

var doc_num = dbName.fieldByName('doc_num');
var barcode = dbName.fieldByName('barcode');
var product_name = dbName.fieldByName('product_name');
var rack_loc = dbName.fieldByName('rack_loc');
var oum = dbName.fieldByName('oum');
var qty = dbName.fieldByName('qty');
dbName.next();
Ti.API.info(doc_num + ' ' + barcode + ' ' + product_name+' ' + rack_loc +' '+ oum +' '+qty);

}

dbName.close();
});

currentWin.add(label_warning);

currentWin.add(btn_search);

And this my table structure that I use for my database.Database name products and tape name also products

CREATE TABLE products (id INTEGER PRIMARY KEY, doc_num VARCHAR, product_name VARCHAR, barcode VARCHAR, rack_loc VARCHAR, oum VARCHAR, qty NUMERIC)

Body:
You just need to use this line of code instead of yours:

var dbName = db.execute('SELECT doc_num,barcode, product_name,oum,rack_loc,qty FROM products WHERE doc_num = ?', doc_num.value);

You cannot concatenate strings in execute method, you will need to standard approach of passing parameters in SQL query using '?' sign.

Also note that you cannot do this something like this also:

var query = 'select * from products where doc_num = ' + doc_num.value;

This query will fail in case where there are spaces in doc_num.value

So the recommended and safest way of passing values to queries is this:

var query = 'select * from products where doc_num = ? and someother_condition = ?';
db.execute(query, doc_num.value, someother_value);

db.execute method can take any number of parameters starting from 2nd parameter.


答:
Your view2 inside the view1.html should be the name of the route

```<code> <a href="#/view2">View 2</a>
</code>```

DEMO

Title: Not able to redirect page using Angular Routing

Body:
Your view2 inside the view1.html should be the name of the route

 <a href="#/view2">View 2</a>

DEMO


问:
Where in memory the const function parameters are stored in C?
Where in memory are the const function parameters stored in C?

Generally the parameters are stored on the stack, but if the parameter is declared const then where it is stored?

答:
const keyword means that data with this keyword won't be able to modify content.

For example, if function has parameter with const:

```<code>void my_func(const char c) {
    //Do things
    //This is prohibited and will cause error:
    c = 3;
}

//Function call
char a = 'a';   //This is stored on RAM somewhere (if inside function, then it is on stack)
my_func(a); //Call function, value of a is pushed to stack.
</code>```

This function cannot change value of c inside.

If you have global variable with const parameter, then some compiler will put it to FLASH memory (non-volatile) memory. This happens on embedded systems mostly, but it is not sure that will actually happen.

```<code>//This is stored either on RAM or on non-volatile memory (FLASH)
const char str[] = "My string which cannot be modified later";
int main(void) {
   //...your code
   //This is prohibited:
   str[2] = 3; //Error!
}
</code>```

This str is constant and is not able to be modified. Now, modern compilers (ARM compilers) will put this to flash memory, on AVR, this might now happen. There you have to add PROGMEM keyword of GCC for AVR.

Body:
const keyword means that data with this keyword won't be able to modify content.

For example, if function has parameter with const:

void my_func(const char c) {
    //Do things
    //This is prohibited and will cause error:
    c = 3;
}

//Function call
char a = 'a';   //This is stored on RAM somewhere (if inside function, then it is on stack)
my_func(a); //Call function, value of a is pushed to stack.

This function cannot change value of c inside.

If you have global variable with const parameter, then some compiler will put it to FLASH memory (non-volatile) memory. This happens on embedded systems mostly, but it is not sure that will actually happen.

//This is stored either on RAM or on non-volatile memory (FLASH)
const char str[] = "My string which cannot be modified later";
int main(void) {
   //...your code
   //This is prohibited:
   str[2] = 3; //Error!
}

This str is constant and is not able to be modified. Now, modern compilers (ARM compilers) will put this to flash memory, on AVR, this might now happen. There you have to add PROGMEM keyword of GCC for AVR.


问:
how to speed up NE recognition with stanford NER with python nltk
First I tokenize the file content into sentences and then call Stanford NER on each of the sentences. But this process is really slow. I know if I call it on the whole file content if would be faster, but I'm calling it on each sentence as I want to index each sentence before and after NE recognition.

```<code>st = NERTagger('stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz', 'stanford-ner/stanford-ner.jar')
for filename in filelist:
    sentences = sent_tokenize(filecontent) #break file content into sentences
    for j,sent in enumerate(sentences):
        words = word_tokenize(sent) #tokenize sentences into words
        ne_tags = st.tag(words) #get tagged NEs from Stanford NER
</code>```

This is probably due to calling st.tag() for each sentence, but is there any way to make it run faster?

EDIT

The reason that I want to tag sentences separate is that I want to write sentences to a file (like sentence indexing) so that given the ne tagged sentence at a later stage, i can get the unprocessed sentence (i'm also doing lemmatizing here)

file format:

(sent_number, orig_sentence, NE_and_lemmatized_sentence)

答:
you can use stanford ner server.
The speed will be much faster.

install sner

pip install sner
```

<p>run ner server
<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>cd your_stanford_ner_dir
java -Djava.ext.dirs=./lib -cp stanford-ner.jar edu.stanford.nlp.ie.NERServer -port 9199 -loadClassifier ./classifiers/english.all.3class.distsim.crf.ser.gz</code>```

from sner import Ner

test_string = "Alice went to the Museum of Natural History."
tagger = Ner(host='localhost',port=9199)
print(tagger.get_entities(test_string))```
</div>
</div>
</p>

<p>this code result is</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>[('Alice', 'PERSON'),
 ('went', 'O'),
 ('to', 'O'),
 ('the', 'O'),
 ('Museum', 'ORGANIZATION'),
 ('of', 'ORGANIZATION'),
 ('Natural', 'ORGANIZATION'),
 ('History', 'ORGANIZATION'),
 ('.', 'O')]</code>```

more detail to look https://github.com/caihaoyu/sner

Body:
First I tokenize the file content into sentences and then call Stanford NER on each of the sentences. But this process is really slow. I know if I call it on the whole file content if would be faster, but I'm calling it on each sentence as I want to index each sentence before and after NE recognition.

st = NERTagger('stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz', 'stanford-ner/stanford-ner.jar')
for filename in filelist:
    sentences = sent_tokenize(filecontent) #break file content into sentences
    for j,sent in enumerate(sentences):
        words = word_tokenize(sent) #tokenize sentences into words
        ne_tags = st.tag(words) #get tagged NEs from Stanford NER

This is probably due to calling st.tag() for each sentence, but is there any way to make it run faster?

EDIT

The reason that I want to tag sentences separate is that I want to write sentences to a file (like sentence indexing) so that given the ne tagged sentence at a later stage, i can get the unprocessed sentence (i'm also doing lemmatizing here)

file format:

(sent_number, orig_sentence, NE_and_lemmatized_sentence)

Body:
you can use stanford ner server.
The speed will be much faster.

install sner

pip install sner

run ner server

cd your_stanford_ner_dir
java -Djava.ext.dirs=./lib -cp stanford-ner.jar edu.stanford.nlp.ie.NERServer -port 9199 -loadClassifier ./classifiers/english.all.3class.distsim.crf.ser.gz

from sner import Ner

test_string = "Alice went to the Museum of Natural History."
tagger = Ner(host='localhost',port=9199)
print(tagger.get_entities(test_string))

this code result is

[('Alice', 'PERSON'),
 ('went', 'O'),
 ('to', 'O'),
 ('the', 'O'),
 ('Museum', 'ORGANIZATION'),
 ('of', 'ORGANIZATION'),
 ('Natural', 'ORGANIZATION'),
 ('History', 'ORGANIZATION'),
 ('.', 'O')]

more detail to look https://github.com/caihaoyu/sner


问:
A local or parameter named 'ContactForm' cannot be declared in this scope because
I have created a partial view containing a quick contact form.
The contact form should be rendered from the _Layout, without passing a model, like so

```<code> @Html.Partial("_QuickContact")
</code>```

Within the _QuickContact view i thought of declaring a variable like so

```<code>@{ContactForm ContactForm = new ContactForm();}
</code>```

so i can i use it as

```<code> <div>
    @Html.TextBoxFor(ContactForm => ContactForm.Email)
    @Html.ValidationMessageFor(ContactFormm => ContactForm.Email)
 </div>
</code>```

since i would not like to pass a model at it. (This approach if i am not mistaken, would require tuples or a wrapper containing multiple models).

Unfortunately i get the error

A local or parameter named 'ContactForm' cannot be declared in this
  scope because that name is used in an enclosing local scope to define
  a local or parameter

Is there any work around for this?

答:
You model needs a @model ContactForm declaration, and then you can use @Html.TextBoxFor(m => m.Email) etc.

However because you calling this using @Html.Partial(), you need to pass a model (which can be a default instance) to the partial, otherwise the model in the main view will be passed and an exception will be thrown.

```<code>@Html.Partial("_QuickContact", new ContactForm())
</code>```

The alternative would be to use a Html.Action() to call a server method that returns your partial, for example

```<code>[ChildActionOnly]
public PartialViewResult Contact
{
    return PartialView("_QuickContact"); // or return PartialView("_QuickContact", new ContactForm());
}
</code>```

and in the layout

```<code>@Html.Action("Contact") // or @{ Html.RenderAction("Contact"); }
</code>```

Body:
I have created a partial view containing a quick contact form.
The contact form should be rendered from the _Layout, without passing a model, like so

 @Html.Partial("_QuickContact")

Within the _QuickContact view i thought of declaring a variable like so

@{ContactForm ContactForm = new ContactForm();}

so i can i use it as

    @Html.TextBoxFor(ContactForm => ContactForm.Email)
    @Html.ValidationMessageFor(ContactFormm => ContactForm.Email)

since i would not like to pass a model at it. (This approach if i am not mistaken, would require tuples or a wrapper containing multiple models).

Unfortunately i get the error

A local or parameter named 'ContactForm' cannot be declared in this
  scope because that name is used in an enclosing local scope to define
  a local or parameter

Is there any work around for this?

Body:
You model needs a @model ContactForm declaration, and then you can use @Html.TextBoxFor(m => m.Email) etc.

However because you calling this using @Html.Partial(), you need to pass a model (which can be a default instance) to the partial, otherwise the model in the main view will be passed and an exception will be thrown.

@Html.Partial("_QuickContact", new ContactForm())

The alternative would be to use a Html.Action() to call a server method that returns your partial, for example

[ChildActionOnly]
public PartialViewResult Contact
{
    return PartialView("_QuickContact"); // or return PartialView("_QuickContact", new ContactForm());
}

and in the layout

@Html.Action("Contact") // or @{ Html.RenderAction("Contact"); }


问:
Asset management in yii2
I have the code like this:

```<code>class BootBoxAsset extends AssetBundle
{
    public $sourcePath = '@vendor/almasaeed2010/adminlte';

    public $css = [
    ];

    public $js = [
        'https://cdn.bootcss.com/bootbox.js/4.4.0/bootbox.js'
    ];

    public $depends = [
        'plugins\jQuery\jquery-2.2.3.min.js',
        'bootstrap\js\bootstrap.min.js',
    ];

    public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
}
</code>```

As the code shows above, I want to use bootbox.js which requires the related jquery and bootstrap dependency that located in my $sourcePath variable combined with the directories in $depends array,
when I register this asset in my view, there's an error tells me that the Class plugins\jQuery\jquery-2.2.3.min.js does not exist, so what should I do to register the dependency not start from yii directory?
thanks!

答:
this mean that you have wrong path for
your dependency

```<code>  public $depends = [
    'yii\web\YiiAsset',
    'yii\bootstrap\BootstrapAsset',
];
</code>```

then check for proper path

but for these assets you could use

```<code>public $depends = [
    'yii\web\YiiAsset',
    'yii\bootstrap\BootstrapAsset',
];
</code>```

Title: Asset management in yii2

Body:
I have the code like this:

class BootBoxAsset extends AssetBundle
{
    public $sourcePath = '@vendor/almasaeed2010/adminlte';

    public $css = [
    ];

    public $js = [
        'https://cdn.bootcss.com/bootbox.js/4.4.0/bootbox.js'
    ];

    public $depends = [
        'plugins\jQuery\jquery-2.2.3.min.js',
        'bootstrap\js\bootstrap.min.js',
    ];

    public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
}

As the code shows above, I want to use bootbox.js which requires the related jquery and bootstrap dependency that located in my $sourcePath variable combined with the directories in $depends array,
when I register this asset in my view, there's an error tells me that the Class plugins\jQuery\jquery-2.2.3.min.js does not exist, so what should I do to register the dependency not start from yii directory?
thanks!

Body:
this mean that you have wrong path for
your dependency

  public $depends = [
    'yii\web\YiiAsset',
    'yii\bootstrap\BootstrapAsset',
];

then check for proper path

but for these assets you could use

public $depends = [
    'yii\web\YiiAsset',
    'yii\bootstrap\BootstrapAsset',
];


问:
jQuery: any suggestions how to preload all images in dom sequentially?
any ideas about it? any plugin? I want find all img tag and show them sequentially?
thank you</p>

答: Go through this</p>

Body: Go through this


问:
express not responding to route
I am using nodejs and express for api end points, I am using app.use to handle a route, but it is not responding no matter what I do.

```<code>var express = require("express");
var mongoose = require('mongoose');
var path = require("path");
var favicon = require("serve-favicon");
var http = require('http');

var app = express();

var config = require('./conf/config');

var PORT = config.PORT;

mongoose.connect(config.MONGODB);

//route handlers

app.use('/', function(req, res) {
    console.log("Hello");
});

var server = http.createServer(function(req, res) {
    console.log("Request received", req.url);
});

server.listen(PORT);
console.log("Server running on port", PORT);
</code>```

It should print hello on console whenever I request on root route i.e. / but it's not doing anything.

答:
Your Express code is not correct.  You are creating a plain web server, but that web server is not hooked up to Express in any way.  If you aren't trying to create any special kind of server (like an https server), then you can just let Express create the server for you with app.listen(PORT) and then it will create a server and hook itself up to that server.

I would suggest this:

```<code>var express = require("express");
var mongoose = require('mongoose');
var path = require("path");
var favicon = require("serve-favicon");

var app = express();

var config = require('./conf/config');
var PORT = config.PORT;

mongoose.connect(config.MONGODB);

//route handlers

app.get('/', function(req, res) {
    console.log("Hello");
    res.send("Hello");
});

app.listen(PORT);
console.log("Server running on port", PORT);
</code>```

Note: I changed a couple other things too.  I switched to app.get() and I inserted a res.send() since you need to always send some kind of response of the browser will just wait and wait for something to come back.

Title: express not responding to route

Body:
I am using nodejs and express for api end points, I am using app.use to handle a route, but it is not responding no matter what I do.

var express = require("express");
var mongoose = require('mongoose');
var path = require("path");
var favicon = require("serve-favicon");
var http = require('http');

var app = express();

var config = require('./conf/config');

var PORT = config.PORT;

mongoose.connect(config.MONGODB);

//route handlers

app.use('/', function(req, res) {
    console.log("Hello");
});

var server = http.createServer(function(req, res) {
    console.log("Request received", req.url);
});

server.listen(PORT);
console.log("Server running on port", PORT);

It should print hello on console whenever I request on root route i.e. / but it's not doing anything.

Body:
Your Express code is not correct.  You are creating a plain web server, but that web server is not hooked up to Express in any way.  If you aren't trying to create any special kind of server (like an https server), then you can just let Express create the server for you with app.listen(PORT) and then it will create a server and hook itself up to that server.

I would suggest this:

var express = require("express");
var mongoose = require('mongoose');
var path = require("path");
var favicon = require("serve-favicon");

var app = express();

var config = require('./conf/config');
var PORT = config.PORT;

mongoose.connect(config.MONGODB);

//route handlers

app.get('/', function(req, res) {
    console.log("Hello");
    res.send("Hello");
});

app.listen(PORT);
console.log("Server running on port", PORT);

Note: I changed a couple other things too.  I switched to app.get() and I inserted a res.send() since you need to always send some kind of response of the browser will just wait and wait for something to come back.


答: Try using app.get instead of app.use, as well. The latter is used for mounting sub-routes, using middleware etc. but not for actually configuring request handlers.

Title: express not responding to route


问:
Using match .. case in scala
I might sound silly but I am new to scala so please bear with me.
I am little confused about using switch case in scala. As per the example of finding the last element of a list

what is the letter 'h' and 'k' is doing ? In short if somebody can explain the below, I will be very grateful.

```<code>def recLast[A](ls: List[A]): A = ls match {
    case h :: Nil => h
    case b :: rest => recLast(rest)
}
</code>```

答:
the case statement does pattern matching  if the list has one element (i.e. it is  :: Nil it would be matched for the first case and  would be assigned to h the latter case does the same thing and also assigned the rest (tail) to "rest"

you can also see this pattern matching if you write the following in the REPL

```<code>scala> val h :: rest = List(1,2,3,4)
h: Int = 1
rest: List[Int] = List(2, 3, 4)
</code>```

Title: Using match .. case in scala

Body:
I might sound silly but I am new to scala so please bear with me.
I am little confused about using switch case in scala. As per the example of finding the last element of a list

what is the letter 'h' and 'k' is doing ? In short if somebody can explain the below, I will be very grateful.

def recLast[A](ls: List[A]): A = ls match {
    case h :: Nil => h
    case b :: rest => recLast(rest)
}

Body:
the case statement does pattern matching  if the list has one element (i.e. it is  :: Nil it would be matched for the first case and  would be assigned to h the latter case does the same thing and also assigned the rest (tail) to "rest"

you can also see this pattern matching if you write the following in the REPL

scala> val h :: rest = List(1,2,3,4)
h: Int = 1
rest: List[Int] = List(2, 3, 4)


问:
CSS: How to make a background-image appear within a div without setting a fixed height
I have made the following layout:

html,
body {
  height: 100%;
}

.header {
  height: 120px;
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />
<div class="row">
  <div class="columns small-12 header"></div>
</div></code>```

It works because I have used a height-property with a fixed pixel-value.

If one removes that the image disappears:

html,
body {
  height: 100%;
}

.header {
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />
<div class="row">
  <div class="columns small-12 header"></div>
</div></code>```

One of the problems with using that fixed height is that responsiveness can't be accomplished.

How can I make the background appear without having to use a fixed height?
Or should I fall back to using img-tag instead?

There the height is determined by the image-sizes itself.

答:
Currently, your .header doesn't have any content, and thus its height is actually 0px....

To change that, you can either put content into your .header like: text, images... OR give it height via css, either static (in px), or dynamic (via '%', or 'vh'...)

Body:
I have made the following layout:

html,
body {
  height: 100%;
}

.header {
  height: 120px;
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />

It works because I have used a height-property with a fixed pixel-value.

If one removes that the image disappears:

html,
body {
  height: 100%;
}

.header {
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />

One of the problems with using that fixed height is that responsiveness can't be accomplished.

How can I make the background appear without having to use a fixed height?
Or should I fall back to using img-tag instead?

There the height is determined by the image-sizes itself.


问:
Free alternative to SoundBooth for adding cue-points into MP3 for Flash?
Is there a free alternative to Soundbooth for adding cue-points to audio tracks for use in Flash? I seem to remember that you can add them to the file itself (I think). I know you can do this with FLV.

Just checking before I buy SB..

答:
u can only embedd cue point into flv files not mp3.

Ive also noticed that flash itself can"t read those points properly !!! Make sure u test it before buying it


问:
C++Builder 10.2 - Debugging breakpoints not working for my BPL IDE-package
I'm trying to debug an IDE design-time package in C++Builder 10.2 Tokyo and although the package itself works, I can't get no breakpoint to work:

Just no blue markers and only red'x'es when double clicking in the editor breakpoint column...

The project options I set for Debug:

Debugger → Host Application: C:\Program Files (x86)\Embarcadero\Studio\19.0\bin\bds.exe

Debugger → Parameters: -rNameOfMyBpl

C++ Compiler → Debugging → Debug information: True

C++ Compiler → Debugging → Debug line number information: True

C++ Compiler → Optimizations → Disable all optimizations: True

C++ Compiler → Optimizations → Generate fastest possible code: False

C++ Linker → Full Debug information: True

Delphi Compiler → Optimization: False

Delphi Compiler → Use debug .dcus: True

When manually triggering a breakpoint by

```<code>{ _asm { int 3 } }
</code>```

it breaks and the IDE switches to assembly view, so what am I doing wrong here?

答:
Thanks for the comments, but it seems to be a bug in RAD Studio

https://quality.embarcadero.com/browse/RSP-16491?filter=-2

Body:
I'm trying to debug an IDE design-time package in C++Builder 10.2 Tokyo and although the package itself works, I can't get no breakpoint to work:

Just no blue markers and only red'x'es when double clicking in the editor breakpoint column...

The project options I set for Debug:

Debugger → Host Application: C:\Program Files (x86)\Embarcadero\Studio\19.0\bin\bds.exe

Debugger → Parameters: -rNameOfMyBpl

C++ Compiler → Debugging → Debug information: True

C++ Compiler → Debugging → Debug line number information: True

C++ Compiler → Optimizations → Disable all optimizations: True

C++ Compiler → Optimizations → Generate fastest possible code: False

C++ Linker → Full Debug information: True

Delphi Compiler → Optimization: False

Delphi Compiler → Use debug .dcus: True

When manually triggering a breakpoint by

{ _asm { int 3 } }

it breaks and the IDE switches to assembly view, so what am I doing wrong here?


问:
How can i make django-rest-framework-jwt return token on registration?
I have a basic django rest service, which

registers a person and

updates his password.

I want to add jwt authentication on top of it. If I follow the tutorial I would need to add a new url named "api-token-auth" in project's urls.py. But, I don't want to add this new url and want my register call to send a token in response.

Here's my code:

serializers.py

```<code>class UserSerializer(serializers.HyperlinkedModelSerializer):
    def create(self, validated_data):
        user = User(
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

    def update(self, instance, validated_data):
        instance.set_password(validated_data['password'])
        instance.save()
        return instance

    class Meta:
        model = User
        fields = ('url', 'username', 'password')
        lookup_field = 'username'
        write_only_fields = ('password',)
</code>```

views.py

```<code>class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.exclude(is_superuser=1)
    serializer_class = UserSerializer
    lookup_field = 'username'
</code>```

What should be done to achieve this ? should I call api-auth-token inside my serializer's create method ?

How does django-rest-framework-jwt handles multiple authentication tokens and correctly identifies which token belongs to which user ? Especially when it doesn't store tokens in a db.

How can I use this authentication mechanism to limit my user to view/update/delete only his user ?

How can I use this authentication mechanism to do anything in general. For instance if a user wants to write his name to /tmp/abcd.txt. How can I make sure that only authenticated users would be able to do so ?

Are there any potential loopholes in this approach. Should I use the same code if my app is going to store lots of classified data ?

答:
The Accepted answer has some code that generates token but it doesn't show how to integrate it in serializer/view. Also not sure that manual jwt.encode is a good modern way of doing this if we already have jwt_encode_handler
to do this. You can create SerializerMethodField and create tokens there:

```<code>token = serializers.SerializerMethodField()

def get_token(self, obj):
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

    payload = jwt_payload_handler(obj)
    token = jwt_encode_handler(payload)
    return token
</code>```

Then add token field to Meta.fields.

Working Example

Body:
I have a basic django rest service, which

registers a person and

updates his password.

I want to add jwt authentication on top of it. If I follow the tutorial I would need to add a new url named "api-token-auth" in project's urls.py. But, I don't want to add this new url and want my register call to send a token in response.

Here's my code:

serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    def create(self, validated_data):
        user = User(
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

    def update(self, instance, validated_data):
        instance.set_password(validated_data['password'])
        instance.save()
        return instance

    class Meta:
        model = User
        fields = ('url', 'username', 'password')
        lookup_field = 'username'
        write_only_fields = ('password',)

views.py

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.exclude(is_superuser=1)
    serializer_class = UserSerializer
    lookup_field = 'username'

What should be done to achieve this ? should I call api-auth-token inside my serializer's create method ?

How does django-rest-framework-jwt handles multiple authentication tokens and correctly identifies which token belongs to which user ? Especially when it doesn't store tokens in a db.

How can I use this authentication mechanism to limit my user to view/update/delete only his user ?

How can I use this authentication mechanism to do anything in general. For instance if a user wants to write his name to /tmp/abcd.txt. How can I make sure that only authenticated users would be able to do so ?

Are there any potential loopholes in this approach. Should I use the same code if my app is going to store lots of classified data ?

Body:
The Accepted answer has some code that generates token but it doesn't show how to integrate it in serializer/view. Also not sure that manual jwt.encode is a good modern way of doing this if we already have jwt_encode_handler
to do this. You can create SerializerMethodField and create tokens there:

token = serializers.SerializerMethodField()

def get_token(self, obj):
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

    payload = jwt_payload_handler(obj)
    token = jwt_encode_handler(payload)
    return token

Then add token field to Meta.fields.

Working Example


问:
Full Template Specialization errors
Since I am SIMD'ifying my code I decided to use template specialization to handle each type case but it seems I did something wrong.

```<code>template<typename T> struct __declspec(align(16)) TVec2
{
};

template<> __declspec(align(16)) struct TVec2<s64>
{
    union
    {
        struct
        {
            s64 x, y;
        };
        struct
        {
            __m128i v;
        };
    };
    TVec2()
    {
        v = _mm_setzero_si128();
    }
    TVec2(s64 scalar)
    {
        v = _mm_set_epi64x(scalar, scalar);
    }
    TVec2(s64 x, s64 y)
    {
        v = _mm_set_epi64x(x, y);
    }
    template<typename U> operator TVec2<U>() const
    {
        return TVec2<U>(static_cast<U>(x), static_cast<U>(y));
    }
    s64& operator[](word index)
    {
        return v.m128i_i64[index];
    }
    const s64& operator[](word index) const
    {
        return v.m128i_i64[index];
    }
};
// There are other specializations but they produce the same errors
</code>```

When I compile in Visual Studio (2015) I get (C2988: unrecognizeable template declaration/definition) followed by (C2059: syntax error: "< end Parse >"). I am fairly sure I followed the documentation for specialization correctly but I am prone to errors.

答:
It looks like the problem is caused by __declspec written before structure keyword so template is not recognized properly. Try changing to

```<code>template<> struct __declspec(align(16)) TVec2<s64>
</code>```

It may be also a good idea to use alignas specifier and get rid of nameless struct/union.

Title: Full Template Specialization errors

Body:
Since I am SIMD'ifying my code I decided to use template specialization to handle each type case but it seems I did something wrong.

template<typename T> struct __declspec(align(16)) TVec2
{
};

template<> __declspec(align(16)) struct TVec2<s64>
{
    union
    {
        struct
        {
            s64 x, y;
        };
        struct
        {
            __m128i v;
        };
    };
    TVec2()
    {
        v = _mm_setzero_si128();
    }
    TVec2(s64 scalar)
    {
        v = _mm_set_epi64x(scalar, scalar);
    }
    TVec2(s64 x, s64 y)
    {
        v = _mm_set_epi64x(x, y);
    }
    template<typename U> operator TVec2() const
    {
        return TVec2(static_cast(x), static_cast(y));
    }
    s64& operator[](word index)
    {
        return v.m128i_i64[index];
    }
    const s64& operator[](word index) const
    {
        return v.m128i_i64[index];
    }
};
// There are other specializations but they produce the same errors

When I compile in Visual Studio (2015) I get (C2988: unrecognizeable template declaration/definition) followed by (C2059: syntax error: "< end Parse >"). I am fairly sure I followed the documentation for specialization correctly but I am prone to errors.

Body:
It looks like the problem is caused by __declspec written before structure keyword so template is not recognized properly. Try changing to

template<> struct __declspec(align(16)) TVec2<s64>

It may be also a good idea to use alignas specifier and get rid of nameless struct/union.