问:
Desperately seeking the answer to my pointer problem
I have been working on a college C assignment, and have been trying to make sense of a bug I seem to be having with my code. Basically, it seems like something is wrong with my pointers (and or memory allocation).

This assignment is primarily about linked lists, so the structs contain pointers to the next element in the list. Obviously, to traverse the list until I find that the current element has a NULL pointer to the next element (and then I change that to be the pointer to the 'new' element I want to add.

The problem I have though, is for some reason my code seems to be completely screwing with my memory pointers, because they're getting garbled somehow.  They seem fine for moment but very soon go rubbish.

Here is what my watches in XCode's debugger are showing me:

The first circle shows me the values as the first element in the list, which as far as I can tell are initially set correctly, and should be "C0001\0". The second circle shows the current->nextCategory pointer which should be NULL (0x0) but instead show that weird memory address (look at the size of it!). I assume that these problems are related, but as I am new to C, I don't know how or why.

In either case, when I check current->nextCategory != NULL in my while statement, it throws EXC_BAD_ACCESS:

I've spent the past few hours pulling my hair out becasue I cannot work out what the heck is happening to my program.  Am I doing something wrong with my pointers, or using malloc() improperly?

Here is the relevant part of my program:

```<code>/****************************************************************************
* Initialises the system to a safe empty state.
****************************************************************************/
void systemInit(GJCType* menu)
{
   if (menu == NULL) {
      fprintf(stderr, "can't initialize system with a null menu pointer.\n");
      exit(EXIT_FAILURE);
   }
   menu->headCategory = NULL;
   menu->numCategories = 0;
}

/****************************************************************************
* Loads all data into the system.
****************************************************************************/
int loadData(GJCType* menu, char* menuFile, char* submenuFile)
{
   FILE *fp;
   size_t len;
   char *line;
   char *buffer;
   CategoryTypePtr category_p;
   ItemTypePtr item_p;
   char *catId;

   if (menu == NULL)
      return FALSE;

   fp = fopen(menuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", menuFile);
      return FALSE;
    }

   buffer = malloc(MAX_BUFFER_SIZE);
   len = MAX_BUFFER_SIZE;
   catId = malloc(ID_LEN + 1);

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      category_p = malloc(sizeof(CategoryTypePtr));

      if (!tokenizeCategory(line, category_p)) {
         fprintf(stderr, "can't tokenize category:> %s\n", line);
         free(category_p);
         category_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      pushCategory(menu, category_p);
      free(category_p);
      category_p = NULL;
   }

   fp = fopen(submenuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", submenuFile);
      return FALSE;
    }

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      item_p = malloc(sizeof(ItemTypePtr));

      if (!tokenizeItem(line, item_p, catId)) {
         fprintf(stderr, "can't tokenize item:> %s\n", line);
         free(item_p);
         item_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      category_p = findCategory(menu, catId);
      pushItem(category_p, item_p);
      free(item_p);
      item_p = NULL;
   }

   free(buffer);
   free(catId);
   return TRUE;
}

void pushItem(CategoryTypePtr category, ItemTypePtr item)
{
   ItemTypePtr current;
   ItemTypePtr new;

   if ((new = malloc(sizeof(ItemTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new item pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *item;

   if (category->headItem == NULL) {
      category->headItem = new;
   } else {
      current = category->headItem;
      while (current->nextItem != NULL) {
         current = current->nextItem;
      }
      current->nextItem = new;

   }
   category->numItems++;
}

void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr current;
   CategoryTypePtr new;

   if ((new = malloc(sizeof(CategoryTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new category pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *category;

   if (menu->headCategory == NULL) {
      menu->headCategory = new;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = new;
   }
   menu->numCategories++;
}

CategoryTypePtr findCategory(GJCType* menu, char* id)
{
   CategoryTypePtr current;

   current = menu->headCategory;
   while (current != NULL) {
      if (!strcmp(current->categoryID, id))
         return current;
      current = current->nextCategory;
   }
   return NULL;
}

/* This function takes the character delimited string and converts it into
 * a category structure at the location of the category pointer supplied.
 */
int tokenizeCategory(char *data, CategoryTypePtr category)
{
   char* buffer;

   if (category == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(category->categoryID, strtok(buffer, "|\n"));
   category->drinkType = *(strtok(NULL, "|\n"));
   strcpy(category->categoryName, strtok(NULL, "|\n"));
   strcpy(category->categoryDescription, strtok(NULL, "|\n"));
   category->numItems = 0;
   category->nextCategory = NULL;
   category->headItem = NULL;
   free(buffer);
   return TRUE;
}

/* This function takes the character delimited string and converts it into
 * an item structure at the location of the item pointer supplied.
 */
int tokenizeItem(char *data, ItemTypePtr item, char* categoryId)
{
   char* buffer;
   int i;

   if (item == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(item->itemID, strtok(buffer, "|\n"));
   strcpy(categoryId, strtok(NULL, "|\n"));
   strcat(categoryId, "\0");
   strcpy(item->itemName, strtok(NULL, "|\n"));
   for (i = 0; i < NUM_PRICES; i++)
      sscanf(strtok(NULL, "|\n"),"%d.%d",&(item->prices[i].dollars),&(item->prices[i].cents));
   strcpy(item->itemDescription, strtok(NULL, "|\n"));
   item->nextItem = NULL;
   free(buffer);
   return TRUE;
}
</code>```

Header definitions:

```<code>/* System-wide constants. */
#define ID_LEN 5
#define MIN_NAME_LEN 1
#define MAX_NAME_LEN 25
#define MIN_DESC_LEN 1
#define MAX_DESC_LEN 250
#define NUM_PRICES 3
#define HOT 'H'
#define COLD 'C'
#define FALSE 0
#define TRUE 1
#define MAX_BUFFER_SIZE 1024

typedef struct category* CategoryTypePtr;
typedef struct item* ItemTypePtr;

/* Structure definitions. */
typedef struct price
{
   unsigned dollars;
   unsigned cents;
} PriceType;

typedef struct item
{
   char itemID[ID_LEN + 1];
   char itemName[MAX_NAME_LEN + 1];
   PriceType prices[NUM_PRICES];
   char itemDescription[MAX_DESC_LEN + 1];
   ItemTypePtr nextItem;
} ItemType;

typedef struct category
{
   char categoryID[ID_LEN + 1];
   char categoryName[MAX_NAME_LEN + 1];
   char drinkType;      /* (H)ot or (C)old. */
   char categoryDescription[MAX_DESC_LEN + 1];
   CategoryTypePtr nextCategory;
   ItemTypePtr headItem;
   unsigned numItems;
} CategoryType;

typedef struct gjc
{
   CategoryTypePtr headCategory;
   unsigned numCategories;
} GJCType;
</code>```

答:
You have multiple issues. Besides incorrectly allocating memory you are doing

```<code>*new = *category;
</code>```

in your pushCategory function expecting to automagically copy the internal contents of the category structure: that simply doesn't work. You'll need to allocate a new CategoryType object and then copy each individual element appropriately. Something like this:

```<code>void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr newCategory;
   CategoryTypePtr current;

   if ((newCategory = malloc(sizeof(CategoryType))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new category pointer.\n");
      exit(EXIT_FAILURE);
   }

      // copy individual elements here and set values properly
      newCategory->headItem = NULL;
      strncpy(newCategory->categoryID, category->categoryID, ID_LEN);
      // copy other strings and NULL-initialize other pointers

   if (menu->headCategory == NULL) {
      menu->headCategory = new;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = newCategory;
   }
   menu->numCategories++;
}
</code>```

You will need to do the same thing for pushItem.

Body:
I have been working on a college C assignment, and have been trying to make sense of a bug I seem to be having with my code. Basically, it seems like something is wrong with my pointers (and or memory allocation).

This assignment is primarily about linked lists, so the structs contain pointers to the next element in the list. Obviously, to traverse the list until I find that the current element has a NULL pointer to the next element (and then I change that to be the pointer to the 'new' element I want to add.

The problem I have though, is for some reason my code seems to be completely screwing with my memory pointers, because they're getting garbled somehow.  They seem fine for moment but very soon go rubbish.

Here is what my watches in XCode's debugger are showing me:

The first circle shows me the values as the first element in the list, which as far as I can tell are initially set correctly, and should be "C0001\0". The second circle shows the current->nextCategory pointer which should be NULL (0x0) but instead show that weird memory address (look at the size of it!). I assume that these problems are related, but as I am new to C, I don't know how or why.

In either case, when I check current->nextCategory != NULL in my while statement, it throws EXC_BAD_ACCESS:

I've spent the past few hours pulling my hair out becasue I cannot work out what the heck is happening to my program.  Am I doing something wrong with my pointers, or using malloc() improperly?

Here is the relevant part of my program:

/****************************************************************************
* Initialises the system to a safe empty state.
****************************************************************************/
void systemInit(GJCType* menu)
{
   if (menu == NULL) {
      fprintf(stderr, "can't initialize system with a null menu pointer.\n");
      exit(EXIT_FAILURE);
   }
   menu->headCategory = NULL;
   menu->numCategories = 0;
}

/****************************************************************************
* Loads all data into the system.
****************************************************************************/
int loadData(GJCType* menu, char* menuFile, char* submenuFile)
{
   FILE *fp;
   size_t len;
   char *line;
   char *buffer;
   CategoryTypePtr category_p;
   ItemTypePtr item_p;
   char *catId;

   if (menu == NULL)
      return FALSE;

   fp = fopen(menuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", menuFile);
      return FALSE;
    }

   buffer = malloc(MAX_BUFFER_SIZE);
   len = MAX_BUFFER_SIZE;
   catId = malloc(ID_LEN + 1);

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      category_p = malloc(sizeof(CategoryTypePtr));

      if (!tokenizeCategory(line, category_p)) {
         fprintf(stderr, "can't tokenize category:> %s\n", line);
         free(category_p);
         category_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      pushCategory(menu, category_p);
      free(category_p);
      category_p = NULL;
   }

   fp = fopen(submenuFile, "r");
   if(fp == NULL) {
      fprintf(stderr, "can't open %s\n", submenuFile);
      return FALSE;
    }

   while((buffer = fgetln(fp, &len))) {
      line = strtok(buffer, "\n\0");
      item_p = malloc(sizeof(ItemTypePtr));

      if (!tokenizeItem(line, item_p, catId)) {
         fprintf(stderr, "can't tokenize item:> %s\n", line);
         free(item_p);
         item_p = NULL;
         free(buffer);
         free(catId);
         return FALSE;
      }
      category_p = findCategory(menu, catId);
      pushItem(category_p, item_p);
      free(item_p);
      item_p = NULL;
   }

   free(buffer);
   free(catId);
   return TRUE;
}

void pushItem(CategoryTypePtr category, ItemTypePtr item)
{
   ItemTypePtr current;
   ItemTypePtr new;

   if ((new = malloc(sizeof(ItemTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new item pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *item;

   if (category->headItem == NULL) {
      category->headItem = new;
   } else {
      current = category->headItem;
      while (current->nextItem != NULL) {
         current = current->nextItem;
      }
      current->nextItem = new;

   }
   category->numItems++;
}

void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr current;
   CategoryTypePtr new;

   if ((new = malloc(sizeof(CategoryTypePtr))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new category pointer.\n");
      exit(EXIT_FAILURE);
   }

   *new = *category;

   if (menu->headCategory == NULL) {
      menu->headCategory = new;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = new;
   }
   menu->numCategories++;
}

CategoryTypePtr findCategory(GJCType* menu, char* id)
{
   CategoryTypePtr current;

   current = menu->headCategory;
   while (current != NULL) {
      if (!strcmp(current->categoryID, id))
         return current;
      current = current->nextCategory;
   }
   return NULL;
}

/* This function takes the character delimited string and converts it into
 * a category structure at the location of the category pointer supplied.
 */
int tokenizeCategory(char *data, CategoryTypePtr category)
{
   char* buffer;

   if (category == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(category->categoryID, strtok(buffer, "|\n"));
   category->drinkType = *(strtok(NULL, "|\n"));
   strcpy(category->categoryName, strtok(NULL, "|\n"));
   strcpy(category->categoryDescription, strtok(NULL, "|\n"));
   category->numItems = 0;
   category->nextCategory = NULL;
   category->headItem = NULL;
   free(buffer);
   return TRUE;
}

/* This function takes the character delimited string and converts it into
 * an item structure at the location of the item pointer supplied.
 */
int tokenizeItem(char *data, ItemTypePtr item, char* categoryId)
{
   char* buffer;
   int i;

   if (item == NULL || strlen(data) < 1)
      return FALSE;

   buffer = malloc(MAX_BUFFER_SIZE);
   strcpy(buffer, data);
   strcpy(item->itemID, strtok(buffer, "|\n"));
   strcpy(categoryId, strtok(NULL, "|\n"));
   strcat(categoryId, "\0");
   strcpy(item->itemName, strtok(NULL, "|\n"));
   for (i = 0; i < NUM_PRICES; i++)
      sscanf(strtok(NULL, "|\n"),"%d.%d",&(item->prices[i].dollars),&(item->prices[i].cents));
   strcpy(item->itemDescription, strtok(NULL, "|\n"));
   item->nextItem = NULL;
   free(buffer);
   return TRUE;
}

Header definitions:

/* System-wide constants. */
#define ID_LEN 5
#define MIN_NAME_LEN 1
#define MAX_NAME_LEN 25
#define MIN_DESC_LEN 1
#define MAX_DESC_LEN 250
#define NUM_PRICES 3
#define HOT 'H'
#define COLD 'C'
#define FALSE 0
#define TRUE 1
#define MAX_BUFFER_SIZE 1024

typedef struct category* CategoryTypePtr;
typedef struct item* ItemTypePtr;

/* Structure definitions. */
typedef struct price
{
   unsigned dollars;
   unsigned cents;
} PriceType;

typedef struct item
{
   char itemID[ID_LEN + 1];
   char itemName[MAX_NAME_LEN + 1];
   PriceType prices[NUM_PRICES];
   char itemDescription[MAX_DESC_LEN + 1];
   ItemTypePtr nextItem;
} ItemType;

typedef struct category
{
   char categoryID[ID_LEN + 1];
   char categoryName[MAX_NAME_LEN + 1];
   char drinkType;      /* (H)ot or (C)old. */
   char categoryDescription[MAX_DESC_LEN + 1];
   CategoryTypePtr nextCategory;
   ItemTypePtr headItem;
   unsigned numItems;
} CategoryType;

typedef struct gjc
{
   CategoryTypePtr headCategory;
   unsigned numCategories;
} GJCType;

Body:
You have multiple issues. Besides incorrectly allocating memory you are doing

*new = *category;

in your pushCategory function expecting to automagically copy the internal contents of the category structure: that simply doesn't work. You'll need to allocate a new CategoryType object and then copy each individual element appropriately. Something like this:

void pushCategory(GJCType* menu, CategoryTypePtr category)
{
   CategoryTypePtr newCategory;
   CategoryTypePtr current;

   if ((newCategory = malloc(sizeof(CategoryType))) == NULL) {
      fprintf(stderr, "can't malloc enough memory for new category pointer.\n");
      exit(EXIT_FAILURE);
   }

      // copy individual elements here and set values properly
      newCategory->headItem = NULL;
      strncpy(newCategory->categoryID, category->categoryID, ID_LEN);
      // copy other strings and NULL-initialize other pointers

   if (menu->headCategory == NULL) {
      menu->headCategory = new;
   } else {
      current = menu->headCategory;
      while (current->nextCategory != NULL) {
         current = current->nextCategory;
      }
      current->nextCategory = newCategory;
   }
   menu->numCategories++;
}

You will need to do the same thing for pushItem.


来源: stackexchange

问:
What am I doing wrong? - Uncaught TypeError: Object(...) is not a function - React GraphQL
I read in other posts that to solve this issue I need to install "react": "16.8.0" and "react-dom": "16.8.0", I already did that and the error persists-

This is the first time messing with GraphQL, here is my code (simplified)

```<code>import React from 'react'
import { Query } from 'react-apollo'
import { gql } from 'graphql-tag'

const Header = () => (
      <Query query={
         gql`
          {
            menu(id: "TWVudToy") {
              menuId
            }
          }`
      }>

        {
          ({ loading, error, data }) => {
            console.log(data)
            return <div>ff</div>
        }

        }
      </Query>

)

export default Header
</code>```

The full error is

```<code>Uncaught TypeError: Object(...) is not a function
    at Header (index.js:40)
    at renderWithHooks (react-dom.development.js:12740)
    at mountIndeterminateComponent (react-dom.development.js:14670)
    at beginWork (react-dom.development.js:15194)
    at performUnitOfWork (react-dom.development.js:18780)
    at workLoop (react-dom.development.js:18820)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at replayUnitOfWork (react-dom.development.js:18052)
</code>```

答:
Use the default import from graphql-tag, e.g.:

```<code>import gql from 'graphql-tag'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I read in other posts that to solve this issue I need to install "react": "16.8.0" and "react-dom": "16.8.0", I already did that and the error persists-

This is the first time messing with GraphQL, here is my code (simplified)

import React from 'react'
import { Query } from 'react-apollo'
import { gql } from 'graphql-tag'

const Header = () => (
      <Query query={
         gql`
          {
            menu(id: "TWVudToy") {
              menuId
            }
          }`
      }>

        {
          ({ loading, error, data }) => {
            console.log(data)
            return
ff

        }

        }
      </Query>

)

export default Header

The full error is

Uncaught TypeError: Object(...) is not a function
    at Header (index.js:40)
    at renderWithHooks (react-dom.development.js:12740)
    at mountIndeterminateComponent (react-dom.development.js:14670)
    at beginWork (react-dom.development.js:15194)
    at performUnitOfWork (react-dom.development.js:18780)
    at workLoop (react-dom.development.js:18820)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at replayUnitOfWork (react-dom.development.js:18052)

Body:
Use the default import from graphql-tag, e.g.:

import gql from 'graphql-tag'


问:
Python sum of number in array, ignoring sections of specific numbers
I am very new to Python and have been going through multiple tutorials to get better.

I have straggled with one difficult problem and found a solution. But it feels, works very newbie like. I think that I have tailored it to answer the specific question.

So the question is:

SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.

```<code>summer_69([1, 3, 5]) --> 9
summer_69([4, 5, 6, 7, 8, 9]) --> 9
summer_69([2, 1, 6, 9, 11]) --> 14
</code>```

My code to solve this is:

```<code>def summer_69(arr):
    list1 = arr
    summ = int()
    for i in range(0, len(arr)):
        if 6 in list1:
            listOfRange = range(list1.index(6), list1.index(9) + 1)
            for index in listOfRange:
                    print(listOfRange)
                    arr[index] = 0
            if 6 != arr[i]:
                summ += arr[i]
            else:
                continue
        else:
            summ += arr[i]
    return summ
</code>```

It is a very basic problem and I am very alerted that I have struggled with something like this already.

答:
def summer_69(arr):
    if 6 in arr:
        c=arr[arr.index(6):arr.index(9)+1]
        for i in c:
            arr.remove(i)
        print(arr)
        return sum(arr)
    else:
        return sum(arr)

summer_69([1,2,3,4,5,6,7,8,9,10,11,12])
```

Body:
I am very new to Python and have been going through multiple tutorials to get better.

I have straggled with one difficult problem and found a solution. But it feels, works very newbie like. I think that I have tailored it to answer the specific question.

So the question is:

SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.

summer_69([1, 3, 5]) --> 9
summer_69([4, 5, 6, 7, 8, 9]) --> 9
summer_69([2, 1, 6, 9, 11]) --> 14

My code to solve this is:

def summer_69(arr):
    list1 = arr
    summ = int()
    for i in range(0, len(arr)):
        if 6 in list1:
            listOfRange = range(list1.index(6), list1.index(9) + 1)
            for index in listOfRange:
                    print(listOfRange)
                    arr[index] = 0
            if 6 != arr[i]:
                summ += arr[i]
            else:
                continue
        else:
            summ += arr[i]
    return summ

It is a very basic problem and I am very alerted that I have struggled with something like this already.


问:
Complex sorting by single colum in R
I am trying to sort a data frame by codes contained in one column.

The logic behind these code is:

S/number/number/number/digit (e.g. S120B). The numbers are not always 3 (e.g. S10K) and the letters are not always present (e.g. S2).

The first code is S1, and the list goes until S999, where it turns to S1A. Then it goes to S999A and then turns to S1B, and so on.

Furthermore, there are also codes inside thare are totally different, as W23, E100, etc that should go together.

How can I order the dataframe according to this pretty sick ordering scheme?

MWE: codes <- c(S1, S20D, S550C, S88A, S420K, E44, W22)

答:
1.Create minimal reproducible example ;)

```<code>mre <- data.frame(ID = c("S1", "S20D", "S550C", "S88A", "S420K", "E44", "W22"),
                stringsAsFactors = FALSE)
</code>```

Now, I am not sure what you mean by:

Furthermore, there are also codes inside thare are totally different, as W23, E100, etc that should go together.

If you mean that "W23" should be read an sorted totally different than "S999" we need some additional information on how to distinguish between the two cases. Otherwise this should work:

2.Suggested solution alphabetical sorting:

```<code>library(dplyr)
mre %>%
  arrange(ID)

     ID
1   E44
2    S1
3  S20D
4 S420K
5 S550C
6  S88A
7   W22
</code>```

Or using only base R:

```<code>mre[order(mre$ID),]
</code>```

Title: Complex sorting by single colum in R

Body:
1.Create minimal reproducible example ;)

mre <- data.frame(ID = c("S1", "S20D", "S550C", "S88A", "S420K", "E44", "W22"),
                stringsAsFactors = FALSE)

Now, I am not sure what you mean by:

Furthermore, there are also codes inside thare are totally different, as W23, E100, etc that should go together.

If you mean that "W23" should be read an sorted totally different than "S999" we need some additional information on how to distinguish between the two cases. Otherwise this should work:

2.Suggested solution alphabetical sorting:

library(dplyr)
mre %>%
  arrange(ID)

     ID
1   E44
2    S1
3  S20D
4 S420K
5 S550C
6  S88A
7   W22

Or using only base R:

mre[order(mre$ID),]


问:
How to change soap context's mode in Gsoap when deploying a service using mod_gsoap?
So I am deploying a web service developed using gsoap using mod_gsoap. I wanted to set SOAP_IO_KEEPALIVE and SOAP_IO_CHUNK modes of the soap context object to accept chunked requests. How do I achieve this?
Or is there any other way to accept chunked requests? Right now the server responds as soon as it receives the first chunk without waiting for the rest.

答:
The documentation says:

Warning

Do not use any of the SOAP_IO flags to initialize or set the
  context, such as SOAP_IO_KEEPALIVE and SOAP_IO_CHUNK.

The Apache server controls the connection settings and HTTP payload parameters to send and receive HTTP requests. Data is received with ap_get_client_block, which de-chunks the content when chunked.


问:
Set QFrame width to match QTableWidget
I need to set a QFrame to properly match a QTableWidget's width.
I have tried setting different size policies but nothing I have done worked, so I ran out of ideas.

This is my code:

```<code>from PySide2 import QtWidgets
from PySide2.QtWidgets import QTableWidget

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.showMaximized()
        # Create a table
        table = QTableWidget(1, 3)
        table.setHorizontalHeaderLabels(['Column A', 'Column B', 'Column C'])
        # Create a frame
        myFrame = QtWidgets.QFrame(self)
        myFrame.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Ignored))
        myFrame.setFrameShape(QtWidgets.QFrame.Box)
        # Create frame's layout
        frameLayout = QtWidgets.QVBoxLayout()
        frameLayout.addWidget(table)
        myFrame.setLayout(frameLayout)
        # Create central widget
        centralWidget = QtWidgets.QWidget()
        # Create central widget's layout
        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(myFrame)
        centralWidget.setLayout(layout)
        # Set central widget
        self.setCentralWidget(centralWidget)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())
</code>```

P.S.: I know centralWidget isn't necessary here, but this code is just a portion of my whole project so I have to keep it since the solution may be different without it.

答:
sizeAdjustPolicy : SizeAdjustPolicy

This property holds the policy describing how the size of the scroll area changes when the size of the viewport changes.

The default policy is QAbstractScrollArea::AdjustIgnored. Changing this property might actually resize the scrollarea.

```<code>table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)  # <---
</code>```

```<code>#from PySide2 import QtWidgets
#from PySide2.QtWidgets import QTableWidget
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QTableWidget

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.showMaximized()

        # Create a table
        table = QTableWidget(1, 3)
        table.setHorizontalHeaderLabels(['Column A', 'Column B', 'Column C'])

        table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)  # <---

        # Create a frame
        myFrame = QtWidgets.QFrame(self)
        myFrame.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Ignored))
        myFrame.setFrameShape(QtWidgets.QFrame.Box)
        # Create frame's layout
        frameLayout = QtWidgets.QVBoxLayout()
        frameLayout.addWidget(table)
        myFrame.setLayout(frameLayout)
        # Create central widget
        centralWidget = QtWidgets.QWidget()
        # Create central widget's layout
        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(myFrame)
        centralWidget.setLayout(layout)
        # Set central widget
        self.setCentralWidget(centralWidget)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())
</code>```

Title: Set QFrame width to match QTableWidget

Body:
I need to set a QFrame to properly match a QTableWidget's width.
I have tried setting different size policies but nothing I have done worked, so I ran out of ideas.

This is my code:

from PySide2 import QtWidgets
from PySide2.QtWidgets import QTableWidget

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.showMaximized()
        # Create a table
        table = QTableWidget(1, 3)
        table.setHorizontalHeaderLabels(['Column A', 'Column B', 'Column C'])
        # Create a frame
        myFrame = QtWidgets.QFrame(self)
        myFrame.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Ignored))
        myFrame.setFrameShape(QtWidgets.QFrame.Box)
        # Create frame's layout
        frameLayout = QtWidgets.QVBoxLayout()
        frameLayout.addWidget(table)
        myFrame.setLayout(frameLayout)
        # Create central widget
        centralWidget = QtWidgets.QWidget()
        # Create central widget's layout
        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(myFrame)
        centralWidget.setLayout(layout)
        # Set central widget
        self.setCentralWidget(centralWidget)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

P.S.: I know centralWidget isn't necessary here, but this code is just a portion of my whole project so I have to keep it since the solution may be different without it.

Body:
sizeAdjustPolicy : SizeAdjustPolicy

This property holds the policy describing how the size of the scroll area changes when the size of the viewport changes.

The default policy is QAbstractScrollArea::AdjustIgnored. Changing this property might actually resize the scrollarea.

table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)  # <---

#from PySide2 import QtWidgets
#from PySide2.QtWidgets import QTableWidget
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QTableWidget

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.showMaximized()

        # Create a table
        table = QTableWidget(1, 3)
        table.setHorizontalHeaderLabels(['Column A', 'Column B', 'Column C'])

        table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)  # <---

        # Create a frame
        myFrame = QtWidgets.QFrame(self)
        myFrame.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Ignored))
        myFrame.setFrameShape(QtWidgets.QFrame.Box)
        # Create frame's layout
        frameLayout = QtWidgets.QVBoxLayout()
        frameLayout.addWidget(table)
        myFrame.setLayout(frameLayout)
        # Create central widget
        centralWidget = QtWidgets.QWidget()
        # Create central widget's layout
        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(myFrame)
        centralWidget.setLayout(layout)
        # Set central widget
        self.setCentralWidget(centralWidget)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())


