问:
How to get the intersection of two sets while recognizing equal set values/items not only by reference but by their equal structures and entries too?
I have two deal with two Set instances.

```<code>const set1 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  { name: 'd' },
]);

const set2 = new Set([
  { name: 'b' },
  { name: 'd' },
]);
</code>```

Any object within a set will feature several and also distinct keys and values. The goal is to find structurally equal objects (same keys and values) in both sets, which is ... The intersection of equal data items in/of set1 and set2.

In the following example the expected result is [ { name: 'd' } ] ...

```<code>console.log([...set1].filter(item => set2.has(item)));
</code>```

... but it logs an empty array / [] instead.

An object features more than 20 keys so one has to compare them one by one, which can not be done in a hard coded way.

How could one achieve a generic approach for an intersection of two lists of structurally equal data items?

答:
One could write a generic solution which compares pure, thus JSON conform, data structures regardless of any object's nesting depth/level and (creation time) key order.

Such a function would be self recursive for Array item (order matters) and Object property (key order does not matter) comparison. Otherwise values are compared strictly.

function isDeepDataStructureEquality(a, b) {
  let isEqual = Object.is(a, b);

  if (!isEqual) {
    if (Array.isArray(a) && Array.isArray(b)) {

      isEqual = (a.length === b.length) && a.every(
        (item, idx) => isDeepDataStructureEquality(item, b[idx])
      );
    } else if (
      a && b
      && (typeof a === 'object')
      && (typeof b === 'object')
    ) {
      const aKeys = Object.keys(a);
      const bKeys = Object.keys(b);

      isEqual = (aKeys.length === bKeys.length) && aKeys.every(
        (key, idx) => isDeepDataStructureEquality(a[key], b[key])
      );
    }
  }
  return isEqual;
}

const objA = { // `objA` equals `objB`.
  name: 'foo',
  value: 1,
  obj: {
    z: 'z',
    y: 'y',
    a: {
      name: 'bar',
      value: 2,
      obj: {
        x: 'x',
        w: 'w',
        b: 'b',
      },
      arr: ['3', 4, 'W', 'X', {
        name: 'baz',
        value: 3,
        obj: {
          k: 'k',
          i: 'i',
          c: 'c',
        },
        arr: ['5', 6, 'B', 'A'],
      }],
    },
  },
  arr: ['Z', 'Y', 1, '2'],
};

const objB = { // `objB` equals `objA`.
  arr: ['Z', 'Y', 1, '2'],
  obj: {
    z: 'z',
    y: 'y',
    a: {
      obj: {
        x: 'x',
        w: 'w',
        b: 'b',
      },
      arr: ['3', 4, 'W', 'X', {
        obj: {
          k: 'k',
          i: 'i',
          c: 'c',
        },
        name: 'baz',
        value: 3,
        arr: ['5', 6, 'B', 'A'],
      }],
      name: 'bar',
      value: 2,
    },
  },
  name: 'foo',
  value: 1,
};

const objC = { // `objC` equals neither `objA` nor `objB`.
  arr: ['Z', 'Y', 1, '2'],
  obj: {
    z: 'z',
    y: 'y',
    a: {
      obj: {
        x: 'x',
        w: 'w',
        b: 'b',
      },
      arr: ['3', 4, 'W', 'X', {
        obj: {
          k: 'k',
          i: 'i',
          c: 'C', // the single difference to `objA` and `objB`.
        },
        name: 'baz',
        value: 3,
        arr: ['5', 6, 'B', 'A'],
      }],
      name: 'bar',
      value: 2,
    },
  },
  name: 'foo',
  value: 1,
};

console.log(
  'isDeepDataStructureEquality(objA, objB) ?..',
  isDeepDataStructureEquality(objA, objB)
);
console.log(
  'isDeepDataStructureEquality(objA, objC) ?..',
  isDeepDataStructureEquality(objA, objC)
);
console.log(
  'isDeepDataStructureEquality(objB, objC) ?..',
  isDeepDataStructureEquality(objB, objC)
);
console.log(
  'isDeepDataStructureEquality(objB, objA) ?..',
  isDeepDataStructureEquality(objB, objA)
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%!important; top: 0; }</code>```

Based on the above implementation of isDeepDataStructureEquality one can solve the OP's task, that actually looks for the intersection of two list structures, by additionally providing a getIntersectionOfDeeplyEqualDataStructures functionality ...

function getIntersectionOfDeeplyEqualDataStructures(a, b) {
  return [...(a ?? [])]
    .reduce((collector, sourceItem) => {

      const { target, intersection } = collector;

      const targetIndex = target.findIndex(targetItem =>
        isDeepDataStructureEquality(targetItem, sourceItem)
      );
      if (targetIndex >= 0) {
        // collect the intersection of
        // both, source (a) and target (b).

        intersection.push(target[targetIndex]);
      }
      return collector;

    }, {

      target: [...(b ?? [])],
      intersection: [],

    }).intersection;
}

const set1 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  { name: 'd' }
]);
const set2 = new Set([
  { name: 'b' },
  { name: 'd' },
]);
console.log(
  "getIntersectionOfDeeplyEqualDataStructures(set1, set2) ...",
  getIntersectionOfDeeplyEqualDataStructures(set1, set2)
);

const set3 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  {
    name: 'd',
    list: ['foo', 1, null, false, 0, {
      foo: { bar: { baz: 'bizz', buzz: '' } }
    }],
  },
]);
const set4 = new Set([
  {
    list: ['foo', 1, null, false, 0, {
      foo: { bar: { buzz: '', baz: 'bizz' } }
    }],
    name: 'd',
  },
  { name: 'C' },
  { lastname: 'bb', name: 'b' },
  { name: 'aa' }
]);
console.log(
  "getIntersectionOfDeeplyEqualDataStructures(set3, set4) ...",
  getIntersectionOfDeeplyEqualDataStructures(set3, set4)
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%!important; top: 0; }</code>```

```
</div>
</div>
</p>
<p><em><strong>Edit</strong></em></p>
<p>As for <em><strong>Titus'</strong></em> approach ...</p>
```set1.forEach(value => {
  if (
    ![...set2].some(o =>
      Object.entries(o).every(([k, v], _, arr) =>
        (Object.keys(value).length === arr.length && value[k] === v)
      )
    )
  ) {
    set1.delete(value);
  }
});
```
<p>... which works for flat objects only, though already agnostic to key insertion order, one could optimize the code by ...</p>
<ul>
<li><p>... not creating the <code>keys</code> array of the most outer currently processed object again and again with every nested <code>some</code> and <code>every</code> iteration.</p>
<ul>
<li>thus, something like ... <code>const valueKeys = Object.keys(value);</code> ... before the <code>if</code> clause, already helps improving the code.</li>
</ul>
</li>
<li><p>... inverting the nested <code>some</code> and <code>every</code> logic which does result in a more efficient way of ... <em><strong>deleting every flat data-item from the processed set which does not equal any flat data-item from the secondary set</strong></em>.</p>
</li>
</ul>
<p>On top of that, one could implement a <em>function statement</em> which not only helps code-reuse but also makes the implementation independent from outer scope references.</p>
<p>For instance, the primary set which is operated and going to be mutated can be accessed as such a function's third parameter. But most important for outer scope independency is the also available <code>thisArg</code> binding for any set's <code>forEach</code> method. Thus any <em>function statement</em> or <em>function expression</em> can access e.g. the other/secondary set via <code>this</code> in case the latter was passed as the <code>forEach</code>'s 2nd parameter.</p>
<p>Also an improved wording supports a better readability of the code ...</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>//the function naming of cause is exaggerated.
function deleteItemFromSourceWhichDoesNotEqualAnyItemFromBoundTarget(sourceItem, _, sourceSet) {
  const targetSet = this;

  const sourceKeys = Object.keys(sourceItem);
  if (
    // ... for any data-item from the (bound) target-set ...
    [...targetSet].every(targetItem =>

      // ... which does not equal the currently processed data-item from the source-set ...
      Object.entries(targetItem).some(([targetKey, targetValue], _, targetEntries) =>
        sourceKeys.length !== targetEntries.length || sourceItem[targetKey] !== targetValue
      )
    )
  ) {
    // ... delete the currently processed data-item from the source-set.
    sourceSet.delete(sourceItem);
  }
}

const set1 = new Set([
  { name: 'a' },                        // - to be kept.
  { name: 'b', lastname: 'bb' },        // - to be kept.
  { name: 'c' },                        // - to be deleted.
  { name: 'd', nested: { name: 'a' } }, // - to be kept, but fails ...
]);                                     //   ... due to not being flat.
const set2 = new Set([
  { name: 'd', nested: { name: 'a' } }, // - should equal, but doesn't.
  { name: 'a' },                        // - does equal.
  { lastname: 'bb', name: 'b' },        // - does equal.
  { name: 'e' },                        // - doesn't equal.
]);

// `set1` is going to be mutated.
set1.forEach(deleteItemFromSourceWhichDoesNotEqualAnyItemFromBoundTarget, set2);

console.log(
  'mutated `set1` now (almost) being equal to the intersection of initial `set1` and `set2` ...',
  [...set1]
);</code>```

