问:
Memoizing a filtered array in Redux
I have the following selectors setup

selectors.js

```<code>const getNodeHistory = (state) => state.session.nodeHistory;
const getUnit = (state, unit) => unit;

export const selectNodeHistory = createSelector(
    [getNodeHistory, getUnit],
    (history, unit) => history.filter((h) => h.unit === unit)
);
</code>```

Component

```<code>const nodeHistory = useSelector((state) => selectNodeHistory(state, unit));
</code>```

However each component that uses selectNodeHistory re-renders any time there is a change to state.session.nodeHistory i.e a new item added or changed, even if that item doesn't belong to the filtered selector.

Not sure if I'm doing something wrong or it's not possible using this method.

答:
I would make a selector creator that will curry the unit parameter. I am assuming that unit comes from props and the component wants to re calculate if unit changes or history changes:

```<code>const getNodeHistory = (state) => state.session.nodeHistory;

export const createSelectNodeHistory = (unit) =>// curry unit parameter
  createSelector([getNodeHistory], (history) =>
    history.filter((h) => h.unit === unit)
  );

const Component = ({ unit }) => {
  //memoize the selector (re create when unit changes)
  //  here memoization of unit parameter is done in component
  //  so each component has their own memoized selector
  const selectNodeHistory = React.useMemo(
    () => createSelectNodeHistory(unit),
    [unit]
  );
  const nodeHistory = useSelector(selectNodeHistory);
};
</code>```

In that example each component will have their own selector. You could also move the memoization logic to the code creating the selector but if you render multiple components with different unit values using this selector then nothing will be memoized because they all share the same selector.

```<code>//moved memoizing to create selector, memoization or unit is shared
//  for all components calling createSelectNodeHistory
export const createSelectNodeHistory = createSelector(
  (unit) => unit,
  (unit) =>
    createSelector([getNodeHistory], (history) =>
      history.filter((h) => h.unit === unit)
    )
);

const Component = ({ unit }) => {
  //create memoized selector, will be re created when
  //  unit changes. Because memoization of unit is shared by
  //  all components nothing will be memoized when you do
  //  <Component unit={1} /><Component unit={2} />
  const selectNodeHistory = createSelectNodeHistory(unit);
  const nodeHistory = useSelector(selectNodeHistory);
};
</code>```

Now to address our problem; when nodeHistory changes but that change did not affect history.filter you could memoize the filter result like in this answer in your situation the code would look like this:

```<code>const createMemoizedArray = () => {
  const memArray = defaultMemoize((...array) => array);
  return (array) => memArray.apply(null, array);
};

export const createSelectNodeHistory = createSelector(
  (unit) => unit,
  (unit) => {
    const memArray = createMemoizedArray();
    return createSelector([getNodeHistory], (history) =>
      memArray(history.filter((h) => h.unit === unit))
    );
  }
);
</code>```

Or like this if each component needs their own memomized selector:

```<code>export const createSelectNodeHistory = (
  unit // curry unit parameter
) => {
  const memArray = createMemoizedArray();
  return createSelector([getNodeHistory], (history) =>
    memArray(history.filter((h) => h.unit === unit))
  );
};
</code>```

Title: Memoizing a filtered array in Redux

Body:
I have the following selectors setup

selectors.js

const getNodeHistory = (state) => state.session.nodeHistory;
const getUnit = (state, unit) => unit;

export const selectNodeHistory = createSelector(
    [getNodeHistory, getUnit],
    (history, unit) => history.filter((h) => h.unit === unit)
);

Component

const nodeHistory = useSelector((state) => selectNodeHistory(state, unit));

However each component that uses selectNodeHistory re-renders any time there is a change to state.session.nodeHistory i.e a new item added or changed, even if that item doesn't belong to the filtered selector.

Not sure if I'm doing something wrong or it's not possible using this method.

Body:
I would make a selector creator that will curry the unit parameter. I am assuming that unit comes from props and the component wants to re calculate if unit changes or history changes:

const getNodeHistory = (state) => state.session.nodeHistory;

export const createSelectNodeHistory = (unit) =>// curry unit parameter
  createSelector([getNodeHistory], (history) =>
    history.filter((h) => h.unit === unit)
  );

const Component = ({ unit }) => {
  //memoize the selector (re create when unit changes)
  //  here memoization of unit parameter is done in component
  //  so each component has their own memoized selector
  const selectNodeHistory = React.useMemo(
    () => createSelectNodeHistory(unit),
    [unit]
  );
  const nodeHistory = useSelector(selectNodeHistory);
};

In that example each component will have their own selector. You could also move the memoization logic to the code creating the selector but if you render multiple components with different unit values using this selector then nothing will be memoized because they all share the same selector.

//moved memoizing to create selector, memoization or unit is shared
//  for all components calling createSelectNodeHistory
export const createSelectNodeHistory = createSelector(
  (unit) => unit,
  (unit) =>
    createSelector([getNodeHistory], (history) =>
      history.filter((h) => h.unit === unit)
    )
);

const Component = ({ unit }) => {
  //create memoized selector, will be re created when
  //  unit changes. Because memoization of unit is shared by
  //  all components nothing will be memoized when you do
  //  <Component unit={1} /><Component unit={2} />
  const selectNodeHistory = createSelectNodeHistory(unit);
  const nodeHistory = useSelector(selectNodeHistory);
};

Now to address our problem; when nodeHistory changes but that change did not affect history.filter you could memoize the filter result like in this answer in your situation the code would look like this:

const createMemoizedArray = () => {
  const memArray = defaultMemoize((...array) => array);
  return (array) => memArray.apply(null, array);
};

export const createSelectNodeHistory = createSelector(
  (unit) => unit,
  (unit) => {
    const memArray = createMemoizedArray();
    return createSelector([getNodeHistory], (history) =>
      memArray(history.filter((h) => h.unit === unit))
    );
  }
);

Or like this if each component needs their own memomized selector:

export const createSelectNodeHistory = (
  unit // curry unit parameter
) => {
  const memArray = createMemoizedArray();
  return createSelector([getNodeHistory], (history) =>
    memArray(history.filter((h) => h.unit === unit))
  );
};


来源: stackexchange

问:
Why is negative (MSE or MAS) Scoring parameter like- neg_mean_absolute_error in SKLEARN is considered for regression model evaluation
I an a novice in Machine Learning and while going through the course I came across the "Scoring Parameter". I understood for Regression model evaluation, we consider the negatives of Mean Squared error, mean absolute error etc.

When I wanted to know the reason, I went through SKLearn documentation which says "All scorer objects follow the convention that higher return values are better than lower return values. Thus metrics which measure the distance between the model and the data, like metrics.mean_squared_error, are available as neg_mean_squared_error which return the negated value of the metric."

This explanation does not answer my why's completely and I am confused. So, why is the negatives taken more because logically if the difference in prediction is higher whether -ve or +ve, it makes our models equally bad. Then why is it that scoring parameter is focused on negative differences?

答:
I think there is a slight misunderstanding in the way you understood neg_mean_absolute_error (NMAE). The way in which neg_mean_absolute_error is computed as follows:

where N is the total number of data points, Y_i is the true value and Y_i^p is the predicted value.

Still we equally penalize the model if it predicts higher or lower than the true value, but it is just that we multiply the final result with -1 just to follow the convention that sklearn has set. So if a model gives you a MAE of say 0.55 and another model gives you a MAE of say 0.78, their NMAE values would be flipped as -0.55 and -0.78 and by following the convention of higher the better, we pick the former model which results has a higher NMAE of -0.55.

You can make a similar argument for MSE.

ContentLicense: CC BY-SA 4.0


问:
How to deal with inheritance in PageObjects pattern of WebDriver?
Could please anybody suggest a way to deal with Inheritance regarding Page Objects pattern ?

For instance, page objects need to share properties and methods.

```<code>public class LoginPage extends SuperPage
public class SuperPage extends LoadableComponent<SuperPage>
</code>```

This would be Ok. But the problem is that your UnitTests don't extend SuperPage, they extend TestCase, that holds global properties etc. for Tests.

I try to avoid duplication, because I need to share the same stuff in TestCase and SuperPage... Pages and Tests can extend only one of these.

For instance, I need the same Form Data in  PageObjects and Tests available...

Example:

If you have a PageObject for filling out a html form, you need names of the form fields, but you need them even in other pageObjects. So that you extend SuperPage where the field names are. They cannot be supplied from UnitTests, because of this for instance :

```<code>@CacheLookup
@FindBy(how = How.ID, using = namespace + signifLvl)
private WebElement sigLvl;
@CacheLookup
@FindBy(how = How.ID, using = namespace + languageTo)
private WebElement langTo;
@CacheLookup
@FindBy(how = How.ID, using = namespace + languageFrom)
private WebElement langFrom;
@CacheLookup
@FindBy(how = How.ID, using = namespace + description)
private WebElement desc;
</code>```

But on the other hand, you need to use these in UnitTest methods, because you supply different values from them to PageObjects.

Otherwise it would always by like this, prepopulating PageObjects with variables from TestCase :

```<code>@Test
public void doStuff() throws IOException {
    driver.navigate().refresh();
    FillOutFormPage fofp = new FillOutFormPage(driver);
    fofp.fill(some values from TestCase);
    fofp.get();
}
</code>```

答:
I haven't done much with WebDriver, but I remember, that most of of the PageObjects I created and tested, didn't need to be populated. They just contained a scenario - sequence of conditions to be tested, in form of testing methods to be called from UnitTest. The only property to be shared between PageObjects were just a few fields or field names (very exceptionally - like a submit button that when clicked, validation is triggered - it needs to be reachable from all components that forms the entire page and validate something) and namespace for instance.

In case of creating PageObjects that need to be populated with varying data. It must go from outside (UnitTests). So I guess one should be populating or rather constructing pageObjects with data in unitTests, but only if it is a "service like component" that is needed by others and must be in different that initial state. If you always do it like this, there shouldn't be a need for sharing this kind of data between TestCase and PageObjects.

There should be a "boarder" between PageObjects and UnitTests ...varying data must come from unitTests into pageObjects testing methods, static data regarding html stay in PageObjects... IMHO

I don't recommend having SuperPageObejct because as you have it. SomePageObject.get() method returns SuperObject instead of SomePageObject... What you need in object1, stays in object one. There should be no inheritance. In Object1 there is nothing that you should need from object2.

ContentLicense: CC BY-SA 3.0

Body:
Could please anybody suggest a way to deal with Inheritance regarding Page Objects pattern ?

For instance, page objects need to share properties and methods.

public class LoginPage extends SuperPage
public class SuperPage extends LoadableComponent<SuperPage>

This would be Ok. But the problem is that your UnitTests don't extend SuperPage, they extend TestCase, that holds global properties etc. for Tests.

I try to avoid duplication, because I need to share the same stuff in TestCase and SuperPage... Pages and Tests can extend only one of these.