问:
Using GerritHub with GitHub Actions
I would like to add a project to gerrithub.io, where the continuous integration parts are done by GitHub Actions. I am considering the following steps given a new change to Gerrit:

Replicate the change branch to GitHub.

Add appropriate GitHub CI Actions to run on the change branch.

Notify gerrithub.io about the CI result.

I am thinking of using Gerrit's REST API to do the notification in 3. However, I do not have a solution to the replication in 1. Any ideas?

答:
GerritHub allows to import GitHub PRs into Gerrit Changes, however, it looks like you would like to do the opposite and have the changes starting in Gerrit and import them as GitHub PRs.

Unfortunately, there isn't a solution available out-of-the-box right now.
It shouldn't be very difficult to implement by using the GitHub API, however, I do see a problem having chained Changes represented in GitHub, because PRs cannot be chained.

HTH.

Luca.

Title: Using GerritHub with GitHub Actions


问:
Valet Plus Installation Problems - MacOS Catalina
I've had Valet Plus installed on my Mac for about 2 years with no problems. Then the other week it suddenly stopped working, I think after upgrading to Catalina, by saying the apcu_fetch() could not be found.

Thinking it was me that had screwed something up, I uninstalled everything to start again, and now I cant install valet again due to pecl not being able to connect via ssl.

