问:
How can I generate JSON schema for list of dataclass with pydantic?
I am trying to generate JSON Schema from python data classes that contain lists of other data classes as parameters. I don't really care about any functionality from pydantic other than generating json schema, since I am just using the output to auto-generate a web frontend. So solutions using other libraries are fine.

from typing import List
from dataclasses import dataclass
import pydantic

@dataclass()
class SomeParameters:
    a: int = 5

@dataclass()
class SomeMoreParameters:
    another: List[SomeParameters]

pydantic_cls = pydantic.dataclasses.dataclass(SomeMoreParameters)
schema = pydantic_cls.__pydantic_model__.schema()
```
<p>This code errors with the following stacktrace (you can use <code> SKIP_CYTHON=1 pip install --no-cache-dir --no-binary :all: pydantic</code> to install pydantic so that you can debug into it):</p>
```Traceback (most recent call last):
  File "/home/veith/Projects/job-ui-parametrization/debug.py", line 17, in <module>
    schema = pydantic_cls.__pydantic_model__.schema()
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/main.py", line 647, in schema
    s = model_schema(cls, by_alias=by_alias, ref_template=ref_template)
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 185, in model_schema
    m_schema, m_definitions, nested_models = model_process_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 617, in model_process_schema
    m_schema, m_definitions, nested_models = model_type_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 658, in model_type_schema
    f_schema, f_definitions, f_nested_models = field_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 258, in field_schema
    f_schema, f_definitions, f_nested_models = field_type_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 498, in field_type_schema
    items_schema, f_definitions, f_nested_models = field_singleton_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 848, in field_singleton_schema
    return field_singleton_sub_fields_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 736, in field_singleton_sub_fields_schema
    return field_type_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 563, in field_type_schema
    f_schema, f_definitions, f_nested_models = field_singleton_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 947, in field_singleton_schema
    raise ValueError(f'Value not declarable with JSON Schema, field: {field}')
ValueError: Value not declarable with JSON Schema, field: name='_another' type=SomeParameters required=True

Process finished with exit code 1
```

Now according to JSON Schema documentation an array of things is valid.
The pydantic documentation uses list of integers, which also works for me.
I would expect that I can also use custom types in a list. The documentation further states Nested dataclasses are supported both in dataclasses and normal models.

Am I doing something wrong/not doing something that I should be doing? Or am I misunderstanding something, and this is actually not allowed?
What are some alternatives if this is the case?

答:
Interesting, your code is working for me on Python 3.9.1 (Windows). Just curious, what version of pydantic are you using?

Here is code that is working for me. Note you can use pydantic drop-in dataclasses to simplify the JSON schema generation a bit.

from typing import List
# from dataclasses import dataclass
from pydantic.dataclasses import dataclass

@dataclass
class SomeParameters:
    a: int = 5

@dataclass
class SomeMoreParameters:
    another: List[SomeParameters]

# pydantic_cls = pydantic.dataclasses.dataclass(SomeMoreParameters)
schema = SomeMoreParameters.__pydantic_model__.schema()
print(schema)
```
<p>Output:</p>
```{'title': 'SomeMoreParameters', 'type': 'object', 'properties': {'another': {'title': 'Another', 'type': 'array', 'items': {'$ref': '#/definitions/SomeParameters'}}}, 'required': ['another'], 'definitions': {'SomeParameters': {'title': 'SomeParameters', 'type': 'object', 'properties': {'a': {'title': 'A', 'default': 5, 'type': 'integer'}}}}}
```

Note: I am using pydantic==1.8.2.

Body:
I am trying to generate JSON Schema from python data classes that contain lists of other data classes as parameters. I don't really care about any functionality from pydantic other than generating json schema, since I am just using the output to auto-generate a web frontend. So solutions using other libraries are fine.

from typing import List
from dataclasses import dataclass
import pydantic

@dataclass()
class SomeParameters:
    a: int = 5

@dataclass()
class SomeMoreParameters:
    another: List[SomeParameters]

pydantic_cls = pydantic.dataclasses.dataclass(SomeMoreParameters)
schema = pydantic_cls.__pydantic_model__.schema()

This code errors with the following stacktrace (you can use  SKIP_CYTHON=1 pip install --no-cache-dir --no-binary :all: pydantic to install pydantic so that you can debug into it):

Traceback (most recent call last):
  File "/home/veith/Projects/job-ui-parametrization/debug.py", line 17, in <module>
    schema = pydantic_cls.__pydantic_model__.schema()
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/main.py", line 647, in schema
    s = model_schema(cls, by_alias=by_alias, ref_template=ref_template)
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 185, in model_schema
    m_schema, m_definitions, nested_models = model_process_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 617, in model_process_schema
    m_schema, m_definitions, nested_models = model_type_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 658, in model_type_schema
    f_schema, f_definitions, f_nested_models = field_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 258, in field_schema
    f_schema, f_definitions, f_nested_models = field_type_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 498, in field_type_schema
    items_schema, f_definitions, f_nested_models = field_singleton_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 848, in field_singleton_schema
    return field_singleton_sub_fields_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 736, in field_singleton_sub_fields_schema
    return field_type_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 563, in field_type_schema
    f_schema, f_definitions, f_nested_models = field_singleton_schema(
  File "/home/veith/Projects/job-ui-parametrization/venv/lib/python3.9/site-packages/pydantic/schema.py", line 947, in field_singleton_schema
    raise ValueError(f'Value not declarable with JSON Schema, field: {field}')
ValueError: Value not declarable with JSON Schema, field: name='_another' type=SomeParameters required=True

Process finished with exit code 1

Now according to JSON Schema documentation an array of things is valid.
The pydantic documentation uses list of integers, which also works for me.
I would expect that I can also use custom types in a list. The documentation further states Nested dataclasses are supported both in dataclasses and normal models.

Am I doing something wrong/not doing something that I should be doing? Or am I misunderstanding something, and this is actually not allowed?
What are some alternatives if this is the case?

Body:
Interesting, your code is working for me on Python 3.9.1 (Windows). Just curious, what version of pydantic are you using?

Here is code that is working for me. Note you can use pydantic drop-in dataclasses to simplify the JSON schema generation a bit.

from typing import List
# from dataclasses import dataclass
from pydantic.dataclasses import dataclass

@dataclass
class SomeParameters:
    a: int = 5

@dataclass
class SomeMoreParameters:
    another: List[SomeParameters]

# pydantic_cls = pydantic.dataclasses.dataclass(SomeMoreParameters)
schema = SomeMoreParameters.__pydantic_model__.schema()
print(schema)

Output:

{'title': 'SomeMoreParameters', 'type': 'object', 'properties': {'another': {'title': 'Another', 'type': 'array', 'items': {'$ref': '#/definitions/SomeParameters'}}}, 'required': ['another'], 'definitions': {'SomeParameters': {'title': 'SomeParameters', 'type': 'object', 'properties': {'a': {'title': 'A', 'default': 5, 'type': 'integer'}}}}}

Note: I am using pydantic==1.8.2.


来源: stackexchange

问:
@FetchRequest predicate is ignored if the context changes
I have a simple SwiftUI application with CoreData and two views. One view displays all "Place" objects. You can create new places and you can show the details for the place.
Inside the second view you can add "PlaceItem"s to a place.

The problem is that, once a new "PlaceItem" is added to the viewContext, the @NSFetchRequest seems to forget about its additional predicates, which I set in onAppear. Then every place item is shown inside the details view. Once I update the predicate manually (the refresh button), only the items from the selected place are visible again.

Any idea how this can be fixed? Here's the code for my two views:

```<code>struct PlaceView: View {
    @FetchRequest(sortDescriptors: []) private var places: FetchedResults<Place>
    @Environment(\.managedObjectContext) private var viewContext

    var body: some View {
        NavigationView {
            List(places) { place in
                NavigationLink {
                    PlaceItemsView(place: place)
                } label: {
                    Text(place.name ?? "")
                }

            }
        }
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let place = Place(context: viewContext)
                    place.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }

            }
        }
        .navigationTitle("Places")
    }
}

struct PlaceItemsView: View {
    @ObservedObject var place: Place
    @State var searchText = ""

    @FetchRequest(sortDescriptors: []) private var items: FetchedResults<PlaceItem>
    @Environment(\.managedObjectContext) private var viewContext

    func updatePredicate() {
        var predicates = [NSPredicate]()
        predicates.append(NSPredicate(format: "place == %@", place))
        if !searchText.isEmpty {
            predicates.append(NSPredicate(format: "name CONTAINS %@", searchText))
        }

        items.nsPredicate = NSCompoundPredicate(type: .and, subpredicates: predicates)
    }

    var body: some View {
        NavigationView {
            List(items) { item in
                Text(item.name ?? "");
            }
        }
        .onAppear(perform: updatePredicate)
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let item = PlaceItem(context: viewContext)
                    item.place = place
                    item.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }
            }

            ToolbarItem(placement: .navigationBarLeading) {
                Button(action: updatePredicate) {
                    Label("Refresh", systemImage: "arrow.clockwise")
                }
            }
        }
        .searchable(
            text: $searchText,
            placement: .navigationBarDrawer(displayMode: .always),
            prompt: "Search or add articles …"
        )
        .onAppear(perform: updatePredicate)
        .onChange(of: searchText, perform: { _ in
            updatePredicate()
        })
        .navigationTitle(place.name ?? "")
    }
}

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    var body: some View {
        NavigationView {
            PlaceView()
        }
    }
}
</code>```

Thanks!

答:
It's best to break Views up by the data they need, its called having a tighter invalidation and solves your problem of updating the fetch request too! e.g.

```<code>struct PlaceItemsView {
     @FetchRequest private var items: FetchedResults<PlaceItem>

    var body: some View {
        List(items) { item in
            Text(item.name ?? "")
        }
    }
}

// body called when either searchText is different or its a different place (not when the place's properties change because no need to)
struct SearchPlaceView {
    let searchText: String
    let place: Place

    var predicate: NSPredicate {
        var predicates = [NSPredicate]()
        predicates.append(NSPredicate(format: "place == %@", place))
        if !searchText.isEmpty {
            predicates.append(NSPredicate(format: "name CONTAINS %@", searchText))
        }
        return NSCompoundPredicate(type: .and, subpredicates: predicates)
    }

    var body: some View {
         PlaceItemsView(items:FetchRequest<PlaceItem>(sortDescriptors:[], predicate:predicate))
    }
}

// body called when either the place has a change or search text changes
struct PlaceItemsView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @ObservedObject var place: Place
    @State var searchText = ""

    var body: some View {
        NavigationView {
            SearchPlaceView(searchTest:searchText, place: place)
        }
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let item = PlaceItem(context: viewContext)
                    item.place = place
                    item.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }
            }

            ToolbarItem(placement: .navigationBarLeading) {
                Button(action: updatePredicate) {
                    Label("Refresh", systemImage: "arrow.clockwise")
                }
            }
        }
        .searchable(
            text: $searchText,
            placement: .navigationBarDrawer(displayMode: .always),
            prompt: "Search or add articles …"
        )
        .navigationTitle(place.name ?? "")
    }
}
</code>```

Always try to break the Views up by the smallest data their body needs, try to not think about breaking them up by screens or areas of a screen which is a very common mistake.

ContentLicense: CC BY-SA 4.0

Body:
I have a simple SwiftUI application with CoreData and two views. One view displays all "Place" objects. You can create new places and you can show the details for the place.
Inside the second view you can add "PlaceItem"s to a place.

The problem is that, once a new "PlaceItem" is added to the viewContext, the @NSFetchRequest seems to forget about its additional predicates, which I set in onAppear. Then every place item is shown inside the details view. Once I update the predicate manually (the refresh button), only the items from the selected place are visible again.

Any idea how this can be fixed? Here's the code for my two views:

struct PlaceView: View {
    @FetchRequest(sortDescriptors: []) private var places: FetchedResults<Place>
    @Environment(\.managedObjectContext) private var viewContext

    var body: some View {
        NavigationView {
            List(places) { place in
                NavigationLink {
                    PlaceItemsView(place: place)
                } label: {
                    Text(place.name ?? "")
                }

            }
        }
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let place = Place(context: viewContext)
                    place.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }

            }
        }
        .navigationTitle("Places")
    }
}

