问:
Searching for pattern string in a long sequence without arrays
I wanted to ask how can I search for two patterns (such as RFMKCR and AWY) in a long input of different characters using getchar()?

P.S It is not allowed to use arrays.
Thanks!

答:
This is complete code for the state machine which gets input from generic function getchar1(). Patterns: AWY and RFMKCR are recognized and reported.

Function getchar1() is just a wrapper for any function which gets a char from the input.  getchar() or scanf can be used inside it. Char defined by the   STOP terminates input processing.

Difficulties for this problem come from the need to hunt for the beginning of two patterns: AWY and RFMKCR at the same time. We may be forced to switch to hunt for the different pattern in the middle of another one or to re-synchronize.

Three complete solutions are given.

First solution use recursion.

Second solution use a simple goto constructs avoiding recursive calls. This approach works very well for this particular problem.

Note: The usage of goto is typically discouraged in C.
It is good programming style to use the break, continue, and return statement in preference to goto whenever possible. Since the break statement only exits from one level of the loop, a goto may be necessary for exiting a loop from within a deeply nested loop.

Third solution does not use recursion or goto statements and tries to show a generic approach which can be easily adapted to different patterns.

Solution 1)

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

#define STOP    '!'

int START(void);
int AWY(void);
int RFMKCR(void);
int END(void);

int getchar1 (void)
{
  char in;
  in = getchar(); // scanf ("%c", &in);
  return in;
}

int START(void)
{
  int c = getchar1 ();
  if (c == 'A')    return AWY();
  if (c == 'R')    return RFMKCR();
  if (c == STOP)   return END();
  return 1;
}

int AWY(void)   // A already found
{
  int c = getchar1 ();
  if (c == 'A')    return AWY();
  if (c == 'R')    return RFMKCR();
  if (c == STOP)   return END();
  if (c != 'W')    return 1;
  // W found

  c = getchar1 ();
  if (c == 'A')    return AWY();
  if (c == 'R')    return RFMKCR();
  if (c == STOP)   return END();
  if (c != 'Y')    return 1;
  // Y found

  printf ("AWY found\n");
  return 1;
}

int RFMKCR(void)    // R already found
{
  int c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == 'R')     return RFMKCR();
  if (c == STOP)    return END();
  if (c != 'F')     return 1;
  // F found

  c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == 'R')     return RFMKCR();
  if (c == STOP)    return END();
  if (c != 'M')     return 1;
  // M found

  c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == 'R')     return RFMKCR();
  if (c == STOP)    return END();
  if (c != 'K')     return 1;
  // K found

  c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == 'R')     return RFMKCR();
  if (c == STOP)    return END();
  if (c != 'C')     return 1;
  // C found
  c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == STOP)    return END();
  if (c != 'R')     return 1;
  // R found

  printf ("RFMKCR found\n");
  return 1;
}

int END(void)
{
  return 0;
}

int main ()
{
  printf ("\n*start*\n");
  while(START());
  printf ("*the end*\n");
  return 0;
}
</code>```

Solution 2)

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

#define STOP '!'

int START()
{
int c;

START:
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  goto START;

AWY:                // A found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  if (c != 'W')    goto START;
  // W found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  if (c != 'Y')    goto START;
  // Y found
  printf ("AWY found\n");
  goto START;

RFMKCR:         // R found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  if (c != 'F')    goto START;
  // F found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == '!')    goto END;
  if (c != 'M')    goto START;
  // M found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == '!')    goto END;
  if (c != 'K')    goto START;
  // K found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  if (c != 'C')    goto START;
  // C found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == STOP)   goto END;
  if (c != 'R')    goto START;
  // R found
  printf ("RFMKCR found\n");
  goto START;

END:
  return 0;
}

int getchar1(void) // wraper around your input
{
  char in;
  in = getchar(); // or scanf ("%c", &in);
  return in;
}

int main ()
{
  printf ("*start*\n");
  START();
  printf ("*the end*\n");
  return 0;
}
</code>```

Same output is produced by both solutions.

OUTPUT for INPUT: AAWY AAWWAWY RRRFMKCR A A WY AWRFMCR AAA!

```<code>*start*
AWY found
AWY found
RFMKCR found
*the end*
</code>```

3) Solution

```<code>/******************************************************************************

                 CLASSICAL STATE MACHINE APPROACH

                 - take a notice how the generic `next` function service transitions
                 - together with the `start` helper.
                 - `next` and `start` have the same functions signatures
                 - and can be replaced with a function pointers

The resulting code is more complicated than previous two examples.

However:
a) the input is taken only from one place (inside the while loop)
b) the generic nature of the code allows easy customization/

*******************************************************************************/

#include <stdio.h>
#include <stdlib.h>

#define STOP             '!' // character chosen to stop processing

#define END               0
#define IDLE              1
#define START             2

#define AWY_A             3
#define AWY_W             4
#define AWY_Y             5

#define RFMKCR_R          6
#define RFMKCR_F          7
#define RFMKCR_M          8
#define RFMKCR_K          9
#define RFMKCR_C         10
#define RFMKCR_R_END     11

#define AWY_FOUND        12
#define RFMKCR_FOUND     13
#define TO_BE_CALCULATED 14
#define UNKNOWN_STATE    15

// we keep here the current state and next state to which we will transit
struct state_machine_state
{
    int current_state;
    int next_state;

    unsigned int debug_flag;
};

int getchar1 (void);

int start(struct state_machine_state *p, int c, int current_state, int char_expected, int next_state);
int next(struct state_machine_state *p, int c, int current_state, int char_expected, int next_state);

int state_machine(struct state_machine_state *p, int c);
int processing(void);

int getchar1 (void)
{
  int in;
  in = getchar();   //char in = scanf ("%c", &in);
  return in;
}

int next(struct state_machine_state *p, int c, int current_state, int char_expected, int next_state)
{
    // This generic function provides transitions to the required states based on the input `c` character
    // If c matches the expected character than we transition to known apriori next state
    // If the input `c` does not match expected character then we re-start the hunt for patterns

    if (c == char_expected)
    {
        if(p->debug_flag)
            printf("++: c=%c cs=%d next=%d \n", c, p->next_state, next_state);

        p->current_state = current_state;
        p->next_state = next_state;

        return next_state;
    }
    return ( start(p, c, current_state, c, TO_BE_CALCULATED) );
}

int start(struct state_machine_state *p, int c, int current_state, int char_expected, int next_state)
{
    // We hunt for the following
    // - start of the AWY pattern: 'A'
    // - start of the RFMKCR pattern 'R'
    // - special termination character (see: #define STOP  )

    // If none of the above is found than continue the hunt, we stay in the START state

    switch(c)
    {
        case 'A':   return( next(p, c, AWY_A, 'A', AWY_W) );        //  ==  p->current_state = AWY_A;     p->next_state = AWY_W;    return AWY_W;
        case 'R':   return( next(p, c, RFMKCR_R, 'R', RFMKCR_F) );  //  ==  p->current_state = RFMKCR_R;  p->next_state = RFMKCR_F; return RFMKCR_F;
        case STOP:  return( next(p, c, END, STOP, END) );           //  ==  p->current_state = END;       p->next_state = END;      return END;
        default:    return( next(p, c, START, c, START) );          //  == p->current_state = START;      p->next_state = START;    return START;
    }
}

int state_machine(struct state_machine_state *p, int c)
{
    // state machine gets two inputs, pointer `p` to state_machine_state structure
    // and current char  `c` to be processed

    switch (p->next_state)
    {
        // search for the beginning of the pattern:
        case START: return( start(p, c, START, c, TO_BE_CALCULATED) ); // can return: AWY_W, RFMKCR_F, START, END

        // process all expected transitions for the AWY pattern
        // A->W->Y
        case AWY_W: return( next(p, c, AWY_W, 'W', AWY_Y) );              // can return AWY_W
        case AWY_Y: return( next(p, c, AWY_Y, 'Y', AWY_FOUND ) );         // can return AWY_FOUND

        // process proper transitions for the RFMKCR pattern:
        // R->F->M->K->C->R
        case RFMKCR_F: return ( next(p, c, RFMKCR_F, 'F', RFMKCR_M) );
        case RFMKCR_M: return ( next(p, c, RFMKCR_M, 'M', RFMKCR_K) );
        case RFMKCR_K: return ( next(p, c, RFMKCR_K, 'K', RFMKCR_C) );
        case RFMKCR_C: return ( next(p, c, RFMKCR_C, 'C', RFMKCR_R_END) );
        case RFMKCR_R_END: return ( next(p, c, RFMKCR_R_END, 'R', RFMKCR_FOUND) );  // can retun RFMKCR_FOUND

        default: printf ("UNKNOWN STATE! %d=\n", p->next_state); return( start(p,c,UNKNOWN_STATE,c,TO_BE_CALCULATED) );  // We should never come here!!!
    }
}

int processing(void)
{
  int c;
  int next_state;
  struct state_machine_state s;

  // Init state machine:
  s.current_state = IDLE;
  s.next_state = START;

  s.debug_flag = 0; // change to 1 if you need to see transitions
  // --

  while(1)
  {
        c = getchar1(); // may state machine designs like to have an input in one place

        next_state = state_machine(&s,c); // our main state processor

        // We service here special states:

        switch(next_state) // s.next_state can be used as well
        {
            case AWY_FOUND:
                printf("AWY found\n"); // we will continue search
                next(&s, c, AWY_FOUND, 'Y', START);
            break;
            case RFMKCR_FOUND: // we will continue search
                printf("RFMKCR found\n");
                next(&s, c, RFMKCR_FOUND, 'R', START);
            break;
            case END:
                next(&s, c, END, STOP, END);
            return 0; // This state terminates processing

            default:
            // We are not interested in these states!
            break;
        }
   }

  return 0;
}

int main ()
{
  printf ("*start*\n");

  processing();

  printf ("*the end*\n");

  return 0;
}
</code>```

OUTPUT:

```<code>*start*
AAWY A W Y RFMKCRR AWYY!
AWY found
RFMKCR found
AWY found
*the end*
</code>```

Body:
This is complete code for the state machine which gets input from generic function getchar1(). Patterns: AWY and RFMKCR are recognized and reported.

Function getchar1() is just a wrapper for any function which gets a char from the input.  getchar() or scanf can be used inside it. Char defined by the   STOP terminates input processing.

Difficulties for this problem come from the need to hunt for the beginning of two patterns: AWY and RFMKCR at the same time. We may be forced to switch to hunt for the different pattern in the middle of another one or to re-synchronize.