Whenever I run pecl install apcu_bc it just returns Connection to 'ssl://pecl.php.net:443' failed.

Whenever I sometimes get past this part, by installing and uninstalling different versions of php, I then end up back in the same situation of  cant find apcu_fetch

I have tried following every single bit advice on the web that references these problems to no avail.

Is anyone else having the same problems and has any new advice please as I am going crazy!

答:
Due to issues with the apcu_bc pecl extension install and growing support for PHP 7.0+ within the apcu pecl extension, deprecate the use of apcu_bc. To ensure new apcu install do the following for every PHP version installed:

Uninstall your pecl installed apcu extensions pecl uninstall apcu && pecl uninstall apcu_bc

Remove the apcu.so and apc.so extensions from /usr/local/etc/valet-php//php.ini


问:
Quarkus kubernetesMockServer for application initialization
I am working on a Quarkus application to acct as an Operator in a OpenShift/Kubernetes cluster. When writing the tests using a kubernetesMockServer it is working fine for REST calls to developed application but when code runs inside an Initialization Block it is failing, in the log I see that mock server is replying with a 404 error:

```<code>2020-02-17 11:04:12,148 INFO  [okh.moc.MockWebServer] (MockWebServer /127.0.0.1:53048) MockWebServer[57577] received request: GET /apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions HTTP/1.1 and responded: HTTP/1.1 404 Client Error
</code>```

On the TestCode I have:

@QuarkusTestResource(KubernetesMockServerTestResource.class)
@QuarkusTest
class TestAIRController {

    @MockServer
    KubernetesMockServer mockServer;

    private CustomResourceDefinition crd;
    private CustomResourceDefinitionList crdlist;

    @BeforeEach
    public void before() {
        crd = new CustomResourceDefinitionBuilder()
            .withApiVersion("apiextensions.k8s.io/v1beta1")
            .withNewMetadata().withName("types.openshift.example-cloud.com")
            .endMetadata()
            .withNewSpec()
            .withNewNames()
            .withKind("Type")
            .withPlural("types")
            .endNames()
            .withGroup("openshift.example-cloud.com")
            .withVersion("v1")
            .withScope("Namespaced")
            .endSpec()
            .build();
        crdlist = new CustomResourceDefinitionListBuilder().withItems(crd).build();
        mockServer.expect().get().withPath("/apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions")
            .andReturn(200, crdlist)
            .always();
    }

