问:
Do I really need to define reactive svelte variables twice?
I'm trying to use svelte's reactive variables. However, it seems I need to define my function twice. Is there a way to get rid of one of the two very similar lines?

```<code>let reactive_var = my_function( editable_var, 32 );
$: reactive_var = my_function( editable_var, 32 );

let another_var = reactive_var * 4;
</code>```

Removing the first line messes up the definition of another_var.

答:
To avoid the double declaration of reactive_var you could set another_var (the non reactive one based on the reactive) inside onMount() >> REPL

```<code>    import {onMount} from 'svelte'

    export let editable_var

    $: reactive_var = my_function( editable_var, 32 );
    let non_reactive_var

    onMount(() => {
        non_reactive_var = reactive_var * 4;
    })
</code>```

Or with the function twice, but still one line less..

```<code>    let non_reactive_var = my_function( editable_var, 32 ) * 4;

    $: reactive_var = my_function( editable_var, 32 );
</code>```

Body:
I'm trying to use svelte's reactive variables. However, it seems I need to define my function twice. Is there a way to get rid of one of the two very similar lines?

let reactive_var = my_function( editable_var, 32 );
$: reactive_var = my_function( editable_var, 32 );

let another_var = reactive_var * 4;

Removing the first line messes up the definition of another_var.

Body:
To avoid the double declaration of reactive_var you could set another_var (the non reactive one based on the reactive) inside onMount() >> REPL

    import {onMount} from 'svelte'

    export let editable_var

    $: reactive_var = my_function( editable_var, 32 );
    let non_reactive_var

    onMount(() => {
        non_reactive_var = reactive_var * 4;
    })

Or with the function twice, but still one line less..

    let non_reactive_var = my_function( editable_var, 32 ) * 4;

    $: reactive_var = my_function( editable_var, 32 );


来源: stackexchange

问:
How to get select value on form in php?
I want to get a selected value on the form.

Suppose If I select category "car" from sub-category "nissan".
I want this value on php.

Not value 1 and 1 because I do not recognise what value is selected.
I want name or unique value in my php file.

This is php file on the same page:

```<code><?php

if(isset($_POST['select1'])){
    $select1 = $_POST['select1'];
}

if(isset($_POST['select2'])){
 $select2 = $_POST['select2'];
}

?>

 <html>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
 </script>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<select name="select1" id="select1">
 <option value=""></option>
 <option value="1">car</option>
 <option value="2">phone</option>
 <option value="3">tv</option>
</select>

<select name="select2" id="select2">
 <option value=""></option>
 <option value="1">toyota</option>
 <option value="1">nissan</option>
 <option value="1">bmw</option>
 <option value="2">Iphone</option>
 <option value="2">LG</option>
 <option value="2">Samsung</option>
 <option value="3">Philips</option>
 <option value="3">Samsung</option>
</select>
</form>
</html>

<script>
 $("#select1").change(function() {
  if ($(this).data('options') == undefined) {
  /*Taking an array of all options-2 and kind of embedding it on the select1*/
  $(this).data('options', $('#select2 option').clone());
  }
  var id = $(this).val();
  var options = $(this).data('options').filter('[value=' + id + ']');
  $('#select2').html(options);
 });
</script>
</code>```

Any idea or suggestions would be welcome
Thank You.

答:
hmm, Add the data attribute in the parent option and give a value like data-parent='1'
and change value='car'

same you can do with child data-child='1' and value="toyota"

then simply target the data attribute in js and remove other options from the child options

ContentLicense: CC BY-SA 4.0

Title: How to get select value on form in php?

Body:
I want to get a selected value on the form.

Suppose If I select category "car" from sub-category "nissan".
I want this value on php.

Not value 1 and 1 because I do not recognise what value is selected.
I want name or unique value in my php file.

This is php file on the same page:

<?php

if(isset($_POST['select1'])){
    $select1 = $_POST['select1'];
}

if(isset($_POST['select2'])){
 $select2 = $_POST['select2'];
}

?>

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<select name="select1" id="select1">
 <option value=""></option>
 <option value="1">car</option>
 <option value="2">phone</option>
 <option value="3">tv</option>
</select>

<select name="select2" id="select2">
 <option value=""></option>
 <option value="1">toyota</option>
 <option value="1">nissan</option>
 <option value="1">bmw</option>
 <option value="2">Iphone</option>
 <option value="2">LG</option>
 <option value="2">Samsung</option>
 <option value="3">Philips</option>
 <option value="3">Samsung</option>
</select>
</form>

Any idea or suggestions would be welcome
Thank You.


问:
Count and Sum functions with help of ViewBag
I have a question how to solve my problem. There is a table with items. Each item has a status "open" or "closed". For instance, 9 items with "closed" status and 14 ones with "open". I need to find the difference between open and closed items (14 - 9 = 5). How can I do it with help of ViewBag? As I understood, it is required to write "count" function in controller and transmit the result to View via ViewBag. But I don't know how to write this code. The result should be shown on the View page.

Request.cs (Model):

```<code>public class Request
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string Status { get; set; } = "";
}

</code>```

Controller.cs:

```<code>public IActionResult Requests()
{
    var Requests = _repo.GetAllRequests();
    return View(Requests);
}

</code>```

Repository:

```<code>public Request GetRequest(int id)
{
    return _ctx.Requests.FirstOrDefault(c => c.Id == id);
}

public List<Request> GetAllRequests()
{
    return _ctx.Requests.ToList();
}

</code>```

View:

```<code><div>
    <table>
        @foreach (var request in Model)
        {
        <tr>
            <th>@request.Name</th>
            <th>@request.Status</th>
        </tr>
        }
    </table>
</div>
</code>```

答:
You would pass a predicate to Count to filter the requests by status:

```<code>public IActionResult Requests()
{
    var requests = _repo.GetAllRequests();

    ViewBag.OpenRequests = requests.Count(r => r.Status == "open");
    ViewBag.ClosedRequests = requests.Count(r => r.Status == "closed");

    return View(requests);
}
</code>```

However, rather than using the ViewBag you could create a view model to hold all the information/data required by the view:

```<code>// ViewModel
public class RequestViewModel
{
    public List<Request> Requests { get; set; }
    public int OpenRequests { get; set; }
    public int ClosedRequests { get; set; }
}

// Controller
public IActionResult Requests()
{
    var requests = _repo.GetAllRequests();

    var viewModel = new RequestViewModel();
    viewModel.OpenRequests = requests.Count(r => r.Status == "open");
    viewModel.ClosedRequests = requests.Count(r => r.Status == "closed");
    viewModel.Requests = requests;

    return View(viewModel);
}

// View: set the model for the view
@model Project.Namespace.RequestViewModel
...
<div>
    <div>Open Requests: @model.OpenRequests</div>
    <div>Closed Requests: @model.ClosedRequests</div>
    <div>Difference/delta: @(model.OpenRequests - model.ClosedRequests)</div>
</div>
</code>```

Body:
I have a question how to solve my problem. There is a table with items. Each item has a status "open" or "closed". For instance, 9 items with "closed" status and 14 ones with "open". I need to find the difference between open and closed items (14 - 9 = 5). How can I do it with help of ViewBag? As I understood, it is required to write "count" function in controller and transmit the result to View via ViewBag. But I don't know how to write this code. The result should be shown on the View page.

Request.cs (Model):

public class Request
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string Status { get; set; } = "";
}

Controller.cs:

public IActionResult Requests()
{
    var Requests = _repo.GetAllRequests();
    return View(Requests);
}

Repository:

public Request GetRequest(int id)
{
    return _ctx.Requests.FirstOrDefault(c => c.Id == id);
}

public List<Request> GetAllRequests()
{
    return _ctx.Requests.ToList();
}

View:

        @foreach (var request in Model)
        {

            @request.Name
            @request.Status

        }

Body:
You would pass a predicate to Count to filter the requests by status:

public IActionResult Requests()
{
    var requests = _repo.GetAllRequests();

    ViewBag.OpenRequests = requests.Count(r => r.Status == "open");
    ViewBag.ClosedRequests = requests.Count(r => r.Status == "closed");

    return View(requests);
}

However, rather than using the ViewBag you could create a view model to hold all the information/data required by the view:

// ViewModel
public class RequestViewModel
{
    public List<Request> Requests { get; set; }
    public int OpenRequests { get; set; }
    public int ClosedRequests { get; set; }
}

// Controller
public IActionResult Requests()
{
    var requests = _repo.GetAllRequests();

    var viewModel = new RequestViewModel();
    viewModel.OpenRequests = requests.Count(r => r.Status == "open");
    viewModel.ClosedRequests = requests.Count(r => r.Status == "closed");
    viewModel.Requests = requests;

    return View(viewModel);
}

// View: set the model for the view
@model Project.Namespace.RequestViewModel
...
<div>
    <div>Open Requests: @model.OpenRequests</div>
    <div>Closed Requests: @model.ClosedRequests</div>
    <div>Difference/delta: @(model.OpenRequests - model.ClosedRequests)</div>
</div>


问:
Advantage of switching from ASP.NET to bread & butter HTML/jQuery
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

```

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

```

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

答: This might be a paradigm shift, but if you are looking for more "bread and butter" and are comfortable working without asp.net server controls, Monorail might just be a good option for you.  It allows you what you are looking for, while being much lighter weight, an MVC based architecture as well.  I would recommend asp.net mvc if it were not for your .net 2.0 restriction. Since you are restricted, Monorail might just be a viable choice.</p>

OwnerDisplayName: Martin

ContentLicense: CC BY-SA 2.5

Body:
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

LastEditorDisplayName: Martin

OwnerDisplayName: Jeremy B.


问:
App crashes on simulator but works fine in device after upgrading to lion
My app is working fine on simulator all the while until i upgraded to OS Lion & xcode Version 4.1.

Now I got the error below.

EXC_BAD_ACCESS
warning: Unable to restore previously selected frame.

But It's working fine on iPhone.
Appreciate for any suggestion ...

答: Did you uninstall Xcode via the command line before you installed the new version? This is a crucial step that many seem to be missing. </p>

ContentLicense: CC BY-SA 3.0


问:
Prevent duplicate class generation (__1) with jsonschema2pojo
I have some json schema that I try to convert to pojo classes using jsonschema2pojo.

Unfortunately, I get some duplicated classes generated with an additional __1 postfix on the classname.

You can test this at https://www.jsonschema2pojo.org/.
Add this example and hit Preview:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "something": {
      "type": "object",
      "properties": {}
    },
    "other": {
      "type": "object",
      "properties": {
        "physical": {
          "$ref": "#/properties/something"
        }
      }
    }
  }
}
```

I get the classes Something and Something__1. They have the same code (except the class name).

I found other questions, where someone commented that one can change some ObjectRule and RuleFactory, but I don't want to patch the library.

Is there something with my schema or is this a bug?

答:
jung,

The below code might be working for you, I am facing the same issue for a week and walked through the lots of docs and references available.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
        "other": {
      "type": "object",
      "properties": {
        "physical": {
          "existingJavaType":"com.example.Something" // package name with class name
        }
      }
    },
    "something": {
      "type": "object"
    }

  }
}
```

Refer this

Body:
I have some json schema that I try to convert to pojo classes using jsonschema2pojo.

Unfortunately, I get some duplicated classes generated with an additional __1 postfix on the classname.

You can test this at https://www.jsonschema2pojo.org/.
Add this example and hit Preview:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "something": {
      "type": "object",
      "properties": {}
    },
    "other": {
      "type": "object",
      "properties": {
        "physical": {
          "$ref": "#/properties/something"
        }
      }
    }
  }
}