.as-console-wrapper { min-height: 100%!important; top: 0; }```

Body:
I have two deal with two Set instances.

const set1 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  { name: 'd' },
]);

const set2 = new Set([
  { name: 'b' },
  { name: 'd' },
]);

Any object within a set will feature several and also distinct keys and values. The goal is to find structurally equal objects (same keys and values) in both sets, which is ... The intersection of equal data items in/of set1 and set2.

In the following example the expected result is [ { name: 'd' } ] ...

console.log([...set1].filter(item => set2.has(item)));

... but it logs an empty array / [] instead.

An object features more than 20 keys so one has to compare them one by one, which can not be done in a hard coded way.

How could one achieve a generic approach for an intersection of two lists of structurally equal data items?

Body:
One could write a generic solution which compares pure, thus JSON conform, data structures regardless of any object's nesting depth/level and (creation time) key order.

Such a function would be self recursive for Array item (order matters) and Object property (key order does not matter) comparison. Otherwise values are compared strictly.

function isDeepDataStructureEquality(a, b) {
  let isEqual = Object.is(a, b);

  if (!isEqual) {
    if (Array.isArray(a) && Array.isArray(b)) {

      isEqual = (a.length === b.length) && a.every(
        (item, idx) => isDeepDataStructureEquality(item, b[idx])
      );
    } else if (
      a && b
      && (typeof a === 'object')
      && (typeof b === 'object')
    ) {
      const aKeys = Object.keys(a);
      const bKeys = Object.keys(b);

      isEqual = (aKeys.length === bKeys.length) && aKeys.every(
        (key, idx) => isDeepDataStructureEquality(a[key], b[key])
      );
    }
  }
  return isEqual;
}

const objA = { // `objA` equals `objB`.
  name: 'foo',
  value: 1,
  obj: {
    z: 'z',
    y: 'y',
    a: {
      name: 'bar',
      value: 2,
      obj: {
        x: 'x',
        w: 'w',
        b: 'b',
      },
      arr: ['3', 4, 'W', 'X', {
        name: 'baz',
        value: 3,
        obj: {
          k: 'k',
          i: 'i',
          c: 'c',
        },
        arr: ['5', 6, 'B', 'A'],
      }],
    },
  },
  arr: ['Z', 'Y', 1, '2'],
};

const objB = { // `objB` equals `objA`.
  arr: ['Z', 'Y', 1, '2'],
  obj: {
    z: 'z',
    y: 'y',
    a: {
      obj: {
        x: 'x',
        w: 'w',
        b: 'b',
      },
      arr: ['3', 4, 'W', 'X', {
        obj: {
          k: 'k',
          i: 'i',
          c: 'c',
        },
        name: 'baz',
        value: 3,
        arr: ['5', 6, 'B', 'A'],
      }],
      name: 'bar',
      value: 2,
    },
  },
  name: 'foo',
  value: 1,
};

const objC = { // `objC` equals neither `objA` nor `objB`.
  arr: ['Z', 'Y', 1, '2'],
  obj: {
    z: 'z',
    y: 'y',
    a: {
      obj: {
        x: 'x',
        w: 'w',
        b: 'b',
      },
      arr: ['3', 4, 'W', 'X', {
        obj: {
          k: 'k',
          i: 'i',
          c: 'C', // the single difference to `objA` and `objB`.
        },
        name: 'baz',
        value: 3,
        arr: ['5', 6, 'B', 'A'],
      }],
      name: 'bar',
      value: 2,
    },
  },
  name: 'foo',
  value: 1,
};

console.log(
  'isDeepDataStructureEquality(objA, objB) ?..',
  isDeepDataStructureEquality(objA, objB)
);
console.log(
  'isDeepDataStructureEquality(objA, objC) ?..',
  isDeepDataStructureEquality(objA, objC)
);
console.log(
  'isDeepDataStructureEquality(objB, objC) ?..',
  isDeepDataStructureEquality(objB, objC)
);
console.log(
  'isDeepDataStructureEquality(objB, objA) ?..',
  isDeepDataStructureEquality(objB, objA)
);

.as-console-wrapper { min-height: 100%!important; top: 0; }

Based on the above implementation of isDeepDataStructureEquality one can solve the OP's task, that actually looks for the intersection of two list structures, by additionally providing a getIntersectionOfDeeplyEqualDataStructures functionality ...

function getIntersectionOfDeeplyEqualDataStructures(a, b) {
  return [...(a ?? [])]
    .reduce((collector, sourceItem) => {

      const { target, intersection } = collector;

      const targetIndex = target.findIndex(targetItem =>
        isDeepDataStructureEquality(targetItem, sourceItem)
      );
      if (targetIndex >= 0) {
        // collect the intersection of
        // both, source (a) and target (b).

        intersection.push(target[targetIndex]);
      }
      return collector;

    }, {

      target: [...(b ?? [])],
      intersection: [],

    }).intersection;
}

const set1 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  { name: 'd' }
]);
const set2 = new Set([
  { name: 'b' },
  { name: 'd' },
]);
console.log(
  "getIntersectionOfDeeplyEqualDataStructures(set1, set2) ...",
  getIntersectionOfDeeplyEqualDataStructures(set1, set2)
);

const set3 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  {
    name: 'd',
    list: ['foo', 1, null, false, 0, {
      foo: { bar: { baz: 'bizz', buzz: '' } }
    }],
  },
]);
const set4 = new Set([
  {
    list: ['foo', 1, null, false, 0, {
      foo: { bar: { buzz: '', baz: 'bizz' } }
    }],
    name: 'd',
  },
  { name: 'C' },
  { lastname: 'bb', name: 'b' },
  { name: 'aa' }
]);
console.log(
  "getIntersectionOfDeeplyEqualDataStructures(set3, set4) ...",
  getIntersectionOfDeeplyEqualDataStructures(set3, set4)
);

.as-console-wrapper { min-height: 100%!important; top: 0; }

<script>
  function isDeepDataStructureEquality(a, b) {
    let isEqual = Object.is(a, b);

    if (!isEqual) {
      if (Array.isArray(a) && Array.isArray(b)) {

        isEqual = (a.length === b.length) && a.every(
          (item, idx) => isDeepDataStructureEquality(item, b[idx])
        );
      } else if (
        a && b
        && (typeof a === 'object')
        && (typeof b === 'object')
      ) {
        const aKeys = Object.keys(a);
        const bKeys = Object.keys(b);

        isEqual = (aKeys.length === bKeys.length) && aKeys.every(
          (key, idx) => isDeepDataStructureEquality(a[key], b[key])
        );
      }
    }
    return isEqual;
  }
</script>

Edit

As for Titus' approach ...

set1.forEach(value => {
  if (
    ![...set2].some(o =>
      Object.entries(o).every(([k, v], _, arr) =>
        (Object.keys(value).length === arr.length && value[k] === v)
      )
    )
  ) {
    set1.delete(value);
  }
});

... which works for flat objects only, though already agnostic to key insertion order, one could optimize the code by ...

... not creating the keys array of the most outer currently processed object again and again with every nested some and every iteration.

thus, something like ... const valueKeys = Object.keys(value); ... before the if clause, already helps improving the code.

... inverting the nested some and every logic which does result in a more efficient way of ... deleting every flat data-item from the processed set which does not equal any flat data-item from the secondary set.

On top of that, one could implement a function statement which not only helps code-reuse but also makes the implementation independent from outer scope references.

For instance, the primary set which is operated and going to be mutated can be accessed as such a function's third parameter. But most important for outer scope independency is the also available thisArg binding for any set's forEach method. Thus any function statement or function expression can access e.g. the other/secondary set via this in case the latter was passed as the forEach's 2nd parameter.

Also an improved wording supports a better readability of the code ...

//the function naming of cause is exaggerated.
function deleteItemFromSourceWhichDoesNotEqualAnyItemFromBoundTarget(sourceItem, _, sourceSet) {
  const targetSet = this;

  const sourceKeys = Object.keys(sourceItem);
  if (
    // ... for any data-item from the (bound) target-set ...
    [...targetSet].every(targetItem =>

      // ... which does not equal the currently processed data-item from the source-set ...
      Object.entries(targetItem).some(([targetKey, targetValue], _, targetEntries) =>
        sourceKeys.length !== targetEntries.length || sourceItem[targetKey] !== targetValue
      )
    )
  ) {
    // ... delete the currently processed data-item from the source-set.
    sourceSet.delete(sourceItem);
  }
}

const set1 = new Set([
  { name: 'a' },                        // - to be kept.
  { name: 'b', lastname: 'bb' },        // - to be kept.
  { name: 'c' },                        // - to be deleted.
  { name: 'd', nested: { name: 'a' } }, // - to be kept, but fails ...
]);                                     //   ... due to not being flat.
const set2 = new Set([
  { name: 'd', nested: { name: 'a' } }, // - should equal, but doesn't.
  { name: 'a' },                        // - does equal.
  { lastname: 'bb', name: 'b' },        // - does equal.
  { name: 'e' },                        // - doesn't equal.
]);

// `set1` is going to be mutated.
set1.forEach(deleteItemFromSourceWhichDoesNotEqualAnyItemFromBoundTarget, set2);

console.log(
  'mutated `set1` now (almost) being equal to the intersection of initial `set1` and `set2` ...',
  [...set1]
);

.as-console-wrapper { min-height: 100%!important; top: 0; }


来源: stackexchange

问:
Method with Interface Parameters with Mockito Argument Capture
I've one simple question. I've got two classes

XMessage and YMessage. These two classes are the sub class of ZClass.

These messages are published from a PublisherService with method

```<code>public void publish(ZClass message, Properties props){
     // some lowlevel stuff.
     // note that method is taking ZClass as an arg.
}
</code>```

According to my logic XMessage is sent many times while YMessage is sent only once in one test.

Let's say XMessage is supposed to be sent 4 times where YMessage is sent 1 time. I would assume below code would work.

```<code>        ArgumentCaptor<XMessage> xCaptor = ArgumentCaptor.forClass(XMessage.class);

        verify(publisherService, times(4)).sendMessage(isA(XMessage.class),any());
        verify(publisherService, times(1)).sendMessage(isA(YMessage.class),any());
        verify(publisherService, times(4)).sendMessage(xCaptor,any());
</code>```

However it fails with captor and the captor has 5 values.

What am I doing wrong?

Thanks in advance.

答:
This is a known issue in Mockito. The issue is that ArgumentCaptor is not type aware.

See https://github.com/mockito/mockito/issues/565

This is open from 2016 and still not fully fixed so I would just did some workaround around it.

You can capture all of the arguments and then instanceof just the ones you need.

ArgumentCaptor<ZClass> zCaptor = ArgumentCaptor.forClass(ZClass.class);

Mockito.verify(publisherService, times(5)).publish(zCaptor.capture(), ArgumentMatchers.<Properties>any());

List<XMessage> xMessages = zCaptor.getAllValues()
                                  .stream()
                                  .filter(arg -> arg instanceof XMessage)
                                  .map(arg -> (XMessage) arg)
                                  .collect(Collectors.toList());
```

ContentLicense: CC BY-SA 4.0

Body:
I've one simple question. I've got two classes

XMessage and YMessage. These two classes are the sub class of ZClass.

These messages are published from a PublisherService with method

public void publish(ZClass message, Properties props){
     // some lowlevel stuff.
     // note that method is taking ZClass as an arg.
}

According to my logic XMessage is sent many times while YMessage is sent only once in one test.

Let's say XMessage is supposed to be sent 4 times where YMessage is sent 1 time. I would assume below code would work.

        ArgumentCaptor<XMessage> xCaptor = ArgumentCaptor.forClass(XMessage.class);

        verify(publisherService, times(4)).sendMessage(isA(XMessage.class),any());
        verify(publisherService, times(1)).sendMessage(isA(YMessage.class),any());
        verify(publisherService, times(4)).sendMessage(xCaptor,any());

However it fails with captor and the captor has 5 values.

What am I doing wrong?

Thanks in advance.


问:
Pass a variable into a filter - R dplyr
Here is a sample of the dataset that I have. I am looking to find the state that has the maximum number of stores. In this case, CA and also see how many IDs come from that state

```<code>| ID | | State | | Stores|
| -- | |------ | | ----- |
|a11 | | CA    | | 16585 |
|a12 | | CA    | | 45552 |
|a13 | | AK    | | 7811  |
|a14 | | MA    | | 4221  |
</code>```

I have this code using dplyr

```<code>max_state <- df  %>%
    group_by(State)  %>%
    summarise(total_stores = sum(Stores))  %>%
    top_n(1)  %>%
    select(State)
</code>```

This gives me "CA"

Can I use this variable "max(state)" to pass through a filter and use summarise(n()) to count the number of Ids for CA?

答:
You can combine more operations into one summarize call that will be applied to the same group:

df |>
  group_by(State) |>
  summarize(gsum = sum(Stores), nids = n()) |>
  filter(gsum == max(gsum))

