问:
How do I implement a child context (CoreData) in SwiftUI environment?
I'm currently learning SwiftUI to further include it in my daily UIKit-based workflow. I got to a point where I can not get a concept running in SwiftUI, that I've been using for years in UIKit.

The idea is to use a child context of my main CoreData managedObjectContext for editing entities. I implement it quite basically by doing the following:

```<code>// Get view context of application
let viewContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

// Create NSManagedObjectContext
let editingContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

// Set the parent of the editing context to the main view context
editingContext.parent = viewContext
</code>```

By using a separate editingContext I can make changes to an entity in it without the change proceeding directly to my main context. If the user chooses to abort the change, I just reset the editingContext.

For the implementation in SwiftUI, I chose to implement the editingContext as an environment object by creating a custom EnvironmentKey:

```<code>struct EditingContextKey: EnvironmentKey {
    static let defaultValue: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
}

extension EnvironmentValues {
    var editingContext: NSManagedObjectContext {
        get {
            return self[EditingContextKey.self]
        }
        set {
            self[EditingContextKey.self] = newValue
        }
    }
}
</code>```

Then the editingContext is added to my root view:

```<code>let contentView = ContentView()
    .environment(\.managedObjectContext, viewContext)
    .environment(\.editingContext, editingContext)
</code>```

To this point everything works fine. I also can use the editingContext by calling the following in the respective view.

```<code>@Environment(\.editingContext) var editingContext
</code>```

However, as soon as I make changes to the entity in the editingContext and try to save the editingContext, I get an unexpected error:

```<code>Fatal error: Unresolved error Error Domain=Foundation._GenericObjCError Code=0 "(null)", [:]: file
</code>```

I did already checked, if the context of the edited entity is matching the editingContext. This seems to be the case. I have the feeling, it could have something to do with a binding in SwiftUI, but have no idea how to approach finding a solution.

Has anyone had a similar problem? Or is my basic approach to the desired functionality wrong and there is a more convenient way of doing this?

Thank you!

答:
Looking at your approach, I would not recommend injecting two different contexts at the same time into a single view's environment. It's best to have a clear mental picture of whether the view is in the main view context territory or the editing child context territory. If we are working with a view that we know is driven by a nested context, merely dismissing that view will clear out its struct from memory, destroy its context, and thus discard our changes.

We also have to be mindful of where we create our nested contexts. The mistake I used to make is creating a nested context inside a .sheet modifier like so:

.sheet(isPresented: $isPresentingItemEditor) {
    makeItemEditor()
}

func makeItemEditor() -> some View {
     let childContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
     childContext.parent = viewContext
     let childItem = Item(context: childContext)
     return ItemEditor(item: childItem)
         .environment(\.managedObjectContext, childContext)
}
```
<p>It works fine at first, but the system might call <code>.sheet</code> modifier many times, and we'll be creating new child contexts for the same operation. As we scale, this might cause the user to lose their changes when the app moves to the background, failures establishing relationships between objects because they are in different contexts.</p>
<p>To remedy this, we can store our nested context, and a newly created object in that context, in a dedicated structure like this:</p>
<pre class="lang-swift prettyprint-override"><code>struct CreateOperation<Object: NSManagedObject>: Identifiable {
    let id = UUID()
    let childContext: NSManagedObjectContext
    let object: Object

    init(withParentContext parentContext: NSManagedObjectContext) {
        childContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        childContext.parent = parentContext
        object = Object(context: childContext)
    }
}
</code>```

Now to create a new object and present accompanying UI for editing, we simply need to create an instance of that structure.

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

    @FetchRequest(sortDescriptors: [SortDescriptor(\.name)])
    private var items: FetchedResults<Item>

    @State private var configuration: CreateOperation<Item>?

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

            .toolbar {
                Button(action: addItem) {
                    Label("Add Item", systemImage: "plus")
                }
            }
        }
        .sheet(item: $configuration) { configuration in
            ItemEditor(item: configuration.object)
                .environment(\.managedObjectContext, configuration.childContext)
        }
    }

    private func addItem() {
        configuration = CreateOperation(withParentContext: viewContext)
    }
}
```
<pre class="lang-swift prettyprint-override"><code>struct ItemEditor: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.managedObjectContext) private var context

    @ObservedObject var item: Item
    var body: some View {
        NavigationView {
            Form {
                TextField("Name", text: Binding($item.name)!)
            }
            .navigationTitle("New Item")
            .toolbar {
                Button("Save") {
                    try? context.save()
                    dismiss()
                }
            }
        }
    }
}
</code>```

Body:
I'm currently learning SwiftUI to further include it in my daily UIKit-based workflow. I got to a point where I can not get a concept running in SwiftUI, that I've been using for years in UIKit.

The idea is to use a child context of my main CoreData managedObjectContext for editing entities. I implement it quite basically by doing the following:

// Get view context of application
let viewContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

// Create NSManagedObjectContext
let editingContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

// Set the parent of the editing context to the main view context
editingContext.parent = viewContext

By using a separate editingContext I can make changes to an entity in it without the change proceeding directly to my main context. If the user chooses to abort the change, I just reset the editingContext.

For the implementation in SwiftUI, I chose to implement the editingContext as an environment object by creating a custom EnvironmentKey:

struct EditingContextKey: EnvironmentKey {
    static let defaultValue: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
}

extension EnvironmentValues {
    var editingContext: NSManagedObjectContext {
        get {
            return self[EditingContextKey.self]
        }
        set {
            self[EditingContextKey.self] = newValue
        }
    }
}

Then the editingContext is added to my root view:

let contentView = ContentView()
    .environment(\.managedObjectContext, viewContext)
    .environment(\.editingContext, editingContext)

To this point everything works fine. I also can use the editingContext by calling the following in the respective view.

@Environment(\.editingContext) var editingContext

However, as soon as I make changes to the entity in the editingContext and try to save the editingContext, I get an unexpected error:

Fatal error: Unresolved error Error Domain=Foundation._GenericObjCError Code=0 "(null)", [:]: file

I did already checked, if the context of the edited entity is matching the editingContext. This seems to be the case. I have the feeling, it could have something to do with a binding in SwiftUI, but have no idea how to approach finding a solution.

Has anyone had a similar problem? Or is my basic approach to the desired functionality wrong and there is a more convenient way of doing this?

Thank you!

Body:
Looking at your approach, I would not recommend injecting two different contexts at the same time into a single view's environment. It's best to have a clear mental picture of whether the view is in the main view context territory or the editing child context territory. If we are working with a view that we know is driven by a nested context, merely dismissing that view will clear out its struct from memory, destroy its context, and thus discard our changes.

We also have to be mindful of where we create our nested contexts. The mistake I used to make is creating a nested context inside a .sheet modifier like so:

.sheet(isPresented: $isPresentingItemEditor) {
    makeItemEditor()
}

func makeItemEditor() -> some View {
     let childContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
     childContext.parent = viewContext
     let childItem = Item(context: childContext)
     return ItemEditor(item: childItem)
         .environment(\.managedObjectContext, childContext)
}

It works fine at first, but the system might call .sheet modifier many times, and we'll be creating new child contexts for the same operation. As we scale, this might cause the user to lose their changes when the app moves to the background, failures establishing relationships between objects because they are in different contexts.

To remedy this, we can store our nested context, and a newly created object in that context, in a dedicated structure like this:

struct CreateOperation<Object: NSManagedObject>: Identifiable {
    let id = UUID()
    let childContext: NSManagedObjectContext
    let object: Object

    init(withParentContext parentContext: NSManagedObjectContext) {
        childContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        childContext.parent = parentContext
        object = Object(context: childContext)
    }
}

Now to create a new object and present accompanying UI for editing, we simply need to create an instance of that structure.

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

    @FetchRequest(sortDescriptors: [SortDescriptor(\.name)])
    private var items: FetchedResults<Item>

    @State private var configuration: CreateOperation<Item>?

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

            .toolbar {
                Button(action: addItem) {
                    Label("Add Item", systemImage: "plus")
                }
            }
        }
        .sheet(item: $configuration) { configuration in
            ItemEditor(item: configuration.object)
                .environment(\.managedObjectContext, configuration.childContext)
        }
    }

    private func addItem() {
        configuration = CreateOperation(withParentContext: viewContext)
    }
}

struct ItemEditor: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.managedObjectContext) private var context

    @ObservedObject var item: Item
    var body: some View {
        NavigationView {
            Form {
                TextField("Name", text: Binding($item.name)!)
            }
            .navigationTitle("New Item")
            .toolbar {
                Button("Save") {
                    try? context.save()
                    dismiss()
                }
            }
        }
    }
}


来源: stackexchange

问:
How to use func assign(_ object: Any, to store: NSPersistentStore) of a NSManagedObjectContext?
Setup:

My app uses 2 persistent stores managed by a single persistent store coordinator that is used by several managed object contexts. Both persistent stores store the same entities.

It is required that any inserts, updates and deletes of managed objects are only done in one of both persistent stores, and the app can select the persistent store.

Problem:

In order to store a managed object only in one persistent store, I want to use func assign(_ object: Any, to store: NSPersistentStore) of a NSManagedObjectContext. The docs say

Specifies the store in which a newly inserted object will be saved.

Question:

What means „newly inserted“?

Can I assign a persistent store as long as the object has never been saved by its context?

Could I use, e.g., a willSaveObjectsNotification to loop though all registeredObjects of the context and assign the required persistent store?

When the app switches the persistent store, I would then reset the contexts so that all managed objects would be fetched newly, and the required persistent store could be set again in the willSaveObjectsNotification notification.

Is this the right way to go?

答:
Based on Tom Harrington’s answer, I did the following tests.

The result is:

As long as a managed object has never been saved to a persistent store, one can use assign(_:to:) to define one of several persistent stores into which the object will be saved later.

My code:

```<code>// Setup:
// privateStore and sharedStore are persistent stores to which the Item entity is assigned.
// Item is a managed object whose entity is assigned to the persistent stores privateStore and sharedStore.
// It has an attribute "name" to distibguish it from other objects.

// Create for privateStore and sharedStore one fetch request respectively for an Item with name "item"
let namePredicate = NSPredicate(format: "name == %@", "item")

let privateStoreItemFetchRequest = NSFetchRequest<Item>(entityName: Item.entityName)
privateStoreItemFetchRequest.predicate = namePredicate
privateStoreItemFetchRequest.affectedStores = [privateStore]

let sharedStoreItemFetchRequest = NSFetchRequest<Item>(entityName: Item.entityName)
sharedStoreItemFetchRequest.predicate = namePredicate
sharedStoreItemFetchRequest.affectedStores = [sharedStore]

// 1st test: Create an Item without a context, assign it to a store, insert it into a context and try to fetch it from both stores
let item1 = Item(entity: itemEntity, insertInto: nil)
item1.name = "item"
viewContext!.assign(item1, to: privateStore)
viewContext!.insert(item1)
let items1InPrivateStore = try? viewContext!.fetch(privateStoreItemFetchRequest)
print("Test 1: privateStore: \(items1InPrivateStore ?? [])") // Prints item1
let items1InSharedStore = try? viewContext!.fetch(sharedStoreItemFetchRequest)
print("Test 1: sharedStore: \(items1InSharedStore ?? [])") // Prints []

// 2nd test: Create an Item and insert it into a context, assign it to a store and try to fetch it from both stores
let item2 = Item(entity: itemEntity, insertInto: viewContext!)
item2.name = "item"
viewContext!.assign(item2, to: privateStore)
let items2InPrivateStore = try? viewContext!.fetch(privateStoreItemFetchRequest)
print("Test 2: privateStore: \(items2InPrivateStore ?? [])") // Prints item1 and item2
let items2InSharedStore = try? viewContext!.fetch(sharedStoreItemFetchRequest)
print("Test 2: sharedStore: \(items2InSharedStore ?? [])") // Prints []

// Save the context and try to fetch both items from both stores
do {
    try viewContext!.save()
} catch { fatalError() }
let items3InPrivateStore = try? viewContext!.fetch(privateStoreItemFetchRequest)
print("Test 3: privateStore: \(items3InPrivateStore ?? [])") // Prints item1 and item2
let items3InSharedStore = try? viewContext!.fetch(sharedStoreItemFetchRequest)
print("Test 3: sharedStore: \(items3InSharedStore ?? [])") // Prints []

// item1 has been assigned above to the privateStore. Try now to assign it to the sharedStore
viewContext!.assign(item1, to: sharedStore) // Run time error: "Can't reassign an object to a different store once it has been saved."
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Based on Tom Harrington’s answer, I did the following tests.

The result is:

As long as a managed object has never been saved to a persistent store, one can use assign(_:to:) to define one of several persistent stores into which the object will be saved later.

My code:

// Setup:
// privateStore and sharedStore are persistent stores to which the Item entity is assigned.
// Item is a managed object whose entity is assigned to the persistent stores privateStore and sharedStore.
// It has an attribute "name" to distibguish it from other objects.

// Create for privateStore and sharedStore one fetch request respectively for an Item with name "item"
let namePredicate = NSPredicate(format: "name == %@", "item")

let privateStoreItemFetchRequest = NSFetchRequest<Item>(entityName: Item.entityName)
privateStoreItemFetchRequest.predicate = namePredicate
privateStoreItemFetchRequest.affectedStores = [privateStore]

let sharedStoreItemFetchRequest = NSFetchRequest<Item>(entityName: Item.entityName)
sharedStoreItemFetchRequest.predicate = namePredicate
sharedStoreItemFetchRequest.affectedStores = [sharedStore]

// 1st test: Create an Item without a context, assign it to a store, insert it into a context and try to fetch it from both stores
let item1 = Item(entity: itemEntity, insertInto: nil)
item1.name = "item"
viewContext!.assign(item1, to: privateStore)
viewContext!.insert(item1)
let items1InPrivateStore = try? viewContext!.fetch(privateStoreItemFetchRequest)
print("Test 1: privateStore: \(items1InPrivateStore ?? [])") // Prints item1
let items1InSharedStore = try? viewContext!.fetch(sharedStoreItemFetchRequest)
print("Test 1: sharedStore: \(items1InSharedStore ?? [])") // Prints []

// 2nd test: Create an Item and insert it into a context, assign it to a store and try to fetch it from both stores
let item2 = Item(entity: itemEntity, insertInto: viewContext!)
item2.name = "item"
viewContext!.assign(item2, to: privateStore)
let items2InPrivateStore = try? viewContext!.fetch(privateStoreItemFetchRequest)
print("Test 2: privateStore: \(items2InPrivateStore ?? [])") // Prints item1 and item2
let items2InSharedStore = try? viewContext!.fetch(sharedStoreItemFetchRequest)
print("Test 2: sharedStore: \(items2InSharedStore ?? [])") // Prints []

// Save the context and try to fetch both items from both stores
do {
    try viewContext!.save()
} catch { fatalError() }
let items3InPrivateStore = try? viewContext!.fetch(privateStoreItemFetchRequest)
print("Test 3: privateStore: \(items3InPrivateStore ?? [])") // Prints item1 and item2
let items3InSharedStore = try? viewContext!.fetch(sharedStoreItemFetchRequest)
print("Test 3: sharedStore: \(items3InSharedStore ?? [])") // Prints []

// item1 has been assigned above to the privateStore. Try now to assign it to the sharedStore
viewContext!.assign(item1, to: sharedStore) // Run time error: "Can't reassign an object to a different store once it has been saved."


问:
change color using JavaScript (DOM)
```<code> const box = document.getElementsByClassName('box');
 let colorAsString = '#FEC6F0';
 let colorAsNumber = #FEC6F0;
    Array.from(box).forEach((element) =>{
        element.style.backgroundColor = colorAsString;
        element.style.backgroundColor = colorAsNumber;
    });
</code>```

I stored a hex-color value in string as well as a number and pass the variable as a value for css property.
Why this code not work can you explain me...!

答:
When you edit the style property, it is in the end only a CSS string. So to represent colors you can use formats like: '#ffffff' or 'rgb(255,255,255)'. But you cannot use a number.

You can read more about that here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

 const box = document.getElementsByClassName('box');
 let colorAsString = '#FEC6F0';
    Array.from(box).forEach((element) =>{
        element.style.backgroundColor = colorAsString;
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  width:100px;
  height:100px;
  margin:10px;
  background-color:gray;
}</code>```