I get the classes Something and Something__1. They have the same code (except the class name).

I found other questions, where someone commented that one can change some ObjectRule and RuleFactory, but I don't want to patch the library.

Is there something with my schema or is this a bug?

Body:
jung,

The below code might be working for you, I am facing the same issue for a week and walked through the lots of docs and references available.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
        "other": {
      "type": "object",
      "properties": {
        "physical": {
          "existingJavaType":"com.example.Something" // package name with class name
        }
      }
    },
    "something": {
      "type": "object"
    }

  }
}

Refer this


问:
What is an INTERFACE IMPORTED library in CMake and what are its uses?
So far I've seen the INTERFACE library type used to describe header-only libraries, as it does not compile sources and does not produce library artifacts. The IMPORTED library type I've seen less of, but from what I've read it is used to describe precompiled libraries that are already on-disk.

I recently saw some code with the IMPORTED INTERFACE library type, and was confused as to why it was used. What properties does this type have, and what are some typical use-cases of this type?

答:
It's referring to a header-only library whose sources you don't control or are found in another build tree / in the system. Will most commonly be created in a Find module or CMake package config module.

Like other imported targets, and unlike non-imported targets, it doesn't have to be (and indeed cannot be) install()-ed if it appears in the INTERFACE_LINK_LIBRARIES property of an install()ed target transitively; instead, the resulting package will need to find_dependency the package.


问:
Highlight Cell above value
looking to highlight a cell based on a text criteria.

My file look like this dummy data:

```<code>Blue
Yellow
Red
Yellow
Blue
BLue
Blue
</code>```

I would like to highlight every cell above the word "Yellow" is there anyway to do this?

答:
Have you tried in this way, follow the steps, first in the adjacent column type the below formula as mentioned (Assuming the data is in Column A and starts from cell A1)

```<code>=((A1<>"Yellow")*(A2="Yellow"))=1
</code>```

To check whether it is giving you the expected result as you wanted for,

• Copy the formula,

• Select the range where you want to conditionally highlight,

• From Home Tab, Under Styles Group, Select Conditional Formatting,

• Click New,

• From New Formatting Rule,

• Select the last rule --> Use a formula to determine which cells to format,

• Place the above formula in the Edit the Rule Description

• Click Format from Fill Tab Choose desired color,

• Press Ok Twice and you are done!

Title: Highlight Cell above value

Body:
looking to highlight a cell based on a text criteria.

My file look like this dummy data:

Blue
Yellow
Red
Yellow
Blue
BLue
Blue

I would like to highlight every cell above the word "Yellow" is there anyway to do this?

Body:
Have you tried in this way, follow the steps, first in the adjacent column type the below formula as mentioned (Assuming the data is in Column A and starts from cell A1)

=((A1<>"Yellow")*(A2="Yellow"))=1

To check whether it is giving you the expected result as you wanted for,

• Copy the formula,

• Select the range where you want to conditionally highlight,

• From Home Tab, Under Styles Group, Select Conditional Formatting,

• Click New,

• From New Formatting Rule,

• Select the last rule --> Use a formula to determine which cells to format,

• Place the above formula in the Edit the Rule Description

• Click Format from Fill Tab Choose desired color,

• Press Ok Twice and you are done!


问:
Wrap typescript interface value types with some generic type
Is there a way in Typescript to wrap all interface's values into some generic type to get another interface?

I have interface which represents an object with class constructors:

```<code>interface MyConstructors {
  foo: typeof Foo;
  bar: typeof Bar;
  // ... etc (many lines here)
}
</code>```

Then I create instances of these classes:

```<code>const instances = {
  foo: new Foo(params),
  bar: new Bar(params)
};
</code>```

Interface of that object should look like

```<code>interface MyInstances {
  foo: InstanceType<typeof Foo>;
  bar: InstanceType<typeof Bar>;
  // ... etc (many lines here)
}
</code>```

As you can see it looks mostly the same as MyConstructors. So I'm looking for some way to avoid that duplication.

答:
You can use a mapped type:</p>
```<code>type MyInstanceType = {
  [key in keyof MyConstructors]: InstanceType<MyConstructors[key]>
}

// Same as:
// type MyInstanceType = {
//    foo: Foo;
//    bar: Bar;
//}
</code>```

Body:
Is there a way in Typescript to wrap all interface's values into some generic type to get another interface?

I have interface which represents an object with class constructors:

interface MyConstructors {
  foo: typeof Foo;
  bar: typeof Bar;
  // ... etc (many lines here)
}

Then I create instances of these classes:

const instances = {
  foo: new Foo(params),
  bar: new Bar(params)
};

Interface of that object should look like

interface MyInstances {
  foo: InstanceType<typeof Foo>;
  bar: InstanceType<typeof Bar>;
  // ... etc (many lines here)
}

As you can see it looks mostly the same as MyConstructors. So I'm looking for some way to avoid that duplication.

Body:
You can use a mapped type:

type MyInstanceType = {
  [key in keyof MyConstructors]: InstanceType<MyConstructors[key]>
}

// Same as:
// type MyInstanceType = {
//    foo: Foo;
//    bar: Bar;
//}


问:
Unable to start minikube and exiting due to PROVIDER_HYPERV_NOT_FOUND
We are getting the below error while running the command "minikube start --driver=hyperv" which was initially working properly but suddenly started giving an error.

C:\Windows\system32>minikube start --driver=hyperv

minikube v1.22.0 on Microsoft Windows 10 Enterprise 10.0.19043 Build 19043

Using the hyperv driver based on user configuration

Exiting due to PROVIDER_HYPERV_NOT_FOUND: The 'hyperv' provider was not found: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NonInteractive @(Get-Wmiobject Win32_ComputerSystem).HypervisorPresent returned "False\r\n"

