问:
React-router <Route> tag not rendering component
I'm running into an issue where my route tag in specific is not rendering any components.

Steps I have tried:

Changed import of { Route } from "react-router-dom".

Changed paths to see if other paths render.

Rendered the component within  tags (this worked).

The issue seems to be coming down to something going on with the  tag.

Here is a copy of my code:

```<code>import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <NavBar />
                <Route path="/" exact component={Login} />
            </BrowserRouter>
        )
    }
}

export default App;
</code>```

The versions are:

```<code>├─┬ react-router-dom@6.2.1
│ └── react-router@6.2.1 deduped
└── react-router@6.2.1
</code>```

I tried changing the tags to  as per a suggestion and it still didn't work, but I may have implemented it incorrectly. Here is what I tried:

```<code>import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter, Routes } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <Routes>
                <NavBar />
                <Route path="/" exact component={Login} />
            </Routes>
        )
    }
}

export default App;
</code>```

The errors I am getting on the console are:

```<code>Uncaught Error: useRoutes() may be used only in the context of a <Router> component.
    Choo 3
    React 17
    Choo 2
    Webpack 3
</code>```
```<code>The above error occurred in the <Routes> component:

Routes@http://localhost:3000/static/js/bundle.js:54433:7
App@http://localhost:3000/static/js/bundle.js:42:1
</code>```

Any help would be greatly appreciated!

Solution:

Was resolved by switching the "component" tag to "element" tag and removing the  tag outside as follows:

```<code>            <>
                <NavBar />
                <Routes>
                    <Route path="/" exact element={<Login />} />
                </Routes>
            </>
</code>```

答:
List item

put Navbar outside for Routes tag like i did below

```<code>import { BrowserRouter, Routes,Route } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
           <>
            <NavBar />
            <Routes>
                <Route path="/" element={<Login/>} />
            </Routes>
          </>
        )
    }
}

export default App;
</code>```

also for newer version of react-router-dom use element instead of component and remove exact
It will be good if you use BrowserRouter index.js and wrapper App over there
for example index.js

```<code><BrowserRouter><App/></BrowserRouter>
</code>```

Body:
I'm running into an issue where my route tag in specific is not rendering any components.

Steps I have tried:

Changed import of { Route } from "react-router-dom".

Changed paths to see if other paths render.

Rendered the component within  tags (this worked).

The issue seems to be coming down to something going on with the  tag.

Here is a copy of my code:

import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <NavBar />
                <Route path="/" exact component={Login} />
            </BrowserRouter>
        )
    }
}

export default App;

The versions are:

├─┬ react-router-dom@6.2.1
│ └── react-router@6.2.1 deduped
└── react-router@6.2.1

I tried changing the tags to  as per a suggestion and it still didn't work, but I may have implemented it incorrectly. Here is what I tried:

import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter, Routes } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <Routes>
                <NavBar />
                <Route path="/" exact component={Login} />
            </Routes>
        )
    }
}

export default App;

The errors I am getting on the console are:

Uncaught Error: useRoutes() may be used only in the context of a <Router> component.
    Choo 3
    React 17
    Choo 2
    Webpack 3

The above error occurred in the <Routes> component:

Routes@http://localhost:3000/static/js/bundle.js:54433:7
App@http://localhost:3000/static/js/bundle.js:42:1

Any help would be greatly appreciated!

Solution:

Was resolved by switching the "component" tag to "element" tag and removing the  tag outside as follows:

            <>
                <NavBar />
                <Routes>
                    <Route path="/" exact element={<Login />} />
                </Routes>
            </>

Body:
List item

put Navbar outside for Routes tag like i did below

import { BrowserRouter, Routes,Route } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
           <>
            <NavBar />
            <Routes>
                <Route path="/" element={<Login/>} />
            </Routes>
          </>
        )
    }
}

export default App;

also for newer version of react-router-dom use element instead of component and remove exact
It will be good if you use BrowserRouter index.js and wrapper App over there
for example index.js

<BrowserRouter><App/></BrowserRouter>


来源: stackexchange

问:
Managing multiple threads at the console
When I run multiple threads I get lost in System.out.println output because I suppose each thread has to be in a different consoles.

Is there an easy way to manage it using Eclipse?

EDIT: The problem is not to know which message belongs to each thread. The exact problem is that the console stops printing when a new thread is called, and the same happens with log4j too.

答: You could use log4j and set up a different Logger for each thread, connecting each logger to a different Eclipse view, but that would be a lot of configuration and a lot of coding in your app. Alternatively, if you just logged the thread ID along with your message, then you could tell what thread printed out even if all threads logged to the same view.</p>

ContentLicense: CC BY-SA 3.0


问:
Need to create wider container in Bootstrap - 1920px
I have .psd design for client site, graphic designer drew container width up to 1920px, and I need a help how to properly set up width of container to 1920px.

I know how to set up smaller

```<code>@media (min-width: 1200px)
.container {
      width: 1170px;
}
</code>```

答:
This css will override bootstrap's container sizing.  Adjust the max-width values as needed. Tested with bootstrap 4.6.1

/* Override bootstrap to make containers wider by 60px */
@media screen and (min-width: 576px) {
    .container, .container-sm {
        max-width: 600px;
    }
}
@media screen and (min-width: 768px) {
    .container, .container-md, .container-sm {
        max-width: 780px;
    }
}
@media screen and (min-width: 992px) {
    .container, .container-lg, .container-md, .container-sm {
        max-width: 1020px;
    }
}
@media screen and (min-width: 1200px) {
    .container, .container-lg, .container-md, .container-sm, .container-xl {
        max-width: 1200px;
    }
}
```

ContentLicense: CC BY-SA 4.0

Body:
I have .psd design for client site, graphic designer drew container width up to 1920px, and I need a help how to properly set up width of container to 1920px.

I know how to set up smaller

@media (min-width: 1200px)
.container {
      width: 1170px;
}


问:
Django Image not showing up in django when using template tags
When i try calling an image like this {{ profile.image.url }}  it works in the profile page, but in the home page when i do {{ post.user.profile.image.url }} nothing shows up and that is not what i expect. i have also tried checking if the image url work and yes it's working.
NOTE: It working fine as expected in the profile page but in index.html it seems like nothing is showing up.

index.html

```<code>{% for post in post_items %}
   <a href="{{post.user.profile.image.url}}" class="post__avatar">
       <img src="{{post.user.profile.image.url}}" alt="User Picture">
   </a>
   <a href=""{{ post.user.username }}</a>
</code>```

models.py

```<code>class Profile(models.Model):
    user = models.ForeignKey(User, related_name='profile', on_delete=models.CASCADE)
    image = models.ImageField(upload_to="profile_pciture", null=True)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

    def __str__(self):
        return f'{self.user.username} - Profile'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
</code>```

答:
The way you have defined your Profile model results in a one-to-many relationship with User, so the field to follow the relationship backward would be something like  post.user.profile_set.objects.all().first().image.

Since it appears that you want a one-to-one relationship, the Profile model should be:

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
    image = models.ImageField(upload_to="profile_pciture", null=True)
</code>```

With this, you should be able to follow the relationship backwards with post.user.profile.image.

You can find the relevant docs here.

Body:
When i try calling an image like this {{ profile.image.url }}  it works in the profile page, but in the home page when i do {{ post.user.profile.image.url }} nothing shows up and that is not what i expect. i have also tried checking if the image url work and yes it's working.
NOTE: It working fine as expected in the profile page but in index.html it seems like nothing is showing up.

index.html

{% for post in post_items %}

   <a href=""{{ post.user.username }}

models.py

class Profile(models.Model):
    user = models.ForeignKey(User, related_name='profile', on_delete=models.CASCADE)
    image = models.ImageField(upload_to="profile_pciture", null=True)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

    def __str__(self):
        return f'{self.user.username} - Profile'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

Body:
The way you have defined your Profile model results in a one-to-many relationship with User, so the field to follow the relationship backward would be something like  post.user.profile_set.objects.all().first().image.

Since it appears that you want a one-to-one relationship, the Profile model should be:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
    image = models.ImageField(upload_to="profile_pciture", null=True)

With this, you should be able to follow the relationship backwards with post.user.profile.image.

You can find the relevant docs here.


问:
Github API works in curl but not python - bad credentials
I am trying to use the Github API and it works when I do curl from terminal but not when using the Python Request library:

WORKS:

```<code>curl -v --location --request GET 'https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100' \
--header 'Authorization: Bearer MY_TOKEN'
</code>```

DOESN'T WORK:

```<code>import requests

url = https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100
r = requests.get(url, auth=(MY_GITHUB_USERNAME, MY_TOKEN))
</code>```

I get the following response for python:

" b'{"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"}' "

Would appreciate any help - thank you in advance!

答:
The following should get you going I think. Think it is just the headers that needed a little bit of a change.</p>
```<code>import requests

token = MYTOKEN
url = "some url"

headers = {"Accept": "application/vnd.github.html",
           "Authorization": f"token {token}",}

request = requests.get(url, headers=headers)
</code>```

Body:
I am trying to use the Github API and it works when I do curl from terminal but not when using the Python Request library:

WORKS:

curl -v --location --request GET 'https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100' \
--header 'Authorization: Bearer MY_TOKEN'

DOESN'T WORK:

import requests

url = https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100
r = requests.get(url, auth=(MY_GITHUB_USERNAME, MY_TOKEN))

I get the following response for python:

" b'{"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"}' "

Would appreciate any help - thank you in advance!

Body:
The following should get you going I think. Think it is just the headers that needed a little bit of a change.

import requests

token = MYTOKEN
url = "some url"

headers = {"Accept": "application/vnd.github.html",
           "Authorization": f"token {token}",}

request = requests.get(url, headers=headers)


问:
Webpack build error: [Error: ENOENT: no such file or directory, rename '*.js -> '*.webpack.js']
A little bit of context for this one, I have this following folder structure. My program in particular is issuetrax (for reference to the image)

current folder structure for error

I keep getting the following error:

```<code>[Error: ENOENT: no such file or directory, rename '*.js -> '*.webpack.js']
</code>```

I've also deleted node_modules, yarn.lock (it's a new module so no worries there) and esm.

What's causing it to snag?

答:
What's happening is that if there is only ONE folder under lib (that being issuetrax in my case), it'll just assume that folder is the root and ignore the rest of the structure. This causes Webpack to misplace files and then hence our problem.

To fix this, add this property to to your "compilerOptions" in module.tsconfig.json:

```<code>"rootDir": "./<name-of-root-folder>"
</code>```

In my case, my root folder was named lib but you can name yours accordingly.

You can also add more folders/files to your root directory and that fixes the problem as well. Either way, Potato Tomato.

Body:
A little bit of context for this one, I have this following folder structure. My program in particular is issuetrax (for reference to the image)

current folder structure for error