For instance, I need the same Form Data in  PageObjects and Tests available...

Example:

If you have a PageObject for filling out a html form, you need names of the form fields, but you need them even in other pageObjects. So that you extend SuperPage where the field names are. They cannot be supplied from UnitTests, because of this for instance :

@CacheLookup
@FindBy(how = How.ID, using = namespace + signifLvl)
private WebElement sigLvl;
@CacheLookup
@FindBy(how = How.ID, using = namespace + languageTo)
private WebElement langTo;
@CacheLookup
@FindBy(how = How.ID, using = namespace + languageFrom)
private WebElement langFrom;
@CacheLookup
@FindBy(how = How.ID, using = namespace + description)
private WebElement desc;

But on the other hand, you need to use these in UnitTest methods, because you supply different values from them to PageObjects.

Otherwise it would always by like this, prepopulating PageObjects with variables from TestCase :

@Test
public void doStuff() throws IOException {
    driver.navigate().refresh();
    FillOutFormPage fofp = new FillOutFormPage(driver);
    fofp.fill(some values from TestCase);
    fofp.get();
}


问:
flutter remove back button on appbar
I am wondering, if anyone knows of a way to remove the back button that shows up on the appBar in a flutter app when you use Navigator.pushNamed to go to another page. The reason I do not want it on this resulting page is that it is coming from the navigation and I want users to use the logout button instead, so that the session starts over.

答:
The AppBar widget has a property called automaticallyImplyLeading. By default it's value is true. If you don't want flutter automatically build the back button for you then just make the property false.

```<code>appBar: AppBar(
  title: Text("YOUR_APPBAR_TITLE"),
  automaticallyImplyLeading: false,
),
</code>```

To add your custom back button

```<code>appBar: AppBar(
  title: Text("YOUR_APPBAR_TITLE"),
  automaticallyImplyLeading: false,
  leading: YOUR_CUSTOM_WIDGET(),
),
</code>```

Title: flutter remove back button on appbar

Body:
The AppBar widget has a property called automaticallyImplyLeading. By default it's value is true. If you don't want flutter automatically build the back button for you then just make the property false.

appBar: AppBar(
  title: Text("YOUR_APPBAR_TITLE"),
  automaticallyImplyLeading: false,
),

To add your custom back button

appBar: AppBar(
  title: Text("YOUR_APPBAR_TITLE"),
  automaticallyImplyLeading: false,
  leading: YOUR_CUSTOM_WIDGET(),
),


问:
Javascript : Create a variable that returns me only the first word of page title
I have a website page with a three words title.
how can I create a variable in Javascript that outputs only the first word of that title ?

thanks for your help !

答:
const firstWord = document.getElementsByTagName('title')[0].innerText.split(' ')[0]
```

Description:

docuemnt.getElementsByTagName('tagName') finds all the elements with the given tagName. We want only only the first element of it. Hence add put [0] next to it.

innerText gives the content of the given element.

split(" ") splits the given string into an array based on the argument. Here since we want to split into words, we use empty space ' '. Since we need only the first word, you have to again use [0]

Body:
const firstWord = document.getElementsByTagName('title')[0].innerText.split(' ')[0]

Description:

docuemnt.getElementsByTagName('tagName') finds all the elements with the given tagName. We want only only the first element of it. Hence add put [0] next to it.

innerText gives the content of the given element.

split(" ") splits the given string into an array based on the argument. Here since we want to split into words, we use empty space ' '. Since we need only the first word, you have to again use [0]


问:
How to ignore "null" or empty properties in json, globally, using Spring configuration
I'm trying to return only the properties that have values, but the null ones are also being returned.

I know that there's an annotation that does this ( @JsonInclude(Include.NON_NULL) ), but then I need these in every single entity class.

So, my question is: Is there a way to configure this globally through spring config? (avoiding XML, preferably)

EDIT: It seems that this question has been considered a duplicate, but I don't think so. The real question here is how to configure it through spring config, which I couldn't find in other questions.

答:
In newer versions of Spring Boot (2.0+), use:</p>

```<code>spring.jackson.default-property-inclusion=non_null
</code>```

Body:
In newer versions of Spring Boot (2.0+), use:

spring.jackson.default-property-inclusion=non_null


问:
Echo a 3 dimensional array with foreach statement in PHP
I have seen all the questions that are relative with mine, and still didn't find any soloution to my 'simple' problem. I have a 3dimensional array and i just want to display the results. But when it's tome to echo the . "".$person ['job']."	" i am getting errors. Any advice thnx

```<code>$people= array(

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington"),
        array(
            "job"=>"web developer"
        ),

array(
    "name" => "Rodney Hutchers",
    "age"=>"55",
    "email" => "def@gmail.com",
    "city" => "Los Angeles",
    "state" => "California"),
        array(
             "job"=>"data developer"
         );

echo "<table>"
    ."<th>FullName</th>"
    ."<th>Age</th>"
    ."<th>Email</th>"
    ."<th>City</th>"
    ."<th>State</th>"
    ."<th>Job</th>";

 foreach ($people as $person) {
    echo "<tr>"
        . "<td>" . $person ['name'] . "</td>"
        . "<td>" . $person ['age'] . "</td>"
        . "<td>" . $person ['email'] . "</td>"
        . "<td>" . $person ['city'] . "</td>"
        . "<td>" . $person ['state'] . "</td>"
        . "<td>" . $person ['job'] . "</td>"
        . "</tr>";

}
echo "</table>";
</code>```

答:
Your array structure is slightly off, in

```<code>array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington"),  // Close bracket here
        array(
            "job"=>"web developer"
        ),
</code>```

This indented properly is

```<code>array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington"),
array(
    "job"=>"web developer"),
</code>```

so your loop is trying to use this as two separate bits of data and the second one doesn't contain a lot of the fields you are expecting.

You need to make sure you close the array elements in the right place / add the job to the same element as the rest of the data...

```<code>array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington",  // Move ) after the job
    "job" => "web developer"
),
</code>```

If you need that extra level of arrays, then you could make it a list of jobs...

```<code>array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington",
    "jobs" => array( "title" => "web developer")
),
</code>```

The to display them

```<code>foreach ($people as $person) {
    echo "<tr>"
        . "<td>" . $person ['name'] . "</td>"
        . "<td>" . $person ['age'] . "</td>"
        . "<td>" . $person ['email'] . "</td>"
        . "<td>" . $person ['city'] . "</td>"
        . "<td>" . $person ['state'] . "</td>"
        . "<td>";
    foreach ( $person['jobs'] as $job ) {
         echo $job . "/";
    }
    echo "</td>"
        . "</tr>";
}
</code>```

although this way you will end up with a trailing / after the job title, it shows the principle.  You could instead of the inner foreach() loop use...

```<code>echo implode("/", $person['jobs']);
</code>```

Body:
I have seen all the questions that are relative with mine, and still didn't find any soloution to my 'simple' problem. I have a 3dimensional array and i just want to display the results. But when it's tome to echo the . "".$person ['job']."	" i am getting errors. Any advice thnx

$people= array(

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington"),
        array(
            "job"=>"web developer"
        ),

array(
    "name" => "Rodney Hutchers",
    "age"=>"55",
    "email" => "def@gmail.com",
    "city" => "Los Angeles",
    "state" => "California"),
        array(
             "job"=>"data developer"
         );

echo "
"
    ."FullName	"
    ."Age	"
    ."Email	"
    ."City	"
    ."State	"
    ."Job	";

 foreach ($people as $person) {
    echo "
"
        . "" . $person ['name'] . "	"
        . "" . $person ['age'] . "	"
        . "" . $person ['email'] . "	"
        . "" . $person ['city'] . "	"
        . "" . $person ['state'] . "	"
        . "" . $person ['job'] . "	"
        . "
";

}
echo "
";

Body:
Your array structure is slightly off, in

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington"),  // Close bracket here
        array(
            "job"=>"web developer"
        ),

This indented properly is

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington"),
array(
    "job"=>"web developer"),

so your loop is trying to use this as two separate bits of data and the second one doesn't contain a lot of the fields you are expecting.

You need to make sure you close the array elements in the right place / add the job to the same element as the rest of the data...

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington",  // Move ) after the job
    "job" => "web developer"
),

If you need that extra level of arrays, then you could make it a list of jobs...

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "abc@gmail.com",
    "city" => "Seattle",
    "state" => "Washington",
    "jobs" => array( "title" => "web developer")
),

The to display them

foreach ($people as $person) {
    echo "<tr>"
        . "<td>" . $person ['name'] . "</td>"
        . "<td>" . $person ['age'] . "</td>"
        . "<td>" . $person ['email'] . "</td>"
        . "<td>" . $person ['city'] . "</td>"
        . "<td>" . $person ['state'] . "</td>"
        . "<td>";
    foreach ( $person['jobs'] as $job ) {
         echo $job . "/";
    }
    echo "</td>"
        . "</tr>";
}

although this way you will end up with a trailing / after the job title, it shows the principle.  You could instead of the inner foreach() loop use...

echo implode("/", $person['jobs']);


问:
' % ' symbol was not printing on objective-c

Possible Duplicate:

  How to add percent sign to NSString

I am trying to print red (10.0 %) in Objective-C using the statement:

```<code>    $ newlabel1.text= [[NSString alloc] initWithFormat:@"red (%.1f %)",rv];
</code>```

However, I am getting red(10.0) only, and the % symbol was not printing. How can I make the percentage symbol print?

答: You should double the percent sign (%%).</p>

Body:
Possible Duplicate:

  How to add percent sign to NSString

I am trying to print red (10.0 %) in Objective-C using the statement:

    $ newlabel1.text= [[NSString alloc] initWithFormat:@"red (%.1f %)",rv];

However, I am getting red(10.0) only, and the % symbol was not printing. How can I make the percentage symbol print?


问:
What's the difference between "VARCHAR BINARY" and "VARBINARY" in MySQL?
I've created the following test table:

```<code>CREATE TABLE t (
   a VARCHAR(32) BINARY,
   b VARBINARY(32)
);

INSERT INTO t (a, b) VALUES ( 'test    ', 'test    ');
INSERT INTO t (a, b) VALUES ( 'test    \0', 'test    \0');
</code>```

But this query indicated no difference between the two types:

```<code>SELECT a, LENGTH(a), HEX(a), b, LENGTH(b), HEX(b) FROM t;