##>+ # A tibble: 1 × 3
##>  State  gsum  nids
##>  <chr> <dbl> <int>
##>1 CA    62137     2
```
<p>Where the dataset <code>df</code> is obtained by:</p>
```df <- data.frame(ID = c("a11", "a12","a13", "a14"),
                 State = c("CA", "CA", "AK", "MA"),
                 Stores = c(16585, 45552, 7811, 4221))
```

Title: Pass a variable into a filter - R dplyr

Body:
Here is a sample of the dataset that I have. I am looking to find the state that has the maximum number of stores. In this case, CA and also see how many IDs come from that state

| ID | | State | | Stores|
| -- | |------ | | ----- |
|a11 | | CA    | | 16585 |
|a12 | | CA    | | 45552 |
|a13 | | AK    | | 7811  |
|a14 | | MA    | | 4221  |

I have this code using dplyr

max_state <- df  %>%
    group_by(State)  %>%
    summarise(total_stores = sum(Stores))  %>%
    top_n(1)  %>%
    select(State)

This gives me "CA"

Can I use this variable "max(state)" to pass through a filter and use summarise(n()) to count the number of Ids for CA?

Body:
You can combine more operations into one summarize call that will be applied to the same group:

df |>
  group_by(State) |>
  summarize(gsum = sum(Stores), nids = n()) |>
  filter(gsum == max(gsum))

##>+ # A tibble: 1 × 3
##>  State  gsum  nids
##>  <chr> <dbl> <int>
##>1 CA    62137     2

Where the dataset df is obtained by:

df <- data.frame(ID = c("a11", "a12","a13", "a14"),
                 State = c("CA", "CA", "AK", "MA"),
                 Stores = c(16585, 45552, 7811, 4221))


问:
Error while excel exporting using Django xlwt
I am trying to export information to an Excel file from my web application using the xlwt library, but the following error appears in urls.py

TypeError: export_excel_av_items() missing 1 required positional
argument: 'request'

models.py:

```<code>class Stock(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30, unique=True)
    quantity = models.IntegerField(default=1)
    is_deleted = models.BooleanField(default=False)

    def __str__(self):
        return self.name