I keep getting the following error:

[Error: ENOENT: no such file or directory, rename '*.js -> '*.webpack.js']

I've also deleted node_modules, yarn.lock (it's a new module so no worries there) and esm.

What's causing it to snag?

Body:
What's happening is that if there is only ONE folder under lib (that being issuetrax in my case), it'll just assume that folder is the root and ignore the rest of the structure. This causes Webpack to misplace files and then hence our problem.

To fix this, add this property to to your "compilerOptions" in module.tsconfig.json:

"rootDir": "./<name-of-root-folder>"

In my case, my root folder was named lib but you can name yours accordingly.

You can also add more folders/files to your root directory and that fixes the problem as well. Either way, Potato Tomato.


问:
Add column with row number count of grouped column values while excluding NA's
I am trying to add a column to a data frame with a row number by groups. I do not want to count NA's. I have grouped by Day and want to add a column counting the row numbers by group without NA's. I am getting a data frame that counts the NA's first and then the number values.

Code so far:

```<code>df <- data.frame (Day  = c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2", "3", "3", "3", "3", "3"),
                  test1 = c("1.2", NA, "3.2", NA, "7.2", "1.2", "2.5", "0.98", NA, "1.6","1.2", NA, "4.1", "9.2", "0.78")
)

df <- df %>%
  group_by(Day) %>%
  mutate(row_num = row_number(!is.na(test1)))
print(df)

# A tibble: 15 x 3
# Groups:   Day [3]
   Day   test1 row_num
   <chr> <chr>       <int>
 1 1     1.2             3
 2 1     NA              1
 3 1     3.2             4
 4 1     NA              2
 5 1     7.2             5
 6 2     1.2             2
 7 2     2.5             3
 8 2     0.98            4
 9 2     NA              1
10 2     1.6             5
11 3     1.2             2
12 3     NA              1
13 3     4.1             3
14 3     9.2             4
15 3     0.78            5
</code>```

It should be:

```<code>Day   test1 row_num
   <chr> <chr>       <int>
 1 1     1.2             1
 2 1     NA
 3 1     3.2             2
 4 1     NA
 5 1     7.2             3
 6 2     1.2             4
 7 2     2.5             5
 8 2     0.98            6
 9 2     NA
10 2     1.6             1
11 3     1.2             2
12 3     NA
13 3     4.1             3
14 3     9.2             4
15 3     0.78            5
</code>```

答:
We may use replace

```<code>library(dplyr)
df %>%
  group_by(Day) %>%
   mutate(row_num =  replace(test1, !is.na(test1),
       seq_along(test1[!is.na(test1)]))) %>%
   ungroup
</code>```

Or with data.table

```<code>library(data.table)
setDT(df)[!is.na(test1), row_num := seq_len(.N), by = Day]
</code>```

Body:
I am trying to add a column to a data frame with a row number by groups. I do not want to count NA's. I have grouped by Day and want to add a column counting the row numbers by group without NA's. I am getting a data frame that counts the NA's first and then the number values.

Code so far:

df <- data.frame (Day  = c("1", "1", "1", "1", "1", "2", "2", "2", "2", "2", "3", "3", "3", "3", "3"),
                  test1 = c("1.2", NA, "3.2", NA, "7.2", "1.2", "2.5", "0.98", NA, "1.6","1.2", NA, "4.1", "9.2", "0.78")
)

df <- df %>%
  group_by(Day) %>%
  mutate(row_num = row_number(!is.na(test1)))
print(df)

# A tibble: 15 x 3
# Groups:   Day [3]
   Day   test1 row_num
   <chr> <chr>       <int>
 1 1     1.2             3
 2 1     NA              1
 3 1     3.2             4
 4 1     NA              2
 5 1     7.2             5
 6 2     1.2             2
 7 2     2.5             3
 8 2     0.98            4
 9 2     NA              1
10 2     1.6             5
11 3     1.2             2
12 3     NA              1
13 3     4.1             3
14 3     9.2             4
15 3     0.78            5

It should be:

Day   test1 row_num
   <chr> <chr>       <int>
 1 1     1.2             1
 2 1     NA
 3 1     3.2             2
 4 1     NA
 5 1     7.2             3
 6 2     1.2             4
 7 2     2.5             5
 8 2     0.98            6
 9 2     NA
10 2     1.6             1
11 3     1.2             2
12 3     NA
13 3     4.1             3
14 3     9.2             4
15 3     0.78            5

Body:
We may use replace

library(dplyr)
df %>%
  group_by(Day) %>%
   mutate(row_num =  replace(test1, !is.na(test1),
       seq_along(test1[!is.na(test1)]))) %>%
   ungroup

Or with data.table

library(data.table)
setDT(df)[!is.na(test1), row_num := seq_len(.N), by = Day]


问:
QLThumbnailGenerator doesn't generate the thumbnail
I tried using QLThumbnailGenerator in Simulator/Device for iOS and iPadOS, but it does not work.
I'am able to only obtain a standard empty thumbnail but not the rich icon from my files from documents directory.

Some progress with files in sandbox but nothing useful.

Do you make it work?
Maybe something with the permission is wrong...but what? From my app I am able to list files, and read (open) them.

```<code>@IBAction func generateDidSelect(_ sender: Any) {

    let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
    print("DOC: \(docDir)")

    let absPath = URL(fileURLWithPath: docDir ?? "").appendingPathComponent("flowers.png").absoluteString
    //[[NSBundle mainBundle]URLForResource:@"flowers" withExtension:@"png"];
    let fileURL = URL(fileURLWithPath: absPath)
    fileURL.startAccessingSecurityScopedResource()

    let size = CGSize(width: 200, height: 200)
    let scale = UIScreen.main.scale

    let isFile = fileURL.isFile()
    let exists = FileManager.default.fileExists(atPath: fileURL.path)
    print("isFILE? \(isFile ? "YES" : "NO") exists? \(exists ? "YES" : "NO") \nFILE: \(fileURL)")

    let request = QLThumbnailGenerationRequest(fileAtURL: fileURL, size: size, scale: scale, representationTypes: QLThumbnailGenerationRequestRepresentationTypeAll)
    //request.iconMode = YES;

    QLThumbnailGenerator.shared().generateRepresentations(for: request, updateHandler: { thumbnail, type, error i

        DispatchQueue.main.async(execute: {

            print(String(format: "*** TYPE: %ld ****", Int(type)))
            let uiimage = thumbnail?.uiImage
            let cgImage = thumbnail?.cgImage

            if let uiimage = uiimage {
                print("uiimage: \(uiimage)")
            }
            if let cgImage = cgImage {
                print("cgImage: \(cgImage)")
           }

            if uiimage != nil {
                self.thumbnailImageView.image = uiimage
            }

            if error != nil {
                if let error = error {
                    print("ERROR: \(error)")
                }
                //self.thumbnailImageView.image = [UIImage imageWithContentsOfFile:fileURL.path]; // test read, works
            }
        })
    })

}

</code>```

Then I tried with an image into the bundle.

Getting the file url with:

```<code>Bundle.main.url(forResource: "flowers", withExtension: "png")
</code>```

and it magically works! ...but no with fileURLWithPath method.

But, accessing the same identical file uploaded via iTunes into the Documents directory of the app i get a read error.

```<code>2019-10-01 12:41:27.167091+0200 test_thumb_obj[618:57118] DOC: /var/mobile/Containers/Data/Application/BE4A5950-5D24-4620-A1FE-B837222E8B64/Documents
2019-10-01 12:41:27.196739+0200 test_thumb_obj[618:57118] isFILE? YES exists? YES
FILE: file:///var/mobile/Containers/Data/Application/BE4A5950-5D24-4620-A1FE-B837222E8B64/Documents/flowers.png
2019-10-01 12:41:27.233546+0200 test_thumb_obj[618:57118] *** TYPE: 0 ****
2019-10-01 12:41:27.233788+0200 test_thumb_obj[618:57118] uiimage:
2019-10-01 12:41:27.233858+0200 test_thumb_obj[618:57118] cgImage:  (DP)
  < (kCGColorSpaceDeviceRGB)>
  width = 493, height = 640, bpc = 8, bpp = 32, row bytes = 1984
  kCGImageAlphaPremultipliedFirst | kCGImageByteOrder32Little  | kCGImagePixelFormatPacked
  is mask? No, has masking color? No, has soft mask? No, has matte? No, should interpolate? Yes
2019-10-01 12:41:27.234761+0200 test_thumb_obj[618:57118] *** TYPE: 1 ****
2019-10-01 12:41:27.234836+0200 test_thumb_obj[618:57118] uiimage: (null)
2019-10-01 12:41:27.234865+0200 test_thumb_obj[618:57118] cgImage: (null)
2019-10-01 12:41:27.234943+0200 test_thumb_obj[618:57118] ERROR: Error Domain=QLThumbnailErrorDomain Code=2 "No cached thumbnail"
2019-10-01 12:41:27.262228+0200 test_thumb_obj[618:57118] *** TYPE: 2 ****
2019-10-01 12:41:27.262317+0200 test_thumb_obj[618:57118] uiimage: (null)
2019-10-01 12:41:27.262349+0200 test_thumb_obj[618:57118] cgImage: (null)
2019-10-01 12:41:27.262452+0200 test_thumb_obj[618:57118] ERROR: Error Domain=QLThumbnailErrorDomain Code=0 "Could not generate a thum
bnail" UserInfo={NSUnderlyingError=0x281676940 {Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened."}}
</code>```

The only image a get i TYPE = 0, the white empty one.

And, as before, on simulator nothing good....

```<code>Error Domain=NSPOSIXErrorDomain Code=22 "couldn't issue sandbox extension com.apple.app-sandbox.read for...
</code>```

Some test i missed to make it working?

答:
This worked for me, I create this method:

import QuickLook

...

func generateThumbnailFromQuickLook(url: URL,
                                    type: QLThumbnailGenerator.Request.RepresentationTypes,
                                    completionHandler: @escaping (Bool, UIImage?) -> Void) {
    let size = CGSize(width: 300, height: 250)
    let scale = UIScreen.main.scale

    let request = QLThumbnailGenerator.Request(fileAt: url,
                                               size: size,
                                               scale: scale,
                                               representationTypes: type)

    let generator = QLThumbnailGenerator.shared

    generator.generateBestRepresentation(for: request) { thumbnail, error in
        if let error = error {
            print(error)
        }

        completionHandler(thumbnail != nil, thumbnail?.uiImage)
    }
}
```
<p>Then I check if the representation type <code>thumbnail</code> fail. If it fails, I try to get the representation type <code>all</code>:</p>
<pre class="lang-swift prettyprint-override"><code>let url: URL = <url file>

generateThumbnailFromQuickLook(url: url, type: .thumbnail) { success, image in
    if success == false {
        generateThumbnailFromQuickLook(url: url, type: .all) { success, image in
            // use the thumbnail here
        }
    } else if let image = image {
        // use the thumbnail here
    }
}

</code>```