Three complete solutions are given.

First solution use recursion.

Second solution use a simple goto constructs avoiding recursive calls. This approach works very well for this particular problem.

Note: The usage of goto is typically discouraged in C.
It is good programming style to use the break, continue, and return statement in preference to goto whenever possible. Since the break statement only exits from one level of the loop, a goto may be necessary for exiting a loop from within a deeply nested loop.

Third solution does not use recursion or goto statements and tries to show a generic approach which can be easily adapted to different patterns.

Solution 1)

#include <stdio.h>
#include <stdlib.h>

#define STOP    '!'

int START(void);
int AWY(void);
int RFMKCR(void);
int END(void);

int getchar1 (void)
{
  char in;
  in = getchar(); // scanf ("%c", &in);
  return in;
}

int START(void)
{
  int c = getchar1 ();
  if (c == 'A')    return AWY();
  if (c == 'R')    return RFMKCR();
  if (c == STOP)   return END();
  return 1;
}

int AWY(void)   // A already found
{
  int c = getchar1 ();
  if (c == 'A')    return AWY();
  if (c == 'R')    return RFMKCR();
  if (c == STOP)   return END();
  if (c != 'W')    return 1;
  // W found

  c = getchar1 ();
  if (c == 'A')    return AWY();
  if (c == 'R')    return RFMKCR();
  if (c == STOP)   return END();
  if (c != 'Y')    return 1;
  // Y found

  printf ("AWY found\n");
  return 1;
}

int RFMKCR(void)    // R already found
{
  int c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == 'R')     return RFMKCR();
  if (c == STOP)    return END();
  if (c != 'F')     return 1;
  // F found

  c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == 'R')     return RFMKCR();
  if (c == STOP)    return END();
  if (c != 'M')     return 1;
  // M found

  c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == 'R')     return RFMKCR();
  if (c == STOP)    return END();
  if (c != 'K')     return 1;
  // K found

  c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == 'R')     return RFMKCR();
  if (c == STOP)    return END();
  if (c != 'C')     return 1;
  // C found
  c = getchar1 ();
  if (c == 'A')     return AWY();
  if (c == STOP)    return END();
  if (c != 'R')     return 1;
  // R found

  printf ("RFMKCR found\n");
  return 1;
}

int END(void)
{
  return 0;
}

int main ()
{
  printf ("\n*start*\n");
  while(START());
  printf ("*the end*\n");
  return 0;
}

Solution 2)

#include <stdio.h>
#include <stdlib.h>

#define STOP '!'

int START()
{
int c;

START:
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  goto START;

AWY:                // A found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  if (c != 'W')    goto START;
  // W found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  if (c != 'Y')    goto START;
  // Y found
  printf ("AWY found\n");
  goto START;

RFMKCR:         // R found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  if (c != 'F')    goto START;
  // F found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == '!')    goto END;
  if (c != 'M')    goto START;
  // M found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == '!')    goto END;
  if (c != 'K')    goto START;
  // K found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == 'R')    goto RFMKCR;
  if (c == STOP)   goto END;
  if (c != 'C')    goto START;
  // C found
  c = getchar1 ();
  if (c == 'A')    goto AWY;
  if (c == STOP)   goto END;
  if (c != 'R')    goto START;
  // R found
  printf ("RFMKCR found\n");
  goto START;

END:
  return 0;
}

int getchar1(void) // wraper around your input
{
  char in;
  in = getchar(); // or scanf ("%c", &in);
  return in;
}

int main ()
{
  printf ("*start*\n");
  START();
  printf ("*the end*\n");
  return 0;
}

Same output is produced by both solutions.

OUTPUT for INPUT: AAWY AAWWAWY RRRFMKCR A A WY AWRFMCR AAA!

*start*
AWY found
AWY found
RFMKCR found
*the end*

3) Solution

/******************************************************************************

                 CLASSICAL STATE MACHINE APPROACH

                 - take a notice how the generic `next` function service transitions
                 - together with the `start` helper.
                 - `next` and `start` have the same functions signatures
                 - and can be replaced with a function pointers

The resulting code is more complicated than previous two examples.

However:
a) the input is taken only from one place (inside the while loop)
b) the generic nature of the code allows easy customization/

*******************************************************************************/

#include <stdio.h>
#include <stdlib.h>

#define STOP             '!' // character chosen to stop processing

#define END               0
#define IDLE              1
#define START             2

#define AWY_A             3
#define AWY_W             4
#define AWY_Y             5

#define RFMKCR_R          6
#define RFMKCR_F          7
#define RFMKCR_M          8
#define RFMKCR_K          9
#define RFMKCR_C         10
#define RFMKCR_R_END     11

#define AWY_FOUND        12
#define RFMKCR_FOUND     13
#define TO_BE_CALCULATED 14
#define UNKNOWN_STATE    15

// we keep here the current state and next state to which we will transit
struct state_machine_state
{
    int current_state;
    int next_state;

    unsigned int debug_flag;
};

int getchar1 (void);

int start(struct state_machine_state *p, int c, int current_state, int char_expected, int next_state);
int next(struct state_machine_state *p, int c, int current_state, int char_expected, int next_state);

int state_machine(struct state_machine_state *p, int c);
int processing(void);

int getchar1 (void)
{
  int in;
  in = getchar();   //char in = scanf ("%c", &in);
  return in;
}

int next(struct state_machine_state *p, int c, int current_state, int char_expected, int next_state)
{
    // This generic function provides transitions to the required states based on the input `c` character
    // If c matches the expected character than we transition to known apriori next state
    // If the input `c` does not match expected character then we re-start the hunt for patterns

    if (c == char_expected)
    {
        if(p->debug_flag)
            printf("++: c=%c cs=%d next=%d \n", c, p->next_state, next_state);

        p->current_state = current_state;
        p->next_state = next_state;

        return next_state;
    }
    return ( start(p, c, current_state, c, TO_BE_CALCULATED) );
}

int start(struct state_machine_state *p, int c, int current_state, int char_expected, int next_state)
{
    // We hunt for the following
    // - start of the AWY pattern: 'A'
    // - start of the RFMKCR pattern 'R'
    // - special termination character (see: #define STOP  )

    // If none of the above is found than continue the hunt, we stay in the START state

    switch(c)
    {
        case 'A':   return( next(p, c, AWY_A, 'A', AWY_W) );        //  ==  p->current_state = AWY_A;     p->next_state = AWY_W;    return AWY_W;
        case 'R':   return( next(p, c, RFMKCR_R, 'R', RFMKCR_F) );  //  ==  p->current_state = RFMKCR_R;  p->next_state = RFMKCR_F; return RFMKCR_F;
        case STOP:  return( next(p, c, END, STOP, END) );           //  ==  p->current_state = END;       p->next_state = END;      return END;
        default:    return( next(p, c, START, c, START) );          //  == p->current_state = START;      p->next_state = START;    return START;
    }
}

int state_machine(struct state_machine_state *p, int c)
{
    // state machine gets two inputs, pointer `p` to state_machine_state structure
    // and current char  `c` to be processed

    switch (p->next_state)
    {
        // search for the beginning of the pattern:
        case START: return( start(p, c, START, c, TO_BE_CALCULATED) ); // can return: AWY_W, RFMKCR_F, START, END

        // process all expected transitions for the AWY pattern
        // A->W->Y
        case AWY_W: return( next(p, c, AWY_W, 'W', AWY_Y) );              // can return AWY_W
        case AWY_Y: return( next(p, c, AWY_Y, 'Y', AWY_FOUND ) );         // can return AWY_FOUND

        // process proper transitions for the RFMKCR pattern:
        // R->F->M->K->C->R
        case RFMKCR_F: return ( next(p, c, RFMKCR_F, 'F', RFMKCR_M) );
        case RFMKCR_M: return ( next(p, c, RFMKCR_M, 'M', RFMKCR_K) );
        case RFMKCR_K: return ( next(p, c, RFMKCR_K, 'K', RFMKCR_C) );
        case RFMKCR_C: return ( next(p, c, RFMKCR_C, 'C', RFMKCR_R_END) );
        case RFMKCR_R_END: return ( next(p, c, RFMKCR_R_END, 'R', RFMKCR_FOUND) );  // can retun RFMKCR_FOUND

        default: printf ("UNKNOWN STATE! %d=\n", p->next_state); return( start(p,c,UNKNOWN_STATE,c,TO_BE_CALCULATED) );  // We should never come here!!!
    }
}

int processing(void)
{
  int c;
  int next_state;
  struct state_machine_state s;

  // Init state machine:
  s.current_state = IDLE;
  s.next_state = START;

  s.debug_flag = 0; // change to 1 if you need to see transitions
  // --

  while(1)
  {
        c = getchar1(); // may state machine designs like to have an input in one place

        next_state = state_machine(&s,c); // our main state processor

        // We service here special states:

        switch(next_state) // s.next_state can be used as well
        {
            case AWY_FOUND:
                printf("AWY found\n"); // we will continue search
                next(&s, c, AWY_FOUND, 'Y', START);
            break;
            case RFMKCR_FOUND: // we will continue search
                printf("RFMKCR found\n");
                next(&s, c, RFMKCR_FOUND, 'R', START);
            break;
            case END:
                next(&s, c, END, STOP, END);
            return 0; // This state terminates processing

            default:
            // We are not interested in these states!
            break;
        }
   }

  return 0;
}

int main ()
{
  printf ("*start*\n");

  processing();

  printf ("*the end*\n");

  return 0;
}

OUTPUT:

*start*
AAWY A W Y RFMKCRR AWYY!
AWY found
RFMKCR found
AWY found
*the end*


来源: stackexchange

问:
Multiply-included header with guards
Let's say I have a special header file which is designed to be included multiple times and generates different code depending on the value of some macro which must be defined before including it. For example, the following file dumb.h:

```<code>#define RETFUNC return_ ## VALUE
static inline int RETFUNC() {
  return VALUE;
}
</code>```

You include it like:

```<code>#define VALUE 100
#include "dumb.h"
#define VALUE 200
#include "dumb.h"
</code>```

and it generates two versions of the function like:

```<code>static inline return_100 {
  return 100;
}

static inline return_200 {
  return 200;
}
</code>```

Great1.

How can I make a header guard for this type of file? Without guards, if two different consumers of the header file both requested the same VALUE, you'd get an error since two identical versions of the return_* function would be generated.

Now a normal header guard like:

```<code>#ifndef DUMB_H_
#define DUMB_H_
...
#endif // DUMB_H_
</code>```