    @Test
    void test() {
        RestAssured.when().get("/dummy").then().body("size()", Is.is(0));
    }

}

```

<p>The dummy rest is using the same code for searching the CRD, and in fact when running withouth the class observing the startup event it works fine</p>

<pre class="lang-java prettyprint-override"><code>@Path("/dummy")
public class Dummy {

    private static final Logger LOGGER =LoggerFactory.getLogger(Dummy.class);

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response listCRDs(){
        KubernetesClient oc = new DefaultKubernetesClient();
        CustomResourceDefinition crd = oc.customResourceDefinitions()
                .list().getItems().stream()
                    .filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
                    .findFirst().get();
        LOGGER.info("CRD NAME is {}", crd.getMetadata().getName());
        return Response.ok(new ArrayList<String>()).build();
    }
}

</code>```

Finally this is an except of the

```<code>@ApplicationScoped
public class AIRWatcher {

    private static final Logger LOGGER = LoggerFactory.getLogger(AIRWatcher.class);

    void OnStart(@Observes StartupEvent ev) {
        KubernetesClient oc = new DefaultKubernetesClient();
        CustomResourceDefinition crd = oc.customResourceDefinitions()
                .list().getItems().stream()
                    .filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
                    .findFirst().get();
        LOGGER.info("Using {}", crd.getMetadata().getName());

    }

}

</code>```

It's like for some reason the mock server is still not initialized for the Startup event, is there any way to solve it?

答:
The problem is that the Mock Server is only configured to respond right before the test execution, while this code:

```<code>void OnStart(@Observes StartupEvent ev) {
        KubernetesClient oc = new DefaultKubernetesClient();
        CustomResourceDefinition crd = oc.customResourceDefinitions()
                .list().getItems().stream()
                    .filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
                    .findFirst().get();
        LOGGER.info("Using {}", crd.getMetadata().getName());

    }
</code>```

runs when the application is actually comes up (which is before any @BeforeEach runs).

Can you please open an issue on the Quarkus Github? This should be something we provide a solution for

Body:
I am working on a Quarkus application to acct as an Operator in a OpenShift/Kubernetes cluster. When writing the tests using a kubernetesMockServer it is working fine for REST calls to developed application but when code runs inside an Initialization Block it is failing, in the log I see that mock server is replying with a 404 error:

2020-02-17 11:04:12,148 INFO  [okh.moc.MockWebServer] (MockWebServer /127.0.0.1:53048) MockWebServer[57577] received request: GET /apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions HTTP/1.1 and responded: HTTP/1.1 404 Client Error

On the TestCode I have:

@QuarkusTestResource(KubernetesMockServerTestResource.class)
@QuarkusTest
class TestAIRController {

    @MockServer
    KubernetesMockServer mockServer;

    private CustomResourceDefinition crd;
    private CustomResourceDefinitionList crdlist;

    @BeforeEach
    public void before() {
        crd = new CustomResourceDefinitionBuilder()
            .withApiVersion("apiextensions.k8s.io/v1beta1")
            .withNewMetadata().withName("types.openshift.example-cloud.com")
            .endMetadata()
            .withNewSpec()
            .withNewNames()
            .withKind("Type")
            .withPlural("types")
            .endNames()
            .withGroup("openshift.example-cloud.com")
            .withVersion("v1")
            .withScope("Namespaced")
            .endSpec()
            .build();
        crdlist = new CustomResourceDefinitionListBuilder().withItems(crd).build();
        mockServer.expect().get().withPath("/apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions")
            .andReturn(200, crdlist)
            .always();
    }

    @Test
    void test() {
        RestAssured.when().get("/dummy").then().body("size()", Is.is(0));
    }

}

The dummy rest is using the same code for searching the CRD, and in fact when running withouth the class observing the startup event it works fine

@Path("/dummy")
public class Dummy {

    private static final Logger LOGGER =LoggerFactory.getLogger(Dummy.class);

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response listCRDs(){
        KubernetesClient oc = new DefaultKubernetesClient();
        CustomResourceDefinition crd = oc.customResourceDefinitions()
                .list().getItems().stream()
                    .filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
                    .findFirst().get();
        LOGGER.info("CRD NAME is {}", crd.getMetadata().getName());
        return Response.ok(new ArrayList<String>()).build();
    }
}

Finally this is an except of the

@ApplicationScoped
public class AIRWatcher {

    private static final Logger LOGGER = LoggerFactory.getLogger(AIRWatcher.class);

    void OnStart(@Observes StartupEvent ev) {
        KubernetesClient oc = new DefaultKubernetesClient();
        CustomResourceDefinition crd = oc.customResourceDefinitions()
                .list().getItems().stream()
                    .filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
                    .findFirst().get();
        LOGGER.info("Using {}", crd.getMetadata().getName());

    }

}

It's like for some reason the mock server is still not initialized for the Startup event, is there any way to solve it?

Body:
The problem is that the Mock Server is only configured to respond right before the test execution, while this code:

void OnStart(@Observes StartupEvent ev) {
        KubernetesClient oc = new DefaultKubernetesClient();
        CustomResourceDefinition crd = oc.customResourceDefinitions()
                .list().getItems().stream()
                    .filter( ob -> ob.getMetadata().getName().equals("types.openshift.example-cloud.com"))
                    .findFirst().get();
        LOGGER.info("Using {}", crd.getMetadata().getName());

    }

runs when the application is actually comes up (which is before any @BeforeEach runs).

Can you please open an issue on the Quarkus Github? This should be something we provide a solution for


问:
Vuetify - Get object's single property on v-select
I am creating a form with Vuetify, which has initial values on some inputs and these values come from objects.
Basically, the objects have two important properties: the name and the id. Folllowing the Vuetify docs, i'm using item-text prop to display the object's name on the v-select and item-value to return the object's id when the option is selected. When another option is selected, it returns the id as expected. However, if the initial option is not changed, the returned value is the whole object, instead of just the id.

The context is this:

```<code>       <v-select
          label="Select an specialty..."
          v-model="entry.specialty"
          :items="specialties"
          :item-text="item=>item.name"
          :item-value="item=>item.id"
        ></v-select>
</code>```

The entry object has the specialty property and the initial specialty's name is displayed on the select. I think the problem is the v-model, which has the whole specialty object. I tried to set the v-model as entry.specialty.id, but it did not work as expected.

Let me know if there's more information i can give.

答:
Try to set the property return-object:

```<code><v-select
  label="Select an specialty..."
  v-model="entry.specialty"
  :items="specialties"
  :item-text="item=>item.name"
  :item-value="item=>item.id"
  :return-object="false"
/>
</code>```

The return-obejct can be: true or false

If this don't work, please post whole component code.

Body:
I am creating a form with Vuetify, which has initial values on some inputs and these values come from objects.
Basically, the objects have two important properties: the name and the id. Folllowing the Vuetify docs, i'm using item-text prop to display the object's name on the v-select and item-value to return the object's id when the option is selected. When another option is selected, it returns the id as expected. However, if the initial option is not changed, the returned value is the whole object, instead of just the id.

The context is this:

       <v-select
          label="Select an specialty..."
          v-model="entry.specialty"
          :items="specialties"
          :item-text="item=>item.name"
          :item-value="item=>item.id"
        ></v-select>

The entry object has the specialty property and the initial specialty's name is displayed on the select. I think the problem is the v-model, which has the whole specialty object. I tried to set the v-model as entry.specialty.id, but it did not work as expected.

Let me know if there's more information i can give.

Body:
Try to set the property return-object:

<v-select
  label="Select an specialty..."
  v-model="entry.specialty"
  :items="specialties"
  :item-text="item=>item.name"
  :item-value="item=>item.id"
  :return-object="false"
/>

The return-obejct can be: true or false

If this don't work, please post whole component code.


问:
Generate a PDF and return a response
Today I have faced a problem with generating PDF using KnpSnappyBundle on symfony.

I'm running a route using AJAX, the code works fine, but it does not generate the PDF,

What I want to accomplish here is to generate a PDF in new tab or window
and return a successful message to the client.

Here is my code:

```<code> /**
 * @Route("/api/release_bills/{month}/{year}/{region}", name="api_print_bills", methods={"GET","POST"})
 * @param BillRepository $billRepository
 * @param ConsumptionRepository $consumptionRepository
 * @param Request $request
 * @param Snappy $snappy
 * @param $month
 * @param $year
 * @param $region
 * @return Response
 * @throws Exception
 */
public function releaseBills(BillRepository $billRepository,ConsumptionRepository $consumptionRepository, Request $request, Snappy $snappy,  $month,$year,$region ): Response
{
    $error = array();
    $success = array();
    if( $month>0 && $month<13 || preg_match("/^\d{4}$/",$year)||$region!=''){

        if($year>=2018 && $year <=2050){
            $entityManager = $this->getDoctrine()->getManager();

                $bills = $consumptionRepository->findAllWaterMetersForBilling($month,$year,$region);

                $isBillsExisted = $billRepository->findAllBillsByDate($month,$year,$region);

                if(empty($bills)){
                    array_push($error,['error'=>'there is not bills to be release for this criteria : [ city: '.$region.', year :'.$year.', and Month : '.$month.'!]']);
                    return new JsonResponse($error);
                }

                $arr = array();
                $newBills = array();
                $billsEnd=end($bills);

                foreach ($bills as $key=>$b){
                    $wmNumber =  $b->getWaterMeter()->getWmNumber();
                    $fullName = $b->getWaterMeter()->getClient()->getFullName();
                    $cin = $b->getWaterMeter()->getClient()->getCin();
                    $address= $b->getWaterMeter()->getAddress();
                    $wmAddress = $b->getWaterMeter()->getAddress()->getStreetAddress();
                    $city = $b->getWaterMeter()->getAddress()->getCity();
                    $zipCode = $b->getWaterMeter()->getAddress()->getZipCode();
                    $billCode = $b->getId();
                    $consumptionDate = $b->getDate();
                    $oldConsumption=$b->getPreviousRecord();
                    $newConsumption=$b->getCurrentRecord();
                    $printDate =new \DateTime('now');
                    $consumption=$b->getConsumption();
                    $cost = $b->getCost()+10;
                    $wmReferenceNumber = $b->getWaterMeter()->getWmReferenceNumber();
                    $client= $b->getWaterMeter()->getClient();
                    // tranche calculation
                    //==================================================
                    $tranche1 = $consumption >= 5 ? 5 : $consumption; //4
                    $tranche2 = $consumption - $tranche1 >= 5 ? 5: 0; //0
                    $tranche3 = $consumption - $tranche1 - $tranche2;
                    //==================================================
                    $bill = new Bill();
                    $bill->setCode($wmNumber);
                    $bill->setFullName($fullName);
                    $bill->setCin($cin);
                    $bill->setPrintDate($printDate);
                    $bill->setCost($cost);
                    $bill->setConsumption($consumption);
                    $bill->setConsumptionDate($consumptionDate);
                    $bill->setPreviousRecord($oldConsumption);
                    $bill->setNewRecord($newConsumption);
                    $bill->setWaterMeter($b->getWaterMeter());
                    $bill->setRegion($city);
                    $bill->setClient($client);
                    $entityManager->persist($bill);
                    array_push($arr,['wmAddress'=>$wmAddress,'city'=>$city,'zipCode'=>$zipCode,'tranche1'=>$tranche1,'wmNumber'=>$wmNumber,'fullName'=>$fullName,'cin'=>$cin,'address'=>strval($address),'billCode'=>$billCode,'consumptionDate'=>$consumptionDate,'oldConsumption'=>$oldConsumption,'newConsumption'=>$newConsumption,'printDate'=>$printDate,'consumption'=>$consumption,'cost'=>$cost,'wmReferenceNumber'=>$wmReferenceNumber]);

                    if(count($arr)==6||$billCode==$billsEnd->getId()){
                        array_push($newBills,$arr);
                        $arr = array();
                    }

                }

                $date = new \DateTime('now');
                $html= $this->renderView('bill/bill.html.twig', array(
                    'arrayBills'=>$newBills,
                ));

                if($isBillsExisted){
                    return new PdfResponse(
                        $snappy->getOutputFromHtml($html), "bill_".$date->format('Y-m-d').".pdf"
                    );
                }
                $entityManager->flush(); //Persist objects that did not make up an entire batch
                $entityManager->clear();

                return new PdfResponse(
                    $snappy->getOutputFromHtml($html), "bill_".$date->format('Y-m-d').".pdf"
                );

            }
        }
    array_push($success,['success'=>'bills were successfully released']);
    return new JsonResponse($success);
}
</code>```

And my AJAX call is:

```<code> generatePDF = () =>{
        const {yearValue, monthValue, regionValue}= this.state;
        $.ajax({
            url: `http://symfony.localhost/bill/api/release_bills/${monthValue.value}/${yearValue.value}/${regionValue.value}`,
            success: function (data) {
                console.log('DATA',data)
            }.bind(this)
        });
    };
</code>```

I believe that I can't return more than one response, anyway I have done console log to the response of the ajax call  displays the HTML content of the page I want to generate a PDF from and no PDF is being generated.

答:
with the help of a friend i managed to generate pdf , but still i don't know how to return a an error or successful message when a the Pdf get generated or not.

here is what i did:

```<code>generatePDF = () =>{
    const {yearValue, monthValue, regionValue}= this.state;

    var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
    var URL = `http://symfony.localhost/bill/api/release_bills/${monthValue.value}/${yearValue.value}/${regionValue.value}`;
    window.open(URL, "_blank", strWindowFeatures);
};
</code>```

the function generatePDF gets called on onClick button

Title: Generate a PDF and return a response

Body:
Today I have faced a problem with generating PDF using KnpSnappyBundle on symfony.

I'm running a route using AJAX, the code works fine, but it does not generate the PDF,

What I want to accomplish here is to generate a PDF in new tab or window
and return a successful message to the client.

Here is my code:

 /**
 * @Route("/api/release_bills/{month}/{year}/{region}", name="api_print_bills", methods={"GET","POST"})
 * @param BillRepository $billRepository
 * @param ConsumptionRepository $consumptionRepository
 * @param Request $request
 * @param Snappy $snappy
 * @param $month
 * @param $year
 * @param $region
 * @return Response
 * @throws Exception
 */
public function releaseBills(BillRepository $billRepository,ConsumptionRepository $consumptionRepository, Request $request, Snappy $snappy,  $month,$year,$region ): Response
{
    $error = array();
    $success = array();
    if( $month>0 && $month<13 || preg_match("/^\d{4}$/",$year)||$region!=''){

        if($year>=2018 && $year <=2050){
            $entityManager = $this->getDoctrine()->getManager();

                $bills = $consumptionRepository->findAllWaterMetersForBilling($month,$year,$region);

                $isBillsExisted = $billRepository->findAllBillsByDate($month,$year,$region);

                if(empty($bills)){
                    array_push($error,['error'=>'there is not bills to be release for this criteria : [ city: '.$region.', year :'.$year.', and Month : '.$month.'!]']);
                    return new JsonResponse($error);
                }

                $arr = array();
                $newBills = array();
                $billsEnd=end($bills);

                foreach ($bills as $key=>$b){
                    $wmNumber =  $b->getWaterMeter()->getWmNumber();
                    $fullName = $b->getWaterMeter()->getClient()->getFullName();
                    $cin = $b->getWaterMeter()->getClient()->getCin();
                    $address= $b->getWaterMeter()->getAddress();
                    $wmAddress = $b->getWaterMeter()->getAddress()->getStreetAddress();
                    $city = $b->getWaterMeter()->getAddress()->getCity();
                    $zipCode = $b->getWaterMeter()->getAddress()->getZipCode();
                    $billCode = $b->getId();
                    $consumptionDate = $b->getDate();
                    $oldConsumption=$b->getPreviousRecord();
                    $newConsumption=$b->getCurrentRecord();
                    $printDate =new \DateTime('now');
                    $consumption=$b->getConsumption();
                    $cost = $b->getCost()+10;
                    $wmReferenceNumber = $b->getWaterMeter()->getWmReferenceNumber();
                    $client= $b->getWaterMeter()->getClient();
                    // tranche calculation
                    //==================================================
                    $tranche1 = $consumption >= 5 ? 5 : $consumption; //4
                    $tranche2 = $consumption - $tranche1 >= 5 ? 5: 0; //0
                    $tranche3 = $consumption - $tranche1 - $tranche2;
                    //==================================================
                    $bill = new Bill();
                    $bill->setCode($wmNumber);
                    $bill->setFullName($fullName);
                    $bill->setCin($cin);
                    $bill->setPrintDate($printDate);
                    $bill->setCost($cost);
                    $bill->setConsumption($consumption);
                    $bill->setConsumptionDate($consumptionDate);
                    $bill->setPreviousRecord($oldConsumption);
                    $bill->setNewRecord($newConsumption);
                    $bill->setWaterMeter($b->getWaterMeter());
                    $bill->setRegion($city);
                    $bill->setClient($client);
                    $entityManager->persist($bill);
                    array_push($arr,['wmAddress'=>$wmAddress,'city'=>$city,'zipCode'=>$zipCode,'tranche1'=>$tranche1,'wmNumber'=>$wmNumber,'fullName'=>$fullName,'cin'=>$cin,'address'=>strval($address),'billCode'=>$billCode,'consumptionDate'=>$consumptionDate,'oldConsumption'=>$oldConsumption,'newConsumption'=>$newConsumption,'printDate'=>$printDate,'consumption'=>$consumption,'cost'=>$cost,'wmReferenceNumber'=>$wmReferenceNumber]);

                    if(count($arr)==6||$billCode==$billsEnd->getId()){
                        array_push($newBills,$arr);
                        $arr = array();
                    }

                }

                $date = new \DateTime('now');
                $html= $this->renderView('bill/bill.html.twig', array(
                    'arrayBills'=>$newBills,
                ));

                if($isBillsExisted){
                    return new PdfResponse(
                        $snappy->getOutputFromHtml($html), "bill_".$date->format('Y-m-d').".pdf"
                    );
                }
                $entityManager->flush(); //Persist objects that did not make up an entire batch
                $entityManager->clear();

                return new PdfResponse(
                    $snappy->getOutputFromHtml($html), "bill_".$date->format('Y-m-d').".pdf"
                );

            }
        }
    array_push($success,['success'=>'bills were successfully released']);
    return new JsonResponse($success);
}

And my AJAX call is:

 generatePDF = () =>{
        const {yearValue, monthValue, regionValue}= this.state;
        $.ajax({
            url: `http://symfony.localhost/bill/api/release_bills/${monthValue.value}/${yearValue.value}/${regionValue.value}`,
            success: function (data) {
                console.log('DATA',data)
            }.bind(this)
        });
    };

I believe that I can't return more than one response, anyway I have done console log to the response of the ajax call  displays the HTML content of the page I want to generate a PDF from and no PDF is being generated.

Body:
with the help of a friend i managed to generate pdf , but still i don't know how to return a an error or successful message when a the Pdf get generated or not.

here is what i did:

generatePDF = () =>{
    const {yearValue, monthValue, regionValue}= this.state;

    var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
    var URL = `http://symfony.localhost/bill/api/release_bills/${monthValue.value}/${yearValue.value}/${regionValue.value}`;
    window.open(URL, "_blank", strWindowFeatures);
};

the function generatePDF gets called on onClick button


问:
It doesn't let me use or statements
This was working just fine until I added in the or statements then it gave me these errors:

error CS1525: Unexpected symbol `)'

error CS1525: Unexpected symbol else'

```<code>      if (age < 18 && age1 < 18 && age2 < 18 || age > 3 && age1 > 3 && age2 > 3){
      Console.WriteLine("Everyone got into the playground today!");
    } else if(age > 18 && age1 > 18 && age2 > 18 || age < 3 && age1 < 3 && age2 < 3)){
      Console.WriteLine("No one got into the playground today!");
    } else if(age1 > 18 && age2 > 18 || age1 < 3 && age2 < 3){
      Console.WriteLine(name1 + " and " + name2 + " Couldn't get into the playground today");
    }
</code>```

答:
Extra ) showing up on this line

```<code>} else if(age > 18 && age1 > 18 && age2 > 18 || age < 3 && age1 < 3 && age2 < 3)){
</code>```

it should be

```<code>} else if(age > 18 && age1 > 18 && age2 > 18 || age < 3 && age1 < 3 && age2 < 3){
</code>```

Title: It doesn't let me use or statements

Body:
This was working just fine until I added in the or statements then it gave me these errors:

error CS1525: Unexpected symbol `)'