Body:
I tried using QLThumbnailGenerator in Simulator/Device for iOS and iPadOS, but it does not work.
I'am able to only obtain a standard empty thumbnail but not the rich icon from my files from documents directory.

Some progress with files in sandbox but nothing useful.

Do you make it work?
Maybe something with the permission is wrong...but what? From my app I am able to list files, and read (open) them.

@IBAction func generateDidSelect(_ sender: Any) {

    let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
    print("DOC: \(docDir)")

    let absPath = URL(fileURLWithPath: docDir ?? "").appendingPathComponent("flowers.png").absoluteString
    //[[NSBundle mainBundle]URLForResource:@"flowers" withExtension:@"png"];
    let fileURL = URL(fileURLWithPath: absPath)
    fileURL.startAccessingSecurityScopedResource()

    let size = CGSize(width: 200, height: 200)
    let scale = UIScreen.main.scale

    let isFile = fileURL.isFile()
    let exists = FileManager.default.fileExists(atPath: fileURL.path)
    print("isFILE? \(isFile ? "YES" : "NO") exists? \(exists ? "YES" : "NO") \nFILE: \(fileURL)")

    let request = QLThumbnailGenerationRequest(fileAtURL: fileURL, size: size, scale: scale, representationTypes: QLThumbnailGenerationRequestRepresentationTypeAll)
    //request.iconMode = YES;

    QLThumbnailGenerator.shared().generateRepresentations(for: request, updateHandler: { thumbnail, type, error i

        DispatchQueue.main.async(execute: {

            print(String(format: "*** TYPE: %ld ****", Int(type)))
            let uiimage = thumbnail?.uiImage
            let cgImage = thumbnail?.cgImage

            if let uiimage = uiimage {
                print("uiimage: \(uiimage)")
            }
            if let cgImage = cgImage {
                print("cgImage: \(cgImage)")
           }

            if uiimage != nil {
                self.thumbnailImageView.image = uiimage
            }

            if error != nil {
                if let error = error {
                    print("ERROR: \(error)")
                }
                //self.thumbnailImageView.image = [UIImage imageWithContentsOfFile:fileURL.path]; // test read, works
            }
        })
    })

}

Then I tried with an image into the bundle.

Getting the file url with:

Bundle.main.url(forResource: "flowers", withExtension: "png")

and it magically works! ...but no with fileURLWithPath method.

But, accessing the same identical file uploaded via iTunes into the Documents directory of the app i get a read error.

2019-10-01 12:41:27.167091+0200 test_thumb_obj[618:57118] DOC: /var/mobile/Containers/Data/Application/BE4A5950-5D24-4620-A1FE-B837222E8B64/Documents
2019-10-01 12:41:27.196739+0200 test_thumb_obj[618:57118] isFILE? YES exists? YES
FILE: file:///var/mobile/Containers/Data/Application/BE4A5950-5D24-4620-A1FE-B837222E8B64/Documents/flowers.png
2019-10-01 12:41:27.233546+0200 test_thumb_obj[618:57118] *** TYPE: 0 ****
2019-10-01 12:41:27.233788+0200 test_thumb_obj[618:57118] uiimage:
2019-10-01 12:41:27.233858+0200 test_thumb_obj[618:57118] cgImage:  (DP)
  < (kCGColorSpaceDeviceRGB)>
  width = 493, height = 640, bpc = 8, bpp = 32, row bytes = 1984
  kCGImageAlphaPremultipliedFirst | kCGImageByteOrder32Little  | kCGImagePixelFormatPacked
  is mask? No, has masking color? No, has soft mask? No, has matte? No, should interpolate? Yes
2019-10-01 12:41:27.234761+0200 test_thumb_obj[618:57118] *** TYPE: 1 ****
2019-10-01 12:41:27.234836+0200 test_thumb_obj[618:57118] uiimage: (null)
2019-10-01 12:41:27.234865+0200 test_thumb_obj[618:57118] cgImage: (null)
2019-10-01 12:41:27.234943+0200 test_thumb_obj[618:57118] ERROR: Error Domain=QLThumbnailErrorDomain Code=2 "No cached thumbnail"
2019-10-01 12:41:27.262228+0200 test_thumb_obj[618:57118] *** TYPE: 2 ****
2019-10-01 12:41:27.262317+0200 test_thumb_obj[618:57118] uiimage: (null)
2019-10-01 12:41:27.262349+0200 test_thumb_obj[618:57118] cgImage: (null)
2019-10-01 12:41:27.262452+0200 test_thumb_obj[618:57118] ERROR: Error Domain=QLThumbnailErrorDomain Code=0 "Could not generate a thum
bnail" UserInfo={NSUnderlyingError=0x281676940 {Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened."}}

The only image a get i TYPE = 0, the white empty one.

And, as before, on simulator nothing good....

Error Domain=NSPOSIXErrorDomain Code=22 "couldn't issue sandbox extension com.apple.app-sandbox.read for...

Some test i missed to make it working?

Body:
This worked for me, I create this method:

import QuickLook

...

func generateThumbnailFromQuickLook(url: URL,
                                    type: QLThumbnailGenerator.Request.RepresentationTypes,
                                    completionHandler: @escaping (Bool, UIImage?) -> Void) {
    let size = CGSize(width: 300, height: 250)
    let scale = UIScreen.main.scale

    let request = QLThumbnailGenerator.Request(fileAt: url,
                                               size: size,
                                               scale: scale,
                                               representationTypes: type)

    let generator = QLThumbnailGenerator.shared

    generator.generateBestRepresentation(for: request) { thumbnail, error in
        if let error = error {
            print(error)
        }

        completionHandler(thumbnail != nil, thumbnail?.uiImage)
    }
}

Then I check if the representation type thumbnail fail. If it fails, I try to get the representation type all:

let url: URL = <url file>

generateThumbnailFromQuickLook(url: url, type: .thumbnail) { success, image in
    if success == false {
        generateThumbnailFromQuickLook(url: url, type: .all) { success, image in
            // use the thumbnail here
        }
    } else if let image = image {
        // use the thumbnail here
    }
}


问:
Determining if a knight can pass through all cells in a 2d array - if so print board
I need an advice regarding this problem called "Knight Path".
Given an n*n board whose cells are initialized to 0, I need to determine, given an arbitrary Knight's position, if the knight can pass through every cell on the board exactly once, where every cell the Knight had visited will be marked as counter, counting from: 1 - n^2.
If a path is possible, I need to print the board. I need to print all the valid boards.
The knight, for those who do not know the rules for chess, can move either up or down one square vertically and over two squares horizontally OR up or down two squares vertically and over one square horizontally.

For example given a 5*5 board, starting at (0,0) the method should print:

```<code>{{1,16,11,6,21},
{10,5,20,15,12},
{17,2,13,22,7},
{4,9,24,19,14},
{25,18,3,8,23}};
</code>```

The above out put would be one of few, as there could be different other ways considering different initial positions.
I've written the below code but it doesn't print anything. I need to spot the logic flaws here so I can make it work.

```<code>public class KnightDemo {

    static int counter = 1;
    public static void KnightPath(int[][] b, int i, int j) {
        b[i][j] = counter;
        if (counter == b.length * b[0].length) {
            printMatrix(b);
            return;
        } else {
            counter++;

            if (isValid(b, i - 1, j + 2) && b[i - 1][j + 2] == 0) {
                KnightPath(b, i - 1, j + 2);
            } else {
                return;
            }
            if (isValid(b, i - 2, j + 1) && b[i - 1][j + 1] == 0) {
                KnightPath(b, i - 2, j + 1);
            } else {
                return;
            }
            if (isValid(b, i - 1, j - 2) && b[i - 1][j - 2] == 0) {
                KnightPath(b, i - 1, j - 2);
            } else {
                return;
            }
            if (isValid(b, i - 2, j - 1) && b[i - 2][j - 1] == 0) {
                KnightPath(b, i - 2, j - 1);
            } else {
                return;
            }
            if (isValid(b, i + 2, j - 1) && b[i + 2][j - 1] == 0) {
                KnightPath(b, i + 2, j - 1);
            } else {
                return;
            }
            if (isValid(b, i + 1, j - 2) && b[i + 1][j - 2] == 0) {
                KnightPath(b, i + 1, j - 2);
            } else {
                return;
            }
            if (isValid(b, i + 1, j + 2) && b[i + 1][j + 2] == 0) {
                KnightPath(b, i + 1, j + 2);
            } else {
                return;
            }
            if (isValid(b, i + 2, j + 1) && b[i + 2][j + 1] == 0) {
                KnightPath(b, i + 2, j + 1);
            } else {
                return;
            }

        }
    }

    public static boolean isValid(int[][] a, int i, int j) {
        if (i > a.length - 1 || i < 0 || j > a[0].length - 1 || j < 0) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        int[][] b = new int[5][5];
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                KnightPath(b, i, j);
            }
        }
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] rows: matrix) {
            StringBuilder buff = new StringBuilder();
            buff.append("[");
            for (int i = 0; i < rows.length; i++) {
                int value = rows[i];
                buff.append(value);
                if (i < rows.length - 1) {
                    buff.append(", ");
                }
            }
            buff.append("]");
            System.out.println(buff.toString());
        }
    }
}
</code>```

The output is

```<code>[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20]
[21, 22, 23, 24, 25]
</code>```

答:
Based on the OP's explanation in the comments section, the goal is to map out all possible paths a knight can take from a location on the board. Basically, given the knight's location b[i][j], calculate all legal paths.

If a knight is at {0, 0}, the knight has only two legal paths that end in {1, 2} and {2, 1}. The idea here is to capture that in a map. Then, move on to the next location on the board (i.e. {1, 0}) and repeat the process. Since each board location can be identified as an integer (counter), we can use it to map the paths...

```<code>0=[{1, 2}, {2, 1}]
1=[{2, 2}, {1, 3}, {2, 0}]
...
n=[{n^-2 - 3, n^-2 - 2}, {n^-2 - 2, n^-2 - 3}] // last location is always a corner
</code>```

To make it simple, I decided to create a Java record of coordinates to store the {x, y} coordinates of the end location of a given path, making my map <Integer, Set<Coordinates>>

The logic here is quite simple. First, seed the map with empty lists for each one corresponding location in the matrix. Then, iterate through the matrix (2D array) and calculate all the legal paths a knight can take from this location. For each legal path, add the Coordinates of the end location of the path. I used a Set to eliminate duplicate coordinates.

My solution (perhaps not optimal) is as follows (used OP code as baseline) - Need Java 15 or later to run. For Java 14 or earlier, replace Coordinates with an Integer[] of length 2, and store the coordinates in it.