Suggestion: Enable Hyper-V: Start PowerShell as Administrator, and run: 'Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All'

Documentation: https://minikube.sigs.k8s.io/docs/reference/drivers/hyperv/

We tried to disabled and enabled the "hyperv" from the Windows Features tab and then restarted the machine but it didn't work.

When we hit a command "systeminfo" we got the below, saying "hyperv" is enabled.

Hyper-V Requirements:
VM Monitor Mode Extensions: Yes

```<code>                  Virtualization Enabled In Firmware: Yes

                  Second Level Address Translation: Yes

                  Data Execution Prevention Available: Yes
</code>```

Now we have enabled the "hyperv", restarted the machine but still we are getting the error, could anyone please help us out in this?

Thanks in advance!!!

答:
Reason:  missing powershell.exe path

Resolution:  Add C:\Windows\System32\WindowsPowerShell\v1.0 into Environmental Variables... > System variables > Path

Body:
We are getting the below error while running the command "minikube start --driver=hyperv" which was initially working properly but suddenly started giving an error.

C:\Windows\system32>minikube start --driver=hyperv

minikube v1.22.0 on Microsoft Windows 10 Enterprise 10.0.19043 Build 19043

Using the hyperv driver based on user configuration

Exiting due to PROVIDER_HYPERV_NOT_FOUND: The 'hyperv' provider was not found: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NonInteractive @(Get-Wmiobject Win32_ComputerSystem).HypervisorPresent returned "False\r\n"

Suggestion: Enable Hyper-V: Start PowerShell as Administrator, and run: 'Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All'

Documentation: https://minikube.sigs.k8s.io/docs/reference/drivers/hyperv/

We tried to disabled and enabled the "hyperv" from the Windows Features tab and then restarted the machine but it didn't work.

When we hit a command "systeminfo" we got the below, saying "hyperv" is enabled.

Hyper-V Requirements:
VM Monitor Mode Extensions: Yes

                  Virtualization Enabled In Firmware: Yes

                  Second Level Address Translation: Yes

                  Data Execution Prevention Available: Yes

Now we have enabled the "hyperv", restarted the machine but still we are getting the error, could anyone please help us out in this?

Thanks in advance!!!


问:
Edit the Web.Config file
I'm attempting to update some values in the web.config file from code during an install process.

So far I've found this for updating the connection  string,

```<code>    ' Open Application's Web.Config
    Dim config = WebConfigurationManager.OpenWebConfiguration("/" + TargetVDir, friendlySiteName)

    'Add new connection string setting for web.config
    Dim appDatabase = New ConnectionStringSettings()
    appDatabase.Name = "TimeOffEntities"
    appDatabase.ConnectionString = EFconnectionstring

    config.ConnectionStrings.ConnectionStrings.Clear()
    config.ConnectionStrings.ConnectionStrings.Add(appDatabase)

    ' Persist web.config settings
    config.Save()
</code>```

However I need to update another section and I'm not sure how. I have the settings for an email and I'm not sure how to update them. Relevant web.config section below,

```<code><configuration>

  <system.net>
    <mailSettings>
      <smtp>
        <network
             host="relayServerHostname"
             port="portNumber"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>

</configuration>
</code>```

答: You'll need to roll out some XML parsing of your own. Or better yet, if you're on .NET 4 use config file transforms.</p>

Title: Edit the Web.Config file

Body:
I'm attempting to update some values in the web.config file from code during an install process.

So far I've found this for updating the connection  string,

    ' Open Application's Web.Config
    Dim config = WebConfigurationManager.OpenWebConfiguration("/" + TargetVDir, friendlySiteName)

    'Add new connection string setting for web.config
    Dim appDatabase = New ConnectionStringSettings()
    appDatabase.Name = "TimeOffEntities"
    appDatabase.ConnectionString = EFconnectionstring

    config.ConnectionStrings.ConnectionStrings.Clear()
    config.ConnectionStrings.ConnectionStrings.Add(appDatabase)

    ' Persist web.config settings
    config.Save()

However I need to update another section and I'm not sure how. I have the settings for an email and I'm not sure how to update them. Relevant web.config section below,

<configuration>

  <system.net>
    <mailSettings>
      <smtp>
        <network
             host="relayServerHostname"
             port="portNumber"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>

</configuration>


问:
Getting Null in all column for Snowflake even though data is present
.I am working on a Snowflake table. I am getting a Null value on every column even though data is present in JSON. Can you please help me on this issue.

```<code>create or replace external table "database_name"."schema"."TABLE_Name"
(Name varchar(20) as ( value:Name::varchar),
Surname varchar(20) as (value:Surname::varchar),
City varchar(20) as (value:City::varchar),
Country varchar(20) as (value:Country::varchar),
Age varchar(20) as (value:Age::varchar),
date_part date as to_date(split_part(metadata$filename, '/', 2)
|| '/' || split_part(metadata$filename, '/', 3)
|| '/' || split_part(metadata$filename, '/', 4), 'YYYY/MM/DD'))
partition by (date_part)
location = @stage/logs/
file_format = parquet;
</code>```

答:
JSON properties are case sensitive. If you specify a nonexistent property name it will return null. Correcting the case for the JSON properties should fix this.</p>
```<code>create or replace external table "database_name"."schema"."TABLE_Name"
(Name varchar(20) as ( value:NAME::varchar),
Surname varchar(20) as (value:SURNAME::varchar),
City varchar(20) as (value:CITY::varchar),
Country varchar(20) as (value:COUNTRY::varchar),
Age varchar(20) as (value:AGE::varchar),
date_part date as to_date(split_part(metadata$filename, '/', 2)
|| '/' || split_part(metadata$filename, '/', 3)
|| '/' || split_part(metadata$filename, '/', 4), 'YYYY/MM/DD'))
partition by (date_part)
location = @stage/logs/
file_format = parquet;
</code>```