Isn't going to work since it would only effectively include the file once (the #include sequence above would generate the _100 version of the function, but not the _200 version).

In principle I would like to generate the name of a macro using token pasting, to check as the guard, like:

```<code>#ifndef DUMB_H_ ## VALUE
#define DUMB_H_ ## VALUE
...
</code>```

But token pasting can't be used like that (outside of macro expansion).

Any there any other options to prevent this file from being included multiple times with the same VALUE, but to still allow the body to be effectively included once for each different VALUE requested?

1 Not great in the sense that this is a good pattern or anything like that, but in it that it at least appears to work.

答:
With the explanation in comment 1 and comment 2, I think the normal process is more like this.  I'm going to use a type as the argument, and generate a 'minimum' function for the different types:

dumb.h

```<code>#ifndef DUMB_H_INCLUDED
#define DUMB_H_INCLUDED

#define MIN_TYPE(x) \
    static inline x min_ ## x(x v1, x v2) { return (v1 < v2) ? v1 : v2; }

#endif /* DUMB_H_INCLUDED */
</code>```

Consumer code

```<code>#include "dumb.h"
#include <inttypes.h>

MIN_TYPE(int)          // No semicolon; no empty declaration!
MIN_TYPE(double)
MIN_TYPE(uint64_t)

void write_minima(int i1, int i2, double d1, double d2, uint64_t u1, uint64_t u2)
{
    printf("Minima: (%d, %g, %" PRIu64 ")\n",
           min_int(i1, i2), min_double(d1, d2), min_uint64_t(u1, u2));
}
</code>```

This does not stop you from trying to instantiate the same function twice in a single TU (translation unit), but the compiler will object if you do that.  And frankly, letting the compiler do the complaining is simpler than trying to make the C preprocessor spot that you've screwed up and rectify your mistake.

If the C code will be generated by another program, then you need to ensure that the code generator keeps a track of what it has requested and ensure that it doesn't double generate the code.

ContentLicense: CC BY-SA 3.0

Title: Multiply-included header with guards

Body:
Let's say I have a special header file which is designed to be included multiple times and generates different code depending on the value of some macro which must be defined before including it. For example, the following file dumb.h:

#define RETFUNC return_ ## VALUE
static inline int RETFUNC() {
  return VALUE;
}

You include it like:

#define VALUE 100
#include "dumb.h"
#define VALUE 200
#include "dumb.h"

and it generates two versions of the function like:

static inline return_100 {
  return 100;
}

static inline return_200 {
  return 200;
}

Great1.

How can I make a header guard for this type of file? Without guards, if two different consumers of the header file both requested the same VALUE, you'd get an error since two identical versions of the return_* function would be generated.

Now a normal header guard like:

#ifndef DUMB_H_
#define DUMB_H_
...
#endif // DUMB_H_

Isn't going to work since it would only effectively include the file once (the #include sequence above would generate the _100 version of the function, but not the _200 version).

In principle I would like to generate the name of a macro using token pasting, to check as the guard, like:

#ifndef DUMB_H_ ## VALUE
#define DUMB_H_ ## VALUE
...

But token pasting can't be used like that (outside of macro expansion).

Any there any other options to prevent this file from being included multiple times with the same VALUE, but to still allow the body to be effectively included once for each different VALUE requested?

1 Not great in the sense that this is a good pattern or anything like that, but in it that it at least appears to work.

Body:
With the explanation in comment 1 and comment 2, I think the normal process is more like this.  I'm going to use a type as the argument, and generate a 'minimum' function for the different types:

dumb.h

#ifndef DUMB_H_INCLUDED
#define DUMB_H_INCLUDED

#define MIN_TYPE(x) \
    static inline x min_ ## x(x v1, x v2) { return (v1 < v2) ? v1 : v2; }

#endif /* DUMB_H_INCLUDED */

Consumer code

#include "dumb.h"
#include <inttypes.h>

MIN_TYPE(int)          // No semicolon; no empty declaration!
MIN_TYPE(double)
MIN_TYPE(uint64_t)

void write_minima(int i1, int i2, double d1, double d2, uint64_t u1, uint64_t u2)
{
    printf("Minima: (%d, %g, %" PRIu64 ")\n",
           min_int(i1, i2), min_double(d1, d2), min_uint64_t(u1, u2));
}

This does not stop you from trying to instantiate the same function twice in a single TU (translation unit), but the compiler will object if you do that.  And frankly, letting the compiler do the complaining is simpler than trying to make the C preprocessor spot that you've screwed up and rectify your mistake.

If the C code will be generated by another program, then you need to ensure that the code generator keeps a track of what it has requested and ensure that it doesn't double generate the code.


问:
Environment variables in nodejs deployed app
I am developing a Node application in which I am connecting to an azure database. I would like to keep the credentials as environment variables. I have a .env file and I have the credentials in that. When I run the app locally I can fetch the credentials from the file but when it is deployed in Azure, the process.env.SERVER is returning undefined and so I am unable to connect to the server.</p>

答:
In Azure Web Apps, we can define these environment variables in section Application settings -> App settings by using Azure portal:

Then these variables can be accessed from our Node.js code via process.env["variablename"].


问:
Combine columns of dataframe into new dataframe
I am new to pandas and working with DataFrames. I'm looking at the documentation for Merge,Join,Concatenate, and it's probably staring me right in the face, but I'm still having trouble transposing the data the way I need it.

I have data that looks like this ( R rows x 4302 columns ):

```<code>| w:350 |       r:350 | w:351 |   r:351 |  ...  | w:2499 |      r:2499 | w:2500 |  r:2500 |
-------------------------------------------------------------------------------------------
|   350 | -3.0998e-04 |   351 |  0.0001 |  ...  |   2499 | -3.6000e-05 |   2500 |  0.0004 |
|   350 | -1.8316e-03 |   351 | -0.0008 |  ...  |   2499 | -3.1124e-04 |   2500 | -0.0004 |
|   350 | -1.0520e-03 |   351 | -0.0014 |  ...  |   2499 |  4.0166e-04 |   2500 |  0.0012 |
|   350 | -3.4060e-04 |   351 |  0.0006 |  ...  |   2499 |  1.2782e-03 |   2500 |  0.0012 |
</code>```

That I want to look like this ( X rows x 2 columns ):

```<code>|     x |           y |
-----------------------
|   350 | -3.0998e-04 |
|   350 | -1.8316e-03 |
|   350 | -1.0520e-03 |
|   350 | -3.4060e-04 |
|   351 |      0.0001 |
|   351 |     -0.0008 |
|   351 |     -0.0014 |
|   351 |      0.0006 |
...
|  2499 | -3.6000e-05 |
|  2499 | -3.1124e-04 |
|  2499 |  4.0166e-04 |
|  2499 |  1.2782e-03 |
|  2500 |      0.0004 |
|  2500 |     -0.0004 |
|  2500 |      0.0012 |
|  2500 |      0.0012 |
</code>```

I guess you can think of it as a DataFrame of rows of multiple sets of x,y data, that I want combined into a DataFrame of rows of a single set of x,y data. Or in other words, each row is currently a graph of x,y data. And I need a single collection of x,y data of all the graphs.

I've tried this, but it's not working (probably because the column names not named the same). It's also probably not the most efficient way to do what I'm trying to do. Here output is my original data, and outputxy is the transposed data that I want.

```<code>outputxy = pandas.DataFrame()
for i in range(0, len(output.columns), 2):
    outputxy = pandas.concat([output.iloc[:, i:i+2], outputxy])
</code>```

Thank you in advance for any help!

Body:
I am new to pandas and working with DataFrames. I'm looking at the documentation for Merge,Join,Concatenate, and it's probably staring me right in the face, but I'm still having trouble transposing the data the way I need it.

I have data that looks like this ( R rows x 4302 columns ):

| w:350 |       r:350 | w:351 |   r:351 |  ...  | w:2499 |      r:2499 | w:2500 |  r:2500 |
-------------------------------------------------------------------------------------------
|   350 | -3.0998e-04 |   351 |  0.0001 |  ...  |   2499 | -3.6000e-05 |   2500 |  0.0004 |
|   350 | -1.8316e-03 |   351 | -0.0008 |  ...  |   2499 | -3.1124e-04 |   2500 | -0.0004 |
|   350 | -1.0520e-03 |   351 | -0.0014 |  ...  |   2499 |  4.0166e-04 |   2500 |  0.0012 |
|   350 | -3.4060e-04 |   351 |  0.0006 |  ...  |   2499 |  1.2782e-03 |   2500 |  0.0012 |

That I want to look like this ( X rows x 2 columns ):

|     x |           y |
-----------------------
|   350 | -3.0998e-04 |
|   350 | -1.8316e-03 |
|   350 | -1.0520e-03 |
|   350 | -3.4060e-04 |
|   351 |      0.0001 |
|   351 |     -0.0008 |
|   351 |     -0.0014 |
|   351 |      0.0006 |
...
|  2499 | -3.6000e-05 |
|  2499 | -3.1124e-04 |
|  2499 |  4.0166e-04 |
|  2499 |  1.2782e-03 |
|  2500 |      0.0004 |
|  2500 |     -0.0004 |
|  2500 |      0.0012 |
|  2500 |      0.0012 |

I guess you can think of it as a DataFrame of rows of multiple sets of x,y data, that I want combined into a DataFrame of rows of a single set of x,y data. Or in other words, each row is currently a graph of x,y data. And I need a single collection of x,y data of all the graphs.

I've tried this, but it's not working (probably because the column names not named the same). It's also probably not the most efficient way to do what I'm trying to do. Here output is my original data, and outputxy is the transposed data that I want.

outputxy = pandas.DataFrame()
for i in range(0, len(output.columns), 2):
    outputxy = pandas.concat([output.iloc[:, i:i+2], outputxy])

Thank you in advance for any help!

Body:
Can use melt and drop as shown below

df =  '''
w1  r1 w2 r2
1  14 4  23
2  15 5 32
3  16 6 33
'''

df1 = pd.DataFrame()
df1['X'] = pd.melt(df.iloc[:,::2]).drop('variable',1)
df1['Y'] = pd.melt(df.iloc[:,1::2]).drop('variable',1)

print df1

  X   Y
0  1  14
1  2  15
2  3  16
3  4  23
4  5  32
5  6  33


问:
Error Code: 1109. Unknown table 'new' in field list
I'm creating a database, where I validate input data with triggers. I added them successfully, but there is an error when I try to input fine data.

creating db, tables and triggers