```<code>public class KnightDemo {

    static int counter = 0;
    static Map<Integer, Set<Coordinates>> map = new HashMap<>();

    public static void KnightPath(int[][] b, int i, int j) {
        Set<Coordinates> paths = map.get(counter);
        if (isValid(b, i - 1, j + 2)) {
            paths.add(new Coordinates(i - 1, j + 2));
            map.put(counter, paths);
        }
        if (isValid(b, i - 2, j + 1)) {
            paths.add(new Coordinates(i - 2, j + 1));
            map.put(counter, paths);
        }
        if (isValid(b, i - 1, j - 2)) {
            paths.add(new Coordinates(i - 1, j - 2));
            map.put(counter, paths);
        }
        if (isValid(b, i - 2, j - 1)) {
            paths.add(new Coordinates(i - 2, j - 1));
            map.put(counter, paths);
        }
        if (isValid(b, i + 2, j - 1)) {
            paths.add(new Coordinates(i + 2, j - 1));
            map.put(counter, paths);
        }
        if (isValid(b, i + 1, j - 2)) {
            paths.add(new Coordinates(i + 1, j - 2));
            map.put(counter, paths);
        }
        if (isValid(b, i + 1, j + 2)) {
            paths.add(new Coordinates(i + 1, j + 2));
            map.put(counter, paths);
        }
        if (isValid(b, i + 2, j + 1)) {
            paths.add(new Coordinates(i + 2, j + 1));
            map.put(counter, paths);
        }

        counter++;
    }

    public static boolean isValid(int[][] a, int i, int j) {
        return i >= 0 && i < a.length && j >= 0 && j < a[0].length;
    }

    public static void main(String[] args) {
        int[][] b = new int[5][5];
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                map.put(counter, new HashSet<>()); // add a new set before calculating paths
                KnightPath(b, i, j);
            }
        }
        map.entrySet().stream().forEach(System.out::println);
    }

    private static record Coordinates(int row, int col) {

        @Override
        public String toString() {
            return "{" + row + ", " + col + "}";
        }
    }
}
</code>```

The program outputs:

```<code>0=[{1, 2}, {2, 1}]
1=[{2, 2}, {1, 3}, {2, 0}]
2=[{2, 3}, {1, 4}, {2, 1}, {1, 0}]
3=[{2, 2}, {1, 1}, {2, 4}]
4=[{2, 3}, {1, 2}]
5=[{2, 2}, {0, 2}, {3, 1}]
6=[{2, 3}, {0, 3}, {3, 0}, {3, 2}]
7=[{0, 0}, {3, 3}, {2, 4}, {0, 4}, {3, 1}, {2, 0}]
8=[{0, 1}, {3, 4}, {3, 2}, {2, 1}]
9=[{3, 3}, {2, 2}, {0, 2}]
10=[{1, 2}, {0, 1}, {4, 1}, {3, 2}]
11=[{0, 0}, {3, 3}, {1, 3}, {0, 2}, {4, 0}, {4, 2}]
12=[{0, 1}, {3, 4}, {1, 4}, {0, 3}, {4, 1}, {3, 0}, {1, 0}, {4, 3}]
13=[{1, 1}, {4, 4}, {0, 2}, {0, 4}, {4, 2}, {3, 1}]
14=[{1, 2}, {0, 3}, {4, 3}, {3, 2}]
15=[{2, 2}, {1, 1}, {4, 2}]
16=[{2, 3}, {1, 2}, {1, 0}, {4, 3}]
17=[{1, 1}, {4, 4}, {2, 4}, {1, 3}, {4, 0}, {2, 0}]
18=[{1, 2}, {1, 4}, {4, 1}, {2, 1}]
19=[{2, 2}, {1, 3}, {4, 2}]
20=[{3, 2}, {2, 1}]
21=[{3, 3}, {2, 2}, {2, 0}]
22=[{3, 4}, {2, 3}, {3, 0}, {2, 1}]
23=[{2, 2}, {2, 4}, {3, 1}]
24=[{2, 3}, {3, 2}]
</code>```

UPDATE: Can you use this in a real game of chess?

Yes, you can! Suppose you seed the matrix with black and white. You could enhance the logic so that, if the end location corresponds to your color, you don't add as a valid path since it is blocked by one of your pieces.

SECOND UPDATE: Same code but using Coordinate object as key

```<code>public class KnightDemo {

    static int counter = 0;
    static Map<Coordinates, Set<Coordinates>> map = new HashMap<>();

    public static void KnightPath(int[][] b, Coordinates coordinates) {

        Set<Coordinates> paths = map.get(coordinates);
        if (isValid(b, coordinates.row() - 1, coordinates.col() + 2)) {
            paths.add(new Coordinates(coordinates.row() - 1, coordinates.col() + 2));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() - 2, coordinates.col() + 1)) {
            paths.add(new Coordinates(coordinates.row() - 2, coordinates.col() + 1));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() - 1, coordinates.col() - 2)) {
            paths.add(new Coordinates(coordinates.row() - 1, coordinates.col() - 2));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() - 2, coordinates.col() - 1)) {
            paths.add(new Coordinates(coordinates.row() - 2, coordinates.col() - 1));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() + 2, coordinates.col() - 1)) {
            paths.add(new Coordinates(coordinates.row() + 2, coordinates.col() - 1));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() + 1, coordinates.col() - 2)) {
            paths.add(new Coordinates(coordinates.row() + 1, coordinates.col() - 2));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() + 1, coordinates.col() + 2)) {
            paths.add(new Coordinates(coordinates.row() + 1, coordinates.col() + 2));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() + 2, coordinates.col() + 1)) {
            paths.add(new Coordinates(coordinates.row() + 2, coordinates.col() + 1));
            map.put(coordinates, paths);
        }
    }

    public static boolean isValid(int[][] a, int i, int j) {
        return i >= 0 && i < a.length && j >= 0 && j < a[0].length;
    }

    public static void main(String[] args) {
        int[][] b = new int[5][5];
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                Coordinates coordinates = new Coordinates(i, j);
                map.put(coordinates, new HashSet<>());
                KnightPath(b, coordinates);
                counter++;
            }
        }
        map.entrySet().stream().forEach(System.out::println);
    }

    private static record Coordinates(int row, int col) {

        @Override
        public String toString() {
            return "{" + row + ", " + col + "}";
        }
    }
}
</code>```

Outputs:

```<code>{0, 0}=[{1, 2}, {2, 1}]
{2, 2}=[{0, 1}, {3, 4}, {1, 4}, {0, 3}, {4, 1}, {3, 0}, {1, 0}, {4, 3}]
{4, 4}=[{2, 3}, {3, 2}]
{0, 1}=[{2, 2}, {1, 3}, {2, 0}]
{2, 3}=[{1, 1}, {4, 4}, {0, 2}, {0, 4}, {4, 2}, {3, 1}]
{0, 2}=[{2, 3}, {1, 4}, {2, 1}, {1, 0}]
{2, 4}=[{1, 2}, {0, 3}, {4, 3}, {3, 2}]
{0, 3}=[{2, 2}, {1, 1}, {2, 4}]
{0, 4}=[{2, 3}, {1, 2}]
{3, 0}=[{2, 2}, {1, 1}, {4, 2}]
{3, 1}=[{2, 3}, {1, 2}, {1, 0}, {4, 3}]
{1, 0}=[{2, 2}, {0, 2}, {3, 1}]
{3, 2}=[{1, 1}, {4, 4}, {2, 4}, {1, 3}, {4, 0}, {2, 0}]
{1, 1}=[{2, 3}, {0, 3}, {3, 0}, {3, 2}]
{3, 3}=[{1, 2}, {1, 4}, {4, 1}, {2, 1}]
{1, 2}=[{0, 0}, {3, 3}, {2, 4}, {0, 4}, {3, 1}, {2, 0}]
{3, 4}=[{2, 2}, {1, 3}, {4, 2}]
{1, 3}=[{0, 1}, {3, 4}, {3, 2}, {2, 1}]
{1, 4}=[{3, 3}, {2, 2}, {0, 2}]
{4, 0}=[{3, 2}, {2, 1}]
{4, 1}=[{3, 3}, {2, 2}, {2, 0}]
{2, 0}=[{1, 2}, {0, 1}, {4, 1}, {3, 2}]
{4, 2}=[{3, 4}, {2, 3}, {3, 0}, {2, 1}]
{2, 1}=[{0, 0}, {3, 3}, {1, 3}, {0, 2}, {4, 0}, {4, 2}]
{4, 3}=[{2, 2}, {2, 4}, {3, 1}]
</code>```

They don't print in the same order, but you can tell that coordinates {2, 2} is the same set as counter==12 in the previous example. Cell {2, 2} is the 13th cell from the top-left.

Body:
I need an advice regarding this problem called "Knight Path".
Given an n*n board whose cells are initialized to 0, I need to determine, given an arbitrary Knight's position, if the knight can pass through every cell on the board exactly once, where every cell the Knight had visited will be marked as counter, counting from: 1 - n^2.
If a path is possible, I need to print the board. I need to print all the valid boards.
The knight, for those who do not know the rules for chess, can move either up or down one square vertically and over two squares horizontally OR up or down two squares vertically and over one square horizontally.

For example given a 5*5 board, starting at (0,0) the method should print:

{{1,16,11,6,21},
{10,5,20,15,12},
{17,2,13,22,7},
{4,9,24,19,14},
{25,18,3,8,23}};

The above out put would be one of few, as there could be different other ways considering different initial positions.
I've written the below code but it doesn't print anything. I need to spot the logic flaws here so I can make it work.

public class KnightDemo {

    static int counter = 1;
    public static void KnightPath(int[][] b, int i, int j) {
        b[i][j] = counter;
        if (counter == b.length * b[0].length) {
            printMatrix(b);
            return;
        } else {
            counter++;

            if (isValid(b, i - 1, j + 2) && b[i - 1][j + 2] == 0) {
                KnightPath(b, i - 1, j + 2);
            } else {
                return;
            }
            if (isValid(b, i - 2, j + 1) && b[i - 1][j + 1] == 0) {
                KnightPath(b, i - 2, j + 1);
            } else {
                return;
            }
            if (isValid(b, i - 1, j - 2) && b[i - 1][j - 2] == 0) {
                KnightPath(b, i - 1, j - 2);
            } else {
                return;
            }
            if (isValid(b, i - 2, j - 1) && b[i - 2][j - 1] == 0) {
                KnightPath(b, i - 2, j - 1);
            } else {
                return;
            }
            if (isValid(b, i + 2, j - 1) && b[i + 2][j - 1] == 0) {
                KnightPath(b, i + 2, j - 1);
            } else {
                return;
            }
            if (isValid(b, i + 1, j - 2) && b[i + 1][j - 2] == 0) {
                KnightPath(b, i + 1, j - 2);
            } else {
                return;
            }
            if (isValid(b, i + 1, j + 2) && b[i + 1][j + 2] == 0) {
                KnightPath(b, i + 1, j + 2);
            } else {
                return;
            }
            if (isValid(b, i + 2, j + 1) && b[i + 2][j + 1] == 0) {
                KnightPath(b, i + 2, j + 1);
            } else {
                return;
            }

        }
    }