struct PlaceItemsView: View {
    @ObservedObject var place: Place
    @State var searchText = ""

    @FetchRequest(sortDescriptors: []) private var items: FetchedResults<PlaceItem>
    @Environment(\.managedObjectContext) private var viewContext

    func updatePredicate() {
        var predicates = [NSPredicate]()
        predicates.append(NSPredicate(format: "place == %@", place))
        if !searchText.isEmpty {
            predicates.append(NSPredicate(format: "name CONTAINS %@", searchText))
        }

        items.nsPredicate = NSCompoundPredicate(type: .and, subpredicates: predicates)
    }

    var body: some View {
        NavigationView {
            List(items) { item in
                Text(item.name ?? "");
            }
        }
        .onAppear(perform: updatePredicate)
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let item = PlaceItem(context: viewContext)
                    item.place = place
                    item.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }
            }

            ToolbarItem(placement: .navigationBarLeading) {
                Button(action: updatePredicate) {
                    Label("Refresh", systemImage: "arrow.clockwise")
                }
            }
        }
        .searchable(
            text: $searchText,
            placement: .navigationBarDrawer(displayMode: .always),
            prompt: "Search or add articles …"
        )
        .onAppear(perform: updatePredicate)
        .onChange(of: searchText, perform: { _ in
            updatePredicate()
        })
        .navigationTitle(place.name ?? "")
    }
}

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    var body: some View {
        NavigationView {
            PlaceView()
        }
    }
}

Thanks!

Body:
It's best to break Views up by the data they need, its called having a tighter invalidation and solves your problem of updating the fetch request too! e.g.

struct PlaceItemsView {
     @FetchRequest private var items: FetchedResults<PlaceItem>

    var body: some View {
        List(items) { item in
            Text(item.name ?? "")
        }
    }
}

// body called when either searchText is different or its a different place (not when the place's properties change because no need to)
struct SearchPlaceView {
    let searchText: String
    let place: Place

    var predicate: NSPredicate {
        var predicates = [NSPredicate]()
        predicates.append(NSPredicate(format: "place == %@", place))
        if !searchText.isEmpty {
            predicates.append(NSPredicate(format: "name CONTAINS %@", searchText))
        }
        return NSCompoundPredicate(type: .and, subpredicates: predicates)
    }

    var body: some View {
         PlaceItemsView(items:FetchRequest<PlaceItem>(sortDescriptors:[], predicate:predicate))
    }
}

// body called when either the place has a change or search text changes
struct PlaceItemsView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @ObservedObject var place: Place
    @State var searchText = ""

    var body: some View {
        NavigationView {
            SearchPlaceView(searchTest:searchText, place: place)
        }
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let item = PlaceItem(context: viewContext)
                    item.place = place
                    item.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }
            }

            ToolbarItem(placement: .navigationBarLeading) {
                Button(action: updatePredicate) {
                    Label("Refresh", systemImage: "arrow.clockwise")
                }
            }
        }
        .searchable(
            text: $searchText,
            placement: .navigationBarDrawer(displayMode: .always),
            prompt: "Search or add articles …"
        )
        .navigationTitle(place.name ?? "")
    }
}

Always try to break the Views up by the smallest data their body needs, try to not think about breaking them up by screens or areas of a screen which is a very common mistake.


问:
What is the name of the feature/syntax that combines curly braces, ampersand and length of character sequences?
I was reading Chapter 9 of the 2nd edition of A Tour of C++ by Bjarne Stroustrup and was puzzled by the use of {&king[0],2} where king is a string variable. I get that it returns the first 2 strings but I don't know what the name is for this to look up more details about it like:

Does the & ampersand indicate that it is a reference or does it switch it to pointer?

In what version was this feature introduced? I know the book is based on C++17 but don't know what version began supporting it.

```<code>// Strings and Regular Expressions
#pragma once
#include <string>

using namespace std;

string cat(string_view sv1, string_view sv2) {
    string res(sv1.length()+sv2.length(), '\0');
    char* p = &res[0];

    for (char c : sv1)                  // one way
        *p++ = c;
    copy(sv2.begin(), sv2.end(), p);    // another way
    return res;
}

void tryCat() {
    string king = "Harold";
    auto s1 = cat(king, "William");             // string and const char*
    auto s2 = cat(king, king);                  // string and string
    auto s3 = cat("Edward", "Stephen"sv);       // const char* and string_view
    auto s4 = cat("Canute"sv, king);
    auto s5 = cat({&king[0],2}, "Henry"sv);     // HaHenry
    auto s6 = cat({&king[0],2}, {&king[2],4});  // Harold
    cout << s6 << endl;
}

int main () {
    tryCat();
}
</code>```

答:
I think it's called copy-list-initialization, specifically form #7 at List initialization - Cppreference. Copy-list-initialization was introduced in C++11.

```<code>function( { arg1, arg2, ... } )           (7)
</code>```

&king[0] gets the underlying char* array from the std::string. &king[2] gets the address of the third character of that array.  In this case, & is the address-of operator, not a reference. [0] is a subscript. The second item in the braces after the comma is the second argument to the string_view constructor which specifies the length of the string.

Here's the description of copy-list-initialization from the cppreference link.

copy-list-initialization (both explicit and non-explicit constructors are considered, but only non-explicit constructors may be called)

initialization of a named variable with a braced-init-list after an equals sign

in a function call expression, with braced-init-list used as an argument and list-initialization initializes the function parameter

Body:
I was reading Chapter 9 of the 2nd edition of A Tour of C++ by Bjarne Stroustrup and was puzzled by the use of {&king[0],2} where king is a string variable. I get that it returns the first 2 strings but I don't know what the name is for this to look up more details about it like:

Does the & ampersand indicate that it is a reference or does it switch it to pointer?

In what version was this feature introduced? I know the book is based on C++17 but don't know what version began supporting it.

// Strings and Regular Expressions
#pragma once
#include <string>

using namespace std;

string cat(string_view sv1, string_view sv2) {
    string res(sv1.length()+sv2.length(), '\0');
    char* p = &res[0];

    for (char c : sv1)                  // one way
        *p++ = c;
    copy(sv2.begin(), sv2.end(), p);    // another way
    return res;
}

void tryCat() {
    string king = "Harold";
    auto s1 = cat(king, "William");             // string and const char*
    auto s2 = cat(king, king);                  // string and string
    auto s3 = cat("Edward", "Stephen"sv);       // const char* and string_view
    auto s4 = cat("Canute"sv, king);
    auto s5 = cat({&king[0],2}, "Henry"sv);     // HaHenry
    auto s6 = cat({&king[0],2}, {&king[2],4});  // Harold
    cout << s6 << endl;
}

int main () {
    tryCat();
}

Body:
I think it's called copy-list-initialization, specifically form #7 at List initialization - Cppreference. Copy-list-initialization was introduced in C++11.

function( { arg1, arg2, ... } )           (7)

&king[0] gets the underlying char* array from the std::string. &king[2] gets the address of the third character of that array.  In this case, & is the address-of operator, not a reference. [0] is a subscript. The second item in the braces after the comma is the second argument to the string_view constructor which specifies the length of the string.

Here's the description of copy-list-initialization from the cppreference link.

copy-list-initialization (both explicit and non-explicit constructors are considered, but only non-explicit constructors may be called)

initialization of a named variable with a braced-init-list after an equals sign

in a function call expression, with braced-init-list used as an argument and list-initialization initializes the function parameter


问:
How to handle popups in puppeteer
how to handle the popup and access the popup to do some operations on it.    </p>

```<code>const puppeteer = require('puppeteer');

async function run() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com');
    await page.click(Launchpopup);
}
</code>```

答:
Puppeteer popup event

Starting with puppeteer version 1.12, a special ‘popup’ event has been added to the page, which allows you to catch new tabs and popups. We use it by rewriting the first example:

```<code>const puppeteer = require('puppeteer');         // puppeteer

const browser = await puppeteer.launch();       // run browser
const page = await browser.newPage();           // open new tab
await page.goto('https://example.com');            // go to site.com

await page.waitForSelector('#goto');            // wait object load
const link = await page.$('#goto');             // declare object

const newPagePromise = new Promise(x => page.once('popup', x));

await link.click();                        // click, a new tab  opens
const newPage = await newPagePromise;
await newPage.close();             // close it, for example
await browser.close();                          // close browser
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to handle popups in puppeteer

Body:
how to handle the popup and access the popup to do some operations on it.

const puppeteer = require('puppeteer');

async function run() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com');
    await page.click(Launchpopup);
}

Body:
Puppeteer popup event

Starting with puppeteer version 1.12, a special ‘popup’ event has been added to the page, which allows you to catch new tabs and popups. We use it by rewriting the first example:

const puppeteer = require('puppeteer');         // puppeteer

const browser = await puppeteer.launch();       // run browser
const page = await browser.newPage();           // open new tab
await page.goto('https://example.com');            // go to site.com

await page.waitForSelector('#goto');            // wait object load
const link = await page.$('#goto');             // declare object

const newPagePromise = new Promise(x => page.once('popup', x));

await link.click();                        // click, a new tab  opens
const newPage = await newPagePromise;
await newPage.close();             // close it, for example
await browser.close();                          // close browser


问:
Apache Avro maven plugin seems to be ignoring config
I am using apache avro maven plugin with the aim of generating java from avsc.
I am running this on an m1 mac(though i didn't see anything online about that being an issue).

The issue appears to be that my config is not picked up. The code generation seems to work with the defaults. for example

Its looking for the avsc in.

```<code>Failed to execute goal org.apache.avro:avro-maven-plugin:1.10.2:schema (default-cli) on project falc-proxy: neither sourceDirectory: /Users/pdhulipala/falc-proxy/src/main/avro or testSourceDirectory: /Users/pdhulipala/falc-proxy/src/test/avro are directories
</code>```

With the plugin details defined as below.

```<code><plugin>
                <groupId>org.apache.avro</groupId>
                <artifactId>avro-maven-plugin</artifactId>
                <version>${avro.version}</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>schema</goal>
                        </goals>
                        <configuration>
                            <sourceDirectory>${project.basedir}/src/main/resources/avro/</sourceDirectory>
                            <outputDirectory>${project.basedir}/src/main/resources/java/</outputDirectory>
                            <imports>
                                <import>${project.basedir}/src/main/resources/avro/MsgHeader.avsc</import>
                                <import>${project.basedir}/src/main/resources/avro/Request.avsc</import>
                            </imports>
                            <includes>
                                <include>*.avsc</include>
                            </includes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</code>```

Wondering if there is anyway to debug this/add logging etc.

答:
I fixed this issue by moving the configuration section to the same level as the executions tag. Now I'm able to generate the schemas with the plugin. This is my configuration:</p>
```<code><plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>${project.parent.version}</version>
        </plugin>
        <plugin>
            <groupId>org.apache.avro</groupId>
            <artifactId>avro-maven-plugin</artifactId>
            <version>1.11.0</version>
            <executions>
                <execution>
                    <phase>none</phase>
                    <!-- <phase>generate-sources</phase>-->
                    <goals>
                        <goal>schema</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <createSetters>false</createSetters>
                <sourceDirectory>${project.basedir}/src/main/resources/avro/</sourceDirectory>
                <outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
                <fieldVisibility>PRIVATE</fieldVisibility>
                <stringType>String</stringType>
            </configuration>
        </plugin>
    </plugins>
</code>```

Body:
I am using apache avro maven plugin with the aim of generating java from avsc.
I am running this on an m1 mac(though i didn't see anything online about that being an issue).

The issue appears to be that my config is not picked up. The code generation seems to work with the defaults. for example

Its looking for the avsc in.

Failed to execute goal org.apache.avro:avro-maven-plugin:1.10.2:schema (default-cli) on project falc-proxy: neither sourceDirectory: /Users/pdhulipala/falc-proxy/src/main/avro or testSourceDirectory: /Users/pdhulipala/falc-proxy/src/test/avro are directories

With the plugin details defined as below.

<plugin>
                <groupId>org.apache.avro</groupId>
                <artifactId>avro-maven-plugin</artifactId>
                <version>${avro.version}</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>schema</goal>
                        </goals>
                        <configuration>
                            <sourceDirectory>${project.basedir}/src/main/resources/avro/</sourceDirectory>
                            <outputDirectory>${project.basedir}/src/main/resources/java/</outputDirectory>
                            <imports>
                                <import>${project.basedir}/src/main/resources/avro/MsgHeader.avsc</import>
                                <import>${project.basedir}/src/main/resources/avro/Request.avsc</import>
                            </imports>
                            <includes>
                                <include>*.avsc</include>
                            </includes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

Wondering if there is anyway to debug this/add logging etc.

Body:
I fixed this issue by moving the configuration section to the same level as the executions tag. Now I'm able to generate the schemas with the plugin. This is my configuration:

<plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>${project.parent.version}</version>
        </plugin>
        <plugin>
            <groupId>org.apache.avro</groupId>
            <artifactId>avro-maven-plugin</artifactId>
            <version>1.11.0</version>
            <executions>
                <execution>
                    <phase>none</phase>
                    <!-- <phase>generate-sources</phase>-->
                    <goals>
                        <goal>schema</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <createSetters>false</createSetters>
                <sourceDirectory>${project.basedir}/src/main/resources/avro/</sourceDirectory>
                <outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
                <fieldVisibility>PRIVATE</fieldVisibility>
                <stringType>String</stringType>
            </configuration>
        </plugin>
    </plugins>


问:
recv() not waiting for data
On the first iteration of a while(1) loop for communication in a socket, everything works fine - on the second iteration, even though the connection is still open and ongoing (the server's send() waits for the user to insert data, on this same socket), the recv() from the client fails to wait for data.

```<code>while(1)
                memset(buffer, 0, 300);
                int nRet = recv(sock, buffer, 299, 0);
                printf("Recv: %d\n", nRet);
                if(nRet < 0)
                    fprintf(stderr, "recv() failed.");
                else if(nRet == 0)
                    continue;
                else
                    fprintf(stdout, buffer);
</code>```

This is the beginning of the loop, which is of concern. The output, on the second iteration, is an infinite printing of "Recv: 0". This to me seems illogical - recv() is supposed to wait until data is sent, and none is being sent by the server.

答:
From the man page on my Linux system,

When a stream socket peer has performed an orderly shutdown, the return value will be 0 (the traditional "end-of-file" return).

Datagram sockets in various domains (e.g., the UNIX and Internet domains) permit zero-length datagrams.  When such a datagram is received, the return value is 0.

The value 0 may also be returned if the requested number of bytes to receive from a stream socket was 0.

So either the connection was closed, or you received an 0-byte datagram. The endless repetition suggests the former. Repeatedly trying to read from a closed connection won't magically reopen it.

What it isn't is an error.

These calls return the number of bytes received, or -1 if an error occurred.  In the event of an error, errno is set to indicate the error.

A signal interruption results in error EINTR. If the socket was made non-blocking and nothing is available, that results in error EAGAIN or EWOULDBLOCK. You aren't experiencing either of these.

Title: recv() not waiting for data

Body:
On the first iteration of a while(1) loop for communication in a socket, everything works fine - on the second iteration, even though the connection is still open and ongoing (the server's send() waits for the user to insert data, on this same socket), the recv() from the client fails to wait for data.

while(1)
                memset(buffer, 0, 300);
                int nRet = recv(sock, buffer, 299, 0);
                printf("Recv: %d\n", nRet);
                if(nRet < 0)
                    fprintf(stderr, "recv() failed.");
                else if(nRet == 0)
                    continue;
                else
                    fprintf(stdout, buffer);

This is the beginning of the loop, which is of concern. The output, on the second iteration, is an infinite printing of "Recv: 0". This to me seems illogical - recv() is supposed to wait until data is sent, and none is being sent by the server.


问:
how to add my own templates to eclipse in play! framework editor
I've noticed that the play plugin for eclipse adds a play editor,
along with several useful templates
I'd like to add my own ones, but I couldn't find the way to do it
I go to window, preferences, web, html files, templates and I can add
templates to eclipse html editor, but I couldn't find a similar option
for play editor </p>

答:
Check out the source code for the play plugin :
https://github.com/playframework/playclipse/tree/master/source/templates

You might want to fork it and add your templates to that file. That is what I would do. But I do not have enough Eclipse development knowledge to help you further than point the direction.


问:
Undefined reading in promise chain
I have a simple employee profile generator app.  Everything works just as expected up until the promise for generatePage(employeeData).  The console correctly logs employeeData but it is not getting passed to generatePage.  Does anyone have insight into why?  I have also included a picture of the beginning code for generate-page.js and the "undefined" console error message.

const {writeFile, copyFile} = require('./utils/generate-site.js');
const generatePage = require('./src/page-template.js');
const mockData = [
    {
       // lots of mock data objects here
    },
]
let employeeData = mockData;

function init() {
    return inquirer.prompt(questions.startQuestions);
}
function getEmployeeData(answers) {
    if (answers.role === 'Engineer') {
        let engineer = new Engineer (
            answers.name,
            answers.id,
            answers.email,
            answers.role
        )
        return getEngineerData(engineer);
    } else if (answers.role === 'Intern') {
        let intern = new Intern (
            answers.name,
            answers.id,
            answers.email,
            answers.role
        )
        return getInternData(intern)
    } else if (answers.role === 'Manager') {
        let manager = new Manager (
            answers.name,
            answers.id,
            answers.email,
            answers.role
        )
        return getManagerData(manager)
    }
}

function getEngineerData(engineer) {
        return new Promise((resolve) => {
            resolve (
            inquirer.prompt(questions.engineerQuestions)
            .then ((response) => {
                    engineer = {...engineer, ...response};
                    // console.log(engineer)
                    employeeData.push(engineer)
                }
            )
        )
    })
}
function getInternData(intern) {
        return new Promise((resolve) => {
        // same as getEngineerData function
    })
}
function getManagerData(manager) {
       return new Promise((resolve) => {
        // same as getEngineerData function
    })
}
function confirm() {
    return inquirer.prompt(questions.confirmQuestion)
}

function buildTeam() {
    init()
    .then(answers => getEmployeeData(answers))
    .then(confirm)
    .then(response => response.confirmAdd ? buildTeam() : console.log(employeeData))
    .then(employeeData => generatePage(employeeData))
    .then(pageHTML => {
        return writeFile(pageHTML)
    })
    .then (writeFileResponse => {
        console.log(writeFileResponse);
        return copyFile()
    })
    .then(copyFileResponse => {
        console.log(copyFileResponse);
    })
    .catch (err => {
        console.log(err);
    });
}
buildTeam();
```

