问:
How to cancel a UIWebView?
I'm modally presenting a UIViewController with a UIWebView as its view. How do I dismiss the UIWebView when the user hits a cancel button on it?

One idea I have is to have the cancel button link to http://cancel and then check in

```<code>- (void)webViewDidStartLoad:(UIWebView *)webView
</code>```

If webView.request.URL.host isEqualToString:@"cancel", then dismiss the view controller.

Does the host have to have a dot in it, e.g., "cancel.com"?

答:
It's not entirely clear if you want to stop loading in a web view or just dismiss the modal view controller that's containing it.

To stop loading:

```<code>[webView stopLoading];
</code>```

To dismiss the view controller:

```<code>[self dismissModalViewControllerAnimated:YES];
</code>```

Don't forget to set the web view's delegate to nil before you release it.

Title: How to cancel a UIWebView?

Body:
I'm modally presenting a UIViewController with a UIWebView as its view. How do I dismiss the UIWebView when the user hits a cancel button on it?

One idea I have is to have the cancel button link to http://cancel and then check in

- (void)webViewDidStartLoad:(UIWebView *)webView

If webView.request.URL.host isEqualToString:@"cancel", then dismiss the view controller.

Does the host have to have a dot in it, e.g., "cancel.com"?

Body:
It's not entirely clear if you want to stop loading in a web view or just dismiss the modal view controller that's containing it.

To stop loading:

[webView stopLoading];

To dismiss the view controller:

[self dismissModalViewControllerAnimated:YES];

Don't forget to set the web view's delegate to nil before you release it.


来源: stackexchange

问:
Add n spaces between each letter in a given string in Haskell
I am quite a beginner and I am trying to write a function in Haskell that would take in a number n and a given string. The function will then return the string with n spaces between each letter in the string.
For example the function addSpace 2 "hello" will return the following "h  e l l o".

For the moment I have only managed to have a function that would take in a String and just add a single space between each letter.

```<code>addSpace :: String -> String
addSpace s = if length s <= 1
              then s
              else take 1 s ++ " " ++ addSpace (drop 1 s)
</code>```

However the function in Haskell I would like it to be:

```<code>addSpace :: Integer -> String -> String
</code>```

Appreciate all help!

答:
You already have a working implementation that adds a string between every character of the input string; it's just that the string to be added is hardcoded as " ". So it should be fairly obvious that all you need to do is replace the " " with some function call that takes an Integer and works out how many spaces there should be:

```<code>addSpace :: Integer -> String -> String
addSpace n s
  = if length s <= 1
      then s
      else take 1 s ++ makeSpaces n ++ addSpace (drop 1 s)
</code>```

Now all you have to do is define the makeSpaces function. From how we're using it, it must have this type:

```<code>makeSpaces :: Integer -> String
makeSpaces n = _
</code>```

I'm not going to give you any more code, but you can implement it very similarly to the recursion scheme you already demonstrated in addSpace, only instead of the choice of whether to recurse of not being based on the length of an input string, it will be based on the value of an input integer. When n is zero, what should you return? When it's greater than zero, what should you add to a recursive call to get the right answer? And how should you transform n as input for the recursive call.

For bonus points1: your current addString works (at least for finite inputs) but can be very inefficient, because every time you ask for the length of a string (which you do in every recursive call) it has to walk the entire string to count out the length. Since you don't actually use the length for anything except checking whether it it's less than or equal to 1, do you really need to calculate the exact length? If you've been shown pattern matching2 then you should be able to think of a way to tell whether a list has at least one character in it without calling length.

1 I say "bonus points" because an addSpace :: Integer -> String -> String function based on the way you've written your current solution works and I imagine it would get a decent mark in a beginner course, but I also imagine it will not get a top mark; the code is inefficient and longer than it needs to be.

2 If you haven't been shown pattern matching then (a) you can ignore this whole "bonus points" paragraph, as I don't think it will be required of you to get a good mark, and (b) they're teaching you Haskell in a very weird order.

ContentLicense: CC BY-SA 4.0

Body:
I am quite a beginner and I am trying to write a function in Haskell that would take in a number n and a given string. The function will then return the string with n spaces between each letter in the string.
For example the function addSpace 2 "hello" will return the following "h  e l l o".

For the moment I have only managed to have a function that would take in a String and just add a single space between each letter.

addSpace :: String -> String
addSpace s = if length s <= 1
              then s
              else take 1 s ++ " " ++ addSpace (drop 1 s)

However the function in Haskell I would like it to be:

addSpace :: Integer -> String -> String

Appreciate all help!

Body:
You already have a working implementation that adds a string between every character of the input string; it's just that the string to be added is hardcoded as " ". So it should be fairly obvious that all you need to do is replace the " " with some function call that takes an Integer and works out how many spaces there should be:

addSpace :: Integer -> String -> String
addSpace n s
  = if length s <= 1
      then s
      else take 1 s ++ makeSpaces n ++ addSpace (drop 1 s)

Now all you have to do is define the makeSpaces function. From how we're using it, it must have this type:

makeSpaces :: Integer -> String
makeSpaces n = _

I'm not going to give you any more code, but you can implement it very similarly to the recursion scheme you already demonstrated in addSpace, only instead of the choice of whether to recurse of not being based on the length of an input string, it will be based on the value of an input integer. When n is zero, what should you return? When it's greater than zero, what should you add to a recursive call to get the right answer? And how should you transform n as input for the recursive call.

For bonus points1: your current addString works (at least for finite inputs) but can be very inefficient, because every time you ask for the length of a string (which you do in every recursive call) it has to walk the entire string to count out the length. Since you don't actually use the length for anything except checking whether it it's less than or equal to 1, do you really need to calculate the exact length? If you've been shown pattern matching2 then you should be able to think of a way to tell whether a list has at least one character in it without calling length.

1 I say "bonus points" because an addSpace :: Integer -> String -> String function based on the way you've written your current solution works and I imagine it would get a decent mark in a beginner course, but I also imagine it will not get a top mark; the code is inefficient and longer than it needs to be.

2 If you haven't been shown pattern matching then (a) you can ignore this whole "bonus points" paragraph, as I don't think it will be required of you to get a good mark, and (b) they're teaching you Haskell in a very weird order.


问:
How to count number of times a text appeared in multiple cells using python
I want to figure out a way by which I could count number of times a similar word have appeared in multiple rows. For example, 'Street' have appeared, 'Carla' have appeared twice. (* Note --> There are many such rows wherein I am not sure which word is common)

Description

Street 29 euro

Street 31 USD

Carla xyz 45 output

Street 345 tmd

Carla asb 6789 tim

Please help

答:
Not sure what format your data is in but lets assume its a pandas DataFrame.

First convert to a list:

```<code>rows = df["Description"]
</code>```

Create a large list as a container for all words:

```<code>large_list = []
</code>```

Iterate over the rows, split each row by whitespaces and append the list of words in this row to the large list:

```<code>for row in rows:
    large_list += row.split()
</code>```

Count how often each element (word) in the list occurs:

```<code>import collections
counts = collections.Counter(large_list)
print(counts)
</code>```

You might want to add filters such as a word can only contain of letters (and not e.g. numbers), stopword filtering etc..

Body:
Not sure what format your data is in but lets assume its a pandas DataFrame.

First convert to a list:

rows = df["Description"]

Create a large list as a container for all words:

large_list = []

Iterate over the rows, split each row by whitespaces and append the list of words in this row to the large list:

for row in rows:
    large_list += row.split()

Count how often each element (word) in the list occurs:

import collections
counts = collections.Counter(large_list)
print(counts)

You might want to add filters such as a word can only contain of letters (and not e.g. numbers), stopword filtering etc..