```<code>CREATE DATABASE IF NOT EXISTS DBWorkers;

CREATE TABLE IF NOT EXISTS Ludzie(
PESEL char(11) NOT NULL,
imie varchar(30) NOT NULL,
nazwisko varchar(30) NOT NULL,
data_urodzenia date NOT NULL,
wzrost float NOT NULL,
waga float NOT NULL,
rozmiar_buta int NOT NULL,

PRIMARY KEY(PESEL));

DELIMITER $$
CREATE FUNCTION check_pesel(PESEL char(11)) RETURNS bool
BEGIN
IF(
    CHAR_LENGTH(NEW.PESEL) <> 11 AND
    CONVERT(PESEL, SIGNED INT) > 0 AND
    CONVERT(LEFT(PESEL,2), SIGNED INT) BETWEEN 0 AND 99 AND
    CONVERT(SUBSTRING(PESEL,3,2), SIGNED INT) BETWEEN 1 AND 12 AND
    CONVERT(SUBSTRING(PESEL,3,2), SIGNED INT) BETWEEN 1 AND     DAY(LAST_DAY(CONCAT('19',LEFT(PESEL,2),'-',SUBSTRING(PESEL,3,2),'-01')))
    )
    THEN
        RETURN TRUE;
    ELSE
        RETURN FALSE;
END IF;
END $$

CREATE TRIGGER `ludzie_data_check_before_insert` BEFORE INSERT ON `Ludzie`
FOR EACH ROW
BEGIN
IF NOT(
        check_pesel(NEW.PESEL) AND
        NEW.WZROST > 0.0 AND
        NEW.WAGA > 0.0 AND
        NEW.ROZMIAR_BUTA > 0
    )
THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'check on Ludzie failed during insert';
END IF;
END $$
DELIMITER ;
</code>```

When I try to input data by

```<code>INSERT INTO Ludzie VALUES ('7810396705', 'Anders', 'Kennedy','1958-08-20', 1.70, 88.6, 43)
</code>```

I get

```<code>Error Code: 1109. Unknown table 'new' in field list
</code>```

I already tried turning mysql server on and off, checked if I'm doing it to the right database. Everything seems to look fine, but it isn't :/

答:
Yes, After doing some reading I as well am willing to bet that the "NEW" keyword is not needed in

CHAR_LENGTH(NEW.PESEL).

NEW keyword is used in update and insert commands.

Body:
I'm creating a database, where I validate input data with triggers. I added them successfully, but there is an error when I try to input fine data.

creating db, tables and triggers

CREATE DATABASE IF NOT EXISTS DBWorkers;

CREATE TABLE IF NOT EXISTS Ludzie(
PESEL char(11) NOT NULL,
imie varchar(30) NOT NULL,
nazwisko varchar(30) NOT NULL,
data_urodzenia date NOT NULL,
wzrost float NOT NULL,
waga float NOT NULL,
rozmiar_buta int NOT NULL,

PRIMARY KEY(PESEL));

DELIMITER $$
CREATE FUNCTION check_pesel(PESEL char(11)) RETURNS bool
BEGIN
IF(
    CHAR_LENGTH(NEW.PESEL) <> 11 AND
    CONVERT(PESEL, SIGNED INT) > 0 AND
    CONVERT(LEFT(PESEL,2), SIGNED INT) BETWEEN 0 AND 99 AND
    CONVERT(SUBSTRING(PESEL,3,2), SIGNED INT) BETWEEN 1 AND 12 AND
    CONVERT(SUBSTRING(PESEL,3,2), SIGNED INT) BETWEEN 1 AND     DAY(LAST_DAY(CONCAT('19',LEFT(PESEL,2),'-',SUBSTRING(PESEL,3,2),'-01')))
    )
    THEN
        RETURN TRUE;
    ELSE
        RETURN FALSE;
END IF;
END $$

CREATE TRIGGER `ludzie_data_check_before_insert` BEFORE INSERT ON `Ludzie`
FOR EACH ROW
BEGIN
IF NOT(
        check_pesel(NEW.PESEL) AND
        NEW.WZROST > 0.0 AND
        NEW.WAGA > 0.0 AND
        NEW.ROZMIAR_BUTA > 0
    )
THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'check on Ludzie failed during insert';
END IF;
END $$
DELIMITER ;

When I try to input data by

INSERT INTO Ludzie VALUES ('7810396705', 'Anders', 'Kennedy','1958-08-20', 1.70, 88.6, 43)

I get

Error Code: 1109. Unknown table 'new' in field list

I already tried turning mysql server on and off, checked if I'm doing it to the right database. Everything seems to look fine, but it isn't :/


问:
Why isn't this instance being removed from my list of objects?
So I have created 2 classes called Invitation and Response. Then, I created a class called Event. Within the Event class, I have to create function that looks at the current list of invites and list of responses and counts how many invites have no response.

The invites and the responses both have a "name" attribute that I use in my get_pending() method.

I have a class instance called "e" that looks as follows:

```<code>e = Event("graduation",[Invitation("A",5),Invitation("B",10),Invitation("C",5),Invitation("D",7)], [Response("A",True,5),Response("B",True,6),Response("C",False,0),Response("D",True,1)])
</code>```

I then print the class method get_pending:

```<code>print(e.count_pending())
</code>```

Here is my code with the get_pending() method:

```<code>class Invitation:
    def __init__(self, name, num_invited):
        self.name = name #str
        self.num_invited = num_invited #positive int
    def __str__(self):
        return ("Invitation('%s', %i)" % (self.name, self.num_invited))
    def __repr__(self):
        return str(self)
    def __eq__(self, other):
        if self.name == other.name and self.num_invited == other.num_invited:
            return True
    def __lt__(self, other):
        if self.name < other.name:
            return True
        elif self.name == other.name:
            if self.num_invited < other.num_invited:
                return True
class Response:
    def __init__(self, name, ans, num_attending):
        self.name = name #str
        self.ans = ans #bool - T/F
        self.num_attending = num_attending #zero or more people
    def __str__(self):
        return ("Response('%s', %r, %i)" % (self.name, self.ans, self.num_attending))
    def __repr__(self):
        return str(self)
    def __eq__(self, other):
        if self.name == other.name and self.ans == other.ans and self.num_attending == other.num_attending:
            return True
    def __lt__(self, other):
        if self.name < other.name:
            return True
        elif self.name == other.name:
            if self.ans < other.ans:
                return True
            elif self.ans == other.ans:
                if self.num_attending < other.num_attending:
                    return True
class Event:
    def __init__(self, title, invites=None, responses=None):
        self.title = title #str
        self.invites = invites #list
        self.responses = responses #list
        if self.invites == None:
            self.invites = []
        if self.responses == None:
            self.responses = []
        self.invites.sort()
        self.responses.sort()
    def __str__(self):
        return ("""Event('%s', %r, %r)""" % (self.title, self.invites, self.responses))
    def __repr__(self):
        return str(self)
    def __eq__(self, other):
        if self.title == other.title and self.invites == other.invites and self.responses == other.responses:
            return True
    def count_pending(self):
        num_pending = 0
        lst_noresp = self.invites[:]
        for invi in lst_noresp:
            if (any(invi.name == resp.name for resp in self.responses)) == True:
                lst_noresp.remove(invi)
        for invi in lst_noresp:
            num_pending += invi.num_invited
        return num_pending

e = Event("graduation",[Invitation("A",5),Invitation("B",10),Invitation("C",5),Invitation("D",7)], [Response("A",True,5),Response("B",True,6),Response("C",False,0),Response("D",True,1)])
print(e.count_pending())
</code>```

My error is that the count_pending() method is only removing some (Invite with name 'A' and Invite with name 'C') objects from the invite list even though all invites have a corresponding response. Why isn't the invi.name == resp.name comparison working properly? Or, is that even the issue?

答:
You have the classic problem of mutating a list while iterating it here:

```<code>    for invi in lst_noresp:  # Iterating
        if (any(invi.name == resp.name for resp in self.responses)) == True:
            lst_noresp.remove(invi)  # Mutating
</code>```