a          LENGTH(a)  HEX(a)              b          LENGTH(b)  HEX(b)
---------  ---------  ------------------  ---------  ---------  --------------------
test               8  7465737420202020    test               8  7465737420202020
test               9  746573742020202000  test               9  746573742020202000
</code>```

答:
As the MySQL manual page on String Data Type Syntax explains, VARBINARY is equivalent to VARCHAR CHARACTER SET binary, while VARCHAR BINARY is equivalent to VARCHAR CHARACTER SET latin1 COLLATE latin1_bin (or some other non-binary character set with the corresponding binary collation; it depends on table settings):

Specifying the CHARACTER SET binary attribute for a character string data type causes the column to be created as the corresponding binary string data type: CHAR becomes BINARY, VARCHAR becomes VARBINARY, and TEXT becomes BLOB.

The BINARY attribute is a nonstandard MySQL extension that is shorthand for specifying the binary (_bin) collation of the column character set (or of the table default character set if no column character set is specified).

So, VARBINARY stores bytes; VARCHAR BINARY stores character codes but sorts them like bytes (almost - see below).

What this means in practice is explained on the manual page The binary Collation Compared to _bin Collations:

VARBINARY sorts by comparing byte by byte; VARCHAR BINARY compares the byte groups that correspond to characters (not much of a difference for most encodings)

VARCHAR BINARY performs a character set conversion when assigning value from another column with a different encoding, or when the value is inserted/updated by a client with a different encoding; VARBINARY just takes the value as a raw byte string.

Case conversion in SQL (ie. the LOWER / UPPER functions) has no effect on VARBINARY (bytes have no case).

Trailing spaces will be usually ignored in VARCHAR BINARY comparisons (that is, 'x ' = 'x' will be true).

Body:
I've created the following test table:

CREATE TABLE t (
   a VARCHAR(32) BINARY,
   b VARBINARY(32)
);

INSERT INTO t (a, b) VALUES ( 'test    ', 'test    ');
INSERT INTO t (a, b) VALUES ( 'test    \0', 'test    \0');

But this query indicated no difference between the two types:

SELECT a, LENGTH(a), HEX(a), b, LENGTH(b), HEX(b) FROM t;

a          LENGTH(a)  HEX(a)              b          LENGTH(b)  HEX(b)
---------  ---------  ------------------  ---------  ---------  --------------------
test               8  7465737420202020    test               8  7465737420202020
test               9  746573742020202000  test               9  746573742020202000


问:
Problem with promise and create-react-app
I'm a bit new to react, so don't bully me hard. I got to solve this until tomorrow as my homework, and I thought you could help me with it.

Got a task which sounds like:

Create a promise that returns data, must use create-react-app:

```<code>{
    "valid": true,
    "timestamp": 1582195447,
    "base": "USD",
    "rates": {
        "AED": 3.67338,
        "AFN": 77.8079,
        "ALL": 113.23065,
        "AMD": 478.14251
    }
}
</code>```

Display response in the list/table with flexBox

I am familiar with the flexbox tech, but I simply don't understand how to do part one. Despite I am familiar with promise/response in vanilla js, I know how to retrieve data from the API (like ships, planets, and stuff from starWarsApr for example), what I don't know is how to do it with this kind of object and with the usage of create-react-app.

Can you be so kind and maybe supply me with the link to materials about such staff, or to solve and explain to me how is this can be done. I don't have any friends front-end developers to explain to me such things, so I am sorry to ask.

答:
Sincerely, I don't understand the goal of React in this exercice (maybe for ES6 setup).

The part one is quite simple, just create a Promise that returns the object asked for:

```<code>const promise = new Promise((resolve) => {
  resolve({
    valid: true,
    timestamp: 1582195447,
    base: 'USD',
    rates: {
      AED: 3.67338,
      AFN: 77.8079,
      ALL: 113.23065,
      AMD: 478.14251,
    },
  });
});
</code>```

If you want to learn more about promises, check these links:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://web.dev/promises/

https://javascript.info/promise-api

Body:
I'm a bit new to react, so don't bully me hard. I got to solve this until tomorrow as my homework, and I thought you could help me with it.

Got a task which sounds like:

Create a promise that returns data, must use create-react-app:

{
    "valid": true,
    "timestamp": 1582195447,
    "base": "USD",
    "rates": {
        "AED": 3.67338,
        "AFN": 77.8079,
        "ALL": 113.23065,
        "AMD": 478.14251
    }
}

Display response in the list/table with flexBox

I am familiar with the flexbox tech, but I simply don't understand how to do part one. Despite I am familiar with promise/response in vanilla js, I know how to retrieve data from the API (like ships, planets, and stuff from starWarsApr for example), what I don't know is how to do it with this kind of object and with the usage of create-react-app.

Can you be so kind and maybe supply me with the link to materials about such staff, or to solve and explain to me how is this can be done. I don't have any friends front-end developers to explain to me such things, so I am sorry to ask.

Body:
Sincerely, I don't understand the goal of React in this exercice (maybe for ES6 setup).

The part one is quite simple, just create a Promise that returns the object asked for:

const promise = new Promise((resolve) => {
  resolve({
    valid: true,
    timestamp: 1582195447,
    base: 'USD',
    rates: {
      AED: 3.67338,
      AFN: 77.8079,
      ALL: 113.23065,
      AMD: 478.14251,
    },
  });
});

If you want to learn more about promises, check these links:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://web.dev/promises/

https://javascript.info/promise-api


问:
Dreamweaver: Syntax Error, Unexpected '?' when using null-coalescing operator
My server is running PHP 7.2.26.
I'm coding in Dreamweaver CC (Ver 19.2.1).
I'm using null-coalescing operator on a page, but Dreamweaver is giving me "Syntax Error, Unexpected '?'" as a line error.

My code:

($_SESSION['form_data']['smtpEmailAddress'] ?? "")

It works fine when viewing in a browser. I only get the error in Dreamweaver.
Is there a way to get Dreamweaver to accept Null-coalescing Operator?
Dreamweaver is currently set to use PHP 7.1.  7.2 is not an option within preferences.

I know I could just ignore the Dreamweaver error, but I do scan my code for errors using the Dreamweaver error indicators.  I'd rather fix Dreamweaver than just ignore the error.

答:
This is how to fix it in Dreamweaver 2020:

Go to Edit>Preferences>PHP>Select your 7.x version of PHP

Go to Site>Manage Sites>(select your site)>Advanced settings>PHP>Select your 7.x version of PHP.

And sorted, the errors are gone.

This is an issue with the lack of explanation in the options, not a bug. When you select PHP in the global preferences it establishes that version as default for the creation of NEW SITES, but if you are importing sites from previous versions it keeps the old configuration. It is explained in detail here:

https://helpx.adobe.com/uk/dreamweaver/using/setting-coding-environment.html

Dreamweaver supports PHP versions 5.6 and 7.1.

You can choose to compile your site’s PHP files with PHP version 5.6 or 7.1 using the Site Setup dialog box (on a per-site basis), or application preferences (for all PHP files saved outside Dreamweaver sites). Dreamweaver then sets up the code hints, and linting checks for the selected PHP language version.

For new sites in Dreamweaver, the default PHP compiler is set to the version specified in Edit > Preferences > PHP.


问:
Pointer arithmic for arrays which are members of a struct in C
I realized the following problem:

```<code>struct S{
   double **A;
 }
 struct S s;
 s.A = (double **) malloc(sizeof(double*)*2);
 s.A[0] = (double *) malloc(sizeof(double)*3);
 s.A[1] = (double *) malloc(sizeof(double)*3);
</code>```

Now let us say I want to do pointer arithmetic of s.A.
If I start by defining a pointer to a double like:

```<code>double ptr
ptr = &s.A[0][0];
</code>```

I  will expect that

*(ptr+1) is equivalent to s.A[0][1]

*(ptr+2) is equivalent to s.A[0][2]

*(ptr+3) is equivalent to s.A[1][0]

I realize that   *(ptr+3) is NOT equivalent to s.A[1][0] and points to a wrong address. To point to s.A[1][0] I need to do *(ptr+4), so jumping with 1. Can anyone explain why I need to jump an extra one when I want to begin at the next row, and how will I do it if I had to start at the third, fourth etc rows?

答:
when you allocate the pointers at:

```<code>s.A[0] = (double *) malloc(sizeof(double)*3);
s.A[1] = (double *) malloc(sizeof(double)*3);
</code>```

you get what addresses the operating system gives you. Not like an array, it doesn't have to be consecutive.

Body:
I realized the following problem:

struct S{
   double **A;
 }
 struct S s;
 s.A = (double **) malloc(sizeof(double*)*2);
 s.A[0] = (double *) malloc(sizeof(double)*3);
 s.A[1] = (double *) malloc(sizeof(double)*3);

Now let us say I want to do pointer arithmetic of s.A.
If I start by defining a pointer to a double like:

double ptr
ptr = &s.A[0][0];

I  will expect that

*(ptr+1) is equivalent to s.A[0][1]

*(ptr+2) is equivalent to s.A[0][2]

*(ptr+3) is equivalent to s.A[1][0]

I realize that   *(ptr+3) is NOT equivalent to s.A[1][0] and points to a wrong address. To point to s.A[1][0] I need to do *(ptr+4), so jumping with 1. Can anyone explain why I need to jump an extra one when I want to begin at the next row, and how will I do it if I had to start at the third, fourth etc rows?

Body:
when you allocate the pointers at:

s.A[0] = (double *) malloc(sizeof(double)*3);
s.A[1] = (double *) malloc(sizeof(double)*3);

you get what addresses the operating system gives you. Not like an array, it doesn't have to be consecutive.


问:
python check for alternating monday starting on certain date
```<code>my_date = datetime.now(pytz.timezone('US/Central'))
</code>```

So, I have a date my_date and I want to check if this datetime object is an alternating Tuesday starting on the week of September 2nd.  So if my_date is the 4th, it should return true, 11th false, 18th true, etc.. How would this be done?

答:
The easiest solution for this problem should be like.

```<code>if datetime.date.today() in [datetime.date(2020, 6, 1) + timedelta(x) for x in range(14, 365, 14)]:
    print "This day is alternate Monday"
else:
    print "This is not"