    public static boolean isValid(int[][] a, int i, int j) {
        if (i > a.length - 1 || i < 0 || j > a[0].length - 1 || j < 0) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        int[][] b = new int[5][5];
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                KnightPath(b, i, j);
            }
        }
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] rows: matrix) {
            StringBuilder buff = new StringBuilder();
            buff.append("[");
            for (int i = 0; i < rows.length; i++) {
                int value = rows[i];
                buff.append(value);
                if (i < rows.length - 1) {
                    buff.append(", ");
                }
            }
            buff.append("]");
            System.out.println(buff.toString());
        }
    }
}

The output is

[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20]
[21, 22, 23, 24, 25]

Body:
Based on the OP's explanation in the comments section, the goal is to map out all possible paths a knight can take from a location on the board. Basically, given the knight's location b[i][j], calculate all legal paths.

If a knight is at {0, 0}, the knight has only two legal paths that end in {1, 2} and {2, 1}. The idea here is to capture that in a map. Then, move on to the next location on the board (i.e. {1, 0}) and repeat the process. Since each board location can be identified as an integer (counter), we can use it to map the paths...

0=[{1, 2}, {2, 1}]
1=[{2, 2}, {1, 3}, {2, 0}]
...
n=[{n^-2 - 3, n^-2 - 2}, {n^-2 - 2, n^-2 - 3}] // last location is always a corner

To make it simple, I decided to create a Java record of coordinates to store the {x, y} coordinates of the end location of a given path, making my map <Integer, Set<Coordinates>>

The logic here is quite simple. First, seed the map with empty lists for each one corresponding location in the matrix. Then, iterate through the matrix (2D array) and calculate all the legal paths a knight can take from this location. For each legal path, add the Coordinates of the end location of the path. I used a Set to eliminate duplicate coordinates.

My solution (perhaps not optimal) is as follows (used OP code as baseline) - Need Java 15 or later to run. For Java 14 or earlier, replace Coordinates with an Integer[] of length 2, and store the coordinates in it.

public class KnightDemo {

    static int counter = 0;
    static Map<Integer, Set<Coordinates>> map = new HashMap<>();

    public static void KnightPath(int[][] b, int i, int j) {
        Set<Coordinates> paths = map.get(counter);
        if (isValid(b, i - 1, j + 2)) {
            paths.add(new Coordinates(i - 1, j + 2));
            map.put(counter, paths);
        }
        if (isValid(b, i - 2, j + 1)) {
            paths.add(new Coordinates(i - 2, j + 1));
            map.put(counter, paths);
        }
        if (isValid(b, i - 1, j - 2)) {
            paths.add(new Coordinates(i - 1, j - 2));
            map.put(counter, paths);
        }
        if (isValid(b, i - 2, j - 1)) {
            paths.add(new Coordinates(i - 2, j - 1));
            map.put(counter, paths);
        }
        if (isValid(b, i + 2, j - 1)) {
            paths.add(new Coordinates(i + 2, j - 1));
            map.put(counter, paths);
        }
        if (isValid(b, i + 1, j - 2)) {
            paths.add(new Coordinates(i + 1, j - 2));
            map.put(counter, paths);
        }
        if (isValid(b, i + 1, j + 2)) {
            paths.add(new Coordinates(i + 1, j + 2));
            map.put(counter, paths);
        }
        if (isValid(b, i + 2, j + 1)) {
            paths.add(new Coordinates(i + 2, j + 1));
            map.put(counter, paths);
        }

        counter++;
    }

    public static boolean isValid(int[][] a, int i, int j) {
        return i >= 0 && i < a.length && j >= 0 && j < a[0].length;
    }

    public static void main(String[] args) {
        int[][] b = new int[5][5];
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                map.put(counter, new HashSet<>()); // add a new set before calculating paths
                KnightPath(b, i, j);
            }
        }
        map.entrySet().stream().forEach(System.out::println);
    }

    private static record Coordinates(int row, int col) {

        @Override
        public String toString() {
            return "{" + row + ", " + col + "}";
        }
    }
}

The program outputs:

0=[{1, 2}, {2, 1}]
1=[{2, 2}, {1, 3}, {2, 0}]
2=[{2, 3}, {1, 4}, {2, 1}, {1, 0}]
3=[{2, 2}, {1, 1}, {2, 4}]
4=[{2, 3}, {1, 2}]
5=[{2, 2}, {0, 2}, {3, 1}]
6=[{2, 3}, {0, 3}, {3, 0}, {3, 2}]
7=[{0, 0}, {3, 3}, {2, 4}, {0, 4}, {3, 1}, {2, 0}]
8=[{0, 1}, {3, 4}, {3, 2}, {2, 1}]
9=[{3, 3}, {2, 2}, {0, 2}]
10=[{1, 2}, {0, 1}, {4, 1}, {3, 2}]
11=[{0, 0}, {3, 3}, {1, 3}, {0, 2}, {4, 0}, {4, 2}]
12=[{0, 1}, {3, 4}, {1, 4}, {0, 3}, {4, 1}, {3, 0}, {1, 0}, {4, 3}]
13=[{1, 1}, {4, 4}, {0, 2}, {0, 4}, {4, 2}, {3, 1}]
14=[{1, 2}, {0, 3}, {4, 3}, {3, 2}]
15=[{2, 2}, {1, 1}, {4, 2}]
16=[{2, 3}, {1, 2}, {1, 0}, {4, 3}]
17=[{1, 1}, {4, 4}, {2, 4}, {1, 3}, {4, 0}, {2, 0}]
18=[{1, 2}, {1, 4}, {4, 1}, {2, 1}]
19=[{2, 2}, {1, 3}, {4, 2}]
20=[{3, 2}, {2, 1}]
21=[{3, 3}, {2, 2}, {2, 0}]
22=[{3, 4}, {2, 3}, {3, 0}, {2, 1}]
23=[{2, 2}, {2, 4}, {3, 1}]
24=[{2, 3}, {3, 2}]

UPDATE: Can you use this in a real game of chess?

Yes, you can! Suppose you seed the matrix with black and white. You could enhance the logic so that, if the end location corresponds to your color, you don't add as a valid path since it is blocked by one of your pieces.

SECOND UPDATE: Same code but using Coordinate object as key

public class KnightDemo {

    static int counter = 0;
    static Map<Coordinates, Set<Coordinates>> map = new HashMap<>();

    public static void KnightPath(int[][] b, Coordinates coordinates) {

        Set<Coordinates> paths = map.get(coordinates);
        if (isValid(b, coordinates.row() - 1, coordinates.col() + 2)) {
            paths.add(new Coordinates(coordinates.row() - 1, coordinates.col() + 2));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() - 2, coordinates.col() + 1)) {
            paths.add(new Coordinates(coordinates.row() - 2, coordinates.col() + 1));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() - 1, coordinates.col() - 2)) {
            paths.add(new Coordinates(coordinates.row() - 1, coordinates.col() - 2));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() - 2, coordinates.col() - 1)) {
            paths.add(new Coordinates(coordinates.row() - 2, coordinates.col() - 1));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() + 2, coordinates.col() - 1)) {
            paths.add(new Coordinates(coordinates.row() + 2, coordinates.col() - 1));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() + 1, coordinates.col() - 2)) {
            paths.add(new Coordinates(coordinates.row() + 1, coordinates.col() - 2));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() + 1, coordinates.col() + 2)) {
            paths.add(new Coordinates(coordinates.row() + 1, coordinates.col() + 2));
            map.put(coordinates, paths);
        }
        if (isValid(b, coordinates.row() + 2, coordinates.col() + 1)) {
            paths.add(new Coordinates(coordinates.row() + 2, coordinates.col() + 1));
            map.put(coordinates, paths);
        }
    }

    public static boolean isValid(int[][] a, int i, int j) {
        return i >= 0 && i < a.length && j >= 0 && j < a[0].length;
    }

    public static void main(String[] args) {
        int[][] b = new int[5][5];
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                Coordinates coordinates = new Coordinates(i, j);
                map.put(coordinates, new HashSet<>());
                KnightPath(b, coordinates);
                counter++;
            }
        }
        map.entrySet().stream().forEach(System.out::println);
    }

    private static record Coordinates(int row, int col) {

        @Override
        public String toString() {
            return "{" + row + ", " + col + "}";
        }
    }
}

Outputs:

{0, 0}=[{1, 2}, {2, 1}]
{2, 2}=[{0, 1}, {3, 4}, {1, 4}, {0, 3}, {4, 1}, {3, 0}, {1, 0}, {4, 3}]
{4, 4}=[{2, 3}, {3, 2}]
{0, 1}=[{2, 2}, {1, 3}, {2, 0}]
{2, 3}=[{1, 1}, {4, 4}, {0, 2}, {0, 4}, {4, 2}, {3, 1}]
{0, 2}=[{2, 3}, {1, 4}, {2, 1}, {1, 0}]
{2, 4}=[{1, 2}, {0, 3}, {4, 3}, {3, 2}]
{0, 3}=[{2, 2}, {1, 1}, {2, 4}]
{0, 4}=[{2, 3}, {1, 2}]
{3, 0}=[{2, 2}, {1, 1}, {4, 2}]
{3, 1}=[{2, 3}, {1, 2}, {1, 0}, {4, 3}]
{1, 0}=[{2, 2}, {0, 2}, {3, 1}]
{3, 2}=[{1, 1}, {4, 4}, {2, 4}, {1, 3}, {4, 0}, {2, 0}]
{1, 1}=[{2, 3}, {0, 3}, {3, 0}, {3, 2}]
{3, 3}=[{1, 2}, {1, 4}, {4, 1}, {2, 1}]
{1, 2}=[{0, 0}, {3, 3}, {2, 4}, {0, 4}, {3, 1}, {2, 0}]
{3, 4}=[{2, 2}, {1, 3}, {4, 2}]
{1, 3}=[{0, 1}, {3, 4}, {3, 2}, {2, 1}]
{1, 4}=[{3, 3}, {2, 2}, {0, 2}]
{4, 0}=[{3, 2}, {2, 1}]
{4, 1}=[{3, 3}, {2, 2}, {2, 0}]
{2, 0}=[{1, 2}, {0, 1}, {4, 1}, {3, 2}]
{4, 2}=[{3, 4}, {2, 3}, {3, 0}, {2, 1}]
{2, 1}=[{0, 0}, {3, 3}, {1, 3}, {0, 2}, {4, 0}, {4, 2}]
{4, 3}=[{2, 2}, {2, 4}, {3, 1}]