While there is no documented behavior for it, in practice, this causes the loop to skip the value following each removed element (the iterator stores the current index, and the remove shifts the following elements down, so when you get the next element, you've bypassed the element that was shifted into the space occupied by the removed element), so you're not even checking half your values. Iterate over self.invites, and mutate lst_noresp, and the problem should disappear.

Alternatively, construct a new list and avoid O(n**2) performance:

```<code>    lst_noresp = [invi for invi in self.invites
                  if not any(invi.name == resp.name for resp in self.responses)]
</code>```

which avoids slow removals from the middle of a list in favor of filtering during construction of a new list (O(n) work).

Body:
So I have created 2 classes called Invitation and Response. Then, I created a class called Event. Within the Event class, I have to create function that looks at the current list of invites and list of responses and counts how many invites have no response.

The invites and the responses both have a "name" attribute that I use in my get_pending() method.

I have a class instance called "e" that looks as follows:

e = Event("graduation",[Invitation("A",5),Invitation("B",10),Invitation("C",5),Invitation("D",7)], [Response("A",True,5),Response("B",True,6),Response("C",False,0),Response("D",True,1)])

I then print the class method get_pending:

print(e.count_pending())

Here is my code with the get_pending() method:

class Invitation:
    def __init__(self, name, num_invited):
        self.name = name #str
        self.num_invited = num_invited #positive int
    def __str__(self):
        return ("Invitation('%s', %i)" % (self.name, self.num_invited))
    def __repr__(self):
        return str(self)
    def __eq__(self, other):
        if self.name == other.name and self.num_invited == other.num_invited:
            return True
    def __lt__(self, other):
        if self.name < other.name:
            return True
        elif self.name == other.name:
            if self.num_invited < other.num_invited:
                return True
class Response:
    def __init__(self, name, ans, num_attending):
        self.name = name #str
        self.ans = ans #bool - T/F
        self.num_attending = num_attending #zero or more people
    def __str__(self):
        return ("Response('%s', %r, %i)" % (self.name, self.ans, self.num_attending))
    def __repr__(self):
        return str(self)
    def __eq__(self, other):
        if self.name == other.name and self.ans == other.ans and self.num_attending == other.num_attending:
            return True
    def __lt__(self, other):
        if self.name < other.name:
            return True
        elif self.name == other.name:
            if self.ans < other.ans:
                return True
            elif self.ans == other.ans:
                if self.num_attending < other.num_attending:
                    return True
class Event:
    def __init__(self, title, invites=None, responses=None):
        self.title = title #str
        self.invites = invites #list
        self.responses = responses #list
        if self.invites == None:
            self.invites = []
        if self.responses == None:
            self.responses = []
        self.invites.sort()
        self.responses.sort()
    def __str__(self):
        return ("""Event('%s', %r, %r)""" % (self.title, self.invites, self.responses))
    def __repr__(self):
        return str(self)
    def __eq__(self, other):
        if self.title == other.title and self.invites == other.invites and self.responses == other.responses:
            return True
    def count_pending(self):
        num_pending = 0
        lst_noresp = self.invites[:]
        for invi in lst_noresp:
            if (any(invi.name == resp.name for resp in self.responses)) == True:
                lst_noresp.remove(invi)
        for invi in lst_noresp:
            num_pending += invi.num_invited
        return num_pending

e = Event("graduation",[Invitation("A",5),Invitation("B",10),Invitation("C",5),Invitation("D",7)], [Response("A",True,5),Response("B",True,6),Response("C",False,0),Response("D",True,1)])
print(e.count_pending())

My error is that the count_pending() method is only removing some (Invite with name 'A' and Invite with name 'C') objects from the invite list even though all invites have a corresponding response. Why isn't the invi.name == resp.name comparison working properly? Or, is that even the issue?

Body:
You have the classic problem of mutating a list while iterating it here:

    for invi in lst_noresp:  # Iterating
        if (any(invi.name == resp.name for resp in self.responses)) == True:
            lst_noresp.remove(invi)  # Mutating

While there is no documented behavior for it, in practice, this causes the loop to skip the value following each removed element (the iterator stores the current index, and the remove shifts the following elements down, so when you get the next element, you've bypassed the element that was shifted into the space occupied by the removed element), so you're not even checking half your values. Iterate over self.invites, and mutate lst_noresp, and the problem should disappear.

Alternatively, construct a new list and avoid O(n**2) performance:

    lst_noresp = [invi for invi in self.invites
                  if not any(invi.name == resp.name for resp in self.responses)]

which avoids slow removals from the middle of a list in favor of filtering during construction of a new list (O(n) work).


问:
how to change text size of android-spinner
How do I change the text size of a spinner in android.
I have read that if you get your items from a resource (like R.array.items) you use ArrayAdapter.createFromResource(context, R.array.items, R.layout.textview), but what if a get my items from a list that changes, how would I then change text size of the spinner.</p>

答:
You need to redefine 2 resource xml's

Adapter dropdown view resource

Spinner item resource

```<code>
    Spinner spinner=new Spinner(context);
    ArrayAdapter adapter = new ArrayAdapter(context, R.layout.my_spinner_item);
    adapter.setDropDownViewResource(R.layout.my_spinner_dropdown_item);
```
E.g. my_spinner_dropdown_item.xml resource can be defined as:

```<code><MyCheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/simpleSpinnerDropDownItem"
    style="?android:attr/spinnerDropDownItemStyle"
    android:singleLine="true"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight" />
</code>```

where MyCheckedTextView class has to be defined by you (extending CheckedTextView) - so it's a place where you can define your text size/style - whatever

ContentLicense: CC BY-SA 2.5

Body:
You need to redefine 2 resource xml's

Adapter dropdown view resource

Spinner item resource

    Spinner spinner=new Spinner(context);
    ArrayAdapter adapter = new ArrayAdapter(context, R.layout.my_spinner_item);
    adapter.setDropDownViewResource(R.layout.my_spinner_dropdown_item);

E.g. my_spinner_dropdown_item.xml resource can be defined as:

<MyCheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/simpleSpinnerDropDownItem"
    style="?android:attr/spinnerDropDownItemStyle"
    android:singleLine="true"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight" />

where MyCheckedTextView class has to be defined by you (extending CheckedTextView) - so it's a place where you can define your text size/style - whatever


问:
AWS S3 - What to set KEY to?
I have been given instructions to download data from s3://x.y.z/ using python, where x, y, z are placeholders of course.

I've gotten myself set up to run the following code

```<code>import boto3
import botocore

BUCKET_NAME = 'my-bucket' # replace with your bucket name
KEY = '???' # replace with your object key
LOCAL_TARGET = 'some.data'

s3 = boto3.resource('s3')

try:
    s3.Bucket(BUCKET_NAME).download_file(KEY, LOCAL_TARGET)
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
    else:
        raise
</code>```

but all my attempts at guessing what to set BUCKET and KEY to have resulted in a 404 error.

What would the appropriate values, given the following information?

The data has been uploaded to s3://x.y.z/

答:
The key will be the filename you want to download for example

http://s3.amazonaws.com/goat-bucket/farms/andys/goat.png

bucket: goat-bucket

key: farms/andys/goat.png

If you don't know the object name, you can list out the object names of goat bucket like so:

```<code>import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('goat-bucket') # Using the bucket name above
for object in bucket.objects.all():
    print('Bucket name: ' + object.bucket_name)
    print('Object key: ' + object.key)
</code>```

Would output:

```<code>Bucket name: goat-bucket
Object key: farms/andys/goat.png
</code>```

Title: AWS S3 - What to set KEY to?

Body:
I have been given instructions to download data from s3://x.y.z/ using python, where x, y, z are placeholders of course.

I've gotten myself set up to run the following code

import boto3
import botocore

BUCKET_NAME = 'my-bucket' # replace with your bucket name
KEY = '???' # replace with your object key
LOCAL_TARGET = 'some.data'

s3 = boto3.resource('s3')

try:
    s3.Bucket(BUCKET_NAME).download_file(KEY, LOCAL_TARGET)
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
    else:
        raise

but all my attempts at guessing what to set BUCKET and KEY to have resulted in a 404 error.

What would the appropriate values, given the following information?

The data has been uploaded to s3://x.y.z/

Body:
The key will be the filename you want to download for example

http://s3.amazonaws.com/goat-bucket/farms/andys/goat.png

bucket: goat-bucket

key: farms/andys/goat.png

If you don't know the object name, you can list out the object names of goat bucket like so:

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('goat-bucket') # Using the bucket name above
for object in bucket.objects.all():
    print('Bucket name: ' + object.bucket_name)
    print('Object key: ' + object.key)

Would output:

Bucket name: goat-bucket
Object key: farms/andys/goat.png


问:
Requests: Check that the proxy has been used to make the HTTP Request
I've been scratching my head the whole day yesterday about this and to my surprise, can't seem to find an easy way to check this.

I am using Python's Requests library to pass my proxy such as:

```<code>def make_request(url):
    with requests.Session() as s:
        s.mount("http://", HTTPAdapter(max_retries=3))
        s.mount("https://", HTTPAdapter(max_retries=3))
        page = None
        d.rotate(-1) #d contains a dict of my proxies. this allows to rotate through the proxies everytime make_request is called.

        s.proxies = d[0]
        page = s.get(url, timeout=3)

        print('proxy used: ' + str(d[0]))
    return page.content
</code>```

Problem is, I can't seem to make the request fail when the proxy is not expected to work. It seems there is always a fallback on my internet ip if the proxy is not working.
For example: I tried passing a random proxy ip like 101.101.101.101:8800 or removing the ip authentication that is needed on my proxies, the request is still passed, even though it should'nt.

I thought adding the timeout parameters when passing the request would do the trick, but obviously it didn't.

So

Why does this happen?

How can I check from which ip a request is being made?

答:
From what I have seen so far, you should use the form

```<code>s.get(url, proxies = d)
</code>```

This should use the proxies in the dict d to make a connection.
This form allowed me to check with working proxies and non-working proxies the status_code

print(s.status_code)

I will update once I find out whether it just circulates over the proxies in the dict to match a working one, or one is able to actually select which one to be used.

[UPDATE]
Tried to work around the dict in proxies, to use different proxy if I wanted to. However, proxies must be a dict to work. So I used a dict in the form of:

d = {"https" : 'https://' + str(proxy_ips[n].strip('\n'))}

This seems to work and allow me to use an ip I want to. Although it seems quite dull, I hope someone might come and help!

The proxies used can be seen through:

```<code>requests.utils.getproxies()
</code>```

or

```<code>requests.utils.get_environ_proxies(url)
</code>```

I hope that helps, obviously quite old question, but still!

Body:
I've been scratching my head the whole day yesterday about this and to my surprise, can't seem to find an easy way to check this.

I am using Python's Requests library to pass my proxy such as:

def make_request(url):
    with requests.Session() as s:
        s.mount("http://", HTTPAdapter(max_retries=3))
        s.mount("https://", HTTPAdapter(max_retries=3))
        page = None
        d.rotate(-1) #d contains a dict of my proxies. this allows to rotate through the proxies everytime make_request is called.

        s.proxies = d[0]
        page = s.get(url, timeout=3)

        print('proxy used: ' + str(d[0]))
    return page.content

Problem is, I can't seem to make the request fail when the proxy is not expected to work. It seems there is always a fallback on my internet ip if the proxy is not working.
For example: I tried passing a random proxy ip like 101.101.101.101:8800 or removing the ip authentication that is needed on my proxies, the request is still passed, even though it should'nt.

I thought adding the timeout parameters when passing the request would do the trick, but obviously it didn't.

So

Why does this happen?

How can I check from which ip a request is being made?

Body:
From what I have seen so far, you should use the form

s.get(url, proxies = d)

This should use the proxies in the dict d to make a connection.
This form allowed me to check with working proxies and non-working proxies the status_code

print(s.status_code)

I will update once I find out whether it just circulates over the proxies in the dict to match a working one, or one is able to actually select which one to be used.

[UPDATE]
Tried to work around the dict in proxies, to use different proxy if I wanted to. However, proxies must be a dict to work. So I used a dict in the form of:

d = {"https" : 'https://' + str(proxy_ips[n].strip('\n'))}

This seems to work and allow me to use an ip I want to. Although it seems quite dull, I hope someone might come and help!

The proxies used can be seen through:

requests.utils.getproxies()

or

requests.utils.get_environ_proxies(url)

I hope that helps, obviously quite old question, but still!

ContentLicense: CC BY-SA 4.0


问:
rails 3 custom mime type - default view format
I need to render some views without layout.
To skip line :render :layout=>false and if else logic from controller actions,
i have custom mime type like phtml (plain html).

```<code>Mime::Type.register "text/phtml", :phtml
</code>```

this format need to render the same html views, but only without layout. I complete this with this chunk of code in app. controller:

```<code> before_filter proc { |controller|
  if params[:format] && params[:format]=='phtml'
    controller.action_has_layout = false
    controller.request.format    = 'html'

  end
  }
</code>```

First, this is ugly, second i can't any more control this format from controller in the way:

```<code>respond_to :phtml,:only=>:index
</code>```

because it will always render view with requested format phtml.
is there a better solution? example? how can i alias view formats?

Thank a lot

答:
I haven't found better solution,only update to my previous example:

```<code> before_filter proc { |controller|
    if params[:format] && params[:format]=='plain_html' && controller.collect_mimes_from_class_level.include?(:plain_html)
      controller.action_has_layout = false
      controller.request.format    = 'html'
    end
  }
</code>```

i added this line to check is a new format defined into our controller:

```<code>controller.collect_mimes_from_class_level.include?(:plain_html)
</code>```

Now we can have full new format which will render our standard html vews rather the build new views for the new format.

This can be useful if we wont to share existing html code, but build different logic based on requested format.

For example, we can easily prepare our html content  for print like:

```<code>class PagesController < ActionController::Base

layout 'print',:only=>:show
respond_to :plain_html,:only=>[:show]

  def show
    Page.find(1)
    respond_with @page
  end
end
</code>```

And request will be like:

```<code>http://www.example.com/pages/1.plain_html
</code>```

I hope that someone will  find this useful.

If u have a better approach for doing this, please share with us.

Regards

Body:
I need to render some views without layout.
To skip line :render :layout=>false and if else logic from controller actions,
i have custom mime type like phtml (plain html).

Mime::Type.register "text/phtml", :phtml

this format need to render the same html views, but only without layout. I complete this with this chunk of code in app. controller:

 before_filter proc { |controller|
  if params[:format] && params[:format]=='phtml'
    controller.action_has_layout = false
    controller.request.format    = 'html'

  end
  }

First, this is ugly, second i can't any more control this format from controller in the way:

respond_to :phtml,:only=>:index

because it will always render view with requested format phtml.
is there a better solution? example? how can i alias view formats?

Thank a lot

Body:
I haven't found better solution,only update to my previous example:

 before_filter proc { |controller|
    if params[:format] && params[:format]=='plain_html' && controller.collect_mimes_from_class_level.include?(:plain_html)
      controller.action_has_layout = false
      controller.request.format    = 'html'
    end
  }

i added this line to check is a new format defined into our controller:

controller.collect_mimes_from_class_level.include?(:plain_html)

Now we can have full new format which will render our standard html vews rather the build new views for the new format.

This can be useful if we wont to share existing html code, but build different logic based on requested format.

For example, we can easily prepare our html content  for print like:

class PagesController < ActionController::Base

layout 'print',:only=>:show
respond_to :plain_html,:only=>[:show]

  def show
    Page.find(1)
    respond_with @page
  end
end

And request will be like:

http://www.example.com/pages/1.plain_html

I hope that someone will  find this useful.

If u have a better approach for doing this, please share with us.

Regards


问:
Illegal character \u201c
While compiling this I got an error. As well as I am still confused if I can create the object Overload before actually writing methods and declaring the variables.

```<code> class Overload {

    public static void main( String args[] ) {
    Overload overload = new Overload();
    Overload.methodOne();
    Overload.methodOne( 8 );
}

    void methodOne() {
    System.out.println(“no arguments”);
}

    void methodOne( int x) {
    System.out.println(“ integer value=” + x );
}

}
</code>```

At line I got an error illegal character:

'\u201c'

答: You are using the wrong quote character. You must use the simple double quote ", and you are using the unicode character '\u201c' “ instead. It's probably your editor biting you.

Title: Illegal character \u201c

Body:
While compiling this I got an error. As well as I am still confused if I can create the object Overload before actually writing methods and declaring the variables.

 class Overload {

    public static void main( String args[] ) {
    Overload overload = new Overload();
    Overload.methodOne();
    Overload.methodOne( 8 );
}

    void methodOne() {
    System.out.println(“no arguments”);
}

    void methodOne( int x) {
    System.out.println(“ integer value=” + x );
}

}

At line I got an error illegal character:

'\u201c'


问:
How to handle a heavy traffic on EC2 API Server after pushing a notification to mobile app?
My company is running food market apps and every 11:00AM, we push an app notification using AWS SNS service. Recently, we are having a heavy traffic and our 5 API servers on EC2(t2.medium) become very unstable. The problem is that heavy traffic only comes about 10 mins right after we send a push notification(11:00AM to 11:10AM). So I applied an auto-scaling but did not work because launching servers took some time and it crashes before scaling up. We are a start-up company so minimizing costs on servers would be wonderful. What solutions can be worked in this situation? </p>

答:
I will recommend a number areas to review:

EC2 Instance Size. Look at enabling T2 Unlimited. This was just announced at re:Invent 2017. This feature removes the CPU throttling that occurs. You only pay if you use it.

Auto Scaling. Before your push notification, increase your Auto Scaling Group manually, then reduce it after the blitz.

If your EC2 instances are taking a long time to come online, consider creating your own AMI with the instances already configured to reduce the time to come online.

Load Balancers. Amazon Classic Load Balancers require pre-warming before big spikes in traffic. If you are using CLB, upgrade to the newer ALB or NLB.

SSL Termination. Terminate your SSL at the load balancer. This will reduce CPU load on the EC2 instances.

CloudFront / S3. Move your static assets (img, js, css, graphics, documents, flyers, etc.) to S3 and serve via CloudFront.

Put CloudFront in front of your load balancers.

Reduce the speed of your push notification.


问:
Can I break an SQL statement with JOINs into smaller queries or optimize query?
I have query that's breaking an area of my website. The site spins forever when attempting to load the following SQL statement! I'm fairly new to sql statements and this particular statement was created by another developer. Is there a way to optimize the following statement? Or break it up into smaller statements so that it will run more quickly? I'm at a loss! I appreciate any help.</p>

```<code>SELECT
    `wp_quiz_users`.`Id`,
    `wp_quiz_users`.`SessionId`,
    `wp_quiz_users`.`Score`,
    `wp_quiz_users`.`Date`,
    `wp_quiz_users`.`Referrer`,
    `wp_quiz_users`.`ContactData`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 1) AS `SectionOne`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 2) AS `SectionTwo`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 3) AS `SectionThree`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 4) AS `SectionFour`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 5) AS `SectionFive`
FROM
    `wp_quiz_users`
</code>```

答:
This answer is similar to Gordon's except that it performs the aggregation for the sums inside a separate subquery.  This frees the outer query from needing to aggregate, and hence there should be no problem at all selecting any columns we want from the wp_quiz_users table.

```<code>SELECT
    t1.Id,
    t1.SessionId,
    t1.Score,
    t1.Date,
    t1.Referrer,
    t1.ContactData,
    COALESCE(t2.SectionOne, 0)   AS SectionOne,
    COALESCE(t2.SectionTwo, 0)   AS SectionTwo,
    COALESCE(t2.SectionThree, 0) AS SectionThree,
    COALESCE(t2.SectionFour, 0)  AS SectionFour,
    COALESCE(t2.SectionFive 0)   AS SectionFive
FROM wp_quiz_users t1
LEFT JOIN
(
    SELECT
        t1.UserId,
        SUM(CASE WHEN t2.Category = 1 THEN t1.AnswerValue ELSE 0 END) AS SectionOne,
        SUM(CASE WHEN t2.Category = 2 THEN t1.AnswerValue ELSE 0 END) AS SectionTwo,
        SUM(CASE WHEN t2.Category = 3 THEN t1.AnswerValue ELSE 0 END) AS SectionThree,
        SUM(CASE WHEN t2.Category = 4 THEN t1.AnswerValue ELSE 0 END) AS SectionFour,
        SUM(CASE WHEN t2.Category = 5 THEN t1.AnswerValue ELSE 0 END) AS SectionFive
    FROM wp_quiz_users_answers t1
    INNER JOIN wp_quiz_questions t2
        ON t1.QuestionId = t2.id
    GROUP BY t1.UserId
) t2
    ON t1.Id = t2.UserId;
</code>```

Body:
I have query that's breaking an area of my website. The site spins forever when attempting to load the following SQL statement! I'm fairly new to sql statements and this particular statement was created by another developer. Is there a way to optimize the following statement? Or break it up into smaller statements so that it will run more quickly? I'm at a loss! I appreciate any help.

SELECT
    `wp_quiz_users`.`Id`,
    `wp_quiz_users`.`SessionId`,
    `wp_quiz_users`.`Score`,
    `wp_quiz_users`.`Date`,
    `wp_quiz_users`.`Referrer`,
    `wp_quiz_users`.`ContactData`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 1) AS `SectionOne`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 2) AS `SectionTwo`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 3) AS `SectionThree`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 4) AS `SectionFour`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 5) AS `SectionFive`
