问:
Filter an array of object, if X cannot find looking for Y
I have an array of object and I want to make a filter when a language does not exist use an another one.
For example when I'm searching for the langauge de and it is not exist I want to search in this case to language en

```<code>const arrObj = [
  {id: 0, name: 'Zero', lang: 'hu', video: 'Clip'},
  {id: 1, name: 'One', lang: 'en', video: 'Clip'},
  {id: 2, name: 'Two', lang: 'en', video: 'Clip'},
  {id: 3, name: 'Three', lang: 'en', video: 'Trailer'},
  {id: 4, name: 'Four', lang: 'hu', video: 'Clip'},
  {id: 5, name: 'Five', lang: 'en', video: 'Trailer'},
  {id: 6, name: 'Six', lang: 'hu', video: 'Trailer'},
  {id: 7, name: 'Seven', lang: 'hu', video: 'Clip'},
]
</code>```
```<code>const language = 'de'
</code>```
```<code>const item = arrObj.filter(e => {
  if (e.lang === language && e.video === 'Trailer') {
    return e.video === 'Trailer'
  }
})
</code>```

I've tried with find function and with different if else statement as well. I'm really stuck with this now.
Any help would be appreciated

答:
This will search using all given keywords until one of them returns some result. If no result is found, returns empty array;

let searchTerms = ["de", "be", "en"]

const arrObj = [{
        id: 0,
        name: 'Zero',
        lang: 'hu',
        video: 'Clip'
    },
    {
        id: 1,
        name: 'One',
        lang: 'en',
        video: 'Clip'
    },
    {
        id: 2,
        name: 'Two',
        lang: 'en',
        video: 'Clip'
    },
    {
        id: 3,
        name: 'Three',
        lang: 'en',
        video: 'Trailer'
    },
    {
        id: 4,
        name: 'Four',
        lang: 'hu',
        video: 'Clip'
    },
    {
        id: 5,
        name: 'Five',
        lang: 'en',
        video: 'Trailer'
    },
    {
        id: 6,
        name: 'Six',
        lang: 'hu',
        video: 'Trailer'
    },
    {
        id: 7,
        name: 'Seven',
        lang: 'hu',
        video: 'Clip'
    },
];

let search = (data, keywords) => {
    let filteredData = [];
    for (let j = 0; j < keywords.length; j++) {

        filteredData = data.filter(x => x.lang === keywords[j])
        if (filteredData.length != 0) {
            return filteredData;
        }

    }
    return filteredData;

}

console.log(search(arrObj, searchTerms))```

Body:
I have an array of object and I want to make a filter when a language does not exist use an another one.
For example when I'm searching for the langauge de and it is not exist I want to search in this case to language en

const arrObj = [
  {id: 0, name: 'Zero', lang: 'hu', video: 'Clip'},
  {id: 1, name: 'One', lang: 'en', video: 'Clip'},
  {id: 2, name: 'Two', lang: 'en', video: 'Clip'},
  {id: 3, name: 'Three', lang: 'en', video: 'Trailer'},
  {id: 4, name: 'Four', lang: 'hu', video: 'Clip'},
  {id: 5, name: 'Five', lang: 'en', video: 'Trailer'},
  {id: 6, name: 'Six', lang: 'hu', video: 'Trailer'},
  {id: 7, name: 'Seven', lang: 'hu', video: 'Clip'},
]

const language = 'de'

const item = arrObj.filter(e => {
  if (e.lang === language && e.video === 'Trailer') {
    return e.video === 'Trailer'
  }
})

I've tried with find function and with different if else statement as well. I'm really stuck with this now.
Any help would be appreciated


来源: stackexchange

问:
How to adjust Bulma Column height when one changes?
is it possible to make a column adjust its height when others change?
I have all columns at the same height using flex but when I change one of them dynamically, the others stay the same...
Any way to fix that?

Thanks!!

答:
If your flex direction is row than you can use align-items: stretch

.fparent {
  display: flex;
  align-items: stretch;
  justify-content: flex-start
}

.fparent>div {
  background: yellow;
  flex: 1;
  border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fparent">
  <div>Some content in first div Some content in first divSome content in first divSome content in first divSome content in first divSome content in first divSome content in first div
  </div>
  <div></div>
  <div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
If your flex direction is row than you can use align-items: stretch

.fparent {
  display: flex;
  align-items: stretch;
  justify-content: flex-start
}

.fparent>div {
  background: yellow;
  flex: 1;
  border: 1px solid black;
}

<div class="fparent">
  <div>Some content in first div Some content in first divSome content in first divSome content in first divSome content in first divSome content in first divSome content in first div
  </div>
  <div></div>
  <div>
  </div>
</div>


问:
Using the object URL pdf files are not downloading from aws s3 when using chrome. I get "Failed -Forbidden error. works in Firefox and Edge
When using the Object Url for a file stored in AWS S3, the pdf files are not downloading from aws s3 when using chrome. I get "Failed -Forbidden error. works in Firefox and Edge</p>

答:
This has to do with read/write permissions, you will need to check the S3 bucket permissions and ACL (Access control lists) modify them so you can "List" and "Read" but not "Write".

This should resolve your issue.


问:
Hugo change layout
I have a following structure in my Hugo & Doks project:

```<code> - content
   - docs
      - working.md
      - working-as-well.md
   - get-started2
      - working.md
      ...
   - get-started.md
...
  - layouts
    - get-started2
      - single.html
    - get-started.html
</code>```

Content placed in docs and get-started2 has customized layout and works as expected. Great!

However, I have huge pain to set-up custom layout for get-started.md. I cannot do it like with get-started2 - place it into a folder. Client requests to have get started URL as:

www.SomeProject.com/get-started

so it must not be placed in folder (like get-started2)

www.SomeProject.com/get-started2/working

Do you have any hints please?

答:
You have at least three options:

Use front matter to set the "type":

In content/get-started.md set type: mytype in front matter.

The layout will be located at (for example) layout/mytype/single.html.

Use front matter to set the "layout":

In content/get-started.md set layout: mylayout in front matter.

The layout will be located at (for example) layout/_default/mylayout.html

Or use a subdirectory, but make it the section index:

The file is located at content/get-started/_index.md

The layout will be located at (for example) layout/get-started/list.html

Notice that the template name has changed from "single" to "list", but you can still write your layout in exactly the same way.

I use "(for example)" because Hugo has an enormous list of directories/filenames it searches through to find its templates, and if an earlier matching template is found, the custom layout gets ignored.

Title: Hugo change layout

Body:
I have a following structure in my Hugo & Doks project:

 - content
   - docs
      - working.md
      - working-as-well.md
   - get-started2
      - working.md
      ...
   - get-started.md
...
  - layouts
    - get-started2
      - single.html
    - get-started.html

Content placed in docs and get-started2 has customized layout and works as expected. Great!

However, I have huge pain to set-up custom layout for get-started.md. I cannot do it like with get-started2 - place it into a folder. Client requests to have get started URL as:

www.SomeProject.com/get-started

so it must not be placed in folder (like get-started2)

www.SomeProject.com/get-started2/working

Do you have any hints please?


问:
Is UIView's opaque property with a value of YES in conflict with its backgroundColor property with a value of [UIColor clearColor]?
such as the code:

```<code>view.opaque = YES;
</code>```

and

```<code>view.backgroundColor = [UIColor clearColor];
</code>```

any one who can explain something about this?

EDIT:

as the document shows:

Declare Views as Opaque Whenever Possible

UIKit uses the opaque property of each view to determine whether the view can optimize compositing operations. Setting the value of this property to YES for a custom view tells UIKit that it does not need to render any content behind your view. Less rendering can lead to increased performance for your drawing code and is generally encouraged. Of course, if you set the opaque property to YES, your view must fills its bounds rectangle completely with fully opaque content.

opaque property is used for determining whether the view can optimize compositing operations.

so the question is:

if i set view.opaque = YES and view.backgroundColor = [UIColor clearColor]，the former increased performance，how about the latter?

答: No, it shouldn't be. It should act clear. The color clear is completely opaque, if that even makes sense. It won't show up black or white or anything else if you change its alpha. It will be clear.</p>

ContentLicense: CC BY-SA 3.0

Body:
such as the code:

view.opaque = YES;

and

view.backgroundColor = [UIColor clearColor];

any one who can explain something about this?

EDIT:

as the document shows:

Declare Views as Opaque Whenever Possible

UIKit uses the opaque property of each view to determine whether the view can optimize compositing operations. Setting the value of this property to YES for a custom view tells UIKit that it does not need to render any content behind your view. Less rendering can lead to increased performance for your drawing code and is generally encouraged. Of course, if you set the opaque property to YES, your view must fills its bounds rectangle completely with fully opaque content.

opaque property is used for determining whether the view can optimize compositing operations.

so the question is:

if i set view.opaque = YES and view.backgroundColor = [UIColor clearColor]，the former increased performance，how about the latter?


答:
As comments @Evanss

Also height auto doens't make the SVG appear, but height 100% does.

width="22" height="100%"

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="22" height="100%"  aria-hidden="true" focusable="false" role="img" style="border:1px solid red">

  <path fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z">
  </path>
  </svg>```
</div>
</div>
</p>
<p>The snippet above doesn't render the image correctly, but if you save the svg as a separate file and open it in a browser, you'll see exactly the same image.</p>
<p>In the image below, the red rectangle is the border of the svg canvas with <code>width="22"</code> and <code>height="100%"</code></p>
<p><img src="https://i.stack.imgur.com/mQNlk.png" alt="enter image description here" /></p>
<p>As you can see, with this SVG configuration, paddings  are too large. What is unacceptable and will interfere with layout</p>
<blockquote>
<p>Using JavaScript isnt idea as it may cause the page to flicker</p>
</blockquote>
<p>Using the JavaScript method <em><strong>getBBox()</strong></em>  in the snippet console allows you to find out the physical dimensions of the svg shape
In this case, JS is not involved in the SVG rendering process and is only a reference tool.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 32 448 512" width="22" height="100%" aria-hidden="true" focusable="false" role="img" style="border:1px solid red">
  <path id="path" fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z">
  </path>
 </svg>
 <script>
   console.log(path.getBBox())
 </script></code>```

In the console, we can see the physical dimensions (dimensions that are given by the path of the svg shape)

```<code>  "x": 0,
  "y": 31.999996185302734,
  "width": 448,
  "height": 448