They don't print in the same order, but you can tell that coordinates {2, 2} is the same set as counter==12 in the previous example. Cell {2, 2} is the 13th cell from the top-left.


问:
SQL Statement to Retrieve All New Customers in a Specific Month
I have an ecommerce MySQL database that stores order information in the table 'orders'

I need to select all NEW customers for the month of March. Customers do not have to register to order, so I'm working simply with the customer email and the date time of the order. So select all customer emails that don't feature at all in previous months.

The database table has about 100k rows, and I'm looking for an efficient query.

I'm not too good with SQL (you can probably tell!), but this is what I have...

```<code>SELECT distinct(user_email) FROM orders
WHERE order_datetime > '2011-03-01 00:00:00'
      AND order_datetime < '2011-03-31 23:59:59'
      AND user_email NOT IN (
          SELECT user_email FROM orders
          WHERE order_datetime < '2011-03-01 00:00:00')
GROUP BY user_email
</code>```

Is that a really convoluted way of doing things? :) Please let me know if there's a more speed efficient way...

Thanks, Rich

答: That's a pretty reasonable implementation - though "group by" is redundant; DISTINCT is not an aggregate function (http://www.w3schools.com/sql/sql_groupby.asp).</p>

Body:
I have an ecommerce MySQL database that stores order information in the table 'orders'

I need to select all NEW customers for the month of March. Customers do not have to register to order, so I'm working simply with the customer email and the date time of the order. So select all customer emails that don't feature at all in previous months.

The database table has about 100k rows, and I'm looking for an efficient query.

I'm not too good with SQL (you can probably tell!), but this is what I have...

SELECT distinct(user_email) FROM orders
WHERE order_datetime > '2011-03-01 00:00:00'
      AND order_datetime < '2011-03-31 23:59:59'
      AND user_email NOT IN (
          SELECT user_email FROM orders
          WHERE order_datetime < '2011-03-01 00:00:00')
GROUP BY user_email

Is that a really convoluted way of doing things? :) Please let me know if there's a more speed efficient way...

Thanks, Rich


问:
How do I filter an object with an object using Array.filter similar to lodash?
I am trying to avoid importing lodash for a simple filter. I am trying to do something similar to this...

```<code>// Items
[
  { "title": "a", "name": "a", "location": "here"},
  { "title": "b", "name": "a", "location": "here"},
  { "title": "d", "location": "there"},
]
// Filter
{ "name" : "a", "location": "here" }
</code>```

Should return the first two items. In lodash this is done by something similar to _.filter(Items, Filter). I would like to implement this without lodash or a bunch of code and getting Object.keys. Is there a simple way in modern Javascript to handle this?

答:
I don't believe there's a "simple way in modern Javascript to handle this" but if you don't have a hard requirement on avoiding Object.keys you could write a helper function to do this:

const myItems = [
  { "title": "a", "name": "a", "location": "here"},
  { "title": "b", "name": "a", "location": "here"},
  { "title": "d", "location": "there"},
]

const myFilter = { "name" : "a", "location": "here" };

const filter = (items, filterBy) =>
  items.filter(item =>
    Object.keys(filterBy).every(key => item[key] === filterBy[key])
  )

alert(JSON.stringify(filter(myItems, myFilter)));```

Body:
I am trying to avoid importing lodash for a simple filter. I am trying to do something similar to this...

// Items
[
  { "title": "a", "name": "a", "location": "here"},
  { "title": "b", "name": "a", "location": "here"},
  { "title": "d", "location": "there"},
]
// Filter
{ "name" : "a", "location": "here" }

Should return the first two items. In lodash this is done by something similar to _.filter(Items, Filter). I would like to implement this without lodash or a bunch of code and getting Object.keys. Is there a simple way in modern Javascript to handle this?


问:
How to tackle time limit exceeded error in leetcode
I've wrote my code for Longest Common Prefix in LeetCode, but it was returned "Time Limit Exceeded".

There is no specific error message, so I have no idea how to fix my code to pass test cases.

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:

        #find the number of shortest characters
        shortest_num = 0
        nums = [0] * len(strs)
        for i in range(len(strs)):
            nums[i] = len(strs[i])
            shortest_num = min(nums)

        l1 = strs[0]
        l2 = strs[1]
        l3 = strs[2]

        for j in range(shortest_num):
            tmp = ""
            while l1[j] == l2[j] and l2[j] == l3[j]:
                tmp += l1[j]
            candidate.append(tmp)

        print(max(candidate))
```

<p>Error Message </p>

```Time Limit Exceeded
```

答:
This error comes when you don't have written code in Good Time complexity.
When the Leetcode system ran your code with bigger input your code did not run in optimal time.
There may be some known Algorithm to solve your problem statement. Search the question statement on internet you will find some Algorithm to solve this problem.</p>

Body:
I've wrote my code for Longest Common Prefix in LeetCode, but it was returned "Time Limit Exceeded".

There is no specific error message, so I have no idea how to fix my code to pass test cases.

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:

        #find the number of shortest characters
        shortest_num = 0
        nums = [0] * len(strs)
        for i in range(len(strs)):
            nums[i] = len(strs[i])
            shortest_num = min(nums)

        l1 = strs[0]
        l2 = strs[1]
        l3 = strs[2]

        for j in range(shortest_num):
            tmp = ""
            while l1[j] == l2[j] and l2[j] == l3[j]:
                tmp += l1[j]
            candidate.append(tmp)

        print(max(candidate))

Error Message

Time Limit Exceeded


问:
Chi-square Goodness of Fit for a Test of Normality in r
I want to test for normality of a set of data using Chi-Square Goodness of Fit Test in R just the way I tested for Shapiro- wilk test. I have my sample sizes to be 10, 20,50 and 100 while my replicate is 1000

```<code>## Shapiro- wilk test [sw]

x <- rnorm(x, 0, 1)
out <- t(sapply(c(10, 20, 50, 100), function(x)
  table(replicate(1000,shapiro.test(rnorm(x)))["p.value",] < 0.05)))
row.names(out) <- c(10, 20, 50, 100)
out

#     FALSE TRUE
# 10    947   53
# 20    945   55
# 50    943   57
# 100   943   57
</code>```

答:
You need to make sure the chi test get non negative values.
Try replacing the table calculation with this code:</p>
```<code>table(replicate(1000,chisq.test(x=abs(rnorm(x)),p=c(rep(1/x,x))))["p.value",] < 0.05)

</code>```

Body:
I want to test for normality of a set of data using Chi-Square Goodness of Fit Test in R just the way I tested for Shapiro- wilk test. I have my sample sizes to be 10, 20,50 and 100 while my replicate is 1000

## Shapiro- wilk test [sw]

x <- rnorm(x, 0, 1)
out <- t(sapply(c(10, 20, 50, 100), function(x)
  table(replicate(1000,shapiro.test(rnorm(x)))["p.value",] < 0.05)))
row.names(out) <- c(10, 20, 50, 100)
out

#     FALSE TRUE
# 10    947   53
# 20    945   55
# 50    943   57
# 100   943   57

Body:
You need to make sure the chi test get non negative values.
Try replacing the table calculation with this code:

table(replicate(1000,chisq.test(x=abs(rnorm(x)),p=c(rep(1/x,x))))["p.value",] < 0.05)


问:
Are CSS box shadows officially unsupported for safari <select> fields?
I've looked around but I cannot find any official statements regarding this issue.

The CSS box-shadow simply seems not to be supported in Safari Desktop (at least) for select elements.

Here is the JS Fiddle:
https://jsfiddle.net/t8uhwp3c/

For example this simple select does not show anything around the select element in Safari, but it shows the "shadow" properly in Chrome and Firefox:

```<code><select style="box-shadow:0 0 0 20px red">
    <option>sfasdfasd</option>
</select>
</code>```

This is important as I've seen box-shadows used input-feedback elements in several libraries, but I have not been able to find any reports of this issue happening.

答: If you use -webkit-appearance: none; it will work

Body:
I've looked around but I cannot find any official statements regarding this issue.

The CSS box-shadow simply seems not to be supported in Safari Desktop (at least) for select elements.

Here is the JS Fiddle:
https://jsfiddle.net/t8uhwp3c/

For example this simple select does not show anything around the select element in Safari, but it shows the "shadow" properly in Chrome and Firefox:

<select style="box-shadow:0 0 0 20px red">
    <option>sfasdfasd</option>
</select>

This is important as I've seen box-shadows used input-feedback elements in several libraries, but I have not been able to find any reports of this issue happening.


问:
Unable to display the full image in datagridview cell
I have data grid view with columns product name and product image and I am populating these values coming from database...

i am using winforms  desktop application.....

my problem is I am not able to showing the image in datagridview cell properly ..see the diagram below

i want to display this image in actual product image  column for every cell in that column

this task is very simple in webforms by using datalist  control    but i dont know how to display full image in grid view cell

can any one help on this....

many thanks.......

and this is where i am binding the datagridview by using linq query..

```<code>      private void EquipmentFinder_Load(object sender, EventArgs e)
     {

        var products = from prods in abc.products
                       select new
                       {
                           productid = prods.product_Id,   //0
                           productname =  prods.product_Name, //1
                           productimage = prods.product_Image, //2
                           productprice = prods.product_Price,//3
                           productdescr = prods.product_Description, //4

                       };
        productbindingsource.DataSource = products;
        productgridview.DataSource = productbindingsource;
        productgridview.Columns[0].Visible = false;
        productgridview.Columns[3].Visible = false;
        productgridview.Columns[4].Visible = false;
    }
</code>```

答:
Set DataGridViewImageColumn.ImageLayout property to DataGridViewImageCellLayout.Zoom

If you set to "Stretch" your image will be inproportionally scaled to fit whole cell. And that is probably not what you want.

Set to zoom to have The graphic is uniformly enlarged until it fills the width or height of the containing cell.

By default the value is set to "Normal": The graphic is displayed centered using its native resolution.

Body:
I have data grid view with columns product name and product image and I am populating these values coming from database...

i am using winforms  desktop application.....

my problem is I am not able to showing the image in datagridview cell properly ..see the diagram below

i want to display this image in actual product image  column for every cell in that column

this task is very simple in webforms by using datalist  control    but i dont know how to display full image in grid view cell

can any one help on this....

many thanks.......

and this is where i am binding the datagridview by using linq query..

      private void EquipmentFinder_Load(object sender, EventArgs e)
     {

        var products = from prods in abc.products
                       select new
                       {
                           productid = prods.product_Id,   //0
                           productname =  prods.product_Name, //1
                           productimage = prods.product_Image, //2
                           productprice = prods.product_Price,//3
                           productdescr = prods.product_Description, //4

                       };
        productbindingsource.DataSource = products;
        productgridview.DataSource = productbindingsource;
        productgridview.Columns[0].Visible = false;
        productgridview.Columns[3].Visible = false;
        productgridview.Columns[4].Visible = false;
    }