FROM
    `wp_quiz_users`

Body:
This answer is similar to Gordon's except that it performs the aggregation for the sums inside a separate subquery.  This frees the outer query from needing to aggregate, and hence there should be no problem at all selecting any columns we want from the wp_quiz_users table.

SELECT
    t1.Id,
    t1.SessionId,
    t1.Score,
    t1.Date,
    t1.Referrer,
    t1.ContactData,
    COALESCE(t2.SectionOne, 0)   AS SectionOne,
    COALESCE(t2.SectionTwo, 0)   AS SectionTwo,
    COALESCE(t2.SectionThree, 0) AS SectionThree,
    COALESCE(t2.SectionFour, 0)  AS SectionFour,
    COALESCE(t2.SectionFive 0)   AS SectionFive
FROM wp_quiz_users t1
LEFT JOIN
(
    SELECT
        t1.UserId,
        SUM(CASE WHEN t2.Category = 1 THEN t1.AnswerValue ELSE 0 END) AS SectionOne,
        SUM(CASE WHEN t2.Category = 2 THEN t1.AnswerValue ELSE 0 END) AS SectionTwo,
        SUM(CASE WHEN t2.Category = 3 THEN t1.AnswerValue ELSE 0 END) AS SectionThree,
        SUM(CASE WHEN t2.Category = 4 THEN t1.AnswerValue ELSE 0 END) AS SectionFour,
        SUM(CASE WHEN t2.Category = 5 THEN t1.AnswerValue ELSE 0 END) AS SectionFive
    FROM wp_quiz_users_answers t1
    INNER JOIN wp_quiz_questions t2
        ON t1.QuestionId = t2.id
    GROUP BY t1.UserId
) t2
    ON t1.Id = t2.UserId;


问:
How can I select :last-child in d3.js?
I need to manipulate the text elements of the first and last tick of an axis to bring them more towards the center.