</code>```

Here datetime.date.today() is the date you want to check if it is alternate Monday or not.
datetime.date(2020, 6, 1) This is the date from where you want to start or date of first Monday.

Body:
my_date = datetime.now(pytz.timezone('US/Central'))

So, I have a date my_date and I want to check if this datetime object is an alternating Tuesday starting on the week of September 2nd.  So if my_date is the 4th, it should return true, 11th false, 18th true, etc.. How would this be done?

Body:
The easiest solution for this problem should be like.

if datetime.date.today() in [datetime.date(2020, 6, 1) + timedelta(x) for x in range(14, 365, 14)]:
    print "This day is alternate Monday"
else:
    print "This is not"

Here datetime.date.today() is the date you want to check if it is alternate Monday or not.
datetime.date(2020, 6, 1) This is the date from where you want to start or date of first Monday.


问:
Can't access to private cocoapods repo using https

Error

[!] Unable to add a source with url https://{company_domain}/project.git named ios-dev-repo.
  You can try adding it manually in /Users/{use}/.cocoapods/repos or via pod repo add.

Premise

Actually, I have the permissions to this repo and have set up the ssh key in the GitLab profile. Also, I can clone this repo manually. What's more, I can even use git to set up the repo.

```<code>source 'gitlab@git.{company_domain}/project.git'
</code>```

But once I use https for the source,  I encounter the above error.

```<code>source 'https://{company_domain}/project.git'
</code>```

env

cocoapods version: 1.6.1

VPN: Cisco Anyconnect

答:
In this case, I can change git config globally or locally to use git instead of https.

https://gist.github.com/taoyuan/bfa3ff87e4b5611b5cbe

https://www.jvt.me/posts/2019/03/20/git-rewrite-url-https-ssh/

Change git config

```<code># npm using git for https
git config --global url."gitlab@{company_domain}:".insteadOf https://{company_domain}/
</code>```

Check it with:

```<code>git config -l
</code>```

How to revert

```<code>git config --global --unset-all url.gitlab@{company_domain}:.insteadof
</code>```

Body:
Error

[!] Unable to add a source with url https://{company_domain}/project.git named ios-dev-repo.
  You can try adding it manually in /Users/{use}/.cocoapods/repos or via pod repo add.

Premise

Actually, I have the permissions to this repo and have set up the ssh key in the GitLab profile. Also, I can clone this repo manually. What's more, I can even use git to set up the repo.

source 'gitlab@git.{company_domain}/project.git'

But once I use https for the source,  I encounter the above error.

source 'https://{company_domain}/project.git'

env

cocoapods version: 1.6.1

VPN: Cisco Anyconnect

Body:
In this case, I can change git config globally or locally to use git instead of https.

https://gist.github.com/taoyuan/bfa3ff87e4b5611b5cbe

https://www.jvt.me/posts/2019/03/20/git-rewrite-url-https-ssh/

Change git config

# npm using git for https
git config --global url."gitlab@{company_domain}:".insteadOf https://{company_domain}/

Check it with:

git config -l

How to revert

git config --global --unset-all url.gitlab@{company_domain}:.insteadof


问:
using jquery function when added runat server tag with textbox inside grid view
I have two textboxes for value conversion inside the gridview. Outside the gridview the jJquery function is working perfectly. But when I add the textboxes inside the gridview, it is not working.

```<code><asp:GridView ID="GridCustomer" runat="server" DataKeyNames="ID">
    <Columns>

        <asp:TemplateField HeaderText="Status Reading">
            <ItemTemplate>
               <input type="text" runat="server" id="nepaliDate9" value="2069-08-01"/>
               <input type="text" runat="server" id="englishDate9" value="2012-11-16"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

 <script>
        $(document).ready(function () {
            $('.js-example-basic-single').select2({
                placeholder: "select tole"
            });

            $("[id$=englishDate9]").change(function () {
                $("[id$=nepaliDate9]").val(AD2BS($("[id$=englishDate9]").val()));
            });

            $("[id$=nepaliDate9]").change(function () {
                $("[id$=englishDate9]").val(BS2AD($("[id$=nepaliDate9]").val()));
            });
        });
    </script>
</code>```

I also tried using asp textbox with ClientIDMode="Static" but still no use. While inspecting the textboxes, its showing::

```<code><input name="ctl00$ContentPlaceHolder1$GridCustomer$ctl02$nepaliDate9" type="text" id="ContentPlaceHolder1_GridCustomer_nepaliDate9_0" value="2069-08-01">

<input name="ctl00$ContentPlaceHolder1$GridCustomer$ctl02$englishDate9" type="text" id="ContentPlaceHolder1_GridCustomer_englishDate9_0" value="2012-11-16">
</code>```

I tried changing the function as ::

```<code>$('#<%=GridCustomer.ClientID%>').find("[id$=englishDate9]").change(function () {
    $('#<%=GridCustomer.ClientID%>').find("[id$=nepaliDate9]").val(AD2BS($("[id$=englishDate9]").val()));
});

$('#<%=GridCustomer.ClientID%>').find("[id$=nepaliDate9]").change(function () {
    $('#<%=GridCustomer.ClientID%>').find("[id$=englishDate9]").val(BS2AD($("[id$=nepaliDate9]").val()));
});
</code>```

but still not working. Please help !!!

答:
There are multiple things that you should take into consideration while using jQuery and ASP.NET GridView. I would want to point out some things that might help you to resolve the issue:

First and Foremost, you must make sure that your ID attribute of the server control is not being modified as asp.net changes the ids so that every id is different based on the row, it probably includes row index at the end of the id with an underscore.

In your case, it is ContentPlaceHolder1_GridCustomer_nepaliDate9_0 which means, the text box nepaliDate9 control is at zeroth row of the GridCusomter GridView which is inside a content place holder with the id ContentPlaceHolder1.

So, in my opinion it is better to use classes to bind the events instead of IDs. In your case you should bind it like this:

```<code><asp:GridView ID="GridCustomer" runat="server" DataKeyNames="ID">
    <Columns>

        <asp:TemplateField HeaderText="Status Reading">
            <ItemTemplate>
               <input type="text" runat="server" id="nepaliDate9" class="nepaliDate9" value="2069-08-01"/>
               <input type="text" runat="server" id="englishDate9" class="englishDate9" value="2012-11-16"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<script>
        $(document).ready(function () {
            $(".englishDate9").change(function () {
                $(".nepaliDate9").val(AD2BS($(this).val())); // I suppose you want to use the value of the currently changed item
            });

            $(".nepaliDate9").change(function () {
                $(".englishDate9").val(BS2AD($(this).val()));
            });
        });
</script>
</code>```

Secondly, you must check if your jquery events are being bound to the control or not. For some reasons, jQuery events are not bound to the controls e.g when scripts are loaded before the controls are rendered.

You might want to try something like this to bind the controls:

```<code>$("body").on('change', "[id$=englishDate9]", function () {
    $("[id$=nepaliDate9]").val(AD2BS($("[id$=englishDate9]").val()));
});
</code>```

Thirdly, It is always a good idea to keep a track of the browser dev console so whenever there is some issue you immediately get the idea what went wrong.

Body:
I have two textboxes for value conversion inside the gridview. Outside the gridview the jJquery function is working perfectly. But when I add the textboxes inside the gridview, it is not working.

<asp:GridView ID="GridCustomer" runat="server" DataKeyNames="ID">
    <Columns>

        <asp:TemplateField HeaderText="Status Reading">
            <ItemTemplate>
               <input type="text" runat="server" id="nepaliDate9" value="2069-08-01"/>
               <input type="text" runat="server" id="englishDate9" value="2012-11-16"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

I also tried using asp textbox with ClientIDMode="Static" but still no use. While inspecting the textboxes, its showing::

<input name="ctl00$ContentPlaceHolder1$GridCustomer$ctl02$nepaliDate9" type="text" id="ContentPlaceHolder1_GridCustomer_nepaliDate9_0" value="2069-08-01">

<input name="ctl00$ContentPlaceHolder1$GridCustomer$ctl02$englishDate9" type="text" id="ContentPlaceHolder1_GridCustomer_englishDate9_0" value="2012-11-16">

I tried changing the function as ::

$('#<%=GridCustomer.ClientID%>').find("[id$=englishDate9]").change(function () {
    $('#<%=GridCustomer.ClientID%>').find("[id$=nepaliDate9]").val(AD2BS($("[id$=englishDate9]").val()));
});

$('#<%=GridCustomer.ClientID%>').find("[id$=nepaliDate9]").change(function () {
    $('#<%=GridCustomer.ClientID%>').find("[id$=englishDate9]").val(BS2AD($("[id$=nepaliDate9]").val()));
});

but still not working. Please help !!!

Body:
There are multiple things that you should take into consideration while using jQuery and ASP.NET GridView. I would want to point out some things that might help you to resolve the issue:

First and Foremost, you must make sure that your ID attribute of the server control is not being modified as asp.net changes the ids so that every id is different based on the row, it probably includes row index at the end of the id with an underscore.

In your case, it is ContentPlaceHolder1_GridCustomer_nepaliDate9_0 which means, the text box nepaliDate9 control is at zeroth row of the GridCusomter GridView which is inside a content place holder with the id ContentPlaceHolder1.

So, in my opinion it is better to use classes to bind the events instead of IDs. In your case you should bind it like this:

<asp:GridView ID="GridCustomer" runat="server" DataKeyNames="ID">
    <Columns>

        <asp:TemplateField HeaderText="Status Reading">
            <ItemTemplate>
               <input type="text" runat="server" id="nepaliDate9" class="nepaliDate9" value="2069-08-01"/>
               <input type="text" runat="server" id="englishDate9" class="englishDate9" value="2012-11-16"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<script>
        $(document).ready(function () {
            $(".englishDate9").change(function () {
                $(".nepaliDate9").val(AD2BS($(this).val())); // I suppose you want to use the value of the currently changed item
            });

            $(".nepaliDate9").change(function () {
                $(".englishDate9").val(BS2AD($(this).val()));
            });
        });
</script>

Secondly, you must check if your jquery events are being bound to the control or not. For some reasons, jQuery events are not bound to the controls e.g when scripts are loaded before the controls are rendered.

You might want to try something like this to bind the controls:

$("body").on('change', "[id$=englishDate9]", function () {
    $("[id$=nepaliDate9]").val(AD2BS($("[id$=englishDate9]").val()));
});

Thirdly, It is always a good idea to keep a track of the browser dev console so whenever there is some issue you immediately get the idea what went wrong.


问:
React - passing props up components tree through functional components
I want to pass a simple string, number or boolean up more than one level in my component tree. From what I read I need to do this with callback functions but I can't seem to get the logic right.

Here is a sample of where I pass a prop down from Parent App to grandchild Breadcrumb. I would like this prop to actually come from the last child in the tree, the "ResultsPage" component.

I realise there are better ways of doing sth like this (redux, context, different structure, etc), the point here for me is learning and to understand how to use callback functions and how to pass a prop up several more than 1 level.

Newbie friendly please - thanks for any input :)

```<code>class App extends React.Component {
  render() {
    return (
      <>
        <h1>Top level app</h1>

        {/* I import the header and pass down prop */}
        <Header currentLocation="Results Page" />

        {/* I import the main app content */}
        <ResultsPage />
      </>
    );
  }
}

function Header(props) {
  return (
    <>
      <h2>
        This is the header element. It will have some nav items and the
        breadcrumb I import
      </h2>

      {/* I import the breadcrumb accept the props from parent and pass the props down to child */}
      <Crumbs currentLocation={props.currentLocation} />
    </>
  );
}

function Crumbs(props) {
  return (
    <>
      {/* I display the props I passed down through the tree */}
      <h3>
        <small>This is the breadcrumb, you are on</small>{" "}
        {props.currentLocation}
      </h3>
    </>
  );
}

function ResultsPage() {
  return (
    <>
      <p>
        This is the actual results content. I would like this component to tell
        the header component that I have loaded so it can update the breadcrumb
        to let it know which page is currently loaded in the app.
      </p>
    </>
  );
}