问:
How do I format and post Json in the post request body (RestSharp)
I don't understand how to sent this json in the request body.
Here is the json from the postman create collection body (https://www.postman.com/postman/workspace/postman-public-workspace/request/12959542-049042b8-447f-4f71-8b79-ae978cf40a04):

```<code>{
    "collection": {
        "info": {
            "name": "Sample Collection 909",
            "description": "This is just a sample collection.",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
        },
        "item": [
            {
                "name": "This is a folder",
                "item": [
                    {
                        "name": "Sample POST Request",
                        "request": {
                            "url": "https://postman-echo.com/post",
                            "method": "POST",
                            "header": [
                                {
                                    "key": "Content-Type",
                                    "value": "application/json"
                                }
                            ],
                            "body": {
                                "mode": "raw",
                                "raw": "{\"data\": \"123\"}"
                            },
                            "description": "This is a sample POST Request"
                        }
                    }
                ]
            },
            {
                "name": "Sample GET Request",
                "request": {
                    "url": "https://postman-echo/get",
                    "method": "GET",
                    "description": "This is a sample GET Request"
                }
            }
        ]
    }
}
</code>```

Json above works fine using the Postman app, my attempt at it:

```<code>RestSharp.Settings.Init("collections", Method.Post);
RestSharp.Settings.AddHeader("X-Api-Key", "I hid my key");
RestSharp.Settings.restRequest.RequestFormat = DataFormat.Json;

RestSharp.Settings.restRequest.AddParameter("application/json; charset=utf-8", "{\n    \"collection\": {\n        \"info\": {\n            \"name\": \"Sample Collection 909\",\n            \"description\": \"This is just a sample collection.\",\n            \"schema\": \"https://schema.getpostman.com/json/collection/v2.1.0/collection.json\"\n        },\n        \"item\": [\n            {\n                \"name\": \"This is a folder\",\n                \"item\": [\n                    {\n                        \"name\": \"Sample POST Request\",\n                        \"request\": {\n                            \"url\": \"https://postman-echo.com/post\",\n                            \"method\": \"POST\",\n                            \"header\": [\n                                {\n                                    \"key\": \"Content-Type\",\n                                    \"value\": \"application/json\"\n                                }\n                            ],\n                            \"body\": {\n                                \"mode\": \"raw\",\n                                \"raw\": \"{\\\"data\\\": \\\"123\\\"}\"\n                            },\n                            \"description\": \"This is a sample POST Request\"\n                        }\n                    }\n                ]\n            },\n            {\n                \"name\": \"Sample GET Request\",\n                \"request\": {\n                    \"url\": \"https://postman-echo/get\",\n                    \"method\": \"GET\",\n                    \"description\": \"This is a sample GET Request\"\n                }\n            }\n        ]\n    }\n}",ParameterType.RequestBody);

var response = RestSharp.Settings.restClient.ExecuteAsync(RestSharp.Settings.restRequest).Result;

Console.WriteLine("Returned http status code is: " + response.StatusCode + " expected OK");

Assert.IsTrue((int)response.StatusCode == 200);
</code>```

答:
try this</p>
```<code>var client = new RestClient("http://..");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", json,  ParameterType.RequestBody);
IRestResponse response =  await client.ExecuteAsync(request);
var jsonOutput=response.Content;
</code>```

Body:
I don't understand how to sent this json in the request body.
Here is the json from the postman create collection body (https://www.postman.com/postman/workspace/postman-public-workspace/request/12959542-049042b8-447f-4f71-8b79-ae978cf40a04):

{
    "collection": {
        "info": {
            "name": "Sample Collection 909",
            "description": "This is just a sample collection.",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
        },
        "item": [
            {
                "name": "This is a folder",
                "item": [
                    {
                        "name": "Sample POST Request",
                        "request": {
                            "url": "https://postman-echo.com/post",
                            "method": "POST",
                            "header": [
                                {
                                    "key": "Content-Type",
                                    "value": "application/json"
                                }
                            ],
                            "body": {
                                "mode": "raw",
                                "raw": "{\"data\": \"123\"}"
                            },
                            "description": "This is a sample POST Request"
                        }
                    }
                ]
            },
            {
                "name": "Sample GET Request",
                "request": {
                    "url": "https://postman-echo/get",
                    "method": "GET",
                    "description": "This is a sample GET Request"
                }
            }
        ]
    }
}

Json above works fine using the Postman app, my attempt at it:

RestSharp.Settings.Init("collections", Method.Post);
RestSharp.Settings.AddHeader("X-Api-Key", "I hid my key");
RestSharp.Settings.restRequest.RequestFormat = DataFormat.Json;

RestSharp.Settings.restRequest.AddParameter("application/json; charset=utf-8", "{\n    \"collection\": {\n        \"info\": {\n            \"name\": \"Sample Collection 909\",\n            \"description\": \"This is just a sample collection.\",\n            \"schema\": \"https://schema.getpostman.com/json/collection/v2.1.0/collection.json\"\n        },\n        \"item\": [\n            {\n                \"name\": \"This is a folder\",\n                \"item\": [\n                    {\n                        \"name\": \"Sample POST Request\",\n                        \"request\": {\n                            \"url\": \"https://postman-echo.com/post\",\n                            \"method\": \"POST\",\n                            \"header\": [\n                                {\n                                    \"key\": \"Content-Type\",\n                                    \"value\": \"application/json\"\n                                }\n                            ],\n                            \"body\": {\n                                \"mode\": \"raw\",\n                                \"raw\": \"{\\\"data\\\": \\\"123\\\"}\"\n                            },\n                            \"description\": \"This is a sample POST Request\"\n                        }\n                    }\n                ]\n            },\n            {\n                \"name\": \"Sample GET Request\",\n                \"request\": {\n                    \"url\": \"https://postman-echo/get\",\n                    \"method\": \"GET\",\n                    \"description\": \"This is a sample GET Request\"\n                }\n            }\n        ]\n    }\n}",ParameterType.RequestBody);

var response = RestSharp.Settings.restClient.ExecuteAsync(RestSharp.Settings.restRequest).Result;

Console.WriteLine("Returned http status code is: " + response.StatusCode + " expected OK");

Assert.IsTrue((int)response.StatusCode == 200);

Body:
try this

var client = new RestClient("http://..");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", json,  ParameterType.RequestBody);
IRestResponse response =  await client.ExecuteAsync(request);
var jsonOutput=response.Content;


问:
edit a string by removing characters without creating a new string, is it legit or not?
EDIT: I think I've understood how this concept works, this is my code

```<code>void delete_duplicate(char* str) {
    if (str == NULL) {
        exit(1);
    }
    for (size_t i = 0; str[i] != 0; i++) {
        if (str[i] == str[i + 1]) {
            str[i] = '\0';
        }
    }
}

    int main(void) {
    char str[] = "hhhhhhhheeeeeeeeyyyyyyyyyyy";
    delete_duplicate(str);
    return 0;
}
</code>```

the output string is "00...0h0...000e0...000y" (with lots of zeros). if the string is "abbbb", the string becomes "a" and not "ab".

I was thinking about an algorithm for this exercise:

given a string, for example "ssttringg" the output must be "string". the function has to remove one character if and only if the current character and the next character are the same.

the exercise expects a function declared like this:

```<code>extern void delete_consecutive(char* str);
</code>```

this is my algorithm:

loop: if the current character is equal to the next character, increment length by 1, and repeat until zero terminator is reached.

critical part: dynamic memory allocation.

allocate enough memory to store the output. Why did I say this is the critical part? because I have to do it in a void function, therefore I can't create a second string, allocate enough memory with malloc, and then return it at the end. I need to edit the original string instead. I think I can do it by means of a realloc, and by decrementing the size of the string. But I don't know how to do it, and more important: I don't know if it's legit to do it, without losing data. I think I'm overcomplicating the homework, but it's a void function, therefore I can't simply create a new string and copying characters in it, because I can't return it.

if it's not clear, I'll edit the question.

答:
This isn't an answer, but consider this code:

```<code>    char str[] = "strunqg";
    printf("before: %s\n", str);
    modifystring(str);
    printf("after:  %s\n", str);
</code>```

where the "modifystring" function looks like this:

```<code>void modifystring(char *p)
{
    p[3] = 'i';
    p[5] = p[6];
    p[6] = '\0';
}
</code>```

This is totally "legit".  It would not work, however, to call

```<code>    char *str = "strunqg";
    modifystring(str);            /* WRONG */
</code>```

or

```<code>    modifystring("strunqg");      /* WRONG */
</code>```

Either of these second two would attempt to modify a string literal, and that's not copacetic.

Body:
EDIT: I think I've understood how this concept works, this is my code

void delete_duplicate(char* str) {
    if (str == NULL) {
        exit(1);
    }
    for (size_t i = 0; str[i] != 0; i++) {
        if (str[i] == str[i + 1]) {
            str[i] = '\0';
        }
    }
}

    int main(void) {
    char str[] = "hhhhhhhheeeeeeeeyyyyyyyyyyy";
    delete_duplicate(str);
    return 0;
}

the output string is "00...0h0...000e0...000y" (with lots of zeros). if the string is "abbbb", the string becomes "a" and not "ab".

I was thinking about an algorithm for this exercise:

given a string, for example "ssttringg" the output must be "string". the function has to remove one character if and only if the current character and the next character are the same.

the exercise expects a function declared like this:

extern void delete_consecutive(char* str);

this is my algorithm:

loop: if the current character is equal to the next character, increment length by 1, and repeat until zero terminator is reached.

critical part: dynamic memory allocation.

allocate enough memory to store the output. Why did I say this is the critical part? because I have to do it in a void function, therefore I can't create a second string, allocate enough memory with malloc, and then return it at the end. I need to edit the original string instead. I think I can do it by means of a realloc, and by decrementing the size of the string. But I don't know how to do it, and more important: I don't know if it's legit to do it, without losing data. I think I'm overcomplicating the homework, but it's a void function, therefore I can't simply create a new string and copying characters in it, because I can't return it.

if it's not clear, I'll edit the question.

Body:
This isn't an answer, but consider this code:

    char str[] = "strunqg";
    printf("before: %s\n", str);
    modifystring(str);
    printf("after:  %s\n", str);

where the "modifystring" function looks like this:

void modifystring(char *p)
{
    p[3] = 'i';
    p[5] = p[6];
    p[6] = '\0';
}

This is totally "legit".  It would not work, however, to call

    char *str = "strunqg";
    modifystring(str);            /* WRONG */

or

    modifystring("strunqg");      /* WRONG */

Either of these second two would attempt to modify a string literal, and that's not copacetic.


问:
How to retrieve data from a model of an App in the views of another application?
Hello django python developers. Indeed, I developed a django project composed of 2 applications.
MyApp and Blog

I want to retrieve the data from the MyApp App models from the database on the App Blog views without rewriting the same functions

How do I do it

答:
You can import anything from one app to another. Just add in the top of you file proper from ... import ... to use it at it is.

If you want to use your class models, just do import with from starting from app level:

```<code>from MyApp.models import MyModel

my_model = MyModel.objects.first()
my_model.some_method()
</code>```

If you have more things you want to import from a file, you can separate them with comma:

```<code>from MyApp.models import MyModel, some_function

my_model = MyModel.objects.first()
some_function(my_model)
</code>```

Body:
You can import anything from one app to another. Just add in the top of you file proper from ... import ... to use it at it is.

If you want to use your class models, just do import with from starting from app level:

from MyApp.models import MyModel

my_model = MyModel.objects.first()
my_model.some_method()

If you have more things you want to import from a file, you can separate them with comma:

from MyApp.models import MyModel, some_function

my_model = MyModel.objects.first()
some_function(my_model)


问:
osascript: how to keep nested lists structure when output from command-line
I'm trying to code a script which can be able to extract the menu structure of a given app. This is a simplified working example:

```<code>tell application "System Events"
    tell process "Terminal"
        tell menu bar 1
            set listA to name of every menu bar item
            set listB to name of every menu of every menu bar item
            set listC to name of every menu item of every menu of every menu bar item
            set listD to name of every menu of every menu item of every menu of every menu bar item
            set listE to name of every menu item of every menu of every menu item of every menu of every menu bar item
        end tell
    end tell
end tell
return {listA, listB, listC, listD, listE}
</code>```

When I run this script on Script Editor, the result is a set of nested lists, like this (real result is too long, so I'm giving a sample):

```<code>{{{"Option1", "Option2", "Option3"}, {{"subOption1.1", "subOption1.2"}, {"subOption2.1", subOption2.2", "subOption2.3"}, {"subOption3.1"}}}
</code>```

Thus, it's easy to know that menu Option1 has two items inside and so on...

But when I run this same script from python, using "osascript -e", the list structure and braces are gone, like this

```<code>{{"Option1", "Option2", "Option3"}, {"subOption1.1", "subOption1.2", "subOption2.1", subOption2.2", "subOption2.3", "subOption3.1"}}
</code>```

So there is no way to know which sub-list corresponds to each other.

Is there a way to keep those braces or converting them into something different you can manage later on, or write this in a sort of "raw" data which keeps that nested structure?

Thanks in advance!

答:
Following @red_menace advice, I finally managed to get all application menu structure:</p>
```<code>    itemList = []

    def findit():

        level = 0

        while True:
            part = ""
            for lev in range(level):
                if lev % 2 == 0:
                    part = " of every menu" + part
                else:
                    part = " of every menu item" + part
            subCmd = "set itemList to name" + part + " of every menu bar item"

            if level % 2 == 0:  # Grabbing items only (menus will have non-empty lists on the next level)

                cmd = """
                        on run arg1
                        set procName to arg1 as string
                        tell application "System Events"
                            tell process procName
                                tell menu bar 1
                                    %s
                                end tell
                            end tell
                        end tell
                        return itemList as list
                        end run
                        """ % subCmd
                # https://stackoverflow.com/questions/69774133/how-to-use-global-variables-inside-of-an-applescript-function-for-a-python-code
                # Didn't find a way to get the "injected code" working when passed as argument
                proc = subprocess.Popen(['osascript', '-s', 's', '-', str(self._parent._app.localizedName())],
                                        stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding='utf8')
                ret, err = proc.communicate(cmd)
                ret = ret.replace("\n", "").replace('missing value', '"separator"').replace("{", "[").replace("}", "]")
                item = ast.literal_eval(ret)

                if err is None and not self._isListEmpty(item):
                    itemList.append(item)
                else:
                    break
            level += 1

        return itemList != []

    def fillit(subList):
       # Pending: build hierarchy structure (dict format) from list

    if findit():
        print(itemList)
        fillit(itemList)
</code>```

Body:
I'm trying to code a script which can be able to extract the menu structure of a given app. This is a simplified working example:

tell application "System Events"
    tell process "Terminal"
        tell menu bar 1
            set listA to name of every menu bar item
            set listB to name of every menu of every menu bar item
            set listC to name of every menu item of every menu of every menu bar item
            set listD to name of every menu of every menu item of every menu of every menu bar item
            set listE to name of every menu item of every menu of every menu item of every menu of every menu bar item
        end tell
    end tell
end tell
return {listA, listB, listC, listD, listE}

When I run this script on Script Editor, the result is a set of nested lists, like this (real result is too long, so I'm giving a sample):

{{{"Option1", "Option2", "Option3"}, {{"subOption1.1", "subOption1.2"}, {"subOption2.1", subOption2.2", "subOption2.3"}, {"subOption3.1"}}}

Thus, it's easy to know that menu Option1 has two items inside and so on...

But when I run this same script from python, using "osascript -e", the list structure and braces are gone, like this

{{"Option1", "Option2", "Option3"}, {"subOption1.1", "subOption1.2", "subOption2.1", subOption2.2", "subOption2.3", "subOption3.1"}}

So there is no way to know which sub-list corresponds to each other.

Is there a way to keep those braces or converting them into something different you can manage later on, or write this in a sort of "raw" data which keeps that nested structure?

Thanks in advance!

Body:
Following @red_menace advice, I finally managed to get all application menu structure:

    itemList = []

    def findit():

        level = 0

        while True:
            part = ""
            for lev in range(level):
                if lev % 2 == 0:
                    part = " of every menu" + part
                else:
                    part = " of every menu item" + part
            subCmd = "set itemList to name" + part + " of every menu bar item"

            if level % 2 == 0:  # Grabbing items only (menus will have non-empty lists on the next level)

                cmd = """
                        on run arg1
                        set procName to arg1 as string
                        tell application "System Events"
                            tell process procName
                                tell menu bar 1
                                    %s
                                end tell
                            end tell
                        end tell
                        return itemList as list
                        end run
                        """ % subCmd
                # https://stackoverflow.com/questions/69774133/how-to-use-global-variables-inside-of-an-applescript-function-for-a-python-code
                # Didn't find a way to get the "injected code" working when passed as argument
                proc = subprocess.Popen(['osascript', '-s', 's', '-', str(self._parent._app.localizedName())],
                                        stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding='utf8')
                ret, err = proc.communicate(cmd)
                ret = ret.replace("\n", "").replace('missing value', '"separator"').replace("{", "[").replace("}", "]")
                item = ast.literal_eval(ret)

                if err is None and not self._isListEmpty(item):
                    itemList.append(item)
                else:
                    break
            level += 1

        return itemList != []

    def fillit(subList):
       # Pending: build hierarchy structure (dict format) from list

    if findit():
        print(itemList)
        fillit(itemList)


问:
`Universe` - but for small and finite enumeration of ADTs
I want to generically derive something like Universe for user's route type defined in terms of ADTs.

Problem: I can use neither Enum/Bounded nor Universe - because they are not safe. The default instances on types like Int64 can lead to gazillion routes being generated.

The following route is valid, and should be accepted because there is a small and finite number of routes:

data R = Index | Blog BlogR
data BlogR = Foo | Bar
```
<p>The following route is invalid, and should not be accepted because there is an infinite number of routes generateble due to <code>String</code>. Neither should finitely enumerable types like <code>Int64</code> be accepted.</p>
<pre class="lang-hs prettyprint-override"><code>data R = Index | Blog BlogR
data BlogR = Post String
</code>```

The following route seems valid, but it should not be accepted either due to recursion.

data R = Index | Blog BlogR
data BlogR = Foo | Bar | Rec R
```

Questions:

Is there an existing type class that captures this constraint? If not, I would create one.

How to generically (generics-sop?) derive instances to capture this constraint, and fail with an user-friendly TypeError on invalid types?

Are there better ways of approaching this problem? Ultimately, I want a default implementation for IsRoute r => allRoutes :: [r]. At the moment, I use Enum and Bounded (see real-world code here) which is limiting because it cannot handle the first route type above.

答:
No, there's no existing type class that captures this type of constraint.

The challenge in defining a generics-based answer seems to be ruling out the recursion, as demonstrated below.  I think the simplest approach is probably to use a counter that sets an upper limit on the "depth" of a type.  The alternative would be to keep a type-level list of types already visited which seems like way too much trouble to be worth it.

So, here's a solution that uses GHC.Generics together with a type family constraint to enforce non-recursion (or technically, limited "depth" of the type).

Perhaps you're already familiar with the general GHC.Generics approach, but for completeness, here's how we'd put together a solution without worrying about recursion yet.  We start with the type class we want to define:

```<code>class Small a where
  universe :: [a]
</code>```

Then, we introduce a stylized generic type class, where the generic type a is replaced by a type f p such that f will play the role of the type-level representation Rep a of the type a we want to handle generically, while p is a dummy type variable that's never used:

```<code>import GHC.Generics

class GSmall f where
  guniverse :: [f p]
</code>```

Instances of the GSmall type class are defined on types from GHC.Generics that represent meta information, sum and product types, and constructor fields.

For meta information (e.g., names of fields, etc.), generic classes like GSmall that want to ignore it should simply "get the types right" by wrapping or unwrapping with the M1 constructor, as appropriate.  Here, we add M1 to every element of the universe list:

```<code>instance GSmall f => GSmall (M1 i c f) where
  guniverse = map M1 guniverse
</code>```

For sum and product types, we need instances for the null sum (Void) and the null product (()) represented by generic types V1 and U1 respectively:

```<code>-- handle uninhabited type Void
instance GSmall V1 where
  guniverse = []
-- handle unit
instance GSmall U1 where
  guniverse = [U1]
</code>```

For binary sums, the type level representation uses the operator :+: while the generic inhabitants are represented by the L1 and R1 constructors respectively.  Here, by wrapping with the right constructors, we call guniverse polymorphically on the left and right types of the sum:

```<code>{-# LANGUAGE TypeOperators #-}

instance (GSmall f, GSmall g) => GSmall (f :+: g) where
  guniverse = map L1 guniverse ++ map R1 guniverse
</code>```

For binary products, the process is similar, except we want to generate all combinations of the left and right side of the product:

```<code>instance (GSmall f, GSmall g) => GSmall (f :*: g) where
  guniverse = [f :*: g | f <- guniverse, g <- guniverse]
</code>```

Finally, we handle constructor fields of type a by looping back to the concrete Small class:

```<code>instance Small a => GSmall (K1 r a) where
  guniverse = map K1 universe
</code>```

If desired, we can add a default definition for universe in the Small class:

```<code>{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}

class Small a where
  universe :: [a]
  default universe :: (Generic a, GSmall (Rep a)) => [a]
  universe = universeGeneric

universeGeneric :: (Generic a, GSmall (Rep a)) => [a]
universeGeneric = map to guniverse
</code>```

To use this generic instance, we write

```<code>{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeApplications #-}

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Foo | Bar deriving (Show, Generic)

instance Small Route
instance Small BlogR

main = print $ universe @Route
</code>```

If you want to use a non-generic instance for some types, you can do that as well by overriding the default universe instance:

```<code>universeEnum :: (Bounded a, Enum a) => [a]
universeEnum = [minBound..maxBound]

data BlogR = Foo | Bar deriving (Show, Enum, Bounded)

instance Small BlogR where universe = universeEnum
</code>```

Here's the complete solution so far:

```<code>{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeApplications #-}

import GHC.Generics

class Small a where
  universe :: [a]
  default universe :: (Generic a, GSmall (Rep a)) => [a]
  universe = universeGeneric

class GSmall f where
  guniverse :: [f p]

universeGeneric :: (Generic a, GSmall (Rep a)) => [a]
universeGeneric = map to guniverse

universeEnum :: (Bounded a, Enum a) => [a]
universeEnum = [minBound..maxBound]

instance GSmall f => GSmall (M1 i c f) where
  guniverse = map M1 guniverse
instance GSmall V1 where
  guniverse = []
instance GSmall U1 where
  guniverse = [U1]
instance (GSmall f, GSmall g) => GSmall (f :+: g) where
  guniverse = map L1 guniverse ++ map R1 guniverse
instance (GSmall f, GSmall g) => GSmall (f :*: g) where
  guniverse = [f :*: g | f <- guniverse, g <- guniverse]
instance Small a => GSmall (K1 r a) where
  guniverse = map K1 universe

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Foo | Bar deriving (Show, Generic)

instance Small Route
-- use generic
instance Small BlogR
-- or enum-based
-- instance Small BlogR where universe = universeEnum

main = print $ universe @Route
</code>```

If you try to generate an instance for a non-recursive, non-small type (using Int, for example):

```<code>data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = PostId Int deriving (Show, Generic)

instance Small Route
instance Small BlogR  -- error
</code>```

you get an error:

```<code>No instance for (Small Int)
</code>```

which seems user-friendly enough without a TypeError.

The one problem is that recursive types are accepted, including lists, so we can define:

```<code>{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = PostId String deriving (Show, Generic)

instance Small Route
instance Small BlogR
instance Small String
instance Small Char where universe = universeEnum
</code>```

and get valid instances.  Same for your explicitly recursive example.

I think the simplest way to address this is to define a separate generic type family constraint to check that a type is non-recursive (or more exactly, has a limited depth).  This should include a generics based closed type family, something like the following.  Note that the top parameter is used here to remember the top-level type for error messages.  The generic type being processed is f, and the family yields an empty constraint if the depth of f doesn't exceed the depth "countdown" in n, and a TypeError otherwise:

```<code>{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}

import Data.Kind
import GHC.TypeLits

type family GClosed n top f :: Constraint where
  GClosed 0 top f = TypeError (Text "Depth limit exceeded by type: " :<>: ShowType top)
  GClosed n top (M1 i c f) = GClosed n top f
  GClosed n top V1 = ()
  GClosed n top U1 = ()
  GClosed n top (f :+: g) = (GClosed n top f, GClosed n top g)
  GClosed n top (f :*: g) = (GClosed n top f, GClosed n top g)
  GClosed n top (K1 r a) = NClosed (n-1) top a
</code>```

Note that the final case for K1 calls into an associated NClosed type family in the Small class, defaulting to the generic assessment of being "closed" via GClosed:

```<code>class Small a where
  ...
  type NClosed (n :: Nat) top a :: Constraint
  type instance NClosed n top a = GClosed n top (Rep a)
</code>```

We can then define:

```<code>type ClosedLimit = 20
type Closed a = NClosed ClosedLimit a a
</code>```

and sneak this constraint into the definition of universeGeneric:

```<code>universeGeneric :: (Generic a, GSmall (Rep a), Closed a) => [a]
universeGeneric = map to guniverse
</code>```

(with an associated update to the default universe signature in class Small).

This separation between GClosed and NClosed allows us to indicate that non-generic Small instances are closed with a little boilerplate.  For example, if we want to allow Word8's to be small:

```<code>instance Small Word8 where
  universe = universeEnum     -- use enum implementation
  type NClosed n a Int = ()   -- Word8s are closed
</code>```

The full code looks like this:

```<code>{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}

import GHC.Generics
import Data.Kind
import GHC.TypeLits

type Closed a = NClosed ClosedLimit a a
type family GClosed n top f :: Constraint where
  GClosed 0 top f = TypeError (Text "Depth limit exceeded by type: " :<>: ShowType top)
  GClosed n top (M1 i c f) = GClosed n top f
  GClosed n top V1 = ()
  GClosed n top U1 = ()
  GClosed n top (f :+: g) = (GClosed n top f, GClosed n top g)
  GClosed n top (f :*: g) = (GClosed n top f, GClosed n top g)
  GClosed n top (K1 r a) = NClosed (n-1) top a
type ClosedLimit = 20

class Small a where
  universe :: [a]
  default universe :: (Generic a, GSmall (Rep a), Closed a) => [a]
  universe = universeGeneric
  type NClosed (n :: Nat) top a :: Constraint
  type instance NClosed n top a = GClosed n top (Rep a)

class GSmall f where
  guniverse :: [f p]

universeGeneric :: (Generic a, GSmall (Rep a), Closed a) => [a]
universeGeneric = map to guniverse

universeEnum :: (Bounded a, Enum a) => [a]
universeEnum = [minBound..maxBound]

instance GSmall f => GSmall (M1 i c f) where
  guniverse = map M1 guniverse
instance GSmall V1 where
  guniverse = []
instance GSmall U1 where
  guniverse = [U1]
instance (GSmall f, GSmall g) => GSmall (f :+: g) where
  guniverse = map L1 guniverse ++ map R1 guniverse
instance (GSmall f, GSmall g) => GSmall (f :*: g) where
  guniverse = [f :*: g | f <- guniverse, g <- guniverse]
instance Small a => GSmall (K1 r a) where
  guniverse = map K1 universe

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Foo | Bar deriving (Show, Generic)

instance Small Route
instance Small BlogR

main = print $ universe @Route
</code>```

Both of your "bad" examples are rejected.  The first:

```<code>data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Post String deriving (Show, Generic)
</code>```

generates a couple of nasty error messages about NClosed plus the reasonably friendly message:

```<code>No instance for (Small [Char])
</code>```

Attempts to define instance Small [Char] will result in:

```<code>Depth limit exceeded by type: [Char]
</code>```

while the second:

```<code>data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Foo | Bar | Rec Route deriving (Show, Generic)
</code>```

generates the message:

```<code>Depth limit exceeded by type: Route
</code>```

Body:
I want to generically derive something like Universe for user's route type defined in terms of ADTs.

Problem: I can use neither Enum/Bounded nor Universe - because they are not safe. The default instances on types like Int64 can lead to gazillion routes being generated.

The following route is valid, and should be accepted because there is a small and finite number of routes:

data R = Index | Blog BlogR
data BlogR = Foo | Bar

The following route is invalid, and should not be accepted because there is an infinite number of routes generateble due to String. Neither should finitely enumerable types like Int64 be accepted.

data R = Index | Blog BlogR
data BlogR = Post String

The following route seems valid, but it should not be accepted either due to recursion.

data R = Index | Blog BlogR
data BlogR = Foo | Bar | Rec R

Questions:

Is there an existing type class that captures this constraint? If not, I would create one.

How to generically (generics-sop?) derive instances to capture this constraint, and fail with an user-friendly TypeError on invalid types?

Are there better ways of approaching this problem? Ultimately, I want a default implementation for IsRoute r => allRoutes :: [r]. At the moment, I use Enum and Bounded (see real-world code here) which is limiting because it cannot handle the first route type above.

Body:
No, there's no existing type class that captures this type of constraint.

The challenge in defining a generics-based answer seems to be ruling out the recursion, as demonstrated below.  I think the simplest approach is probably to use a counter that sets an upper limit on the "depth" of a type.  The alternative would be to keep a type-level list of types already visited which seems like way too much trouble to be worth it.

So, here's a solution that uses GHC.Generics together with a type family constraint to enforce non-recursion (or technically, limited "depth" of the type).

Perhaps you're already familiar with the general GHC.Generics approach, but for completeness, here's how we'd put together a solution without worrying about recursion yet.  We start with the type class we want to define:

class Small a where
  universe :: [a]

Then, we introduce a stylized generic type class, where the generic type a is replaced by a type f p such that f will play the role of the type-level representation Rep a of the type a we want to handle generically, while p is a dummy type variable that's never used:

import GHC.Generics

class GSmall f where
  guniverse :: [f p]

Instances of the GSmall type class are defined on types from GHC.Generics that represent meta information, sum and product types, and constructor fields.

For meta information (e.g., names of fields, etc.), generic classes like GSmall that want to ignore it should simply "get the types right" by wrapping or unwrapping with the M1 constructor, as appropriate.  Here, we add M1 to every element of the universe list:

instance GSmall f => GSmall (M1 i c f) where
  guniverse = map M1 guniverse

For sum and product types, we need instances for the null sum (Void) and the null product (()) represented by generic types V1 and U1 respectively:

-- handle uninhabited type Void
instance GSmall V1 where
  guniverse = []
-- handle unit
instance GSmall U1 where
  guniverse = [U1]

For binary sums, the type level representation uses the operator :+: while the generic inhabitants are represented by the L1 and R1 constructors respectively.  Here, by wrapping with the right constructors, we call guniverse polymorphically on the left and right types of the sum:

{-# LANGUAGE TypeOperators #-}

instance (GSmall f, GSmall g) => GSmall (f :+: g) where
  guniverse = map L1 guniverse ++ map R1 guniverse

For binary products, the process is similar, except we want to generate all combinations of the left and right side of the product:

instance (GSmall f, GSmall g) => GSmall (f :*: g) where
  guniverse = [f :*: g | f <- guniverse, g <- guniverse]

Finally, we handle constructor fields of type a by looping back to the concrete Small class:

instance Small a => GSmall (K1 r a) where
  guniverse = map K1 universe

If desired, we can add a default definition for universe in the Small class:

{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}

class Small a where
  universe :: [a]
  default universe :: (Generic a, GSmall (Rep a)) => [a]
  universe = universeGeneric

universeGeneric :: (Generic a, GSmall (Rep a)) => [a]
universeGeneric = map to guniverse

To use this generic instance, we write

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeApplications #-}

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Foo | Bar deriving (Show, Generic)

instance Small Route
instance Small BlogR

main = print $ universe @Route

If you want to use a non-generic instance for some types, you can do that as well by overriding the default universe instance:

universeEnum :: (Bounded a, Enum a) => [a]
universeEnum = [minBound..maxBound]

data BlogR = Foo | Bar deriving (Show, Enum, Bounded)

instance Small BlogR where universe = universeEnum

Here's the complete solution so far:

{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeApplications #-}

import GHC.Generics

class Small a where
  universe :: [a]
  default universe :: (Generic a, GSmall (Rep a)) => [a]
  universe = universeGeneric

class GSmall f where
  guniverse :: [f p]

universeGeneric :: (Generic a, GSmall (Rep a)) => [a]
universeGeneric = map to guniverse

universeEnum :: (Bounded a, Enum a) => [a]
universeEnum = [minBound..maxBound]

instance GSmall f => GSmall (M1 i c f) where
  guniverse = map M1 guniverse
instance GSmall V1 where
  guniverse = []
instance GSmall U1 where
  guniverse = [U1]
instance (GSmall f, GSmall g) => GSmall (f :+: g) where
  guniverse = map L1 guniverse ++ map R1 guniverse
instance (GSmall f, GSmall g) => GSmall (f :*: g) where
  guniverse = [f :*: g | f <- guniverse, g <- guniverse]
instance Small a => GSmall (K1 r a) where
  guniverse = map K1 universe

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Foo | Bar deriving (Show, Generic)

instance Small Route
-- use generic
instance Small BlogR
-- or enum-based
-- instance Small BlogR where universe = universeEnum

main = print $ universe @Route

If you try to generate an instance for a non-recursive, non-small type (using Int, for example):

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = PostId Int deriving (Show, Generic)

instance Small Route
instance Small BlogR  -- error

you get an error:

No instance for (Small Int)

which seems user-friendly enough without a TypeError.

The one problem is that recursive types are accepted, including lists, so we can define:

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = PostId String deriving (Show, Generic)

instance Small Route
instance Small BlogR
instance Small String
instance Small Char where universe = universeEnum

and get valid instances.  Same for your explicitly recursive example.

I think the simplest way to address this is to define a separate generic type family constraint to check that a type is non-recursive (or more exactly, has a limited depth).  This should include a generics based closed type family, something like the following.  Note that the top parameter is used here to remember the top-level type for error messages.  The generic type being processed is f, and the family yields an empty constraint if the depth of f doesn't exceed the depth "countdown" in n, and a TypeError otherwise:

{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}

import Data.Kind
import GHC.TypeLits

type family GClosed n top f :: Constraint where
  GClosed 0 top f = TypeError (Text "Depth limit exceeded by type: " :<>: ShowType top)
  GClosed n top (M1 i c f) = GClosed n top f
  GClosed n top V1 = ()
  GClosed n top U1 = ()
  GClosed n top (f :+: g) = (GClosed n top f, GClosed n top g)
  GClosed n top (f :*: g) = (GClosed n top f, GClosed n top g)
  GClosed n top (K1 r a) = NClosed (n-1) top a

Note that the final case for K1 calls into an associated NClosed type family in the Small class, defaulting to the generic assessment of being "closed" via GClosed:

class Small a where
  ...
  type NClosed (n :: Nat) top a :: Constraint
  type instance NClosed n top a = GClosed n top (Rep a)

We can then define:

type ClosedLimit = 20
type Closed a = NClosed ClosedLimit a a

and sneak this constraint into the definition of universeGeneric:

universeGeneric :: (Generic a, GSmall (Rep a), Closed a) => [a]
universeGeneric = map to guniverse

(with an associated update to the default universe signature in class Small).

This separation between GClosed and NClosed allows us to indicate that non-generic Small instances are closed with a little boilerplate.  For example, if we want to allow Word8's to be small:

instance Small Word8 where
  universe = universeEnum     -- use enum implementation
  type NClosed n a Int = ()   -- Word8s are closed

The full code looks like this:

{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}

import GHC.Generics
import Data.Kind
import GHC.TypeLits

type Closed a = NClosed ClosedLimit a a
type family GClosed n top f :: Constraint where
  GClosed 0 top f = TypeError (Text "Depth limit exceeded by type: " :<>: ShowType top)
  GClosed n top (M1 i c f) = GClosed n top f
  GClosed n top V1 = ()
  GClosed n top U1 = ()
  GClosed n top (f :+: g) = (GClosed n top f, GClosed n top g)
  GClosed n top (f :*: g) = (GClosed n top f, GClosed n top g)
  GClosed n top (K1 r a) = NClosed (n-1) top a
type ClosedLimit = 20

class Small a where
  universe :: [a]
  default universe :: (Generic a, GSmall (Rep a), Closed a) => [a]
  universe = universeGeneric
  type NClosed (n :: Nat) top a :: Constraint
  type instance NClosed n top a = GClosed n top (Rep a)

class GSmall f where
  guniverse :: [f p]

universeGeneric :: (Generic a, GSmall (Rep a), Closed a) => [a]
universeGeneric = map to guniverse

universeEnum :: (Bounded a, Enum a) => [a]
universeEnum = [minBound..maxBound]

instance GSmall f => GSmall (M1 i c f) where
  guniverse = map M1 guniverse
instance GSmall V1 where
  guniverse = []
instance GSmall U1 where
  guniverse = [U1]
instance (GSmall f, GSmall g) => GSmall (f :+: g) where
  guniverse = map L1 guniverse ++ map R1 guniverse
instance (GSmall f, GSmall g) => GSmall (f :*: g) where
  guniverse = [f :*: g | f <- guniverse, g <- guniverse]
instance Small a => GSmall (K1 r a) where
  guniverse = map K1 universe

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Foo | Bar deriving (Show, Generic)

instance Small Route
instance Small BlogR

main = print $ universe @Route

Both of your "bad" examples are rejected.  The first:

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Post String deriving (Show, Generic)

generates a couple of nasty error messages about NClosed plus the reasonably friendly message:

No instance for (Small [Char])

Attempts to define instance Small [Char] will result in:

Depth limit exceeded by type: [Char]

while the second:

data Route = Index | Blog BlogR deriving (Show, Generic)
data BlogR = Foo | Bar | Rec Route deriving (Show, Generic)

generates the message:

Depth limit exceeded by type: Route


问:
Bumblebee Android studio Plugin [id: 'com.android.application', version: '7.1.0', apply: false] was not found in any of the following sources:
I updated my android studio from Android studio fox to Android studio Bumblebee 2021.1.1
but none of my projects can run in Android studio Bumblebee 2021.1.1. I ended up getting this beautiful error.

Here is my gradle file

```<code>plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
This happens to me with AS Bumblebee when I add a new module to my project. It adds these two lines to my project-level build.gradle in the plugins block:

```<code>    id 'com.android.library' version '7.1.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
</code>```

I removed them to fix the error.

Body:
I updated my android studio from Android studio fox to Android studio Bumblebee 2021.1.1
but none of my projects can run in Android studio Bumblebee 2021.1.1. I ended up getting this beautiful error.

Here is my gradle file

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
This happens to me with AS Bumblebee when I add a new module to my project. It adds these two lines to my project-level build.gradle in the plugins block:

    id 'com.android.library' version '7.1.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false

I removed them to fix the error.


问:
Show PKDrawing on macOS in SwiftUI
Is it possible to display a PKDrawing on macOS that was previously created on an iOS device?

答:
You can initialize a new PKDrawing object from your drawing data and generate a NSImage from it:

```<code>import PencilKit
</code>```

```<code>do {
    let pkDrawing = try PKDrawing(data: drawingData)
    let nsImage = pkDrawing.image(from: pkDrawing.bounds, scale: view.window?.backingScaleFactor ?? 1)
} catch {
    print(error)
}
</code>```

Title: Show PKDrawing on macOS in SwiftUI

Body:
You can initialize a new PKDrawing object from your drawing data and generate a NSImage from it:

import PencilKit

do {
    let pkDrawing = try PKDrawing(data: drawingData)
    let nsImage = pkDrawing.image(from: pkDrawing.bounds, scale: view.window?.backingScaleFactor ?? 1)
} catch {
    print(error)
}


问:
Selenium + facebook php-webdriver: Unable to create new service: ChromeDriverService
I'm trying to set up Selenium with the facebook php-webdriver. This is what I've done:

Ran composer require facebook/webdriver to install the package

Started the selenium server on port 4444 (default)

Downloaded the latest 32-bit chromedriver from enter link description here (No separate 64bit available)

Copied the chromedriver.exe to the project folder (don't know if this is necessary)

Stated chromedriver. It runs on port 9515 by default.

Ran the script to open a browser window in chrome.

In my script below, I get an error on the third line

```<code>$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::chrome();
$driver = RemoteWebDriver::create($host, $capabilities);
</code>```

The error:

```<code>Fatal error: Uncaught Facebook\WebDriver\Exception\SessionNotCreatedException: Unable to create new service: ChromeDriverService Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:33:15.31Z' System info: host: 'WINCOM', ip: '192.168.0.10', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '9.0.1' Driver info: driver.version: unknown in C:\xampp\htdocs\xampp\testnew\vendor\facebook\webdriver\lib\Exception\WebDriverException.php:154 Stack trace: #0 C:\xampp\htdocs\xampp\testnew\vendor\facebook\webdriver\lib\Remote\HttpCommandExecutor.php(320): Facebook\WebDriver\Exception\WebDriverException::throwException(33, 'Unable to creat...', Array) #1 C:\xampp\htdocs\xampp\testnew\vendor\facebook\webdriver\lib\Remote\RemoteWebDriver.php(126): Facebook\WebDriver\Remote\HttpCommandExecutor->execute(Object(Facebook\WebDriver\Remote\WebDriverCommand)) #2 C:\xampp\htdocs\xampp\testnew\test.php(11): Facebook\WebDriver\Remote\RemoteWebDriver::create('http://localhos...', Object(Facebook\WebDriver in C:\xampp\htdocs\xampp\testnew\vendor\facebook\webdriver\lib\Exception\WebDriverException.php on line 154
</code>```

In the Selenium terminal, I see this message:

```<code>14:18:08.607 INFO [ActiveSessionFactory.lambda$apply$11] - Matched factory org.openqa.selenium.remote.server.ServicedSession$Factory (provider:org.openqa.selenium.chrome.ChromeDriverService)
</code>```

Can anyone direct me on how to solve this. I've looked everywhere, but nothing seems to work.

Thanks

答:
Running geckodriver with root user I got the same problem.
Running geckodriver with same user than php scripts, it started to work.
You can try running both with unprivileged user.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to set up Selenium with the facebook php-webdriver. This is what I've done:

Ran composer require facebook/webdriver to install the package

Started the selenium server on port 4444 (default)

Downloaded the latest 32-bit chromedriver from enter link description here (No separate 64bit available)

Copied the chromedriver.exe to the project folder (don't know if this is necessary)

Stated chromedriver. It runs on port 9515 by default.

Ran the script to open a browser window in chrome.

In my script below, I get an error on the third line

$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::chrome();
$driver = RemoteWebDriver::create($host, $capabilities);

The error:

Fatal error: Uncaught Facebook\WebDriver\Exception\SessionNotCreatedException: Unable to create new service: ChromeDriverService Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:33:15.31Z' System info: host: 'WINCOM', ip: '192.168.0.10', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '9.0.1' Driver info: driver.version: unknown in C:\xampp\htdocs\xampp\testnew\vendor\facebook\webdriver\lib\Exception\WebDriverException.php:154 Stack trace: #0 C:\xampp\htdocs\xampp\testnew\vendor\facebook\webdriver\lib\Remote\HttpCommandExecutor.php(320): Facebook\WebDriver\Exception\WebDriverException::throwException(33, 'Unable to creat...', Array) #1 C:\xampp\htdocs\xampp\testnew\vendor\facebook\webdriver\lib\Remote\RemoteWebDriver.php(126): Facebook\WebDriver\Remote\HttpCommandExecutor->execute(Object(Facebook\WebDriver\Remote\WebDriverCommand)) #2 C:\xampp\htdocs\xampp\testnew\test.php(11): Facebook\WebDriver\Remote\RemoteWebDriver::create('http://localhos...', Object(Facebook\WebDriver in C:\xampp\htdocs\xampp\testnew\vendor\facebook\webdriver\lib\Exception\WebDriverException.php on line 154

In the Selenium terminal, I see this message:

14:18:08.607 INFO [ActiveSessionFactory.lambda$apply$11] - Matched factory org.openqa.selenium.remote.server.ServicedSession$Factory (provider:org.openqa.selenium.chrome.ChromeDriverService)

Can anyone direct me on how to solve this. I've looked everywhere, but nothing seems to work.

Thanks


问:
CreateInstance inside Extension Method not allowed?
I'm trying to convert my IQueryable<TEntity> results to IEnumerable<TDomainModel> via an extension method.

```<code>IEnumerable<DeviceModel> resultEntities =  _unitofwork.PersonDeviceRepository
.GetUnassociatedDevices()
.AddFilters(deviceByTypeQueryObject.AsExpression())
.ToDomainModels<DeviceModel,Device>();
</code>```

The IQueryable Extension is:

```<code>public static IEnumerable<TDomainModel> ToDomainModels<TDomainModel, TEntity>(this IQueryable<TEntity> queryableEntities)
{
IEnumerable<TDomainModel> domainModels =
queryableEntities
.Select(indiv => (TDomainModel)Activator.CreateInstance(typeof(TDomainModel), indiv));
return domainModels;
}
</code>```

It compiles but errors in runtime:

```<code>System.InvalidOperationException: The client projection contains a reference to a constant expression of 'System.RuntimeType' which is being passed as an argument to the method 'CreateInstance'.

</code>```

But it works if the Activator.CreateInstance conversion is NOT done in as part of an extension method. ie: in a regular method

Why is this happening?

答:
Found the issue:

I was feeding an IQueryable to the Extension method, but it doesn't work. It had nothing to do with the CreateInstance.

It worked after first converting the IQueryable to AsEnumerable, then fed it to the ToDomainModel extension method.

```<code>IEnumerable<DeviceModel> resultEntities = _unitofwork.PersonDeviceRepository.GetUnassociatedDevices().AddFilters(deviceByTypeQueryObject.AsExpression()).AsEnumerable().ToDomainModels<Device,DeviceModel>();
</code>```

The extension method was rewritten for IEnumerable instead of IQueryable

```<code>        public static IEnumerable<TDomainModel> ToDomainModels<TEntity, TDomainModel>(this IEnumerable<TEntity> enumerableEntities)
        {
            IEnumerable<TDomainModel> domainModels = queryableEntities.Select(indiv => (TDomainModel)Activator.CreateInstance(typeof(TDomainModel), indiv));
            return domainModels;
        }
</code>```

Body:
I'm trying to convert my IQueryable<TEntity> results to IEnumerable<TDomainModel> via an extension method.

IEnumerable<DeviceModel> resultEntities =  _unitofwork.PersonDeviceRepository
.GetUnassociatedDevices()
.AddFilters(deviceByTypeQueryObject.AsExpression())
.ToDomainModels<DeviceModel,Device>();

The IQueryable Extension is:

public static IEnumerable<TDomainModel> ToDomainModels<TDomainModel, TEntity>(this IQueryable<TEntity> queryableEntities)
{
IEnumerable<TDomainModel> domainModels =
queryableEntities
.Select(indiv => (TDomainModel)Activator.CreateInstance(typeof(TDomainModel), indiv));
return domainModels;
}

It compiles but errors in runtime:

System.InvalidOperationException: The client projection contains a reference to a constant expression of 'System.RuntimeType' which is being passed as an argument to the method 'CreateInstance'.

But it works if the Activator.CreateInstance conversion is NOT done in as part of an extension method. ie: in a regular method

Why is this happening?

Body:
Found the issue:

I was feeding an IQueryable to the Extension method, but it doesn't work. It had nothing to do with the CreateInstance.

It worked after first converting the IQueryable to AsEnumerable, then fed it to the ToDomainModel extension method.

IEnumerable<DeviceModel> resultEntities = _unitofwork.PersonDeviceRepository.GetUnassociatedDevices().AddFilters(deviceByTypeQueryObject.AsExpression()).AsEnumerable().ToDomainModels<Device,DeviceModel>();

The extension method was rewritten for IEnumerable instead of IQueryable

        public static IEnumerable<TDomainModel> ToDomainModels<TEntity, TDomainModel>(this IEnumerable<TEntity> enumerableEntities)
        {
            IEnumerable<TDomainModel> domainModels = queryableEntities.Select(indiv => (TDomainModel)Activator.CreateInstance(typeof(TDomainModel), indiv));
            return domainModels;
        }


问:
weblogic undeploy apps command line
I have a requirement where i need to undeploy war files in weblogic using command line, the below code does it for me :

```<code> java weblogic.Deployer -adminurl t3://localhost:8001 -user weblogic -password password123  -name <name> -undeploy
</code>```

But the file names change after every deployment, i,e (file 1.0.0 and file 1.1.1).

i need a command in such a way so that it undeploys all the files present in that server.

can any body let me know how to undeploy all files at a single go ?

Thanks in advance,

Vishal

答:
I have found out how to undeploy all the apps without using files</p>
```<code>def undeployWars():
    cd("AppDeployments")
    namesWars = ls(returnMap='true')
    for nameWar in namesWars:
        undeploy(nameWar)

connect('weblogic', 'weblogic01', 't3://localhost:7001')
undeployWars()
disconnect()
exit()
</code>```

Title: weblogic undeploy apps command line

Body:
I have a requirement where i need to undeploy war files in weblogic using command line, the below code does it for me :

 java weblogic.Deployer -adminurl t3://localhost:8001 -user weblogic -password password123  -name <name> -undeploy

But the file names change after every deployment, i,e (file 1.0.0 and file 1.1.1).

i need a command in such a way so that it undeploys all the files present in that server.

can any body let me know how to undeploy all files at a single go ?

Thanks in advance,

Vishal

Body:
I have found out how to undeploy all the apps without using files

def undeployWars():
    cd("AppDeployments")
    namesWars = ls(returnMap='true')
    for nameWar in namesWars:
        undeploy(nameWar)

connect('weblogic', 'weblogic01', 't3://localhost:7001')
undeployWars()
disconnect()
exit()


问:
How to open keyboard automatically in React Native?
I have a screen in my React Native application in which I have few text fields.

I was wondering if there is any way in which on screen load my keyword opens automatically  and focuses on my first text input field?

I was searching for something like stateAlwaysVisible in android.

答:
another solution :)</p>
```<code>import React, { useRef } from 'react'

export function mycomponent(props) {
   const inputRef = useRef();

   return(
         <TextInput
           ref={inputRef}
           onLayout={()=> inputRef.current.focus()}>
         </TextInput>
   )
}

</code>```

Body:
another solution :)

import React, { useRef } from 'react'

export function mycomponent(props) {
   const inputRef = useRef();

   return(
         <TextInput
           ref={inputRef}
           onLayout={()=> inputRef.current.focus()}>
         </TextInput>
   )
}


问:
How to activate compression for Azure Front Door routes using Bicep?
I am using Azure Front Door Standard/Premium and have already manually enabled compression for my UI routes via Azure Portal. I wanted to map this configuration as IaC with Bicep. However, there was no proper documentation on how to do this. My attempts:

I checked the Azure Bicep templates for Azure Front Door routes. Here I found a reference to a property compressionSettings: any(), whose usage was not further specified.

My next approach was to export the manual configuration in the portal via "Export template" as ARM and then compile it to Bicep. However, the compressionSettings property always kept the value {}. If I deploy my bicep template with the value compressionSettings: {}, then the compression in the portal remains disabled.

So how can I enable compression for Azure Front Door using Bicep?

答:
I found the solution by manually searching in azure-quickstart-templates. At the bottom of the page: Microsoft.Cdn profiles/afdEndpoints/routes 2020-09-01, I found the template Front Door Standard/Premium. After analyzing the main.bicep file here, the compression settings must be set as follows:

```<code>compressionSettings: {
   contentTypesToCompress: [
     'application/javascript'
     'application/json'
     'font/woff'
     'font/woff2'
     'image/svg+xml'
     'image/x-icon'
     'text/css'
     'text/html'
   ]
   isCompressionEnabled: true
}
</code>```

Within a section of my entire code it then looks like this:

```<code>var contentTypesToCompress = [
  'application/javascript'
  'application/json'
  'font/woff'
  'font/woff2'
  'image/svg+xml'
  'image/x-icon'
  'text/css'
  'text/html'
]

resource profile 'Microsoft.Cdn/profiles@2020-09-01' = {
  name: 'frontDoor'
  location: 'global'
  sku: {
    name: 'Premium_AzureFrontDoor'
  }
  tags: tags
}

resource endpoint 'Microsoft.Cdn/profiles/afdEndpoints@2020-09-01' = {
  parent: profile
  name: 'endpoint'
  location: 'Global'
  tags: tags
  properties: {
    originResponseTimeoutSeconds: 60
    enabledState: 'Enabled'
  }
}

resource route 'Microsoft.Cdn/profiles/afdEndpoints/routes@2020-09-01' = {
  parent: endpoint
  name: 'route'
  properties: {
    queryStringCachingBehavior: 'IgnoreQueryString'
    compressionSettings: {
      contentTypesToCompress: contentTypesToCompress
      isCompressionEnabled: true
    }
    ...
  }
  dependsOn: [
    profile
  ]
}
</code>```

Since this has not really been documented anywhere so far, I thought it would be useful to share this here in Q&A-style.

Body:
I found the solution by manually searching in azure-quickstart-templates. At the bottom of the page: Microsoft.Cdn profiles/afdEndpoints/routes 2020-09-01, I found the template Front Door Standard/Premium. After analyzing the main.bicep file here, the compression settings must be set as follows:

compressionSettings: {
   contentTypesToCompress: [
     'application/javascript'
     'application/json'
     'font/woff'
     'font/woff2'
     'image/svg+xml'
     'image/x-icon'
     'text/css'
     'text/html'
   ]
   isCompressionEnabled: true
}

Within a section of my entire code it then looks like this:

var contentTypesToCompress = [
  'application/javascript'
  'application/json'
  'font/woff'
  'font/woff2'
  'image/svg+xml'
  'image/x-icon'
  'text/css'
  'text/html'
]

resource profile 'Microsoft.Cdn/profiles@2020-09-01' = {
  name: 'frontDoor'
  location: 'global'
  sku: {
    name: 'Premium_AzureFrontDoor'
  }
  tags: tags
}

resource endpoint 'Microsoft.Cdn/profiles/afdEndpoints@2020-09-01' = {
  parent: profile
  name: 'endpoint'
  location: 'Global'
  tags: tags
  properties: {
    originResponseTimeoutSeconds: 60
    enabledState: 'Enabled'
  }
}

resource route 'Microsoft.Cdn/profiles/afdEndpoints/routes@2020-09-01' = {
  parent: endpoint
  name: 'route'
  properties: {
    queryStringCachingBehavior: 'IgnoreQueryString'
    compressionSettings: {
      contentTypesToCompress: contentTypesToCompress
      isCompressionEnabled: true
    }
    ...
  }
  dependsOn: [
    profile
  ]
}

Since this has not really been documented anywhere so far, I thought it would be useful to share this here in Q&A-style.


问:
Return value from Ajax callback?
I have a JavaScript class that handles queries to a local DB (on a WebOs device). Now what I want to do is, create a model with all my basic queries to simplify my code.

So first I create a function:

```<code>getLists: function(){
          this.query( 'SELECT * FROM lists ORDER BY rowID DESC', {
                onSuccess:  enyo.bind(this,function(data) { this.getData(data); } ),
                onError: function() { return false; } } );
   }
</code>```

And than I have my callback function which receives the data:

```<code>getData: function(data){
       return data;
   }
</code>```

Now what I would like to do, is call it like this from my app:

```<code>var data = getLists();
</code>```

The problem is, this is not returning the data from my callback function (getData). My question is how can I have "getLists" return the data from the callback?

Thank you

答:
You don't get to.  The first A in AJAX is Asynchronous.  The requests happen "out of time" with the other processing.  Your call to getLists returns after it launches the AJAX request, and the callback function is called when the remote server responds to the AJAX request.

-- Edited for comments --

If you want to "watch" a variable you can use something like this:

```<code>// Set up a container for the data to return to.
var retData;

// Modify the getData function to assign to the global variable
getData: function (data) {
  retData = data;
}

// Start the "wait" process.
var myInterval = setInterval(function () {
  if (retData == undefined) {
    return;
  }

  // when the return data shows up stop waiting.
  clearInterval(myInterval);

  // some other data processing here in this function
  // or trigger the actual processing function.
  // don't have to pass retData to it, it's global, the
  // data handler function can retrieve it itself.
  myDataHandler();
}, 1000);

// make the ajax call here.
getLists();
</code>```

Title: Return value from Ajax callback?

Body:
I have a JavaScript class that handles queries to a local DB (on a WebOs device). Now what I want to do is, create a model with all my basic queries to simplify my code.

So first I create a function:

getLists: function(){
          this.query( 'SELECT * FROM lists ORDER BY rowID DESC', {
                onSuccess:  enyo.bind(this,function(data) { this.getData(data); } ),
                onError: function() { return false; } } );
   }

And than I have my callback function which receives the data:

getData: function(data){
       return data;
   }

Now what I would like to do, is call it like this from my app:

var data = getLists();

The problem is, this is not returning the data from my callback function (getData). My question is how can I have "getLists" return the data from the callback?

Thank you

Body:
You don't get to.  The first A in AJAX is Asynchronous.  The requests happen "out of time" with the other processing.  Your call to getLists returns after it launches the AJAX request, and the callback function is called when the remote server responds to the AJAX request.

-- Edited for comments --

If you want to "watch" a variable you can use something like this:

// Set up a container for the data to return to.
var retData;

// Modify the getData function to assign to the global variable
getData: function (data) {
  retData = data;
}

// Start the "wait" process.
var myInterval = setInterval(function () {
  if (retData == undefined) {
    return;
  }

  // when the return data shows up stop waiting.
  clearInterval(myInterval);

  // some other data processing here in this function
  // or trigger the actual processing function.
  // don't have to pass retData to it, it's global, the
  // data handler function can retrieve it itself.
  myDataHandler();
}, 1000);

// make the ajax call here.
getLists();


问:
renderer.writePDF doesn't work without error
I learn swift and faced with problem: when i try write pdf file in document directory nothing happened.
Code:

```<code>func createPDF() {
        // MARK: - create path
        let documentDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
        let path = documentDir.appendingPathComponent("\(clientCompanyName + UUID().uuidString).pdf")

        // MARK: - create meta
        let pdfMetaData = [
            kCGPDFContextCreator: "something",
            kCGPDFContextAuthor: "https://bla-bla.com"
        ]
        let format = UIGraphicsPDFRendererFormat()
        format.documentInfo = pdfMetaData as [String: Any]

        // MARK: - set page size
        let pageWidth = 8.5 * 72.0
        let pageHeight = 11 * 72.0
        let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)

        // MARK: - render
        let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
        try? renderer.writePDF(to: path) { (context) in
            let attributes = [
                NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
            ]
            let text = clientCompanyName + " " + formattedDate
            text.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
        }
    }
</code>```

When i start this code, i don't see any errors in terminal. But if i open Files, my document didn't save

答:
So I think the problem was that you were not allowed to write to the cachesDirectory. So replace everything with that, it should work. Also with with pageDatas you are now able to print in CGRects on multiple pages, just append the array, you're welcome :)

```<code>    func createPDF() -> URL {
            // MARK: - create path
        let documentDir = FileManager.default.temporaryDirectory
            let path = documentDir.appendingPathComponent("\("clientCompanyName" + UUID().uuidString).pdf")

            // MARK: - create meta
            let pdfMetaData = [
                kCGPDFContextCreator: "something",
                kCGPDFContextAuthor: "https://bla-bla.com"
            ]
        let format = UIGraphicsPDFRendererFormat()
        format.documentInfo = pdfMetaData as [String: Any]

        // MARK: - set page size
        let pageWidth = 8.5 * 72.0
        let pageHeight = 11 * 72.0
        let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)

        // MARK: - render
        let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
        let attributes = [
                NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
            ]
        let text = "clientCompanyName" + " " + "formattedDate"
        let myAttributedString = NSAttributedString(string: text, attributes: attributes)
        let pageDatas = [[[pageRect, myAttributedString]]]
        let pdfData = createCustomPdfDataa(renderer: renderer, pageDatas: pageDatas)
        do {
            try pdfData.write(to: path)
        } catch {
            fatalError("Sorry this does not work, because \(error)")
        }
        return path
    }

    func createCustomPdfDataa(renderer: UIGraphicsPDFRenderer, pageDatas: [[[Any?]]]) -> Data {
        // render context to pdfData
        let data = renderer.pdfData { (context) in
            // create pages
            for pageNumber in 0..<pageDatas.count {
                context.beginPage()
                let pageData = pageDatas[pageNumber]
                for textIndex in 0..<pageData.count {
                    drawAttributedText(inFrame: pageData[textIndex][0] as! CGRect, pageData[textIndex][1] as! NSAttributedString)
                }
            }
        }
        return data
    }

    func drawAttributedText(inFrame: CGRect, _ text: NSAttributedString) {
        text.draw(in: inFrame)
    }
}
</code>```

The createPDF function returns the url you are saving to, so call it with this code below if you want to display it in a PDFView:

```<code>    let documentDir = createPDF()
    let data = readDataFromUrl(with: documentDir)
    pdfView.document = PDFDocument(data: data)

func readDataFromUrl(with url: URL) -> Data {
    // PathUrl
    let fileURL = url
    // Read
    var readData = Data()
    do {
        readData = try Data(contentsOf: fileURL)
    } catch let jsonErr {
        print("Error read file:", jsonErr)
    }
    return readData
}
</code>```

Body:
I learn swift and faced with problem: when i try write pdf file in document directory nothing happened.
Code:

func createPDF() {
        // MARK: - create path
        let documentDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
        let path = documentDir.appendingPathComponent("\(clientCompanyName + UUID().uuidString).pdf")

        // MARK: - create meta
        let pdfMetaData = [
            kCGPDFContextCreator: "something",
            kCGPDFContextAuthor: "https://bla-bla.com"
        ]
        let format = UIGraphicsPDFRendererFormat()
        format.documentInfo = pdfMetaData as [String: Any]

        // MARK: - set page size
        let pageWidth = 8.5 * 72.0
        let pageHeight = 11 * 72.0
        let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)

        // MARK: - render
        let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
        try? renderer.writePDF(to: path) { (context) in
            let attributes = [
                NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
            ]
            let text = clientCompanyName + " " + formattedDate
            text.draw(at: CGPoint(x: 0, y: 0), withAttributes: attributes)
        }
    }

When i start this code, i don't see any errors in terminal. But if i open Files, my document didn't save

Body:
So I think the problem was that you were not allowed to write to the cachesDirectory. So replace everything with that, it should work. Also with with pageDatas you are now able to print in CGRects on multiple pages, just append the array, you're welcome :)

    func createPDF() -> URL {
            // MARK: - create path
        let documentDir = FileManager.default.temporaryDirectory
            let path = documentDir.appendingPathComponent("\("clientCompanyName" + UUID().uuidString).pdf")

            // MARK: - create meta
            let pdfMetaData = [
                kCGPDFContextCreator: "something",
                kCGPDFContextAuthor: "https://bla-bla.com"
            ]
        let format = UIGraphicsPDFRendererFormat()
        format.documentInfo = pdfMetaData as [String: Any]

        // MARK: - set page size
        let pageWidth = 8.5 * 72.0
        let pageHeight = 11 * 72.0
        let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)

        // MARK: - render
        let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
        let attributes = [
                NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 72)
            ]
        let text = "clientCompanyName" + " " + "formattedDate"
        let myAttributedString = NSAttributedString(string: text, attributes: attributes)
        let pageDatas = [[[pageRect, myAttributedString]]]
        let pdfData = createCustomPdfDataa(renderer: renderer, pageDatas: pageDatas)
        do {
            try pdfData.write(to: path)
        } catch {
            fatalError("Sorry this does not work, because \(error)")
        }
        return path
    }

    func createCustomPdfDataa(renderer: UIGraphicsPDFRenderer, pageDatas: [[[Any?]]]) -> Data {
        // render context to pdfData
        let data = renderer.pdfData { (context) in
            // create pages
            for pageNumber in 0..<pageDatas.count {
                context.beginPage()
                let pageData = pageDatas[pageNumber]
                for textIndex in 0..<pageData.count {
                    drawAttributedText(inFrame: pageData[textIndex][0] as! CGRect, pageData[textIndex][1] as! NSAttributedString)
                }
            }
        }
        return data
    }

    func drawAttributedText(inFrame: CGRect, _ text: NSAttributedString) {
        text.draw(in: inFrame)
    }
}

The createPDF function returns the url you are saving to, so call it with this code below if you want to display it in a PDFView:

    let documentDir = createPDF()
    let data = readDataFromUrl(with: documentDir)
    pdfView.document = PDFDocument(data: data)

func readDataFromUrl(with url: URL) -> Data {
    // PathUrl
    let fileURL = url
    // Read
    var readData = Data()
    do {
        readData = try Data(contentsOf: fileURL)
    } catch let jsonErr {
        print("Error read file:", jsonErr)
    }
    return readData
}


问:
Where i can see the font code of scipy special chndtr and chndtrix?
I am navigating in the github of scipy but I couldn't find the definition code of scipy.special.chndtr. Any suggestions?</p>

答:
Seems like these are wrappers functions:

```<code>  "chndtr": {
        "cdf_wrappers.h": {
            "cdfchn1_wrap": "ddd->d"
        }
    },
    "chndtrix": {
        "cdf_wrappers.h": {
            "cdfchn2_wrap": "ddd->d"
        }
    },
</code>```

and you can find cdfchn1_wrap under  scipy/special/cdf_wrappers.c.

https://github.com/scipy/scipy/blob/main/scipy/special/cdf_wrappers.c

the same thing with chndtrix , you can find it in the same file under cdfchn2_wrap

Body:
Seems like these are wrappers functions:

  "chndtr": {
        "cdf_wrappers.h": {
            "cdfchn1_wrap": "ddd->d"
        }
    },
    "chndtrix": {
        "cdf_wrappers.h": {
            "cdfchn2_wrap": "ddd->d"
        }
    },

and you can find cdfchn1_wrap under  scipy/special/cdf_wrappers.c.

https://github.com/scipy/scipy/blob/main/scipy/special/cdf_wrappers.c

the same thing with chndtrix , you can find it in the same file under cdfchn2_wrap


问:
How do I use GZipStream with System.IO.MemoryStream?
I am having an issue with this test function where I take an in memory string, compress it, and decompress it.  The compression works great, but I can't seem to get the decompression to work.

```<code>//Compress
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
GZipStream tinyStream = new GZipStream(outStream, CompressionMode.Compress);
mStream.Position = 0;
mStream.CopyTo(tinyStream);

//Decompress
outStream.Position = 0;
GZipStream bigStream = new GZipStream(outStream, CompressionMode.Decompress);
System.IO.MemoryStream bigStreamOut = new System.IO.MemoryStream();
bigStream.CopyTo(bigStreamOut);

//Results:
//bigStreamOut.Length == 0
//outStream.Position == the end of the stream.
</code>```

I believe that bigStream out should at least have data in it, especially if my source stream (outStream) is being read. is this a MSFT bug or mine?

答:
I thought I would share this answer for anyone interested in reproducing this on PowerShell, the code is mostly inspired from Timwi's helpful answer, however unfortunately as of now there is no implementation for the using statement like on C# for PowerShell, hence the need to manually dispose the streams before output.

Functions below requires PowerShell 5.0+.

Required using statements and ArgumentCompleter for -Encoding Parameter.

Improved versions of these 2 functions as well as Compression From File Path and Expansion from File Path can be found in this repo as well as in the PowerShell Gallery.

using namespace System.Text
using namespace System.IO
using namespace System.IO.Compression
using namespace System.Collections
using namespace System.Management.Automation
using namespace System.Collections.Generic
using namespace System.Management.Automation.Language

Add-Type -AssemblyName System.IO.Compression

class EncodingCompleter : IArgumentCompleter {
    [IEnumerable[CompletionResult]] CompleteArgument (
        [string] $commandName,
        [string] $parameterName,
        [string] $wordToComplete,
        [CommandAst] $commandAst,
        [IDictionary] $fakeBoundParameters
    ) {
        [CompletionResult[]] $arguments = foreach($enc in [Encoding]::GetEncodings().Name) {
            if($enc.StartsWith($wordToComplete)) {
                [CompletionResult]::new($enc)
            }
        }
        return $arguments
    }
}
```
<ul>
<li>Compression from <em><strong>string</strong></em> to <em><strong>Base64 GZip compressed string</strong></em>:</li>
</ul>
<pre class="lang-bash prettyprint-override"><code>function Compress-GzipString {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string] $String,

        [Parameter()]
        [ArgumentCompleter([EncodingCompleter])]
        [string] $Encoding = 'utf-8',

        [Parameter()]
        [CompressionLevel] $CompressionLevel = 'Optimal'
    )

    try {
        $enc       = [Encoding]::GetEncoding($Encoding)
        $outStream = [MemoryStream]::new()
        $gzip      = [GZipStream]::new($outStream, [CompressionMode]::Compress, $CompressionLevel)
        $inStream  = [MemoryStream]::new($enc.GetBytes($string))
        $inStream.CopyTo($gzip)
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
    finally {
        $gzip, $outStream, $inStream | ForEach-Object Dispose
    }

    try {
        [Convert]::ToBase64String($outStream.ToArray())
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
}
</code>```

Expansion from Base64 GZip compressed string to string:

function Expand-GzipString {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string] $String,

        [Parameter()]
        [ArgumentCompleter([EncodingCompleter])]
        [string] $Encoding = 'utf-8'
    )

    try {
        $enc       = [Encoding]::GetEncoding($Encoding)
        $bytes     = [Convert]::FromBase64String($String)
        $outStream = [MemoryStream]::new()
        $inStream  = [MemoryStream]::new($bytes)
        $gzip      = [GZipStream]::new($inStream, [CompressionMode]::Decompress)
        $gzip.CopyTo($outStream)
        $enc.GetString($outStream.ToArray())
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
    finally {
        $gzip, $outStream, $inStream | ForEach-Object Dispose
    }
}
```
<p>And for the little <em><strong>Length</strong></em> comparison, querying the Loripsum API:</p>
<pre class="lang-bash prettyprint-override"><code>$loremIp = Invoke-RestMethod loripsum.net/api/10/long
$compressedLoremIp = Compress-GzipString $loremIp

$loremIp, $compressedLoremIp | Select-Object Length

Length
------
  8353
  4940

(Expand-GzipString $compressedLoremIp) -eq $loremIp # => Should be True
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am having an issue with this test function where I take an in memory string, compress it, and decompress it.  The compression works great, but I can't seem to get the decompression to work.

//Compress
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
GZipStream tinyStream = new GZipStream(outStream, CompressionMode.Compress);
mStream.Position = 0;
mStream.CopyTo(tinyStream);

//Decompress
outStream.Position = 0;
GZipStream bigStream = new GZipStream(outStream, CompressionMode.Decompress);
System.IO.MemoryStream bigStreamOut = new System.IO.MemoryStream();
bigStream.CopyTo(bigStreamOut);

//Results:
//bigStreamOut.Length == 0
//outStream.Position == the end of the stream.

I believe that bigStream out should at least have data in it, especially if my source stream (outStream) is being read. is this a MSFT bug or mine?

Body:
I thought I would share this answer for anyone interested in reproducing this on PowerShell, the code is mostly inspired from Timwi's helpful answer, however unfortunately as of now there is no implementation for the using statement like on C# for PowerShell, hence the need to manually dispose the streams before output.

Functions below requires PowerShell 5.0+.

Required using statements and ArgumentCompleter for -Encoding Parameter.

Improved versions of these 2 functions as well as Compression From File Path and Expansion from File Path can be found in this repo as well as in the PowerShell Gallery.

using namespace System.Text
using namespace System.IO
using namespace System.IO.Compression
using namespace System.Collections
using namespace System.Management.Automation
using namespace System.Collections.Generic
using namespace System.Management.Automation.Language

Add-Type -AssemblyName System.IO.Compression

class EncodingCompleter : IArgumentCompleter {
    [IEnumerable[CompletionResult]] CompleteArgument (
        [string] $commandName,
        [string] $parameterName,
        [string] $wordToComplete,
        [CommandAst] $commandAst,
        [IDictionary] $fakeBoundParameters
    ) {
        [CompletionResult[]] $arguments = foreach($enc in [Encoding]::GetEncodings().Name) {
            if($enc.StartsWith($wordToComplete)) {
                [CompletionResult]::new($enc)
            }
        }
        return $arguments
    }
}

Compression from string to Base64 GZip compressed string:

function Compress-GzipString {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string] $String,

        [Parameter()]
        [ArgumentCompleter([EncodingCompleter])]
        [string] $Encoding = 'utf-8',

        [Parameter()]
        [CompressionLevel] $CompressionLevel = 'Optimal'
    )

    try {
        $enc       = [Encoding]::GetEncoding($Encoding)
        $outStream = [MemoryStream]::new()
        $gzip      = [GZipStream]::new($outStream, [CompressionMode]::Compress, $CompressionLevel)
        $inStream  = [MemoryStream]::new($enc.GetBytes($string))
        $inStream.CopyTo($gzip)
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
    finally {
        $gzip, $outStream, $inStream | ForEach-Object Dispose
    }

    try {
        [Convert]::ToBase64String($outStream.ToArray())
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
}

Expansion from Base64 GZip compressed string to string:

function Expand-GzipString {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string] $String,

        [Parameter()]
        [ArgumentCompleter([EncodingCompleter])]
        [string] $Encoding = 'utf-8'
    )

    try {
        $enc       = [Encoding]::GetEncoding($Encoding)
        $bytes     = [Convert]::FromBase64String($String)
        $outStream = [MemoryStream]::new()
        $inStream  = [MemoryStream]::new($bytes)
        $gzip      = [GZipStream]::new($inStream, [CompressionMode]::Decompress)
        $gzip.CopyTo($outStream)
        $enc.GetString($outStream.ToArray())
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
    finally {
        $gzip, $outStream, $inStream | ForEach-Object Dispose
    }
}

And for the little Length comparison, querying the Loripsum API:

$loremIp = Invoke-RestMethod loripsum.net/api/10/long
$compressedLoremIp = Compress-GzipString $loremIp

$loremIp, $compressedLoremIp | Select-Object Length

Length
------
  8353
  4940

(Expand-GzipString $compressedLoremIp) -eq $loremIp # => Should be True