问:
When Spring Boot starts up, it throws the "method names must be tokens" exception
When Spring Boot starts up, it throws the method names must be tokens exception

```<code>2016-08-11 16:53:54.499  INFO 14212 --- [0.1-8888-exec-1] o.apache.coyote.http11.Http11Processor   : Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.

java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
        at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:462) ~[tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:994) ~[tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_72]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_72]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at java.lang.Thread.run(Thread.java:745) [na:1.8.0_72]

2016-08-11 16:53:58.885  INFO 14212 --- [0.1-8888-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-08-11 16:53:58.888  INFO 14212 --- [0.1-8888-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-08-11 16:53:58.922  INFO 14212 --- [0.1-8888-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 30 ms
11111111-chinadfadf-xxxxxxxx@121.com
</code>```

Anyone knows why it throws this exception?

答: In my case it was when Tomcat created HTTPS request without SSL certificate installed on it. To fix it I changed schema in request to HTTP. Or you should create SSL certificate to use HTTPS.</p>

Body:
When Spring Boot starts up, it throws the method names must be tokens exception

2016-08-11 16:53:54.499  INFO 14212 --- [0.1-8888-exec-1] o.apache.coyote.http11.Http11Processor   : Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.

java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
        at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:462) ~[tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:994) ~[tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_72]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_72]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.4.jar!/:8.5.4]
        at java.lang.Thread.run(Thread.java:745) [na:1.8.0_72]