Body:
.I am working on a Snowflake table. I am getting a Null value on every column even though data is present in JSON. Can you please help me on this issue.

create or replace external table "database_name"."schema"."TABLE_Name"
(Name varchar(20) as ( value:Name::varchar),
Surname varchar(20) as (value:Surname::varchar),
City varchar(20) as (value:City::varchar),
Country varchar(20) as (value:Country::varchar),
Age varchar(20) as (value:Age::varchar),
date_part date as to_date(split_part(metadata$filename, '/', 2)
|| '/' || split_part(metadata$filename, '/', 3)
|| '/' || split_part(metadata$filename, '/', 4), 'YYYY/MM/DD'))
partition by (date_part)
location = @stage/logs/
file_format = parquet;

Body:
JSON properties are case sensitive. If you specify a nonexistent property name it will return null. Correcting the case for the JSON properties should fix this.

create or replace external table "database_name"."schema"."TABLE_Name"
(Name varchar(20) as ( value:NAME::varchar),
Surname varchar(20) as (value:SURNAME::varchar),
City varchar(20) as (value:CITY::varchar),
Country varchar(20) as (value:COUNTRY::varchar),
Age varchar(20) as (value:AGE::varchar),
date_part date as to_date(split_part(metadata$filename, '/', 2)
|| '/' || split_part(metadata$filename, '/', 3)
|| '/' || split_part(metadata$filename, '/', 4), 'YYYY/MM/DD'))
partition by (date_part)
location = @stage/logs/
file_format = parquet;


问:
How to make 'copies' of variables that all connect back to the original variable
I need to sort students into classes based on their preferences and I am planning to use the Hungarian Algorithm to sort them. The problem that I am running into though is that there are more people than classes and each class has a minimum number of people that it needs to have.

In my dataset, there are ~550 students, and each one has a list of top 5 preferences. Every preference is an ID that corresponds to a class. Each class has a minimum and maximum capacity (in my case a min cap of 15 people and a max cap of 27 people) and there are 21 classes in the dataset.

Here is an example dataset for every student:

Email
first choice
second choice
third choice
fourth choice
fith choice

email@gmail.com
4
7
1
8
21

email2@gmail.com
6
9
14
17
2

Here is an example dataset for every class:

Class Title
Class ID
Min Cap
Max Cap

Class Title1
1
15
27

Class Title2
2
15
27

Class Title3
3
15
27

Because there are ~550 students and 21 classes and for the Hungarian algorithm to work, I was planning to make "copies" of the classes. I would first make 15 copies of every class (like class 1.1, 1.2, 1.3, 1.4, 2.1, 2.2, 2.3, etc.) to fill the minimum requirement of the class and then would add even more copies to the most popular classes among the students until there is an equal number of students and copies of classes.

My question is: how would I loop the copying of the variables that would, in the algorithm act like their own classes or choices for classes (since the choices would also need to be different as to put the people to different copies of the same class and not have them compete for only one variable when there are other copies of it) but then after the sorting is done, the copies could be traced back to the original?

Thank you in advance and let me know if there is anything I can clarify

答:
You should know that some types in Python are mutable types, one of them is the list type:

```<code>>>> a = []
>>> a.append('.')
>>> a
['.']
>>> b = a
>>> b.append('$')
>>> a
['.', '$']
</code>```

You may describe a list in Python like a pointer that points toward the cells.

An other example may be this:

```<code>>>> def foo(n: int):
        i+=1
>>> i = 2
>>> foo(i)
>>> i
2
</code>```

As you can see the i variable is not passed by reference, since it's an immutable typed variable. But look at this:

```<code>>>> def baz(n: list[int]):
        n[0]+=1
>>> i = [2]
>>> baz(i)
>>> i
[3]
</code>```

The same thing is true for dicts, so that if you want to have a copy [indipendent from the original] of that dictionary you will have to do something like this:

```<code>newDict = oldDict.copy()
</code>```

So, if you need a short answer:

How to make 'copies' of variables that all connect back to the original variable?

You just have to create them with b = a

Body:
You should know that some types in Python are mutable types, one of them is the list type:

>>> a = []
>>> a.append('.')
>>> a
['.']
>>> b = a
>>> b.append('$')
>>> a
['.', '$']

You may describe a list in Python like a pointer that points toward the cells.

An other example may be this:

>>> def foo(n: int):
        i+=1
>>> i = 2
>>> foo(i)
>>> i
2

As you can see the i variable is not passed by reference, since it's an immutable typed variable. But look at this:

>>> def baz(n: list[int]):
        n[0]+=1
>>> i = [2]
>>> baz(i)
>>> i
[3]

The same thing is true for dicts, so that if you want to have a copy [indipendent from the original] of that dictionary you will have to do something like this:

newDict = oldDict.copy()

So, if you need a short answer:

How to make 'copies' of variables that all connect back to the original variable?

You just have to create them with b = a


问:
Airflow - Copy blob from/to Google Cloud Storage within 2 different projects
I'm trying to copy a blob from the GCS bucket A in the project X to the bucket B in the project Y using Airflow.

It seems that the available operator (GCSToGCSOperator) works well only between two buckets within the same project.

How can I have achieve the copy in my case?

I'd like to avoid using a BashOperator...

Thanks!!

答:
Option 1:
Using CloudDataTransferServiceCreateJobOperator which creates a transfer job using Google API. You can find information about it in docs. Note that this require the service account to have access to both. If this is not the case then it's not supported yet See Use Google Storage Transfer API to transfer data from external GCS into my GCS

Option 2:
Use GCSToLocalFilesystemOperator with project 1 and then LocalFilesystemToGCSOperator using project 2.

A skeleton of this solution:

```<code>from airflow import DAG
from airflow.providers.google.cloud.transfers.local_to_gcs import LocalFilesystemToGCSOperator
from airflow.providers.google.cloud.transfers.gcs_to_local import GCSToLocalFilesystemOperator

with DAG(
    "example", schedule_interval="@daily", start_date=datetime(2021, 1, 1), catchup=False
) as dag:
    download = GCSToLocalFilesystemOperator(
        task_id="download_task",
        bucket='some_bucket',
        filename='/tmp/fake1.csv',
        object_name="test/test1.csv",
        gcp_conn_id='google_cloud_origin'
    )

    upload = LocalFilesystemToGCSOperator(
        task_id='upload_task',
        bucket='some_bucket',
        src='/tmp/fake1.csv',
        dst='test/test1.csv',
        gcp_conn_id='google_cloud_dest'
    )

    download >> upload
</code>```

Though this is not ideal solution. It really depends on the volumes and frequency of your job. With this solution you are transferring files via the local disk - in small volumes it can be fine. This solution will work in cases of two distinct accounts as each operator is associated to a different Google connection.

Body:
Option 1:
Using CloudDataTransferServiceCreateJobOperator which creates a transfer job using Google API. You can find information about it in docs. Note that this require the service account to have access to both. If this is not the case then it's not supported yet See Use Google Storage Transfer API to transfer data from external GCS into my GCS

Option 2:
Use GCSToLocalFilesystemOperator with project 1 and then LocalFilesystemToGCSOperator using project 2.

A skeleton of this solution:

from airflow import DAG
from airflow.providers.google.cloud.transfers.local_to_gcs import LocalFilesystemToGCSOperator
from airflow.providers.google.cloud.transfers.gcs_to_local import GCSToLocalFilesystemOperator

with DAG(
    "example", schedule_interval="@daily", start_date=datetime(2021, 1, 1), catchup=False
) as dag:
    download = GCSToLocalFilesystemOperator(
        task_id="download_task",
        bucket='some_bucket',
        filename='/tmp/fake1.csv',
        object_name="test/test1.csv",
        gcp_conn_id='google_cloud_origin'
    )

    upload = LocalFilesystemToGCSOperator(
        task_id='upload_task',
        bucket='some_bucket',
        src='/tmp/fake1.csv',
        dst='test/test1.csv',
        gcp_conn_id='google_cloud_dest'
    )

    download >> upload

Though this is not ideal solution. It really depends on the volumes and frequency of your job. With this solution you are transferring files via the local disk - in small volumes it can be fine. This solution will work in cases of two distinct accounts as each operator is associated to a different Google connection.


问:
How can I get the right calculations for the total of the coin change calculator?
I am new at programming and I want to get better at it. I am working on a change calculator that accepts five arguments(dollars, quarters, dimes, nickels, pennies) and calculates the total amount of change. When I put change.py in the command line followed by 1 1 1 1 1 I am supposed to get 1.41 as the total but I am getting 1.95. Can anyone help with this? Thank you!</p>
```<code>import sys

def change(dollars,quarters,dimes,nickels,pennies):

    dollars = int(float(dollars))
    quarters = int(float(quarters))
    dimes = int(float(dimes))
    nickels = int(float(nickels))
    pennies = int(float(pennies))

    total = (dollars * 100) + (quarters * 0.25 ) + (dimes * 0.10) + (nickels * 0.5) + (pennies * 0.1)

dollars = sys.argv[1]
quarters = sys.argv[2]
dimes = sys.argv[3]
nickels = sys.argv[4]
pennies = sys.argv[5]

print('The total value of your change is ',(total))

change(dollars,quarters,dimes,nickels,pennies)

IndexError                                Traceback (most recent call
last)
<ipython-input-10-6fd4ec30e3dc> in <module>
 16 dollars = sys.argv[1]
 17 quarters = sys.argv[2]
 ---> 18 dimes = sys.argv[3]
 19 nickels = sys.argv[4]
 20 pennies = sys.argv[5]

 IndexError: list index out of range
</code>```

答:
With the code you have you need to ensure you are passing those arugments in the command line when you run your code:

python coinprogram.py 1 2 3 4 5

I also noticed the change is not being calculated correctly
try this out:

import sys

dollars = sys.argv[1]
quarters = sys.argv[2]
dimes = sys.argv[3]
nickels = sys.argv[4]
pennies = sys.argv[5]

def change(dollars, quarters, dimes, nickels, pennies):

    dollars = int(float(dollars))
    quarters = int(float(quarters))
    dimes = int(float(dimes))
    nickels = int(float(nickels))
    pennies = int(float(pennies))

    return ((dollars * 100) + (quarters * 25) + (dimes * 10) + (nickels * 5) + (pennies * 1)) / 100

total = change(dollars, quarters, dimes, nickels, pennies)
print('The total value of your change is ', (total))
```
<p>if you would prefer to get user input within the program then you could do something like this instead:</p>
<pre class="lang-python prettyprint-override"><code>import sys

dollars = input("Enter dollars: ")
quarters = input("Enter quarters: ")
dimes = input("Enter dimes: ")
nickels = input("Enter nickels: ")
pennies = input("Enter pennies: ")

def change(dollars, quarters, dimes, nickels, pennies):

    dollars = int(float(dollars))
    quarters = int(float(quarters))
    dimes = int(float(dimes))
    nickels = int(float(nickels))
    pennies = int(float(pennies))

    return ((dollars * 100) + (quarters * 25) + (dimes * 10) + (nickels * 5) + (pennies * 1)) / 100

total = change(dollars, quarters, dimes, nickels, pennies)
print('The total value of your change is ', (total))

</code>```

Body:
I am new at programming and I want to get better at it. I am working on a change calculator that accepts five arguments(dollars, quarters, dimes, nickels, pennies) and calculates the total amount of change. When I put change.py in the command line followed by 1 1 1 1 1 I am supposed to get 1.41 as the total but I am getting 1.95. Can anyone help with this? Thank you!

import sys