答:
console.log returns "undefined" so the solution was to return the employeeData array in the promise chain to pass on.

 .then(response => {
        if (response.confirmAdd) {
            buildTeam()
            return employeeData
        } else {
            return employeeData
        }
    })
```

Title: Undefined reading in promise chain


问:
I want to delete all the numbers that have 1, 4 or 5 in them, but it gives a index error
```<code>#list 000 to 999
numbers = []
for i in range(0, 1000):
    i = str(i).zfill(3)
    numbers.append(i)

num = "145"
for j in range(1000):
    for k in range(3):
        if numbers[j][k] in num:
            numbers.remove(numbers[j])
</code>```

I want to delete all the numbers that have 1, 4 or 5 in them

答:
You're deleting elements in the list as you're iterating over it. So, for example, by the time you reach index 999, there are no longer 1000 elements in the list. (In truth, this out-of-bounds issue happens at a much earlier index.)

Rather than try to modify the list as you're iterating over it, you should create a new list instead. The easiest way of doing that is to use filter() to remove numbers on a specified condition; in this case, we remove numbers that contain a 1, 4, or 5:

def contains_forbidden_digit(num):
    for digit in str(num):
        if digit in {'1', '4', '5'}:
            return True
    return False

print(list(filter(lambda x: not contains_forbidden_digit(x), range(1000))))
```

Body:
#list 000 to 999
numbers = []
for i in range(0, 1000):
    i = str(i).zfill(3)
    numbers.append(i)

num = "145"
for j in range(1000):
    for k in range(3):
        if numbers[j][k] in num:
            numbers.remove(numbers[j])

I want to delete all the numbers that have 1, 4 or 5 in them


问:
Style Chakra UI FormControl and label at application theme level
Have been using Chakra for a while but I can not get my head around styling all my components, in this case, FormControl at a global level with the theme file.

For example if i want to add margin bottom to my FormControl and FormLabel elements I would add the components object to the theme file like so:

```<code>  components: {
    Form: {
      parts: ['control', 'label', 'errorMessage'],
      baseStyle: {
        control: {
          marginBottom: '2rem',
        },
        label: {
          marginBottom: '3rem',
        },
      },
    },
  },
</code>```

But this has no effect on the base style of the rendered FormControl or FormLabel.

Could someone please help me with what I am doing wrong here?

答:
This worked for me:</p>
```<code>import type { ComponentStyleConfig } from '@chakra-ui/theme';
import { extendTheme } from '@chakra-ui/react'

const Form: ComponentStyleConfig = {
  // The styles all button have in common
  parts: ['container'],
  baseStyle: {
    /// The container styles the FormControl
    container: {
      marginY: '20px'
    }
  },
}

const theme = extendTheme({
  components: {
    Form,
  },
})
</code>```

Body:
Have been using Chakra for a while but I can not get my head around styling all my components, in this case, FormControl at a global level with the theme file.

For example if i want to add margin bottom to my FormControl and FormLabel elements I would add the components object to the theme file like so:

  components: {
    Form: {
      parts: ['control', 'label', 'errorMessage'],
      baseStyle: {
        control: {
          marginBottom: '2rem',
        },
        label: {
          marginBottom: '3rem',
        },
      },
    },
  },

But this has no effect on the base style of the rendered FormControl or FormLabel.

Could someone please help me with what I am doing wrong here?

Body:
This worked for me:

import type { ComponentStyleConfig } from '@chakra-ui/theme';
import { extendTheme } from '@chakra-ui/react'

const Form: ComponentStyleConfig = {
  // The styles all button have in common
  parts: ['container'],
  baseStyle: {
    /// The container styles the FormControl
    container: {
      marginY: '20px'
    }
  },
}

const theme = extendTheme({
  components: {
    Form,
  },
})


问:
Invalid behavior for arguments in Bash version 4.4 vs version 5.1?
I am confused with this behavior, I have the following script:

backup.sh

```<code>#!/bin/bash -x

set -e

if [[ $# -eq 0 ]] ; then
    echo 'No arguments passed'
    exit 1
fi

# Get the arguments
for ARGUMENT in "$@"; do
  KEY=$(echo $ARGUMENT | cut -f1 -d=)
  VALUE=$(echo $ARGUMENT | cut -f2 -d=)

  case "$KEY" in
  backup_dir) BACKUP_DIR=${VALUE} ;;
  postgres_dbs) POSTGRES_DBS=${VALUE} ;;
  backup_name) BACKUP_NAME=${VALUE} ;;
  postgres_port) POSTGRES_PORT=${VALUE} ;;
  postgres_host) POSTGRES_HOST=${VALUE} ;;
  *) ;;
  esac
done
</code>```

And I am executing it using:

1.

```<code>/bin/bash -c /usr/bin/backup.sh postgres_dbs=grafana,keycloak backup_name=postgres-component-test-20220210.165630 backup_dir=/backups/postgres postgres_port=5432 postgres_host=postgres.default.svc.cluster.local
</code>```

```<code>/usr/bin/backup.sh postgres_dbs=grafana,keycloak backup_name=postgres-component-test-20220210.165630 backup_dir=/backups/postgres postgres_port=5432 postgres_host=postgres.default.svc.cluster.local
</code>```

But the output is:

```<code>+ set -e
+ [[ 0 -eq 0 ]]
+ echo 'No arguments passed'
No arguments passed
+ exit 1
</code>```

Environment:

```<code># cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
</code>```

Bash version where I can reproduce this issue:

```<code>GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
</code>```

However, this is not happening in the Bash version:

```<code>GNU bash, version 5.1.8(1)-release (x86_64-apple-darwin20.3.0)
</code>```

答:
It's not a bug, just a feature!

When you use the bash -c 'code …' style, actually the first CLI argument is passed to the inline code as $0, not $1.

Furthermore, if the 'code …' itself invokes an external script such as ./script.sh, then you should not forget to pass the arguments using the "$@" construct.

So you could just write (as pointed out in the comments):

bash -c './script.sh "$@"' bash "first argument"
```
<p>Or most succinctly, just like you mention you had already tried:</p>
<pre class="lang-sh prettyprint-override"><code>bash script.sh "first argument"
</code>```

Additional notes

As your example was not really "minimal" (it had a very long command-line), here is a complete minimal example that you might want to test for debugging purpose:

script.sh

#!/usr/bin/env bash
echo "\$#: $#"
for arg; do printf -- '- %s\n' "$arg"; done
```
<p>Then you should get a session similar to:</p>
<pre class="lang-sh prettyprint-override"><code>$ chmod a+x script.sh

$ bash -c ./script.sh "arg 1" "arg 2"
$#: 0

$ bash -c './script.sh "$@"' "arg 1" "arg 2"
$#: 1
- arg 2

$ bash -c './script.sh "$@"' bash "arg 1" "arg 2"
$#: 2
- arg 1
- arg 2

$ bash script.sh "arg 1" "arg 2"
$#: 2
- arg 1
- arg 2

$ ./script.sh "arg 1" "arg 2"
$#: 2
- arg 1
- arg 2
</code>```

Body:
I am confused with this behavior, I have the following script:

backup.sh

#!/bin/bash -x

set -e

if [[ $# -eq 0 ]] ; then
    echo 'No arguments passed'
    exit 1
fi

# Get the arguments
for ARGUMENT in "$@"; do
  KEY=$(echo $ARGUMENT | cut -f1 -d=)
  VALUE=$(echo $ARGUMENT | cut -f2 -d=)

  case "$KEY" in
  backup_dir) BACKUP_DIR=${VALUE} ;;
  postgres_dbs) POSTGRES_DBS=${VALUE} ;;
  backup_name) BACKUP_NAME=${VALUE} ;;
  postgres_port) POSTGRES_PORT=${VALUE} ;;
  postgres_host) POSTGRES_HOST=${VALUE} ;;
  *) ;;
  esac
done

And I am executing it using:

1.

/bin/bash -c /usr/bin/backup.sh postgres_dbs=grafana,keycloak backup_name=postgres-component-test-20220210.165630 backup_dir=/backups/postgres postgres_port=5432 postgres_host=postgres.default.svc.cluster.local

/usr/bin/backup.sh postgres_dbs=grafana,keycloak backup_name=postgres-component-test-20220210.165630 backup_dir=/backups/postgres postgres_port=5432 postgres_host=postgres.default.svc.cluster.local

But the output is:

+ set -e
+ [[ 0 -eq 0 ]]
+ echo 'No arguments passed'
No arguments passed
+ exit 1

Environment:

# cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic

Bash version where I can reproduce this issue:

GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)

However, this is not happening in the Bash version:

GNU bash, version 5.1.8(1)-release (x86_64-apple-darwin20.3.0)

Body:
It's not a bug, just a feature!

When you use the bash -c 'code …' style, actually the first CLI argument is passed to the inline code as $0, not $1.

Furthermore, if the 'code …' itself invokes an external script such as ./script.sh, then you should not forget to pass the arguments using the "$@" construct.

So you could just write (as pointed out in the comments):

bash -c './script.sh "$@"' bash "first argument"

Or most succinctly, just like you mention you had already tried:

bash script.sh "first argument"

Additional notes

As your example was not really "minimal" (it had a very long command-line), here is a complete minimal example that you might want to test for debugging purpose:

script.sh

#!/usr/bin/env bash
echo "\$#: $#"
for arg; do printf -- '- %s\n' "$arg"; done