2016-08-11 16:53:58.885  INFO 14212 --- [0.1-8888-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-08-11 16:53:58.888  INFO 14212 --- [0.1-8888-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-08-11 16:53:58.922  INFO 14212 --- [0.1-8888-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 30 ms
11111111-chinadfadf-xxxxxxxx@121.com

Anyone knows why it throws this exception?


来源: stackexchange

问:
Typescript: Property doesn't exist on Generic Type
I'm trying to learn Typescript and I've been following some exercises I've found on the internet. But the feedback on incorrect solutions aren't that great. So I've got the following code but TS keeps complaining that property type is not defined on T:

```<code>interface User {
    type: 'user';
    name: string;
    age: number;
    occupation: string;
}

interface Admin {
    type: 'admin';
    name: string;
    age: number;
    role: string;
}

export type Person = User | Admin;

export const persons: Person[] = [
    { type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
    { type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
    { type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' },
    { type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' },
    { type: 'user', name: 'Wilson', age: 23, occupation: 'Ball' },
    { type: 'admin', name: 'Agent Smith', age: 23, role: 'Anti-virus engineer' }
];

export function filterPersons<T>(persons: T[], personType: string, criteria: T): T[] {
    return persons
        .filter((person) => person.type === personType)
        .filter((person) => {
            let criteriaKeys = Object.keys(criteria) as (keyof T)[];
            return criteriaKeys.every((fieldName) => {
                return person[fieldName] === criteria[fieldName];
            });
        });
}

export const usersOfAge23 = filterPersons<User>(persons, 'user', { age: 23 });
export const adminsOfAge23 = filterPersons<Admin>(persons, 'admin', { age: 23 });
</code>```

What am I doing wrong here? T should be a genertic type or in this case User or Admin that is passed right?

答:
Inferring types in a filter only works if you don't use an arrow (source). So you'd need something like:

```<code>export function filterPersons<T extends Person>(
    persons: Person[],
    personType: T['type'],
    criteria: Partial<T>
): T[] {
    const isPersonOf = (person: Person): person is T => person.type === personType;

    return persons
        .filter(isPersonOf)
        .filter((person) => {
            let criteriaKeys = Object.keys(criteria) as (keyof T)[];
            return criteriaKeys.every((fieldName) => {
                return person[fieldName] === criteria[fieldName];
            });
        });
}
</code>```

Note the type of usersOfAge23 (User[]) and adminsOfAge23 (Admin[]) when using this implementation.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to learn Typescript and I've been following some exercises I've found on the internet. But the feedback on incorrect solutions aren't that great. So I've got the following code but TS keeps complaining that property type is not defined on T:

interface User {
    type: 'user';
    name: string;
    age: number;
    occupation: string;
}

interface Admin {
    type: 'admin';
    name: string;
    age: number;
    role: string;
}

export type Person = User | Admin;

export const persons: Person[] = [
    { type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
    { type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
    { type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' },
    { type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' },
    { type: 'user', name: 'Wilson', age: 23, occupation: 'Ball' },
    { type: 'admin', name: 'Agent Smith', age: 23, role: 'Anti-virus engineer' }
];

export function filterPersons<T>(persons: T[], personType: string, criteria: T): T[] {
    return persons
        .filter((person) => person.type === personType)
        .filter((person) => {
            let criteriaKeys = Object.keys(criteria) as (keyof T)[];
            return criteriaKeys.every((fieldName) => {
                return person[fieldName] === criteria[fieldName];
            });
        });
}

export const usersOfAge23 = filterPersons<User>(persons, 'user', { age: 23 });
export const adminsOfAge23 = filterPersons<Admin>(persons, 'admin', { age: 23 });

What am I doing wrong here? T should be a genertic type or in this case User or Admin that is passed right?

Body:
Inferring types in a filter only works if you don't use an arrow (source). So you'd need something like:

export function filterPersons<T extends Person>(
    persons: Person[],
    personType: T['type'],
    criteria: Partial<T>
): T[] {
    const isPersonOf = (person: Person): person is T => person.type === personType;

    return persons
        .filter(isPersonOf)
        .filter((person) => {
            let criteriaKeys = Object.keys(criteria) as (keyof T)[];
            return criteriaKeys.every((fieldName) => {
                return person[fieldName] === criteria[fieldName];
            });
        });
}

Note the type of usersOfAge23 (User[]) and adminsOfAge23 (Admin[]) when using this implementation.


问:
Swift viewWillAppear not being called after dismissing view controller
I am presenting a view controller from a view controller called HomeController like so:

```<code>let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginController") as! LoginController

let navigationController: UINavigationController = UINavigationController(rootViewController: viewController)

present(navigationController, animated: true, completion: nil)
</code>```

In the presented view controller LoginController at some point gets dismissed:

```<code>self.dismiss(animated: true, completion: nil)
</code>```

But when it comes back to HomeController it is not calling viewWillAppear, I really need to check on condition on HomeController when it comes back to it, So how can I call viewWillAppear when LoginController dismisses the view?

答:
If presented viewController is half screen then you will have to Call the viewWillAppear of presenting viewController manually in side presented view controller's viewWillDisappear.
Add following code to your Presented view controller.

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    presentingViewController?.viewWillDisappear(true)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    presentingViewController?.viewWillAppear(true)
}
</code>```

Note: you must have to call 'presentingViewController?.viewWillDisappear(true)' to get your Presenting view controllers viewWillAppear execute everytime.

Body:
I am presenting a view controller from a view controller called HomeController like so:

let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginController") as! LoginController

let navigationController: UINavigationController = UINavigationController(rootViewController: viewController)

present(navigationController, animated: true, completion: nil)

In the presented view controller LoginController at some point gets dismissed:

self.dismiss(animated: true, completion: nil)

But when it comes back to HomeController it is not calling viewWillAppear, I really need to check on condition on HomeController when it comes back to it, So how can I call viewWillAppear when LoginController dismisses the view?

Body:
If presented viewController is half screen then you will have to Call the viewWillAppear of presenting viewController manually in side presented view controller's viewWillDisappear.
Add following code to your Presented view controller.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    presentingViewController?.viewWillDisappear(true)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    presentingViewController?.viewWillAppear(true)
}

Note: you must have to call 'presentingViewController?.viewWillDisappear(true)' to get your Presenting view controllers viewWillAppear execute everytime.


问:
Azure API Management, single API accept AAD or subscription key
Is it possible to have a single API in APIM that either accepts AAD token or subscription, based on what product it belongs to?

Default, this does not work, since unchecking "require subscription" on API-level will override setting product to require subscription.

So, I see two solutions.. create two APIs in APIM and place them in separate products (same backend), or write a custom policy. Is there a way to check context.Subscription.Key and match with the product subscriptions?

答:
Should be possible by adding your API to two products:

One with subscription requirement enabled

Another without subscription requirement enabled, but with validate-jwt policy added at product level to require AAD token


问:
Call facebook from ViewController not from appdelegate
Hello guys i am new about this implementing facebook into my app.I check developer's facebook and the sdk tutorial.But they all show how to open facebook when the application started.I have a button and i want to open the facebook application ask permission and post the users wall from another view controller. Can anybody help me to do that?</p>

答:
I'd suggest two things.

Firstly: Presuming you've read through https://developers.facebook.com/docs/guides/mobile/
You'll probably have yourself an appid (an essential component of connecting to facebook).
With this you can have a look at this demo facebook app https://github.com/facebook/facebook-ios-sdk/tree/master/sample/DemoApp and apply the key to the property 'kAppId'. This will allow you to run the demo and show how the Facebook classes are initialised and make calls, updating the view as you go.

Secondly: Once you have this grounding of a good example, the next part of your question is relatively easy. If you look at the above examples DemoAppViewController you'll notice that you can start the entire Facebook login process by creating a new instance of the FBConnect class (and it's appropriate delegate). This means that you can link it to a button that updates a new view as long as this new view has the delegate contained or some way to update itself to say "Hey, I'm logged in"

There are a wealth of step by step tutorials to help better explain what I'm getting at.
I really like this one: http://www.raywenderlich.com/1488/how-to-use-facebooks-new-graph-api-from-your-iphone-app as it's extremely in-depth and probably works at the level you are interested in.

edit - Additionally, just to hit on passing data between view controllers, even facebook related material, I'd suggest you look at http://www.iphonedevsdk.com/forum/iphone-sdk-development/54859-sharing-data-between-view-controllers-other-objects.html (Some improvements coming too in iOS5)

ContentLicense: CC BY-SA 3.0


问:
Ansible Python API - how to get variables defined in vars_files, host_vars, group_vars
I am trying to pull variables from all possible locations using Python API

In my playbook test_play.yml I have..

```<code>---
hosts: abc.com
gather_facts: no

roles:
  - my_roles

vars_files:
  - var/var.yml

tasks:
  .....
  .....
</code>```

file structure -

```<code>test_play.yml
roles
  - my_roles
    -- defaults
vars
  - var.yml
hosts
  - DEV
    -- hosts
    -- group_vars
       --- all.yml
</code>```

My code --

```<code>host_file = path_to_host_file
play_path = path_to_playbook

inventory = InventoryManager(loader=DataLoader(), source=[host_file])
variable_manager = VariableManager(loader=DataLoader(), inventory=inventory)

pb = Playbook.load(play_path, variable_manager, DataLoader())
play = pb.get_plays()

# here I get one play, which is fine
all_vars = variable_manager.get_vars(play=plays[0])
</code>```

in all_vars, I am getting variables defined in inventory file, rules only. But the variables defined in var.yml, group_vars/all.yml are missing. How to get them?

答:
You just need to:

variable_manager.get_vars(host=inventory.get_host("hostname"))
```

It is sad that Ansible does not provide a better documentation for their API.

Body:
I am trying to pull variables from all possible locations using Python API

In my playbook test_play.yml I have..

---
hosts: abc.com
gather_facts: no

roles:
  - my_roles

vars_files:
  - var/var.yml

tasks:
  .....
  .....

file structure -

test_play.yml
roles
  - my_roles
    -- defaults
vars
  - var.yml
hosts
  - DEV
    -- hosts
    -- group_vars
       --- all.yml

My code --

host_file = path_to_host_file
play_path = path_to_playbook

inventory = InventoryManager(loader=DataLoader(), source=[host_file])
variable_manager = VariableManager(loader=DataLoader(), inventory=inventory)

pb = Playbook.load(play_path, variable_manager, DataLoader())
play = pb.get_plays()

# here I get one play, which is fine
all_vars = variable_manager.get_vars(play=plays[0])

in all_vars, I am getting variables defined in inventory file, rules only. But the variables defined in var.yml, group_vars/all.yml are missing. How to get them?

Body:
You just need to:

variable_manager.get_vars(host=inventory.get_host("hostname"))

It is sad that Ansible does not provide a better documentation for their API.


问:
How can I create a wrapper for the RecyclerView Adapter that will accept any Adapter that implements RecyclerView.Adapter<RecyclerView.ViewHolder>
I know the title is a bit weird, sorry. This is a weird one that I'm not even sure I can explain it correctly, here is my attempt:

Basically I want to implement a wrapper for any adapters that extend RecyclerView.Adapter<RecyclerView.ViewHolder> , the wrapper eventually will be able to insert rows if needed and it will modify things like getItemCount() as necessary, but I'm nowhere near that part yet.

This is my class definition:

```<code>class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

I pass to it the original adapter which I want to wrap.

If I have the class definition like that, and then I try to create an instance of MyRecyclerAdapterWrapper like this:

```<code>val wrapper = MyRecyclerAdapterWrapper(activity, myOriginalAdapter)
</code>```

Where myOriginalAdapter is an instance of:

```<code>class MyOriginalAdapter() : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {
</code>```

I then get an error saying that it is expecting RecyclerView.Adapter<RecyclerView.ViewHolder>  but instead got MyOriginalAdapter.

So then I tried the out keyword on the class definition like this:

```<code>class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

And that allows my constructor call MyRecyclerAdapterWrapper(activity, myOriginalAdapter) to stop complaining, however then my MyRecyclerAdapterWrapper class fails at implementing some of the RecyclerView.Adapter<RecyclerView.ViewHolder> overrides because originalAdapter expects Nothing instead of RecyclerView.ViewHolder.

For example inside MyRecyclerAdapterWrapper I have this piece of code:

```<code>override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder,position)
}
</code>```

The error here is Type mismatch Required: Nothing Found: RecyclerView.ViewHolder.

So what is the correct way to handle this?

Edit: just wanted to be clear that other adapters will also use this wrapper, so the wrapper must be generic.

Edit: I should have mentioned this, there is a similar wrapper that works fine that I was using but it is in Java, the class definition on that one was:

```<code>public final class MyRecyclerAdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
     public MyRecyclerAdapterWrapper(@NonNull Activity activity,
        @NonNull RecyclerView.Adapter originalAdapter){
</code>```

Edit: Based on the answer from @muetzenflo I was able to get most of it to work but still have a problem with some methods.

I now have this:

```<code>class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

And

```<code> class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {

        }
</code>```

This works:

```<code>val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
</code>```

But this doesn't:

```<code>genericMethod(myRecyclerAdapterWrapper)

private fun genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<RecyclerView.ViewHolder>) {

    }
</code>```

The error is:

```<code>Type mismatch: inferred type is MainActivity.MyRecyclerAdapterWrapper<MainActivity.MyCustomAdapter.MyViewHolder> but MainActivity.MyRecyclerAdapterWrapper<RecyclerView.ViewHolder> was expected
</code>```

Edit: Think I figured out how to make the generic methods:

```<code>private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {

    }
</code>```

So in the end this is how my class ended up and it all compiles and runs:

```<code>class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
        genericMethod(myRecyclerAdapterWrapper)
    }
    private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {
    }
    class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return originalAdapter.onCreateViewHolder(parent,viewType)
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            originalAdapter.onBindViewHolder(holder as T,position)
        }
        override fun getItemCount(): Int {
            return originalAdapter.itemCount
        }
    }
    class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {
        }
        override fun getItemCount(): Int {
            TODO("Not yet implemented")
        }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            TODO("Not yet implemented")
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            TODO("Not yet implemented")
        }
    }
}
</code>```

答:
If I understand what you are trying to do, this should solve your issue in a generic matter.

Your RecyclerViewWrapper can use generic types for both the Adapter and for the ViewHolder

```<code>class RecyclerViewWrapper<VH : RecyclerView.ViewHolder, A : RecyclerView.Adapter<VH>>(
    activity: Activity,
    val originalAdapter: A
) : RecyclerView.Adapter<VH>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        TODO("Not yet implemented")
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        TODO("Not yet implemented")
    }

    override fun getItemCount(): Int {
        TODO("Not yet implemented")
    }
}
</code>```

Your OriginalAdapter can be whatever adapter you want

```<code>class OriginalAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        TODO("Not yet implemented")
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        TODO("Not yet implemented")
    }

    override fun getItemCount(): Int {
        TODO("Not yet implemented")
    }
}
</code>```

And then to use it you can just initiate it as such

```<code>fun example(activity: Activity) {
    val wrapper = RecyclerViewWrapper(activity, OriginalAdapter())
}
</code>```

I think this will be able to help you (as long as I understood correctly), you may need to make minor changes to fit your needs but nothing breaking

Body:
I know the title is a bit weird, sorry. This is a weird one that I'm not even sure I can explain it correctly, here is my attempt:

Basically I want to implement a wrapper for any adapters that extend RecyclerView.Adapter<RecyclerView.ViewHolder> , the wrapper eventually will be able to insert rows if needed and it will modify things like getItemCount() as necessary, but I'm nowhere near that part yet.

This is my class definition:

class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

I pass to it the original adapter which I want to wrap.

If I have the class definition like that, and then I try to create an instance of MyRecyclerAdapterWrapper like this:

val wrapper = MyRecyclerAdapterWrapper(activity, myOriginalAdapter)

Where myOriginalAdapter is an instance of:

class MyOriginalAdapter() : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {

I then get an error saying that it is expecting RecyclerView.Adapter<RecyclerView.ViewHolder>  but instead got MyOriginalAdapter.

So then I tried the out keyword on the class definition like this:

class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

And that allows my constructor call MyRecyclerAdapterWrapper(activity, myOriginalAdapter) to stop complaining, however then my MyRecyclerAdapterWrapper class fails at implementing some of the RecyclerView.Adapter<RecyclerView.ViewHolder> overrides because originalAdapter expects Nothing instead of RecyclerView.ViewHolder.

For example inside MyRecyclerAdapterWrapper I have this piece of code:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder,position)
}

The error here is Type mismatch Required: Nothing Found: RecyclerView.ViewHolder.

So what is the correct way to handle this?

Edit: just wanted to be clear that other adapters will also use this wrapper, so the wrapper must be generic.

Edit: I should have mentioned this, there is a similar wrapper that works fine that I was using but it is in Java, the class definition on that one was:

public final class MyRecyclerAdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
     public MyRecyclerAdapterWrapper(@NonNull Activity activity,
        @NonNull RecyclerView.Adapter originalAdapter){

Edit: Based on the answer from @muetzenflo I was able to get most of it to work but still have a problem with some methods.

I now have this:

class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

And

 class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {

        }

This works:

val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())

But this doesn't:

genericMethod(myRecyclerAdapterWrapper)

private fun genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<RecyclerView.ViewHolder>) {

    }

The error is:

Type mismatch: inferred type is MainActivity.MyRecyclerAdapterWrapper<MainActivity.MyCustomAdapter.MyViewHolder> but MainActivity.MyRecyclerAdapterWrapper<RecyclerView.ViewHolder> was expected

Edit: Think I figured out how to make the generic methods:

private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {

    }

So in the end this is how my class ended up and it all compiles and runs:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
        genericMethod(myRecyclerAdapterWrapper)
    }
    private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {
    }
    class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return originalAdapter.onCreateViewHolder(parent,viewType)
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            originalAdapter.onBindViewHolder(holder as T,position)
        }
        override fun getItemCount(): Int {
            return originalAdapter.itemCount
        }
    }
    class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {
        }
        override fun getItemCount(): Int {
            TODO("Not yet implemented")
        }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            TODO("Not yet implemented")
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            TODO("Not yet implemented")
        }
    }
}

Body:
If I understand what you are trying to do, this should solve your issue in a generic matter.

Your RecyclerViewWrapper can use generic types for both the Adapter and for the ViewHolder

class RecyclerViewWrapper<VH : RecyclerView.ViewHolder, A : RecyclerView.Adapter<VH>>(
    activity: Activity,
    val originalAdapter: A
) : RecyclerView.Adapter<VH>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        TODO("Not yet implemented")
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        TODO("Not yet implemented")
    }

    override fun getItemCount(): Int {
        TODO("Not yet implemented")
    }
}

Your OriginalAdapter can be whatever adapter you want

class OriginalAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        TODO("Not yet implemented")
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        TODO("Not yet implemented")
    }

    override fun getItemCount(): Int {
        TODO("Not yet implemented")
    }
}

And then to use it you can just initiate it as such

fun example(activity: Activity) {
    val wrapper = RecyclerViewWrapper(activity, OriginalAdapter())
}

I think this will be able to help you (as long as I understood correctly), you may need to make minor changes to fit your needs but nothing breaking


问:
Failed to resolve module specifier "three" as of 137
Coming back to some old project, I discover nothing was loading. Checking the console log I see the following:

```<code>Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".
</code>```

In my script I got the following:

```<code><script type="module">
import * as THREE from "https://cdn.skypack.dev/three/build/three.module.js"
import { OBJLoader } from "https://cdn.skypack.dev/three/examples/jsm/loaders/OBJLoader.js"
import { FirstPersonControls } from "https://cdn.skypack.dev/three/examples/jsm/controls/FirstPersonControls.js"
</code>```

I try to step back some versions and not until I reach 0.136.0 does this error go away. Has the way one imports three.js changed, or is this a bug?

Also, would there be some way of catching this at runtime? Like I get the latest version number from Skypack and try an import. If failed, automatically step back a decimal and try again.

Edit

@Mugen87 offers using importmap. I change my code with the following:

```<code><script type="importmap">
{
    "imports": {
        "three": "https://cdn.skypack.dev/three/build/three.module.js",
        "three/OBJLoader": "https://cdn.skypack.dev/three/examples/jsm/loaders/OBJLoader.js",
        "three/FirstPersonControls": "https://cdn.skypack.dev/three/examples/jsm/controls/FirstPersonControls.js"
    }
}
</script>