export default App;
</code>```

To complete this issue I lewave the following solutions:

Codesandbox: Solution to the initial question

Codesandbox: Additional solution for the same problem using only functional components

Hope it helps the next guy :)

答:
Maintain a local state variable to store the location, and pass a callback function through the props to set it.

```<code>class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      currentLocation : "InitialLocation"
    }
  }

  changeCurrentLocation = (newLocation) => {
    this.setState({currentLocation : newLocation})
  }

  render() {
    ...
    <ResultsPage callback={this.changeCurrentLocation}/>
  }
}
</code>```

The changeCurrentLocation function takes the new location as argument and modifies the state. Everytime the state changes, the render function is called again. This would refresh the view with updated state information, in your case - currentLocation.

```<code>function ResultsPage({ callback }) {
  useEffect(() => {
    callback('My Results');
  }, [callback])

  return (
    ...
  );
}
</code>```

Body:
I want to pass a simple string, number or boolean up more than one level in my component tree. From what I read I need to do this with callback functions but I can't seem to get the logic right.

Here is a sample of where I pass a prop down from Parent App to grandchild Breadcrumb. I would like this prop to actually come from the last child in the tree, the "ResultsPage" component.

I realise there are better ways of doing sth like this (redux, context, different structure, etc), the point here for me is learning and to understand how to use callback functions and how to pass a prop up several more than 1 level.

Newbie friendly please - thanks for any input :)

class App extends React.Component {
  render() {
    return (
      <>

Top level app

        {/* I import the header and pass down prop */}

        {/* I import the main app content */}
        <ResultsPage />
      </>
    );
  }
}

function Header(props) {
  return (
    <>

        This is the header element. It will have some nav items and the
        breadcrumb I import

      {/* I import the breadcrumb accept the props from parent and pass the props down to child */}
      <Crumbs currentLocation={props.currentLocation} />
    </>
  );
}

function Crumbs(props) {
  return (
    <>
      {/* I display the props I passed down through the tree */}

        This is the breadcrumb, you are on{" "}
        {props.currentLocation}

    </>
  );
}

function ResultsPage() {
  return (
    <>

        This is the actual results content. I would like this component to tell
        the header component that I have loaded so it can update the breadcrumb
        to let it know which page is currently loaded in the app.

    </>
  );
}

export default App;

To complete this issue I lewave the following solutions:

Codesandbox: Solution to the initial question

Codesandbox: Additional solution for the same problem using only functional components

Hope it helps the next guy :)

Body:
Maintain a local state variable to store the location, and pass a callback function through the props to set it.

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      currentLocation : "InitialLocation"
    }
  }

  changeCurrentLocation = (newLocation) => {
    this.setState({currentLocation : newLocation})
  }

  render() {
    ...
    <ResultsPage callback={this.changeCurrentLocation}/>
  }
}

The changeCurrentLocation function takes the new location as argument and modifies the state. Everytime the state changes, the render function is called again. This would refresh the view with updated state information, in your case - currentLocation.

function ResultsPage({ callback }) {
  useEffect(() => {
    callback('My Results');
  }, [callback])

  return (
    ...
  );
}


问:
Python scikit learn n_jobs
This is not a real issue, but I'd like to understand:

running sklearn from Anaconda distrib on a Win7 4 cores 8 GB system

fitting a KMeans model on a 200.000 samples*200 values table.

running with n-jobs = -1: (after adding the if __name__ == '__main__': line to my script) I see the script starting 4 processes with
10 threads each. Each process uses about 25% of the CPU (total:
100%). Seems to work as expected

running with n-jobs = 1: stays on a single process (not a surprise), with 20 threads, and also uses 100% of the CPU.

My question: what is the point of using n-jobs (and joblib) if the the library uses all cores anyway? Am I missing something? Is it a Windows-specific behaviour?

答:
The documentation says:

This parameter is used to specify how many concurrent processes or
  threads should be used for routines that are parallelized with joblib.

n_jobs is an integer, specifying the maximum number of concurrently
  running workers. If 1 is given, no joblib parallelism is used at all,
  which is useful for debugging. If set to -1, all CPUs are used. For
  n_jobs below -1, (n_cpus + 1 + n_jobs) are used. For example with
  n_jobs=-2, all CPUs but one are used.

n_jobs is None by default, which means unset; it will generally be
  interpreted as n_jobs=1, unless the current joblib.Parallel backend
  context specifies otherwise.

For more details on the use of joblib and its interactions with
  scikit-learn, please refer to our parallelism notes.

Title: Python scikit learn n_jobs


问:
Vote only once in Django to posts and comments
I have two models called Post and Comment and a User that can upvote or downvote that post or comment. I want to restrict each user however to be able to to vote only once to a certain Post or Comment.

I could do something on the model level to Post and Comment and instead tally up total votes for the specific post or comment. However, I think it's a bit more scalable to create a separate Vote model where:

total votes can be tallied with one query (SELECT count(*) FROM votes where user_id=, etc...)

voting once per user can be enforced with unique_together

Currently I have figured out something like this:

```<code>import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.db import models

# Create your models here.