</code>```

To move the image to the top left corner (this is the svgs  origin) we set the value viewBox="0 32 448 448"` And to reduce the margin margins we set fixed values width="22" height="22"

Recommendations for creating and using icons

Setting both dimensions would be very time consuming as I have a lot
of icons with the same issue.

If you are using some unique icons created by a designer, then you cannot avoid the manual positioning and scaling process for each icon described above.

There is no universal solution for this case. It all depends on how the icon was drawn.

If the icon is simple, standard, then it is better to use icons drawn by professionals. There are many such resources on the web.

In this case, manual, additional processing is not required.

You can use google-fonts character font

Icons by name can be selected here

The name of your icon - Close `Fullscreen

Below is an example with minimal layout

span {
  margin-left: 0.5em;
  margin-top:0.5em;
  transition: transform 1s ease-in-out;
}
span:hover {
  transform: scale(2);
  color:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<span class="material-icons"> close_fullscreen </span></code>```

Title: SVG invisible on Safari without height attribute, but issue not recreatable?

Body:
I have an SVG in my website which displays fine on Chrome but isn't visible on Safari and Mobile Safari.

Weirdly, if I copy and paste the SVG into a Codepen page then it works fine, so I'm not able to recreate the issue publicly.

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="22" aria-hidden="true" focusable="false" role="img"><path fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z"></path></svg>

Setting height 100% as an attribute fixes the issue in Safari and doesn't make it the wrong size or aspect ratio.

What is going on here? Why does this work and is a safe fix? And also why is the issue not reproducible?

UPDATE: Ive now been able to recreate. Safari hides the SVG when it has a parent div with display: flex:

https://codepen.io/adsfdsfhdsafkhdsafjkdhafskjds/pen/yLPgaJx

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="22" aria-hidden="true" focusable="false" role="img"><path fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z"></path></svg>

If I set the container div to display: block or set a height on the SVG then it comes back.

Body:
As comments @Evanss

Also height auto doens't make the SVG appear, but height 100% does.

width="22" height="100%"

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="22" height="100%"  aria-hidden="true" focusable="false" role="img" style="border:1px solid red">

  <path fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z">
  </path>
  </svg>

The snippet above doesn't render the image correctly, but if you save the svg as a separate file and open it in a browser, you'll see exactly the same image.

In the image below, the red rectangle is the border of the svg canvas with width="22" and height="100%"

As you can see, with this SVG configuration, paddings  are too large. What is unacceptable and will interfere with layout

Using JavaScript isnt idea as it may cause the page to flicker

Using the JavaScript method getBBox()  in the snippet console allows you to find out the physical dimensions of the svg shape
In this case, JS is not involved in the SVG rendering process and is only a reference tool.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 32 448 512" width="22" height="100%" aria-hidden="true" focusable="false" role="img" style="border:1px solid red">
  <path id="path" fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z">
  </path>
 </svg>
 <script>
   console.log(path.getBBox())
 </script>

In the console, we can see the physical dimensions (dimensions that are given by the path of the svg shape)

  "x": 0,
  "y": 31.999996185302734,
  "width": 448,
  "height": 448

To move the image to the top left corner (this is the svgs  origin) we set the value viewBox="0 32 448 448"` And to reduce the margin margins we set fixed values width="22" height="22"

Recommendations for creating and using icons

Setting both dimensions would be very time consuming as I have a lot
of icons with the same issue.

If you are using some unique icons created by a designer, then you cannot avoid the manual positioning and scaling process for each icon described above.

There is no universal solution for this case. It all depends on how the icon was drawn.

If the icon is simple, standard, then it is better to use icons drawn by professionals. There are many such resources on the web.

In this case, manual, additional processing is not required.

You can use google-fonts character font

Icons by name can be selected here

The name of your icon - Close `Fullscreen

Below is an example with minimal layout

span {
  margin-left: 0.5em;
  margin-top:0.5em;
  transition: transform 1s ease-in-out;
}
span:hover {
  transform: scale(2);
  color:red;
}

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<span class="material-icons"> close_fullscreen </span>


问:
When I click on the button, the value of that button needs to add up to sum
I was trying to code a POS like system as a small project to learn with.
So currently I have two buttons "cola" and "fanta". The prices of those drinks are in an object.
As soon as I click on one button the price needs to be added to sum.
Well what the code is currently doing is to add up the prices of the same product.
So if I click three times in a row on "cola", which has a price of 3, I get 9 as sum. So far so good, but as soon as I click fanta, which has a price of 2, I get a sum of 2. But when I continue with the cola button it continues at 12 and so on.

Here is the code:

```<code>  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  for (let i = 0; i < btnChoose.length; i++) {
    let sum = null;
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }
</code>```

and here is the HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>POS</title>
  </head>

  <body>
    <button class="btn" id="cola">Cola</button>
    <button class="btn" id="fanta">Fanta</button>
    <script>
     ....
    </script>
  </body>