error CS1525: Unexpected symbol else'

      if (age < 18 && age1 < 18 && age2 < 18 || age > 3 && age1 > 3 && age2 > 3){
      Console.WriteLine("Everyone got into the playground today!");
    } else if(age > 18 && age1 > 18 && age2 > 18 || age < 3 && age1 < 3 && age2 < 3)){
      Console.WriteLine("No one got into the playground today!");
    } else if(age1 > 18 && age2 > 18 || age1 < 3 && age2 < 3){
      Console.WriteLine(name1 + " and " + name2 + " Couldn't get into the playground today");
    }

Body:
Extra ) showing up on this line

} else if(age > 18 && age1 > 18 && age2 > 18 || age < 3 && age1 < 3 && age2 < 3)){

it should be

} else if(age > 18 && age1 > 18 && age2 > 18 || age < 3 && age1 < 3 && age2 < 3){


问:
Issue with url_for mapping variables to URL if multiple routes are used
I've hit an issue with url_for, where it won't automatically remap the variable straight into the URL because there are two routes.

My use case is an API, where creating an object will return the same data as if a GET command was run on it.

Here's an example of the code:

```<code>@app.route('/test', methods=['POST'])
@app.route('/test/<string:name>', methods=['GET'])
def test(name=None):
    if request.method == 'POST':
        return redirect(url_for('test', name='xyz'))
    return name
</code>```

If the first app.route is removed, then url_for('test', name='xyz') will correctly return "test/xyz".

However, with both app.route lines, it instead returns "test?name=xyz". This then causes name to be None, where the variable is actually located at request.args['name'].

I don't want to do a if name is None: name=request.args.get('name'), so is there any way I can force it to only look at routes with a GET method? My case right now is simple enough I could just do url_for('test')+'/xyz', but it seems like there should be better way of doing this.

答:
According to the Flask Docs you can specify which method to map against use the _method argument.

flask.url_for(endpoint, **values)
```

<p>And the values you can pass are:</p>

<ul>
<li><strong>endpoint</strong> – the endpoint of the URL (name of the function)</li>
<li><strong>values</strong> – the variable arguments of the URL rule</li>
<li><strong>_external</strong> – if set to True, an absolute URL is generated. Server address can be changed via SERVER_NAME configuration variable which falls back to the Host header, then to the IP and port of the request.</li>
<li><strong>_scheme</strong> – a string specifying the desired URL scheme. The _external parameter must be set to True or a ValueError is raised. The default behavior uses the same scheme as the current request, or PREFERRED_URL_SCHEME from the app configuration if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs.</li>
<li><strong>_anchor</strong> – if provided this is added as anchor to the URL.</li>
<li><strong>_method</strong> – if provided this explicitly specifies an HTTP method. <---- This one</li>
</ul>

<p>Specify the <strong>_method</strong> argument in url_for like this:</p>

<pre class="lang-py prettyprint-override"><code>url_for('test', name='xyz', _method='GET')
</code>```

Body:
I've hit an issue with url_for, where it won't automatically remap the variable straight into the URL because there are two routes.

My use case is an API, where creating an object will return the same data as if a GET command was run on it.

Here's an example of the code:

@app.route('/test', methods=['POST'])
@app.route('/test/<string:name>', methods=['GET'])
def test(name=None):
    if request.method == 'POST':
        return redirect(url_for('test', name='xyz'))
    return name

If the first app.route is removed, then url_for('test', name='xyz') will correctly return "test/xyz".

However, with both app.route lines, it instead returns "test?name=xyz". This then causes name to be None, where the variable is actually located at request.args['name'].

I don't want to do a if name is None: name=request.args.get('name'), so is there any way I can force it to only look at routes with a GET method? My case right now is simple enough I could just do url_for('test')+'/xyz', but it seems like there should be better way of doing this.

Body:
According to the Flask Docs you can specify which method to map against use the _method argument.

flask.url_for(endpoint, **values)

And the values you can pass are:

endpoint – the endpoint of the URL (name of the function)

values – the variable arguments of the URL rule

_external – if set to True, an absolute URL is generated. Server address can be changed via SERVER_NAME configuration variable which falls back to the Host header, then to the IP and port of the request.

_scheme – a string specifying the desired URL scheme. The _external parameter must be set to True or a ValueError is raised. The default behavior uses the same scheme as the current request, or PREFERRED_URL_SCHEME from the app configuration if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs.

_anchor – if provided this is added as anchor to the URL.

_method – if provided this explicitly specifies an HTTP method. <---- This one

Specify the _method argument in url_for like this:

url_for('test', name='xyz', _method='GET')


问:
Dictionary of tensors input for Keras Functional API TensorFlow 2.0
I have a dataset of dictionary of tensors, and the following model defined using the  subclassing API:

```<code>class Model(tf.keras.Model):

  def __init__(self):
    super().__init__()
    self._movie_full_dense = tf.keras.layers.Dense(
        units=40, activation=tf.keras.layers.Activation("relu"))
    self._user_full_dense = tf.keras.layers.Dense(
        units=40, activation=tf.keras.layers.Activation("relu"))
    self._full_dense = tf.keras.layers.Dense(
        units=1, activation=tf.keras.layers.Activation("sigmoid"))

  def call(self, features):
    movie_embedding = self._movie_full_dense(features['movie'])
    user_embedding = self._user_full_dense(features['user'])
    combined = tf.concat([movie_embedding, user_embedding], 1)
    output = self._full_dense(combined)
    return output
</code>```

I want to implement it using the functional API. but I do not know how to define the inputs? Namely, what is the functional equivalent for the following?

```<code>self._movie_full_dense(features['movie'])
</code>```

答:
```<code>import tensorflow as tf

print(tf.version.VERSION)

toy_data = {'movie': [[0], [1], [0], [1]], 'user': [[10], [12], [12], [10]]}
dataset = tf.data.Dataset.from_tensor_slices(toy_data).batch(2)

for x in dataset:
    print(x)

def make_model():
    inp_movie = tf.keras.Input(shape=(1,))
    inp_user = tf.keras.Input(shape=(1,))
    movie_embedding = tf.keras.layers.Dense(
            units=40, activation=tf.keras.layers.Activation("relu"))(inp_movie)
    user_embedding = tf.keras.layers.Dense(
            units=40, activation=tf.keras.layers.Activation("relu"))(inp_user)
    combined = tf.concat([movie_embedding, user_embedding], 1)
    output = tf.keras.layers.Dense(
            units=1, activation=tf.keras.layers.Activation("sigmoid"))(combined)
    model = tf.keras.Model(inputs=[inp_movie, inp_user], outputs=output)
    return model

model = make_model()

for x in dataset:
    print(model(x))
</code>```

This works. Beware that the iterable you pass to the inputs argument of the tf.keras.Model call has to be sorted in the same order as the dictionary you will use, which is sorted by its keys, movie then user. So using inputs={'a': inp_movie, 'b': inp_user} or inputs={'movie': inp_movie, 'user': inp_user} also works, while inputs=[inp_user, inp_movie] won't.

You can use this code to test this kind of interaction:

```<code>def make_test_model():
    inp_movie = tf.keras.Input(shape=(1,))
    inp_user = tf.keras.Input(shape=(1,))
    model = tf.keras.Model(inputs={'a': inp_movie, 'b': inp_user}, outputs=inp_movie)
    return model

def make_test_model_2():
    inp_movie = tf.keras.Input(shape=(1,))
    inp_user = tf.keras.Input(shape=(1,))
    model = tf.keras.Model(inputs=[inp_user, inp_movie], outputs=inp_movie)
    return model

model_test = make_test_model()
model_test_2 = make_test_model_2()

for x in dataset:
    print(model_test(x))
for x in dataset:
    print(model_test_2(x))
</code>```

You can also name the Input layers using the keys of your dictonary, and give as the inputs argument a list of Input layers sorted by the layers names. This allows you to add or remove inputs in your model without having to worry about rewriting your inputs argument each time. So this is what I would do:

```<code>def make_model_2():
    input_list = []
    inp_movie = tf.keras.Input(shape=(1,), name='movie')
    input_list.append(inp_movie)
    inp_user = tf.keras.Input(shape=(1,), name='user')
    input_list.append(inp_user)
    movie_embedding = tf.keras.layers.Dense(
            units=40, activation=tf.keras.layers.Activation("relu"))(inp_movie)
    user_embedding = tf.keras.layers.Dense(
            units=40, activation=tf.keras.layers.Activation("relu"))(inp_user)
    combined = tf.concat([movie_embedding, user_embedding], 1)
    output = tf.keras.layers.Dense(
            units=1, activation=tf.keras.layers.Activation("sigmoid"))(combined)
    input_list.sort(key=lambda inp: inp._keras_history.layer.name)
    model = tf.keras.Model(inputs=input_list, outputs=output)
    return model
</code>```

Here is a way to test that it works:

```<code>def make_test_model_3(boolean):
    input_list = []
    inp_movie = tf.keras.Input(shape=(1,), name='movie')
    inp_user = tf.keras.Input(shape=(1,), name='user')
    if boolean:
        input_list.append(inp_movie)
        input_list.append(inp_user)
    else:
        input_list.append(inp_user)
        input_list.append(inp_movie)
    input_list.sort(key=lambda inp: inp._keras_history.layer.name)
    model = tf.keras.Model(inputs=input_list, outputs=inp_movie)
    return model

model_test_3_0= make_test_model_3(True)
model_test_3_1= make_test_model_3(False)

for x in dataset:
    print(model_test_3_0(x))
for x in dataset:
    print(model_test_3_1(x))
</code>```

Edit 2020-02-20:

make_model does not work with tf2.1.0, but make_model_2 still does. I have oppened an issue on GitHub about this backward incompatibility. Here is the link if you are interested. Recall that both functions work if you plan to stay on tf2.0.0.

Body:
I have a dataset of dictionary of tensors, and the following model defined using the  subclassing API:

class Model(tf.keras.Model):

  def __init__(self):
    super().__init__()
    self._movie_full_dense = tf.keras.layers.Dense(
        units=40, activation=tf.keras.layers.Activation("relu"))
    self._user_full_dense = tf.keras.layers.Dense(
        units=40, activation=tf.keras.layers.Activation("relu"))
    self._full_dense = tf.keras.layers.Dense(
        units=1, activation=tf.keras.layers.Activation("sigmoid"))

  def call(self, features):
    movie_embedding = self._movie_full_dense(features['movie'])
    user_embedding = self._user_full_dense(features['user'])
    combined = tf.concat([movie_embedding, user_embedding], 1)
    output = self._full_dense(combined)
    return output

I want to implement it using the functional API. but I do not know how to define the inputs? Namely, what is the functional equivalent for the following?

self._movie_full_dense(features['movie'])

Body:
import tensorflow as tf

print(tf.version.VERSION)

toy_data = {'movie': [[0], [1], [0], [1]], 'user': [[10], [12], [12], [10]]}
dataset = tf.data.Dataset.from_tensor_slices(toy_data).batch(2)

for x in dataset:
    print(x)

def make_model():
    inp_movie = tf.keras.Input(shape=(1,))
    inp_user = tf.keras.Input(shape=(1,))
    movie_embedding = tf.keras.layers.Dense(
            units=40, activation=tf.keras.layers.Activation("relu"))(inp_movie)
    user_embedding = tf.keras.layers.Dense(
            units=40, activation=tf.keras.layers.Activation("relu"))(inp_user)
    combined = tf.concat([movie_embedding, user_embedding], 1)
    output = tf.keras.layers.Dense(
            units=1, activation=tf.keras.layers.Activation("sigmoid"))(combined)
    model = tf.keras.Model(inputs=[inp_movie, inp_user], outputs=output)
    return model

model = make_model()

for x in dataset:
    print(model(x))

This works. Beware that the iterable you pass to the inputs argument of the tf.keras.Model call has to be sorted in the same order as the dictionary you will use, which is sorted by its keys, movie then user. So using inputs={'a': inp_movie, 'b': inp_user} or inputs={'movie': inp_movie, 'user': inp_user} also works, while inputs=[inp_user, inp_movie] won't.

You can use this code to test this kind of interaction:

def make_test_model():
    inp_movie = tf.keras.Input(shape=(1,))
    inp_user = tf.keras.Input(shape=(1,))
    model = tf.keras.Model(inputs={'a': inp_movie, 'b': inp_user}, outputs=inp_movie)
    return model

def make_test_model_2():
    inp_movie = tf.keras.Input(shape=(1,))
    inp_user = tf.keras.Input(shape=(1,))
    model = tf.keras.Model(inputs=[inp_user, inp_movie], outputs=inp_movie)
    return model

model_test = make_test_model()
model_test_2 = make_test_model_2()

for x in dataset:
    print(model_test(x))
for x in dataset:
    print(model_test_2(x))

You can also name the Input layers using the keys of your dictonary, and give as the inputs argument a list of Input layers sorted by the layers names. This allows you to add or remove inputs in your model without having to worry about rewriting your inputs argument each time. So this is what I would do:

def make_model_2():
    input_list = []
    inp_movie = tf.keras.Input(shape=(1,), name='movie')
    input_list.append(inp_movie)
    inp_user = tf.keras.Input(shape=(1,), name='user')
    input_list.append(inp_user)
    movie_embedding = tf.keras.layers.Dense(
            units=40, activation=tf.keras.layers.Activation("relu"))(inp_movie)
    user_embedding = tf.keras.layers.Dense(
            units=40, activation=tf.keras.layers.Activation("relu"))(inp_user)
    combined = tf.concat([movie_embedding, user_embedding], 1)
    output = tf.keras.layers.Dense(
            units=1, activation=tf.keras.layers.Activation("sigmoid"))(combined)
    input_list.sort(key=lambda inp: inp._keras_history.layer.name)
    model = tf.keras.Model(inputs=input_list, outputs=output)
    return model

Here is a way to test that it works:

def make_test_model_3(boolean):
    input_list = []
    inp_movie = tf.keras.Input(shape=(1,), name='movie')
    inp_user = tf.keras.Input(shape=(1,), name='user')
    if boolean:
        input_list.append(inp_movie)
        input_list.append(inp_user)
    else:
        input_list.append(inp_user)
        input_list.append(inp_movie)
    input_list.sort(key=lambda inp: inp._keras_history.layer.name)
    model = tf.keras.Model(inputs=input_list, outputs=inp_movie)
    return model

model_test_3_0= make_test_model_3(True)
model_test_3_1= make_test_model_3(False)

for x in dataset:
    print(model_test_3_0(x))
for x in dataset:
    print(model_test_3_1(x))

Edit 2020-02-20:

make_model does not work with tf2.1.0, but make_model_2 still does. I have oppened an issue on GitHub about this backward incompatibility. Here is the link if you are interested. Recall that both functions work if you plan to stay on tf2.0.0.


问:
Assigning K,V pairs to a JSON object in NodeJS
I have a NodeJS script that takes data from a source in the form of "key, value" pairs, and I would like to put that data into a JSON object.

I am using SNMP to get the k, v pairs, where the key is the OID. I would like to then map those values onto a JSON object without having to iteratively check each OID against a known value.

The k,v pairs are stored in objects as such, and I have no flexibility over this incoming data.

let pair = {
    key: "abc...",
    value: "xyz..."
}
```

<p>I have defined the JSON object as an empty structure.</p>

<pre class="lang-js prettyprint-override"><code>let jsonObject = {
    ipaddress: "",
    network: {
        uptime: "",
        throughput: "",
        devices: ""
    }
}
</code>```

And I iterate through my keys (pairs is the name of an array containing the k,v objects)

for (let i = 0; i < pairs.length; i++) {
    if (pairs[i].key == "1.2.3.4.5.6.7") jsonObject.ipaddress = pairs[i].value;
    if (pairs[i].key == "2.3.4.5.6.7.8") jsonObject.network.uptime = pairs[i].value;
    if (pairs[i].key == "3.4.5.6.7.8.9") jsonObject.network.devices = pairs[i].value;
}
```

<p>I would like to know if there is any way to simplify this, as I have around 200 keys to process (the above code is simply an example), and it doesn't seem particularly well optimised for me to iterate over every possible key.</p>

<p>EDIT: The jsonObject is a lot more complex than shown here, with lots of layers and the names of the keys do not match up 1:1 with the json object property names as shown.</p>

<p>EDIT 2: This seems like an odd situation, I know.
For example, I want to take the K,V input:</p>

```Key            Value
1.2.3.4.5.6    "10.0.0.1"
2.3.4.5.6.7    "3 Days 14 Hours 32 Minutes"
3.4.5.6.7.8    "1.1.1.1"
```

<p>And convert it to a dissimilarly named JSON object</p>

<pre class="lang-js prettyprint-override"><code>{
    uptime: "3 Days 14 Hours 32 Minutes",
    networking: {
        ip: "10.0.0.1",
        dns: "1.1.1.1"
    }
}
</code>```

Potentially using some form of mapping, instead of using ~200 if statements

答:
Use the Array.prototype.reduce function.

```<code>const { name, ...properties } = pairs.reduce(
  (obj, { key, value }) => Object.assign(obj, { [key]: value }),
  {}
)

const obj = { name, properties }
</code>```

Reduce will reduce an array into a scalar, in this case an object with all k,v pairs as fields with values on an object, starting with {} as a default value the merging each k,v pair 1 at a time.

Object.assign will merge objects, overwriting objects on the left with the fields of keys of objects on the right.

And finally the syntax to dynamically add a key on an object literal is { [k]: v }

By the way this is a useful trick for reducing the complexity of algorithms where you need to look up values in an array in a loop. Simply create an index of one array then in the loop, lookup in the index instead.

Body:
I have a NodeJS script that takes data from a source in the form of "key, value" pairs, and I would like to put that data into a JSON object.

I am using SNMP to get the k, v pairs, where the key is the OID. I would like to then map those values onto a JSON object without having to iteratively check each OID against a known value.

The k,v pairs are stored in objects as such, and I have no flexibility over this incoming data.

let pair = {
    key: "abc...",
    value: "xyz..."
}

I have defined the JSON object as an empty structure.

let jsonObject = {
    ipaddress: "",
    network: {
        uptime: "",
        throughput: "",
        devices: ""
    }
}

And I iterate through my keys (pairs is the name of an array containing the k,v objects)

for (let i = 0; i < pairs.length; i++) {
    if (pairs[i].key == "1.2.3.4.5.6.7") jsonObject.ipaddress = pairs[i].value;
    if (pairs[i].key == "2.3.4.5.6.7.8") jsonObject.network.uptime = pairs[i].value;
    if (pairs[i].key == "3.4.5.6.7.8.9") jsonObject.network.devices = pairs[i].value;
}

I would like to know if there is any way to simplify this, as I have around 200 keys to process (the above code is simply an example), and it doesn't seem particularly well optimised for me to iterate over every possible key.

EDIT: The jsonObject is a lot more complex than shown here, with lots of layers and the names of the keys do not match up 1:1 with the json object property names as shown.

EDIT 2: This seems like an odd situation, I know.
For example, I want to take the K,V input:

Key            Value
1.2.3.4.5.6    "10.0.0.1"
2.3.4.5.6.7    "3 Days 14 Hours 32 Minutes"
3.4.5.6.7.8    "1.1.1.1"

And convert it to a dissimilarly named JSON object

{
    uptime: "3 Days 14 Hours 32 Minutes",
    networking: {
        ip: "10.0.0.1",
        dns: "1.1.1.1"
    }
}

Potentially using some form of mapping, instead of using ~200 if statements

Body:
Use the Array.prototype.reduce function.

const { name, ...properties } = pairs.reduce(
  (obj, { key, value }) => Object.assign(obj, { [key]: value }),
  {}
)

const obj = { name, properties }

Reduce will reduce an array into a scalar, in this case an object with all k,v pairs as fields with values on an object, starting with {} as a default value the merging each k,v pair 1 at a time.

Object.assign will merge objects, overwriting objects on the left with the fields of keys of objects on the right.

And finally the syntax to dynamically add a key on an object literal is { [k]: v }

By the way this is a useful trick for reducing the complexity of algorithms where you need to look up values in an array in a loop. Simply create an index of one array then in the loop, lookup in the index instead.


问:
How to search JSON array field in MySQL?
I have a column which has json type arrays like

```<code>row1: ["abc", 10, null, true, false]
row2: ["def", 10, null, true, false]
</code>```

How can i use where clause to find "abc" contained rows? My json arrays has no key. They only have values.

```<code>select * from myTable where JSON_SEARCH(myColumn,"all","abc")
</code>```

returns 0 rows

答:
You can use MySQL JSON search function JSON_CONTAINS():

```<code>where json_contains(myColumn, '"abc"')
</code>```

Body:
I have a column which has json type arrays like

row1: ["abc", 10, null, true, false]
row2: ["def", 10, null, true, false]

How can i use where clause to find "abc" contained rows? My json arrays has no key. They only have values.

select * from myTable where JSON_SEARCH(myColumn,"all","abc")

returns 0 rows

Body:
You can use MySQL JSON search function JSON_CONTAINS():

where json_contains(myColumn, '"abc"')


问:
Connect MySQL database in AWS EC2
I am exploring Apache SuperSet. I want to connect to MySQL database on server i.e., EC2 instance. I have installed all the required libraries based on https://superset.incubator.apache.org/installation.html.I did go through https://docs.sqlalchemy.org/en/12/core/engines.html#database-urls. Although I have the library, yet when I try to connect the MySQL it says "No module named 'MySQLdb'".

I am wondering if URL mysql://{username}:{password}@{ip address of ec2 instance}/{database name} itself is right?

Steps followed

I have a server having MySQL data source and I am also launching superset from the same server.

I have added an inbound rule with 0.0.0.0 IP address on port 8088.

I have launched superset successfully with superset run -h 0.0.0.0 -p 8088 --with-threads --debugger --reload

After this I tried creating a new data source on the superset, the data source is MySQL on the same ec2 instance. (I will also need to connect to another data source on another server)

I used the following as recommended:
mysql://username:password@host:3306/dbname
(additional info: in /etc/mysql/my.cnf the following is already configured port:3306,bind-address:127.0.0.1)

On testing connection, got error

The new error I am getting

```<code>Connection failed!

The error message returned was:
(MySQLdb._exceptions.OperationalError) (2003, \"Can't connect to MySQL server on {ip address}
</code>```

答:
You most likely need to specify the host's port, as in mysql://username:password@host:port/dbname.

You also need to make sure the IP address of your EC2 instance is a public one - something you'd allocate when configuring your instance.

Title: Connect MySQL database in AWS EC2

Body:
I am exploring Apache SuperSet. I want to connect to MySQL database on server i.e., EC2 instance. I have installed all the required libraries based on https://superset.incubator.apache.org/installation.html.I did go through https://docs.sqlalchemy.org/en/12/core/engines.html#database-urls. Although I have the library, yet when I try to connect the MySQL it says "No module named 'MySQLdb'".

I am wondering if URL mysql://{username}:{password}@{ip address of ec2 instance}/{database name} itself is right?

Steps followed

I have a server having MySQL data source and I am also launching superset from the same server.

I have added an inbound rule with 0.0.0.0 IP address on port 8088.

I have launched superset successfully with superset run -h 0.0.0.0 -p 8088 --with-threads --debugger --reload

After this I tried creating a new data source on the superset, the data source is MySQL on the same ec2 instance. (I will also need to connect to another data source on another server)

I used the following as recommended:
mysql://username:password@host:3306/dbname
(additional info: in /etc/mysql/my.cnf the following is already configured port:3306,bind-address:127.0.0.1)

On testing connection, got error

The new error I am getting

Connection failed!

The error message returned was:
(MySQLdb._exceptions.OperationalError) (2003, \"Can't connect to MySQL server on {ip address}


问:
Strategies For Tracking Down Memory Leaks When You've Done Everything Wrong
My program, alas, has a memory leak somewhere, but I'll be damned if I know what it is.

Its job is to read in a bunch of ~2MB files, do some parsing and string replacement, then output them in various formats. Naturally, this means a lot of strings, and so doing memory tracing shows that I have a lot of strings, which is exactly what I'd expect. The structure of the program is a series of classes (each in their own thread, because I'm an idiot) that acts on an object that represents each file in memory. (Each object has an input queue that uses a lock on both ends. While this means I get to run this simple processing in parallel, it also means I have multiple 2MB objects sitting in memory.) Each object's structure is defined by a schema object.

My processing classes raise events when they've done their processing and pass a reference to the large object that holds all my strings to add it to the next processing object's queue. Replacing the event with a function call to add to the queue does not stop the leak. One of the output formats requires me to use an unmanaged object. Implementing Dispose() on the class does not stop the leak. I've replaced all the references to the schema object with an index name. No dice. I got no idea what's causing it, and no idea where to look. The memory trace doesn't help because all I see are a bunch of strings being created, and I don't see where the references are sticking in memory.

We're pretty much going to give up and roll back at this point, but I have a pathological need to know exactly how I messed this up. I know Stack Overflow can't exactly comb my code, but what strategies can you suggest for tracking this leak down? I'm probably going to do this in my own time, so any approach is viable.

答: You mentioned that your using events. Are you removing the handlers from those events when your done with your object? I've found that 'loose' event handlers will cause a lot of memory leak problems if you add a bunch of handlers without removing them when your done.</p>

OwnerDisplayName: Merus

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Justin Drury


问:
How can we use legends as filters in AmCharts4?
Currently, in amchart4, the legends can be used to show / hide the target series on click. I would like the behaviour wherein on clicking on the legend:

Do not hide the clicked series.

Hide all other series except the one that was clicked so as to show only the seires whose legend that was clicked.

This question is on the back of an older question targetting amcharts3. However, since v4 is significantly different from v3, the answer does not work.

Based on the documentation here, it appears that the below should work:

```<code>series1.events.on("hidden", function() {
  series2.hide();
  series3.hide();
// but when I run series1.show() in order to mimic series1 to not hide, I get a max call size exceeded msg
});
</code>```

Further to that, according to this, one can outright disable the toggle on the legends - but it works at the cart level and not at the series level.

Thanks.

Update: Follow up is available on GitHub. Posting the update here for the sake of completeness.

@zeroin 's answer works perfectly. I just needed it to be modified a bit more to have it working for the below scenario.

How do I re-enable all the series again? In the graph I'm building, I
  have a series called 'allTraffic' and multiple other series.

AllTraffic should never get hidden.

When I click on any of the other series apart from AllTraffic, hide the other series apart from AllTraffic and the series whose legend has been clicked.

Reset everything (bring back all the series) when AllTraffic's legend is clicked.

chart.legend.itemContainers.template.togglable = false;

```<code>    chart.legend.itemContainers.template.events.on("hit", function(event) {
        var target = event.target;

        chart.legend.itemContainers.each(function(item) {

            if (target.dataItem.dataContext.name != 'All traffic' && item.dataItem.dataContext.name != 'All traffic') {
                console.log("clicked other: ", target.dataItem.dataContext.name);
                item.isActive = true;
                item.dataItem.dataContext.hide();
            }
            if (target.dataItem.dataContext.name == 'All traffic') {
                console.log("Clicked all traffic");
                item.isActive = false;
                item.dataItem.dataContext.show();
            }
        });
        target.isActive = false;
        target.dataItem.dataContext.show();
    })
</code>```

答:
Here is how you do it:
https://codepen.io/team/amcharts/pen/285b315ff30a2740fdbf72f27230711c

To avoid SO you need to make itemContainers not togglable:

```<code>chart.legend.itemContainers.template.togglable = false;

chart.legend.itemContainers.template.events.on("hit", function(event){
    var target = event.target;

    chart.legend.itemContainers.each(function(item){
        if(item != target){
            item.isActive = true;
            item.dataItem.dataContext.hide();
        }
    })
    target.isActive = false;
    target.dataItem.dataContext.show();
})
</code>```

Body:
Currently, in amchart4, the legends can be used to show / hide the target series on click. I would like the behaviour wherein on clicking on the legend:

Do not hide the clicked series.

Hide all other series except the one that was clicked so as to show only the seires whose legend that was clicked.

This question is on the back of an older question targetting amcharts3. However, since v4 is significantly different from v3, the answer does not work.

Based on the documentation here, it appears that the below should work:

series1.events.on("hidden", function() {
  series2.hide();
  series3.hide();
// but when I run series1.show() in order to mimic series1 to not hide, I get a max call size exceeded msg
});

Further to that, according to this, one can outright disable the toggle on the legends - but it works at the cart level and not at the series level.

Thanks.

Update: Follow up is available on GitHub. Posting the update here for the sake of completeness.

@zeroin 's answer works perfectly. I just needed it to be modified a bit more to have it working for the below scenario.

How do I re-enable all the series again? In the graph I'm building, I
  have a series called 'allTraffic' and multiple other series.

AllTraffic should never get hidden.

When I click on any of the other series apart from AllTraffic, hide the other series apart from AllTraffic and the series whose legend has been clicked.

Reset everything (bring back all the series) when AllTraffic's legend is clicked.

chart.legend.itemContainers.template.togglable = false;

    chart.legend.itemContainers.template.events.on("hit", function(event) {
        var target = event.target;

        chart.legend.itemContainers.each(function(item) {

            if (target.dataItem.dataContext.name != 'All traffic' && item.dataItem.dataContext.name != 'All traffic') {
                console.log("clicked other: ", target.dataItem.dataContext.name);
                item.isActive = true;
                item.dataItem.dataContext.hide();
            }
            if (target.dataItem.dataContext.name == 'All traffic') {
                console.log("Clicked all traffic");
                item.isActive = false;
                item.dataItem.dataContext.show();
            }
        });
        target.isActive = false;
        target.dataItem.dataContext.show();
    })

Body:
Here is how you do it:
https://codepen.io/team/amcharts/pen/285b315ff30a2740fdbf72f27230711c

To avoid SO you need to make itemContainers not togglable:

chart.legend.itemContainers.template.togglable = false;

chart.legend.itemContainers.template.events.on("hit", function(event){
    var target = event.target;

    chart.legend.itemContainers.each(function(item){
        if(item != target){
            item.isActive = true;
            item.dataItem.dataContext.hide();
        }
    })
    target.isActive = false;
    target.dataItem.dataContext.show();
})


问:
How do you set Instance Breakpoints in Eclipse?
I'm running Eclipse 3.5 and I'm trying to set an "Instance Breakpoint". I've hit a breakpoint in the debugger, and from the Variables view, I right-click on the object instance I want to set a breakpoint for and click on "Instance Breakpoints..."

Then, I get this:

Google give me nothing but a few links that point to the message bundles that contain that message in the source code.

How can I set a breakpoint on the specific object instance I care about?

答:
How I know to do it is like this:

Set a breakpoint or watchpoint in some class, wait for it to trigger in debug mode.

In the "Variables" view, right click on "this" -> instance breakpoints... -> select form a list of breakpoints in this class -> click ok.

ContentLicense: CC BY-SA 3.0