问:
Counting all descendants in a family tree (python dictionary)
I'm kind of beating my head against a wall here and I'm hoping that someone on stackoverflow can help me.
Let's say I have a python dictionary that looks like:

```<code>{
    'Son1': 'Father',
    'Son2': 'Father',
    'Father': 'Grandfather',
    'Grandfather': 'Great Grandfather',
    'Uncle': 'Grandfather',
    'Cousin': 'Uncle',
}
</code>```

Right, so each key is a person and the corresponding value is that person's parent. All I want to do at the moment is find out how many total descendants a given person has.
I've got a pretty simple function that finds and returns a list of a given person's immediate children.

```<code>def get_kids(person, dictionary):
    kids = []
    for key in dictionary:
        if dictionary[key] == person:
            kids.append(key)
    return kids
</code>```

Which works fine. From there, I keep thinking that all I need to do is write a recursive function that's something like:

```<code>def descendants(person, dictionary, count):
    kids = get_kids(person, dictionary)
    count = count + len(kids)
    for kid in kids:
         descendants(kid, dictionary, count)
    return count
</code>```

But this doesn't work. I think because the 'count' variable resets at the end of a 'line' of descendants, instead of being a running total. e.g. If I run:

```<code>descendants('Grandfather', familydictionary, 0)
</code>```

I get back a value of 2 (instead of the hoped-for 5). Presumably, the count reaches 4 when the function is exploring the 'Father' line, but then drops back down to 3 when it explores the 'Uncle' line, instead. And then, I suppose, the count drops all the way back to 2 when the function finds that 'Cousin' has no kids?
I often struggle with these kinds of recursion problems. What I want to do is pretty straightforward: check if a person has kids and count them, check if their kids have kids and count them, add them to the total ... keep going until there are no more kids. But I get very muddled when I try to actually, well, write the code that does that.
Any help or guidance is appreciated.

答:
You need to sum the descendants of each descendant.

```<code>>>> tree = {
...     'Son1': 'Father',
...     'Son2': 'Father',
...     'Father': 'Grandfather',
...     'Grandfather': 'Great Grandfather',
...     'Uncle': 'Grandfather',
...     'Cousin': 'Uncle',
... }
>>> def descendants(person: str, tree: dict[str, str]) -> int:
...     return sum(
...         1 + descendants(child, tree)
...         for child, parent in tree.items()
...         if parent == person
...     )
...
>>> descendants("Father", tree)
2
>>> descendants("Grandfather", tree)
5
</code>```

If you want a list of the actual descendants, you can use the same basic structure but sum the lists instead of the counts.  This also makes it easier to visualize how the summing leads to the final solution for the recursive case:

```<code>>>> def descendants(person: str, tree: dict[str, str]) -> list[str]:
...     return sum((
...         [child] + descendants(child, tree)
...         for child, parent in tree.items()
...         if parent == person
...     ), [])
...
>>> descendants("Father", tree)
['Son1', 'Son2']
>>> descendants("Uncle", tree)
['Cousin']
>>> descendants("Grandfather", tree)
['Father', 'Son1', 'Son2', 'Uncle', 'Cousin']
</code>```

i.e.:

```<code>descendants("Father", tree) == [] + ["Son1"] + ["Son2"]
descendants("Uncle", tree) == [] + ["Cousin"]
descendants("Grandfather", tree) == [] + ["Father"] + descendants("Father", tree) + ["Uncle"] + descendants("Uncle", tree)
</code>```

Body:
I'm kind of beating my head against a wall here and I'm hoping that someone on stackoverflow can help me.
Let's say I have a python dictionary that looks like:

{
    'Son1': 'Father',
    'Son2': 'Father',
    'Father': 'Grandfather',
    'Grandfather': 'Great Grandfather',
    'Uncle': 'Grandfather',
    'Cousin': 'Uncle',
}

Right, so each key is a person and the corresponding value is that person's parent. All I want to do at the moment is find out how many total descendants a given person has.
I've got a pretty simple function that finds and returns a list of a given person's immediate children.

def get_kids(person, dictionary):
    kids = []
    for key in dictionary:
        if dictionary[key] == person:
            kids.append(key)
    return kids

Which works fine. From there, I keep thinking that all I need to do is write a recursive function that's something like:

def descendants(person, dictionary, count):
    kids = get_kids(person, dictionary)
    count = count + len(kids)
    for kid in kids:
         descendants(kid, dictionary, count)
    return count

But this doesn't work. I think because the 'count' variable resets at the end of a 'line' of descendants, instead of being a running total. e.g. If I run:

descendants('Grandfather', familydictionary, 0)

I get back a value of 2 (instead of the hoped-for 5). Presumably, the count reaches 4 when the function is exploring the 'Father' line, but then drops back down to 3 when it explores the 'Uncle' line, instead. And then, I suppose, the count drops all the way back to 2 when the function finds that 'Cousin' has no kids?
I often struggle with these kinds of recursion problems. What I want to do is pretty straightforward: check if a person has kids and count them, check if their kids have kids and count them, add them to the total ... keep going until there are no more kids. But I get very muddled when I try to actually, well, write the code that does that.
Any help or guidance is appreciated.

Body:
You need to sum the descendants of each descendant.

>>> tree = {
...     'Son1': 'Father',
...     'Son2': 'Father',
...     'Father': 'Grandfather',
...     'Grandfather': 'Great Grandfather',
...     'Uncle': 'Grandfather',
...     'Cousin': 'Uncle',
... }
>>> def descendants(person: str, tree: dict[str, str]) -> int:
...     return sum(
...         1 + descendants(child, tree)
...         for child, parent in tree.items()
...         if parent == person
...     )
...
>>> descendants("Father", tree)
2
>>> descendants("Grandfather", tree)
5

If you want a list of the actual descendants, you can use the same basic structure but sum the lists instead of the counts.  This also makes it easier to visualize how the summing leads to the final solution for the recursive case:

>>> def descendants(person: str, tree: dict[str, str]) -> list[str]:
...     return sum((
...         [child] + descendants(child, tree)
...         for child, parent in tree.items()
...         if parent == person
...     ), [])
...
>>> descendants("Father", tree)
['Son1', 'Son2']
>>> descendants("Uncle", tree)
['Cousin']
>>> descendants("Grandfather", tree)
['Father', 'Son1', 'Son2', 'Uncle', 'Cousin']

i.e.:

descendants("Father", tree) == [] + ["Son1"] + ["Son2"]
descendants("Uncle", tree) == [] + ["Cousin"]
descendants("Grandfather", tree) == [] + ["Father"] + descendants("Father", tree) + ["Uncle"] + descendants("Uncle", tree)


问:
App is crashing in IOS - The client has already been terminated
I have develope flutter app in that I have implement isolate function.
After implementing isolate function app is crashing while app is launch.

In isolate function I am initializing Firebase.

```<code>await Firebase.initializeApp();
</code>```

When process is done in isolate function I am terminating firebase.

```<code>await FirebaseFirestore.instance.terminate();
await FirebaseFirestore.instance.clearPersistence();
</code>```

Below error log is showing while app was crash :

```<code>Incident Identifier: D3E1DB0C-893F-43CA-909A-49C5DA68F8DF
CrashReporter Key:   28B3B2E4-C62D-80C4-F0D1-42AAE9E88E5E
Hardware Model:      iMac18,1
Process:             Runner [16596]
Path:                /Users/USER/Library/Developer/CoreSimulator/Devices/558D2DD4-FC71-4C6F-9007-9D369BEAADB8/data/Containers/Bundle/Application/B212F0D3-7088-46E2-A104-AC24B8079688/Runner.app/Runner
Identifier:          -----
Version:             -----
Code Type:           X86-64 (Native)
Role:                Foreground
Parent Process:      launchd_sim [852]
Coalition:           com.apple.CoreSimulator.SimDevice.558D2DD4-FC71-4C6F-9007-9D369BEAADB8 [800]
Responsible Process: SimulatorTrampoline [844]

Date/Time:           2022-01-13 19:45:40.6432 +0530
Launch Time:         2022-01-13 19:43:15.5481 +0530
OS Version:          macOS 12.0.1 (21A559)
Release Type:        User
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot
CoreSimulator 776.4 - Device: iPhone 8 Plus (********-****-****-****-************) - Runtime: iOS 15.0 (19A339) - DeviceType: iPhone 8 Plus
terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'FIRIllegalStateException', reason: 'The client has already been terminated.'
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot
abort() called
</code>```

Please help me solve this, thanks in advance.

答:
Reverse the order:

```<code>await FirebaseFirestore.instance.clearPersistence();
await FirebaseFirestore.instance.terminate();
</code>```

Once you terminate the instance you cannot attempt to modify its cached data.

Body:
I have develope flutter app in that I have implement isolate function.
After implementing isolate function app is crashing while app is launch.

In isolate function I am initializing Firebase.

await Firebase.initializeApp();

When process is done in isolate function I am terminating firebase.

await FirebaseFirestore.instance.terminate();
await FirebaseFirestore.instance.clearPersistence();

Below error log is showing while app was crash :

Incident Identifier: D3E1DB0C-893F-43CA-909A-49C5DA68F8DF
CrashReporter Key:   28B3B2E4-C62D-80C4-F0D1-42AAE9E88E5E
Hardware Model:      iMac18,1
Process:             Runner [16596]
Path:                /Users/USER/Library/Developer/CoreSimulator/Devices/558D2DD4-FC71-4C6F-9007-9D369BEAADB8/data/Containers/Bundle/Application/B212F0D3-7088-46E2-A104-AC24B8079688/Runner.app/Runner
Identifier:          -----
Version:             -----
Code Type:           X86-64 (Native)
Role:                Foreground
Parent Process:      launchd_sim [852]
Coalition:           com.apple.CoreSimulator.SimDevice.558D2DD4-FC71-4C6F-9007-9D369BEAADB8 [800]
Responsible Process: SimulatorTrampoline [844]

Date/Time:           2022-01-13 19:45:40.6432 +0530
Launch Time:         2022-01-13 19:43:15.5481 +0530
OS Version:          macOS 12.0.1 (21A559)
Release Type:        User
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot
CoreSimulator 776.4 - Device: iPhone 8 Plus (********-****-****-****-************) - Runtime: iOS 15.0 (19A339) - DeviceType: iPhone 8 Plus
terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'FIRIllegalStateException', reason: 'The client has already been terminated.'
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot
abort() called

Please help me solve this, thanks in advance.

Body:
Reverse the order:

await FirebaseFirestore.instance.clearPersistence();
await FirebaseFirestore.instance.terminate();