def change(dollars,quarters,dimes,nickels,pennies):

    dollars = int(float(dollars))
    quarters = int(float(quarters))
    dimes = int(float(dimes))
    nickels = int(float(nickels))
    pennies = int(float(pennies))

    total = (dollars * 100) + (quarters * 0.25 ) + (dimes * 0.10) + (nickels * 0.5) + (pennies * 0.1)

dollars = sys.argv[1]
quarters = sys.argv[2]
dimes = sys.argv[3]
nickels = sys.argv[4]
pennies = sys.argv[5]

print('The total value of your change is ',(total))

change(dollars,quarters,dimes,nickels,pennies)

IndexError                                Traceback (most recent call
last)
<ipython-input-10-6fd4ec30e3dc> in <module>
 16 dollars = sys.argv[1]
 17 quarters = sys.argv[2]
 ---> 18 dimes = sys.argv[3]
 19 nickels = sys.argv[4]
 20 pennies = sys.argv[5]

 IndexError: list index out of range

Body:
With the code you have you need to ensure you are passing those arugments in the command line when you run your code:

python coinprogram.py 1 2 3 4 5

I also noticed the change is not being calculated correctly
try this out:

import sys

dollars = sys.argv[1]
quarters = sys.argv[2]
dimes = sys.argv[3]
nickels = sys.argv[4]
pennies = sys.argv[5]

def change(dollars, quarters, dimes, nickels, pennies):

    dollars = int(float(dollars))
    quarters = int(float(quarters))
    dimes = int(float(dimes))
    nickels = int(float(nickels))
    pennies = int(float(pennies))

    return ((dollars * 100) + (quarters * 25) + (dimes * 10) + (nickels * 5) + (pennies * 1)) / 100

total = change(dollars, quarters, dimes, nickels, pennies)
print('The total value of your change is ', (total))

if you would prefer to get user input within the program then you could do something like this instead:

import sys

dollars = input("Enter dollars: ")
quarters = input("Enter quarters: ")
dimes = input("Enter dimes: ")
nickels = input("Enter nickels: ")
pennies = input("Enter pennies: ")

def change(dollars, quarters, dimes, nickels, pennies):

    dollars = int(float(dollars))
    quarters = int(float(quarters))
    dimes = int(float(dimes))
    nickels = int(float(nickels))
    pennies = int(float(pennies))

    return ((dollars * 100) + (quarters * 25) + (dimes * 10) + (nickels * 5) + (pennies * 1)) / 100

total = change(dollars, quarters, dimes, nickels, pennies)
print('The total value of your change is ', (total))


问:
How to view the rendered (raw) query from a MySQLi prepared statement?
I'm building a logging class for my PHP/MySQLi app.  I can obviously log the raw prepared statement (with question marks), but without manually parsing it, is there anyway to see the actual raw query executed in MySQL?

Thanks!

答:
Turn on query logging in MySQL and monitor the mysql query log file.

In your my.cnf or my.ini file in the mysqld section add a directive:

```<code>log = /path/to/my/log/file
</code>```

Body:
Turn on query logging in MySQL and monitor the mysql query log file.

In your my.cnf or my.ini file in the mysqld section add a directive:

log = /path/to/my/log/file


问:
Working postgresql query to native hibernate query PSQLException syntax error
I have the below postgresql query which works fine if used directly on the db:

```<code>select memory_inmb from app where dt=(select dt from app where org='AAAA'

AND to_timestamp(dt/1000) >= date_trunc('month', '2021-07-01 06:07:07+00'::timestamp)

AND to_timestamp(dt/1000) < date_trunc('month', '2021-08-01 06:07:07+00'::timestamp)

limit 1) AND org='AAAA';
</code>```

In my repository I wrote it as a native query like this:

```<code>@Query(value="select a.memory_inmb from app a where a.dt=(select a.dt from app a where a.org='AAAA' AND to_timestamp(a.dt/1000) >= date_trunc('month', '2021-07-01 06:07:07+00'::timestamp) AND to_timestamp(a.dt/1000) < date_trunc('month', '2021-08-01 06:07:07+00'::timestamp) limit 1) AND a.org='AAAA'", nativeQuery = true)

List<BigInteger> findMemory();
</code>```

In my implementation class for now I just call return this.appRepository.findMemory();

This gives me the following syntax exception:

```<code>org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
  Position: 148
</code>```

How come I can run the query directly on the db just fine, but using it as native query doesn't work?

答:
Colons need to be escaped, so :: for JPA should become \\:\\:, as explained here: https://stackoverflow.com/a/32076541

(for JPA : indicates a named parameter)

In your case you may also replace the :: cast by the CAST (myData as timestamp) syntax.

Body:
I have the below postgresql query which works fine if used directly on the db:

select memory_inmb from app where dt=(select dt from app where org='AAAA'

AND to_timestamp(dt/1000) >= date_trunc('month', '2021-07-01 06:07:07+00'::timestamp)

AND to_timestamp(dt/1000) < date_trunc('month', '2021-08-01 06:07:07+00'::timestamp)

limit 1) AND org='AAAA';

In my repository I wrote it as a native query like this:

@Query(value="select a.memory_inmb from app a where a.dt=(select a.dt from app a where a.org='AAAA' AND to_timestamp(a.dt/1000) >= date_trunc('month', '2021-07-01 06:07:07+00'::timestamp) AND to_timestamp(a.dt/1000) < date_trunc('month', '2021-08-01 06:07:07+00'::timestamp) limit 1) AND a.org='AAAA'", nativeQuery = true)

List<BigInteger> findMemory();

In my implementation class for now I just call return this.appRepository.findMemory();

This gives me the following syntax exception:

org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
  Position: 148

How come I can run the query directly on the db just fine, but using it as native query doesn't work?