<script type="module">
import * as THREE from "three"
import { OBJLoader } from "three/OBJLoader"
import { FirstPersonControls } from "three/FirstPersonControls"
</code>```

I get the following error:

```<code>Uncaught SyntaxError: The requested module '/-/three@v0.137.5-HJEdoVYPhjkiJWkt6XIa/dist=es2019,mode=raw/build/three.module.js' does not provide an export named 'default'
</code>```

答:
The CDN you're using (cdn.skypack.dev) does some re-exporting on their side, which is causing the problem.

The file you're referencing in your import isn't actually the three.js module, but a re-direct.

That file does an export * (which is fine), AND an export {default}, which is where the failure is occurring. Three.js does not have a default export.

Skypack is likely applying this redirect universally to all modules, so it's not that they necessarily KNOW this is happening, but they should definitely be testing their system before hosting a specific module...

Try changing your importmap to reference the following URL, and it should work:

```<code>https://cdn.skypack.dev/-/three@v0.137.5-HJEdoVYPhjkiJWkt6XIa/dist=es2019,mode=raw/build/three.module.js
</code>```

Body:
Coming back to some old project, I discover nothing was loading. Checking the console log I see the following:

Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".

In my script I got the following:

Body:
The CDN you're using (cdn.skypack.dev) does some re-exporting on their side, which is causing the problem.

The file you're referencing in your import isn't actually the three.js module, but a re-direct.

That file does an export * (which is fine), AND an export {default}, which is where the failure is occurring. Three.js does not have a default export.

Skypack is likely applying this redirect universally to all modules, so it's not that they necessarily KNOW this is happening, but they should definitely be testing their system before hosting a specific module...

Try changing your importmap to reference the following URL, and it should work:

https://cdn.skypack.dev/-/three@v0.137.5-HJEdoVYPhjkiJWkt6XIa/dist=es2019,mode=raw/build/three.module.js


问:
Doctrine 1.2 hydration fails with HYDRATION_RECORD, but works with HYDRATION_ARRAY
I have a code that runs perfectly with Doctrine_Core::HYDRATION_ARRAY, but crashes with Doctrine_Core::HYDRATION_RECORD. The page is loading for about two minutes and shows standard browser error message, which is something like

```<code>Connection to the server was lost during the page load.
</code>```

(I have localized browser, so that's not the exact error message, but translated).

Using mysql command line Show processlist output

```<code>+-----+--------+-----------------+--------+---------+------+-------+------------------+
| Id  | User   | Host            | db     | Command | Time | State | Info             |
+-----+--------+-----------------+--------+---------+------+-------+------------------+
| 698 | root   | localhost:53899 | NULL   | Query   |    0 | NULL  | show processlist |
| 753 | *user* | localhost:54202 | *db1*  | Sleep   |  102 |       | NULL             |
| 754 | *user* | localhost:54204 | *db2*  | Sleep   |  102 |       | NULL             |
+-----+--------+-----------------+--------+---------+------+-------+------------------+
</code>```

The code itself:

```<code> $q = Doctrine_Query::create()
        ->select("fc.*")
        ->from("Card fc")
        ->leftJoin("fc.Fact f")
        ->where("f.deckid=?", $deck_id);
  $card = $q->execute(array(), Doctrine_Core::HYDRATE_RECORD);
  //Commenting the above line and uncommenting below line leads to an error
  //$card= $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
</code>```

So I think that query is not populated with correct SQL. Hovewer, $q->getSqlQuery() outputs the correct SQL that runs perfectly if executed via command-line or phpMyAdmin.

Server configuration:

```<code>Apache/2.2.4 (Win32) mod_ssl/2.2.4 OpenSSL/0.9.8k mod_wsgi/3.3 Python/2.7.1 PHP/5.2.12
Mysql 5.1.40-community
</code>```

Everything runs on localhost, so that's not a connection issue.

The amount of data for that specific query is very small - about a dozen records, so it's nothing to do with memory or time limits. safe_mode is off, display_errors is on ,error_reporting is 6135.

Could somebody point to some hints or caveats I'm missing?

UPDATE: what's most weird that it works with HYDRATION_RECORD from time to time.

UPDATE2: it crashes when I'm trying to fetch something from the query, e.g. getFirst(). With no fetching it works, but I really don't need a query form which I can't fetch data.

UPDATE3: I've workarounded this issue, but I'm still interested, what's going on.

Update 4:

Sql query:

```<code>SELECT f.id AS f__id, f.createdat AS f__createdat, f.updatedat AS f__updatedat,
    f.flashcardmodelid AS f__flashcardmodelid, f.source AS f__source,
    f.content AS f__content, f.md5 AS f__md5