</html>
</code>```

答:
Your let sum=null statement creates a separate locally scoped variable each pass through the for loop. Simply move the statement outside the for loop to then have only one sum variable.

```<code>  let sum=null;
  for (let i = 0; i < btnChoose.length; i++) {
</code>```

fiddle here: https://jsfiddle.net/cLrao8fu/

Body:
I was trying to code a POS like system as a small project to learn with.
So currently I have two buttons "cola" and "fanta". The prices of those drinks are in an object.
As soon as I click on one button the price needs to be added to sum.
Well what the code is currently doing is to add up the prices of the same product.
So if I click three times in a row on "cola", which has a price of 3, I get 9 as sum. So far so good, but as soon as I click fanta, which has a price of 2, I get a sum of 2. But when I continue with the cola button it continues at 12 and so on.

Here is the code:

  const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  for (let i = 0; i < btnChoose.length; i++) {
    let sum = null;
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }

and here is the HTML:

<!DOCTYPE html>

    <title>POS</title>

    <button class="btn" id="cola">Cola</button>
    <button class="btn" id="fanta">Fanta</button>

Body:
Your let sum=null statement creates a separate locally scoped variable each pass through the for loop. Simply move the statement outside the for loop to then have only one sum variable.

  let sum=null;
  for (let i = 0; i < btnChoose.length; i++) {

fiddle here: https://jsfiddle.net/cLrao8fu/


问:
How to display only an organization name only?
I'm trying to console log an organisation name but get undefined abut when I console log the object I'm able to get the org name and the id. For example;

When I run this, I get the result display in the console log:

```<code>const existingOrganisationID = await Organisation.findOne({ _id: { "$eq": organisationid } })
console.log(existingOrganisationID)

{
  _id: new ObjectId("61fd46ad360f1a287ac6cc65"),
  organisationName: 'OneExample Pte Ltd',
   __v: 0
}
</code>```

But when I run this, I get undefined.

```<code>console.log(existingOrganisationID.organisationName)

undefined
</code>```

Here is the full code for a get API:

```<code>router.get('/api/organisation/:id', async (req, res) => {
      let organisationid = req.params.id
      const existingOrganisationID = await Organisation.findOne({ _id: { "$eq": organisationid } })
      console.log(existingOrganisationID)
      console.log(existingOrganisationID.organisationName)
})
</code>```

Where did I go wrong? thanks

答:
You are not executing the query. Try this:

```<code>router.get('/api/organisation/:id', async (req, res) => {
      let organisationid = req.params.id
      const existingOrganisationID = await Organisation.findOne({ _id: { "$eq": organisationid } }).exec();
      console.log(existingOrganisationID)
      console.log(existingOrganisationID.organisationName)
})
</code>```

You can check this for more details.

Body:
I'm trying to console log an organisation name but get undefined abut when I console log the object I'm able to get the org name and the id. For example;

When I run this, I get the result display in the console log:

const existingOrganisationID = await Organisation.findOne({ _id: { "$eq": organisationid } })
console.log(existingOrganisationID)

{
  _id: new ObjectId("61fd46ad360f1a287ac6cc65"),
  organisationName: 'OneExample Pte Ltd',
   __v: 0
}

But when I run this, I get undefined.

console.log(existingOrganisationID.organisationName)

undefined

Here is the full code for a get API:

router.get('/api/organisation/:id', async (req, res) => {
      let organisationid = req.params.id
      const existingOrganisationID = await Organisation.findOne({ _id: { "$eq": organisationid } })
      console.log(existingOrganisationID)
      console.log(existingOrganisationID.organisationName)
})

Where did I go wrong? thanks

Body:
You are not executing the query. Try this:

router.get('/api/organisation/:id', async (req, res) => {
      let organisationid = req.params.id
      const existingOrganisationID = await Organisation.findOne({ _id: { "$eq": organisationid } }).exec();
      console.log(existingOrganisationID)
      console.log(existingOrganisationID.organisationName)
})

You can check this for more details.


问:
django copy selected data from one table to another table
Can anybody help me. I want to know if there is a good solution to moving a large amount of data filtered from one table in an oracle db to another in a mysql db.
I know that you can run a query and loop over the results of it and insert it to the other database but the problem is that it may run out of memory and i'm looking for a good solution like running jobs or some asynchronous tasks.</p>

答:
You are looking for an ETL system (maybe without the T in your case)

Time ago I use pygrametl and it managed the data surprisingly fast.

Another option is django bulk create (don't try to insert all data at once, split data into chunks)


答:
Sum is product wise because you have declared the variable sum inside the loop. If you move it outside of the loop like below you should get a sum which incorporates sum of all product values.</p>
```<code>let sum = 0;
for (let i = 0; i < btnChoose.length; i++) {
    let price = 0;
    btnChoose[i].addEventListener("click", function () {
      price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }
</code>```

Title: When I click on the button, the value of that button needs to add up to sum

Body:
Sum is product wise because you have declared the variable sum inside the loop. If you move it outside of the loop like below you should get a sum which incorporates sum of all product values.

let sum = 0;
for (let i = 0; i < btnChoose.length; i++) {
    let price = 0;
    btnChoose[i].addEventListener("click", function () {
      price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }


问:
Update timestamps every 30 seconds using setInterval()
I have a list of posts like so:

```<code><ul>
    <li>
       <p class="post" id="432">This is a post</p>
       <p class="timestamp">5 minutes ago</p>
    </li>
    <li>
       <p class="post" id="589">This is another post on the site</p>
       <p class="timestamp">1 hour ago</p>
    </li>
</ul>
</code>```

I want to update the timestamp every 30 seconds (much like facebook timestamps) using setInterval().

```<code>function update_timestamps(){

    $('.timestamp').ajax({
        type    : 'POST',
        url     : '/ajax/refresh_timestamp',
        data    : { 'post_id' : $(this).closest('li').find('p.post').attr('id') },
        success : function(data){
            $(this).html(data);
        }
    });

}

setInterval(update_timestamps(), 30000);
</code>```

Obviously something is wrong with my .ajax() function, or maybe I shouldn't use ajax() at all?

答:
This isn't really an answer to your question but... an alternative, that would mean you could avoid the ajax calls all together, would be to add the timestamp to the attribute, something like:

```<code><ul>
  <li>
    <p class="post" id="432">This is a post</p>
    <p class="timestamp" data-timestamp="1313649170147">5 minutes ago</p>
  </li>
  <li>
    <p class="post" id="589">This is another post on the site</p>
    <p class="timestamp" data-timestamp="1313649189299">1 hour ago</p>
  </li>
</ul>
</code>```

Then you would process your timestamps client side:

```<code>function updateDateTimestamps() {
  $('.timestamp').each(function(i, t) {
    var $t = $(t);
    $t.text(prettyDate($t.data('timestamp')));
  });
}
</code>```

For an implementation of prettyDate see http://ejohn.org/blog/javascript-pretty-date/

Then pass updateDateTimestamps to setInterval:

```<code>setInterval(updateDateTimestamps, 30000);
</code>```

Body:
I have a list of posts like so:

This is a post

5 minutes ago

This is another post on the site

1 hour ago

I want to update the timestamp every 30 seconds (much like facebook timestamps) using setInterval().

function update_timestamps(){

    $('.timestamp').ajax({
        type    : 'POST',
        url     : '/ajax/refresh_timestamp',
        data    : { 'post_id' : $(this).closest('li').find('p.post').attr('id') },
        success : function(data){
            $(this).html(data);
        }
    });

}

setInterval(update_timestamps(), 30000);

Obviously something is wrong with my .ajax() function, or maybe I shouldn't use ajax() at all?

Body:
This isn't really an answer to your question but... an alternative, that would mean you could avoid the ajax calls all together, would be to add the timestamp to the attribute, something like:

<ul>
  <li>
    <p class="post" id="432">This is a post</p>
    <p class="timestamp" data-timestamp="1313649170147">5 minutes ago</p>
  </li>
  <li>
    <p class="post" id="589">This is another post on the site</p>
    <p class="timestamp" data-timestamp="1313649189299">1 hour ago</p>
  </li>
</ul>

Then you would process your timestamps client side:

function updateDateTimestamps() {
  $('.timestamp').each(function(i, t) {
    var $t = $(t);
    $t.text(prettyDate($t.data('timestamp')));
  });
}

For an implementation of prettyDate see http://ejohn.org/blog/javascript-pretty-date/

Then pass updateDateTimestamps to setInterval:

setInterval(updateDateTimestamps, 30000);


问:
Why, in Ansible, I can't have same key in many children groups?
I want to make some clean stuff with my ansible hosts file.

If i use ansible-playbook --limit calendar -i hosts update_common.yml

Ansible execute my playbook on all hosts, even on hostname in other groups.

Apparently, it seems to comme from my keys dev and prod :

all:
  children:
    gitlab:
      children:
        dev:
          hosts:
            gitlab-dev:  # Stretch
        prod:
          hosts:
            gitlab-A:   # Stretch
            gitlab-B:   # Stretch
            gitlab-C.mysociety.fr:
              ansible_port: 22
    intranet:
      children:
        dev:
          hosts:
            intra-dev:      # Buster
            wordpress-dev:  # Buster
        prod:
          hosts:
            intra-prod:     # Buster
    calendar:
      children:
        dev:
          hosts:
            calendar-dev:
        prod:
          hosts:
            calendar:
```

答:
Yes when I make ansible-inventory -i hosts --list

We can see how it is managed, dev hosts are grouped together, same for prod :(

    "all": {
        "children": [
            "calendar",
            "gitlab",
            "intranet",
            "ungrouped"
        ]
    },
    "dev": {
        "hosts": [
            "calendar-dev",
            "gitlab-test",
            "intra-dev",
            "wordpress-dev"
        ]
    },
    "fil-calendar": {
        "children": [
            "dev",
            "prod"
        ]
    },
    "gitlab": {
        "children": [
            "dev",
            "prod"
        ]
    },
    "intranet": {
        "children": [
            "dev",
            "prod"
        ]
    },
    "prod": {
        "hosts": [
            "calendar",
            "gitlab-A",
            "gitlab-B",
            "gitlab-C.mysociety.fr",
            "intra-prod"
        ]
    }
```


问:
Antd: How to change tooltip label on table sorter
I'm new using Antd, I've create a table with sort functionalities, but I need to change the text on the tooltip of the sorter.

Sorter tooltip:-

Thanks in advance, if you need any extra code snippet just please let me know.

答:
Based on this issue in github you can set locale property of Table to what you want

```

Body:
Based on this issue in github you can set locale property of Table to what you want

<Table
      locale={{
          triggerDesc: 'descend sort text',
          triggerAsc: 'ascend sort text',
          cancelSort: 'cancel sort text'
      }}
   />


问:
Joda DateTime disregard/remove milis in comparing for equality
Is there an easier way to remove the millis part of joda DateTime?

Example: 2022-02-08T07:13:00.010Z -> 2022-02-08T07:13:00.000Z

I want to compare two datetimes.. but disregard the millis since the date/time I want to compare have zero millis.

One way I think is to format the date into string and parse it.. but since this will be run via schedule job every minute.. it will be better if there is an easier/lighter way to do this.

Is there an easier/lighter solution to disregard the millis when comparing 2 joda DateTime?

This is how I did it but I think there are better solutions (easier/lighter):

```<code>    DateTime now = new DateTime();
    DateTime noMillis = new DateTime(
            now.getYear(),
            now.getMonthOfYear(),
            now.getDayOfMonth(),
            now.getHourOfDay(),
            now.getMinuteOfHour(),
            now.getSecondOfMinute());
</code>```

Aside from this, I think it is also possible to use string formatter to convert DateTime to string and remove the millis.. then convert it back to DateTime (from String).

答:
You can use .withMillisOfSecond(0) - to remove millis from DateTime.
Also, other options for comparing DateTime and ignoring millis are possible.

Here are some examples:

DateTime t1 = DateTime.parse("2022-02-08T07:13:00.010Z");
DateTime t2 = DateTime.parse("2022-02-08T07:13:00.000Z");

// Option 1: set millis to 0
assertTrue(t1.withMillisOfSecond(0).equals(t2)); // Pass

// Option 2: remove millis from date
assertTrue(t1.minusMillis(t1.getMillisOfSecond()).equals(t2)); // Pass

// Option 3: compare that diff of millis less than 1000
// (If you want a check that t1 and t2 differentiate only in milliseconds)
assertTrue(t1.getMillis() - t2.getMillis() < 1000); // Pass

```

Body:
Is there an easier way to remove the millis part of joda DateTime?

Example: 2022-02-08T07:13:00.010Z -> 2022-02-08T07:13:00.000Z

I want to compare two datetimes.. but disregard the millis since the date/time I want to compare have zero millis.

One way I think is to format the date into string and parse it.. but since this will be run via schedule job every minute.. it will be better if there is an easier/lighter way to do this.

Is there an easier/lighter solution to disregard the millis when comparing 2 joda DateTime?

This is how I did it but I think there are better solutions (easier/lighter):

    DateTime now = new DateTime();
    DateTime noMillis = new DateTime(
            now.getYear(),
            now.getMonthOfYear(),
            now.getDayOfMonth(),
            now.getHourOfDay(),
            now.getMinuteOfHour(),
            now.getSecondOfMinute());

Aside from this, I think it is also possible to use string formatter to convert DateTime to string and remove the millis.. then convert it back to DateTime (from String).


问:
The behavior when putting Row into ConstrainedBox with Flutter is strange
When I put a Row in the ConstrainedBox with Flutter, the display is out of the way.
Is this a Flutter bug?

//Does not Stick out Pattern

```<code>ConstrainedBox(
  constraints: BoxConstraints(
  maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
  child: Container(
    decoration: const BoxDecoration(color: Colors.red),
    width: 300,
    height: 100,
)),
</code>```

//Stick out Pattern

```<code>ConstrainedBox(
  constraints: BoxConstraints(
  maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
  child: Row(
    children: [
      Container(
        decoration: const BoxDecoration(color: Colors.green),
        width: 300,
        height: 100,
      )
    ])),
</code>```

image

答:
Adding an Expanded with a Center Widget remove the overflow

```<code>ConstrainedBox(
          constraints:
              BoxConstraints(maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
          child: Row(children: [
            Expanded(
                child: Center(
                    child: Container(
              decoration: const BoxDecoration(color: Colors.green),
              width: 300,
              height: 100,
            )))
          ]))
</code>```

Body:
When I put a Row in the ConstrainedBox with Flutter, the display is out of the way.
Is this a Flutter bug?

//Does not Stick out Pattern

ConstrainedBox(
  constraints: BoxConstraints(
  maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
  child: Container(
    decoration: const BoxDecoration(color: Colors.red),
    width: 300,
    height: 100,
)),

//Stick out Pattern

ConstrainedBox(
  constraints: BoxConstraints(
  maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
  child: Row(
    children: [
      Container(
        decoration: const BoxDecoration(color: Colors.green),
        width: 300,
        height: 100,
      )
    ])),

image

Body:
Adding an Expanded with a Center Widget remove the overflow

ConstrainedBox(
          constraints:
              BoxConstraints(maxWidth: ScreenUtil.getFullWidth(context) * 0.8),
          child: Row(children: [
            Expanded(
                child: Center(
                    child: Container(
              decoration: const BoxDecoration(color: Colors.green),
              width: 300,
              height: 100,
            )))
          ]))


答:
You can try using the logical or operator. Right side of the operator will only be evaluated when there is no trailer in de since find returns undefined (which is falsy) when there's no match:

const arrObj = [
  {id: 0, name: 'Zero', lang: 'hu', video: 'Clip'},
  {id: 1, name: 'One', lang: 'en', video: 'Clip'},
  {id: 2, name: 'Two', lang: 'en', video: 'Clip'},
  {id: 3, name: 'Three', lang: 'en', video: 'Trailer'},
  {id: 4, name: 'Four', lang: 'hu', video: 'Clip'},
  {id: 5, name: 'Five', lang: 'en', video: 'Trailer'},
  {id: 6, name: 'Six', lang: 'hu', video: 'Trailer'},
  {id: 7, name: 'Seven', lang: 'hu', video: 'Clip'},
]
const language = 'de';

const item = arrObj.find(e => e.video == 'Trailer' && e.lang === language)
                || arrObj.find(e => e.video == 'Trailer' && e.lang ===  'en');

console.log(item);```

Title: Filter an array of object, if X cannot find looking for Y

Body:
I have an array of object and I want to make a filter when a language does not exist use an another one.
For example when I'm searching for the langauge de and it is not exist I want to search in this case to language en

const arrObj = [
  {id: 0, name: 'Zero', lang: 'hu', video: 'Clip'},
  {id: 1, name: 'One', lang: 'en', video: 'Clip'},
  {id: 2, name: 'Two', lang: 'en', video: 'Clip'},
  {id: 3, name: 'Three', lang: 'en', video: 'Trailer'},
  {id: 4, name: 'Four', lang: 'hu', video: 'Clip'},
  {id: 5, name: 'Five', lang: 'en', video: 'Trailer'},
  {id: 6, name: 'Six', lang: 'hu', video: 'Trailer'},
  {id: 7, name: 'Seven', lang: 'hu', video: 'Clip'},
]

const language = 'de'

const item = arrObj.filter(e => {
  if (e.lang === language && e.video === 'Trailer') {
    return e.video === 'Trailer'
  }
})

I've tried with find function and with different if else statement as well. I'm really stuck with this now.
Any help would be appreciated


答:
its because you are defining sum in the loop
define it outside of the loop:</p>
```<code>const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  let sum = null;

  for (let i = 0; i < btnChoose.length; i++) {
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }
</code>```

Body:
its because you are defining sum in the loop
define it outside of the loop:

const btnChoose = document.querySelectorAll(".btn");

  const drinks= {
    cola: 4,
    fanta: 3,
  };

  let sum = null;

  for (let i = 0; i < btnChoose.length; i++) {
    btnChoose[i].addEventListener("click", function () {
      let price = drinks[this.id];
      sum += price;
      console.log(typeof sum, sum);
    });
  }


问:
What's the fastest barcode reader from PDF in c#
for an application i'm developing, I need a barcode reader. I currently use inlite barcode reader (http://how-to.inliteresearch.com/barcode-reading-howto/) but I would like to know if there is not a faster SDK. because this sdk scan the whole pdf page to find the codes (39 and 128 in my case) and it takes up to 4 hours for a 17238 pdf page.

I know IText7 has a barcode reader too but which one is faster? or if there is another sdk faster, I would like to know.

Thanks in advance :-)

答:
iText normally is pretty slow, when it comes to big pdfs. I know only commercial solutions, which are fast.
I measured e.g. for a 10.000 pages document, with a lot of content and 117MB in size a barcode detection on all pages in around 334 seconds with the CIB pdf toolbox (https://pdftoolbox.cib.de/). It searched for all barcode types supported. The speed could be improved further, if you specify a region on the pages (e.g. the left border) to search for or to limit the barcode types.
The library is in C++, but has C# bindings.

Internally it utilizes the zxing-cpp barcode reader, which is pretty fast.
https://github.com/nu-book/zxing-cpp


问:
How do I find missing dates in a list of sorted dates?
In Python how do I find all the missing days in a sorted list of dates?</p>

答:
Here's an example for a pandas dataframe with a date column. If it's an index, then change df.Date to df.index.</p>
```<code>import pandas as pd

df.Date = pd.to_datetime(df.Date) # ensure datetime format of date column
min_dt = df.Date.min() # get lowest date
max_dt = df.Date.max() # get highest date

dt_range = pd.date_range(min_dt, max_dt) # get all requisite dates in range
missing_dts = [d for d in dt_range if d not in df.Date] # list missing
print("There are {n} missing dates".format(n=len(missing_dts)))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here's an example for a pandas dataframe with a date column. If it's an index, then change df.Date to df.index.

import pandas as pd

df.Date = pd.to_datetime(df.Date) # ensure datetime format of date column
min_dt = df.Date.min() # get lowest date
max_dt = df.Date.max() # get highest date

dt_range = pd.date_range(min_dt, max_dt) # get all requisite dates in range
missing_dts = [d for d in dt_range if d not in df.Date] # list missing
print("There are {n} missing dates".format(n=len(missing_dts)))


问:
"User not found" for Graph API request in the Azure enterprise app security group with client credentials auth flow
Design

Goal

Get calendar events for a given user.

Requirements

Application should have access to the MS Graph API.

Application should act like a daemon/background process and not depend on user's login.

Application should have access to the minimal number of users' data in the Azure Active Directory (AAD).

Application should be able to fetch user's calendar events and create them.

Implementation / Setup

to fulfill (1) Azure (Enterprise) App was created as described here.

to enable (2) client credentials flow was used with the setup of application permissions

to meet (3) a security group - as described here - was created with a limited number of users with the related policy that included related permissions (see here). The group was later connected to the app following this instruction.

to implement (4) the Calendar.Read and Calendar.ReadWrite as required by the actions here and here were added to the policy mentioned in the previous setup step.

Testing

Two HTTP requests were used: one to get the token and another to read events.

token request from the Identity Platform

curl --location --request POST 'https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/token' \
--data-raw 'client_id=<APPLICATION_TOKEN>&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=<APPLICATION_SECRET>&grant_type=client_credentials'
```
<p>Upon inspection of the token here I see that it contains required permissions:</p>
<pre class="lang-json prettyprint-override"><code>  "roles": [
    "Calendars.Read",
    "Calendars.ReadWrite"
  ]
</code>```

fetch request of the calendar events from Graph API

curl --location --request GET 'https://graph.microsoft.com/v1.0/users/<USER_ID>/calendar/events' \
--header 'Authorization: Bearer <TOKEN>'
```
<p>results in the following error:</p>
<pre class="lang-json prettyprint-override"><code>{
  "error": {
    "code": "ResourceNotFound",
    "message": "User not found",
    "innerError": {
      "date": "2022-02-08T08:25:39",
      "request-id": "bfaca1f9-e79b-491c-8d75-5a62317e299b",
      "client-request-id": "bfaca1f9-e79b-491c-8d75-5a62317e299b"
    }
  }
}
</code>```

The user id is from my account that I found in the Azure Active Directory details of the Azure Tenant. I double-checked that after adding other users.

Before-asking investigation

This issue looks closest to my case as it uses the client credentials auth flow. But it uses global permissions for all users in the AAD, while we use more fine-grained approach with a security group. It also shows a different error "Resource could not be discovered." versus "User not found" in my case.

答:
In order to call /{user-id}/calendar/events to work the user must have mailbox on Exchange Online if you are using client credentials for Daemon applications.

Also, It seems assigning license to a guest account (Personal account in this case) is not possible and hence the user account never gets access to the calendar service (part of o365 exchange online) due to which it cannot retrieve the calendar information of personal account.

Please refer my answer similar to this in Q&A for detailed description.

Body:
Design

Goal

Get calendar events for a given user.

Requirements

Application should have access to the MS Graph API.

Application should act like a daemon/background process and not depend on user's login.

Application should have access to the minimal number of users' data in the Azure Active Directory (AAD).

Application should be able to fetch user's calendar events and create them.

Implementation / Setup

to fulfill (1) Azure (Enterprise) App was created as described here.

to enable (2) client credentials flow was used with the setup of application permissions

to meet (3) a security group - as described here - was created with a limited number of users with the related policy that included related permissions (see here). The group was later connected to the app following this instruction.

to implement (4) the Calendar.Read and Calendar.ReadWrite as required by the actions here and here were added to the policy mentioned in the previous setup step.

Testing

Two HTTP requests were used: one to get the token and another to read events.

token request from the Identity Platform

curl --location --request POST 'https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/token' \
--data-raw 'client_id=<APPLICATION_TOKEN>&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=<APPLICATION_SECRET>&grant_type=client_credentials'

Upon inspection of the token here I see that it contains required permissions:

  "roles": [
    "Calendars.Read",
    "Calendars.ReadWrite"
  ]

fetch request of the calendar events from Graph API

curl --location --request GET 'https://graph.microsoft.com/v1.0/users/<USER_ID>/calendar/events' \
--header 'Authorization: Bearer <TOKEN>'

results in the following error:

{
  "error": {
    "code": "ResourceNotFound",
    "message": "User not found",
    "innerError": {
      "date": "2022-02-08T08:25:39",
      "request-id": "bfaca1f9-e79b-491c-8d75-5a62317e299b",
      "client-request-id": "bfaca1f9-e79b-491c-8d75-5a62317e299b"
    }
  }
}

The user id is from my account that I found in the Azure Active Directory details of the Azure Tenant. I double-checked that after adding other users.

Before-asking investigation

This issue looks closest to my case as it uses the client credentials auth flow. But it uses global permissions for all users in the AAD, while we use more fine-grained approach with a security group. It also shows a different error "Resource could not be discovered." versus "User not found" in my case.


问:
how to send api response array in code codeigniter?
I am creating api in codeigniter in which i am checking both email and mobilenumber field for updating & in that check it for both field. my single message is go to response but in both casess how can i send both email and mobile number is exists</p>
```<code>    if((isset($postData['email'])) && $postData['email']!="")
        {

                 $message["email_unique"]='Email already exists';
                 return $this->response(array("status" => "400", "message" =>$message), 400);

        }
        if((isset($postData['mobileNumber'])) && $postData['mobileNumber']!="")
        {
             $mobilenumber=$postData['mobileNumber'];

                 $message["mobilenumber_unique"]='Mobile Number already exists';
                 return $this->response(array("status" => "400", "message" =>$message), 400);

        }
</code>```

答:
Check this code

   "400",
          "message" =>$message
        ]);
        exit;
      } else {
        $message['success'] = "Successful";  // success messsage if needed
        $data = null;  // whatever data you need to pass in success resposne - either fetch from Database or hardcoded
        // validated flow
        echo json_encode([
          "status" => "200",
          "message" =>$message,
          "data" => $data
        ]);
      }

    ?>

==================================

```<code>Success resposne:
{"status":"200","message":{"success":"Successful"},"data":null}

 Failed response:
 {"status":"400","message":{"error_email":"Email address required.","error_mobile":"Mobile number required."}}

If email exists and mobile number empty then
Failed response:
{"status":"400","message":{"error_mobile":"Mobile number required."}}
</code>```

Body:
I am creating api in codeigniter in which i am checking both email and mobilenumber field for updating & in that check it for both field. my single message is go to response but in both casess how can i send both email and mobile number is exists

    if((isset($postData['email'])) && $postData['email']!="")
        {

                 $message["email_unique"]='Email already exists';
                 return $this->response(array("status" => "400", "message" =>$message), 400);

        }
        if((isset($postData['mobileNumber'])) && $postData['mobileNumber']!="")
        {
             $mobilenumber=$postData['mobileNumber'];

                 $message["mobilenumber_unique"]='Mobile Number already exists';
                 return $this->response(array("status" => "400", "message" =>$message), 400);

        }

Body:
Check this code

   "400",
          "message" =>$message
        ]);
        exit;
      } else {
        $message['success'] = "Successful";  // success messsage if needed
        $data = null;  // whatever data you need to pass in success resposne - either fetch from Database or hardcoded
        // validated flow
        echo json_encode([
          "status" => "200",
          "message" =>$message,
          "data" => $data
        ]);
      }

    ?>

==================================

Success resposne:
{"status":"200","message":{"success":"Successful"},"data":null}

 Failed response:
 {"status":"400","message":{"error_email":"Email address required.","error_mobile":"Mobile number required."}}

If email exists and mobile number empty then
Failed response:
{"status":"400","message":{"error_mobile":"Mobile number required."}}


问:
How to mock a bean with @Qualifier
I have a class which has a Bean with @Qualifier (See AerospikeClient). While writing test cases, I am unable to mock the bean using @MockBean. I always get null pointer exception for aerospikeClient inside verify(aerospikeClient).put

My class

```<code>package com.a.recharge.service.impl;

import com.aerospike.client.*;
import com.aerospike.client.policy.WritePolicy;
import com.a.recharge.entity.aero.PacksInfo;
import com.a.recharge.service.AerospikeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AerospikeServiceImpl implements AerospikeService {

    @Autowired
    @Qualifier("oldAerospikeClient")
    private AerospikeClient aerospikeClient;

    @Value("${config.aerospike.defaultNS:test}")
    private String nameSpace;

    @Value("${config.aerospike.set.txn:''}")
    private String setname;

    @Value("${config.aerospike.ttl:1800}")
    private int ttl;

    @Value("${config.aerospike.defaultNS}")
    public String defaultNS;

    @Value("${config.aerospike.host}")
    private String aerospikeHost;

    @Value("${config.aerospike.port}")
    private String aerospikePort;

    @Value("${config.aerospike.userName}")
    public String aerospikeUserName;

    @Value("${config.aerospike.password}")
    public String aerospikePassword;

    @Value("${config.aerospike.expiration}")
    public long expiration;

    @Value("${config.aerospike.expiration.no}")
    public long noExpiration;

    @Override
    public void insertRecord(String keyString, PacksInfo packsInfo) {
        // log.info("Saving Records in Aerospike, " + keyString+ ", "+ packsInfo);
        WritePolicy writePolicy = new WritePolicy();
        writePolicy.expiration = ttl; // seconds
        writePolicy.sendKey = true;

        // columns
        Bin[] bins = new Bin[3];

        bins[0] = new Bin("type", packsInfo.getClass().getName());
        bins[2] = new Bin("@user_key", keyString);
        bins[1] = new Bin("value", packsInfo);

        try {
            Key key = new Key("test", "PacksInfo", keyString);
            aerospikeClient.put(writePolicy, key, bins);
        } catch (AerospikeException e) {
            log.error("Exception raised. Root Cause {}, Message {}", ExceptionUtils.getRootCause(e),
                      ExceptionUtils.getMessage(e));
        }
    }

}
</code>```

My test class

```<code>package com.a.recharge.service;

import com.aerospike.client.AerospikeClient;
import com.aerospike.client.Bin;
import com.aerospike.client.Host;
import com.aerospike.client.Key;
import com.aerospike.client.policy.ClientPolicy;
import com.aerospike.client.policy.WritePolicy;
import com.a.recharge.config.AerospikeConfiguration;
import com.a.recharge.service.impl.AerospikeServiceImpl;
import com.a.recharge.util.CollectionUtil;
import com.a.recharge.util.TestUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;
import org.testng.annotations.BeforeMethod;

import java.util.List;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;

@RunWith(MockitoJUnitRunner.class)
// @SpringBootTest(classes = AerospikeServiceImpl.class)

public class AerospikeServiceImplTest {

    @Mock(name ="oldAerospikeClient")
    private AerospikeClient aerospikeClient;// = TestUtil.getAerospikeClient();

    @Captor
    private ArgumentCaptor<WritePolicy> captor1;

    @Captor
    private ArgumentCaptor<Key> captor2;

    @Captor
    private ArgumentCaptor<Bin[]> captor3;

    @InjectMocks
//    @Autowired
    AerospikeServiceImpl aerospikeService;

//    @BeforeMethod(alwaysRun = true)
//    public void setUp() {
//        MockitoAnnotations.initMocks(this);
//    }

    @Test
    public void checkInsert(){
        Mockito.doNothing().when(aerospikeClient).put(Mockito.any(), Mockito.any(), Mockito.any());
        Mockito.verify(aerospikeClient).put(captor1.capture(), captor2.capture(), captor3.capture());
        aerospikeService.insertRecord(TestUtil.keyString, TestUtil.getPacksInfo());

        assertEquals(1800, captor1.getValue().expiration);
        assertEquals(true, captor1.getValue().expiration);
    }
}

</code>```

i changed to InjectMocks and used Mockito.doNothing(), But still the same error.
Is it because the put method of aerospikeClient is final?

Another question is that for testing the AerospikeServiceImpl class should I autowire it directly as above or create a bean like this?

```<code>@TestConfiguration
    static class AerospikeServiceImplTestContextConfiguration {

        @Bean
        public AerospikeServiceImpl AerospikeServiceImpl() {
            return new AerospikeServiceImpl();
        }
    }
</code>```

I am relatively new to Spring Boot, so any best practices' advice will be highly appreciated.

My final test class. It works. No need of @TestConfiguration.

```<code>@RunWith(MockitoJUnitRunner.class)
public class AerospikeServiceImplTest {

    @Mock //(name ="oldAerospikeClient")
    private AerospikeClient aerospikeClient;

    @Captor
    private ArgumentCaptor<Key> captor2;

    @InjectMocks
//    @Autowired
    private AerospikeServiceImpl aerospikeService;

    @Test
    public void checkInsert(){
        aerospikeService.insertRecord(TestUtil.keyString, TestUtil.getPacksInfo());

        Mockito.verify(aerospikeClient).put(captor1.capture(), captor2.capture(), captor3.capture());
        assertEquals("test", captor2.getValue().namespace);
        assertEquals("PacksInfo", captor2.getValue().setName);
        assertEquals("MOBILE_JIOPREPAID_GJ", captor2.getValue().userKey.toString());

    }
</code>```

答:
aerospikeClient.put() is a final method. Mockito 2 now supports mocking final methods but this feature has to be explicitly activated ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line:

mock-maker-inline
Please refer to this link: https://github.com/mockito/mockito/wiki/What's-new-in-Mockito-2#mock-the-unmockable-opt-in-mocking-of-final-classesmethods

Title: How to mock a bean with @Qualifier

Body:
I have a class which has a Bean with @Qualifier (See AerospikeClient). While writing test cases, I am unable to mock the bean using @MockBean. I always get null pointer exception for aerospikeClient inside verify(aerospikeClient).put

My class

package com.a.recharge.service.impl;

import com.aerospike.client.*;
import com.aerospike.client.policy.WritePolicy;
import com.a.recharge.entity.aero.PacksInfo;
import com.a.recharge.service.AerospikeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AerospikeServiceImpl implements AerospikeService {

    @Autowired
    @Qualifier("oldAerospikeClient")
    private AerospikeClient aerospikeClient;

    @Value("${config.aerospike.defaultNS:test}")
    private String nameSpace;

    @Value("${config.aerospike.set.txn:''}")
    private String setname;

    @Value("${config.aerospike.ttl:1800}")
    private int ttl;

    @Value("${config.aerospike.defaultNS}")
    public String defaultNS;

    @Value("${config.aerospike.host}")
    private String aerospikeHost;

    @Value("${config.aerospike.port}")
    private String aerospikePort;

    @Value("${config.aerospike.userName}")
    public String aerospikeUserName;

    @Value("${config.aerospike.password}")
    public String aerospikePassword;

    @Value("${config.aerospike.expiration}")
    public long expiration;

    @Value("${config.aerospike.expiration.no}")
    public long noExpiration;

    @Override
    public void insertRecord(String keyString, PacksInfo packsInfo) {
        // log.info("Saving Records in Aerospike, " + keyString+ ", "+ packsInfo);
        WritePolicy writePolicy = new WritePolicy();
        writePolicy.expiration = ttl; // seconds
        writePolicy.sendKey = true;

        // columns
        Bin[] bins = new Bin[3];

        bins[0] = new Bin("type", packsInfo.getClass().getName());
        bins[2] = new Bin("@user_key", keyString);
        bins[1] = new Bin("value", packsInfo);

        try {
            Key key = new Key("test", "PacksInfo", keyString);
            aerospikeClient.put(writePolicy, key, bins);
        } catch (AerospikeException e) {
            log.error("Exception raised. Root Cause {}, Message {}", ExceptionUtils.getRootCause(e),
                      ExceptionUtils.getMessage(e));
        }
    }

}

My test class

package com.a.recharge.service;

import com.aerospike.client.AerospikeClient;
import com.aerospike.client.Bin;
import com.aerospike.client.Host;
import com.aerospike.client.Key;
import com.aerospike.client.policy.ClientPolicy;
import com.aerospike.client.policy.WritePolicy;
import com.a.recharge.config.AerospikeConfiguration;
import com.a.recharge.service.impl.AerospikeServiceImpl;
import com.a.recharge.util.CollectionUtil;
import com.a.recharge.util.TestUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;
import org.testng.annotations.BeforeMethod;

import java.util.List;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;

@RunWith(MockitoJUnitRunner.class)
// @SpringBootTest(classes = AerospikeServiceImpl.class)

public class AerospikeServiceImplTest {

    @Mock(name ="oldAerospikeClient")
    private AerospikeClient aerospikeClient;// = TestUtil.getAerospikeClient();

    @Captor
    private ArgumentCaptor<WritePolicy> captor1;

    @Captor
    private ArgumentCaptor<Key> captor2;

    @Captor
    private ArgumentCaptor<Bin[]> captor3;

    @InjectMocks
//    @Autowired
    AerospikeServiceImpl aerospikeService;

//    @BeforeMethod(alwaysRun = true)
//    public void setUp() {
//        MockitoAnnotations.initMocks(this);
//    }

    @Test
    public void checkInsert(){
        Mockito.doNothing().when(aerospikeClient).put(Mockito.any(), Mockito.any(), Mockito.any());
        Mockito.verify(aerospikeClient).put(captor1.capture(), captor2.capture(), captor3.capture());
        aerospikeService.insertRecord(TestUtil.keyString, TestUtil.getPacksInfo());

        assertEquals(1800, captor1.getValue().expiration);
        assertEquals(true, captor1.getValue().expiration);
    }
}

i changed to InjectMocks and used Mockito.doNothing(), But still the same error.
Is it because the put method of aerospikeClient is final?

Another question is that for testing the AerospikeServiceImpl class should I autowire it directly as above or create a bean like this?

@TestConfiguration
    static class AerospikeServiceImplTestContextConfiguration {

        @Bean
        public AerospikeServiceImpl AerospikeServiceImpl() {
            return new AerospikeServiceImpl();
        }
    }

I am relatively new to Spring Boot, so any best practices' advice will be highly appreciated.

My final test class. It works. No need of @TestConfiguration.

@RunWith(MockitoJUnitRunner.class)
public class AerospikeServiceImplTest {

    @Mock //(name ="oldAerospikeClient")
    private AerospikeClient aerospikeClient;

    @Captor
    private ArgumentCaptor<Key> captor2;

    @InjectMocks
//    @Autowired
    private AerospikeServiceImpl aerospikeService;

    @Test
    public void checkInsert(){
        aerospikeService.insertRecord(TestUtil.keyString, TestUtil.getPacksInfo());

        Mockito.verify(aerospikeClient).put(captor1.capture(), captor2.capture(), captor3.capture());
        assertEquals("test", captor2.getValue().namespace);
        assertEquals("PacksInfo", captor2.getValue().setName);
        assertEquals("MOBILE_JIOPREPAID_GJ", captor2.getValue().userKey.toString());

    }


问:
vuetify enlarge image on click
i have a image gallery on vuetify and trying to enlarge the image using the fullscreen function.

```<code><template>
 <v-container class="mt-12">
<v-row justify="center" v-if="!$fetchState.pending">
  <v-col
    cols="4"
    v-for="image in service.data.attributes.gallery.data"
    :key="image.id"
  >
    <v-img
      class="d-flex child-flex"
      :src="`${image.attributes.formats.large.url}`"
      :lazy-src="`${image.attributes.formats.thumbnail.url}`"
      contain
      @click="toggleFullscreen(image.attributes.url)"
    >
    </v-img>
  </v-col>
</v-row>
<v-row v-else>
  <LoadSpinner />
</v-row>
</code>```

and my toogle method

```<code>methods: {
toggleFullscreen(elem) {
  console.log(elem);
  if (elem.requestFullscreen) {
    elem.requestFullscreen();
  } else if (elem.msRequestFullscreen) {
    elem.msRequestFullscreen();
  } else if (elem.mozRequestFullScreen) {
    elem.mozRequestFullScreen();
  } else if (elem.webkitRequestFullscreen) {
    elem.webkitRequestFullscreen();
  } else {
    alert(
      "Sorry, your browser is too old and doesn't support fullscreen :-("
    );
  }
},
},
</code>```

i have and array coming from a strapi api, the idea is show in the gallery a low res image and when cliking fullscreen the high res version.

problem everytime i click it triggers the alert, so the method is not getting the correct info to work, could be v-img creates a div and uses de image as background?

thanks

pd tried already dialog and overlay but can't figure out how to "attack" individual elements

答:
After trying various libraries and what had to offer vuetify i did a workaround with vanilla css.

I created a variable, when you click on a image passes the url of the image, the template loads a div when this variable is not null with and overlay class to cover the screen.

in my template

```<code><v-img
      v-for="image in service.data.attributes.gallery.data"
      :key="image.id"
      :src="`${image.attributes.formats.large.url}`"

      @click="toggleFullscreen(image.attributes.url)"
    />
    <div v-if="selectedImage" class="overlay">
      <v-img
        class="mt-12"
        :src="selectedImage"
        alt=""
        height="95vh"
        contain
        dark
        @click.stop="selectedImage = null"
     >
      </v-img>
    </div>
</code>```

script part

```<code><script>
...
export default {
  data() {
    return {
   ...
      selectedImage: null,
    };
  },
  ...
  methods: {
    toggleFullscreen(elem) {
      this.selectedImage = elem;
    },
  },
};
</script>
</code>```

css

```<code>.overlay {
  position: fixed; /* Sit on top of the page content */
  width: 100%; /* Full width (cover the whole page) */
  height: 100%; /* Full height (cover the whole page) */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
  cursor: pointer; /* Add a pointer on hover */
}
</code>```

Title: vuetify enlarge image on click

Body:
i have a image gallery on vuetify and trying to enlarge the image using the fullscreen function.

<template>
 <v-container class="mt-12">
<v-row justify="center" v-if="!$fetchState.pending">
  <v-col
    cols="4"
    v-for="image in service.data.attributes.gallery.data"
    :key="image.id"
  >
    <v-img
      class="d-flex child-flex"
      :src="`${image.attributes.formats.large.url}`"
      :lazy-src="`${image.attributes.formats.thumbnail.url}`"
      contain
      @click="toggleFullscreen(image.attributes.url)"
    >
    </v-img>
  </v-col>
</v-row>
<v-row v-else>
  <LoadSpinner />
</v-row>

and my toogle method

methods: {
toggleFullscreen(elem) {
  console.log(elem);
  if (elem.requestFullscreen) {
    elem.requestFullscreen();
  } else if (elem.msRequestFullscreen) {
    elem.msRequestFullscreen();
  } else if (elem.mozRequestFullScreen) {
    elem.mozRequestFullScreen();
  } else if (elem.webkitRequestFullscreen) {
    elem.webkitRequestFullscreen();
  } else {
    alert(
      "Sorry, your browser is too old and doesn't support fullscreen :-("
    );
  }
},
},

i have and array coming from a strapi api, the idea is show in the gallery a low res image and when cliking fullscreen the high res version.

problem everytime i click it triggers the alert, so the method is not getting the correct info to work, could be v-img creates a div and uses de image as background?

thanks

pd tried already dialog and overlay but can't figure out how to "attack" individual elements

Body:
After trying various libraries and what had to offer vuetify i did a workaround with vanilla css.

I created a variable, when you click on a image passes the url of the image, the template loads a div when this variable is not null with and overlay class to cover the screen.

in my template

<v-img
      v-for="image in service.data.attributes.gallery.data"
      :key="image.id"
      :src="`${image.attributes.formats.large.url}`"

      @click="toggleFullscreen(image.attributes.url)"
    />
    <div v-if="selectedImage" class="overlay">
      <v-img
        class="mt-12"
        :src="selectedImage"
        alt=""
        height="95vh"
        contain
        dark
        @click.stop="selectedImage = null"
     >
      </v-img>
    </div>

script part

<script>
...
export default {
  data() {
    return {
   ...
      selectedImage: null,
    };
  },
  ...
  methods: {
    toggleFullscreen(elem) {
      this.selectedImage = elem;
    },
  },
};
</script>

css

.overlay {
  position: fixed; /* Sit on top of the page content */
  width: 100%; /* Full width (cover the whole page) */
  height: 100%; /* Full height (cover the whole page) */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
  cursor: pointer; /* Add a pointer on hover */
}


问:
Testing postgres database accessibility from django
I am using the django ORM with a postgres database. A small group of users interact with it using import and export scripts. The database is only available on our intranet. If someone tries to use the database when postgres is unavailable the scripts hang. I would like to make the scripts test whether the database is available before attempting to process any data.

I can connect to the database using the shell, import a model, and attempt to make a query:

```<code>from myapp.models import mymodel
mymodel.objects.count()
</code>```

this results in a long delay, but then django raises an OperationalError with an informative message ("could not connect to server: Network is unreachable...").

I thought to test database access by making a minimal query to the database, something like:

```<code>from django.db import connection
cursor = connection.cursor()
cursor.execute("select 1")
</code>```

but this never progresses beyond the cursor = connection.cursor() line. No error message.

Why does one of these queries raise an error, but not the other?

What's the best way to test from a script whether the database is available?

How can I ensure that an error will be raised if the connection doesn't succeed within reasonable (perhaps user specified) time?

This is not a web application, so a middleware solution à la How do I test a database connection in Django? isn't possible.

Edit

Following @benjaoming's suggestion, I've made a function to test the connection:

```<code>import socket

def test_connection():
    """Test whether the postgres database is available. Usage:

        if "--offline" in sys.argv:
            os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings.offline'
        else:
            os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings.standard'
            from myapp.functions.connection import test_connection
            test_connection()
    """
    try:
        s = socket.create_connection(("example.net", 5432), 5)
        s.close()
    except socket.timeout:
        msg = """Can't detect the postgres server. If you're outside the
        intranet, you might need to turn the VPN on."""
        raise socket.timeout(msg)
</code>```

This seems to do the trick.

答:
```<code>from django.db import connections
db_conn = connections['default']
try:
    c = db_conn.cursor()
except Exception as e:
    connected = False
else:
    connected = True
</code>```

This can be used to check connections with databases.

Body:
I am using the django ORM with a postgres database. A small group of users interact with it using import and export scripts. The database is only available on our intranet. If someone tries to use the database when postgres is unavailable the scripts hang. I would like to make the scripts test whether the database is available before attempting to process any data.

I can connect to the database using the shell, import a model, and attempt to make a query:

from myapp.models import mymodel
mymodel.objects.count()

this results in a long delay, but then django raises an OperationalError with an informative message ("could not connect to server: Network is unreachable...").

I thought to test database access by making a minimal query to the database, something like:

from django.db import connection
cursor = connection.cursor()
cursor.execute("select 1")

but this never progresses beyond the cursor = connection.cursor() line. No error message.

Why does one of these queries raise an error, but not the other?

What's the best way to test from a script whether the database is available?

How can I ensure that an error will be raised if the connection doesn't succeed within reasonable (perhaps user specified) time?

This is not a web application, so a middleware solution à la How do I test a database connection in Django? isn't possible.

Edit

Following @benjaoming's suggestion, I've made a function to test the connection:

import socket

def test_connection():
    """Test whether the postgres database is available. Usage:

        if "--offline" in sys.argv:
            os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings.offline'
        else:
            os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings.standard'
            from myapp.functions.connection import test_connection
            test_connection()
    """
    try:
        s = socket.create_connection(("example.net", 5432), 5)
        s.close()
    except socket.timeout:
        msg = """Can't detect the postgres server. If you're outside the
        intranet, you might need to turn the VPN on."""
        raise socket.timeout(msg)

This seems to do the trick.

Body:
from django.db import connections
db_conn = connections['default']
try:
    c = db_conn.cursor()
except Exception as e:
    connected = False
else:
    connected = True

This can be used to check connections with databases.


问:
Java regex for image filename?
I have to filter filenames to match only image (png,jpg,gif,bmp) files, is possible to make a such regex or do I have to have different regex for every file type? It also cannot contain path like ../../ or /var/app/filename.exe etc.</p>

答:
I'll use something like this... This should cover most cases without going too much into crazy details...

```<code>(.*/)*.+\.(png|jpg|gif|bmp|jpeg|PNG|JPG|GIF|BMP|JPEG)$
</code>```

As a Java String this regex looks like this:

```<code>"(.*/)*.+\\.(png|jpg|gif|bmp|jpeg|PNG|JPG|GIF|BMP|JPEG)$"
</code>```

Hope that helps... :)

Title: Java regex for image filename?

Body:
I'll use something like this... This should cover most cases without going too much into crazy details...

(.*/)*.+\.(png|jpg|gif|bmp|jpeg|PNG|JPG|GIF|BMP|JPEG)$

As a Java String this regex looks like this:

"(.*/)*.+\\.(png|jpg|gif|bmp|jpeg|PNG|JPG|GIF|BMP|JPEG)$"

Hope that helps... :)


问:
How to manage multiple states in React?
I have components in my React App, with more than 20 rows with:

```<code>useState()
</code>```

Is that the correct way or to assign them in a object, is there some kind of differences ?

答:
That is fine. Sometimes we can have 10-12 lines of useState() calls only. I usually combine similar states in one so that I can use a single variable in my component instead of 5.

Instead of:

```<code>const [a, setA] = useState('')
const [b, setB] = useState('')
const [c, setC] = useState('')
const [d, setD] = useState('')
const [e, setE] = useState('')
</code>```

I use:

```<code>const [letters, setLetters] = useState({
a: '',
b: '',
c: '',
d: '',
e: ''})
</code>```

and update the state as:

```<code>setLetters(prev => ({...prev, c: 'hello'}))
</code>```

Title: How to manage multiple states in React?

Body:
I have components in my React App, with more than 20 rows with:

useState()

Is that the correct way or to assign them in a object, is there some kind of differences ?

Body:
That is fine. Sometimes we can have 10-12 lines of useState() calls only. I usually combine similar states in one so that I can use a single variable in my component instead of 5.

Instead of:

const [a, setA] = useState('')
const [b, setB] = useState('')
const [c, setC] = useState('')
const [d, setD] = useState('')
const [e, setE] = useState('')

I use:

const [letters, setLetters] = useState({
a: '',
b: '',
c: '',
d: '',
e: ''})

and update the state as:

setLetters(prev => ({...prev, c: 'hello'}))


问:
Desktop Application SSRS Report Rendering Out Of Memory Exception on single user PC
We have a .NET desktop Application Running
One of my user is facing OutOfMemory Exception while SSRS Report Rendering
Though, I am able to run SSRS through Browser Report Link.

All other users are working fine

User PC Configuration
i5 10th Gen 8 GB Ram (Lot of free space Available)

Steps performed

Tried Reinstalling Application

Tried Deleting Temp Files

Checked TaskManager  everything is ok

Is there any thing else why ??

Below is the Error Screenshot i am facing..

答:
This situation will occur when one of the following conditions are true :

The report is too large or complex.

The overhead of other running processes is very high.

The physical memory of computer is too small.

You can reduce memory consumption by redesigning the report queries:

Return less data in the queries.(you can add filter parameter)

Use a better restriction on the WHERE clause.

Move complex aggregations to the data source or view.

Increase sufficient physical memory to the computer.

Adjust MemoryLimit setting accordingly.

For more information about System.OutOfMemoryException and Configuring Available Memory for Report Server Applications, please refer to the articles below:
http://support.microsoft.com/kb/909678/EN-US
http://msdn.microsoft.com/en-us/library/ms159206.aspx


问:
How to Hide TabBarNavigator dynamically react native
I am looking for a way to hide my bottomTabNavigator onScoll from within my UserScreen

Here is my userScreen:

```<code>    function Users() {
    const {headerText, interestText, interestShell, interestsLayout, aboutText, userImage} = styles;

    return (
        <View>
            <ScrollView showsVerticalScrollIndicator={false}>
                <View style={{flex: 1}}>
                    <ProfileButton/>
                    <Image style={userImage} source={mockUsers[0].pictures[0]}/>
                    <UserProfileInfo/>
                </View>
                <View>
                    <Text style={headerText}>About</Text>
                    <View style={{marginLeft: 32}}>
                        <Text style={aboutText}>
                            {mockUsers[0].about}
                        </Text>
                    </View>
                    <Text style={headerText}>Interests</Text>
                    <View style={interestsLayout}>
                        {mockUsers[0].userInterests?.map((interest, index) => {
                            return (
                                <View style={interestShell}>
                                    <Text key={`interest-${index}`} style={interestText}>{interest}</Text>
                                </View>
                            )
                        })}
                    </View>
                    <Text style={headerText}>Questions and answers</Text>
                    <AnsweredQuestionInput/>
                    <AnsweredQuestionInput/>
                    <AnsweredQuestionInput/>
                    <Text style={headerText}>Pictures</Text>
                    <Pictures userPictures={mockUsers[0].pictures} blur={true}/>
                </View>
            </ScrollView>
            <LikeAndDislike/>
        </View>

    );
}
</code>```

Here is my bottomTabNavigator:

```<code>    function BottomTabNavigator() {
    const {buttonShell, buttonText} = styles;
    const Tab = createBottomTabNavigator();
    const Icon = createIconSet(glyphMap, 'Fuze', 'Fuze.ttf');

    return (
        <Tab.Navigator
            initialRouteName="Users"
            screenOptions={({route}) => ({
                headerShown: false,
                tabBarShowLabel: false,
                tabBarStyle: {borderColor: '#DBDBDB', height: 88, paddingTop: 16},
            })}
        >
            {
                bottomTabs.map((bottomTab) => {
                        return (
                            <Tab.Screen
                                key={`screen-${bottomTab.title}`}
                                name={bottomTab.title}
                                component={bottomTab.componentName}
                                options={{
                                    unmountOnBlur: true,
                                    tabBarIcon: (({focused}) => {
                                        return !focused ?
                                            <Icon name={bottomTab.icon} size={32}/> :
                                            <View style={buttonShell}>
                                                <Text style={buttonText}>{bottomTab.title}</Text>
                                            </View>

                                    })
                                }}
                            />
                        )
                    }
                )
            }
        </Tab.Navigator>
    )
}
</code>```

So far I have been researching and found react navigation removed the tabBarVisible option and the only other way that I have seen people hide the screen is through css on the screenOptions by setting display: 'none'
I would love to find a way to pass up from the user screen a if scrolling return true and then set display based on the boolean value. Any help would be brilliant. Thanks

答:
In react navigation they have removed tabBarVisible and instead replace it with tabBarStyles: {display: 'none'}. Therefore, I updated my code in my usersScreen to this:

```<code>function Users() {
const navigation = useNavigation();

const hideTabBar = () => {
    navigation.setOptions({
        tabBarStyle: {display: 'none'},
    });
};

const showTabBar = () => {
    navigation.setOptions({
        tabBarStyle: {display: 'flex', borderColor: '#DBDBDB', height: 88, paddingTop: 16},
    });
};

useEffect(() => hideTabBar(), [])

return (
    <View>
        <ScrollView
            showsVerticalScrollIndicator={false}
            onMomentumScrollEnd={() => showTabBar()}
            onMomentumScrollBegin={() => hideTabBar()}
        >
           //some code//
        </ScrollView>
        <LikeAndDislike/>
    </View>
);
}
</code>```

Body:
I am looking for a way to hide my bottomTabNavigator onScoll from within my UserScreen

Here is my userScreen:

    function Users() {
    const {headerText, interestText, interestShell, interestsLayout, aboutText, userImage} = styles;

    return (
        <View>
            <ScrollView showsVerticalScrollIndicator={false}>
                <View style={{flex: 1}}>
                    <ProfileButton/>
                    <Image style={userImage} source={mockUsers[0].pictures[0]}/>
                    <UserProfileInfo/>
                </View>
                <View>
                    <Text style={headerText}>About</Text>
                    <View style={{marginLeft: 32}}>
                        <Text style={aboutText}>
                            {mockUsers[0].about}
                        </Text>
                    </View>
                    <Text style={headerText}>Interests</Text>
                    <View style={interestsLayout}>
                        {mockUsers[0].userInterests?.map((interest, index) => {
                            return (
                                <View style={interestShell}>
                                    <Text key={`interest-${index}`} style={interestText}>{interest}</Text>
                                </View>
                            )
                        })}
                    </View>
                    <Text style={headerText}>Questions and answers</Text>
                    <AnsweredQuestionInput/>
                    <AnsweredQuestionInput/>
                    <AnsweredQuestionInput/>
                    <Text style={headerText}>Pictures</Text>
                    <Pictures userPictures={mockUsers[0].pictures} blur={true}/>
                </View>
            </ScrollView>
            <LikeAndDislike/>
        </View>

    );
}

Here is my bottomTabNavigator:

    function BottomTabNavigator() {
    const {buttonShell, buttonText} = styles;
    const Tab = createBottomTabNavigator();
    const Icon = createIconSet(glyphMap, 'Fuze', 'Fuze.ttf');

    return (
        <Tab.Navigator
            initialRouteName="Users"
            screenOptions={({route}) => ({
                headerShown: false,
                tabBarShowLabel: false,
                tabBarStyle: {borderColor: '#DBDBDB', height: 88, paddingTop: 16},
            })}
        >
            {
                bottomTabs.map((bottomTab) => {
                        return (
                            <Tab.Screen
                                key={`screen-${bottomTab.title}`}
                                name={bottomTab.title}
                                component={bottomTab.componentName}
                                options={{
                                    unmountOnBlur: true,
                                    tabBarIcon: (({focused}) => {
                                        return !focused ?
                                            <Icon name={bottomTab.icon} size={32}/> :
                                            <View style={buttonShell}>
                                                <Text style={buttonText}>{bottomTab.title}</Text>
                                            </View>

                                    })
                                }}
                            />
                        )
                    }
                )
            }
        </Tab.Navigator>
    )
}

So far I have been researching and found react navigation removed the tabBarVisible option and the only other way that I have seen people hide the screen is through css on the screenOptions by setting display: 'none'
I would love to find a way to pass up from the user screen a if scrolling return true and then set display based on the boolean value. Any help would be brilliant. Thanks

Body:
In react navigation they have removed tabBarVisible and instead replace it with tabBarStyles: {display: 'none'}. Therefore, I updated my code in my usersScreen to this:

function Users() {
const navigation = useNavigation();

const hideTabBar = () => {
    navigation.setOptions({
        tabBarStyle: {display: 'none'},
    });
};

const showTabBar = () => {
    navigation.setOptions({
        tabBarStyle: {display: 'flex', borderColor: '#DBDBDB', height: 88, paddingTop: 16},
    });
};

useEffect(() => hideTabBar(), [])

return (
    <View>
        <ScrollView
            showsVerticalScrollIndicator={false}
            onMomentumScrollEnd={() => showTabBar()}
            onMomentumScrollBegin={() => hideTabBar()}
        >
           //some code//
        </ScrollView>
        <LikeAndDislike/>
    </View>
);
}


问:
apache node js socket.io error connection refused
There is a php-file on apache:

```<code><script src="/../node_modules/socket.io/client-dist/socket.io.js"></script>

let socket = io.connect( 'http://localhost:3000' );

socket.on('update', function updateData(sounds) {
    console.log(sounds);
});
</code>```

and node js in same directory

```<code>let http = require('http');
let express = require('express');
let path = require('path');
let socketIO = require('socket.io');
let app = express();
let server = http.Server(app);
let io = socketIO(server);

app.set('port', 3000);

server.listen(3000, function() {
   console.log('listening on *:3000');
});

io.on('connection', function(socket) {
   console.log('A user connected');

   socket.on('disconnect', function() {
      console.log('A user disconnected');
   });

});
</code>```

browser throws an error: GET http://192.168.100.31/socket.io/?EIO=4&transport=polling&t=NxOsf3z 404 (Not Found)

if replace let socket = io.connect( 'http://localhost:3000' )
on
let socket = io.connect( 'http://192.168.100.31:3000' );
browser will give another error: Access to XMLHttpRequest at 'http://192.168.100.31:3000/socket.io/?EIO=4&transport=polling&t=NxOt0X0' from origin 'http://192.168.100.31' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

答:
Just had to replace

```<code>let socket = io.connect( 'http://localhost:3000' );
</code>```

with

```<code>let socket = io.connect( 'http://192.168.100.31:3000/' );
</code>```

Body:
There is a php-file on apache:

let socket = io.connect( 'http://localhost:3000' );

socket.on('update', function updateData(sounds) {
    console.log(sounds);
});

and node js in same directory

let http = require('http');
let express = require('express');
let path = require('path');
let socketIO = require('socket.io');
let app = express();
let server = http.Server(app);
let io = socketIO(server);

app.set('port', 3000);

server.listen(3000, function() {
   console.log('listening on *:3000');
});

io.on('connection', function(socket) {
   console.log('A user connected');

   socket.on('disconnect', function() {
      console.log('A user disconnected');
   });

});

browser throws an error: GET http://192.168.100.31/socket.io/?EIO=4&transport=polling&t=NxOsf3z 404 (Not Found)

if replace let socket = io.connect( 'http://localhost:3000' )
on
let socket = io.connect( 'http://192.168.100.31:3000' );
browser will give another error: Access to XMLHttpRequest at 'http://192.168.100.31:3000/socket.io/?EIO=4&transport=polling&t=NxOt0X0' from origin 'http://192.168.100.31' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Body:
Just had to replace

let socket = io.connect( 'http://localhost:3000' );

with

let socket = io.connect( 'http://192.168.100.31:3000/' );


问:
how to secure flutter plugin/package ? allow Methods to be used but restrict the access to implementation
I have encryption/decryption code which has "secret code" and "IV" which i don't want the the other developers to know, if i create a flutter package how can i achieve this so that developers should use the methods encrypt/decrypt but should not see the actual implementation especially "secret key" and "IV". any suggestions will help thanks you</p>

答:
convert your code server relate
build small site with some route for your function
such that they make request and retrieve the answer

example with node


问:
Create a JSON string from column values
How do I mutate a Pandas DataFrame with a series of dictionaries.

Given the following DataFrame:

```<code>data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

# add dict series
df = df.assign(my_dict="{}")
df.my_dict = df.my_dict.apply(json.loads)
</code>```

Name
Age
my_dict

tom
10
{}

nick
15
{}

juli
14
{}

How would I operate on column my_dict and mutate it as follows:

Age > 10

Name
Age
my_dict

tom
10
{"age>10": false}

nick
15
{"age>10": true}

juli
14
{"age>10": true}

And then mutate again:

Name = "tom":

Name
Age
my_dict

tom
10
{"age>10": false, "name=tom": true}

nick
15
{"age>10": true, "name=tom", false}

juli
14
{"age>10": true, "name=tom", false}

I'm interested in the process of mutating the dictionary, the rules are arbitrary examples.

答:
apply is generally supposed to be slow. Here are two alternatives, both using list comprehensions, which according to this highly voted answer, is slightly faster than apply.

```<code>import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

# Define your weird func: takes a row of df and returns your dict
def weird_func2(row):
    return {"name=tom":row["Name"]=="tom", "age>10":row["Age"]>10}

# add dict series
df["mydict"] = [weird_func2(i[1]) for i in df.iterrows()]
df
</code>```

Or you can try:

```<code>import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

# Define your weird func: takes a row of df and returns your dict
def weird_func(name, age):
    return {"name=tom":name=="tom", "age>10":age>10}

# add dict series
df["mydict"] = [weird_func(name, age) for name, age in zip(df["Name"], df["Age"])]
df
</code>```

Title: Create a JSON string from column values

Body:
How do I mutate a Pandas DataFrame with a series of dictionaries.

Given the following DataFrame:

data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

# add dict series
df = df.assign(my_dict="{}")
df.my_dict = df.my_dict.apply(json.loads)

Name
Age
my_dict

tom
10
{}

nick
15
{}

juli
14
{}

How would I operate on column my_dict and mutate it as follows:

Age > 10

Name
Age
my_dict

tom
10
{"age>10": false}

nick
15
{"age>10": true}

juli
14
{"age>10": true}

And then mutate again:

Name = "tom":

Name
Age
my_dict

tom
10
{"age>10": false, "name=tom": true}

nick
15
{"age>10": true, "name=tom", false}

juli
14
{"age>10": true, "name=tom", false}

I'm interested in the process of mutating the dictionary, the rules are arbitrary examples.

Body:
apply is generally supposed to be slow. Here are two alternatives, both using list comprehensions, which according to this highly voted answer, is slightly faster than apply.

import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

# Define your weird func: takes a row of df and returns your dict
def weird_func2(row):
    return {"name=tom":row["Name"]=="tom", "age>10":row["Age"]>10}

# add dict series
df["mydict"] = [weird_func2(i[1]) for i in df.iterrows()]
df

Or you can try:

import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

# Define your weird func: takes a row of df and returns your dict
def weird_func(name, age):
    return {"name=tom":name=="tom", "age>10":age>10}

# add dict series
df["mydict"] = [weird_func(name, age) for name, age in zip(df["Name"], df["Age"])]
df