问:
I thought that strings are immutable?
I've always thought that strings and tuples are immutable in Python. But now I've been confused with this function that I wrote (down below). When it's executed, I get a mutable string indeed. Am I missing something here?

```<code>def example():
    string = "/*Jon is @developer & musician"
    for char in string:
        if not char.isalpha():
            string = string.replace(char, '#')
    return(string)
</code>```

Output:

```<code>>>> example()
'##Jon#is##developer###musician'
>>>
</code>```

Thanks in advance for your explanation!

答:
The string's replace method is not a in-place function. It creates a new string.

If instead you tried to run string[0] = "a" for example, you would have gotten an error.

Title: I thought that strings are immutable?

Body:
I've always thought that strings and tuples are immutable in Python. But now I've been confused with this function that I wrote (down below). When it's executed, I get a mutable string indeed. Am I missing something here?

def example():
    string = "/*Jon is @developer & musician"
    for char in string:
        if not char.isalpha():
            string = string.replace(char, '#')
    return(string)

Output:

>>> example()
'##Jon#is##developer###musician'
>>>

Thanks in advance for your explanation!


问:
Best practices writing JavaScript that uses AJAX call to decide if default action should be prevented
I'm using JavaScript and jQuery to write a handler for my form being submitted. Based on certain conditions, the handler may allow or prevent the form from submitting.

This is straight forward but is made more complex by the fact that the handler needs to make an AJAX call.

The issue is that my handler will return right away with true or false, but I won't get the response from the AJAX call until later. But I need the result from the AJAX call to decide what the return value should be.

Seems like this must surely be a common scenario. Are there best practices for handling this case?

答:
My answer on basis what was discussed shortly in the comments, there are (at least) two possible solutions.

Async/await:

Wait for the ajax call to finish and prevent default behavior based on the response. (await $.ajax / await $.post/get)

Prevent by default (as mentioned by @freedomn-m)

You could prevent the default behavior always, wait for the ajax call to finish and execute the desired behavior afterwards. For example with withholding a form submit.

```<code>e.preventDefault();
$ajax...
...
...
if (should_not_be_prevented) {
  $("#myForm").submit()
}
</code>```

Body:
My answer on basis what was discussed shortly in the comments, there are (at least) two possible solutions.

Async/await:

Wait for the ajax call to finish and prevent default behavior based on the response. (await $.ajax / await $.post/get)

Prevent by default (as mentioned by @freedomn-m)

You could prevent the default behavior always, wait for the ajax call to finish and execute the desired behavior afterwards. For example with withholding a form submit.

e.preventDefault();
$ajax...
...
...
if (should_not_be_prevented) {
  $("#myForm").submit()
}


问:
How to pass the latitude and longitude values to the ns url?
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

```<code>NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
</code>```

I write this one in below method for get and pass the latitude and longitude values.

```<code>- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}
</code>```

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method. Or Is there any way to pass that values in any other method.

答:
You can pass the latitude and longitude when the location manager finds new location to Google API:</p>

```<code>NSString *address = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=csv", newLocation.lattitude, newLocation.longitude];
NSURL *url = [NSURL URLFromString:address];
</code>```

Body:
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];

I write this one in below method for get and pass the latitude and longitude values.

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method. Or Is there any way to pass that values in any other method.

Body:
You can pass the latitude and longitude when the location manager finds new location to Google API:

NSString *address = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=csv", newLocation.lattitude, newLocation.longitude];
NSURL *url = [NSURL URLFromString:address];


问:
Partial function with default argument that is being changed later. Should there be any difference between mutable and non mutable objects?
I am learning about partial functions in python. I read that when you are specifying arguments to run your functions with, they get "baked" into function the same as normal functions with default arguments.

Here is what I mean:

```<code>def multiply(item, multiplier):
    return item * multiplier

my_item = 10
my_multiplier = 2

my_partial = partial(multiply, my_item, my_multiplier)

print(my_partial())  # 20

my_item = 5

print(my_partial())  # 20
</code>```

But I was also reading that it should work different when argument is mutable, here:

```<code>def multiply(item, multiplier):
    return item * multiplier

my_item = ['a']
my_multiplier = 2

my_partial = partial(multiply, my_item, my_multiplier)

print(my_partial())  # ['a', 'a']

my_item = ['a', 'b', 'c']

print(my_partial())  # also ['a', 'a'] instead of ['a', 'b', 'c', 'a', 'b', 'c'] ?
</code>```

I wanted to ask if, if I found a mistake or it was working like that with mutable object in previous versions of Python? I checked 3.9 and 3.7 and result is the same.

答:
You aren't mutating the object, you're reassigning the name, and the partial object still has a reference to the old object.

Try

```<code>my_item[:] = ['a', 'b', 'c']
</code>```

to actually mutate the same object.

Body:
I am learning about partial functions in python. I read that when you are specifying arguments to run your functions with, they get "baked" into function the same as normal functions with default arguments.

Here is what I mean:

def multiply(item, multiplier):
    return item * multiplier

my_item = 10
my_multiplier = 2

my_partial = partial(multiply, my_item, my_multiplier)

print(my_partial())  # 20

my_item = 5

print(my_partial())  # 20

But I was also reading that it should work different when argument is mutable, here:

def multiply(item, multiplier):
    return item * multiplier

my_item = ['a']
my_multiplier = 2

my_partial = partial(multiply, my_item, my_multiplier)

print(my_partial())  # ['a', 'a']

my_item = ['a', 'b', 'c']

print(my_partial())  # also ['a', 'a'] instead of ['a', 'b', 'c', 'a', 'b', 'c'] ?

I wanted to ask if, if I found a mistake or it was working like that with mutable object in previous versions of Python? I checked 3.9 and 3.7 and result is the same.

Body:
You aren't mutating the object, you're reassigning the name, and the partial object still has a reference to the old object.

Try

my_item[:] = ['a', 'b', 'c']

to actually mutate the same object.