FROM flashcard f
LEFT JOIN fact f2 ON f.id = f2.flashcardid AND (f2.deleted_at IS NULL)
WHERE (f2.deckid = 19413)
</code>```

Output:

```<code>f__id   f__createdat            f__updatedat            f__flashcardmodelid     f__source           f__content
245639  2011-08-05 20:00:00     2011-08-05 20:00:00     179                     jpod lesson 261     {"source":"\u7f8e\u5473\u3057\u3044","target":"del...
</code>```

So, the query itself is OK, data fectched as expected. Do you need models definition?

Update 5 When running query with HYDRATE_RECORD httpd.exe consumes 100% of one of the CPU cores.

Final Update Don't know why, but now it works... Haven't changed anything. Looks like it just was waiting when I place a bounty on this question. :) But still, as I already have placed a bounty, any idea of what's the difference between HYDRATE_ARRAY and HYDRATE_RECORD that might crash the script is appreciated.

答:
I have had a similar issue with Doctrine 1.2, and found out that PHP reported a FATAL error due to exceeding memory limit or execution time, or sometimes the situation even got PHP to cause a segmentation fault.

You can find these errors in your Apache error log file. On my OS X box those files are in /var/log/apache2/error_log. You can increase the allowed memory or max execution time in your PHP configuration.

In my case, it was caused by the amount of records that was fetched from the database that caused excessive memory consumption. Hydrating Doctrine_Records seems to be a relatively tough thing to do some times.

Just out of curiousity, how many rows do you expect in your result?

Body:
I have a code that runs perfectly with Doctrine_Core::HYDRATION_ARRAY, but crashes with Doctrine_Core::HYDRATION_RECORD. The page is loading for about two minutes and shows standard browser error message, which is something like

Connection to the server was lost during the page load.

(I have localized browser, so that's not the exact error message, but translated).

Using mysql command line Show processlist output

+-----+--------+-----------------+--------+---------+------+-------+------------------+
| Id  | User   | Host            | db     | Command | Time | State | Info             |
+-----+--------+-----------------+--------+---------+------+-------+------------------+
| 698 | root   | localhost:53899 | NULL   | Query   |    0 | NULL  | show processlist |
| 753 | *user* | localhost:54202 | *db1*  | Sleep   |  102 |       | NULL             |
| 754 | *user* | localhost:54204 | *db2*  | Sleep   |  102 |       | NULL             |
+-----+--------+-----------------+--------+---------+------+-------+------------------+

The code itself:

 $q = Doctrine_Query::create()
        ->select("fc.*")
        ->from("Card fc")
        ->leftJoin("fc.Fact f")
        ->where("f.deckid=?", $deck_id);
  $card = $q->execute(array(), Doctrine_Core::HYDRATE_RECORD);
  //Commenting the above line and uncommenting below line leads to an error
  //$card= $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);

So I think that query is not populated with correct SQL. Hovewer, $q->getSqlQuery() outputs the correct SQL that runs perfectly if executed via command-line or phpMyAdmin.

Server configuration:

Apache/2.2.4 (Win32) mod_ssl/2.2.4 OpenSSL/0.9.8k mod_wsgi/3.3 Python/2.7.1 PHP/5.2.12
Mysql 5.1.40-community

Everything runs on localhost, so that's not a connection issue.

The amount of data for that specific query is very small - about a dozen records, so it's nothing to do with memory or time limits. safe_mode is off, display_errors is on ,error_reporting is 6135.

Could somebody point to some hints or caveats I'm missing?

UPDATE: what's most weird that it works with HYDRATION_RECORD from time to time.

UPDATE2: it crashes when I'm trying to fetch something from the query, e.g. getFirst(). With no fetching it works, but I really don't need a query form which I can't fetch data.

UPDATE3: I've workarounded this issue, but I'm still interested, what's going on.

Update 4:

Sql query:

SELECT f.id AS f__id, f.createdat AS f__createdat, f.updatedat AS f__updatedat,
    f.flashcardmodelid AS f__flashcardmodelid, f.source AS f__source,
    f.content AS f__content, f.md5 AS f__md5
FROM flashcard f
LEFT JOIN fact f2 ON f.id = f2.flashcardid AND (f2.deleted_at IS NULL)
WHERE (f2.deckid = 19413)

Output:

f__id   f__createdat            f__updatedat            f__flashcardmodelid     f__source           f__content
245639  2011-08-05 20:00:00     2011-08-05 20:00:00     179                     jpod lesson 261     {"source":"\u7f8e\u5473\u3057\u3044","target":"del...

So, the query itself is OK, data fectched as expected. Do you need models definition?

Update 5 When running query with HYDRATE_RECORD httpd.exe consumes 100% of one of the CPU cores.

Final Update Don't know why, but now it works... Haven't changed anything. Looks like it just was waiting when I place a bounty on this question. :) But still, as I already have placed a bounty, any idea of what's the difference between HYDRATE_ARRAY and HYDRATE_RECORD that might crash the script is appreciated.


问:
How to resize and image before saving it with gridfs?
i'm a beginner with mongoDB and gridfs. I have a code which save in the database an incoming image. But I'd like to resize the image before saving it. It tried to use sharp, but I don't really understand how it works.

I tried the following code, but it's not working

```<code>const storage = new GridFsStorage({
  url: mongoURI,

  file: (req, file) => {
    return new Promise((resolve, reject) => {
      const filename = req.params.userID;
      const fileInfo = {
        filename: filename,
        bucketName: "ProfilePic",
      };
      resolve(fileInfo);
    });
  }
});

const upload = multer({ storage });

router.post("/setProfilePic/:userID", upload.single("picture"), async(req, res) => {
//code not working
  await sharp(req.file.path)
    .resize(500)
    .jpeg({quality: 50})
    .toFile(
        path.resolve(req.file.destination,'resized',image)
    )
// end of non working code
  return res.status(200).json({state: "ok"})
});
</code>```

答:
I used the previous answer. I made a few changes to make it work. My req.file.buffer was always undefined. So I made few changes.

There are two things I want to highlight below

Make sure you use multer version "^2.0.0-rc.1".

You can create buffer by

```<code>const buffer = await getStream.buffer(req.file.stream);
</code>```

rest of solution is exactly same. Here is the full code sample.

```<code>const multer = require('multer')
const { GridFsStorage } = require("multer-gridfs-storage");
const { Readable } = require("stream"); // from nodejs
const sharp = require("sharp");
const getStream = require("get-stream");

const storage = new GridFsStorage({
  url: mongoURI,
  options: { useUnifiedTopology: true }, // silence the warning
  file: () => ({ bucketName: "ProfilePic",filename: req.params.userID }),
});

app.post("/setProfilePic/:userID", multer.single("image"), async (req, res) => {
  const file = req.file;
  const buffer = await getStream.buffer(req.file.stream);

  // chain sharp methods

  sharp(buffer)
    .resize(200, 100)
    .jpeg({ quality: 50 })
    .toBuffer((err, data, info) => {
      // data here directly contains the buffer object.
      const fileStream = Readable.from(data);

      // write the resized stream to the database.
      storage.fromStream(fileStream, req, file).then(() => {
        res.json({ state: "ok" });
      });
    });
});
</code>```

Body:
i'm a beginner with mongoDB and gridfs. I have a code which save in the database an incoming image. But I'd like to resize the image before saving it. It tried to use sharp, but I don't really understand how it works.

I tried the following code, but it's not working

const storage = new GridFsStorage({
  url: mongoURI,

  file: (req, file) => {
    return new Promise((resolve, reject) => {
      const filename = req.params.userID;
      const fileInfo = {
        filename: filename,
        bucketName: "ProfilePic",
      };
      resolve(fileInfo);
    });
  }
});

const upload = multer({ storage });

router.post("/setProfilePic/:userID", upload.single("picture"), async(req, res) => {
//code not working
  await sharp(req.file.path)
    .resize(500)
    .jpeg({quality: 50})
    .toFile(
        path.resolve(req.file.destination,'resized',image)
    )
// end of non working code
  return res.status(200).json({state: "ok"})
});

Body:
I used the previous answer. I made a few changes to make it work. My req.file.buffer was always undefined. So I made few changes.

There are two things I want to highlight below

Make sure you use multer version "^2.0.0-rc.1".

You can create buffer by

const buffer = await getStream.buffer(req.file.stream);

rest of solution is exactly same. Here is the full code sample.

const multer = require('multer')
const { GridFsStorage } = require("multer-gridfs-storage");
const { Readable } = require("stream"); // from nodejs
const sharp = require("sharp");
const getStream = require("get-stream");

const storage = new GridFsStorage({
  url: mongoURI,
  options: { useUnifiedTopology: true }, // silence the warning
  file: () => ({ bucketName: "ProfilePic",filename: req.params.userID }),
});

app.post("/setProfilePic/:userID", multer.single("image"), async (req, res) => {
  const file = req.file;
  const buffer = await getStream.buffer(req.file.stream);

  // chain sharp methods

  sharp(buffer)
    .resize(200, 100)
    .jpeg({ quality: 50 })
    .toBuffer((err, data, info) => {
      // data here directly contains the buffer object.
      const fileStream = Readable.from(data);

      // write the resized stream to the database.
      storage.fromStream(fileStream, req, file).then(() => {
        res.json({ state: "ok" });
      });
    });
});


问:
WKWebView view not resizable
I'm creating a macOS Swift app, I'm new to Swift. I'm trying to make the view resizable like web browsers (Chrome, Firefox, etc.), however my code doesn't seem to work, and I didn't find anything useful about WKWebView resizing.

Here's my code for the ViewController:

import Cocoa
import WebKit

class ViewController: NSViewController, WKUIDelegate
    {
    var webView: WKWebView!

    override func loadView()
    {
        let webConfiguration = WKWebViewConfiguration ();
        webConfiguration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs");
        webView = WKWebView (frame: CGRect(x:0, y:0, width:1920, height:1080), configuration:webConfiguration);
        webView.uiDelegate = self;
            self.view = webView;
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
        self.view.addSubview(webView)
        let url = URL(string: "https://www.google.com/")
        webView.load(URLRequest(url: url!))
    }
}
```

Results:

答:
Okay so I figured out how to fix the issue with Willeke's recommendation:

Replace this:

let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
self.view.addSubview(webView)
let url = URL(string: "https://www.google.com/")
webView.load(URLRequest(url: url!))
```
<p>With this:</p>
<pre class="lang-swift prettyprint-override"><code>if let url = URL(string: "https://www.roblox.com/") {
    let request = URLRequest(url: url)
    webView.load(request)
}
</code>```

Title: WKWebView view not resizable

Body:
I'm creating a macOS Swift app, I'm new to Swift. I'm trying to make the view resizable like web browsers (Chrome, Firefox, etc.), however my code doesn't seem to work, and I didn't find anything useful about WKWebView resizing.

Here's my code for the ViewController:

import Cocoa
import WebKit

class ViewController: NSViewController, WKUIDelegate
    {
    var webView: WKWebView!

    override func loadView()
    {
        let webConfiguration = WKWebViewConfiguration ();
        webConfiguration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs");
        webView = WKWebView (frame: CGRect(x:0, y:0, width:1920, height:1080), configuration:webConfiguration);
        webView.uiDelegate = self;
            self.view = webView;
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
        self.view.addSubview(webView)
        let url = URL(string: "https://www.google.com/")
        webView.load(URLRequest(url: url!))
    }
}

Results:

Body:
Okay so I figured out how to fix the issue with Willeke's recommendation:

Replace this:

let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
self.view.addSubview(webView)
let url = URL(string: "https://www.google.com/")
webView.load(URLRequest(url: url!))

With this:

if let url = URL(string: "https://www.roblox.com/") {
    let request = URLRequest(url: url)
    webView.load(request)
}


问:
Mutate an object which was taken from a vector
I have trouble solving an obvious simple problem.

Basically I want to push an instance of a structure to a vector to get it out later and to modify the object by calling a function implemented for the structure.

To simplify the case, I created the following test code, which reflects in my opinion to the same problem.

```<code>    let mut strings = Vec::new();
    strings.push("Hello".to_string());
    let string_option = strings.last();
    let string = string_option.unwrap();
    string.shrink_to(1);

</code>```

This has the compile error

```<code>error[E0596]: cannot borrow `*string` as mutable, as it is behind a `&` reference
  --> src/main.rs:89:5
   |
88 |     let string = string_option.unwrap();
   |         ------ help: consider changing this to be a mutable reference: `&mut String`
89 |     string.shrink_to(1);
   |     ^^^^^^^^^^^^^^^^^^^ `string` is a `&` reference, so the data it refers to cannot be borrowed as mutable
</code>```

Then I tried sheer endless variants like

```<code>    let mut strings = Vec::new();
    strings.push("Hello".to_string());
    let string_option = strings.last().as_mut();
    let string = string_option.unwrap();
    string.shrink_to(1);
</code>```

... or ...

```<code>    let mut strings = Vec::new();
    strings.push("Hello".to_string());
    let string_option = strings.last().as_deref_mut();
    let string = string_option.unwrap();
    string.shrink_to(1);
</code>```

Actually the code shown above is a simplification from this code, which I originally wanted to do.

```<code>struct Bar {
    data: Vec<String>
}

impl Bar {
    fn shrink_first(&mut self) {

        let s_opt = self.data.last().as_mut();  // s_opt is of type Option<&mut &String>

        let s = s_opt.unwrap(); // s is of type &mut & String
        s.shrink_to(1);
    }
}
</code>```

The code above brings the following errors ...

```<code>error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:67:21
   |
67 |         let s_opt = self.data.last().as_mut();  // s_opt is of type Option<&mut &String>
   |                     ^^^^^^^^^^^^^^^^         - temporary value is freed at the end of this statement
   |                     |
   |                     creates a temporary which is freed while still in use
68 |
69 |         let s = s_opt.unwrap(); // s is of type &mut & String
   |                 ----- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

error[E0596]: cannot borrow `**s` as mutable, as it is behind a `&` reference
  --> src/main.rs:70:9
   |
70 |         s.shrink_to(1);
   |         ^^^^^^^^^^^^^^ cannot borrow as mutable
</code>```

But in my opinion it always has the same root causes, but I have not figured out what to do.

答:
Simply change strings.last() to strings.last_mut().

The last() method returns a standard (immutable) reference (to be more precise, Option<&T>).

To be able to mutate the last String in the vector, you need to get a mutable reference via last_mut().

Body:
I have trouble solving an obvious simple problem.

Basically I want to push an instance of a structure to a vector to get it out later and to modify the object by calling a function implemented for the structure.

To simplify the case, I created the following test code, which reflects in my opinion to the same problem.

    let mut strings = Vec::new();
    strings.push("Hello".to_string());
    let string_option = strings.last();
    let string = string_option.unwrap();
    string.shrink_to(1);

This has the compile error

error[E0596]: cannot borrow `*string` as mutable, as it is behind a `&` reference
  --> src/main.rs:89:5
   |
88 |     let string = string_option.unwrap();
   |         ------ help: consider changing this to be a mutable reference: `&mut String`
89 |     string.shrink_to(1);
   |     ^^^^^^^^^^^^^^^^^^^ `string` is a `&` reference, so the data it refers to cannot be borrowed as mutable

Then I tried sheer endless variants like

    let mut strings = Vec::new();
    strings.push("Hello".to_string());
    let string_option = strings.last().as_mut();
    let string = string_option.unwrap();
    string.shrink_to(1);

... or ...

    let mut strings = Vec::new();
    strings.push("Hello".to_string());
    let string_option = strings.last().as_deref_mut();
    let string = string_option.unwrap();
    string.shrink_to(1);

Actually the code shown above is a simplification from this code, which I originally wanted to do.

struct Bar {
    data: Vec<String>
}

impl Bar {
    fn shrink_first(&mut self) {

        let s_opt = self.data.last().as_mut();  // s_opt is of type Option<&mut &String>

        let s = s_opt.unwrap(); // s is of type &mut & String
        s.shrink_to(1);
    }
}

The code above brings the following errors ...

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:67:21
   |
67 |         let s_opt = self.data.last().as_mut();  // s_opt is of type Option<&mut &String>
   |                     ^^^^^^^^^^^^^^^^         - temporary value is freed at the end of this statement
   |                     |
   |                     creates a temporary which is freed while still in use
68 |
69 |         let s = s_opt.unwrap(); // s is of type &mut & String
   |                 ----- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

error[E0596]: cannot borrow `**s` as mutable, as it is behind a `&` reference
  --> src/main.rs:70:9
   |
70 |         s.shrink_to(1);
   |         ^^^^^^^^^^^^^^ cannot borrow as mutable

But in my opinion it always has the same root causes, but I have not figured out what to do.


问:
jQuery - Change text in an input field after it's created
How can I write a script that will change an input field's text value, but the field is not yet created?

The script is loaded before the input field is created.  It needs to know that when any input with a certain class is created, it will then have some text put in to its value.  Can this be done with live()?

To clarify, the order of events are:

1 - Application-wide JavaScript for the page is loaded.  This contains script something along the lines of:

```<code>$('.myDiv input').each(function() {
    $(this).val('some text');
});
</code>```

2 - A second page-specific script is now loaded, which dynamically creates an input on the page, with no value.  I CANNOT MODIFY THIS SCRIPT. This is important, I need a solution that does not modify this script (otherwise I wouldn't be posting here).

```<code>$('.myDiv').html('<input type="text" />');
</code>```

答:
Since the script is already loaded.

I think the myClass property should be with

```<code><input style="myClass Styles Here">TEXT is Here</input>
</code>```

when it is created.

Body:
How can I write a script that will change an input field's text value, but the field is not yet created?

The script is loaded before the input field is created.  It needs to know that when any input with a certain class is created, it will then have some text put in to its value.  Can this be done with live()?

To clarify, the order of events are:

1 - Application-wide JavaScript for the page is loaded.  This contains script something along the lines of:

$('.myDiv input').each(function() {
    $(this).val('some text');
});

2 - A second page-specific script is now loaded, which dynamically creates an input on the page, with no value.  I CANNOT MODIFY THIS SCRIPT. This is important, I need a solution that does not modify this script (otherwise I wouldn't be posting here).

$('.myDiv').html('<input type="text" />');

Body:
Since the script is already loaded.

I think the myClass property should be with

<input style="myClass Styles Here">TEXT is Here</input>

when it is created.


问:
How are promises (and async) "asynchronous", exactly?
Every single example I read about it has code demonstrations that are synchronously executed, with the article writers pretending they're asynchronous.

No example I've seen yet says the code keeps running past the 'asynchronous' promise. If the code kept running while the promise was fulfilled, or the await was taking place, then it could be called asynchonous.

But if the main line of code stops for the promise/await response, then it's simply synchronous.

Can anyone explain this? I had the impression that code ran past the promise/sync function, rather than stopping and 'awaiting' the result to then continue the rest of the code identically to a normal synchronous execution operation.

答:
Promises themselves aren't really asynchronous. They are a pattern to implement working with other things that themselves are asynchronous.

Just like a callback is just a function, we tend to call them 'callbacks' if they get triggered at a later point.

All a Promise really is for is encapsulating the status of an asynchronous operation and let people access the result.

Asterisk: Promises themselves are also a little asynchronous, because they guarantee that the function passed to then() always happens at least in the next tick if the result already arrived.

And await doesn't block the process, it literally pauses the function and lets other things run. Similar to yield, which is also not asynchronous by itself.


问:
How to align buttons inside cards with different content
I am still learning CSS and HTML. So please excuse me if this is a silly question.
Please see my code below. I need help with aligning the blue buttons on both the cards. It should be on the bottom of the cards (aligned similarly) regardless of content size.
Please advise.

.row {
  display: flex;
  /* equal height of the children */
}

.col1 {
  flex: 1;
  /* additionally, equal width */
  border: 1px solid #dadada;
  margin: 0 40px 0 0;
  padding: 0 0 10px 0;
}

.col2 {
  flex: 1;
  /* additionally, equal width */
  border: 1px solid #dadada;
  padding: 0 0 10px 0;
}

.card-header {
  background: rgba(242, 242, 242, 1);
  text-align: left;
  font-size: 12px;
  font-weight: 600;
  padding: 31px 10px 31px 15px;
}

.card-header-bg {
  height: 7px;
}

.card-container {
  padding: 2px 14px;
}

.blue-button,
a.blue-button {
  background-color: #026fc2;
  border-radius: 99rem;
  box-shadow: inset 0 0 0 1px #454545;
  color: #fff;
  text-decoration: none;
  font-weight: 600;
  padding: 0.5rem 1rem;
  text-align: center;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col1">
    <div class="card-header-bg" style=" background-color: rgba(255, 181, 119, 1);"></div>

    <div class="card-header">Header</div>

    <div class="card-container">
      <p>Test Example</p>

      <ul>
        <li>test1</li>

        <li>test2</li>

        <li>test3</li>

        <li>test4</li>
      </ul>

      <p>Minor updates.</p>

      <ul>
        <li>test</li>

        <li>Test</li>
      </ul>

      <p>Go Here</p>
    </div>
  </div>

  <div class="col2">
    <div class="card-header-bg" style=" background-color: #7ECEFD;"></div>

    <div class="card-header">Header</div>

    <div class="card-container">
      <p>test123/p>

        <ul>
          <li>abc</li>

          <li>def</li>

          <li>ghi</li>
        </ul>

        <p>test test test.</p>

        <ul>
          <li>Learn about testing</li>
        </ul>

        <p>Second Test</p>
    </div>
  </div>
</div></code>```

答:
Not a silly question. They seem unaligned because there are more li's on the left side. Buttons are positioned statically by default, so if there is more content, it will be pushed down. You'll notice if you add more li's on the right side, the button will be pushed down and seem aligned. You may find nesting the buttons in their own divs will give you more control.

However, you can easily resolve this with your current structure by adding
 or the line-break element on the button that is positioned higher. See below.

.row {
  display: flex;
  /* equal height of the children */
}

.col1 {
  flex: 1;
  /* additionally, equal width */
  border: 1px solid #dadada;
  margin: 0 40px 0 0;
  padding: 0 0 10px 0;
}

.col2 {
  flex: 1;
  /* additionally, equal width */
  border: 1px solid #dadada;
  padding: 0 0 10px 0;
}

.card-header {
  background: rgba(242, 242, 242, 1);
  text-align: left;
  font-size: 12px;
  font-weight: 600;
  padding: 31px 10px 31px 15px;
}

.card-header-bg {
  height: 7px;
}

.card-container {
  padding: 2px 14px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.blue-button,
a.blue-button {
  background-color: #026fc2;
  border-radius: 99rem;
  box-shadow: inset 0 0 0 1px #454545;
  color: #fff;
  text-decoration: none;
  font-weight: 600;
  padding: 0.5rem 1rem;
  text-align: center;
  display: inline-block;
}

.btn-primary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px;
}

.card-container>div {
  height: 210px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col1">
    <div class="card-header-bg" style=" background-color: rgba(255, 181, 119, 1);"></div>

    <div class="card-header">Header</div>

    <div class="card-container">
      <div>
        <p>Test Example</p>

        <ul>
          <li>test1</li>

          <li>test2</li>

          <li>test3</li>

          <li>test4</li>
        </ul>

        <p>Minor updates.</p>

        <ul>
          <li>test</li>

          <li>Test</li>
        </ul>
      </div>
    </div>
    <div class="btn-primary">
      Go Here
    </div>
  </div>

  <div class="col2">
    <div class="card-header-bg" style=" background-color: #7ECEFD;"></div>

    <div class="card-header">Header</div>

    <div class="card-container">
      <div>
        <p>test123</p>

        <ul>
          <li>abc</li>

          <li>def</li>

          <li>ghi</li>
        </ul>

        <p>test test test.</p>

        <ul>
          <li>Learn about testing</li>
        </ul>
      </div>
    </div>
    <div class="btn-primary">
      Second Test
    </div>
  </div></code>```

Largest rendered height at default ~ makes height for both divs.

Body:
I am still learning CSS and HTML. So please excuse me if this is a silly question.
Please see my code below. I need help with aligning the blue buttons on both the cards. It should be on the bottom of the cards (aligned similarly) regardless of content size.
Please advise.

.row {
  display: flex;
  /* equal height of the children */
}

.col1 {
  flex: 1;
  /* additionally, equal width */
  border: 1px solid #dadada;
  margin: 0 40px 0 0;
  padding: 0 0 10px 0;
}

.col2 {
  flex: 1;
  /* additionally, equal width */
  border: 1px solid #dadada;
  padding: 0 0 10px 0;
}

.card-header {
  background: rgba(242, 242, 242, 1);
  text-align: left;
  font-size: 12px;
  font-weight: 600;
  padding: 31px 10px 31px 15px;
}

.card-header-bg {
  height: 7px;
}

.card-container {
  padding: 2px 14px;
}

.blue-button,
a.blue-button {
  background-color: #026fc2;
  border-radius: 99rem;
  box-shadow: inset 0 0 0 1px #454545;
  color: #fff;
  text-decoration: none;
  font-weight: 600;
  padding: 0.5rem 1rem;
  text-align: center;
  display: inline-block;
}

Header

Test Example

test1

test2

test3

test4

Minor updates.

test

Test

Go Here

Header

test123/p>

abc

def

ghi

test test test.

Learn about testing

Second Test

Body:
Not a silly question. They seem unaligned because there are more li's on the left side. Buttons are positioned statically by default, so if there is more content, it will be pushed down. You'll notice if you add more li's on the right side, the button will be pushed down and seem aligned. You may find nesting the buttons in their own divs will give you more control.

However, you can easily resolve this with your current structure by adding <br> or the line-break element on the button that is positioned higher. See below.

.row {
  display: flex;
  /* equal height of the children */
}

.col1 {
  flex: 1;
  /* additionally, equal width */
  border: 1px solid #dadada;
  margin: 0 40px 0 0;
  padding: 0 0 10px 0;
}

.col2 {
  flex: 1;
  /* additionally, equal width */
  border: 1px solid #dadada;
  padding: 0 0 10px 0;
}

.card-header {
  background: rgba(242, 242, 242, 1);
  text-align: left;
  font-size: 12px;
  font-weight: 600;
  padding: 31px 10px 31px 15px;
}

.card-header-bg {
  height: 7px;
}

.card-container {
  padding: 2px 14px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.blue-button,
a.blue-button {
  background-color: #026fc2;
  border-radius: 99rem;
  box-shadow: inset 0 0 0 1px #454545;
  color: #fff;
  text-decoration: none;
  font-weight: 600;
  padding: 0.5rem 1rem;
  text-align: center;
  display: inline-block;
}

.btn-primary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px;
}

.card-container>div {
  height: 210px;
}

<div class="row">
  <div class="col1">
    <div class="card-header-bg" style=" background-color: rgba(255, 181, 119, 1);"></div>

    <div class="card-header">Header</div>

    <div class="card-container">
      <div>
        <p>Test Example</p>

        <ul>
          <li>test1</li>

          <li>test2</li>

          <li>test3</li>

          <li>test4</li>
        </ul>

        <p>Minor updates.</p>

        <ul>
          <li>test</li>

          <li>Test</li>
        </ul>
      </div>
    </div>
    <div class="btn-primary">
      <a href=".html" class="blue-button" role="button">Go Here</a>
    </div>
  </div>

  <div class="col2">
    <div class="card-header-bg" style=" background-color: #7ECEFD;"></div>

    <div class="card-header">Header</div>

    <div class="card-container">
      <div>
        <p>test123</p>

        <ul>
          <li>abc</li>

          <li>def</li>

          <li>ghi</li>
        </ul>

        <p>test test test.</p>

        <ul>
          <li>Learn about testing</li>
        </ul>
      </div>
    </div>
    <div class="btn-primary">
      <a href="" class="blue-button" role="button">Second Test</a>
    </div>
  </div>

Largest rendered height at default ~ makes height for both divs.


问:
R: Create a linear mixed-effect model loop that removes one fixed independent variable, then adds it back in and removes another
I'm looking for a way to create a linear mixed-effect model loop that removes one fixed effect independent variable, runs the model, adds it back in, and removes another fixed independent variable from the model.

For example:

library(lme4)

L1 <- lmer(cyl ~ disp + hp + mpg (carb|gear), mtcars)

How can I create a loop of this model so that each new regression loop iteration removes a single fixed effect independent variable, adds it back in on the next iteration, and removes a different fixed independent variable?

Doing this would produce these models:

Original full model: lmer(cyl ~ disp + mpg +  (carb|gear), mtcars)

Partial model with mpg removed: lmer(cyl ~ disp + hp + (carb|gear), mtcars)

Partial model with mpg re-added and disp removed: lmer(cyl ~ hp + mpg  (carb|gear), mtcars)

Partial model with disp re-added and hp removed:  lmer(cyl ~ disp + mpg  (carb|gear), mtcars)

I am also curious how I can add each model to a list after each loop iteration.

Thanks a lot!

答: Check out the MuMIn package for model averaging. You normally start by running the full model, and the dredge function can be used to iteratively run models with all combinations of predictors. You can specify effects that you want to keep consistent e.g. your (carb|gear) random effect. The outputs can give you a table of results for each model.


问:
How can we insert text into Header/Footer after creating Header/Footer in google docs api using PHP?
I am working on google docs api. I want to insert content in header/footer in google docs using google docs API with PHP.

So, Firstly I am creating header/Footer request by the following request-

```<code>$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$requests[] = new Google_Service_Docs_Request(array(
  "createHeader" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
</code>```

After this I am able to get the Header Id and Footer Id from the response, like this-

```<code>$footerId = $response->replies[0]->createFooter->footerId;
$headerId = $response->replies[1]->createHeader->headerId;
print("footerid".$footerId);
print("headerid".$headerId);
</code>```

But, now I want to insert some texts in this above created header/footer.For that I was doing like this-

```<code>$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$requests[] = new Google_Service_Docs_Request(array(
  "createHeader" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

$footerId = $response->replies[0]->createFooter->footerId;
$headerId = $response->replies[1]->createHeader->headerId;
print("footerid".$footerId);
print("headerid".$headerId);

$requests [] = new Google_Service_Docs_Request([
  'insertText' => [
        'text' => "Sample7",
        'location' => [
          'segmentId' => $footerId,
          'index' => 0,
        ],
        'text' => 'sample text',
    ]
]);
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
  'requests' => $requests
));

$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
</code>```

I thought by updating my batch again I can able to insert text in my header/footer, but unfortunately it is not the right way and I am stuck at this point.If this is not the way then how we can insert text into header/footer in google docs using PHP.

答:
SUGGESTION

Perhaps you can try to structure your $requests code similar to an answer from How to insert text with google docs api php

Sample Tweaked Code:

```<code>$requests = array(new Google_Service_Docs_Request(array(
    'insertText' => array(
    'text' => 'sample text',
    'location' => array(
    'segmentId' => $footerId)))));
</code>```

Body:
I am working on google docs api. I want to insert content in header/footer in google docs using google docs API with PHP.

So, Firstly I am creating header/Footer request by the following request-

$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$requests[] = new Google_Service_Docs_Request(array(
  "createHeader" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

After this I am able to get the Header Id and Footer Id from the response, like this-

$footerId = $response->replies[0]->createFooter->footerId;
$headerId = $response->replies[1]->createHeader->headerId;
print("footerid".$footerId);
print("headerid".$headerId);

But, now I want to insert some texts in this above created header/footer.For that I was doing like this-

$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$requests[] = new Google_Service_Docs_Request(array(
  "createHeader" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

$footerId = $response->replies[0]->createFooter->footerId;
$headerId = $response->replies[1]->createHeader->headerId;
print("footerid".$footerId);
print("headerid".$headerId);

$requests [] = new Google_Service_Docs_Request([
  'insertText' => [
        'text' => "Sample7",
        'location' => [
          'segmentId' => $footerId,
          'index' => 0,
        ],
        'text' => 'sample text',
    ]
]);
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
  'requests' => $requests
));

$responses = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

I thought by updating my batch again I can able to insert text in my header/footer, but unfortunately it is not the right way and I am stuck at this point.If this is not the way then how we can insert text into header/footer in google docs using PHP.

Body:
SUGGESTION

Perhaps you can try to structure your $requests code similar to an answer from How to insert text with google docs api php

Sample Tweaked Code:

$requests = array(new Google_Service_Docs_Request(array(
    'insertText' => array(
    'text' => 'sample text',
    'location' => array(
    'segmentId' => $footerId)))));


问:
ansible read parameter value from file
I have a file that looks similarly:

```<code># some comment
foo/variable1 = value1
bar/variable2 = value2
</code>```

etc..

I have been trying to come up with an ansible logic to look up one particular variable of interest from this file.
For example if I need to get value2 assigned to myvar in ansible.

tried lineinfile first something like this:

```<code>- name: taskname
  lineinfile:
    path: /path/to/file
    regexp: '^bar/variable2.*$'
    line: dummy
  register: myvar
  check_mode: yes
</code>```

didn't work. I also tried to escape the / character in the regexp pattern but that wasn't the problem. Then I tried lookup ini file something like:

```<code>vars:
  myvar: "{{ lookup('ini', 'bar/variable2 file=/path/to/file') }}"
</code>```

but the file doesn't have sections so this fails too.

I tried using regex_search too in different ways but I just can't seem to have it working. I'd appreciate if somebody can help me. I wish lookup ini file would have a version where the section is optional. There are some parameter files that follow very similar format except they don't have sections in them.

答:
The ini lookup seems to work just fine, as long as you have a compatible file format (specifically, you need section headers). For example, if I have a file data.ini that contains:

```<code>[global]
# some comment
foo/variable1 = value1
bar/variable2 = value2
</code>```

Then this works:

```<code>- hosts: localhost
  gather_facts: false
  tasks:
    - debug:
        msg: "{{ lookup('ini', 'bar/variable2', file='data.ini') }}"
</code>```

Which results in:

```<code>TASK [debug] ********************************************************************************************
ok: [localhost] => {
    "msg": "value2"
}

</code>```

If you don't want to modify your input file, you can do this with regular expressions:

```<code>- hosts: localhost
  gather_facts: false
  vars:
    config: "{{ lookup('file', 'data.ini') }}"
  tasks:
    - debug:
        msg: >-
          {{
              config |
              regex_search('^foo/variable1 *= *.*', multiline=True) |
              regex_replace('.*= *(.*)$', '\1')
          }}
</code>```

Which results in:

```<code>TASK [debug] ********************************************************************************************
ok: [localhost] => {
    "msg": "value1"
}
</code>```

Some updates in response to your comments:

What is peculiar about the line breaks that made it working?

Mostly nothing. The line breaks are simply to make it easier to read. You just just as easily write it like this:

```<code>    - debug:
        msg: "{{ config | regex_search('^foo/variable1 *= *.*', multiline=True) | regex_replace('.*= *(.*)$', '\\1') }}"

</code>```

The only trick here is that inside a double-quoted string, you need to write \\1 instead of \1. If we were to use single quotes on the outside, it would be identical:

```<code>    - debug:
        msg: '{{ config | regex_search("^foo/variable1 *= *.*", multiline=True) | regex_replace(".*= *(.*)$", "\1") }}'
</code>```

Second, I am trying to understand the regex_replace part.

The output of the regex_search is going to be a single line from the config file, something like:

```<code>foo/variable1 = value1
</code>```

We want just the bit after the = sign. The regex replace captures that, and then replaces the entire string with the value of the capture group (\1). There may be more optimized ways of doing this, but this is what I came up with off the top of my head.

Title: ansible read parameter value from file

Body:
I have a file that looks similarly:

# some comment
foo/variable1 = value1
bar/variable2 = value2

etc..

I have been trying to come up with an ansible logic to look up one particular variable of interest from this file.
For example if I need to get value2 assigned to myvar in ansible.

tried lineinfile first something like this:

- name: taskname
  lineinfile:
    path: /path/to/file
    regexp: '^bar/variable2.*$'
    line: dummy
  register: myvar
  check_mode: yes

didn't work. I also tried to escape the / character in the regexp pattern but that wasn't the problem. Then I tried lookup ini file something like:

vars:
  myvar: "{{ lookup('ini', 'bar/variable2 file=/path/to/file') }}"

but the file doesn't have sections so this fails too.

I tried using regex_search too in different ways but I just can't seem to have it working. I'd appreciate if somebody can help me. I wish lookup ini file would have a version where the section is optional. There are some parameter files that follow very similar format except they don't have sections in them.

Body:
The ini lookup seems to work just fine, as long as you have a compatible file format (specifically, you need section headers). For example, if I have a file data.ini that contains:

[global]
# some comment
foo/variable1 = value1
bar/variable2 = value2

Then this works:

- hosts: localhost
  gather_facts: false
  tasks:
    - debug:
        msg: "{{ lookup('ini', 'bar/variable2', file='data.ini') }}"

Which results in:

TASK [debug] ********************************************************************************************
ok: [localhost] => {
    "msg": "value2"
}

If you don't want to modify your input file, you can do this with regular expressions:

- hosts: localhost
  gather_facts: false
  vars:
    config: "{{ lookup('file', 'data.ini') }}"
  tasks:
    - debug:
        msg: >-
          {{
              config |
              regex_search('^foo/variable1 *= *.*', multiline=True) |
              regex_replace('.*= *(.*)$', '\1')
          }}

Which results in:

TASK [debug] ********************************************************************************************
ok: [localhost] => {
    "msg": "value1"
}

Some updates in response to your comments:

What is peculiar about the line breaks that made it working?

Mostly nothing. The line breaks are simply to make it easier to read. You just just as easily write it like this:

    - debug:
        msg: "{{ config | regex_search('^foo/variable1 *= *.*', multiline=True) | regex_replace('.*= *(.*)$', '\\1') }}"

The only trick here is that inside a double-quoted string, you need to write \\1 instead of \1. If we were to use single quotes on the outside, it would be identical:

    - debug:
        msg: '{{ config | regex_search("^foo/variable1 *= *.*", multiline=True) | regex_replace(".*= *(.*)$", "\1") }}'

Second, I am trying to understand the regex_replace part.

The output of the regex_search is going to be a single line from the config file, something like:

foo/variable1 = value1

We want just the bit after the = sign. The regex replace captures that, and then replaces the entire string with the value of the capture group (\1). There may be more optimized ways of doing this, but this is what I came up with off the top of my head.


问:
INSERT INTO database table, from form not working. SQL
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

```<code><form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
</code>```

PHP (insert.php)

```<code><?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>
</code>```

答:
Change the single quotes surrounding the table name and the column name to backticks. Or get rid of them all together.

```<code>$sql="INSERT INTO `test` (`name`)  VALUES ('{$_POST['namefield']}')";
</code>```

Also, don't reference associative arrays ($_POST) directly in a string without using {} syntax or breaking up the string - what you have done there issues an E_NOTICE and should be avoided.

Read this thoroughly - you'd be amazed what you can (and can't) legally do in PHP strings...

Body:
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):

"Connected to databaseError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test' ('name') VALUES ('daniel')' at line 1"

The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?

Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.

HTML

<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>

PHP (insert.php)

<?php
$dbhost  = 'localhost';
$dbname  = 'carbon_db';
$dbuser  = 'username';
$dbpass  = 'password';

$con = mysql_connect($dbhost, $dbuser, $dbpass);

if($con == FALSE)
{
    echo 'Cannot connect to database' . mysql_error();
}
else
{
    echo 'Connected to database';
}

mysql_select_db($dbname, $con);

$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";

if (!mysql_query($sql, $con))
{
    die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

Body:
Change the single quotes surrounding the table name and the column name to backticks. Or get rid of them all together.

$sql="INSERT INTO `test` (`name`)  VALUES ('{$_POST['namefield']}')";

Also, don't reference associative arrays ($_POST) directly in a string without using {} syntax or breaking up the string - what you have done there issues an E_NOTICE and should be avoided.

Read this thoroughly - you'd be amazed what you can (and can't) legally do in PHP strings...


问:
Access GCP Secret during Cloud Build build step
Lets say I have a cloudbuild.yaml file that looks like this:

```<code>steps:
  - name: 'gcr.io/cloud-builders/docker'
    id: build
    args: ['build', '-t', 'us.gcr.io/${PROJECT_ID}/image_name', '--build-arg', 'secret=$$SECRET', '.']
    secretEnv: ['SECRET']

images:
  - 'us.gcr.io/${PROJECT_ID}/image_name'

availableSecrets:
  secretManager:
  - versionName: projects/project/secrets/my_secret/versions/latest
    env: 'SECRET'
</code>```

Right now, the --build-arg is assigning to the Docker secret arg the value $SECRET instead of the value actually stored in the secret. How can I access the secret value during this step? All of the examples I can find online say to add a bash entrypoint however only for steps that aren't actually doing the build call.

答:
The syntax for assigning secrets to docker args seems to be slightly different to that for normal environment variables. The following snippet is taken from a working project of my own and correctly accesses the secret, and you can see the difference compared to the normal environment variables:</p>
```<code>...
    env:
      - PROJECT_ID=$PROJECT_ID
      - NO_DEPLOY=$_NO_DEPLOY
      - NO_E2E=$_NO_E2E
    secretEnv:
      - "EXAMPLE_API_KEY"
    args:
      - --destination=gcr.io/$PROJECT_ID/api
      - --cache=true
      - --build-arg=PROJECT_ID
      - --build-arg=EXAMPLE_API_KEY
      - --build-arg=NO_DEPLOY
      - --build-arg=NO_E2E

availableSecrets:
  secretManager:
    - versionName: projects/$PROJECT_ID/secrets/example-api-key/versions/latest
      env: "EXAMPLE_API_KEY"
...
</code>```

Body:
Lets say I have a cloudbuild.yaml file that looks like this:

steps:
  - name: 'gcr.io/cloud-builders/docker'
    id: build
    args: ['build', '-t', 'us.gcr.io/${PROJECT_ID}/image_name', '--build-arg', 'secret=$$SECRET', '.']
    secretEnv: ['SECRET']

images:
  - 'us.gcr.io/${PROJECT_ID}/image_name'

availableSecrets:
  secretManager:
  - versionName: projects/project/secrets/my_secret/versions/latest
    env: 'SECRET'

Right now, the --build-arg is assigning to the Docker secret arg the value $SECRET instead of the value actually stored in the secret. How can I access the secret value during this step? All of the examples I can find online say to add a bash entrypoint however only for steps that aren't actually doing the build call.

Body:
The syntax for assigning secrets to docker args seems to be slightly different to that for normal environment variables. The following snippet is taken from a working project of my own and correctly accesses the secret, and you can see the difference compared to the normal environment variables:

...
    env:
      - PROJECT_ID=$PROJECT_ID
      - NO_DEPLOY=$_NO_DEPLOY
      - NO_E2E=$_NO_E2E
    secretEnv:
      - "EXAMPLE_API_KEY"
    args:
      - --destination=gcr.io/$PROJECT_ID/api
      - --cache=true
      - --build-arg=PROJECT_ID
      - --build-arg=EXAMPLE_API_KEY
      - --build-arg=NO_DEPLOY
      - --build-arg=NO_E2E

availableSecrets:
  secretManager:
    - versionName: projects/$PROJECT_ID/secrets/example-api-key/versions/latest
      env: "EXAMPLE_API_KEY"
...


问:
Mixed content & uri_for function
We have an web application using dancer2 framework.The website is using https.
But in the page, it calls other page using uri_for.
i.e The url is generated by uri_for and sending it to template.

The url generated is automatically set ‘http’, so the page has mixed content. And thus doesn’t load.

My question is where is the uri_for located. Why is automatically set ‘http’, how can I specify it to be ‘https’?

Many thanks
Wendy

答:
My question is where is the uri_for located.

See line 283 in Dancer2::Core::Request :

```<code>sub uri_for {
    my ( $self, $part, $params, $dont_escape ) = @_;

    $part ||= '';
    my $uri = $self->base;

    # Make sure there's exactly one slash between the base and the new part
    my $base = $uri->path;
    $base =~ s|/$||;
    $part =~ s|^/||;
    $uri->path("$base/$part");

    $uri->query_form($params) if $params;

    return $dont_escape
           ? uri_unescape( ${ $uri->canonical } )
           : ${ $uri->canonical };
}
</code>```

It obtains the scheme by calling $self->base, see line 242 :

```<code>sub base {
    my $self = shift;
    my $uri  = $self->_common_uri;

    return $uri->canonical;
}
</code>```

which calls $self->_common_uri (see line 249) :

```<code>sub _common_uri {
    my $self = shift;

    my $path   = $self->env->{SCRIPT_NAME};
    my $port   = $self->env->{SERVER_PORT};
    my $server = $self->env->{SERVER_NAME};
    my $host   = $self->host;
    my $scheme = $self->scheme;

    my $uri = URI->new;
    $uri->scheme($scheme);
    $uri->authority( $host || "$server:$port" );
    $uri->path( $path      || '/' );

    return $uri;
}
</code>```

which calls $self->scheme, see line 159 :

```<code>sub scheme {
    my ($self) = @_;
    my $scheme = $self->is_behind_proxy
               ? $self->forwarded_protocol
               : '';

    return $scheme || $self->env->{'psgi.url_scheme'};
}
</code>```

Title: Mixed content & uri_for function

Body:
My question is where is the uri_for located.

See line 283 in Dancer2::Core::Request :

sub uri_for {
    my ( $self, $part, $params, $dont_escape ) = @_;

    $part ||= '';
    my $uri = $self->base;

    # Make sure there's exactly one slash between the base and the new part
    my $base = $uri->path;
    $base =~ s|/$||;
    $part =~ s|^/||;
    $uri->path("$base/$part");

    $uri->query_form($params) if $params;

    return $dont_escape
           ? uri_unescape( ${ $uri->canonical } )
           : ${ $uri->canonical };
}

It obtains the scheme by calling $self->base, see line 242 :

sub base {
    my $self = shift;
    my $uri  = $self->_common_uri;

    return $uri->canonical;
}

which calls $self->_common_uri (see line 249) :

sub _common_uri {
    my $self = shift;

    my $path   = $self->env->{SCRIPT_NAME};
    my $port   = $self->env->{SERVER_PORT};
    my $server = $self->env->{SERVER_NAME};
    my $host   = $self->host;
    my $scheme = $self->scheme;

    my $uri = URI->new;
    $uri->scheme($scheme);
    $uri->authority( $host || "$server:$port" );
    $uri->path( $path      || '/' );

    return $uri;
}

which calls $self->scheme, see line 159 :

sub scheme {
    my ($self) = @_;
    my $scheme = $self->is_behind_proxy
               ? $self->forwarded_protocol
               : '';

    return $scheme || $self->env->{'psgi.url_scheme'};
}