Then you should get a session similar to:

$ chmod a+x script.sh

$ bash -c ./script.sh "arg 1" "arg 2"
$#: 0

$ bash -c './script.sh "$@"' "arg 1" "arg 2"
$#: 1
- arg 2

$ bash -c './script.sh "$@"' bash "arg 1" "arg 2"
$#: 2
- arg 1
- arg 2

$ bash script.sh "arg 1" "arg 2"
$#: 2
- arg 1
- arg 2

$ ./script.sh "arg 1" "arg 2"
$#: 2
- arg 1
- arg 2


问:
Why is there no Disjoint Set (Union Find Algorithm) implemented in most mainstream programming languages' standard library?
I have found articles on how to implement a Disjoint Set (Union Find Algorithm implementation) for C++, Java, Kotlin, Python, etc.. The implementation of it is not especially difficult, although there is some room for error. It surprised me that no languages include a form of this in their standard library.

Is there a reason for this? Given how many various data structures exist in most standard libraries already, I am surprised that not one (that I have found) includes this. Is it just too obscure to include?

答:
This is a reasonable question and perhaps there isn't really a very satisfying answer beyond "because most people don't need it". I have used disjoint set data structures perhaps 10-20 times, but pretty much only ever in the context of competitive programming; most languages' standard libraries are not designed with competitive programmers in mind. Disjoint set data structures are also needed for writing some standard algorithms like Kruskal's algorithm, but if you're implementing Kruskal's algorithm yourself then you can implement a disjoint set data structure yourself too.

Now, you might intuitively think that even if most programmers will never use it, it doesn't hurt to have it in the standard library. And it's true that it would cost very little time for the language developers to write it in the first place, but they'd also have to test it extensively, write documentation, respond to bug reports or feature requests about it, and so on. The language designers would also have to take a position on which algorithm should be the one provided in the standard library; there are various options with different performance and concurrency characteristics, so some research will be needed to choose what to implement.

On the other hand, if some niche data structure isn't in the standard library but is important enough to some programmers, then it is likely to appear in third-party libraries anyway. From the language designers' perspective, there is almost no downside in leaving it to third-party library developers.


问:
Using pipes in an alias
I have this in my .bashrc:

```<code>alias jpsdir="jps | awk '{print $1}' | xargs pwdx"
</code>```

but when I use jpsdir I get this output:

```<code>pwdx: invalid process id: JvmName
</code>```

but running

```<code>jps | awk '{print $1}' | xargs pwdx
</code>```

gives the correct results:

```<code>1234: /some/dir/
</code>```

What is wrong with my alias? Should i make it a function ?

答:
Been trying to run : date | awk '{print $5}'  as a command to extract the time from the date command.
When I run "time"  as a command, I get this gibberish:

```<code>time

real    0m0.000s
user    0m0.000s
sys     0m0.000s
</code>```

So the time is the 5th string item in the date command and I was so pleased when I plucked it out using an awk command, my first attempt at using awk.
As Tom French's answer suggests if you get rid of the $x above, the command prints the entire date string.
It didn't take me very many attempts using the alias command before I came upon a pretty simple example that wouldn't run.

Title: Using pipes in an alias

Body:
I have this in my .bashrc:

alias jpsdir="jps | awk '{print $1}' | xargs pwdx"

but when I use jpsdir I get this output:

pwdx: invalid process id: JvmName

but running

jps | awk '{print $1}' | xargs pwdx

gives the correct results:

1234: /some/dir/

What is wrong with my alias? Should i make it a function ?

Body:
Been trying to run : date | awk '{print $5}'  as a command to extract the time from the date command.
When I run "time"  as a command, I get this gibberish:

time

real    0m0.000s
user    0m0.000s
sys     0m0.000s

So the time is the 5th string item in the date command and I was so pleased when I plucked it out using an awk command, my first attempt at using awk.
As Tom French's answer suggests if you get rid of the $x above, the command prints the entire date string.
It didn't take me very many attempts using the alias command before I came upon a pretty simple example that wouldn't run.


问:
BeagleBone Black: how to activate UART 4 or 5 to enable RS-485 communication
I want to enable RS-485 AND CANbus communications for my BBB using the comms cape 2.

I used to setup my Beaglebone black thru the /boot/uEnv.txt by overwriting with EEProm as follows:

```<code>###Overide capes with eeprom
uboot_overlay_addr0=/lib/firmware/BB-UART1-00A0.dtbo
uboot_overlay_addr1=/lib/firmware/BB-UART2-00A0.dtbo
uboot_overlay_addr2=/lib/firmware/BB-UART4-00A0.dtbo
uboot_overlay_addr3=/lib/firmware/BB-UART5-00A0.dtbo
</code>```

And then I use ttyS4 for RS-485 comms.

Though it used to work on some BBBs, it's no longer the case on many others and many issues raise:

If I do that, the CANbus stops to work - probably messing the UART for the CANbus;

If I do not use CANbus, this settings does not seem to work anymore for the RS-485 itself - I guess something changed that depends on the linux version installed.

Long story short, I'd like to find a modern way to 1) setup RS-485 comms and 2) setup CANbus comm so that they work simultaneously.

And, possibly, how can I test RS-485 comms work, independent of my own software?

What I found on the Web:

The official cape comms doc here https://github.com/beagleboard/capes/tree/master/beaglebone/Comms tells how to setup things as follows:

```<code>For the RS485, you just need
config-pin p9.11 uart
config-pin p9.13 uart
...and then use /dev/ttyS4

For the CAN, you just need
config-pin p9.24 can
config-pin p9.26 can
</code>```

But in my case, setting config-pin p9.11 uart leads to the following error:

```<code>ERROR: open() for /sys/devices/platform/ocp/ocp:P9_11_pinmux/state failed, No such file or directory
</code>```

This SO beaglebone black: no slots while enable uart tells how to setup UART5.
They say to disable video, which I did.
And to:

```<code>config-pin P8_37 uart
config-pin P8_38 uart
</code>```

which works on my side, I mean no error was generated.
And then I used ttS5 in my own software, but I cannot see anything on the RS-485.

At this time I am a bit puzzled: for example, should I overwrite EEPROM or not? Should I stick with the disabling of video, sound, etc. Why config-pin for UART4 doesn't work? Does UART 5 correspond to ttyS5? And how to make sure the ttySX I use really work with the RS-485 comm?

Thanks in advance.

APPENDIX: my current /boot/uEnv.txt

```<code>#Docs: http://elinux.org/Beagleboard:U-boot_partitioning_layout_2.0

uname_r=4.19.94-ti-r42
#uuid=
#dtb=

###U-Boot Overlays###
###Documentation: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian#U$
###Master Enable
enable_uboot_overlays=1
###
###Overide capes with eeprom
#uboot_overlay_addr0=/lib/firmware/BB-UART1-00A0.dtbo
#uboot_overlay_addr1=/lib/firmware/BB-UART2-00A0.dtbo
uboot_overlay_addr2=/lib/firmware/BB-UART4-00A0.dtbo
uboot_overlay_addr3=/lib/firmware/BB-UART5-00A0.dtbo
###
###Additional custom capes
#uboot_overlay_addr4=/lib/firmware/<file4>.dtbo
#uboot_overlay_addr5=/lib/firmware/<file5>.dtbo
#uboot_overlay_addr6=/lib/firmware/<file6>.dtbo
#uboot_overlay_addr7=/lib/firmware/<file7>.dtbo
###
###Custom Cape
#dtb_overlay=/lib/firmware/<file8>.dtbo
###
###Disable auto loading of virtual capes (emmc/video/wireless/adc)
#disable_uboot_overlay_emmc=1
disable_uboot_overlay_video=1
disable_uboot_overlay_audio=1
disable_uboot_overlay_wireless=1
#disable_uboot_overlay_adc=1
###
###PRUSS OPTIONS
###pru_rproc (4.14.x-ti kernel)
#uboot_overlay_pru=/lib/firmware/AM335X-PRU-RPROC-4-14-TI-00A0.dtbo
###pru_rproc (4.19.x-ti kernel)
uboot_overlay_pru=/lib/firmware/AM335X-PRU-RPROC-4-19-TI-00A0.dtbo
###pru_uio (4.14.x-ti, 4.19.x-ti & mainline/bone kernel)
#uboot_overlay_pru=/lib/firmware/AM335X-PRU-UIO-00A0.dtbo
###
###Cape Universal Enable
enable_uboot_cape_universal=1
###
###Debug: disable uboot autoload of Cape
#disable_uboot_overlay_addr0=1
#disable_uboot_overlay_addr1=1
#disable_uboot_overlay_addr2=1
#disable_uboot_overlay_addr3=1
###
###U-Boot fdt tweaks... (60000 = 384KB)
#uboot_fdt_buffer=0x60000
###U-Boot Overlays###

cmdline=coherent_pool=1M net.ifnames=0 lpj=1990656 rng_core.default_qual$

#In the event of edid real failures, uncomment this next line:
#cmdline=coherent_pool=1M net.ifnames=0 lpj=1990656 rng_core.default_qua$

##enable Generic eMMC Flasher:
##make sure, these tools are installed: dosfstools rsync
#cmdline=init=/opt/scripts/tools/eMMC/init-eMMC-flasher-v3.sh
</code>```

答:
Here is my /boot/uEnv.txt file:

```<code>
#Docs: http://elinux.org/Beagleboard:U-boot_partitioning_layout_2.0

uname_r=4.19.94-ti-r71
#uuid=
#dtb=

###U-Boot Overlays###
###Documentation: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian#U-Boot_Overlays
###Master Enable
enable_uboot_overlays=1
###
###Overide capes with eeprom
uboot_overlay_addr0=BONE-SPI1_0.dtbo
uboot_overlay_addr1=BONE-SPI0_0.dtbo
#uboot_overlay_addr2=<file2>.dtbo
#uboot_overlay_addr3=<file3>.dtbo

</code>```

I did not apply the /lib/firmware sections in my uboot-overlays section(s).

This is ls -l /dev/spidev*