class Post(models.Model):
    LINK = "link"
    VIDEO = "video"
    IMAGE = "image"
    POST_TYPE_CHOICES = ((LINK, "Link"), (VIDEO, "Video"), (IMAGE, "Image"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=300)
    url = models.URLField(max_length=300)
    category = models.CharField(max_length=50)
    score = models.DecimalField(default=0, max_digits=20, decimal_places=2)
    votes = models.IntegerField(default=0)
    views = models.IntegerField(default=0)
    post_type = models.CharField(max_length=5, choices=POST_TYPE_CHOICES, default=LINK)
    text = models.CharField(max_length=40000)
    owner = models.ForeignKey('users.User', related_name='posts', on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ["-created"]

class PostVote(models.Model):
    DOWNVOTE = -1
    UPVOTE = 1
    UNVOTE = 0
    VOTE_TYPE_CHOICES = ((DOWNVOTE, "Downvote"), (UPVOTE, "Upvote"), (UNVOTE, "Unvote"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    score = models.IntegerField(choices=VOTE_TYPE_CHOICES, default=UPVOTE)
    voter = models.ForeignKey('users.User', related_name='post_votes', on_delete=models.CASCADE)

class Comment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    body = models.CharField(max_length=10000)
    post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE)
    owner = models.ForeignKey('users.User', related_name='comments', on_delete=models.CASCADE)

    class Meta:
        ordering = ["-created"]

class CommentVote(models.Model):
    DOWNVOTE = -1
    UPVOTE = 1
    UNVOTE = 0
    VOTE_TYPE_CHOICES = ((DOWNVOTE, "Downvote"), (UPVOTE, "Upvote"), (UNVOTE, "Unvote"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    score = models.IntegerField(choices=VOTE_TYPE_CHOICES, default=UPVOTE)
    voter = models.ForeignKey('users.User', related_name='comment_votes', on_delete=models.CASCADE)

    def __str__(self):
        return self.score

    class Meta:
        ordering = ["-created"]
</code>```

I just know this is a bad model of separating the votes to PostVote and CommentVote and instead would want a more generic Vote model where I could specify the vote to be towards a Post or a Comment.

What I don't want is having a Vote model that has both the post_id and comment_id which would make it so that either one is always null, since one vote is always either for a Comment or a Post.

Any help?

答:
I believe that, in your example, one important missing thing is that a vote doesn't know to which Post or Comment it belongs.

Generic relations

You could have a single Vote model as you already guessed in the question using a generic relation. In practice, this is a foreign key which can point to different models.

An example could be:

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models

class Vote(models.Model):
   # ...
   # your model stuff
   # ...
   content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
   voted_object_id = models.UUIDField(default=uuid.uuid4)
   voted_object = models.GenericForeignKey('content_type', 'voted_object_id')
```

<p>And in your <code>Post</code> and in your <code>Comment</code>, in order to be able to access votes of a "voted object" with a query (inverse relationships for generic foreign keys aren't automatically generated):</p>

<pre class="lang-py prettyprint-override"><code>from django.db import models
from django.contrib.contenttypes.fields import GenericRelation

class Post(models.Model):
   # ...
   # other stuff
   # ...
   votes = GenericRelation(Vote, related_query_name='post')

class Comment(models.Model):
   # ...
   # other stuff
   # ...
   votes = GenericRelation(Vote, related_query_name='comment')
</code>```

In this way you can access the "voted object" (so the Post or the Comment) in this way:

post = Post.objects.all()[0]
vote_to_post = Vote.objects.create(**vote_data, voted_object=post)
print(vote_to_post.voted_object)  # <Post: (0)>

print(post.votes)  # <QuerySet [<Vote: 0>]>
```

<p>I believe, but I didn't have the opportunity to test, that you can also do:</p>

<pre class="lang-py prettyprint-override"><code>print(vote_to_post.post)  # <Post: (0)>
</code>```

Body:
I have two models called Post and Comment and a User that can upvote or downvote that post or comment. I want to restrict each user however to be able to to vote only once to a certain Post or Comment.

I could do something on the model level to Post and Comment and instead tally up total votes for the specific post or comment. However, I think it's a bit more scalable to create a separate Vote model where:

total votes can be tallied with one query (SELECT count(*) FROM votes where user_id=, etc...)

voting once per user can be enforced with unique_together

Currently I have figured out something like this:

import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.db import models

# Create your models here.

class Post(models.Model):
    LINK = "link"
    VIDEO = "video"
    IMAGE = "image"
    POST_TYPE_CHOICES = ((LINK, "Link"), (VIDEO, "Video"), (IMAGE, "Image"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=300)
    url = models.URLField(max_length=300)
    category = models.CharField(max_length=50)
    score = models.DecimalField(default=0, max_digits=20, decimal_places=2)
    votes = models.IntegerField(default=0)
    views = models.IntegerField(default=0)
    post_type = models.CharField(max_length=5, choices=POST_TYPE_CHOICES, default=LINK)
    text = models.CharField(max_length=40000)
    owner = models.ForeignKey('users.User', related_name='posts', on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ["-created"]

class PostVote(models.Model):
    DOWNVOTE = -1
    UPVOTE = 1
    UNVOTE = 0
    VOTE_TYPE_CHOICES = ((DOWNVOTE, "Downvote"), (UPVOTE, "Upvote"), (UNVOTE, "Unvote"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    score = models.IntegerField(choices=VOTE_TYPE_CHOICES, default=UPVOTE)
    voter = models.ForeignKey('users.User', related_name='post_votes', on_delete=models.CASCADE)

class Comment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    body = models.CharField(max_length=10000)
    post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE)
    owner = models.ForeignKey('users.User', related_name='comments', on_delete=models.CASCADE)

    class Meta:
        ordering = ["-created"]

class CommentVote(models.Model):
    DOWNVOTE = -1
    UPVOTE = 1
    UNVOTE = 0
    VOTE_TYPE_CHOICES = ((DOWNVOTE, "Downvote"), (UPVOTE, "Upvote"), (UNVOTE, "Unvote"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    score = models.IntegerField(choices=VOTE_TYPE_CHOICES, default=UPVOTE)
    voter = models.ForeignKey('users.User', related_name='comment_votes', on_delete=models.CASCADE)

    def __str__(self):
        return self.score

    class Meta:
        ordering = ["-created"]

I just know this is a bad model of separating the votes to PostVote and CommentVote and instead would want a more generic Vote model where I could specify the vote to be towards a Post or a Comment.

What I don't want is having a Vote model that has both the post_id and comment_id which would make it so that either one is always null, since one vote is always either for a Comment or a Post.

Any help?

Body:
I believe that, in your example, one important missing thing is that a vote doesn't know to which Post or Comment it belongs.

Generic relations

You could have a single Vote model as you already guessed in the question using a generic relation. In practice, this is a foreign key which can point to different models.

An example could be:

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models

class Vote(models.Model):
   # ...
   # your model stuff
   # ...
   content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
   voted_object_id = models.UUIDField(default=uuid.uuid4)
   voted_object = models.GenericForeignKey('content_type', 'voted_object_id')

And in your Post and in your Comment, in order to be able to access votes of a "voted object" with a query (inverse relationships for generic foreign keys aren't automatically generated):

from django.db import models
from django.contrib.contenttypes.fields import GenericRelation

class Post(models.Model):
   # ...
   # other stuff
   # ...
   votes = GenericRelation(Vote, related_query_name='post')

class Comment(models.Model):
   # ...
   # other stuff
   # ...
   votes = GenericRelation(Vote, related_query_name='comment')

In this way you can access the "voted object" (so the Post or the Comment) in this way:

post = Post.objects.all()[0]
vote_to_post = Vote.objects.create(**vote_data, voted_object=post)
print(vote_to_post.voted_object)  # <Post: (0)>

print(post.votes)  # <QuerySet [<Vote: 0>]>

I believe, but I didn't have the opportunity to test, that you can also do:

print(vote_to_post.post)  # <Post: (0)>


答:
A possible solution to consider:

```<code>x<-table(y$treatment,y$WHO)

rowcoltotals <- addmargins(x, FUN = list(Total = sum), quiet = TRUE)
</code>```

output:

```<code>            1   2   3   4 Total
  SSTR     43  34  20  27   124
  SSA      23  28  25   0    76
  Control   0   0   0   0     0
  Total    66  62  45  27   200
</code>```

Title: Is it possible to table() two columns in a way that display the sum horizontally and vertically?

Body:
I have

> table(y$treatment,y$WHO)

           1  2  3  4
  SSTR    43 34 20 27
  SSA     23 28 25  0
  Control  0  0  0  0

I am looking for a way to display the sum of each row and column generated by table(). Thus, the expected output is:

           1  2  3  4
  SSTR    43 34 20 27 124
  SSA     23 28 25  0 76
  Control  0  0  0  0 0
          66 62 45 27

I am particularly interested in dplyr-solutions.

My data

y <- structure(list(treatment = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L), .Label = c("SSTR", "SSA", "Control"), class = "factor"),
    WHO = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 4L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 2L,
    2L, 3L, 3L, 3L, 2L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 4L,
    4L, 1L, 4L, 1L, 2L, 1L, 4L, 1L, 1L, 1L, 1L, 2L, 4L, 1L, 2L,
    1L, 4L, 1L, 4L, 4L, 4L, 4L, 3L, 3L, 4L, 4L, 4L, 4L, 1L, 4L,
    4L, 2L, 1L, 2L, 2L, 4L, 4L, 4L, 2L, 4L, 1L, 4L, 4L, 2L, 4L,
    4L, 3L, 4L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 3L, 2L, 2L,
    2L, 3L, 2L, 3L, 1L, 2L, 3L, 3L, 3L, 1L, 2L, 1L, 2L, 3L, 3L,
    1L, 3L, 4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L,
    2L, 2L, 3L, 3L, 1L, 3L, 1L, 3L, 3L, 2L, 3L, 1L, 1L, 2L, 1L,
    1L, 3L, 2L, 1L, 1L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
    2L, 2L, 2L, 2L, 3L, 2L, 3L, 2L, 1L, 2L, 3L, 2L, 2L, 2L, 1L,
    3L, 3L, 3L, 2L, 3L, 2L, 3L, 1L, 1L, 1L, 3L, 1L, 1L, 1L, 1L,
    2L, 1L, 1L, 3L, 2L, 3L, 1L, 1L, 1L, 1L), .Label = c("1",
    "2", "3", "4"), class = "factor")), na.action = structure(c(`152` = 152L,
`193` = 193L), class = "omit"), row.names = c(1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L,
19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L,
32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L,
45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L,
58L, 59L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, 70L,
71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L,
84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L,
97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L,
108L, 109L, 110L, 111L, 112L, 113L, 114L, 115L, 116L, 117L, 118L,
119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L, 127L, 128L, 129L,
130L, 131L, 132L, 133L, 134L, 135L, 136L, 137L, 138L, 139L, 140L,
141L, 142L, 143L, 144L, 145L, 146L, 147L, 148L, 149L, 150L, 151L,
153L, 154L, 155L, 156L, 157L, 158L, 159L, 160L, 161L, 162L, 163L,
164L, 165L, 166L, 167L, 168L, 169L, 170L, 171L, 172L, 173L, 174L,
175L, 176L, 177L, 178L, 179L, 180L, 181L, 182L, 183L, 184L, 185L,
186L, 187L, 188L, 189L, 190L, 191L, 192L, 194L, 195L, 196L, 197L,
198L, 199L, 200L, 201L, 202L), class = "data.frame")

Body:
A possible solution to consider:

x<-table(y$treatment,y$WHO)

rowcoltotals <- addmargins(x, FUN = list(Total = sum), quiet = TRUE)

output:

            1   2   3   4 Total
  SSTR     43  34  20  27   124
  SSA      23  28  25   0    76
  Control   0   0   0   0     0
  Total    66  62  45  27   200


问:
subscribe to control's events in VBA
How do you subsribe to control's events in VBA? I am using MS Word 2010. I can see the public properties of the control in the properties window (F4), but I don't see any events there or an events window.</p>

答: Assuming you mean events for controls on a userform; In the code editing window there are 2 combo-boxes at the very top, pick the control name from the left one and the event from the right and it will create a stub for you.</p>

Title: subscribe to control's events in VBA


问:
How to update an internal table with another internal table?
I have this table and you'll notice that column VKBUR is empty:

What is the best way to populate this column with entries from another table using column VKGRP as key?

In summary, I would like to populate column VKBUR using data from L_T_ZCUSTSL04 as source. Their key is VKGRP from both tables:

Using this lookup table, I want to pass values from VKBUR into the above table.

Thank you so much for your assistance and have a good weekend.

答:
Another possible way is to fill the table using table comprehensions and table expressions

```<code>TYPES: BEGIN OF ty_mara,
             matnr TYPE matnr,
             matkl TYPE matkl,
             maktx TYPE maktx,
           END OF ty_mara,
           BEGIN OF ty_text,
             matnr TYPE matnr,
             maktx TYPE maktx,
         END OF ty_text.

 DATA: gt_text TYPE STANDARD TABLE OF ty_text.
 DATA: gt_mara TYPE STANDARD TABLE OF ty_mara.
TYPES: tty_empty TYPE STANDARD TABLE OF ty_mara WITH EMPTY KEY.

SELECT matnr, matkl UP TO 10 ROWS
  FROM mara
  INTO TABLE @gt_mara.

SELECT matnr, maktx
  INTO TABLE @gt_text
  FROM makt
   FOR ALL ENTRIES IN @gt_mara
 WHERE matnr = @gt_mara-matnr.

  DATA(gt_result) = VALUE tty_empty( FOR wa IN gt_mara ( matnr = wa-matnr matkl = wa-matkl maktx = VALUE maktx( gt_text[ matnr = wa-matnr ]-maktx OPTIONAL ) ) ).
</code>```

However, it has several disadvantages compared to Dan's way, because it requires static table declaration and it creates new itab instead of modifying the existing one. So I recommend to stick to Dan's way.

Of course, construction of new table can be avoided with old good loop and table expression:

```<code>LOOP AT gt_mara ASSIGNING FIELD-SYMBOL(<fs_mara>).
  maktx = VALUE maktx( gt_text[ matnr = <fs_mara>-matnr ]-maktx OPTIONAL ).
ENDLOOP.
</code>```

Body:
Another possible way is to fill the table using table comprehensions and table expressions

TYPES: BEGIN OF ty_mara,
             matnr TYPE matnr,
             matkl TYPE matkl,
             maktx TYPE maktx,
           END OF ty_mara,
           BEGIN OF ty_text,
             matnr TYPE matnr,
             maktx TYPE maktx,
         END OF ty_text.

 DATA: gt_text TYPE STANDARD TABLE OF ty_text.
 DATA: gt_mara TYPE STANDARD TABLE OF ty_mara.
TYPES: tty_empty TYPE STANDARD TABLE OF ty_mara WITH EMPTY KEY.

SELECT matnr, matkl UP TO 10 ROWS
  FROM mara
  INTO TABLE @gt_mara.

SELECT matnr, maktx
  INTO TABLE @gt_text
  FROM makt
   FOR ALL ENTRIES IN @gt_mara
 WHERE matnr = @gt_mara-matnr.

  DATA(gt_result) = VALUE tty_empty( FOR wa IN gt_mara ( matnr = wa-matnr matkl = wa-matkl maktx = VALUE maktx( gt_text[ matnr = wa-matnr ]-maktx OPTIONAL ) ) ).

However, it has several disadvantages compared to Dan's way, because it requires static table declaration and it creates new itab instead of modifying the existing one. So I recommend to stick to Dan's way.

Of course, construction of new table can be avoided with old good loop and table expression:

LOOP AT gt_mara ASSIGNING FIELD-SYMBOL(<fs_mara>).
  maktx = VALUE maktx( gt_text[ matnr = <fs_mara>-matnr ]-maktx OPTIONAL ).
ENDLOOP.


问:
Changing  icon background will not work
I am using the  tag to create a basic drop down.

I have successfully styled it the way I want with an image of a plus sign as the background. However once the  tag has been expanded I cannot get the background image to change to a picture of a minus.

I have tried many different multiple variations. On another note does classic Edge actually support ? Compatibility sites say it has been supported since v79 however of all the tutorials showing how to use it don't work in classic Edge.

Is there a way to not show the contents of the  and  tags if the browser doesn't support them?

```<code>summary {
    list-style-image: url(images/more.png);

    width: 24px;
    height: 24px;

    margin-bottom: 5px;
  }

  summary::-webkit-details-marker {
    background: url(images/more.png);
    color: transparent;
    width: 24px;
    height: 24px;
    margin-bottom: 10px;

  }

  summary:after {
    list-style-image: url(images/minus.png);

  }

  summary::-webkit-details-marker:after {
    background: url(images/minus.png);
    list-style-image: url(images/minus.png);
    color: transparent;
    width: 24px;
    height: 24px;
    margin-bottom: 10px;

  }
  details[open] summary:after {
    background: url(images/minus.png);
    list-style-image: url(images/minus.png);
  }

  details::-webkit-details-marker[open]   summary::-webkit-details-marker:after {
    background: url(images/minus.png);
    list-style-image: url(images/minus.png);
  }

</code>```

答:
I hope you want something like this. if its only about a plus and minus sign , you can do this with CSS, no need of images , change the sign color in CSS as per your need

EDIT: Although I am not agree with Connexo's comment below, but in case if you want to use some other approach or the same thing and not the summary tag as he mentioned, There is one more pure CSS option available here, check the next 3 + signs, first one is with Summary tag, and next one with Input

summary {
    list-style-image: url(images/more.png);
    position: relative;
    width: 24px;
    height: 24px;

    margin-bottom: 5px;
  }
  summary:after {position: absolute; content: ""; height: 2px; width: 15px; background-color: red; top: 50%; transform: translateY(-50%);}
  summary:before {position: absolute; content: ""; height: 2px; width: 15px; background-color: red; top: 50%; transform: translateY(-50%) rotate(90deg);}
  summary::-webkit-details-marker {
    background: url(images/more.png);
    color: transparent;
    width: 24px;
    height: 24px;
    margin-bottom: 10px;

  }

  summary:after {
    list-style-image: url(images/minus.png);

  }

  details[open] summary:before {
    background: url(images/minus.png);
    list-style-image: url(images/minus.png);
  }

.collapsibles {margin-top: 100px;}
.collapsibles >div {
  position: relative;
margin-bottom: 30px;
padding-left: 30px;
}
.collapsibles >div p {opacity: 0; height: 0;}
.collapsibles >div input {position: absolute; height: 20px; width: 20px; top: 0; left: 0; border: 0 !important; outline: none !important;
    -webkit-appearance: none; cursor: pointer;}
.collapsibles >div input:after {position: absolute; content: ""; height: 2px; width: 15px; background-color: red; top: 50%; transform: translateY(-50%);}
.collapsibles >div input:before {position: absolute; content: ""; height: 2px; width: 15px; background-color: red; top: 50%; transform: translateY(-50%) rotate(90deg);}
.collapsibles >div input:checked + p{opacity: 1; height: auto;}
.collapsibles >div input:checked:before {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>With Summary Tag</h2>
<details>
  <summary></summary>
  <p>Summary Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p>
</details>

<div class="collapsibles">
<h2>Without Summary Tag</h2>
<div><input type="checkbox"><p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p></div>
<div><input type="checkbox"><p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p></div>
<div><input type="checkbox"><p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p></div>
</div></code>```

Title: Changing <summary> icon background will not work

Body:
I am using the  tag to create a basic drop down.

I have successfully styled it the way I want with an image of a plus sign as the background. However once the  tag has been expanded I cannot get the background image to change to a picture of a minus.

I have tried many different multiple variations. On another note does classic Edge actually support ? Compatibility sites say it has been supported since v79 however of all the tutorials showing how to use it don't work in classic Edge.

Is there a way to not show the contents of the  and  tags if the browser doesn't support them?

summary {
    list-style-image: url(images/more.png);

    width: 24px;
    height: 24px;

    margin-bottom: 5px;
  }

  summary::-webkit-details-marker {
    background: url(images/more.png);
    color: transparent;
    width: 24px;
    height: 24px;
    margin-bottom: 10px;

  }

  summary:after {
    list-style-image: url(images/minus.png);

  }

  summary::-webkit-details-marker:after {
    background: url(images/minus.png);
    list-style-image: url(images/minus.png);
    color: transparent;
    width: 24px;
    height: 24px;
    margin-bottom: 10px;

  }
  details[open] summary:after {
    background: url(images/minus.png);
    list-style-image: url(images/minus.png);
  }

  details::-webkit-details-marker[open]   summary::-webkit-details-marker:after {
    background: url(images/minus.png);
    list-style-image: url(images/minus.png);
  }

Body:
I hope you want something like this. if its only about a plus and minus sign , you can do this with CSS, no need of images , change the sign color in CSS as per your need

EDIT: Although I am not agree with Connexo's comment below, but in case if you want to use some other approach or the same thing and not the summary tag as he mentioned, There is one more pure CSS option available here, check the next 3 + signs, first one is with Summary tag, and next one with Input

summary {
    list-style-image: url(images/more.png);
    position: relative;
    width: 24px;
    height: 24px;

    margin-bottom: 5px;
  }
  summary:after {position: absolute; content: ""; height: 2px; width: 15px; background-color: red; top: 50%; transform: translateY(-50%);}
  summary:before {position: absolute; content: ""; height: 2px; width: 15px; background-color: red; top: 50%; transform: translateY(-50%) rotate(90deg);}
  summary::-webkit-details-marker {
    background: url(images/more.png);
    color: transparent;
    width: 24px;
    height: 24px;
    margin-bottom: 10px;

  }

  summary:after {
    list-style-image: url(images/minus.png);

  }

  details[open] summary:before {
    background: url(images/minus.png);
    list-style-image: url(images/minus.png);
  }

.collapsibles {margin-top: 100px;}
.collapsibles >div {
  position: relative;
margin-bottom: 30px;
padding-left: 30px;
}
.collapsibles >div p {opacity: 0; height: 0;}
.collapsibles >div input {position: absolute; height: 20px; width: 20px; top: 0; left: 0; border: 0 !important; outline: none !important;
    -webkit-appearance: none; cursor: pointer;}
.collapsibles >div input:after {position: absolute; content: ""; height: 2px; width: 15px; background-color: red; top: 50%; transform: translateY(-50%);}
.collapsibles >div input:before {position: absolute; content: ""; height: 2px; width: 15px; background-color: red; top: 50%; transform: translateY(-50%) rotate(90deg);}
.collapsibles >div input:checked + p{opacity: 1; height: auto;}
.collapsibles >div input:checked:before {
  display: none;
}

<h2>With Summary Tag</h2>
<details>
  <summary></summary>
  <p>Summary Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p>
</details>

<div class="collapsibles">
<h2>Without Summary Tag</h2>
<div><input type="checkbox"><p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p></div>
<div><input type="checkbox"><p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p></div>
<div><input type="checkbox"><p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p></div>
</div>


问:
how to combine 2 db calls into one
How to combine below 2 db calls to one .Is it possible ?

```<code>IEnumerable<int> NewIds= Table1.NewValue.Split(',')
  .Where(x => int.TryParse(x, out int num))
  .Select(int.Parse)
  .ToList();

if (NewIds!= null && NewIds.Count() > 0)
{
   NewValue = string.Join(",", _context.table1.Where(x => NewIds.Contains(x.Id))
                                              .Select(x => TempTextHelper.L(x.Name)));
}

IEnumerable<int> oldIds = Table1.OldValue.Split(',')
  .Where(x => int.TryParse(x, out int num))
  .Select(int.Parse)
  .ToList();

if (oldIds != null && oldIds.Count() > 0)
{
    OldValue = string.Join(",", _context.table1.Where(x => oldIds.Contains(x.Id))
                                        .Select(x => TempTextHelper.L(x.Name)));
}
</code>```

Thanks And Regards,

答:
To avoid logic duplication create a method which gets ids from string value.
Also you can avoid parsing each string twice with aggregating parse results to hash set. Nice way to do it is an extension method:

```<code>public static class Extensions
{
    public static HashSet<int> GetIds(this string value) =>
          value.Split(',').Aggregate(new HashSet<int>(),
              (acc, s) => { if (Int32.TryParse(s, out int x)) acc.Add(x); return acc; });
}
</code>```

Also I would add second helper method to the same class (see usage later):

```<code>public static string CreateValue(this IEnumerable<KeyValuePair<int, string>> items) =>
  String.Join(',', items.Select(kvp => TempTextHelper.L(kvp.Value)));
</code>```

Now get all ids and query everything but include also Id into results:

```<code>var newIds = Table1.NewValue.GetIds();
var oldIds = Table1.OldValue.GetIds();
var ids = newIds.Union(oldIds).ToList(); // combine two sets of ids
if (ids.Any())
{
    // Single DB call
    var allResults =
      _context.table1.Where(x => ids.Contains(x.Id)).ToDictionary(x => x.Id, x => x.Name);

    NewValue = allResults.Where(kvp => newIds.Contains(kvp.Key)).CreateValue();
    OldValue = allResults.Where(kvp => oldIds.Contains(kvp.Key)).CreateValue();
}
</code>```

Title: how to combine 2 db calls into one

Body:
How to combine below 2 db calls to one .Is it possible ?

IEnumerable<int> NewIds= Table1.NewValue.Split(',')
  .Where(x => int.TryParse(x, out int num))
  .Select(int.Parse)
  .ToList();

if (NewIds!= null && NewIds.Count() > 0)
{
   NewValue = string.Join(",", _context.table1.Where(x => NewIds.Contains(x.Id))
                                              .Select(x => TempTextHelper.L(x.Name)));
}

IEnumerable<int> oldIds = Table1.OldValue.Split(',')
  .Where(x => int.TryParse(x, out int num))
  .Select(int.Parse)
  .ToList();

if (oldIds != null && oldIds.Count() > 0)
{
    OldValue = string.Join(",", _context.table1.Where(x => oldIds.Contains(x.Id))
                                        .Select(x => TempTextHelper.L(x.Name)));
}

Thanks And Regards,

Body:
To avoid logic duplication create a method which gets ids from string value.
Also you can avoid parsing each string twice with aggregating parse results to hash set. Nice way to do it is an extension method:

public static class Extensions
{
    public static HashSet<int> GetIds(this string value) =>
          value.Split(',').Aggregate(new HashSet<int>(),
              (acc, s) => { if (Int32.TryParse(s, out int x)) acc.Add(x); return acc; });
}

Also I would add second helper method to the same class (see usage later):

public static string CreateValue(this IEnumerable<KeyValuePair<int, string>> items) =>
  String.Join(',', items.Select(kvp => TempTextHelper.L(kvp.Value)));

Now get all ids and query everything but include also Id into results:

var newIds = Table1.NewValue.GetIds();
var oldIds = Table1.OldValue.GetIds();
var ids = newIds.Union(oldIds).ToList(); // combine two sets of ids
if (ids.Any())
{
    // Single DB call
    var allResults =
      _context.table1.Where(x => ids.Contains(x.Id)).ToDictionary(x => x.Id, x => x.Name);

    NewValue = allResults.Where(kvp => newIds.Contains(kvp.Key)).CreateValue();
    OldValue = allResults.Where(kvp => oldIds.Contains(kvp.Key)).CreateValue();
}


问:
Google Maps route using 300 waypoint
Framework: Ionic

I am using google map for displaying route in an ionic 4 mobile application.
Is there any way to make a route with 300 waypoint (latitude, longitude)
as google always showing error MAX_WAYPOINTS_EXCEEDED

Google map is allowing upto 25 waypoints only

example:

function calcRoute() {
  var waypts = [];
  prepareWaypointsArray(waypts);

  start = new google.maps.LatLng(51.943382, 6.463116);
  end = new google.maps.LatLng(51.943382, 6.463116);

  createMarker(start);

  var request = {
    origin: start,
    destination: end,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.DirectionsTravelMode.WALKING
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var route = response.routes[0];
    }
  });
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function prepareWaypointsArray(waypts) {
  stop = new google.maps.LatLng(51.943571, 6.463856);
  waypts.push({
    location: stop,
    stopover: true
  });
  stop = new google.maps.LatLng(51.945032, 6.465776);
  waypts.push({
    location: stop,
    stopover: true
  });
  stop = new google.maps.LatLng(51.945538, 6.469413);
  waypts.push({
    location: stop,
    stopover: true
  });

}</code>```

答:
Google only provides upto 25 waypoints.

I did this by receiving my 25 waypoints and breaking them up into different routes and drawing them together as the same route.

For example, I have 400 waypoints, I break them into 25 points each and passed into google DirectionsService api and draw them on the map by concatenating the path.

Working example:

```<code>    var myOptions = {
      zoom: 11,
      center: { lat: this.lat, lng: this.long },
      mapTypeId: google.maps.MapTypeId.ROADMAP,
    };

    this.map = new google.maps.Map(this.mapElement.nativeElement, myOptions);
    this.directionsDisplay.setMap(this.map);
    this.start = this.map.getCenter();
    const marker = new google.maps.Marker({
      position: this.start,
      map: this.map,
      icon: {
        url: "assets/images/count_bg_small.png",
      },
    });
    const myInfoWindow = new google.maps.InfoWindow({
      content: '<div style="color:black"><p>My Location</p></div>',
      position: this.start,
      // pixelOffset: { width: 0, height: 0 },
    });
    myInfoWindow.open(this.map, marker);
    google.maps.event.addListenerOnce(this.map, "idle", () => {
      this.main(data);
    });
    //this.polyLines(this.lat, this.long, data[0][0], data[0][1]);
    const destination = { lat: data[0][0], lng: data[0][1] };
    this.calculateAndDisplayRoute(this.start, this.waypoints, destination);
  }

  main(data) {
    // initalise directions service
    var directionsService = new google.maps.DirectionsService();

    var travelWaypoints = [];
    for (var i = 0; i <= data.length - 1; ++i) {
      travelWaypoints.push({
        location: new google.maps.LatLng(data[i][0], data[i][1]),
      });
    }

    // get directions and draw on map
    this.gDirRequest(directionsService, travelWaypoints, (path) => {
      var line = new google.maps.Polyline({
        strokeColor: "#1A66FE",
        clickable: false,
        map: this.map,
        path: path,
      });
    });

    this.makeMarkerForClassicRide(data, "first");
    this.makeMarkerForClassicRide(data, "last");
  }

  gDirRequest(service, waypoints, userFunction, waypointIndex = 0, path = []) {
    console.log("gDirRequest called");
    // set defaults
    waypointIndex = typeof waypointIndex !== "undefined" ? waypointIndex : 0;
    path = typeof path !== "undefined" ? path : [];

    // get next set of waypoints
    var s: any = this.gDirGetNextSet(waypoints, waypointIndex);

    // build request object
    var startl = s[0].shift()["location"];
    var endl = s[0].pop()["location"];
    var request = {
      origin: startl,
      destination: endl,
      waypoints: s[0],
      travelMode: google.maps.TravelMode.WALKING,
      unitSystem: google.maps.UnitSystem.METRIC,
      optimizeWaypoints: false,
      provideRouteAlternatives: false,
      avoidHighways: this.avoidHighways,
      avoidTolls: this.avoidHighways,
    };
    console.log(request);
    service.route(request, (response, status) => {
      console.log(response);
      console.log(status);
      if (status == google.maps.DirectionsStatus.OK) {
        path = path.concat(response.routes[0].overview_path);

        if (s[1] != null) {
          console.log("...........gDirRequest....>>>>");
          setTimeout(() => {
            this.gDirRequest(service, waypoints, userFunction, s[1], path);
          }, 200);
        } else {
          userFunction(path);
        }
      } else {
        console.log(status);
      }
    });
  }

  gDirGetNextSet(waypoints, startIndex) {
    console.log("gDirGetNextSet called");
    var MAX_WAYPOINTS_PER_REQUEST = 25;

    var w = []; // array of waypoints to return

    if (startIndex > waypoints.length - 1) {
      return [w, null];
    } // no more waypoints to process

    var endIndex = startIndex + MAX_WAYPOINTS_PER_REQUEST;

    // adjust waypoints, because Google allows us to include the start and destination latlongs for free!
    endIndex += 2;

    if (endIndex > waypoints.length - 1) {
      endIndex = waypoints.length;
    }

    for (var i = startIndex; i < endIndex; i++) {
      w.push(waypoints[i]);
    }

    if (endIndex != waypoints.length) {
      return [w, (endIndex -= 1)];
    } else {
      return [w, null];
    }
  }
</code>```

Hope this helps, as it worked for me in a practice application.

Title: Google Maps route using 300 waypoint

Body:
Framework: Ionic

I am using google map for displaying route in an ionic 4 mobile application.
Is there any way to make a route with 300 waypoint (latitude, longitude)
as google always showing error MAX_WAYPOINTS_EXCEEDED

Google map is allowing upto 25 waypoints only

example:

function calcRoute() {
  var waypts = [];
  prepareWaypointsArray(waypts);

  start = new google.maps.LatLng(51.943382, 6.463116);
  end = new google.maps.LatLng(51.943382, 6.463116);

  createMarker(start);

  var request = {
    origin: start,
    destination: end,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.DirectionsTravelMode.WALKING
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var route = response.routes[0];
    }
  });
}

function prepareWaypointsArray(waypts) {
  stop = new google.maps.LatLng(51.943571, 6.463856);
  waypts.push({
    location: stop,
    stopover: true
  });
  stop = new google.maps.LatLng(51.945032, 6.465776);
  waypts.push({
    location: stop,
    stopover: true
  });
  stop = new google.maps.LatLng(51.945538, 6.469413);
  waypts.push({
    location: stop,
    stopover: true
  });

}

Body:
Google only provides upto 25 waypoints.

I did this by receiving my 25 waypoints and breaking them up into different routes and drawing them together as the same route.

For example, I have 400 waypoints, I break them into 25 points each and passed into google DirectionsService api and draw them on the map by concatenating the path.

Working example:

    var myOptions = {
      zoom: 11,
      center: { lat: this.lat, lng: this.long },
      mapTypeId: google.maps.MapTypeId.ROADMAP,
    };

    this.map = new google.maps.Map(this.mapElement.nativeElement, myOptions);
    this.directionsDisplay.setMap(this.map);
    this.start = this.map.getCenter();
    const marker = new google.maps.Marker({
      position: this.start,
      map: this.map,
      icon: {
        url: "assets/images/count_bg_small.png",
      },
    });
    const myInfoWindow = new google.maps.InfoWindow({
      content: '<div style="color:black"><p>My Location</p></div>',
      position: this.start,
      // pixelOffset: { width: 0, height: 0 },
    });
    myInfoWindow.open(this.map, marker);
    google.maps.event.addListenerOnce(this.map, "idle", () => {
      this.main(data);
    });
    //this.polyLines(this.lat, this.long, data[0][0], data[0][1]);
    const destination = { lat: data[0][0], lng: data[0][1] };
    this.calculateAndDisplayRoute(this.start, this.waypoints, destination);
  }

  main(data) {
    // initalise directions service
    var directionsService = new google.maps.DirectionsService();

    var travelWaypoints = [];
    for (var i = 0; i <= data.length - 1; ++i) {
      travelWaypoints.push({
        location: new google.maps.LatLng(data[i][0], data[i][1]),
      });
    }

    // get directions and draw on map
    this.gDirRequest(directionsService, travelWaypoints, (path) => {
      var line = new google.maps.Polyline({
        strokeColor: "#1A66FE",
        clickable: false,
        map: this.map,
        path: path,
      });
    });

    this.makeMarkerForClassicRide(data, "first");
    this.makeMarkerForClassicRide(data, "last");
  }

  gDirRequest(service, waypoints, userFunction, waypointIndex = 0, path = []) {
    console.log("gDirRequest called");
    // set defaults
    waypointIndex = typeof waypointIndex !== "undefined" ? waypointIndex : 0;
    path = typeof path !== "undefined" ? path : [];

    // get next set of waypoints
    var s: any = this.gDirGetNextSet(waypoints, waypointIndex);

    // build request object
    var startl = s[0].shift()["location"];
    var endl = s[0].pop()["location"];
    var request = {
      origin: startl,
      destination: endl,
      waypoints: s[0],
      travelMode: google.maps.TravelMode.WALKING,
      unitSystem: google.maps.UnitSystem.METRIC,
      optimizeWaypoints: false,
      provideRouteAlternatives: false,
      avoidHighways: this.avoidHighways,
      avoidTolls: this.avoidHighways,
    };
    console.log(request);
    service.route(request, (response, status) => {
      console.log(response);
      console.log(status);
      if (status == google.maps.DirectionsStatus.OK) {
        path = path.concat(response.routes[0].overview_path);

        if (s[1] != null) {
          console.log("...........gDirRequest....>>>>");
          setTimeout(() => {
            this.gDirRequest(service, waypoints, userFunction, s[1], path);
          }, 200);
        } else {
          userFunction(path);
        }
      } else {
        console.log(status);
      }
    });
  }

  gDirGetNextSet(waypoints, startIndex) {
    console.log("gDirGetNextSet called");
    var MAX_WAYPOINTS_PER_REQUEST = 25;

    var w = []; // array of waypoints to return

    if (startIndex > waypoints.length - 1) {
      return [w, null];
    } // no more waypoints to process

    var endIndex = startIndex + MAX_WAYPOINTS_PER_REQUEST;

    // adjust waypoints, because Google allows us to include the start and destination latlongs for free!
    endIndex += 2;

    if (endIndex > waypoints.length - 1) {
      endIndex = waypoints.length;
    }

    for (var i = startIndex; i < endIndex; i++) {
      w.push(waypoints[i]);
    }

    if (endIndex != waypoints.length) {
      return [w, (endIndex -= 1)];
    } else {
      return [w, null];
    }
  }

Hope this helps, as it worked for me in a practice application.