</code>```

views.py:

```<code>def export_excel_av_items(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="available-items.xls"'
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Available Items')
    row_num = 0
    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns= ['Name', 'Qty']

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    font_style = xlwt.XFStyle()

    rows = Stock.objects.all().values_list(
        'name', 'quantity')

    for row in rows:
        row_num += 1

        for col_num in range(len(row)):
            ws.write(row_num, col_num, str(row[col_num]), font_style)
    wb.save(response)

    return response
</code>```

urls.py:

```<code>path('', views.StockListView.as_view(), name='inventory'),
path('new', views.StockCreateView.as_view(), name='new-stock'),
path('stock/<pk>/edit', views.StockUpdateView.as_view(), name='edit-stock'),
path('stock/<pk>/delete', views.StockDeleteView.as_view(), name='delete-stock'),
path('inventory/export-excel', views.export_excel_av_items(), name='export-excel'),
</code>```

答:
In URLs, you point to the function, you don't call it so the following line

```<code>path('inventory/export-excel', views.export_excel_av_items(), name='export-excel'),
</code>```

shall be

```<code>path('inventory/export-excel', views.export_excel_av_items, name='export-excel'),
</code>```

Body:
I am trying to export information to an Excel file from my web application using the xlwt library, but the following error appears in urls.py

TypeError: export_excel_av_items() missing 1 required positional
argument: 'request'

models.py:

class Stock(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30, unique=True)
    quantity = models.IntegerField(default=1)
    is_deleted = models.BooleanField(default=False)

    def __str__(self):
        return self.name

views.py:

def export_excel_av_items(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="available-items.xls"'
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Available Items')
    row_num = 0
    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns= ['Name', 'Qty']

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    font_style = xlwt.XFStyle()

    rows = Stock.objects.all().values_list(
        'name', 'quantity')

    for row in rows:
        row_num += 1

        for col_num in range(len(row)):
            ws.write(row_num, col_num, str(row[col_num]), font_style)
    wb.save(response)

    return response

urls.py:

path('', views.StockListView.as_view(), name='inventory'),
path('new', views.StockCreateView.as_view(), name='new-stock'),
path('stock/<pk>/edit', views.StockUpdateView.as_view(), name='edit-stock'),
path('stock/<pk>/delete', views.StockDeleteView.as_view(), name='delete-stock'),
path('inventory/export-excel', views.export_excel_av_items(), name='export-excel'),

Body:
In URLs, you point to the function, you don't call it so the following line

path('inventory/export-excel', views.export_excel_av_items(), name='export-excel'),

shall be

path('inventory/export-excel', views.export_excel_av_items, name='export-excel'),


问:
Why Bootstrap 5 navbar does not collapsing?
I try to compile Bootstrap 5 with sass but I think I miss importing some scss files. If I added <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> navbar collapsing fine, but when I added my compailed css file navbar not collapsing.

Here is my navbar codes

      Workshop

    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
      aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

```
<p>Here is my main.scss codes</p>
<pre class="lang-css prettyprint-override"><code>// PATHS ARE TRUE
// 1. Include functions first (so you can manipulate colors, SVGs, calc, etc)
@import "../../node_modules/bootstrap/scss/functions";

// 2. Include any default variable overrides here

// 3. Include remainder of required Bootstrap stylesheets
@import "../../node_modules/bootstrap/scss/variables";
@import "../../node_modules/bootstrap/scss/mixins";
@import "../../node_modules/bootstrap/scss/root";

// 4. Include any optional Bootstrap CSS as needed
// I GUEST MISSING IN HERE
@import "../../node_modules/bootstrap/scss/utilities";
@import "../../node_modules/bootstrap/scss/reboot";
@import "../../node_modules/bootstrap/scss/type";
@import "../../node_modules/bootstrap/scss/containers";
@import "../../node_modules/bootstrap/scss/grid";
@import "../../node_modules/bootstrap/scss/helpers";
@import "../../node_modules/bootstrap/scss/nav";
@import "../../node_modules/bootstrap/scss/navbar";
@import "../../node_modules/bootstrap/scss/buttons";
@import "../../node_modules/bootstrap/scss/tables";
@import "../../node_modules/bootstrap/scss/images";
@import "../../node_modules/bootstrap/scss/card";

// 5. Optionally include utilities API last to generate classes based on the Sass map in `_utilities.scss`
@import "../../node_modules/bootstrap/scss/utilities/api";

// 6. Add additional custom code here
</code>```

And here is my index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="{{site.baseurl}}/assets/css/main.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
  <title>{{site.title}}</title>
  <link rel="icon" type="image/x-icon" href="{{site.baseurl}}/assets/images/favicon.ico">

  {{content}}

```

Why my navbar does not collapsing? Which scss files i have to import? I have read the documents but I missing something. Could not fix. Please help.

Thank you

答:
You need to add this file too</p>
```<code>@import "../../node_modules/bootstrap/scss/transitions";
</code>```

Body:
I try to compile Bootstrap 5 with sass but I think I miss importing some scss files. If I added <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> navbar collapsing fine, but when I added my compailed css file navbar not collapsing.

Here is my navbar codes

      Workshop

    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
      aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

Here is my main.scss codes

// PATHS ARE TRUE
// 1. Include functions first (so you can manipulate colors, SVGs, calc, etc)
@import "../../node_modules/bootstrap/scss/functions";

// 2. Include any default variable overrides here

// 3. Include remainder of required Bootstrap stylesheets
@import "../../node_modules/bootstrap/scss/variables";
@import "../../node_modules/bootstrap/scss/mixins";
@import "../../node_modules/bootstrap/scss/root";

// 4. Include any optional Bootstrap CSS as needed
// I GUEST MISSING IN HERE
@import "../../node_modules/bootstrap/scss/utilities";
@import "../../node_modules/bootstrap/scss/reboot";
@import "../../node_modules/bootstrap/scss/type";
@import "../../node_modules/bootstrap/scss/containers";
@import "../../node_modules/bootstrap/scss/grid";
@import "../../node_modules/bootstrap/scss/helpers";
@import "../../node_modules/bootstrap/scss/nav";
@import "../../node_modules/bootstrap/scss/navbar";
@import "../../node_modules/bootstrap/scss/buttons";
@import "../../node_modules/bootstrap/scss/tables";
@import "../../node_modules/bootstrap/scss/images";
@import "../../node_modules/bootstrap/scss/card";

// 5. Optionally include utilities API last to generate classes based on the Sass map in `_utilities.scss`
@import "../../node_modules/bootstrap/scss/utilities/api";

// 6. Add additional custom code here

And here is my index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="{{site.baseurl}}/assets/css/main.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
  <title>{{site.title}}</title>
  <link rel="icon" type="image/x-icon" href="{{site.baseurl}}/assets/images/favicon.ico">

  {{content}}

Why my navbar does not collapsing? Which scss files i have to import? I have read the documents but I missing something. Could not fix. Please help.

Thank you

Body:
You need to add this file too

@import "../../node_modules/bootstrap/scss/transitions";


问:
Is Jetpack Compose Navigation good design for navigating?
The following code are from the official sample project.

There are two branches, main and end.

I found the Code main and the Code end using different ways to navigate.

Code main is simple and clear, and in other projects, it navigate based State just like Code A which is from the project.

Code end use NavHostController to navigate, but It seems that we need't to use Navigation again when we use Jetpack Compose, right?

Code main

```<code>@Composable
fun RallyApp() {
    RallyTheme {
        val allScreens = RallyScreen.values().toList()
        var currentScreen by rememberSaveable { mutableStateOf(RallyScreen.Overview) }
        Scaffold(
          ...
        ) { innerPadding ->
            Box(Modifier.padding(innerPadding)) {
                currentScreen.content(
                    onScreenChange = { screen ->
                        currentScreen = RallyScreen.valueOf(screen)
                    }
                )
            }
        }
    }
}

enum class RallyScreen(
    val icon: ImageVector,
    val body: @Composable ((String) -> Unit) -> Unit
) {
    Overview(
        icon = Icons.Filled.PieChart,
        body = { OverviewBody() }
    ),
    Accounts(
        icon = Icons.Filled.AttachMoney,
        body = { AccountsBody(UserData.accounts) }
    ),
    Bills(
        icon = Icons.Filled.MoneyOff,
        body = { BillsBody(UserData.bills) }
    );

    @Composable
    fun content(onScreenChange: (String) -> Unit) {
        body(onScreenChange)
    }
}
</code>```

Code end

```<code>@Composable
fun RallyNavHost(navController: NavHostController, modifier: Modifier = Modifier) {
    NavHost(
        navController = navController,
        startDestination = Overview.name,
        modifier = modifier
    ) {
        composable(Overview.name) {
            OverviewBody(
              ...
            )
        }
        composable(Accounts.name) {
          ...
        }
        composable(Bills.name) {
          ...
        }
    }
}

enum class RallyScreen(
    val icon: ImageVector,
) {
    Overview(
        icon = Icons.Filled.PieChart,
    ),
    Accounts(
        icon = Icons.Filled.AttachMoney,
    ),
    Bills(
        icon = Icons.Filled.MoneyOff,
    );

    companion object {
        fun fromRoute(route: String?): RallyScreen =
            when (route?.substringBefore("/")) {
                Accounts.name -> Accounts
                Bills.name -> Bills
                Overview.name -> Overview
                null -> Overview
                else -> throw IllegalArgumentException("Route $route is not recognized.")
            }
    }
</code>```

Code A

```<code>fun CraneHomeContent(
   ...
) {
    val suggestedDestinations by viewModel.suggestedDestinations.collectAsState()

    val onPeopleChanged: (Int) -> Unit = { viewModel.updatePeople(it) }
    var tabSelected by remember { mutableStateOf(CraneScreen.Fly) }

    BackdropScaffold(
        ...
        frontLayerContent = {
            when (tabSelected) {
                CraneScreen.Fly -> {
                  ...
                }
                CraneScreen.Sleep -> {
                   ...
                }
                CraneScreen.Eat -> {
                   ...
                }
            }
        }
    )
}
</code>```

答:
It depends on the specific use case you want to implement. In general, yes, any sort of navigation library is more suitable for navigation. It is literally in the name. Most navigation libraries, including Navigation Component, provide such essentials as:

storing the whole navigation history (the backstack) and the saved state (rememberSaveable) of every entry in the backstack. The same destination may be several times in the backstack, but they would be stored as different backstack entries. This allows storing the separate saved states for each of them.

providing separate scoped Lifecycle, ViewModelStore and SavedStateRegistry for each of them. This may be useful for allocating/cleaning up resources while the destination is visible or while it is in the backstack.

Doing the simple switching between destinations as in your Code main or Code A MAY be a valid option, but it lacks the functionality mentioned above. All your destinations use the same Lifecycle, ViewModelStore and SavedStateRegistry of the parent composable. Also, rememberSaveable wouldn't save state when switching between destinations. In some cases it might be fine, but you should be aware of the difference.

On the question whether Navigation Component for Compose is good for navigation? It's fine, but there are flaws and complications. You may read a good article by CommonsWare on the topic: Navigating in Compose: Criteria

Considering all the weirdness of the official library, I've even crafted my own navigation library: Compose Navigation Reimagined

Body:
The following code are from the official sample project.

There are two branches, main and end.

I found the Code main and the Code end using different ways to navigate.

Code main is simple and clear, and in other projects, it navigate based State just like Code A which is from the project.

Code end use NavHostController to navigate, but It seems that we need't to use Navigation again when we use Jetpack Compose, right?

Code main

@Composable
fun RallyApp() {
    RallyTheme {
        val allScreens = RallyScreen.values().toList()
        var currentScreen by rememberSaveable { mutableStateOf(RallyScreen.Overview) }
        Scaffold(
          ...
        ) { innerPadding ->
            Box(Modifier.padding(innerPadding)) {
                currentScreen.content(
                    onScreenChange = { screen ->
                        currentScreen = RallyScreen.valueOf(screen)
                    }
                )
            }
        }
    }
}

enum class RallyScreen(
    val icon: ImageVector,
    val body: @Composable ((String) -> Unit) -> Unit
) {
    Overview(
        icon = Icons.Filled.PieChart,
        body = { OverviewBody() }
    ),
    Accounts(
        icon = Icons.Filled.AttachMoney,
        body = { AccountsBody(UserData.accounts) }
    ),
    Bills(
        icon = Icons.Filled.MoneyOff,
        body = { BillsBody(UserData.bills) }
    );

    @Composable
    fun content(onScreenChange: (String) -> Unit) {
        body(onScreenChange)
    }
}

Code end

@Composable
fun RallyNavHost(navController: NavHostController, modifier: Modifier = Modifier) {
    NavHost(
        navController = navController,
        startDestination = Overview.name,
        modifier = modifier
    ) {
        composable(Overview.name) {
            OverviewBody(
              ...
            )
        }
        composable(Accounts.name) {
          ...
        }
        composable(Bills.name) {
          ...
        }
    }
}

enum class RallyScreen(
    val icon: ImageVector,
) {
    Overview(
        icon = Icons.Filled.PieChart,
    ),
    Accounts(
        icon = Icons.Filled.AttachMoney,
    ),
    Bills(
        icon = Icons.Filled.MoneyOff,
    );

    companion object {
        fun fromRoute(route: String?): RallyScreen =
            when (route?.substringBefore("/")) {
                Accounts.name -> Accounts
                Bills.name -> Bills
                Overview.name -> Overview
                null -> Overview
                else -> throw IllegalArgumentException("Route $route is not recognized.")
            }
    }

Code A

fun CraneHomeContent(
   ...
) {
    val suggestedDestinations by viewModel.suggestedDestinations.collectAsState()

    val onPeopleChanged: (Int) -> Unit = { viewModel.updatePeople(it) }
    var tabSelected by remember { mutableStateOf(CraneScreen.Fly) }

    BackdropScaffold(
        ...
        frontLayerContent = {
            when (tabSelected) {
                CraneScreen.Fly -> {
                  ...
                }
                CraneScreen.Sleep -> {
                   ...
                }
                CraneScreen.Eat -> {
                   ...
                }
            }
        }
    )
}


问:
Android - make all RelativeLayouts like floating left and going automatically in new lines
I have this scenario :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
.... >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ImageView as label ... />

        <TextView text content....
          android:layout_toRightOf=label />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ImageView as label ... />

        <TextView text content....
          android:layout_toRightOf=label />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ImageView as label ... />

        <TextView text content....
          android:layout_toRightOf=label />

    </RelativeLayout>

    .
    .
    .
    .

</LinearLayout>
</code>```

And I wanted all those relativelayouts to position automatically each one next to the previous and going automatically at new line if mobile phone is vertical and going automatically in one line if mobile phone is horizontal... I tried with GridLayout but looks like is not so good because contents textviews have different lenght depends from informations I get... is there a way to solve that? Thanks! Cheers!

答: Android framework doesn't have such option built-in, you could write it by own, but Google did that for you. check out flexbox-layout library</p>

Body:
I have this scenario :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
.... >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ImageView as label ... />

        <TextView text content....
          android:layout_toRightOf=label />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ImageView as label ... />

        <TextView text content....
          android:layout_toRightOf=label />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ImageView as label ... />

        <TextView text content....
          android:layout_toRightOf=label />

    </RelativeLayout>

    .
    .
    .
    .

</LinearLayout>

And I wanted all those relativelayouts to position automatically each one next to the previous and going automatically at new line if mobile phone is vertical and going automatically in one line if mobile phone is horizontal... I tried with GridLayout but looks like is not so good because contents textviews have different lenght depends from informations I get... is there a way to solve that? Thanks! Cheers!


问:
Get request for the policies in controller constructor
I'm setting up policies for my laravel application, and I'm stuck with a problem. I have to put the policy in the constructor of my controller this way:

```<code> public function __construct()
    {
        $this->middleware(['can:viewAny,App\Models\Photo'], ['only' => ['index']]);
        $this->middleware(['can:view,photo'], ['only' => ['show']]);
    }
</code>```

Problem is, for the store action, I have to check one of the params sent in the request to check if the user is allowed to post on the related parent. According to the documentation, I could make my Policy this way:

```<code>public function store(User $user, int $parentId)
{
    $parent = Parent::find($parentId);
    return $user->id === $parent->user_id
}
</code>```

And in the controller:

```<code>public function store(Request $request)
{
    $this->authorize('store', [$request->parent]);
    // The current user can store the photo...
}
</code>```

But in the example, the authorization is put in the function, and there are no example with the usage of the request when treating the policy as a middleware. Is it even possible? I would have crafted something like:

```<code>    $this->middleware(['can:store,App\Models\Photo,request->parent'], ['only' => ['store']]);
</code>```

But that won't work. Thanks a lot if you can help me on this one!

答:
I found how to do it, I forgot about the request() helper. Thus, I can access everything put in the request, and I can call the helper directly inside the policy.

So I can do this in the contructor:

```<code>    $this->middleware(['can:store,App\Models\Photo'], ['only' => ['store']]);
</code>```

And in the PhotoPolicy:

```<code>public function store(User $user)
{
    $input = request()->input();
    $parent = Parent::find($input['parent_id']);
    return $user->id === $parent->user_id
}
</code>```

Body:
I'm setting up policies for my laravel application, and I'm stuck with a problem. I have to put the policy in the constructor of my controller this way:

 public function __construct()
    {
        $this->middleware(['can:viewAny,App\Models\Photo'], ['only' => ['index']]);
        $this->middleware(['can:view,photo'], ['only' => ['show']]);
    }

Problem is, for the store action, I have to check one of the params sent in the request to check if the user is allowed to post on the related parent. According to the documentation, I could make my Policy this way:

public function store(User $user, int $parentId)
{
    $parent = Parent::find($parentId);
    return $user->id === $parent->user_id
}

And in the controller:

public function store(Request $request)
{
    $this->authorize('store', [$request->parent]);
    // The current user can store the photo...
}

But in the example, the authorization is put in the function, and there are no example with the usage of the request when treating the policy as a middleware. Is it even possible? I would have crafted something like:

    $this->middleware(['can:store,App\Models\Photo,request->parent'], ['only' => ['store']]);

But that won't work. Thanks a lot if you can help me on this one!

Body:
I found how to do it, I forgot about the request() helper. Thus, I can access everything put in the request, and I can call the helper directly inside the policy.

So I can do this in the contructor:

    $this->middleware(['can:store,App\Models\Photo'], ['only' => ['store']]);

And in the PhotoPolicy:

public function store(User $user)
{
    $input = request()->input();
    $parent = Parent::find($input['parent_id']);
    return $user->id === $parent->user_id
}


问:
JQUERY: add a tiny arrow next to the following field on this form on focus
Im trying to express in Jquery the following:

I want to show a tiny arrow right next to the following input/select on the right side so every user knows where to go next.

To express the exact order im trying to make the users follow when completing the form im using numbers on the field name so you can understand the order.

Form: http://jsfiddle.net/yqh5V/1/

Please EXPAND the jsfiddle html so  u can properly display the form with the margins etc

Tiny green arrow: http://i53.tinypic.com/f1ystu.png

I cant do it without positioning the arrow to the right and not messing up the margins.

Is it clear what i want to do?

答:
I agree that adding the arrow will mess with the margins, etc.

Why not do something else, like change the border on the input / select and maybe the background, too?  Something like this

```<code>$('input, select').focus(function(){
    $(this).css({'border' : '2px solid green' , 'background' : '#999'});
});

$('input, select').blur(function(){
    $(this).css({'border' : 'none' , 'background' : 'none'});
});
</code>```

http://jsfiddle.net/jasongennaro/yqh5V/3/

ContentLicense: CC BY-SA 3.0

Body:
I agree that adding the arrow will mess with the margins, etc.

Why not do something else, like change the border on the input / select and maybe the background, too?  Something like this

$('input, select').focus(function(){
    $(this).css({'border' : '2px solid green' , 'background' : '#999'});
});

$('input, select').blur(function(){
    $(this).css({'border' : 'none' , 'background' : 'none'});
});

http://jsfiddle.net/jasongennaro/yqh5V/3/


问:
Why is ".map" slower then "while/for loop" in Dart(Flutter)
I saw this article:
https://itnext.io/comparing-darts-loops-which-is-the-fastest-731a03ad42a2

It says that ".map" is slow with benchmark result

But I don't understand why slower than while/for loop

How does it work in low level?

I think it's because .map is called an unnamed method like this (_){ }

Can you explain that in detail?

答:
Can you explain that in detail?

It's like saying "I don't understand why hitchhiking on the back of a construction truck is so much slower than taking the high speed train to my destination".

The only detail that is important is that map is not a loop. map() internally probably uses a loop of some kind.

This person is misusing a method call that is meant for something else, just because a side-effect of that call when combining it with a call materializing the iterable, like toList(), is that it loops through the iterable given. It doesn't even have the side effect on it's own.

Stop reading "tutorials" or "tips" of people misusing language features. map() is not a loop. If you need a loop, use a loop. The same goes for the ternary operator. It's not an if, if you need an if, use it.

Use language features for what they are meant, stop misusing language features because their side-effect does what you want and then wondering why they don't work as well as the feature actually meant for it.

Sorry if this seems a bit ranty, but I have seen countless examples by now. I don't know where it comes from. My personal guess is "internet tutorials". Because everybody can write one. Please don't read them. Read a good book. It was written by professionals, proofread, edited, and checked. Internet tutorials are free, written by random people and about worth as much as they cost.


问:
Python: Create a list based on elements on text and extracting specific values
I have the following text:

mytext = '2/3/4/5/6/'

In python, I need to create a list or a dictionary with values on this text, extracting the number between "/", but excluding the last one.

The final result should be something like:

myresult = ['2', '3', '4', '5']

Thank you in advance

答:
```<code>mytext.split('/')[:-2]
</code>```

This should work to create a list for the given format.

Body:
mytext.split('/')[:-2]

This should work to create a list for the given format.


问:
beatiful soup 4 getting an output as (['link1'] ['link2'] ['link3']). How to change as a required format? (['link1', 'link2', 'link3'])
beatiful soup 4 getting an output as (example - ['link1']['link2']['link3']). How to change as a required format? (example - ['link1', 'link2', 'link3'])

I am getting this below output.

```<code>['link1']
['link2']
['link3']
</code>```

I need an output as i mentioned below like this to form a data frame, so what i need to do now.

```<code>['link1', 'link2', 'link3']
</code>```

Exaplain with code also fine. please help me to solve this issue, thanks in advance.

My code

```<code>import bs4
from bs4 import BeautifulSoup
from csv import writer
import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0'}
HOST = 'https://www.zocdoc.com'
#PAGE = 'gastroenterologists/2'
web_page = 'https://www.zocdoc.com/search?address=Houston%2C%20TX&insurance_carrier=&city=Houston&date_searched_for=&day_filter=AnyDay&filters=%7B%7D&gender=-1&language=-1&latitude=29.7604267&locationType=placemark&longitude=-95.3698028&offset=1&insurance_plan=-1&reason_visit=386&search_query=Gastroenterologist&searchType=specialty&sees_children=false&after_5pm=false&before_10am=false&sort_type=Default&dr_specialty=106&state=TX&visitType=inPersonVisit&&timesgridType='
with requests.Session() as session:
    (r := session.get(HOST, headers=headers)).raise_for_status()
    #(r := session.get(f'{HOST}/{PAGE}', headers=headers)).raise_for_status()
    (r := session.get(f'{web_page}', headers=headers)).raise_for_status()
    # process content from here
print(r.text)
soup = BeautifulSoup(r.text, 'lxml')
soup
print(soup.prettify())
</code>```

code 1 to get as a link

```<code>for item in soup.find_all('img'):
    images = []
    items = (item['src'])
    images = 'https:'+items
    print(images)
</code>```

code 2 to get below mentioned output format

```<code>for item in soup.find_all('img'):
    c = []
    items = (item['src'])
    image = ('https:'+items)
    c.append(image)
    print(c)
</code>```

Output - ['link1']
.
.
['linkn']

答:
You have to append the urls to a list outsite your loop to avoid overwriting and get the structure you expect:

```<code>images = []
for item in soup.find_all('img'):
    images.append('https:'+item['src'])
</code>```

As an alternative you can go with a list comprehension notation:

```<code>images = ['https:'+item['src'] for item in soup.find_all('img')]
</code>```

Just a hint - Avoid storing scraped information in these bunch of lists, use more structured like dict:

```<code>data = []
for item in soup.find_all('article'):
    data.append({
        'name':item.find('span',{'itemprop':'name'}).text,
        'image':'https:'+item.img['src'],
        'anyOtherInfo':'anyOtherInfo'
    })
</code>```

Body:
beatiful soup 4 getting an output as (example - ['link1']['link2']['link3']). How to change as a required format? (example - ['link1', 'link2', 'link3'])

I am getting this below output.

['link1']
['link2']
['link3']

I need an output as i mentioned below like this to form a data frame, so what i need to do now.

['link1', 'link2', 'link3']

Exaplain with code also fine. please help me to solve this issue, thanks in advance.

My code

import bs4
from bs4 import BeautifulSoup
from csv import writer
import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0'}
HOST = 'https://www.zocdoc.com'
#PAGE = 'gastroenterologists/2'
web_page = 'https://www.zocdoc.com/search?address=Houston%2C%20TX&insurance_carrier=&city=Houston&date_searched_for=&day_filter=AnyDay&filters=%7B%7D&gender=-1&language=-1&latitude=29.7604267&locationType=placemark&longitude=-95.3698028&offset=1&insurance_plan=-1&reason_visit=386&search_query=Gastroenterologist&searchType=specialty&sees_children=false&after_5pm=false&before_10am=false&sort_type=Default&dr_specialty=106&state=TX&visitType=inPersonVisit&&timesgridType='
with requests.Session() as session:
    (r := session.get(HOST, headers=headers)).raise_for_status()
    #(r := session.get(f'{HOST}/{PAGE}', headers=headers)).raise_for_status()
    (r := session.get(f'{web_page}', headers=headers)).raise_for_status()
    # process content from here
print(r.text)
soup = BeautifulSoup(r.text, 'lxml')
soup
print(soup.prettify())

code 1 to get as a link

for item in soup.find_all('img'):
    images = []
    items = (item['src'])
    images = 'https:'+items
    print(images)

code 2 to get below mentioned output format

for item in soup.find_all('img'):
    c = []
    items = (item['src'])
    image = ('https:'+items)
    c.append(image)
    print(c)

Output - ['link1']
.
.
['linkn']

Body:
You have to append the urls to a list outsite your loop to avoid overwriting and get the structure you expect:

images = []
for item in soup.find_all('img'):
    images.append('https:'+item['src'])

As an alternative you can go with a list comprehension notation:

images = ['https:'+item['src'] for item in soup.find_all('img')]

Just a hint - Avoid storing scraped information in these bunch of lists, use more structured like dict:

data = []
for item in soup.find_all('article'):
    data.append({
        'name':item.find('span',{'itemprop':'name'}).text,
        'image':'https:'+item.img['src'],
        'anyOtherInfo':'anyOtherInfo'
    })


问:
How to 'narrow' onchange for specific id?
I found this cod on jquery web

```<code>$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();
</code>```

I can use it for I want but I want this function to be fired only for #my_id. I tried to insert #my_id after both selects but then the function does nothing.

I though I could bind this function to only select with specific id.

答:
as in?</p>

```<code>$("#my_id").change(function () {
  var str = "";
  $("#my_id :selected").each(function () {
        str += $(this).text() + " ";
      });
  $("div").text(str);
})
.change();
</code>```

Body:
I found this cod on jquery web

$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();

I can use it for I want but I want this function to be fired only for #my_id. I tried to insert #my_id after both selects but then the function does nothing.

I though I could bind this function to only select with specific id.

Body:
as in?

$("#my_id").change(function () {
  var str = "";
  $("#my_id :selected").each(function () {
        str += $(this).text() + " ";
      });
  $("div").text(str);
})
.change();


问:
How to test Reference type value in cdk stack?
I am using aws cdk library to create resource and was able to create resources succuessfully. Now want to test this generated statck. Again if its single resources then able to test it fine but when stack has more than one resources then don't how to rest that.

Following is code to create resources.

```<code>constructor(scope: cdk.Construct, id: string, props: CIAMSQSProps = {} ) {
    super(scope, id);

    const queue = new sqs.Queue(this, id, {
      queueName: props.queueName!,
    });

    let ssmParamters = new CreateSSMParamaters(this, id, {
      envName: props.envName!,
      envValue: sqsQueue.queueUrl
    });
}
</code>```

Following is the code for testing and it fails because stack contains reference.

```<code>test('Test SSM Parameter', () => {
  const app = new App();
  const sqsStack = new TestSQS(app, 'test-sqs-stack', {
    queueName: 'TestQueue',
    envName: 'TestQueue',
  });

  const template = Template.fromStack(sqsStack);
  template.hasResourceProperties(ResourceTypes.SSM_PARAM_TYPE, "{ Name: 'TestQueue', Value: 'TestQueue', Type: 'String' }");
});
</code>```

Following is the error.

```<code>Template has 1 resources with type AWS::SSM::Parameter, but none match as expected.
    The closest result is:
      {
        "Type": "AWS::SSM::Parameter",
        "Properties": {
          "Type": "String",
          "Value": {
            "Ref": "testsqsstackEDC1E09E"
          },
          "Name": "TestQueue"
        }
      }
    with the following mismatches:
        Expected type string but received object at /Properties (using objectLike matcher)
</code>```

can someone help me on this? Or is there any way to test specific property for resource type?

答:
I have found several options to test property references.  I have not seen any documented best practice on this topic. Perhaps this is because, in most cases, we need not test such implementation details.

Option 1:  Export the source Construct from its Stack.  Resolve its Token value.

template.hasResourceProperties('AWS::SSM::Parameter', {
  Value: stack.resolve(stack.queue.queueName),
});
```
<p><strong>Option 2:</strong>  As above, but use escape hatches instead of field export to get the queue reference.</p>
<pre class="lang-js prettyprint-override"><code>const childQueue = stack.node.tryFindChild('MyQueue') as sqs.Queue;

template.hasResourceProperties('AWS::SSM::Parameter', {
  Value: stack.resolve(childQueue.queueName),
});
</code>```

Option 3:  Find the queue resource's name in the template.

const queues = template.findResources('AWS::SQS::Queue');
expect(Object.keys(queues)).toHaveLength(1);
const resolvedQueueName = Object.keys(queues)[0];

template.hasResourceProperties('AWS::SSM::Parameter', {
  Value: { 'Fn::GetAtt': [resolvedQueueName, 'QueueName'],},
});
```

Body:
I am using aws cdk library to create resource and was able to create resources succuessfully. Now want to test this generated statck. Again if its single resources then able to test it fine but when stack has more than one resources then don't how to rest that.

Following is code to create resources.

constructor(scope: cdk.Construct, id: string, props: CIAMSQSProps = {} ) {
    super(scope, id);

    const queue = new sqs.Queue(this, id, {
      queueName: props.queueName!,
    });

    let ssmParamters = new CreateSSMParamaters(this, id, {
      envName: props.envName!,
      envValue: sqsQueue.queueUrl
    });
}

Following is the code for testing and it fails because stack contains reference.

test('Test SSM Parameter', () => {
  const app = new App();
  const sqsStack = new TestSQS(app, 'test-sqs-stack', {
    queueName: 'TestQueue',
    envName: 'TestQueue',
  });

  const template = Template.fromStack(sqsStack);
  template.hasResourceProperties(ResourceTypes.SSM_PARAM_TYPE, "{ Name: 'TestQueue', Value: 'TestQueue', Type: 'String' }");
});

Following is the error.

Template has 1 resources with type AWS::SSM::Parameter, but none match as expected.
    The closest result is:
      {
        "Type": "AWS::SSM::Parameter",
        "Properties": {
          "Type": "String",
          "Value": {
            "Ref": "testsqsstackEDC1E09E"
          },
          "Name": "TestQueue"
        }
      }
    with the following mismatches:
        Expected type string but received object at /Properties (using objectLike matcher)

can someone help me on this? Or is there any way to test specific property for resource type?

Body:
I have found several options to test property references.  I have not seen any documented best practice on this topic. Perhaps this is because, in most cases, we need not test such implementation details.

Option 1:  Export the source Construct from its Stack.  Resolve its Token value.

template.hasResourceProperties('AWS::SSM::Parameter', {
  Value: stack.resolve(stack.queue.queueName),
});

Option 2:  As above, but use escape hatches instead of field export to get the queue reference.

const childQueue = stack.node.tryFindChild('MyQueue') as sqs.Queue;

template.hasResourceProperties('AWS::SSM::Parameter', {
  Value: stack.resolve(childQueue.queueName),
});

Option 3:  Find the queue resource's name in the template.

const queues = template.findResources('AWS::SQS::Queue');
expect(Object.keys(queues)).toHaveLength(1);
const resolvedQueueName = Object.keys(queues)[0];

template.hasResourceProperties('AWS::SSM::Parameter', {
  Value: { 'Fn::GetAtt': [resolvedQueueName, 'QueueName'],},
});


问:
Swift Mac OS: blank page printed when I try to print webView (WKWebView)
I made a webView present a given HTML string, using this code:

```<code>let filePath = Bundle.main.path(forResource: "my file name", ofType: "html")
let htmlStr = try! NSString.init(contentsOfFile: filePath!, encoding: String.Encoding.utf8.rawValue)
webView.loadHTMLString(htmlStr as String, baseURL: nil)
</code>```

the webView present the HTML correctly but when I try to print it the print panel appear with blank page, I used this:

```<code>webView.printView(nil)
</code>```

also I tried this:

```<code>NSPrintOperation(view: webView).run()
</code>```

All appeared print panel with blank page! Any help?

答:
run() doesn't work with WKWebView on OSX.  Use runModal(for:delegate:didRun:contextInfo) instead.  Example:

```<code>let printInfo = NSPrintInfo.shared
printInfo.horizontalPagination = .fit
printInfo.verticalPagination = .automatic
printInfo.isVerticallyCentered = true
printInfo.isHorizontallyCentered = true
printInfo.orientation = .portrait
printInfo.topMargin = 20
printInfo.bottomMargin = 20
printInfo.rightMargin = 20
printInfo.leftMargin = 20

let op = self.webView.printOperation(with: printInfo)
op.showsPrintPanel = true
op.showsProgressPanel = true
op.view?.frame = self.webView.bounds
op.runModal(for: self.view.window!, delegate: self, didRun: nil, contextInfo: nil)
</code>```

I got this from: How does one Print all WKWebView On AND Offscreen content OSX and iOS

Body:
I made a webView present a given HTML string, using this code:

let filePath = Bundle.main.path(forResource: "my file name", ofType: "html")
let htmlStr = try! NSString.init(contentsOfFile: filePath!, encoding: String.Encoding.utf8.rawValue)
webView.loadHTMLString(htmlStr as String, baseURL: nil)

the webView present the HTML correctly but when I try to print it the print panel appear with blank page, I used this:

webView.printView(nil)

also I tried this:

NSPrintOperation(view: webView).run()

All appeared print panel with blank page! Any help?

Body:
run() doesn't work with WKWebView on OSX.  Use runModal(for:delegate:didRun:contextInfo) instead.  Example:

let printInfo = NSPrintInfo.shared
printInfo.horizontalPagination = .fit
printInfo.verticalPagination = .automatic
printInfo.isVerticallyCentered = true
printInfo.isHorizontallyCentered = true
printInfo.orientation = .portrait
printInfo.topMargin = 20
printInfo.bottomMargin = 20
printInfo.rightMargin = 20
printInfo.leftMargin = 20

let op = self.webView.printOperation(with: printInfo)
op.showsPrintPanel = true
op.showsProgressPanel = true
op.view?.frame = self.webView.bounds
op.runModal(for: self.view.window!, delegate: self, didRun: nil, contextInfo: nil)

I got this from: How does one Print all WKWebView On AND Offscreen content OSX and iOS


问:
Creating a view that contains all records from one table, that match the comma separated field content in another table
I have two tables au_postcodes and groups.

Table groups contains a field called PostCodeFootPrint
that contains the postcode set making up the footprint.

Table au_postcodes contains a field called poa_code that
contains a single postcode.

The records in groups.PostCodeFootPrint look like:

PostCodeFootPrint

2529,2530,2533,2534,2535,2536,2537,2538,2539,2540,2541,2575,2576,2577,2580

2640

3844

2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2077, 2079, 2080, 2081, 2082, 2083, 2119, 2120, 2126, 2158, 2159

2848, 2849, 2850, 2852

Some records have only one postcode, some have multiple separated by a "," or ", " (comma and space).

The records in au_postcode.poa_code look like:

poa_code

2090

2092

2093

829

830

836

2080

2081

Single postcode (always).

The objective is to:

Get all records from au_postcode, where the poa_code appears in groups.*PostCodeFootPrint into a view.

I tried:

```<code>SELECT
    au_postcodes.poa_code,
    groups."NameOfGroup"
FROM
    groups,
    au_postcodes
WHERE
    groups."PostcodeFootprint" LIKE '%au_postcodes.poa_code%'
</code>```

But no luck

答:
Since the values of PostCodeFootPrint are separated by a common character, you can easily create an array out of it. From there use unnest to convert the array elements to records, and then join then with au_postcode:

```<code>SELECT * FROM au_postcode au
JOIN (SELECT trim(unnest(string_to_array(PostCodeFootPrint,',')))
      FROM groups) fp (PostCodeFootPrint) ON fp.PostCodeFootPrint = au.poa_code;
</code>```

Demo: db<>fiddle

Body:
I have two tables au_postcodes and groups.

Table groups contains a field called PostCodeFootPrint
that contains the postcode set making up the footprint.

Table au_postcodes contains a field called poa_code that
contains a single postcode.

The records in groups.PostCodeFootPrint look like:

PostCodeFootPrint

2529,2530,2533,2534,2535,2536,2537,2538,2539,2540,2541,2575,2576,2577,2580

2640

3844

2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2077, 2079, 2080, 2081, 2082, 2083, 2119, 2120, 2126, 2158, 2159

2848, 2849, 2850, 2852

Some records have only one postcode, some have multiple separated by a "," or ", " (comma and space).

The records in au_postcode.poa_code look like:

poa_code

2090

2092

2093

829

830

836

2080

2081

Single postcode (always).

The objective is to:

Get all records from au_postcode, where the poa_code appears in groups.*PostCodeFootPrint into a view.

I tried:

SELECT
    au_postcodes.poa_code,
    groups."NameOfGroup"
FROM
    groups,
    au_postcodes
WHERE
    groups."PostcodeFootprint" LIKE '%au_postcodes.poa_code%'

But no luck

Body:
Since the values of PostCodeFootPrint are separated by a common character, you can easily create an array out of it. From there use unnest to convert the array elements to records, and then join then with au_postcode:

SELECT * FROM au_postcode au
JOIN (SELECT trim(unnest(string_to_array(PostCodeFootPrint,',')))
      FROM groups) fp (PostCodeFootPrint) ON fp.PostCodeFootPrint = au.poa_code;

Demo: db<>fiddle


问:
Write annotation to guard a method from being called when parameters are invalid
Can I have an annotation for a method that when its parameters are null, just do nothing, effectively as not being invoked?</p>

答:
Probably the easiest way to do this is using interfaces and dynamic proxies. Annotations do nothing other than add metadata. You're going to have to add code to act based on the annotation.

You'd have to do a few things --

Create an interface

```<code>public interface IService {

     @ValidateNull // Your custom annotation
     public void yourMethod(String s1);
}
</code>```

When using the implementation, instantiate it as a JDK Proxy.

```<code>IService myService = (IService)java.lang.Proxy.newInstance(ServiceImpl.class.getClassLoader(),
                           ServiceImpl.class.getInterfaces(),
                           new YourProxy(new ServiceImpl());
</code>```

Now, you can via reflection, capture all invocations of your method in YourProxy class.

```<code> public YourProxy implements InvocationHandler {
public Object invoke(Object arg0, Method method, Object[] args) throws Throwable {
    if (method.isAnnotationPresent(ValidateNull.class)) {
                   //Check args if they are null and return.
            }
     }
 }
</code>```

If you dont want to do this, then you're looking at more heavyweight frameworks such as AspectJ  / Spring AOP.

Body:
Probably the easiest way to do this is using interfaces and dynamic proxies. Annotations do nothing other than add metadata. You're going to have to add code to act based on the annotation.

You'd have to do a few things --

Create an interface

public interface IService {

     @ValidateNull // Your custom annotation
     public void yourMethod(String s1);
}

When using the implementation, instantiate it as a JDK Proxy.

IService myService = (IService)java.lang.Proxy.newInstance(ServiceImpl.class.getClassLoader(),
                           ServiceImpl.class.getInterfaces(),
                           new YourProxy(new ServiceImpl());

Now, you can via reflection, capture all invocations of your method in YourProxy class.

 public YourProxy implements InvocationHandler {
public Object invoke(Object arg0, Method method, Object[] args) throws Throwable {
    if (method.isAnnotationPresent(ValidateNull.class)) {
                   //Check args if they are null and return.
            }
     }
 }

If you dont want to do this, then you're looking at more heavyweight frameworks such as AspectJ  / Spring AOP.


问:
Why "message here" text seems like bold
I'm using jQuery to append
, and it's appending an extra close icon but I can't see why. If you run the code snippet below and click on "Add more" link, you'll see an additional times (x) icon, and the "message here" text seems bolded.

$(function() {

  $("#add").click(function() {
    $('

<input type="text" class="form-control" placeholder="Domain">

 message here

').appendTo("#DomainsList");
  });

  $("#DomainsList").on("click", ".remove", function() {
    $(this).closest('.domainName').remove();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<section id="DomainsList">
  <div class="row">
    <div class="col">
      <div class="input-group mb-2">
        <span class="input-group-text bg-white"><i class="fas fa-lock text-secondary"></i></span>
        <input type="text" class="form-control" placeholder="Domains">
      </div>
    </div>
    <div class="col">message here</div>
  </div>
</section>
<i class="fas fa-plus-circle"></i> Add More</code>```

答:
//do not use fas fa-times class from i tag and add into span tag html ,and add css .remove {    cursor: pointer;} for display hand cursor while mouse over on it, see bellow code  $("#add").click(function() {
$('
 message here ').appendTo("#DomainsList");
});

Title: Why "message here" text seems like bold

Body:
I'm using jQuery to append
, and it's appending an extra close icon but I can't see why. If you run the code snippet below and click on "Add more" link, you'll see an additional times (x) icon, and the "message here" text seems bolded.

$(function() {

  $("#add").click(function() {
    $('

<input type="text" class="form-control" placeholder="Domain">

 message here

').appendTo("#DomainsList");
  });

  $("#DomainsList").on("click", ".remove", function() {
    $(this).closest('.domainName').remove();
  });
});

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

        <input type="text" class="form-control" placeholder="Domains">

message here

 Add More


问:
how to update specified field to null with update option equals 2 in TDengine database?
by using update = 2 option when creating database, we can update specified field, how should I update this field to null?

taos> create database db update 2;                                                                                [5/2934]
Query OK, 0 of 0 row(s) in database (0.008446s)

taos> use db;
Database changed.

taos> create table tb(ts timestamp, c1 int, c2 nchar(20));
Query OK, 0 of 0 row(s) in database (0.024248s)

taos> insert into tb values(now, 1, "beijing");
Query OK, 1 of 1 row(s) in database (0.008139s)

taos> select * from tb;
           ts            |     c1      |               c2               |
=========================================================================
 2022-02-07 14:54:54.189 |           1 | beijing                        |
Query OK, 1 row(s) in set (0.001694s)

taos> insert into tb values("2022-02-07 14:54:54.189", 2, NULL);
Query OK, 1 of 1 row(s) in database (0.000608s)

taos> select * from tb;
           ts            |     c1      |               c2               |
=========================================================================
 2022-02-07 14:54:54.189 |           2 | beijing                        |
Query OK, 1 row(s) in set (0.005644s)

```

答: Because update = 2 cannot achieve what you want, you can use update = 1


问:
make Laravel 8's Validator class work outside the framework
So I installed this package https://packagist.org/packages/illuminate/validation into my project with the command composer require illuminate/validation where you get a stand-alone version of Laravels validator. Then when I tried to use it like the docs say you should https://laravel.com/docs/8.x/validation and try to implement it like this

```<code>    $validated = Validator::make($data, [
        'token' => 'required',
        'email' => 'required',
        'password' => 'required',
    ])->validate();
</code>```

I get an 'message' => 'A facade root has not been set.', also this is the $data object

```<code>    array (
        'token' => 'c11019348c3876f033603a0d0030ad3f0c9ec7d7ae211a49',
        'email' => 'ewaeaw',
        'password' => 'ewaeaw',
      ),
</code>```

so do I need to invoke the library somewhere or what am I'm doing wrong cause the Github readme of the package just says https://github.com/illuminate/validation [READ ONLY] Subtree split of the Illuminate Validation component (see laravel/framework)
so what steps am I missing so it works fine so that I can implement it into my project

I also have looked into this Fail to make Laravel 4's Validator class work outside the framework it says you can implement it with this line $factory = new \Illuminate\Validation\Factory(new \Symfony\Component\Translation\Translator('en'));
but the class \Illuminate\Validation\Factory doesn't exist anymore. cause the namespace is Illuminate\Support\Facades\Validator prob cause it 9 years old? so some one has any up to date method of doing this? also looking at the vendor map there doesn't exist any factory class inside the Facades folder

答:
you can use validation in simple way like the following

```<code>use Illuminate\Support\Facades\Validator;

        $validation=Validator::make($request->all(),[
        'token'=>'required',
        'email'=>'required',
        'password'=>'required',
    ]);
    if($validation->fails())
    return response()->json($validation->errors());
</code>```

you can test it from postman or any other way

hopefully that help you

Body:
So I installed this package https://packagist.org/packages/illuminate/validation into my project with the command composer require illuminate/validation where you get a stand-alone version of Laravels validator. Then when I tried to use it like the docs say you should https://laravel.com/docs/8.x/validation and try to implement it like this

    $validated = Validator::make($data, [
        'token' => 'required',
        'email' => 'required',
        'password' => 'required',
    ])->validate();

I get an 'message' => 'A facade root has not been set.', also this is the $data object

    array (
        'token' => 'c11019348c3876f033603a0d0030ad3f0c9ec7d7ae211a49',
        'email' => 'ewaeaw',
        'password' => 'ewaeaw',
      ),

so do I need to invoke the library somewhere or what am I'm doing wrong cause the Github readme of the package just says https://github.com/illuminate/validation [READ ONLY] Subtree split of the Illuminate Validation component (see laravel/framework)
so what steps am I missing so it works fine so that I can implement it into my project

I also have looked into this Fail to make Laravel 4's Validator class work outside the framework it says you can implement it with this line $factory = new \Illuminate\Validation\Factory(new \Symfony\Component\Translation\Translator('en'));
but the class \Illuminate\Validation\Factory doesn't exist anymore. cause the namespace is Illuminate\Support\Facades\Validator prob cause it 9 years old? so some one has any up to date method of doing this? also looking at the vendor map there doesn't exist any factory class inside the Facades folder

Body:
you can use validation in simple way like the following

use Illuminate\Support\Facades\Validator;

        $validation=Validator::make($request->all(),[
        'token'=>'required',
        'email'=>'required',
        'password'=>'required',
    ]);
    if($validation->fails())
    return response()->json($validation->errors());

you can test it from postman or any other way

hopefully that help you


问:
XPathSelectElements always return empty in XML with namespace?
I'm working on XML string as follows:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <Get_x0020_Remain_x0020_VacationResponse xmlns="http://tempuri.org/">
      <Get_x0020_Remain_x0020_VacationResult>
        <Period>0:0</Period>
        <Month>0:0</Month>
        <YearPeriod>16:0</YearPeriod>
        <YearMonth>32:0</YearMonth>
        <CurrentPeriod>0:0</CurrentPeriod>
        <CurrentMonth>14:0</CurrentMonth>
        <PeriodName>Davazdah</PeriodName>
        <MonthName>bahman</MonthName>
        <RemainUpToNowPeriod>0:0</RemainUpToNowPeriod>
        <RemainUpToNowMonth>0:0</RemainUpToNowMonth>
        <RemainUpToEndOfThisYearPeriodic>0:0</RemainUpToEndOfThisYearPeriodic>
        <RemainUpToEndOfThisYearMonthly>16:0</RemainUpToEndOfThisYearMonthly>
      </Get_x0020_Remain_x0020_VacationResult>
    </Get_x0020_Remain_x0020_VacationResponse>
  </soap:Body>
</soap:Envelope>
```
<p>I want to access <code>RemainUpToEndOfThisYearMonthly</code> element using <code>XPATH</code><br>
My code:</p>
<pre class="lang-cs prettyprint-override"><code>var xDocument = XDocument.Parse(xmlString);
var xmlNamespaceManager = new XmlNamespaceManager(xDocument.CreateReader().NameTable
    ?? new NameTable());
xmlNamespaceManager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
xmlNamespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNamespaceManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
xmlNamespaceManager.AddNamespace("", "http://tempuri.org/");
var nodeRemainUpToEndOfThisYearMonthly =
     xDocument.XPathSelectElements("//RemainUpToEndOfThisYearMonthly",
        xmlNamespaceManager); // always is empty
</code>```

But nodeRemainUpToEndOfThisYearMonthly is always empty.

How should I do that?

答:
This is included in the docs:

XPath treats the empty prefix as the null namespace. In other words, only prefixes mapped to namespaces can be used in XPath queries. This means that if you want to query against a namespace in an XML document, even if it is the default namespace, you need to define a prefix for it.

So, as stated, you need to add a prefix. Let's say temp:

xmlNamespaceManager.AddNamespace("temp", "http://tempuri.org/");

var nodeRemainUpToEndOfThisYearMonthly =
     xDocument.XPathSelectElements("//temp:RemainUpToEndOfThisYearMonthly",
        xmlNamespaceManager);
```
<p>I'd also note that none of the other prefixes need to be added unless you're going to be using them.</p>
<p>Having said that, I'd suggest that just using the LINQ to XML API is more straightforward and type-safe:</p>
<pre class="lang-cs prettyprint-override"><code>XNamespace temp = "http://tempuri.org/";

var remainUpToEndOfThisYearMonthly = (string) xDocument
    .Descendants(temp + "RemainUpToEndOfThisYearMonthly")
    .SingleOrDefault();
</code>```

Body:
I'm working on XML string as follows:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <Get_x0020_Remain_x0020_VacationResponse xmlns="http://tempuri.org/">
      <Get_x0020_Remain_x0020_VacationResult>
        <Period>0:0</Period>
        <Month>0:0</Month>
        <YearPeriod>16:0</YearPeriod>
        <YearMonth>32:0</YearMonth>
        <CurrentPeriod>0:0</CurrentPeriod>
        <CurrentMonth>14:0</CurrentMonth>
        <PeriodName>Davazdah</PeriodName>
        <MonthName>bahman</MonthName>
        <RemainUpToNowPeriod>0:0</RemainUpToNowPeriod>
        <RemainUpToNowMonth>0:0</RemainUpToNowMonth>
        <RemainUpToEndOfThisYearPeriodic>0:0</RemainUpToEndOfThisYearPeriodic>
        <RemainUpToEndOfThisYearMonthly>16:0</RemainUpToEndOfThisYearMonthly>
      </Get_x0020_Remain_x0020_VacationResult>
    </Get_x0020_Remain_x0020_VacationResponse>
  </soap:Body>
</soap:Envelope>

I want to access RemainUpToEndOfThisYearMonthly element using XPATH

My code:

var xDocument = XDocument.Parse(xmlString);
var xmlNamespaceManager = new XmlNamespaceManager(xDocument.CreateReader().NameTable
    ?? new NameTable());
xmlNamespaceManager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
xmlNamespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNamespaceManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
xmlNamespaceManager.AddNamespace("", "http://tempuri.org/");
var nodeRemainUpToEndOfThisYearMonthly =
     xDocument.XPathSelectElements("//RemainUpToEndOfThisYearMonthly",
        xmlNamespaceManager); // always is empty

But nodeRemainUpToEndOfThisYearMonthly is always empty.

How should I do that?

Body:
This is included in the docs:

XPath treats the empty prefix as the null namespace. In other words, only prefixes mapped to namespaces can be used in XPath queries. This means that if you want to query against a namespace in an XML document, even if it is the default namespace, you need to define a prefix for it.

So, as stated, you need to add a prefix. Let's say temp:

xmlNamespaceManager.AddNamespace("temp", "http://tempuri.org/");

var nodeRemainUpToEndOfThisYearMonthly =
     xDocument.XPathSelectElements("//temp:RemainUpToEndOfThisYearMonthly",
        xmlNamespaceManager);

I'd also note that none of the other prefixes need to be added unless you're going to be using them.

Having said that, I'd suggest that just using the LINQ to XML API is more straightforward and type-safe:

XNamespace temp = "http://tempuri.org/";

var remainUpToEndOfThisYearMonthly = (string) xDocument
    .Descendants(temp + "RemainUpToEndOfThisYearMonthly")
    .SingleOrDefault();


问:
Crossover of two Lists in Python
I have 2 lists with tens of thousands of records as follows:

```<code>list1=[
"c:\\user",
"C:\\Windows\\app\\Prog\\folder2\\folder3",
"C:\\Windows\\app\\Prog\\folder2",
"C:\\Intel\\Profiles\\user3\\se",
"C:\\Win\\add\\folder1"
]

list2=[
"C:\\Win\\add",
"C:\\Windows\\app\\Prog",
"C:\\Intel\\Profiles"
]

</code>```

I need to cross these two lists and put the result in a dictionary list like so:

```<code>dic=[
  {"k1": "c:\\user","k2": ""},
  {"k1": "C:\\Windows\\app\\Prog\\folder2\\folder3", "k2": "C:\\Windows\\app\\Prog"},
  {"k1": "C:\\Windows\\app\\Prog\\folder2", "k2": "C:\\Windows\\app\\Prog"},
  {"k1": "C:\\Intel\\Profiles\\user3\\se", "k2": "C:\\Intel\\Profiles"}
  {"k1": "C:\\Win\\add\\folder1", "k2": "C:\\Win\\add"}
]
</code>```

I solved it like this, but the execution is very slow because the lists can have hundreds of thousands of records.

```<code>def mergelists(list1,list2):
   dic=[]
   for i in range(len(list1)):
        fitem1=list1[i]
        result = [element for element in list2 if element in fitem1]
        row = {"k1": fitem1, "k2": result[0]}
        dic.append(row)
   return (dic)
</code>```

how to increase execution speed?

答:
One obvious way to speed this up is to change

```<code>result = [element for element in list2 if element in fitem1]
row = {"k1": fitem1, "k2": result[0]}
</code>```

to

```<code>result = next(element for element in list2 if element in fitem1)
row = {"k1": fitem1, "k2": result}
</code>```

because currently the code continues to search the whole list2 for elements that match fitem1, even if one has already been found.

The next function will return as soon as one element has been found and will skip searching the rest of list2.

Title: Crossover of two Lists in Python

Body:
I have 2 lists with tens of thousands of records as follows:

list1=[
"c:\\user",
"C:\\Windows\\app\\Prog\\folder2\\folder3",
"C:\\Windows\\app\\Prog\\folder2",
"C:\\Intel\\Profiles\\user3\\se",
"C:\\Win\\add\\folder1"
]

list2=[
"C:\\Win\\add",
"C:\\Windows\\app\\Prog",
"C:\\Intel\\Profiles"
]

I need to cross these two lists and put the result in a dictionary list like so:

dic=[
  {"k1": "c:\\user","k2": ""},
  {"k1": "C:\\Windows\\app\\Prog\\folder2\\folder3", "k2": "C:\\Windows\\app\\Prog"},
  {"k1": "C:\\Windows\\app\\Prog\\folder2", "k2": "C:\\Windows\\app\\Prog"},
  {"k1": "C:\\Intel\\Profiles\\user3\\se", "k2": "C:\\Intel\\Profiles"}
  {"k1": "C:\\Win\\add\\folder1", "k2": "C:\\Win\\add"}
]

I solved it like this, but the execution is very slow because the lists can have hundreds of thousands of records.

def mergelists(list1,list2):
   dic=[]
   for i in range(len(list1)):
        fitem1=list1[i]
        result = [element for element in list2 if element in fitem1]
        row = {"k1": fitem1, "k2": result[0]}
        dic.append(row)
   return (dic)

how to increase execution speed?

Body:
One obvious way to speed this up is to change

result = [element for element in list2 if element in fitem1]
row = {"k1": fitem1, "k2": result[0]}

to

result = next(element for element in list2 if element in fitem1)
row = {"k1": fitem1, "k2": result}

because currently the code continues to search the whole list2 for elements that match fitem1, even if one has already been found.

The next function will return as soon as one element has been found and will skip searching the rest of list2.


问:
Django rest setting the one to one relation creating an post method
I am new to django,I have created the models with OnetoOne relationship , I have user table and i have onetoone relation with storyboard library table, the issue is when i am creating an storyboardlibraby object , i need to save the user objectin the onetoonefield , even after adding user object not able to save the storyboardlibrary to the database, if anybody can help on this please help me , i will add the code which I have written.

```<code>class StoryboardLibrary(models.Model):
   name = models.CharField(max_length=50)
   data = JSONField(db_index=True)
   user = models.OneToOneField(User, on_delete=models.CASCADE)

   def __str__(self):
       return "%s The Library" % self.name
</code>```

Serializer class

```<code>class StoryboardSerializer(serializers.ModelSerializer):
class Meta:
    model = StoryboardLibrary
    fields = ('data','name','user')
</code>```

views post method

```<code>def add_storyboard(request):
# validating for already existing data
if StoryboardLibrary.objects.filter(**request.data).exists():
    raise serializers.ValidationError('This data already exists')
user = get_object_or_404(User, id=request.user.id)
request.data['user'] = user
storyboard = StoryboardSerializer(data=request.data)
print(storyboard)
if storyboard.is_valid():
    storyboard.save()
    return Response(storyboard.data, status=status.HTTP_201_CREATED)
else:
    return Response(status=status.HTTP_404_NOT_FOUND)
</code>```

After hitting the post api i am not able to save the data storyboardserializer is not valid hence it is executing the else block and returning the status 404 not found

答:
So,
here you are filtering with the requested user, so

```<code>get_object_or_404
</code>```

is not required because if request comes, there is a user and an id.

also request.data is immutable you can not change it. so you can not add(modify) your own user to the recieved data.

```<code>request.data['user'] = user
</code>```

rather you can pass context to your serializer with

```<code>storyboard = StoryboardSerializer(data=request.data, context = {'request':request})
</code>```

and save user in create serializer method or directly save user as -

```<code>storyboard.save(user=request.user.id)
</code>```

Body:
I am new to django,I have created the models with OnetoOne relationship , I have user table and i have onetoone relation with storyboard library table, the issue is when i am creating an storyboardlibraby object , i need to save the user objectin the onetoonefield , even after adding user object not able to save the storyboardlibrary to the database, if anybody can help on this please help me , i will add the code which I have written.

class StoryboardLibrary(models.Model):
   name = models.CharField(max_length=50)
   data = JSONField(db_index=True)
   user = models.OneToOneField(User, on_delete=models.CASCADE)

   def __str__(self):
       return "%s The Library" % self.name

Serializer class

class StoryboardSerializer(serializers.ModelSerializer):
class Meta:
    model = StoryboardLibrary
    fields = ('data','name','user')

views post method

def add_storyboard(request):
# validating for already existing data
if StoryboardLibrary.objects.filter(**request.data).exists():
    raise serializers.ValidationError('This data already exists')
user = get_object_or_404(User, id=request.user.id)
request.data['user'] = user
storyboard = StoryboardSerializer(data=request.data)
print(storyboard)
if storyboard.is_valid():
    storyboard.save()
    return Response(storyboard.data, status=status.HTTP_201_CREATED)
else:
    return Response(status=status.HTTP_404_NOT_FOUND)

After hitting the post api i am not able to save the data storyboardserializer is not valid hence it is executing the else block and returning the status 404 not found

Body:
So,
here you are filtering with the requested user, so

get_object_or_404

is not required because if request comes, there is a user and an id.

also request.data is immutable you can not change it. so you can not add(modify) your own user to the recieved data.

request.data['user'] = user

rather you can pass context to your serializer with

storyboard = StoryboardSerializer(data=request.data, context = {'request':request})

and save user in create serializer method or directly save user as -

storyboard.save(user=request.user.id)


问:
How can you get the return value of a Windows thread?
I was just wondering if it is possible (and if so, how) to get the return value of a thread in C++ (Windows). I have several threads, and I use WaitForMultipleObjects(...) on them. This waits until a thread is done, and returns the index of said thread, and all is well. However, I want to be able to obtain the return value of the thread that finished using its handle.

For example:

```<code>DWORD WINAPI Thread1(void *parameter){
    ...
    if(...) return 0;
    else return -1;
}

DWORD WINAPI Thread2(void *parameter){
    ...
    if(...) return 1;
    else return 0;
}

int main(){
    HANDLE t1 = CreateThread(0, 0, Thread1, NULL, 0, 0);
    HANDLE t2 = CreateThread(0, 0, Thread2, NULL, 0, 0);
    HANDLE *threads = new HANDLE[2];
    threads[0] = t1;
    threads[1] = t2;
    int result = WaitForMultipleObjects(2, threads, false, INFINITE);
    if(result == 0){
        //get the threads value here:
        int retVal = SomeFunction(t1); //What is SomeFunction?
    }
    ...
}
</code>```

I have tried to use GetExitCodeThread(thread) but I'm assuming this returns a system exit code, as it always gives me a very strange integer. Does anyone know a way, or a workaround?

答:
The problem with most programmer is that they don't pay attention to compiler warnings. At level 4 (/W4), the compiler produces following warning when returning -1 from a function that is returning DWORD:

warning C4245: 'return' : conversion from 'int' to 'DWORD', signed/unsigned mismatch

Body:
I was just wondering if it is possible (and if so, how) to get the return value of a thread in C++ (Windows). I have several threads, and I use WaitForMultipleObjects(...) on them. This waits until a thread is done, and returns the index of said thread, and all is well. However, I want to be able to obtain the return value of the thread that finished using its handle.

For example:

DWORD WINAPI Thread1(void *parameter){
    ...
    if(...) return 0;
    else return -1;
}

DWORD WINAPI Thread2(void *parameter){
    ...
    if(...) return 1;
    else return 0;
}

int main(){
    HANDLE t1 = CreateThread(0, 0, Thread1, NULL, 0, 0);
    HANDLE t2 = CreateThread(0, 0, Thread2, NULL, 0, 0);
    HANDLE *threads = new HANDLE[2];
    threads[0] = t1;
    threads[1] = t2;
    int result = WaitForMultipleObjects(2, threads, false, INFINITE);
    if(result == 0){
        //get the threads value here:
        int retVal = SomeFunction(t1); //What is SomeFunction?
    }
    ...
}

I have tried to use GetExitCodeThread(thread) but I'm assuming this returns a system exit code, as it always gives me a very strange integer. Does anyone know a way, or a workaround?