```

Title: change color using JavaScript (DOM)

Body:
 const box = document.getElementsByClassName('box');
 let colorAsString = '#FEC6F0';
 let colorAsNumber = #FEC6F0;
    Array.from(box).forEach((element) =>{
        element.style.backgroundColor = colorAsString;
        element.style.backgroundColor = colorAsNumber;
    });

I stored a hex-color value in string as well as a number and pass the variable as a value for css property.
Why this code not work can you explain me...!

Body:
When you edit the style property, it is in the end only a CSS string. So to represent colors you can use formats like: '#ffffff' or 'rgb(255,255,255)'. But you cannot use a number.

You can read more about that here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

 const box = document.getElementsByClassName('box');
 let colorAsString = '#FEC6F0';
    Array.from(box).forEach((element) =>{
        element.style.backgroundColor = colorAsString;
    });

.box {
  width:100px;
  height:100px;
  margin:10px;
  background-color:gray;
}

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>


问:
Android - Emulator in landscape mode, screen does not rotate
When I switch to landscape mode (NUMPAD 7 or CTRL+F11) the emulator rotates the screen to landscape orientation but the Android OS and none of the apps rotate. So everything is sitting sideways. Is there something in the AVD configuration that needs to be set in order for the device to rotate properly?

答:
I had to first press and hold rotate until I got into the menu.
Then toggle Auto-rotate screen to true.

ContentLicense: CC BY-SA 3.0


问:
Play sounds with AVQueuePlayer even if iPhone is muted
I'm using AVQueuePlayer to play sounds (a little App for kids to listen illustrated books), but if iPhone is muted the audio isn't audible.

There is a way to force audio even if iPhone is muted? I think to YouTube where audio is audible or Instagram when you have to pop up the volume to listen stories.

Thanks.

答:
By default AVPlayer is dependent on ringer position if the ringer is in silent mode you can't listen to audio. if you want to play audio even the ringer is in silent position then set setCategory as AVAudioSessionCategoryPlayback before playing video.

```<code>try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, options: [])
</code>```

Body:
By default AVPlayer is dependent on ringer position if the ringer is in silent mode you can't listen to audio. if you want to play audio even the ringer is in silent position then set setCategory as AVAudioSessionCategoryPlayback before playing video.

try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, options: [])


问:
Method Overloading in Excel COM Interop
I am having a lot of troubles with method overloading here and have no idea why only one method gets called each time regardless the number of parameters I pass into. Below is the sample code.

```<code>[ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
public class myClass
{
    //constructor
    public myClass() {}

    //base method
    public string myfunction(string id, string pk) {return results;}

    //overloading method 1
    public string myfunction(string id, string pk, string param1) { return results;}

    //overloading method 2
    public string myfunction(string id, string pk, string param1, string param2) {return results;}

    [ComRegisterFunctionAttribute]
        public static void RegisterFunction(Type type)
        {

            Registry.ClassesRoot.CreateSubKey(
              GetSubKeyName(type, "Programmable"));
            RegistryKey key = Registry.ClassesRoot.OpenSubKey(
              GetSubKeyName(type, "InprocServer32"), true);
            key.SetValue("",
              System.Environment.SystemDirectory + @"\mscoree.dll",
              RegistryValueKind.String);
        }
        [ComUnregisterFunctionAttribute]
        public static void UnregisterFunction(Type type)
        {

            Registry.ClassesRoot.DeleteSubKey(
              GetSubKeyName(type, "Programmable"), false);
        }
        private static string GetSubKeyName(Type type,
          string subKeyName)
        {
            System.Text.StringBuilder s =
              new System.Text.StringBuilder();
            s.Append(@"CLSID\{");
            s.Append(type.GUID.ToString().ToUpper());
            s.Append(@"}\");
            s.Append(subKeyName);
            return s.ToString();
        }

}
</code>```

So when I tested it in Excel, the base method worked fine and I could get the expected value. However, it would fail if I tried the rest two functions using method overloading. They simply didn't get called for some reason. Am I missing something in the code? Can anyone help me please?  Thanks very much.

Edit:

Through some experiments, it occurs to me that there only 1 method can be recognized, which normally is the first method. So if I swap the order between base method and overloading method 1, the overloading method 1 will be called instead of the base method. Looks like the whole class just gets stuck in the first method and wouldn't go on.

答:
Excelfriend, you can't polymorphize a a worksheet function. A
worksheet function called, say, GETSALESFORWEEK can only have one
entry point. If you provide two, say GETSALESFORWEEK(int WeekNumber)
and GETSALESFORWEEK(string WeekName) then Excel 2007 will expose these
functions as GETSALESFORWEEK and GETSALESFORWEEK_2.

Source: http://blogs.msdn.com/b/gabhan_berry/archive/2008/04/07/writing-custom-excel-worksheet-functions-in-c_2d00_sharp.aspx

Well I guess that answers my questions. Sadly, no method overloading for custom Excel functions :(

Solution:

[ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
public class myClass
{
    //constructor
    public myClass() {}

    //base method
    /**public string myfunction(string id, string pk) {return results;}**/

    //overloading method 1
    /**public string myfunction(string id, string pk, string param1) { return results;}**/

    //just use 1 method, but make the last two arguments optional by setting default values
    public string myfunction(string id, string pk, string param1 = "", string param2 = "") {return results;}

    [ComRegisterFunctionAttribute]
    public static void RegisterFunction(Type type)
    {
        Registry.ClassesRoot.CreateSubKey(
          GetSubKeyName(type, "Programmable"));
        RegistryKey key = Registry.ClassesRoot.OpenSubKey(
          GetSubKeyName(type, "InprocServer32"), true);
        key.SetValue("",
          System.Environment.SystemDirectory + @"\mscoree.dll",
          RegistryValueKind.String);
    }

    [ComUnregisterFunctionAttribute]
    public static void UnregisterFunction(Type type)
    {
        Registry.ClassesRoot.DeleteSubKey(
          GetSubKeyName(type, "Programmable"), false);
    }

    private static string GetSubKeyName(Type type, string subKeyName)
    {
        System.Text.StringBuilder s = new System.Text.StringBuilder();
        s.Append(@"CLSID\{");
        s.Append(type.GUID.ToString().ToUpper());
        s.Append(@"}\");
        s.Append(subKeyName);
        return s.ToString();
    }
}
```

Title: Method Overloading in Excel COM Interop

Body:
I am having a lot of troubles with method overloading here and have no idea why only one method gets called each time regardless the number of parameters I pass into. Below is the sample code.

[ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
public class myClass
{
    //constructor
    public myClass() {}

    //base method
    public string myfunction(string id, string pk) {return results;}

    //overloading method 1
    public string myfunction(string id, string pk, string param1) { return results;}

    //overloading method 2
    public string myfunction(string id, string pk, string param1, string param2) {return results;}

    [ComRegisterFunctionAttribute]
        public static void RegisterFunction(Type type)
        {

            Registry.ClassesRoot.CreateSubKey(
              GetSubKeyName(type, "Programmable"));
            RegistryKey key = Registry.ClassesRoot.OpenSubKey(
              GetSubKeyName(type, "InprocServer32"), true);
            key.SetValue("",
              System.Environment.SystemDirectory + @"\mscoree.dll",
              RegistryValueKind.String);
        }
        [ComUnregisterFunctionAttribute]
        public static void UnregisterFunction(Type type)
        {

            Registry.ClassesRoot.DeleteSubKey(
              GetSubKeyName(type, "Programmable"), false);
        }
        private static string GetSubKeyName(Type type,
          string subKeyName)
        {
            System.Text.StringBuilder s =
              new System.Text.StringBuilder();
            s.Append(@"CLSID\{");
            s.Append(type.GUID.ToString().ToUpper());
            s.Append(@"}\");
            s.Append(subKeyName);
            return s.ToString();
        }

}

So when I tested it in Excel, the base method worked fine and I could get the expected value. However, it would fail if I tried the rest two functions using method overloading. They simply didn't get called for some reason. Am I missing something in the code? Can anyone help me please?  Thanks very much.

Edit:

Through some experiments, it occurs to me that there only 1 method can be recognized, which normally is the first method. So if I swap the order between base method and overloading method 1, the overloading method 1 will be called instead of the base method. Looks like the whole class just gets stuck in the first method and wouldn't go on.


问:
Google Login with Laravel
In my website I have a candidate account and a Employer account.

I want to add google login for both users. Both have different controller methods and routes.

Google login for candidate is working but google login with employer saying redirect URI mismatch.

In my google console I have add two redirect URI's one for candidate and one for employer.

My question is is it possible to have multiple redirect uri in .env

My .env looks like
:

```<code>GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_URL=http://www.theunitedjobs.com/login/jobseeker/google/callback
</code>```

But I want to add two google_url want to add this also
:

```<code>GOOGLE_URL=http://theunitedjobs.com/login/employer/google/callback
</code>```

So is it possible to add two redirect URI's???

答: Rather than use a login_uri parameter for your google login markup , you can use data-callback and check in the function on which route you want to send the route to.</p>

Title: Google Login with Laravel

Body:
In my website I have a candidate account and a Employer account.

I want to add google login for both users. Both have different controller methods and routes.

Google login for candidate is working but google login with employer saying redirect URI mismatch.

In my google console I have add two redirect URI's one for candidate and one for employer.

My question is is it possible to have multiple redirect uri in .env

My .env looks like
:

GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_URL=http://www.theunitedjobs.com/login/jobseeker/google/callback

But I want to add two google_url want to add this also
:

GOOGLE_URL=http://theunitedjobs.com/login/employer/google/callback

So is it possible to add two redirect URI's???


问:
Flutter & Shared Preferences: How do i save and read back a List<Object> using setStringList? Also, how do i remove a specific object from the List?
```<code>class Restaurant {
  Restaurant({
    required this.name,
    required this.description,
    required this.address,
    required this.imageUrl,
  });

  Restaurant.fromJson(Map<String, Object?> json)
      : this(
          name: json['name']! as String,
          description: json['description']! as String,
          address: json['address']! as String,
          imageUrl: json['imageUrl'] as String,
        );

  final String name;
  final String description;
  final String address;
  final String imageUrl;

  Map<String, Object?> toJson() {
    return {
      'name': name,
      'description': description,
      'address': address,
      'imageUrl': imageUrl,
    };
  }
}
</code>```

I get the list of restaurants from Firebase and when the user clicks Favorite Icon, I want to save that restaurant locally and retrieve the list of favorite restaurants and show it on another page. I know I can do it on Firebase directly but for now, I want it saved locally.

I am looking forward to hearing from all of you. Thank you.

答:
Instead using SharedPreferences setStringList, you can use setString.

Here excerpt using setStringList:

```<code> // sample restaurants.
 List<Restaurant> favoriteRestos = [resto1, resto2, resto3];

 List<String> favorites = [];

 // Generate json for each restaurant
 for(var resto in favoriteRestos) {
    var json = jsonEncode(resto);
    favorites.add(json);
 }

// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();

// saving
await prefs.setStringList('favorites', favorites);

// Reading part
List<String> jsonRestos = prefs.getStringList('favorites')??[];

List<Restaurant> resFavorites = [];
for(var jsonResto in jsonRestos) {
   var map = jsonDecode(jsonResto);
   var resto = Restaurant.fromJson(map);
   resFavorites.add(resto);
}
</code>```

For setString:

```<code>List<Restaurant> favoriteRestos = [resto1, resto2, resto3];
var json = jsonEncode(favoriteRestos);

// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();

// saving
await prefs.setString('favorites', json);

// reading
var resJson = prefs.getString('favorites')??'';
var parsedJson = jsonDecode(resJson);
List<Restaurant> items = List<Restaurant>.from(parsedJson.map((i) => Restaurant.fromJson(i)));
</code>```

Note:
You need to update your Restaurant class. See https://docs.flutter.dev/development/data-and-backend/json#serializing-json-inside-model-classes

Body:
class Restaurant {
  Restaurant({
    required this.name,
    required this.description,
    required this.address,
    required this.imageUrl,
  });

  Restaurant.fromJson(Map<String, Object?> json)
      : this(
          name: json['name']! as String,
          description: json['description']! as String,
          address: json['address']! as String,
          imageUrl: json['imageUrl'] as String,
        );

  final String name;
  final String description;
  final String address;
  final String imageUrl;

  Map<String, Object?> toJson() {
    return {
      'name': name,
      'description': description,
      'address': address,
      'imageUrl': imageUrl,
    };
  }
}

I get the list of restaurants from Firebase and when the user clicks Favorite Icon, I want to save that restaurant locally and retrieve the list of favorite restaurants and show it on another page. I know I can do it on Firebase directly but for now, I want it saved locally.

I am looking forward to hearing from all of you. Thank you.

Body:
Instead using SharedPreferences setStringList, you can use setString.

Here excerpt using setStringList:

 // sample restaurants.
 List<Restaurant> favoriteRestos = [resto1, resto2, resto3];

 List<String> favorites = [];

 // Generate json for each restaurant
 for(var resto in favoriteRestos) {
    var json = jsonEncode(resto);
    favorites.add(json);
 }

// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();

// saving
await prefs.setStringList('favorites', favorites);

// Reading part
List<String> jsonRestos = prefs.getStringList('favorites')??[];

List<Restaurant> resFavorites = [];
for(var jsonResto in jsonRestos) {
   var map = jsonDecode(jsonResto);
   var resto = Restaurant.fromJson(map);
   resFavorites.add(resto);
}

For setString:

List<Restaurant> favoriteRestos = [resto1, resto2, resto3];
var json = jsonEncode(favoriteRestos);

// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();

// saving
await prefs.setString('favorites', json);

// reading
var resJson = prefs.getString('favorites')??'';
var parsedJson = jsonDecode(resJson);
List<Restaurant> items = List<Restaurant>.from(parsedJson.map((i) => Restaurant.fromJson(i)));

Note:
You need to update your Restaurant class. See https://docs.flutter.dev/development/data-and-backend/json#serializing-json-inside-model-classes


问:
Creating Docker image with springboot layertools - does not find profile specific application properties
I am following the tutorial here and here on how to create a layered Docker image from my springboot backend.  I end up with the following Dockerfile:

```<code>FROM openjdk:8-jre-slim as builder
WORKDIR application
ARG JAR_FILE=target/*-exec.jar
COPY ${JAR_FILE} application.jar
RUN java -Djarmode=layertools -jar application.jar extract

FROM openjdk:8-jre-slim
WORKDIR application
COPY --from=builder application/dependencies/ ./
COPY --from=builder application/spring-boot-loader/ ./
COPY --from=builder application/snapshot-dependencies/ ./
COPY --from=builder application/application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]
</code>```

The problem is that when I run this in my docker-compose with a Spring profile TST, that it does not find application-tst.properties.  I can see from the logs that Spring profile TST is active on startup, yet it only loads the properties from application.properties.

As a sanity check I copied the properties from application-tst.properties over to application.properties and rebuilt my image, which then worked fine (it connects to the database container etc).

I extracted the contents of my executable jar (which is the jar from line 3 in the Dockerfile) and can confirm that application-tst.properties is present there. Anyone know what the issue is?

答:
I found the answer and it's a really dumb one...  The Spring profile is case sensitive, so

```<code>SPRING_PROFILES_ACTIVE=TST
</code>```

should become

```<code>SPRING_PROFILES_ACTIVE=tst
</code>```

Body:
I am following the tutorial here and here on how to create a layered Docker image from my springboot backend.  I end up with the following Dockerfile:

FROM openjdk:8-jre-slim as builder
WORKDIR application
ARG JAR_FILE=target/*-exec.jar
COPY ${JAR_FILE} application.jar
RUN java -Djarmode=layertools -jar application.jar extract

FROM openjdk:8-jre-slim
WORKDIR application
COPY --from=builder application/dependencies/ ./
COPY --from=builder application/spring-boot-loader/ ./
COPY --from=builder application/snapshot-dependencies/ ./
COPY --from=builder application/application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]

The problem is that when I run this in my docker-compose with a Spring profile TST, that it does not find application-tst.properties.  I can see from the logs that Spring profile TST is active on startup, yet it only loads the properties from application.properties.

As a sanity check I copied the properties from application-tst.properties over to application.properties and rebuilt my image, which then worked fine (it connects to the database container etc).

I extracted the contents of my executable jar (which is the jar from line 3 in the Dockerfile) and can confirm that application-tst.properties is present there. Anyone know what the issue is?

Body:
I found the answer and it's a really dumb one...  The Spring profile is case sensitive, so

SPRING_PROFILES_ACTIVE=TST

should become

SPRING_PROFILES_ACTIVE=tst


问:
How to put a black border around certain dots on a ggplot geom_point plot
I am trying to make a geom plot using ggplot for some pathways of interest. I would like to put a black border around certain dots that are significant. -log10 > 1.2, so they are easier to identify. Is there anyway to do this in the package so I do not have to do in an illustrator package after I have produced the image? Thank you kindly for advice.

Image of current dot image:

Image of raw data:

```<code>cols <- c("blue",
          "white",
          "red")

li <- c(-2, 2)

D1 <- ggplot(Practice, aes(Practice$case, Practice$pathway,
      colour = Enrichment_score, size = Practice$ln)) +
  geom_point(alpha = 0.8) +
  scale_colour_gradientn(colours = cols) +
  theme(legend.position="bottom") +
  scale_size(breaks = c(0, 1.2, 1.4), range =  c(0.06,12)) +
  guides(size=guide_legend(title = "-log10(q value)"),
         scale_colour_gradient()) +
  labs(colour = "Enrichment Score") +
  theme_bw()

D1 + ggtitle("") +
  xlab("") + ylab("") +
  scale_x_discrete(limits=c("Responder vs Non-responder",
                            "Non-responder vs Control",
                            "Responder vs Control",
                            "Case vs Control"))
</code>```

答:
Another way, which may be simpler, is to use shape 21 with geom_point:

library(ggplot2)

ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_point(shape = 21,  stroke = 1, aes(colour = disp >= 250, fill = hp)) +
  scale_colour_manual(values = c(`TRUE` = "black", `FALSE` = rgb(0,0,0,0)))

```

The manual colour scale makes the edge of shape 21 either black or transparent. Note the backticks for TRUE or FALSE.

Body:
I am trying to make a geom plot using ggplot for some pathways of interest. I would like to put a black border around certain dots that are significant. -log10 > 1.2, so they are easier to identify. Is there anyway to do this in the package so I do not have to do in an illustrator package after I have produced the image? Thank you kindly for advice.

Image of current dot image:

Image of raw data:

cols <- c("blue",
          "white",
          "red")

li <- c(-2, 2)

D1 <- ggplot(Practice, aes(Practice$case, Practice$pathway,
      colour = Enrichment_score, size = Practice$ln)) +
  geom_point(alpha = 0.8) +
  scale_colour_gradientn(colours = cols) +
  theme(legend.position="bottom") +
  scale_size(breaks = c(0, 1.2, 1.4), range =  c(0.06,12)) +
  guides(size=guide_legend(title = "-log10(q value)"),
         scale_colour_gradient()) +
  labs(colour = "Enrichment Score") +
  theme_bw()

D1 + ggtitle("") +
  xlab("") + ylab("") +
  scale_x_discrete(limits=c("Responder vs Non-responder",
                            "Non-responder vs Control",
                            "Responder vs Control",
                            "Case vs Control"))

Body:
Another way, which may be simpler, is to use shape 21 with geom_point:

library(ggplot2)

ggplot(mtcars, aes(factor(cyl), mpg)) +
  geom_point(shape = 21,  stroke = 1, aes(colour = disp >= 250, fill = hp)) +
  scale_colour_manual(values = c(`TRUE` = "black", `FALSE` = rgb(0,0,0,0)))

The manual colour scale makes the edge of shape 21 either black or transparent. Note the backticks for TRUE or FALSE.


问:
checking the registration number entered by user
I was trying to use a custom dll for checking the registration number entered by user, but I run every time into “magic” behavior. In the tutorial examples http://wix.tramontana.co.hu/tutorial/events-and-actions/whats-not-in-the-book the custom action is running after ‘CostFinalize’, which normally should be before file copying procedure, but it turns out that the action runs before the very first dialog box with License Agreement appears. I have tried to solve the problem by assigning an action on the event of clicking the “next” button in registration Dialog

```<code><Publish Dialog="MySerialCheckDlg" Control="Next" Event="DoAction"      Value="CheckingPID">1</Publish>
<Publish Dialog="MySerialCheckDlg" Control="Next" Event="SpawnDialog" Value="InvalidPidDlg">PIDACCEPTED = "0"</Publish>
...
<CustomAction Id="CheckingPID" BinaryKey="CheckPID" DllEntry="CheckPID" />

<Binary Id="CheckPID" SourceFile="serialcheck.dll" />
</code>```

In dll, using MsiGetProperty (hInstall, "PIDKEY", Pid, &PidLen); does not get the PIDKEY value from msi specified in MySerialCheckDlg UI

```<code><Control Id="CDKeyEdit" Type="Edit" X="45" Y="159" Width="220" Height="16" Property="PIDKEY" Text="[PIDTemplate]" />
</code>```

And in the msi the PIDACCEPTED property is not been checked in the line

```<code><Publish Dialog="MySerialCheckDlg" Control="Next" Event="SpawnDialog" Value="InvalidPidDlg">PIDACCEPTED = "0"</Publish>
</code>```

Thus, the InvalidPidDlg does not appear, and the installation process continues further.

Can you please specify  the order of WiX Action Sequence, or maybe specify any other approach which can be used in this situation.

答:
There are two sequences: InstallExecuteSequence and InstallUISequence. If MSI runs with full UI, it executes actions from InstallUISequence; in case where no UI is shown, these actions are skipped. Actions from InstallExecuteSequence are executed during the installation process, with or without UI.

First of all, is your PIDKEY property tied to an edit control? You should something similar in the dialog where you ask users to type in PIDKEY:

```<code><Control Id="PidKeyEdit" Type="Edit" X="45" Y="105" Width="220" Height="18" Property="PIDKEY" Text="{80}" />
</code>```

Type could be either Edit or MaskedEdit. Publish elements should be associated with Next button control on the dialog:

```<code><Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17"
         Default="yes" Text="Next">
    <Publish Event="DoAction" Value="CheckingPID">1</Publish>
    <Publish Event="SpawnDialog" Value="InvalidPidDlg">PIDACCEPTED = "0"</Publish>
</Control>
</code>```

Run your installation with verbose logging to see how actions are executed, and how property values change:

```<code>msiexec /i your-product.msi /lv* your-product.log
</code>```

Body:
I was trying to use a custom dll for checking the registration number entered by user, but I run every time into “magic” behavior. In the tutorial examples http://wix.tramontana.co.hu/tutorial/events-and-actions/whats-not-in-the-book the custom action is running after ‘CostFinalize’, which normally should be before file copying procedure, but it turns out that the action runs before the very first dialog box with License Agreement appears. I have tried to solve the problem by assigning an action on the event of clicking the “next” button in registration Dialog

<Publish Dialog="MySerialCheckDlg" Control="Next" Event="DoAction"      Value="CheckingPID">1</Publish>
<Publish Dialog="MySerialCheckDlg" Control="Next" Event="SpawnDialog" Value="InvalidPidDlg">PIDACCEPTED = "0"</Publish>
...
<CustomAction Id="CheckingPID" BinaryKey="CheckPID" DllEntry="CheckPID" />

<Binary Id="CheckPID" SourceFile="serialcheck.dll" />

In dll, using MsiGetProperty (hInstall, "PIDKEY", Pid, &PidLen); does not get the PIDKEY value from msi specified in MySerialCheckDlg UI

<Control Id="CDKeyEdit" Type="Edit" X="45" Y="159" Width="220" Height="16" Property="PIDKEY" Text="[PIDTemplate]" />

And in the msi the PIDACCEPTED property is not been checked in the line

<Publish Dialog="MySerialCheckDlg" Control="Next" Event="SpawnDialog" Value="InvalidPidDlg">PIDACCEPTED = "0"</Publish>

Thus, the InvalidPidDlg does not appear, and the installation process continues further.

Can you please specify  the order of WiX Action Sequence, or maybe specify any other approach which can be used in this situation.

Body:
There are two sequences: InstallExecuteSequence and InstallUISequence. If MSI runs with full UI, it executes actions from InstallUISequence; in case where no UI is shown, these actions are skipped. Actions from InstallExecuteSequence are executed during the installation process, with or without UI.

First of all, is your PIDKEY property tied to an edit control? You should something similar in the dialog where you ask users to type in PIDKEY:

<Control Id="PidKeyEdit" Type="Edit" X="45" Y="105" Width="220" Height="18" Property="PIDKEY" Text="{80}" />

Type could be either Edit or MaskedEdit. Publish elements should be associated with Next button control on the dialog:

<Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17"
         Default="yes" Text="Next">
    <Publish Event="DoAction" Value="CheckingPID">1</Publish>
    <Publish Event="SpawnDialog" Value="InvalidPidDlg">PIDACCEPTED = "0"</Publish>
</Control>

Run your installation with verbose logging to see how actions are executed, and how property values change:

msiexec /i your-product.msi /lv* your-product.log


问:
Can I implement custom token generation (fully customized) API Token in WSO2?
I want to implement a custom code for token generation or you can think of removing OAuth2 from the WSO2 implementation and incorporating my specific APIs for token management. Is this possible? If yes, then please guide me how to achieve the same.</p>

答:
When you send an API request to the backend, you pass a token in the Authorization header of the request.  The API Gateway uses this token to authorize access, and then drops it from the outgoing message.  If you wish to use a different (or a custom generated) authorization token than the application generated access token, you can use it as a token exchange mechanism in mediation logic of the API. In this tutorial, we explain how to pass a custom authorization token that is different to the authorization token generated for the application.

Add the following sequence content in to a file and save it as XML file.

Log in to the API Publisher, create a new REST API

Navigate to the Runtime Configurations tab, enable the Message Mediation in Request flow. Engage the In sequence that you created earlier and click Save .

If the API is not in PUBLISHED state, go to Lifecycle tab, click REDPLOY to re-publish the API.

Go Developer Portal, subscribe and obtain a token to invoke the published API.

Install any REST client in your machine. We use cURL here.

Go to the command line, and invoke the API using the following cURL command.
In this command, you pass the token that the backend expects, i.e., 1234, in the Custom header with the authorization token that the system generates in the Authorization header.

curl -H "Authorization: Bearer " -H "Custom: Bearer 1234"

NOTE
 is the token that you got in step 20.
 appears on the API's Overview page in the API Developer Portal. Copy the HTTP endpoint. If you select the HTTPs endpoint, be sure to run the cURL command with the -k option.

Note the response that you get in the command line. According to the sample backend used in this tutorial, you get the response as "Request Received."

FOR MORE EXPLANATION, PLEASE VISIT THIS LINK

[LINK] : https://medium.com/@PrakhashS/passing-access-token-to-oauth2-protected-backends-wso2-api-manager-7d0671a0afca


问:
Port Error - Visual Studio 2022: Azure Function - Port 7071 is unavailable
I am getting below error while debugging two Azure function locally in visual studio 2022</p>
```<code>Port 7071 is unavailable. Close the process using that port, or specify another port using --port [-p].
</code>```

答:
For Visual Studio 2022, the fix is slightly different.

Open project properties and then go to Debug -> Open debug launch profiles UI.

Input  the following line with the port you want to use:

```<code>host start --port 11000
</code>```

The above fix works for .NET 6 Azure functions that runs as Project instead of isolated process

Body:
I am getting below error while debugging two Azure function locally in visual studio 2022

Port 7071 is unavailable. Close the process using that port, or specify another port using --port [-p].

Body:
For Visual Studio 2022, the fix is slightly different.

Open project properties and then go to Debug -> Open debug launch profiles UI.

Input  the following line with the port you want to use:

host start --port 11000

The above fix works for .NET 6 Azure functions that runs as Project instead of isolated process


问:
Pub sub with REST API - the request is missing a valid API Key
I am using the following code to do a test publish to pubsub

```<code>var data = {
  file: 'ciao',
  content_type: 'image/png'
};

needle
  .post('https://pubsub.googleapis.com/v1/projects/topic:publish', data, {
      multipart: true
    },
    function(err, resp) {
      if (err)
        console.log('Error: ' + err.message);
      else
        console.log('OK.' + JSON.stringify(resp.body));
    });
</code>```

But I get the error

```<code>{"error":{"code":403,"message":"The request is missing a valid API key.","status":"PERMISSION_DENIED"}}
</code>```

Do I need a service account authorized to PubSub? Any hint on how to solve this issue?

答:
You will need to verify the credentials you are using and the account permissions that those credentials have.

One of the popular approach is to have a service-account.json file with the credential information and use it as an enviroment variable GOOGLE_APPLICATION_CREDENTIALS. You can get that file when creating a credential account for your pub/sub application. Examples on how to create that you can find it on this link under Setting up authentication for server to server production applications..

Now you also need to verify the permissions and roles you credential account have. For cloud pub/sub there are lot of roles, like roles/editor or roles/pubsub.editor for the scope of your test run. You can even use a sample called testing_permissions from the official documentation to test your access. For a full lists of permissions and roles please see this site.

For more details you can check the access and authentication page

Body:
I am using the following code to do a test publish to pubsub

var data = {
  file: 'ciao',
  content_type: 'image/png'
};

needle
  .post('https://pubsub.googleapis.com/v1/projects/topic:publish', data, {
      multipart: true
    },
    function(err, resp) {
      if (err)
        console.log('Error: ' + err.message);
      else
        console.log('OK.' + JSON.stringify(resp.body));
    });

But I get the error

{"error":{"code":403,"message":"The request is missing a valid API key.","status":"PERMISSION_DENIED"}}

Do I need a service account authorized to PubSub? Any hint on how to solve this issue?


问:
How do I disable an input with Umbrella JS?
The UmbrellaJS docs for attr mention that (similar to jQuery) one should know the difference between attr and prop. I've found some discussion on using prop or attr for disabled in jQuery but all I know is Umbrella doesn't have prop and changing disabled doesn't seem to work in Umbrella:

u('#my-input').attr('disabled', true);

u('#my-input').attr('disabled', false);

(tagging jQuery because it's related and someone who knows jQuery well may be able answer this using their intuition)

答:
I believe you cannot remove an attribute of an item.

If you wish to disable all elements you can do this

```<code>u('.permissionItem').each( function(e){e.disabled = false;});
</code>```

Or if it is just one item, you can do

```<code>u('.permissionItem').first().disabled = false;
</code>```

.first() and the foreach loop both give the node, instead of the umbrella element.

Body:
I believe you cannot remove an attribute of an item.

If you wish to disable all elements you can do this

u('.permissionItem').each( function(e){e.disabled = false;});

Or if it is just one item, you can do

u('.permissionItem').first().disabled = false;

.first() and the foreach loop both give the node, instead of the umbrella element.


问:
How to determine a dependency graph solution is correct
I created a class that takes a directed graph, a vertex in that graph, and outputs an acceptable sequence of vertices to lead to that vertex.

e.g.

A->B

A->C

B->D

C->D

The two possible sequences for vertex D are:

A->B->C->D

A->C->B->D

Now, I need to design a test to determine if a solution my program gives is correct.

Any ideas?

答:
Your problem is quite common. There are essentially two similar and easy ways to deal with it:

put the sequences of nodes in a set and check the set size and whether it contains all the sequences

sort the sequences according to some known algorithm (e.g. by comparing one node after another). Now the order is always the same.

In Java this would mean:

implement equals and hashCode for the sequence of nodes (if this is something like List<Node>, implement equals and hashCode for Node instead) and put them in HashSet. Then simply check if the set has correct size and contains both paths.

make the sequence of nodes Comparable and sort them. Then the order is always known and fixed. In your case simply compare corresponding nodes one after another.


问:
Bitmaps Not Being Saved to Internal Storage (Android)

Problem

I am creating an Android app within Android Studio using Java. It needs a function that takes a bitmap image and saves it to a folder structure in internal memory. The images I'm working with are PNGs. My current implementation is based on the answer found here (Saving and Reading Bitmaps/Images from Internal memory in Android). I am very lost as to why not all of the log statements are being executed and no files are being created:

```<code>    private String saveToInternalStorage( Bitmap bitmapImage, String dataType, int zoom, int x, int y )
    {
        Log.w(TAG, "Function Started.");
        String imageDir = String.format( "%s/%d/%d", dataType, zoom, x );
        String imageName = String.format( "%d.png", y );

        ContextWrapper contextWrapper = new ContextWrapper( getContext() );
        Log.w(TAG, "Passed Context Wrapper.");

        // path to /data/data/app_name/app_data/<dataType>/<zoom>/<x>
        // - - - NO LOGS SHOWN PAST THIS POINT - - -
        File directory = contextWrapper.getDir( imageDir, Context.MODE_PRIVATE );
        Log.w(TAG, "Passed Directory Creation.");

        // Create image at imageDir (<y>.png)
        File imageFile = new File( directory, imageName );
        Log.w(TAG, "Passed File Creation.");

        FileOutputStream outputStream = null;
        Log.e(TAG, "Begining to Output to File.");
        try
        {
            outputStream = new FileOutputStream( imageFile );
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress( Bitmap.CompressFormat.PNG, 100, outputStream );
        }
        catch( Exception e )
        {
            Log.e(TAG, "Error Adding Image to Internal Storage.");
            e.printStackTrace();
        }
        finally
        {
            try
            {
                outputStream.flush();
                outputStream.close();
            }
            catch( Exception e )
            {
                Log.e(TAG, "Error Closing Output Stream.");
                e.printStackTrace();
            }
        }

        return directory.getAbsolutePath();
    }
</code>```

The following two lines are the only relevant output shown in Logcat. I am not shown any errors and no other logs from the above function are shown.

```<code>2022-02-08 02:52:56.433 18914-18990/com.example.biomapper W/ContentValues: Function Started.
2022-02-08 02:52:56.434 18914-18990/com.example.biomapper W/ContentValues: Passed Context Wrapper.
</code>```

What I've Tried

This is my third attempt at creating this function, and the closest I've gotten to making it work. I have looked at many other questions on Stack Overflow regarding this topic. I added many log statements to see where/what might be going wrong. I've tried using the file.exists() command to  test if the file(s) were ever created. I am sure that the parameters given to this function when testing it are correct.

Any advice on saving images to internal storage, checking if the files exist, or improving my code in any way are greatly appreciated.

答:
In This Way I Saved the image in android folder
Create a directory "xml" in res folder and paste

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.project/files/Pictures" />
</paths>
</code>```

In Manifest file add this line under application

```<code><provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.xyz.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path" />
</provider>
</code>```

initialize this in your respective activity

```<code>File photoFile = null;
</code>```

Edit this function according to your requirements !!

```<code>try {

                    photoFile = createImageFile();
                    displayMessage(getBaseContext(), photoFile.getAbsolutePath());

                    // Continue only if the File was successfully created
                    if (photoFile != null) {
                        Uri photoURI = FileProvider.getUriForFile(this,"com.xyz.fileprovider",photoFile);
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST);
                    }
                } catch (Exception ex) {
                    // Error occurred while creating the File
                    displayMessage(getBaseContext(), ex.getMessage().toString());
                }
</code>```

Body:
Problem

I am creating an Android app within Android Studio using Java. It needs a function that takes a bitmap image and saves it to a folder structure in internal memory. The images I'm working with are PNGs. My current implementation is based on the answer found here (Saving and Reading Bitmaps/Images from Internal memory in Android). I am very lost as to why not all of the log statements are being executed and no files are being created:

    private String saveToInternalStorage( Bitmap bitmapImage, String dataType, int zoom, int x, int y )
    {
        Log.w(TAG, "Function Started.");
        String imageDir = String.format( "%s/%d/%d", dataType, zoom, x );
        String imageName = String.format( "%d.png", y );

        ContextWrapper contextWrapper = new ContextWrapper( getContext() );
        Log.w(TAG, "Passed Context Wrapper.");

        // path to /data/data/app_name/app_data/<dataType>/<zoom>/<x>
        // - - - NO LOGS SHOWN PAST THIS POINT - - -
        File directory = contextWrapper.getDir( imageDir, Context.MODE_PRIVATE );
        Log.w(TAG, "Passed Directory Creation.");

        // Create image at imageDir (<y>.png)
        File imageFile = new File( directory, imageName );
        Log.w(TAG, "Passed File Creation.");

        FileOutputStream outputStream = null;
        Log.e(TAG, "Begining to Output to File.");
        try
        {
            outputStream = new FileOutputStream( imageFile );
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress( Bitmap.CompressFormat.PNG, 100, outputStream );
        }
        catch( Exception e )
        {
            Log.e(TAG, "Error Adding Image to Internal Storage.");
            e.printStackTrace();
        }
        finally
        {
            try
            {
                outputStream.flush();
                outputStream.close();
            }
            catch( Exception e )
            {
                Log.e(TAG, "Error Closing Output Stream.");
                e.printStackTrace();
            }
        }

        return directory.getAbsolutePath();
    }

The following two lines are the only relevant output shown in Logcat. I am not shown any errors and no other logs from the above function are shown.

2022-02-08 02:52:56.433 18914-18990/com.example.biomapper W/ContentValues: Function Started.
2022-02-08 02:52:56.434 18914-18990/com.example.biomapper W/ContentValues: Passed Context Wrapper.

What I've Tried

This is my third attempt at creating this function, and the closest I've gotten to making it work. I have looked at many other questions on Stack Overflow regarding this topic. I added many log statements to see where/what might be going wrong. I've tried using the file.exists() command to  test if the file(s) were ever created. I am sure that the parameters given to this function when testing it are correct.

Any advice on saving images to internal storage, checking if the files exist, or improving my code in any way are greatly appreciated.

Body:
In This Way I Saved the image in android folder
Create a directory "xml" in res folder and paste

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.project/files/Pictures" />
</paths>

In Manifest file add this line under application

<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.xyz.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path" />
</provider>

initialize this in your respective activity

File photoFile = null;

Edit this function according to your requirements !!

try {

                    photoFile = createImageFile();
                    displayMessage(getBaseContext(), photoFile.getAbsolutePath());

                    // Continue only if the File was successfully created
                    if (photoFile != null) {
                        Uri photoURI = FileProvider.getUriForFile(this,"com.xyz.fileprovider",photoFile);
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST);
                    }
                } catch (Exception ex) {
                    // Error occurred while creating the File
                    displayMessage(getBaseContext(), ex.getMessage().toString());
                }


答:
I don't think you can't overrule the hardware button (neither you should), a better approach would be to check if the device is silent and show an alert to the user in that case, BUT, as the below library says:

There is no native iOS API to detect if the mute switch is
enabled/disabled on a device.

The general principle to check if the device is muted is to play a
short sound and detect the length it took to play. From this length we
can determine if it was muted or not.

The library that may help you.

Title: Play sounds with AVQueuePlayer even if iPhone is muted

Body:
I'm using AVQueuePlayer to play sounds (a little App for kids to listen illustrated books), but if iPhone is muted the audio isn't audible.

There is a way to force audio even if iPhone is muted? I think to YouTube where audio is audible or Instagram when you have to pop up the volume to listen stories.

Thanks.


问:
How do send a OTP using Firebase in flutter
I have tried flutter_otp plugin but it does not support null safety how can I send a OTP with Firebase in flutter</p>

答:
If you don't know how to setup firebase follow this link otherwise follow next step

https://www.digitalocean.com/community/tutorials/flutter-firebase-setup

After Firebase SetUp you need to follow this step

https://firebase.flutter.dev/docs/auth/phone/


问:
How to fix "insecure content was loaded over HTTPS, but requested an insecure resource"
This URL: https://slowapi.com

I can't find the insecure content and the Chrome keeps complaining,

Any ideas?

答:
I had this error with an iframe to another website.
I changed the src from "https://website.com/folder" to "https://website.com/folder/index.php" and for some reason it works.</p>


问:
How to print the repo project and shortstat with git repo forall command?
With repo forall command, how to print both shortstat and REPO_PROJECT?

I tried below, it didn't work, it just prints the $REPO_PROJECT but not the shortstat.

```<code>repo forall -c 'echo $REPO_PROJECT' -c 'git diff --shortstat tagA tagB'
</code>```

I wanted it to print:

```<code>project/name
1 file changed, 2 insertions(+), 2 deletions(-)
</code>```

答:
repo forall -c 'git status | dos2unix'
works</p>

Body:
With repo forall command, how to print both shortstat and REPO_PROJECT?

I tried below, it didn't work, it just prints the $REPO_PROJECT but not the shortstat.

repo forall -c 'echo $REPO_PROJECT' -c 'git diff --shortstat tagA tagB'

I wanted it to print:

project/name
1 file changed, 2 insertions(+), 2 deletions(-)


问:
Is Interfacing both java.awt.Graphics2D and Html5 Canvas Context in GWT feasible?
I have a java library which heavily uses java.awt.Graphics2d.

I want to port my library to html5 canvas by using gwt.

So I'm planning to write an interface (or just a class), say common.Graphics2d,
an adapter class, say com.test.awt.Graphics2d, implements common.Graphics2d and uses java.awt.Graphics2d

and another adapter class, say com.test.gwt.Graphics2d, implements common.Graphics2d and uses com.google.gwt.canvas.dom.client.Context2d.

Then I will replace all java.awt.Graphics2d with common.Graphics2d.
So after that, my library will work on both gwt and java.

The problem here is to implement graphics2d methods, and configuration by canvas context 2d. Is it feasible to implement same functionality with canvas?

答:
I have done a similar thing. I have an interface which represents aview and two implementations of said interface. One for Android using its android.graphics classes and a second implementations in GWT using com.google.gwt.canvas.client.Canvas.

The GWT canvas stuff seems pretty full-featured to me. You can draw shapes, display text and images, move, rotate, scale...


问:
Changing Navigation Bar Color in Xcode
I am building a Swift app and I am trying to change the color of the navigation bar.
I'm trying to do it directly from Xcode without code on the main.storyboard.

I've tried changing several settings in the Xcode Attribute Inspector but nothing has worked. I've also searched StackOverFlow but all the answers I find are are changing it programatically.

Does anyone know how to change the color of it directly from the Attribute Inspector?

Thanks.

答:
Navigation Bar:

```<code>navigationController?.navigationBar.barTintColor = UIColor.green
</code>```

Replace greenColor with whatever UIColor you want

 Navigation Bar Text:

```<code>navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange]
</code>```

Replace orangeColor with whatever color you like.

 Tab Bar:

```<code>tabBarController?.tabBar.barTintColor = UIColor.brown
</code>```

 Tab Bar Text:

```<code>tabBarController?.tabBar.tintColor = UIColor.yellow
</code>```

On the last two, replace brownColor and yellowColor with the color of your choice.

swift navigation bar title color:

Place this in your didFinishLaunchingWithOptions method in the AppDelegate.

```<code>let attrs = [
  NSAttributedString.Key.foregroundColor: UIColor.white
]

UINavigationBar.appearance().titleTextAttributes = attrs
</code>```

Title: Changing Navigation Bar Color in Xcode

Body:
 Navigation Bar:

navigationController?.navigationBar.barTintColor = UIColor.green

Replace greenColor with whatever UIColor you want

 Navigation Bar Text:

navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange]

Replace orangeColor with whatever color you like.

 Tab Bar:

tabBarController?.tabBar.barTintColor = UIColor.brown

 Tab Bar Text:

tabBarController?.tabBar.tintColor = UIColor.yellow

On the last two, replace brownColor and yellowColor with the color of your choice.

swift navigation bar title color:

Place this in your didFinishLaunchingWithOptions method in the AppDelegate.

let attrs = [
  NSAttributedString.Key.foregroundColor: UIColor.white
]

UINavigationBar.appearance().titleTextAttributes = attrs


问:
I have a mistake for the installation of Matplotlib
When I try to install matplotlib with the command pip install matplotlib
I have this erreur :

```<code>WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)'))': /simple/matplotlib/
Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)'))) - skipping
ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib
</code>```

I use python 3.9.5 64-bit, pip 21.1.2 and I use a Macbook M1 (I don't know if it's important). I have to use matplotlib for my science class and I don't understand this mistake.
thank you in advance for your answers !

答:
You can try:

pip install --trusted-host=pypi.org --trusted-host=files.pythonhosted.org --user matplotlib

That problem is explained here.

Body:
When I try to install matplotlib with the command pip install matplotlib
I have this erreur :

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)'))': /simple/matplotlib/
Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)'))) - skipping
ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib

I use python 3.9.5 64-bit, pip 21.1.2 and I use a Macbook M1 (I don't know if it's important). I have to use matplotlib for my science class and I don't understand this mistake.
thank you in advance for your answers !


问:
Elegant way to correctly index a Dataframe after Subsetting
I have the following dummy dataframe with two columns:

```<code>set.seed(666)
df = data.frame(group = rep(c(-1,1), times = 5, each = 1),
                values = runif(10))

   group     values
1     -1 0.77436849
2      1 0.19722419
3     -1 0.97801384
4      1 0.20132735
5     -1 0.36124443
6      1 0.74261194
7     -1 0.97872844
8      1 0.49811371
9     -1 0.01331584
10     1 0.25994613
</code>```

I want to find the row index of the maximum value from group "1" in the original dataframe. Applying which.max() after subsetting the dataframe will return the wrong row:

```<code>which.max(df[df[,1]==1,2]) #returns '3'
</code>```

As a workaround I did the following:

```<code>sdf = df[df[,1] == 1,] # subset of dataframe that keeps row names
rownames(sdf[which.max(sdf[,2]),]) # returns '6'
</code>```

Which does return the correct row index from the original dataframe. However I feel there must be an easier, more elegant solution but can't think of anything else myself. Any ideas?

I feel really stupid for asking this question but it seems I'm overlooking something very simple.

Body:
I have the following dummy dataframe with two columns:

set.seed(666)
df = data.frame(group = rep(c(-1,1), times = 5, each = 1),
                values = runif(10))

   group     values
1     -1 0.77436849
2      1 0.19722419
3     -1 0.97801384
4      1 0.20132735
5     -1 0.36124443
6      1 0.74261194
7     -1 0.97872844
8      1 0.49811371
9     -1 0.01331584
10     1 0.25994613

I want to find the row index of the maximum value from group "1" in the original dataframe. Applying which.max() after subsetting the dataframe will return the wrong row:

which.max(df[df[,1]==1,2]) #returns '3'

As a workaround I did the following:

sdf = df[df[,1] == 1,] # subset of dataframe that keeps row names
rownames(sdf[which.max(sdf[,2]),]) # returns '6'

Which does return the correct row index from the original dataframe. However I feel there must be an easier, more elegant solution but can't think of anything else myself. Any ideas?

I feel really stupid for asking this question but it seems I'm overlooking something very simple.

Body:
Here I use a base R approach, but it's also not very elegant.

which(df[, 2] == max(df[which(df[, 1] == 1), 2]))
[1] 6

Input

df
   group     values
1     -1 0.77436849
2      1 0.19722419
3     -1 0.97801384
4      1 0.20132735
5     -1 0.36124443
6      1 0.74261194
7     -1 0.97872844
8      1 0.49811371
9     -1 0.01331584
10     1 0.25994613


问:
Reading unsigned int into uint64_t from binary file
I am trying to read a binary file using fstream. I know the types of everything in this file but there are two different versions, an old and a new version. The old version contains variables of type 'unsigned int' deemed to have insufficient range, and are replaced by 'uint64_t' in the new version. I'd like one file reader capable of reading both formats(for backwards compatibility). The read result should always be a uint64_t.

I am sure this is a common problem. I've tried simply reading 4 bytes from an ifstream into the memory of the uint64_t, comparable to the snippet below(without checking for any problems):

```<code>std::uint64_t buff=0;
std::ifstream is(filePath, std::ios_base::binary)
std::is.read(&buff,sizeof(unsigned int));
</code>```

This gives me the correct value but I realize this might be subject to endianness. Is there a common method to solve this problem?

答:
You need to read it into a variable of the correct type and then you can assign it to your uint64_t variable.

static_assert(std::endian::native == std::endian::big ||
              std::endian::native == std::endian::little);

constexpr auto file_endianess = std::endian::big; // or little

std::uint64_t buff = 0;
std::ifstream is(filePath, std::ios_base::binary);
if (is) {
    std::uint32_t temp;
    if (is.read(reinterpret_cast<char*>(&temp), sizeof temp)) {

        // ... deal with endianess here ...
        // (example from C++23 below)
        #ifdef __cpp_lib_byteswap
        if constexpr(std::endian::native != file_endianess) {
            temp = std::byteswap(temp);
        }
        #else
        // an alternative endianess solution goes here
        #endif

        buff = temp;
    }
}
```

Body:
I am trying to read a binary file using fstream. I know the types of everything in this file but there are two different versions, an old and a new version. The old version contains variables of type 'unsigned int' deemed to have insufficient range, and are replaced by 'uint64_t' in the new version. I'd like one file reader capable of reading both formats(for backwards compatibility). The read result should always be a uint64_t.

I am sure this is a common problem. I've tried simply reading 4 bytes from an ifstream into the memory of the uint64_t, comparable to the snippet below(without checking for any problems):

std::uint64_t buff=0;
std::ifstream is(filePath, std::ios_base::binary)
std::is.read(&buff,sizeof(unsigned int));

This gives me the correct value but I realize this might be subject to endianness. Is there a common method to solve this problem?


问:
AttributeError scikit learn pipeline based class
I am trying to write a sklearn based feature extraction pipeline. My pipeline code idea could be splitted in few parts

A parent class where all data preprocessing (if required) could happen

```<code>from sklearn.base import BaseEstimator, TransformerMixin

class FeatureExtractor(BaseEstimator, TransformerMixin):
    """This is the parent class for all feature extractors."""
    def __init__(self, raw_data = {}):
        self.raw_data = raw_data

    def fit(self, X, y=None):
        return self
</code>```

A decorator which helps one define the execution of feature extraction, for intelligently handling the case where one feature is dependent on another feature.

```<code># A decorator to assign order of feature extraction within fearure extractor classes
def feature_order(order):
   def order_assignment(to_func):
       to_func.order = order
       return to_func
   return order_assignment
</code>```

Finally one of the child class where all feature extraction is happening:

```<code>class ChilldFeatureExtractor1(FeatureExtractor):
   """This is the one of the child feature extractor class."""

   def __init__(self, raw_data = {}):
       super().__init__(raw_data)
       self.raw_data = raw_data

   @feature_order(1)
   def foo_plus_one(self):
       return self.raw_data['foo'] + 1

   # This feature extractor depends on value populated in previous feature extractor
   @feature_order(2)
   def foo_plus_one_plus_one(self):
       return self.raw_data['foo_plus_one'] + 1

   def transform(self):
       functions = sorted(
           #get a list of extractor functions with attribute order
           [
           getattr(self, field) for field in dir(self)
           if hasattr(getattr(self, field), "order")
           ],
           #sort the feature extractor functions by their order
           key = (lambda field: field.order)
           )

       for func in functions:
           feature_name = func.__name__
           feature_value = func()
           self.raw_data[feature_name] = feature_value

       return self.raw_data
</code>```

Testing this code a small input:

```<code>if __name__ == '__main__':
    raw_data = {'foo': 1, 'bar': 2}
    fe = ChilldFeatureExtractor1(raw_data)
    print(fe.transform())
</code>```

Gives error:

```<code>Traceback (most recent call last):
  File "/Users/temporaryadmin/deleteme.py", line 55, in <module>
    print(fe.transform())
  File "/Users/temporaryadmin/deleteme.py", line 37, in transform
    [
  File "/Users/temporaryadmin/deleteme.py", line 39, in <listcomp>
    if hasattr(getattr(self, field), "order")
  File "/Users/temporaryadmin/opt/miniconda3/envs/voutopia/lib/python3.8/site-packages/sklearn/base.py", line 450, in _repr_html_
    raise AttributeError("_repr_html_ is only defined when the "
AttributeError: _repr_html_ is only defined when the 'display' configuration option is set to 'diagram'
</code>```

However when I don't inherit sklearn classes in base class ie. class FeatureExtractor(): then I get proper output:

```<code>{'foo': 1, 'bar': 2, 'foo_plus_one': 2, 'foo_plus_one_plus_one': 3}
</code>```

Any pointer on this?

答:
Try this before running your code:

```<code>from sklearn import set_config
set_config(display='diagram')
</code>```

That happens because the BaseEstimator class has _repr_hrml_ property that depends on display to be 'diagram' (source). I assume that the property gets evaluated at some point and throws the error.

Body:
I am trying to write a sklearn based feature extraction pipeline. My pipeline code idea could be splitted in few parts

A parent class where all data preprocessing (if required) could happen

from sklearn.base import BaseEstimator, TransformerMixin

class FeatureExtractor(BaseEstimator, TransformerMixin):
    """This is the parent class for all feature extractors."""
    def __init__(self, raw_data = {}):
        self.raw_data = raw_data

    def fit(self, X, y=None):
        return self

A decorator which helps one define the execution of feature extraction, for intelligently handling the case where one feature is dependent on another feature.

# A decorator to assign order of feature extraction within fearure extractor classes
def feature_order(order):
   def order_assignment(to_func):
       to_func.order = order
       return to_func
   return order_assignment

Finally one of the child class where all feature extraction is happening:

class ChilldFeatureExtractor1(FeatureExtractor):
   """This is the one of the child feature extractor class."""

   def __init__(self, raw_data = {}):
       super().__init__(raw_data)
       self.raw_data = raw_data

   @feature_order(1)
   def foo_plus_one(self):
       return self.raw_data['foo'] + 1

   # This feature extractor depends on value populated in previous feature extractor
   @feature_order(2)
   def foo_plus_one_plus_one(self):
       return self.raw_data['foo_plus_one'] + 1

   def transform(self):
       functions = sorted(
           #get a list of extractor functions with attribute order
           [
           getattr(self, field) for field in dir(self)
           if hasattr(getattr(self, field), "order")
           ],
           #sort the feature extractor functions by their order
           key = (lambda field: field.order)
           )

       for func in functions:
           feature_name = func.__name__
           feature_value = func()
           self.raw_data[feature_name] = feature_value

       return self.raw_data

Testing this code a small input:

if __name__ == '__main__':
    raw_data = {'foo': 1, 'bar': 2}
    fe = ChilldFeatureExtractor1(raw_data)
    print(fe.transform())

Gives error:

Traceback (most recent call last):
  File "/Users/temporaryadmin/deleteme.py", line 55, in <module>
    print(fe.transform())
  File "/Users/temporaryadmin/deleteme.py", line 37, in transform
    [
  File "/Users/temporaryadmin/deleteme.py", line 39, in <listcomp>
    if hasattr(getattr(self, field), "order")
  File "/Users/temporaryadmin/opt/miniconda3/envs/voutopia/lib/python3.8/site-packages/sklearn/base.py", line 450, in _repr_html_
    raise AttributeError("_repr_html_ is only defined when the "
AttributeError: _repr_html_ is only defined when the 'display' configuration option is set to 'diagram'

However when I don't inherit sklearn classes in base class ie. class FeatureExtractor(): then I get proper output:

{'foo': 1, 'bar': 2, 'foo_plus_one': 2, 'foo_plus_one_plus_one': 3}

Any pointer on this?

Body:
Try this before running your code:

from sklearn import set_config
set_config(display='diagram')

That happens because the BaseEstimator class has _repr_hrml_ property that depends on display to be 'diagram' (source). I assume that the property gets evaluated at some point and throws the error.


问:
MongoDB - Update array data in array
What is the best way to update the array element inside the array in MongoDB? For example, the data looks like this:

```<code>{
        "_id" : ObjectId("6201396b866ffbf1b84fb8f9"),
        "title" : "ironman",
        "comments" : [
                {
                        "text" : "nihao",
                        "replies" : [
                                {
                                        "text" : "hi"
                                },
                                {
                                        "text" : "bonjour"
                                },
                                {
                                        "text" : "push replies!!!"
                                }
                        ]
                },
                {
                        "text" : "what??",
                        "replies" : [
                                {
                                        "text" : "the"
                                },
                                {
                                        "text" : "hey"
                                }
                        ]
                },
                {
                        "text" : "push comments!!!"
                }
        ]
}
</code>```

I want to change

```<code>"comments.replies.text: 'hi'"
</code>```

to

```<code>"comments.replies.text: 'hello'"
</code>```

What would be the best way to write a query if you want to update the elements inside replies?

答:
You need $[<identifier>] filtered positional operator and arrayFilters to update nested document(s) in the array.

```<code>db.collection.update({
  title: "ironman"
},
{
  $set: {
    "comments.$[comment].replies.$[reply].text": "hello"
  }
},
{
  arrayFilters: [
    {
      "comment.replies": {
        $exists: true
      }
    },
    {
      "reply.text": "hi"
    }
  ]
})
</code>```

Sample Demo on Mongo Playground

Title: MongoDB - Update array data in array

Body:
What is the best way to update the array element inside the array in MongoDB? For example, the data looks like this:

{
        "_id" : ObjectId("6201396b866ffbf1b84fb8f9"),
        "title" : "ironman",
        "comments" : [
                {
                        "text" : "nihao",
                        "replies" : [
                                {
                                        "text" : "hi"
                                },
                                {
                                        "text" : "bonjour"
                                },
                                {
                                        "text" : "push replies!!!"
                                }
                        ]
                },
                {
                        "text" : "what??",
                        "replies" : [
                                {
                                        "text" : "the"
                                },
                                {
                                        "text" : "hey"
                                }
                        ]
                },
                {
                        "text" : "push comments!!!"
                }
        ]
}

I want to change

"comments.replies.text: 'hi'"

to

"comments.replies.text: 'hello'"

What would be the best way to write a query if you want to update the elements inside replies?

Body:
You need $[<identifier>] filtered positional operator and arrayFilters to update nested document(s) in the array.

db.collection.update({
  title: "ironman"
},
{
  $set: {
    "comments.$[comment].replies.$[reply].text": "hello"
  }
},
{
  arrayFilters: [
    {
      "comment.replies": {
        $exists: true
      }
    },
    {
      "reply.text": "hi"
    }
  ]
})

Sample Demo on Mongo Playground


问:
How to define a generic SwiftUI view that can accept sectioned fetch results for different entities
I need to define a generic SwiftUI view that can accept sectioned fetch results for different CoreData entities, but I'm not sure how to define the generic view.

In the example below, I have two sectioned fetch results defined for Patient and Doctor entities. I need to be able to pass them to the generic view.

```<code>@SectionedFetchRequest(
    sectionIdentifier: \.sectionTitle,
    sortDescriptors: Patient.nameSortDescriptors(), animation: .default)
private var patients: SectionedFetchResults<String, Patient>

@SectionedFetchRequest(
    sectionIdentifier: \.sectionTitle,
    sortDescriptors: Doctor.nameSortDescriptors(), animation: .default)
private var doctors: SectionedFetchResults<String, Doctor>

GenericView(items: patients)
GenericView(items: doctors)

struct GenericView: View {
    let items: ?????
}
</code>```

答:
One way is to supply not only the fetched results but also the view to use for each object in the results.

The below view is generic for the objects to display, Object, and the view to use, Content, for each Object. In this example I am displaying a list of all objects

```<code>struct GenericView<Object: NSManagedObject, Content: View>: View {
    let items: SectionedFetchResults<String, Object>
    let rowContent: (Object) -> Content

    init(items: SectionedFetchResults<String, Object>, rowContent: @escaping (Object) -> Content) {
        self.items = items
        self.rowContent = rowContent
    }

    var body: some View {
        List {
            ForEach(items) { section in
                Section(header: Text(section.id)) {
                    ForEach(section, id: \.objectID) { item in
                        rowContent(item)
                    }
                }
            }
        }
    }
}
</code>```

Then you call the view like this for eaxample

```<code>GenericView(items: patients, rowContent: { patient in
    Text(patient.name)
})
</code>```

Body:
I need to define a generic SwiftUI view that can accept sectioned fetch results for different CoreData entities, but I'm not sure how to define the generic view.

In the example below, I have two sectioned fetch results defined for Patient and Doctor entities. I need to be able to pass them to the generic view.

@SectionedFetchRequest(
    sectionIdentifier: \.sectionTitle,
    sortDescriptors: Patient.nameSortDescriptors(), animation: .default)
private var patients: SectionedFetchResults<String, Patient>

@SectionedFetchRequest(
    sectionIdentifier: \.sectionTitle,
    sortDescriptors: Doctor.nameSortDescriptors(), animation: .default)
private var doctors: SectionedFetchResults<String, Doctor>

GenericView(items: patients)
GenericView(items: doctors)

struct GenericView: View {
    let items: ?????
}

Body:
One way is to supply not only the fetched results but also the view to use for each object in the results.

The below view is generic for the objects to display, Object, and the view to use, Content, for each Object. In this example I am displaying a list of all objects

struct GenericView<Object: NSManagedObject, Content: View>: View {
    let items: SectionedFetchResults<String, Object>
    let rowContent: (Object) -> Content

    init(items: SectionedFetchResults<String, Object>, rowContent: @escaping (Object) -> Content) {
        self.items = items
        self.rowContent = rowContent
    }

    var body: some View {
        List {
            ForEach(items) { section in
                Section(header: Text(section.id)) {
                    ForEach(section, id: \.objectID) { item in
                        rowContent(item)
                    }
                }
            }
        }
    }
}

Then you call the view like this for eaxample

GenericView(items: patients, rowContent: { patient in
    Text(patient.name)
})


问:
How to schedule multiple time specific local notifications in flutter
I am developing water drinking reminder app with flutter.
I want to schedule a list of time specified local notifications that user can add to this list and delete from this list. like this

Any help would appreciate, Thanks.

答:
You can use flutter_local_notifications plugin, it can send scheduled, instant and also repeating notifications

```<code>await flutterLocalNotificationsPlugin.zonedSchedule(
0,
'scheduled title',
'scheduled body',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
const NotificationDetails(
    android: AndroidNotificationDetails(
        'your channel id', 'your channel name',
        channelDescription: 'your channel description')),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
    UILocalNotificationDateInterpretation.absoluteTime);
</code>```

This example will schedule a notification that appears after 5 seconds.

Body:
You can use flutter_local_notifications plugin, it can send scheduled, instant and also repeating notifications

await flutterLocalNotificationsPlugin.zonedSchedule(
0,
'scheduled title',
'scheduled body',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
const NotificationDetails(
    android: AndroidNotificationDetails(
        'your channel id', 'your channel name',
        channelDescription: 'your channel description')),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
    UILocalNotificationDateInterpretation.absoluteTime);

This example will schedule a notification that appears after 5 seconds.


问:
Design tips for a program to be run in 25 years
If creating an application (that does mostly data processing) that needs to be run now and maybe (maybe not) 10 or 25 years later, what design tips are out there for such applications?

The general rules apply: rely on open source software and proven platforms and failsafe data formats.

The language must be a high-level language for readability reasons (maybe the only option will be re-writing the application in 15 years by someone who has little knowledge of the original code).

I'd go for UNIX(Linux)+Python+YAML/JSON(/CSV/plaintext), any tips for this selection or an alternative toolset? Scheme/lisp has been around for ages and is really hard to screw up the language basics as well, given that everything would be self-contained.

EDIT: please don't forget tips about actual design and code, like 2038 year issue!

答: considering that you'll be providing a well documented source code, they could always optimize the code if any new technology comes up that's compatible with your current code. Else, they'l just have to port it themselves.</p>