I am trying to select them, one at the time, with something like svg.select('.tick:last-child text') but it doesn't work. I'd then apply .transform('translate(4,0)')...

Am I doing something wrong? How can I achieve this?

答:
It's for D3.js v4

```<code>d3.selection.prototype.first = function() {
    return d3.select(
        this.nodes()[0]
    );
};
d3.selection.prototype.last = function() {
    return d3.select(
        this.nodes()[this.size() - 1]
    );
};
</code>```

Example:

```<code>var lines = svg.selectAll('line');
   lines.first()
      .attr('transform','translate(4,0)');
   lines.last()
      .attr('transform','translate(-4,0)');
</code>```

Title: How can I select :last-child in d3.js?

Body:
It's for D3.js v4

d3.selection.prototype.first = function() {
    return d3.select(
        this.nodes()[0]
    );
};
d3.selection.prototype.last = function() {
    return d3.select(
        this.nodes()[this.size() - 1]
    );
};

Example:

var lines = svg.selectAll('line');
   lines.first()
      .attr('transform','translate(4,0)');
   lines.last()
      .attr('transform','translate(-4,0)');


问:
Prevent extra whitespace when piping data in a Windows batch script
I have to run an executable (written in C#) 42 times separately for 42 US states on Windows command line. I wrote a batch file to automate the process. The 1st user input to the executable is 1, and the 2nd one is the state abbreviation (AL, AZ, CT etc.). I have written the following script to do it:

```<code>@echo off

for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (

    (echo 1 & echo %%x)|Z:\Models\LossCalc.exe
)
</code>```

Each row in CropHailStates.txt file contains the state abbreviation as follows:

AL

AZ

CT

Now in manual mode, when 1 is entered at the 1st prompt and AL is entered at the 2nd, the C# program reads a file named "AL.Even.CropLoss.csv". But when I run the batch script to do it automatically, I get the error message saying that the file "AL .Even.CropLoss.csv" is not found. The problem is related to the extra whitespace after AL. It’s somehow adding the whitespace after inserting the state abbreviation. It’s like pressing the spacebar after writing the state abbreviation, but before pressing enter.

How can I get rid of that extra whitespace in the file name?

答:
```<code>   (echo 1& echo %%x)>tempfile.txt
   Z:\Models\LossCalc.exe <tempfile.txt
   del tempfile.txt
</code>```

should provide the data without the trailing spaces

Body:
I have to run an executable (written in C#) 42 times separately for 42 US states on Windows command line. I wrote a batch file to automate the process. The 1st user input to the executable is 1, and the 2nd one is the state abbreviation (AL, AZ, CT etc.). I have written the following script to do it:

@echo off

for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (

    (echo 1 & echo %%x)|Z:\Models\LossCalc.exe
)

Each row in CropHailStates.txt file contains the state abbreviation as follows:

AL

AZ

CT

Now in manual mode, when 1 is entered at the 1st prompt and AL is entered at the 2nd, the C# program reads a file named "AL.Even.CropLoss.csv". But when I run the batch script to do it automatically, I get the error message saying that the file "AL .Even.CropLoss.csv" is not found. The problem is related to the extra whitespace after AL. It’s somehow adding the whitespace after inserting the state abbreviation. It’s like pressing the spacebar after writing the state abbreviation, but before pressing enter.

How can I get rid of that extra whitespace in the file name?

Body:
   (echo 1& echo %%x)>tempfile.txt
   Z:\Models\LossCalc.exe <tempfile.txt
   del tempfile.txt

should provide the data without the trailing spaces


问:
Ways to smoothly zoom in LibGDX?
I'm building a LibGDX game and need to zoom the camera in and out. But when I do camera.zoom = 1.2f;, it just 'jumps' to that value. Instead, I want to have a smooth zoom.

My question:
What's the best way to smoothly zoom?

I want to zoom like this graph below. y=0 is the start cam.zoom, y=100 is the desired cam.zoom and the x-axis shows the time.

Should I use cam.zoom = f(time);? (With some modification to f(x))

time is the total time passed since the beginning of the zoom.

Or is it better to use:

```<code>cam.zoom += (desiredZoom - cam.zoom) * delta * scalar;
</code>```

delta is the time between two frames and
 scalar is a float that will be adjusted in order to set the speed.

Or is there another, better way? What do you think?

Thanks a lot!

答:
Simplest way I know is use a countdown with an Interpolation.

```<code>// member variables:
float timeToCameraZoomTarget, cameraZoomTarget, cameraZoomOrigin, cameraZoomDuration;

private float zoomTo (float newZoom, float duration){
    cameraZoomOrigin = camera.zoom;
    cameraZoomTarget = newZoom;
    timeToCameraZoomTarget = cameraZoomDuration = duration;
}

// in render():
if (timeToCameraZoomTarget >= 0){
    timeToCameraZoomTarget -= deltaTime;
    float progress = timeToCameraZoomTarget < 0 ? 1 : 1f - timeToCameraZoomTarget / cameraZoomDuration;
    camera.zoom = Interpolation.pow3out.apply(cameraZoomOrigin, cameraZoomTarget, progress);
}
</code>```

You can replace Interpolation.pow3out with any of the functions pictured here.

Title: Ways to smoothly zoom in LibGDX?

Body:
I'm building a LibGDX game and need to zoom the camera in and out. But when I do camera.zoom = 1.2f;, it just 'jumps' to that value. Instead, I want to have a smooth zoom.

My question:
What's the best way to smoothly zoom?

I want to zoom like this graph below. y=0 is the start cam.zoom, y=100 is the desired cam.zoom and the x-axis shows the time.

Should I use cam.zoom = f(time);? (With some modification to f(x))

time is the total time passed since the beginning of the zoom.

Or is it better to use:

cam.zoom += (desiredZoom - cam.zoom) * delta * scalar;

delta is the time between two frames and
 scalar is a float that will be adjusted in order to set the speed.

Or is there another, better way? What do you think?

Thanks a lot!

Body:
Simplest way I know is use a countdown with an Interpolation.

// member variables:
float timeToCameraZoomTarget, cameraZoomTarget, cameraZoomOrigin, cameraZoomDuration;

private float zoomTo (float newZoom, float duration){
    cameraZoomOrigin = camera.zoom;
    cameraZoomTarget = newZoom;
    timeToCameraZoomTarget = cameraZoomDuration = duration;
}

// in render():
if (timeToCameraZoomTarget >= 0){
    timeToCameraZoomTarget -= deltaTime;
    float progress = timeToCameraZoomTarget < 0 ? 1 : 1f - timeToCameraZoomTarget / cameraZoomDuration;
    camera.zoom = Interpolation.pow3out.apply(cameraZoomOrigin, cameraZoomTarget, progress);
}

You can replace Interpolation.pow3out with any of the functions pictured here.


问:
Get container sizes in Azure Blob Storage using Python
I am trying to use block_blob_service library in Python in order to get the sizes of all containers in an Azure blob storage.
The following works, but takes too long (around 10 minutes for 50TB blob).

Is there a quicker way?

```<code>block_blob_service = BlockBlobService(account_name=azureAccount, account_key=azurekey)
containers = block_blob_service.list_containers()
for c in containers:
        contName = c.name
        generator = block_blob_service.list_blobs(contName)
        contSize = 0
        contNum = 0
        for blob in generator:
            contSize += blob.properties.content_length
            contNum += 1
        print(contName + " : " + str(contSize/1000000) + " MB" + " in " + str(contNum) + " blobs")
</code>```

答:
In addition to the SDK, you can use PowerShell script or a CLI script to get container size.

Also , you can view the container size on the portal directly.

I think the main issue of executing so long is that the storage blobs are too fragmented to increase the number of loops, compared to the capacity of the storage blobs.

So , I suggest you put the calculation in  Azure Function to ease the pressure of your application.

Hope it helps you.

Body:
I am trying to use block_blob_service library in Python in order to get the sizes of all containers in an Azure blob storage.
The following works, but takes too long (around 10 minutes for 50TB blob).

Is there a quicker way?

block_blob_service = BlockBlobService(account_name=azureAccount, account_key=azurekey)
containers = block_blob_service.list_containers()
for c in containers:
        contName = c.name
        generator = block_blob_service.list_blobs(contName)
        contSize = 0
        contNum = 0
        for blob in generator:
            contSize += blob.properties.content_length
            contNum += 1
        print(contName + " : " + str(contSize/1000000) + " MB" + " in " + str(contNum) + " blobs")


问:
Passing a hash as an initial value when creating an object
I am making a Temperature class with instance methods that convert the temperature from f to c, and vice-versa. A test case is:

```<code>Temperature.new(:f => 32).in_celsius #=> 0
</code>```

I thought that passing :f => 32 would give the conversion. I don't know how to extract the value 32 from the hash :f => 32. I want to extract that so that I can convert that number either into f or c.

Below is my answer code.

```<code>class Temperature
  def initialize(f = 0, c = 0)
    @f = f
    @c = c
  end

  def in_fahrenheit
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    @f
  end

  def celsius
    @c
  end
end
</code>```

I am not familiar with hashes passed as initial values when creating objects. I would appreciate any advice.

答:
If I were you, I think I'd do it something like:

```<code>class Temperature

  def initialize(input)
    puts "in #{self.class}.#{__method__}, input.class.name is: #{input.class.name}"
    @f, @c = input[:f], input[:c]
  end

  def in_fahrenheit
    return @f if @f
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    return @c if @c
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    return @f if @f
    in_fahrenheit
  end

  def celsius
    return @c if @c
    in_celsius
  end

end
</code>```

As Mark Thomas points out, initialize is receiving a Hash:

```<code>> t = Temperature.new(f: 32)
in Temperature.initialize, input.class.name is: Hash
 => #<Temperature:0x0000000996cbf8 @f=32, @c=nil>
</code>```

BTW, f: 32 is a bit more modern than :f => 32, I believe.

I added in some return statements. That way, you can do:

```<code>> t = Temperature.new(f: 32)
 => #<Temperature:0x00000009856ca0 @f=32, @c=nil>
> t.fahrenheit
 => 32
> t.celsius
 => 0
> t.in_fahrenheit
 => 32
> t.in_celsius
 => 0
</code>```

And:

```<code>> t = Temperature.new(c: 0)
 => #<Temperature:0x0000000986b038 @f=nil, @c=0>
> t.fahrenheit
 => 32
> t.celsius
 => 0
> t.in_fahrenheit
 => 32
> t.in_celsius
 => 0
</code>```

As Mark also said, you could do:

```<code>t = Temperature.new(f: 32, c: 32)
</code>```

But, that would give you all sorts of erroneous results. So, if you wanted to protect against that, you could do:

```<code>class Temperature

  def initialize(input)
    puts "in #{self.class}.#{__method__}, input.class.name is:"<<" #{input.class.name}"
    @f, @c = input[:f], input[:c]
    raise "Only one input, please!" if @f and @c
  end

  def in_fahrenheit
    return @f if @f
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    return @c if @c
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    return @f if @f
    in_fahrenheit
  end

  def celsius
    return @c if @c
    in_celsius
  end

end
</code>```

Which would give you something like:

```<code>> t = Temperature.new(f: 32, c: 0)
in Temperature.initialize, input.class.name is: Hash
RuntimeError: Only one input, please!
</code>```

Body:
I am making a Temperature class with instance methods that convert the temperature from f to c, and vice-versa. A test case is:

Temperature.new(:f => 32).in_celsius #=> 0

I thought that passing :f => 32 would give the conversion. I don't know how to extract the value 32 from the hash :f => 32. I want to extract that so that I can convert that number either into f or c.

Below is my answer code.

class Temperature
  def initialize(f = 0, c = 0)
    @f = f
    @c = c
  end

  def in_fahrenheit
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    @f
  end

  def celsius
    @c
  end
end

I am not familiar with hashes passed as initial values when creating objects. I would appreciate any advice.

Body:
If I were you, I think I'd do it something like:

class Temperature

  def initialize(input)
    puts "in #{self.class}.#{__method__}, input.class.name is: #{input.class.name}"
    @f, @c = input[:f], input[:c]
  end

  def in_fahrenheit
    return @f if @f
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    return @c if @c
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    return @f if @f
    in_fahrenheit
  end

  def celsius
    return @c if @c
    in_celsius
  end

end

As Mark Thomas points out, initialize is receiving a Hash:

> t = Temperature.new(f: 32)
in Temperature.initialize, input.class.name is: Hash
 => #<Temperature:0x0000000996cbf8 @f=32, @c=nil>

BTW, f: 32 is a bit more modern than :f => 32, I believe.

I added in some return statements. That way, you can do:

> t = Temperature.new(f: 32)
 => #<Temperature:0x00000009856ca0 @f=32, @c=nil>
> t.fahrenheit
 => 32
> t.celsius
 => 0
> t.in_fahrenheit
 => 32
> t.in_celsius
 => 0

And:

> t = Temperature.new(c: 0)
 => #<Temperature:0x0000000986b038 @f=nil, @c=0>
> t.fahrenheit
 => 32
> t.celsius
 => 0
> t.in_fahrenheit
 => 32
> t.in_celsius
 => 0

As Mark also said, you could do:

t = Temperature.new(f: 32, c: 32)

But, that would give you all sorts of erroneous results. So, if you wanted to protect against that, you could do:

class Temperature

  def initialize(input)
    puts "in #{self.class}.#{__method__}, input.class.name is:"<<" #{input.class.name}"
    @f, @c = input[:f], input[:c]
    raise "Only one input, please!" if @f and @c
  end

  def in_fahrenheit
    return @f if @f
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    return @c if @c
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    return @f if @f
    in_fahrenheit
  end

  def celsius
    return @c if @c
    in_celsius
  end

end

Which would give you something like:

> t = Temperature.new(f: 32, c: 0)
in Temperature.initialize, input.class.name is: Hash
RuntimeError: Only one input, please!


问:
Using addEventListener() in a for loop with various listeners
I'm trying to add listeners to a number of buttons using a for loop. The appropriate listener for each button is indicated by the ID attribute of the button. Button IDs follow the form "button-[listenerName]". I get the list of all my button elements using querySelectorAll(), and then I iterate through that list, slicing out the name of each listener from the name of each button element. Then, I use the name of the listener with addEventListener() in an attempt to associate that button with its listener.

```<code><!DOCTYPE html>
<html>
<body>

<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>

<p id="demo"></p>

<script>

var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
  var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
  button.addEventListener("click", listenerName);
}

var listener1 = function() {
  document.getElementById('demo').innerHtml = "1";
}

var listener2 = function() {
  document.getElementById('demo').innerHtml = "2";
}

var listener3 = function() {
  document.getElementById('demo').innerHtml = "3";
}

var listener4 = function() {
  document.getElementById('demo').innerHtml = "4";
}

</script>

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

Unfortunately, it doesn't work. What's up with that? Thank you.

答:
There are 3 issues with your code:

In your for loop, you are essentially attaching strings as eventlisteners. You need to access your event listeners from the string you have.

Since you eventlisteners are declared in the global scopre, you can use window to access them:

```<code>button.addEventListener("click", window[listenerName]);
</code>```

You are attaching the event listeners before declaring them. You need to declare listener1 and so on before your for loop

innerHtml does not exist. The right syntax is innerHTML

Here is a working example:

```<code><!DOCTYPE html>
<html>
<body>

<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>

<p id="demo"></p>

<script>

var listener1 = function() {
  document.getElementById('demo').innerHTML = "1";
}

var listener2 = function() {
  document.getElementById('demo').innerHTML = "2";
}

var listener3 = function() {
  document.getElementById('demo').innerHTML = "3";
}

var listener4 = function() {
  document.getElementById('demo').innerHTML = "4";
}

var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
  var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
  button.addEventListener("click", window[listenerName]);
}
</script>

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

Body:
I'm trying to add listeners to a number of buttons using a for loop. The appropriate listener for each button is indicated by the ID attribute of the button. Button IDs follow the form "button-[listenerName]". I get the list of all my button elements using querySelectorAll(), and then I iterate through that list, slicing out the name of each listener from the name of each button element. Then, I use the name of the listener with addEventListener() in an attempt to associate that button with its listener.

<!DOCTYPE html>

<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>

Unfortunately, it doesn't work. What's up with that? Thank you.

Body:
There are 3 issues with your code:

In your for loop, you are essentially attaching strings as eventlisteners. You need to access your event listeners from the string you have.

Since you eventlisteners are declared in the global scopre, you can use window to access them:

button.addEventListener("click", window[listenerName]);

You are attaching the event listeners before declaring them. You need to declare listener1 and so on before your for loop

innerHtml does not exist. The right syntax is innerHTML

Here is a working example:

<!DOCTYPE html>
<html>
<body>

<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>

<p id="demo"></p>

<script>

var listener1 = function() {
  document.getElementById('demo').innerHTML = "1";
}

var listener2 = function() {
  document.getElementById('demo').innerHTML = "2";
}

var listener3 = function() {
  document.getElementById('demo').innerHTML = "3";
}

var listener4 = function() {
  document.getElementById('demo').innerHTML = "4";
}

var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
  var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
  button.addEventListener("click", window[listenerName]);
}
</script>