Once you terminate the instance you cannot attempt to modify its cached data.


问:
How to logout with flutter_appauth?
I need to logout from flutter_appauth with a button press in flutter;

This package doesn't have any logout method.

This is my get token code:

```<code>appAuth.authorizeAndExchangeCode(AuthorizationTokenRequest(
                clientID, redirectUrl,
                discoveryUrl: discoveryUrl,
                scopes: scopes,
                clientSecret: clientSecret
</code>```

答:
I created a method that take care of logging out the user by ending the session like that:

```<code>Future<bool> endSession(String idToken) async {
    //work like logout method
    try {
      await appAuth.endSession(EndSessionRequest(
          idTokenHint: idToken,
          issuer: _issuer,
          postLogoutRedirectUrl: _redirectUrl,
          allowInsecureConnections: _allowInsecureConnections));
    } catch (err) {
      print(err);
      return false;
    }
    return true;
  }
</code>```

If you're using keycloak then _issuer will be something like that http://localhost:8080/auth/realms/REALM-NAME

idToken is what you received after login (inside AuthorizationTokenResponse)

Title: How to logout with flutter_appauth?

Body:
I need to logout from flutter_appauth with a button press in flutter;

This package doesn't have any logout method.

This is my get token code:

appAuth.authorizeAndExchangeCode(AuthorizationTokenRequest(
                clientID, redirectUrl,
                discoveryUrl: discoveryUrl,
                scopes: scopes,
                clientSecret: clientSecret

Body:
I created a method that take care of logging out the user by ending the session like that:

Future<bool> endSession(String idToken) async {
    //work like logout method
    try {
      await appAuth.endSession(EndSessionRequest(
          idTokenHint: idToken,
          issuer: _issuer,
          postLogoutRedirectUrl: _redirectUrl,
          allowInsecureConnections: _allowInsecureConnections));
    } catch (err) {
      print(err);
      return false;
    }
    return true;
  }

If you're using keycloak then _issuer will be something like that http://localhost:8080/auth/realms/REALM-NAME

idToken is what you received after login (inside AuthorizationTokenResponse)


问:
How do I sort a simple Lua table alphabetically?
I have already seen many threads with examples of how to do this, the problem is, I still can't do it.

All the examples have tables with extra data. For example somethings like this

```<code>lines = {
  luaH_set = 10,
  luaH_get = 24,
  luaH_present = 48,
}
</code>```

or this,

```<code>obj = {
   { N = 'Green1'      },
   { N = 'Green'       },
   { N = 'Sky blue99'  }
}
</code>```

I can code in a few languages but I'm very new to Lua, and tables are really confusing to me. I can't seem to work out how to adapt the code in the examples to be able to sort a simple table.

This is my table:

```<code>local players = {"barry", "susan", "john", "wendy", "kevin"}
</code>```

I want to sort these names alphabetically. I understand that Lua tables don't preserve order, and that's what's confusing me. All I essentially care about doing is just printing these names in alphabetical order, but I feel I need to learn this properly and know how to index them in the right order to a new table.

The examples I see are like this:

```<code>local function cmp(a, b)
   a = tostring(a.N)
   b = tostring(b.N)
   local patt = '^(.-)%s*(%d+)$'
   local _,_, col1, num1 = a:find(patt)
   local _,_, col2, num2 = b:find(patt)
   if (col1 and col2) and col1 == col2 then
      return tonumber(num1) < tonumber(num2)
   end
   return a < b
end

table.sort(obj, cmp)
for i,v in ipairs(obj) do
   print(i, v.N)
end
</code>```

or this:

```<code>function pairsByKeys (t, f)
  local a = {}
  for n in pairs(t) do table.insert(a, n) end
  table.sort(a, f)
  local i = 0      -- iterator variable
  local iter = function ()   -- iterator function
    i = i + 1
    if a[i] == nil then return nil
    else return a[i], t[a[i]]
    end
  end
  return iter
end

for name, line in pairsByKeys(lines) do
  print(name, line)
end
</code>```

and I'm just absolutely thrown by this as to how to do the same thing for a simple 1D table.

Can anyone please help me to understand this? I know if I can understand the most basic example, I'll be able to teach myself these harder examples.

答:
To clear up the confusing in regards to "not preserving order": What's not preserving order are the keys of the values in the table, in particular for string keys, i.e. when you use the table as dictionary and not as array. If you write myTable = {orange="hello", apple="world"} then the fact that you defined key orange to the left of key apple isn't stored. If you enumerate keys/values using for k, v in pairs(myTable) do print(k, v) end then you'd actually get apple  world before orange  hello because "apple" < "orange".

You don't have this problem with numeric keys though (which is what the keys by default will be if you don't specify them - myTable = {"hello", "world", foo="bar"} is the same as myTable = {[1]="hello", [2]="world", foo="bar"}, i.e. it will assign myTable[1] = "hello", myTable[2] = "world" and myTable.foo = "bar" (same as myTable["foo"]). (Here, even if you would get the numeric keys in a random order - which you don't, it wouldn't matter since you could still loop through them by incrementing.)

You can use table.sort which, if no order function is given, will sort the values using < so in case of numbers the result is ascending numbers and in case of strings it will sort by ASCII code:

local players = {"barry", "susan", "john", "wendy", "kevin"}
table.sort(players)
-- players is now {"barry", "john", "kevin", "susan", "wendy"}
```
<p>This will however fall apart if you have mixed lowercase and uppercase entries because uppercase will go before lowercase due to having lower ASCII codes, and of course it also won't work properly with non-ASCII characters like umlauts (they will go last) - it's not a lexicographic sort.</p>
<p>You can however supply your own ordering function which receives arguments <code>(a, b)</code> and needs to return <code>true</code> if <code>a</code> should come before <code>b</code>. Here an example that fixes the lower-/uppercase issues for example, by converting to uppercase before comparing:</p>
<pre class="lang-lua prettyprint-override"><code>table.sort(players, function (a, b)
  return string.upper(a) < string.upper(b)
end)
</code>```

Body:
I have already seen many threads with examples of how to do this, the problem is, I still can't do it.

All the examples have tables with extra data. For example somethings like this

lines = {
  luaH_set = 10,
  luaH_get = 24,
  luaH_present = 48,
}

or this,

obj = {
   { N = 'Green1'      },
   { N = 'Green'       },
   { N = 'Sky blue99'  }
}

I can code in a few languages but I'm very new to Lua, and tables are really confusing to me. I can't seem to work out how to adapt the code in the examples to be able to sort a simple table.

This is my table:

local players = {"barry", "susan", "john", "wendy", "kevin"}

I want to sort these names alphabetically. I understand that Lua tables don't preserve order, and that's what's confusing me. All I essentially care about doing is just printing these names in alphabetical order, but I feel I need to learn this properly and know how to index them in the right order to a new table.

The examples I see are like this:

local function cmp(a, b)
   a = tostring(a.N)
   b = tostring(b.N)
   local patt = '^(.-)%s*(%d+)$'
   local _,_, col1, num1 = a:find(patt)
   local _,_, col2, num2 = b:find(patt)
   if (col1 and col2) and col1 == col2 then
      return tonumber(num1) < tonumber(num2)
   end
   return a < b
end

table.sort(obj, cmp)
for i,v in ipairs(obj) do
   print(i, v.N)
end

or this:

function pairsByKeys (t, f)
  local a = {}
  for n in pairs(t) do table.insert(a, n) end
  table.sort(a, f)
  local i = 0      -- iterator variable
  local iter = function ()   -- iterator function
    i = i + 1
    if a[i] == nil then return nil
    else return a[i], t[a[i]]
    end
  end
  return iter
end

for name, line in pairsByKeys(lines) do
  print(name, line)
end

and I'm just absolutely thrown by this as to how to do the same thing for a simple 1D table.

Can anyone please help me to understand this? I know if I can understand the most basic example, I'll be able to teach myself these harder examples.

Body:
To clear up the confusing in regards to "not preserving order": What's not preserving order are the keys of the values in the table, in particular for string keys, i.e. when you use the table as dictionary and not as array. If you write myTable = {orange="hello", apple="world"} then the fact that you defined key orange to the left of key apple isn't stored. If you enumerate keys/values using for k, v in pairs(myTable) do print(k, v) end then you'd actually get apple  world before orange  hello because "apple" < "orange".

You don't have this problem with numeric keys though (which is what the keys by default will be if you don't specify them - myTable = {"hello", "world", foo="bar"} is the same as myTable = {[1]="hello", [2]="world", foo="bar"}, i.e. it will assign myTable[1] = "hello", myTable[2] = "world" and myTable.foo = "bar" (same as myTable["foo"]). (Here, even if you would get the numeric keys in a random order - which you don't, it wouldn't matter since you could still loop through them by incrementing.)

You can use table.sort which, if no order function is given, will sort the values using < so in case of numbers the result is ascending numbers and in case of strings it will sort by ASCII code:

local players = {"barry", "susan", "john", "wendy", "kevin"}
table.sort(players)
-- players is now {"barry", "john", "kevin", "susan", "wendy"}

This will however fall apart if you have mixed lowercase and uppercase entries because uppercase will go before lowercase due to having lower ASCII codes, and of course it also won't work properly with non-ASCII characters like umlauts (they will go last) - it's not a lexicographic sort.

You can however supply your own ordering function which receives arguments (a, b) and needs to return true if a should come before b. Here an example that fixes the lower-/uppercase issues for example, by converting to uppercase before comparing:

table.sort(players, function (a, b)
  return string.upper(a) < string.upper(b)
end)


问:
Getting following error while deploying to node react app to heroku

List item

I am trying to deploy a node - react app on heroku

答:
A 503 error code means the server cannot handle the request because it is either unresponsive or overloaded, as stated on MDN. This could be a result of incorrectly initializing the application on Heroku. Run the following in your directory from the terminal to deploy to heroku.

```<code>cd  my-project
git init
heroku git:remote -a app-name

git add .
git commit -am "comment"
git push heroku master
</code>```

More details about deploying a Node app to Heroku can be found here

Body:
A 503 error code means the server cannot handle the request because it is either unresponsive or overloaded, as stated on MDN. This could be a result of incorrectly initializing the application on Heroku. Run the following in your directory from the terminal to deploy to heroku.

cd  my-project
git init
heroku git:remote -a app-name

git add .
git commit -am "comment"
git push heroku master

More details about deploying a Node app to Heroku can be found here


答:
This is my table:

local players = {"barry", "susan", "john", "wendy", "kevin"}

I want to sort these names alphabetically.

All you need is table.sort(players)

I understand that LUA tables don't preserve order.

Order of fields in a Lua table (a dictionary with arbitrary keys) is not preserved.

But your Lua table is an array, it is self-ordered by its integer keys 1, 2, 3,....

Title: How do I sort a simple Lua table alphabetically?