```<code>
crw------- 1 root root 153, 0 Feb 10 00:39 /dev/spidev1.0
crw------- 1 root root 153, 1 Feb 10 00:39 /dev/spidev2.0

</code>```

I think not being root might be an issue for me.

Anyway...the symlinks are used in source these days, I think, and there is also an up-to-date repo. from the BeagleBoard.org fellows/gals that help one to produce their .dts files into .dtb/o files. It is useful to me b/c I can then alter things or see what the people at beagleboard.org are doing w/ DT.

Body:
I want to enable RS-485 AND CANbus communications for my BBB using the comms cape 2.

I used to setup my Beaglebone black thru the /boot/uEnv.txt by overwriting with EEProm as follows:

###Overide capes with eeprom
uboot_overlay_addr0=/lib/firmware/BB-UART1-00A0.dtbo
uboot_overlay_addr1=/lib/firmware/BB-UART2-00A0.dtbo
uboot_overlay_addr2=/lib/firmware/BB-UART4-00A0.dtbo
uboot_overlay_addr3=/lib/firmware/BB-UART5-00A0.dtbo

And then I use ttyS4 for RS-485 comms.

Though it used to work on some BBBs, it's no longer the case on many others and many issues raise:

If I do that, the CANbus stops to work - probably messing the UART for the CANbus;

If I do not use CANbus, this settings does not seem to work anymore for the RS-485 itself - I guess something changed that depends on the linux version installed.

Long story short, I'd like to find a modern way to 1) setup RS-485 comms and 2) setup CANbus comm so that they work simultaneously.

And, possibly, how can I test RS-485 comms work, independent of my own software?

What I found on the Web:

The official cape comms doc here https://github.com/beagleboard/capes/tree/master/beaglebone/Comms tells how to setup things as follows:

For the RS485, you just need
config-pin p9.11 uart
config-pin p9.13 uart
...and then use /dev/ttyS4

For the CAN, you just need
config-pin p9.24 can
config-pin p9.26 can

But in my case, setting config-pin p9.11 uart leads to the following error:

ERROR: open() for /sys/devices/platform/ocp/ocp:P9_11_pinmux/state failed, No such file or directory

This SO beaglebone black: no slots while enable uart tells how to setup UART5.
They say to disable video, which I did.
And to:

config-pin P8_37 uart
config-pin P8_38 uart

which works on my side, I mean no error was generated.
And then I used ttS5 in my own software, but I cannot see anything on the RS-485.

At this time I am a bit puzzled: for example, should I overwrite EEPROM or not? Should I stick with the disabling of video, sound, etc. Why config-pin for UART4 doesn't work? Does UART 5 correspond to ttyS5? And how to make sure the ttySX I use really work with the RS-485 comm?

Thanks in advance.

APPENDIX: my current /boot/uEnv.txt

#Docs: http://elinux.org/Beagleboard:U-boot_partitioning_layout_2.0

uname_r=4.19.94-ti-r42
#uuid=
#dtb=

###U-Boot Overlays###
###Documentation: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian#U$
###Master Enable
enable_uboot_overlays=1
###
###Overide capes with eeprom
#uboot_overlay_addr0=/lib/firmware/BB-UART1-00A0.dtbo
#uboot_overlay_addr1=/lib/firmware/BB-UART2-00A0.dtbo
uboot_overlay_addr2=/lib/firmware/BB-UART4-00A0.dtbo
uboot_overlay_addr3=/lib/firmware/BB-UART5-00A0.dtbo
###
###Additional custom capes
#uboot_overlay_addr4=/lib/firmware/<file4>.dtbo
#uboot_overlay_addr5=/lib/firmware/<file5>.dtbo
#uboot_overlay_addr6=/lib/firmware/<file6>.dtbo
#uboot_overlay_addr7=/lib/firmware/<file7>.dtbo
###
###Custom Cape
#dtb_overlay=/lib/firmware/<file8>.dtbo
###
###Disable auto loading of virtual capes (emmc/video/wireless/adc)
#disable_uboot_overlay_emmc=1
disable_uboot_overlay_video=1
disable_uboot_overlay_audio=1
disable_uboot_overlay_wireless=1
#disable_uboot_overlay_adc=1
###
###PRUSS OPTIONS
###pru_rproc (4.14.x-ti kernel)
#uboot_overlay_pru=/lib/firmware/AM335X-PRU-RPROC-4-14-TI-00A0.dtbo
###pru_rproc (4.19.x-ti kernel)
uboot_overlay_pru=/lib/firmware/AM335X-PRU-RPROC-4-19-TI-00A0.dtbo
###pru_uio (4.14.x-ti, 4.19.x-ti & mainline/bone kernel)
#uboot_overlay_pru=/lib/firmware/AM335X-PRU-UIO-00A0.dtbo
###
###Cape Universal Enable
enable_uboot_cape_universal=1
###
###Debug: disable uboot autoload of Cape
#disable_uboot_overlay_addr0=1
#disable_uboot_overlay_addr1=1
#disable_uboot_overlay_addr2=1
#disable_uboot_overlay_addr3=1
###
###U-Boot fdt tweaks... (60000 = 384KB)
#uboot_fdt_buffer=0x60000
###U-Boot Overlays###

cmdline=coherent_pool=1M net.ifnames=0 lpj=1990656 rng_core.default_qual$

#In the event of edid real failures, uncomment this next line:
#cmdline=coherent_pool=1M net.ifnames=0 lpj=1990656 rng_core.default_qua$

##enable Generic eMMC Flasher:
##make sure, these tools are installed: dosfstools rsync
#cmdline=init=/opt/scripts/tools/eMMC/init-eMMC-flasher-v3.sh

Body:
Here is my /boot/uEnv.txt file:

#Docs: http://elinux.org/Beagleboard:U-boot_partitioning_layout_2.0

uname_r=4.19.94-ti-r71
#uuid=
#dtb=

###U-Boot Overlays###
###Documentation: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian#U-Boot_Overlays
###Master Enable
enable_uboot_overlays=1
###
###Overide capes with eeprom
uboot_overlay_addr0=BONE-SPI1_0.dtbo
uboot_overlay_addr1=BONE-SPI0_0.dtbo
#uboot_overlay_addr2=<file2>.dtbo
#uboot_overlay_addr3=<file3>.dtbo

I did not apply the /lib/firmware sections in my uboot-overlays section(s).

This is ls -l /dev/spidev*

crw------- 1 root root 153, 0 Feb 10 00:39 /dev/spidev1.0
crw------- 1 root root 153, 1 Feb 10 00:39 /dev/spidev2.0

I think not being root might be an issue for me.

Anyway...the symlinks are used in source these days, I think, and there is also an up-to-date repo. from the BeagleBoard.org fellows/gals that help one to produce their .dts files into .dtb/o files. It is useful to me b/c I can then alter things or see what the people at beagleboard.org are doing w/ DT.


问:
Putting already existing entities into new entities (spring boot data jpa)
I have 2 entities.
AppUser:
`

```<code>@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
@ManyToOne(cascade = CascadeType.ALL)
private Role role;
public AppUser(String username, String email, Role roles) {
    this.username = username;
    this.email = email;
    this.role = roles;
   }
}
</code>```

and Role:

```<code>@Entity
@Data
@NoArgsConstructor
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private rolesEnum roleName;
public Role(rolesEnum roleName) {
    this.roleName = roleName;
    }
}
</code>```

I save AppUsers to my database when the application starts:

```<code>@EventListener(ApplicationReadyEvent.class)
public void start(){
    List<AppUser> users = new ArrayList<>();
    users.add(new AppUser("adam","adam@gmail.com",new Role(rolesEnum.ADMIN)));
    users.add(new AppUser("maciek","maciek@gmail.com",new Role(rolesEnum.ADMIN)));
    users.add(new AppUser("kuba","kuba@gmail.com",new Role(rolesEnum.USER)));
    appUserRepo.saveAll(users);
}
</code>```

The problem is that in a database rows from roles table are duplicated so instead of having one admin row I have 2 because I just saved two users with admin role. I don't want to add new roles to a table every time I save new user I just want to add an already existing role to a new user.
Image of user table

Image of role table

答:
Create role if not present and then save the user record.

otherwise, it will create new records.

Body:
I have 2 entities.
AppUser:
`

@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
@ManyToOne(cascade = CascadeType.ALL)
private Role role;
public AppUser(String username, String email, Role roles) {
    this.username = username;
    this.email = email;
    this.role = roles;
   }
}

and Role:

@Entity
@Data
@NoArgsConstructor
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private rolesEnum roleName;
public Role(rolesEnum roleName) {
    this.roleName = roleName;
    }
}

I save AppUsers to my database when the application starts:

@EventListener(ApplicationReadyEvent.class)
public void start(){
    List<AppUser> users = new ArrayList<>();
    users.add(new AppUser("adam","adam@gmail.com",new Role(rolesEnum.ADMIN)));
    users.add(new AppUser("maciek","maciek@gmail.com",new Role(rolesEnum.ADMIN)));
    users.add(new AppUser("kuba","kuba@gmail.com",new Role(rolesEnum.USER)));
    appUserRepo.saveAll(users);
}

The problem is that in a database rows from roles table are duplicated so instead of having one admin row I have 2 because I just saved two users with admin role. I don't want to add new roles to a table every time I save new user I just want to add an already existing role to a new user.
Image of user table

Image of role table


问:
Flask-Restx fails to render Swagger doc when inputs.email is used
Whenever I try to define an argument in reqparse object, using the flask_restx.inputs.email type and decorate the method via api.expect; Flask-Restx fails to create the Swagger doc.

Example code:

```<code>@api.route("/route")
class View(Resource):

    parser = reqparse.RequestParser()
    parser.add_argument("email", type=inputs.email)

    @api.expect(parser)
    def post(self):
        ...
</code>```

The error on the Swagger docs page

Python's Error:

```<code>Unable to render schema
Traceback (most recent call last):
  File "\venv\lib\site-packages\flask_restx\api.py", line 571, in __schema__
    self._schema = Swagger(self).as_dict()
  File "\venv\lib\site-packages\flask_restx\swagger.py", line 239, in as_dict
    serialized = self.serialize_resource(
  File "\venv\lib\site-packages\flask_restx\swagger.py", line 438, in serialize_resource
    doc = self.extract_resource_doc(resource, url, route_doc=route_doc)
  File "\venv\lib\site-packages\flask_restx\swagger.py", line 343, in extract_resource_doc
    method_params = self.expected_params(method_doc)
  File "\venv\lib\site-packages\flask_restx\swagger.py", line 382, in expected_params
    (p["name"], p) for p in expect.__schema__ if p["in"] != "body"
  File "\venv\lib\site-packages\flask_restx\reqparse.py", line 435, in __schema__
    param = arg.__schema__
  File "\venv\lib\site-packages\flask_restx\reqparse.py", line 291, in __schema__
    _handle_arg_type(self, param)
  File "\venv\lib\site-packages\flask_restx\reqparse.py", line 451, in _handle_arg_type
    param.update(arg.type.__schema__)
TypeError: 'property' object is not iterable
</code>```

I can use Python's builtin types, other types on Restx's inputs or my own custom type without any issues.

Is there anything I am doing wrong or not aware of? Thanks.

答:
I've found the solution:

Changing inputs.email to inputs.email() resolved the issue.

I assume it is because email is a class based validator rather than a function.

Body:
Whenever I try to define an argument in reqparse object, using the flask_restx.inputs.email type and decorate the method via api.expect; Flask-Restx fails to create the Swagger doc.

Example code:

@api.route("/route")
class View(Resource):

    parser = reqparse.RequestParser()
    parser.add_argument("email", type=inputs.email)

    @api.expect(parser)
    def post(self):
        ...

The error on the Swagger docs page

Python's Error:

Unable to render schema
Traceback (most recent call last):
  File "\venv\lib\site-packages\flask_restx\api.py", line 571, in __schema__
    self._schema = Swagger(self).as_dict()
  File "\venv\lib\site-packages\flask_restx\swagger.py", line 239, in as_dict
    serialized = self.serialize_resource(
  File "\venv\lib\site-packages\flask_restx\swagger.py", line 438, in serialize_resource
    doc = self.extract_resource_doc(resource, url, route_doc=route_doc)
  File "\venv\lib\site-packages\flask_restx\swagger.py", line 343, in extract_resource_doc
    method_params = self.expected_params(method_doc)
  File "\venv\lib\site-packages\flask_restx\swagger.py", line 382, in expected_params
    (p["name"], p) for p in expect.__schema__ if p["in"] != "body"
  File "\venv\lib\site-packages\flask_restx\reqparse.py", line 435, in __schema__
    param = arg.__schema__
  File "\venv\lib\site-packages\flask_restx\reqparse.py", line 291, in __schema__
    _handle_arg_type(self, param)
  File "\venv\lib\site-packages\flask_restx\reqparse.py", line 451, in _handle_arg_type
    param.update(arg.type.__schema__)
TypeError: 'property' object is not iterable

I can use Python's builtin types, other types on Restx's inputs or my own custom type without any issues.

Is there anything I am doing wrong or not aware of? Thanks.


问:
File upload to google drive with service account authentication successful but not missing
I am trying to upload a zip file to google drive with a php script as a cron job on Fedora 33 x86-64. I have been tried several different things but I am not having any luck with this at this point. I have created a service account and downloaded the credentials, created the oauth concent screen, installed the Google Drive API, oauth client id, etc... Anyway when I run the script from the shell I get a very strange. Any help would be appreciated.

```<code><?php
    require_once 'vendor/autoload.php';
    $googleClient = new Google_Client();
    $googleClient->setAuthConfig('***************************.json');
    $googleClient->addScope(Google_Service_Drive::DRIVE);
    $googleClient->setApplicationName('******************');
    $googleClient->setAccessType('offline');
    $googleClient->getAccessToken();
    $drive = new Google_Service_Drive($googleClient);
    $file = new Google_Service_Drive_DriveFile($googleClient);
    $file->setName('Mysql-Backup.zip');
    $file->setMimeType('application/zip');
    try {
      $return = $drive->files->create($file, array('data' => file_get_contents("Mysql-Backup.zip"), 'uploadType' => 'multipart', 'supportsAllDrives' => 'true'));
      echo "Sucessful upload of " . $file['name'] . ".";
    }
    catch (Exception $exc) {
      echo $exc->getMessage() . "\n";
    }
?>
</code>```

Forgive me if I am not doing this correctly both the code and posting on stackoverflow.com. Ok I have tried as you suggested listing the files and you are indeed correct that the files were uploaded to my service account instead of my personal drive. I have also tried your suggestion of sharing a folder from my personal account to the service account using the web interface. However when I try again it still isn't working. This gives me an error "PHP Fatal error:  Uncaught Error: Call to undefined method Google_Service_Drive_Resource_Permissions::insert() in /scripts/google-drive/google-drive.php:25". I have refereed to https://developers.google.com/resources/api-libraries/documentation/drive/v3/php/latest/class-Google_Service_Drive_Permission.html and https://developers.google.com/drive/api/v2/reference/permissions/insert#php but still I don't understand what I am missing. I don't know if this is frowned upon but I am willing to paypal someone if they have a currant working php class with instructions. The documentation for this is all over the place the old stuff doesn't work and the new stuff doesn't work. I am banging my head in at this point.

```<code><?php
require_once 'vendor/autoload.php';
$googleClient = new Google_Client();
$googleClient->setAuthConfig('****');
$googleClient->addScope("https://www.googleapis.com/auth/drive.file");
$googleClient->setApplicationName('MySQL-Backup');
$googleClient->setAccessType('offline');
$googleClient->getAccessToken();
$drive = new Google_Service_Drive($googleClient);
$file = new Google_Service_Drive_DriveFile($googleClient);
$file->setName('Mysql-Backup.zip');
$file->setMimeType('application/zip');
$file->setParents('****');
try
    {
    $return = $drive->files->create($file, array('data' => file_get_contents("Mysql-Backup.zip"), 'uploadType' => 'multipart', 'supportsAllDrives' => 'true'));
    echo "Sucessful upload of " . $file['name'] . " File ID:" . $return->id . "\n";
    $newPermission = new Google_Service_Drive_Permission();
    //$newPermission->setValue('***');
    $newPermission->setType('user');
    $newPermission->setRole('editor');
    echo $return->id . "\n";
    try
        {
        $drive->permissions->insert($return->id, $newPermission);
        }
    catch (Exception $exc)
        {
        echo 'Caught exception: ',  $exc->getMessage(), "\n";
        }
    }
catch (Exception $exc)
    {
    echo 'Caught exception: ',  $exc->getMessage(), "\n";
    }
$optParams = array('fields' => '*');
$myfiles = $drive->files->ListFiles($optParams);
foreach( $myfiles as $k => $file )
    {
    echo "{$file['name']} - {$file['id']} ---- " . $file['mimeType'] . "\n";
    try
        {
        // subfiles
        $sub_files = $drive->files->listFiles(array('q' => "'{$file['id']}' in parents"));
        foreach( $sub_files as $kk => $sub_file )
            {
            echo "{$sub_file['name']} - {$sub_file['id']}  ---- " . $sub_file['mimeType'] . "\n";
            }
        }
    catch (Exception $exc)
        {
        echo 'Caught exception: ',  $exc->getMessage(), "\n";
        }
    }
?>

</code>```

答:
How do you set parents?

If you do: $file->setParents('the id of the folder');, that won't work.

The right way is: $file->setParents(array('the id of the folder'));

Also make sure you are using the folder id and not the name.

Body:
I am trying to upload a zip file to google drive with a php script as a cron job on Fedora 33 x86-64. I have been tried several different things but I am not having any luck with this at this point. I have created a service account and downloaded the credentials, created the oauth concent screen, installed the Google Drive API, oauth client id, etc... Anyway when I run the script from the shell I get a very strange. Any help would be appreciated.

<?php
    require_once 'vendor/autoload.php';
    $googleClient = new Google_Client();
    $googleClient->setAuthConfig('***************************.json');
    $googleClient->addScope(Google_Service_Drive::DRIVE);
    $googleClient->setApplicationName('******************');
    $googleClient->setAccessType('offline');
    $googleClient->getAccessToken();
    $drive = new Google_Service_Drive($googleClient);
    $file = new Google_Service_Drive_DriveFile($googleClient);
    $file->setName('Mysql-Backup.zip');
    $file->setMimeType('application/zip');
    try {
      $return = $drive->files->create($file, array('data' => file_get_contents("Mysql-Backup.zip"), 'uploadType' => 'multipart', 'supportsAllDrives' => 'true'));
      echo "Sucessful upload of " . $file['name'] . ".";
    }
    catch (Exception $exc) {
      echo $exc->getMessage() . "\n";
    }
?>

Forgive me if I am not doing this correctly both the code and posting on stackoverflow.com. Ok I have tried as you suggested listing the files and you are indeed correct that the files were uploaded to my service account instead of my personal drive. I have also tried your suggestion of sharing a folder from my personal account to the service account using the web interface. However when I try again it still isn't working. This gives me an error "PHP Fatal error:  Uncaught Error: Call to undefined method Google_Service_Drive_Resource_Permissions::insert() in /scripts/google-drive/google-drive.php:25". I have refereed to https://developers.google.com/resources/api-libraries/documentation/drive/v3/php/latest/class-Google_Service_Drive_Permission.html and https://developers.google.com/drive/api/v2/reference/permissions/insert#php but still I don't understand what I am missing. I don't know if this is frowned upon but I am willing to paypal someone if they have a currant working php class with instructions. The documentation for this is all over the place the old stuff doesn't work and the new stuff doesn't work. I am banging my head in at this point.

<?php
require_once 'vendor/autoload.php';
$googleClient = new Google_Client();
$googleClient->setAuthConfig('****');
$googleClient->addScope("https://www.googleapis.com/auth/drive.file");
$googleClient->setApplicationName('MySQL-Backup');
$googleClient->setAccessType('offline');
$googleClient->getAccessToken();
$drive = new Google_Service_Drive($googleClient);
$file = new Google_Service_Drive_DriveFile($googleClient);
$file->setName('Mysql-Backup.zip');
$file->setMimeType('application/zip');
$file->setParents('****');
try
    {
    $return = $drive->files->create($file, array('data' => file_get_contents("Mysql-Backup.zip"), 'uploadType' => 'multipart', 'supportsAllDrives' => 'true'));
    echo "Sucessful upload of " . $file['name'] . " File ID:" . $return->id . "\n";
    $newPermission = new Google_Service_Drive_Permission();
    //$newPermission->setValue('***');
    $newPermission->setType('user');
    $newPermission->setRole('editor');
    echo $return->id . "\n";
    try
        {
        $drive->permissions->insert($return->id, $newPermission);
        }
    catch (Exception $exc)
        {
        echo 'Caught exception: ',  $exc->getMessage(), "\n";
        }
    }
catch (Exception $exc)
    {
    echo 'Caught exception: ',  $exc->getMessage(), "\n";
    }
$optParams = array('fields' => '*');
$myfiles = $drive->files->ListFiles($optParams);
foreach( $myfiles as $k => $file )
    {
    echo "{$file['name']} - {$file['id']} ---- " . $file['mimeType'] . "\n";
    try
        {
        // subfiles
        $sub_files = $drive->files->listFiles(array('q' => "'{$file['id']}' in parents"));
        foreach( $sub_files as $kk => $sub_file )
            {
            echo "{$sub_file['name']} - {$sub_file['id']}  ---- " . $sub_file['mimeType'] . "\n";
            }
        }
    catch (Exception $exc)
        {
        echo 'Caught exception: ',  $exc->getMessage(), "\n";
        }
    }
?>


问:
Getting Pygame keyboard input and check if it's a number
I am trying to get keyboard input using Pygame using this command:

if event.type == pg.KEYDOWN:
    # ADD KEYBOARD EVENTS
    keys = pg.key.get_pressed()
```

I want to check if the button pressed represents a number, I already know how to check if a string represent a number using try/except command, but, in my code keys is not a string, it is a huge tuple - and I don't know how to get it in an efficient way because every time I look in the internet on how to get keyboard input, they need to equate keys to something like pygame.pygame.K_LEFT and I don't want to do this for each number and furthermore every number in the number-pad (right side).

Is there an efficient way to determine if a user clicked on a number? Thanks!

答:
The following code offers quite a neat solution, it ignores all inputs that aren't numbers without even using try/except:

```<code>if event.type == pg.KEYDOWN and event.unicode.isdigit():
    print(int(event.unicode))
</code>```

I wasn't able to find a way to do this that was more compact on the web, so worked out this solution by researching how to check if a string is an integer.

How can I check if a string represents an int, without using try/except?

Body:
I am trying to get keyboard input using Pygame using this command:

if event.type == pg.KEYDOWN:
    # ADD KEYBOARD EVENTS
    keys = pg.key.get_pressed()

I want to check if the button pressed represents a number, I already know how to check if a string represent a number using try/except command, but, in my code keys is not a string, it is a huge tuple - and I don't know how to get it in an efficient way because every time I look in the internet on how to get keyboard input, they need to equate keys to something like pygame.pygame.K_LEFT and I don't want to do this for each number and furthermore every number in the number-pad (right side).

Is there an efficient way to determine if a user clicked on a number? Thanks!

Body:
The following code offers quite a neat solution, it ignores all inputs that aren't numbers without even using try/except:

if event.type == pg.KEYDOWN and event.unicode.isdigit():
    print(int(event.unicode))

I wasn't able to find a way to do this that was more compact on the web, so worked out this solution by researching how to check if a string is an integer.

How can I check if a string represents an int, without using try/except?


问:
Issue with corrupted assets flutter, fastapi, Lambda, ApiGateway, S3
I'm running into a strange issue with the following setup:

Flutter app that uploads an image to a fastapi backend thats served from a lambda function through ApiGateway, which uses bota3 to upload and serve the image from s3.

My python routes look like this.

```<code>@router.get("{filePath:path}")
async def read_root(filePath, current_user: CognitoClaims = Depends(get_current_user)):
    user: User = await get_user(current_user.username)
    company: Company = await get_company(user);

    try:
        response = s3.generate_presigned_url('get_object', Params={
            'Bucket': settings.s3_bucket,
            'Key': filePath.strip("/")
        }, ExpiresIn=3600)
    except ClientError as e:
        logging.error(e)
        return None
    return response

@router.post("")
async def add_file(current_user: CognitoClaims = Depends(get_current_user), file: UploadFile = File(...)):
    user: User = await get_user(current_user.username)
    company: Company = await get_company(user);

    file_name = file.filename;

    full_name = f"{current_user.username}/uploads/{file_name}"

    try:
        s3.upload_fileobj(file.file, settings.s3_bucket, full_name)

        response = s3.generate_presigned_url('get_object', Params={
                'Bucket': settings.s3_bucket,
                'Key': full_name
            }, ExpiresIn=3600);
    except ClientError as e:
        logging.error(e)
        return None

    return {
        "path": full_name,
        'url': response
    };

</code>```

The endpoints and functions are all successful, but the images uploaded to s3 seem to be corrupted.

The strange part is that I am able to use these endpoints perfectly when hitting using postman, and even stranger than that it runs fine locally from the flutter app. so i can only assume its an issue related to my ApiGateway setup.

答:
This issue is due to REST API Gateways defaulting to handling all payloads as text. In order for a payload to be handled as binary, the media type for the payload  must be added to the binaryMediaTypes for the REST API Gateway.

In the specific case of file uploads via UploadFile in FastAPI, the media type is multipart/form-data, and so this needs to be added to the binaryMediaTypes configuration for the gateway. In my case I'm deploying via CDK and so on my lambdaRestApi I needed to set binaryMediaTypes to ["multipart/form-data"].

More information can be found in the AWS Working with binary media types for REST APIs Developer Guide.

Body:
I'm running into a strange issue with the following setup:

Flutter app that uploads an image to a fastapi backend thats served from a lambda function through ApiGateway, which uses bota3 to upload and serve the image from s3.

My python routes look like this.

@router.get("{filePath:path}")
async def read_root(filePath, current_user: CognitoClaims = Depends(get_current_user)):
    user: User = await get_user(current_user.username)
    company: Company = await get_company(user);

    try:
        response = s3.generate_presigned_url('get_object', Params={
            'Bucket': settings.s3_bucket,
            'Key': filePath.strip("/")
        }, ExpiresIn=3600)
    except ClientError as e:
        logging.error(e)
        return None
    return response

@router.post("")
async def add_file(current_user: CognitoClaims = Depends(get_current_user), file: UploadFile = File(...)):
    user: User = await get_user(current_user.username)
    company: Company = await get_company(user);

    file_name = file.filename;

    full_name = f"{current_user.username}/uploads/{file_name}"

    try:
        s3.upload_fileobj(file.file, settings.s3_bucket, full_name)

        response = s3.generate_presigned_url('get_object', Params={
                'Bucket': settings.s3_bucket,
                'Key': full_name
            }, ExpiresIn=3600);
    except ClientError as e:
        logging.error(e)
        return None

    return {
        "path": full_name,
        'url': response
    };

The endpoints and functions are all successful, but the images uploaded to s3 seem to be corrupted.

The strange part is that I am able to use these endpoints perfectly when hitting using postman, and even stranger than that it runs fine locally from the flutter app. so i can only assume its an issue related to my ApiGateway setup.


问:
Amazon ECS: Target Group Health Check vs Container Health Check
Amazon ECS supports two different types of health checks:

Target Group health checks make a configurable network request

Container health checks run in the docker container and can be configured to run any shell command that the container supports

If both health checks are configured, which one wins? If either fails is the Service marked as UNHEALTHY? Or both? Can I configure one to override the other?

I'd very much like the Target Group health status to not cause ECS to continually bounce the service and I was hoping the container Health Check could be used to override it.

答: In my experience, either one will cause your container to be decommissioned.  I would say you probably don't need the container health check if you have a target group performing the check.</p>


问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
Ad 1 & 2: The const in the prototype applies to the Dict, that means

```<code>char *get(const Dict *dict, int key)
</code>```

reads as ... function with a (non-const) argument of type pointer to constant Dict ..., which means you can change the dict, but not eg. dict->next.

If you want to get the effect you probably intended, declare it like this

```<code>char *get(Dict * const dict, int key)
</code>```

The rule is: The const applies to the word that is to the left of it, except when it is first in the type name, and then it applies to the next word.

Also, changing dict doesn't change the pointer in the main program, since the pointer is passed by value.

When assigning to the currDict pointer, the compiler checks that the types are compatible, which, in this case, means that you can only add top-level const qualifiers, not remove as you do.

Where should you use const:

In the get() function, you should use const on all Dicts (as you do), as you probably don't want to change the dictionary there.

In the del(), function, I wouldn't use any consts, since the data are to be changed there. A good signature for it would be:

```<code>char *get(Dict ** dict, int key)
</code>```

so you would be able to change the calling function's pointer to delete the first element.

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

Body:
Ad 1 & 2: The const in the prototype applies to the Dict, that means

char *get(const Dict *dict, int key)

reads as ... function with a (non-const) argument of type pointer to constant Dict ..., which means you can change the dict, but not eg. dict->next.

If you want to get the effect you probably intended, declare it like this

char *get(Dict * const dict, int key)

The rule is: The const applies to the word that is to the left of it, except when it is first in the type name, and then it applies to the next word.

Also, changing dict doesn't change the pointer in the main program, since the pointer is passed by value.

When assigning to the currDict pointer, the compiler checks that the types are compatible, which, in this case, means that you can only add top-level const qualifiers, not remove as you do.

Where should you use const:

In the get() function, you should use const on all Dicts (as you do), as you probably don't want to change the dictionary there.

In the del(), function, I wouldn't use any consts, since the data are to be changed there. A good signature for it would be:

char *get(Dict ** dict, int key)

so you would be able to change the calling function's pointer to delete the first element.

OwnerDisplayName: jpalecek

LastEditorDisplayName: jpalecek