</body>
</html>


答:
your line button.addEventListener("click", listenerName); tried to add a function called listenerName to the click event, and since listenerName is a variable and not a function, it doesn't work.

You could use an array of function to make it work instead.

```<code>var array_of_functions = [
    'listener1' : listener1,
    'listener2' : listener2,
    'listener3' : listener3,
    'listener4' : listener4
]
</code>```

and then in your loop you could create the listener by giving the right function:

```<code>button.addEventListener("click", array_of_functions[listenerName]);
</code>```

Also, make sure you create the function and the array before running the loop or they won't exist yet when the code runs.

Title: Using addEventListener() in a for loop with various listeners

Body:
your line button.addEventListener("click", listenerName); tried to add a function called listenerName to the click event, and since listenerName is a variable and not a function, it doesn't work.

You could use an array of function to make it work instead.

var array_of_functions = [
    'listener1' : listener1,
    'listener2' : listener2,
    'listener3' : listener3,
    'listener4' : listener4
]

and then in your loop you could create the listener by giving the right function:

button.addEventListener("click", array_of_functions[listenerName]);

Also, make sure you create the function and the array before running the loop or they won't exist yet when the code runs.


答:
First you should us the this double quote ", instead of this one “.

Second you should use the object name to invoke the method. Use overload instead of Overload (notice the case sensitivity)

Here is a working version of your code:

```<code>public class Overload {
    public static void main(String args[]) {
        Overload overload = new Overload();
        overload.methodOne();
        overload.methodOne(8);
    }
    void methodOne() {
        System.out.println("no arguments");
    }
    void methodOne(int x) {
        System.out.println("integer value=" + x);
    }
}
</code>```

Title: Illegal character \u201c

Body:
First you should us the this double quote ", instead of this one “.

Second you should use the object name to invoke the method. Use overload instead of Overload (notice the case sensitivity)

Here is a working version of your code:

public class Overload {
    public static void main(String args[]) {
        Overload overload = new Overload();
        overload.methodOne();
        overload.methodOne(8);
    }
    void methodOne() {
        System.out.println("no arguments");
    }
    void methodOne(int x) {
        System.out.println("integer value=" + x);
    }
}


问:
Change write location for neo4j-admin import
I'm trying to import around 300G of csv data to neo4j using the neo4j-admin import tool. However, the directory in which neo4j is stored does not have that much space available.

How do I change the directory that the import tool writes to? I tried:

```<code>--database= /new/directory/my.graphdb
</code>```

but got the following:

```<code>'database' should be a name but you seem to have specified a path:
</code>```

Can anyone explain how to do this?

答:
You specify the directory of a neo4j database in the dbms.directories.data property of the neo4j configuration file (which can be found at the location specified in this table, based on your environment). The directory can be specified as a relative path or an absolute path.

The --database option of neo4j-admin only specifies the name of the database file, not the directory.

Body:
I'm trying to import around 300G of csv data to neo4j using the neo4j-admin import tool. However, the directory in which neo4j is stored does not have that much space available.

How do I change the directory that the import tool writes to? I tried:

--database= /new/directory/my.graphdb

but got the following:

'database' should be a name but you seem to have specified a path:

Can anyone explain how to do this?


答:
There's a slightly easier way to do this - just have one function that handles the event:

```<code>for (var button of allButtons) {
  button.addEventListener("click", handleClick, false);
}

function handleClick() {
  var id = this.id.match(/button-listener(\d)/)[1];
  document.getElementById('demo').innerHTML = id;
}
</code>```

DEMO

Body:
There's a slightly easier way to do this - just have one function that handles the event:

for (var button of allButtons) {
  button.addEventListener("click", handleClick, false);
}

function handleClick() {
  var id = this.id.match(/button-listener(\d)/)[1];
  document.getElementById('demo').innerHTML = id;
}

DEMO