问:
Spartacus 4.2 - Type '"before"' is not assignable to type 'OutletPosition'
While trying to customize the navigation slot, we are getting the error

Type '"before"' is not assignable to type 'OutletPosition'.

This is the code we are trying.

Also have tried

[cxOutletPos]=“outletPosition.BEFORE”

Documentation referred for Spartacus 4.2 :

https://sap.github.io/spartacus-docs/outlets/#template-driven-outlets

Result should be something like custom info, followed by navigation bar as shown below:

Also, as the above method didn't work I tried retrieving data through let-model for manipulation.
Array I want to retrieve data from into our component: CategoryNavigationComponent.
But using let-model and Printing model object I can see only "uid" , "typeCode" and "flexType" but not the navigatioNode and Children.

Is there any way to retrieve Navigation bar or Children array data on the screen?

答:
```<code>****in TS File:****
  settingsSubmenu: any = [];

constructor(public component: CmsComponentData<any> )
{
   this.component.data$.forEach(element => {
     element.navigationNode.children.forEach(child => {
      this.settingsSubmenu.push(child)
     });
    });
}
**in HTML File**

 <ng-container *ngFor="let menuItem of settingsSubmenu">
                        <a mat-menu-item >{{menuItem.title}}</a>
  </ng-container>
</code>```


来源: stackexchange

问:
How can I pass variable numbers into PayPal REST API and give customers a receipt?
I am building a lottery web application where customers can select their own numbers or get 4 random numbers. How can I carry these numbers that the customer inputs/randomly generates into my shopping cart / paypal button? Thanks for any help. This is my code so far for the generation of random lottery numbers on JSP page.

```<code><div id="num1" class="ball col-md-2"><span id="one"></span></div>
<div id="num2" class="ball col-md-2"><span id="two"></span></div>
<div id="num3" class="ball col-md-2"><span id="three"></span></div>
<div id="num4" class="ball col-md-2"><span id="four"></span></div>

 <%-- onclick to execute JavaScript function--%>
 <button onclick="random()">QuickPick!</button>
</div>

</code>```

This is the JS file to execute the random numbers to be generated.

```<code>function random(){
 //selects the 4 circles on the page
var one= document.getElementById('one');
var two= document.getElementById('two');
var three= document.getElementById('three');
var four= document.getElementById('four');

//create random number for each of the circles between 1-30
var a = Math.floor(Math.random()*30);
var b = Math.floor(Math.random()*30);
var c = Math.floor(Math.random()*30);
var d = Math.floor(Math.random()*30);

//put the random number into each of the 4 circles
one.textContent = a;
two.textContent = b;
three.textContent = c;
four.textContent = d;

}
</code>```

I have set up a PayPal REST API integration by following instructions on the website, I also can use a buy now smart button from PayPal. My question is, how can I issue the customers a receipt of the numbers they have selected up successful purchase of the ticket? Is there a way to pass the values of the JS code into the PayPal checkout page, any help is greatly appreciated as I cannot find a way to do this, thanks.

答:
In the Integrate Checkout guide, see the bullet #6 which has this example of transferring item information to PayPal:

    createOrder: function(data, actions) {
      return actions.order.create({
         "purchase_units": [{
            "amount": {
              "currency_code": "USD",
              "value": "100",
              "breakdown": {
                "item_total": {  /* Required when including the `items` array */
                  "currency_code": "USD",
                  "value": "100"
                }
              }
            },
            "items": [
              {
                "name": "First Product Name", /* Shows within upper-right dropdown during payment approval */
                "description": "Optional descriptive text..", /* Item details will also be in the completed paypal.com transaction view */
                "unit_amount": {
                  "currency_code": "USD",
                  "value": "50"
                },
                "quantity": "2"
              },
            ]
          }]
      });
    },
```

You can pass the same type of line item information whether using actions.order.create to create the order in the client side JS, or the REST API to create the order on the server. It is the same Orders v2 JSON format either way.

(A server-side REST API integration to create and capture the order is the most robust way; you can pair this with a JS SDK button for approval per the guide in bullet #5 of the above link.)

ContentLicense: CC BY-SA 4.0

Body:
I am building a lottery web application where customers can select their own numbers or get 4 random numbers. How can I carry these numbers that the customer inputs/randomly generates into my shopping cart / paypal button? Thanks for any help. This is my code so far for the generation of random lottery numbers on JSP page.

 <%-- onclick to execute JavaScript function--%>
 <button onclick="random()">QuickPick!</button>

This is the JS file to execute the random numbers to be generated.

function random(){
 //selects the 4 circles on the page
var one= document.getElementById('one');
var two= document.getElementById('two');
var three= document.getElementById('three');
var four= document.getElementById('four');

//create random number for each of the circles between 1-30
var a = Math.floor(Math.random()*30);
var b = Math.floor(Math.random()*30);
var c = Math.floor(Math.random()*30);
var d = Math.floor(Math.random()*30);

//put the random number into each of the 4 circles
one.textContent = a;
two.textContent = b;
three.textContent = c;
four.textContent = d;

}

I have set up a PayPal REST API integration by following instructions on the website, I also can use a buy now smart button from PayPal. My question is, how can I issue the customers a receipt of the numbers they have selected up successful purchase of the ticket? Is there a way to pass the values of the JS code into the PayPal checkout page, any help is greatly appreciated as I cannot find a way to do this, thanks.

Body:
In the Integrate Checkout guide, see the bullet #6 which has this example of transferring item information to PayPal:

    createOrder: function(data, actions) {
      return actions.order.create({
         "purchase_units": [{
            "amount": {
              "currency_code": "USD",
              "value": "100",
              "breakdown": {
                "item_total": {  /* Required when including the `items` array */
                  "currency_code": "USD",
                  "value": "100"
                }
              }
            },
            "items": [
              {
                "name": "First Product Name", /* Shows within upper-right dropdown during payment approval */
                "description": "Optional descriptive text..", /* Item details will also be in the completed paypal.com transaction view */
                "unit_amount": {
                  "currency_code": "USD",
                  "value": "50"
                },
                "quantity": "2"
              },
            ]
          }]
      });
    },

You can pass the same type of line item information whether using actions.order.create to create the order in the client side JS, or the REST API to create the order on the server. It is the same Orders v2 JSON format either way.

(A server-side REST API integration to create and capture the order is the most robust way; you can pair this with a JS SDK button for approval per the guide in bullet #5 of the above link.)


问:
Simple HttpRequestMessage but not working
I'm writing a simple dotnet core API, under search controller which like below :

```<code>[HttpGet("order")]
public async Task <Order> SearchOrder(string ordername, int siteid) {
    return await service.getorder(ordername,siteid)
}
</code>```

The swagger UI where the path https://devehost/search/order test pretty work, but when I use another client to call this api by below

```<code>client = new HttpClient {
    BaseAddress = new Uri("https://devehost")
};

var request = new HttpRequestMessage(HttpMethod.Get, "Search/order")  {
    Content = new FormUrlEncodedContent(
        new List<KeyValuePair<string, string>> {
            new("ordername", "pizza-1"),
            new("siteid", "1"),
       })
};

var response = await client.SendAsync(request);
</code>```

The status code always return bad request. But the postman is work, can I know the problem inside?

Thank you

答:
For a GET request, the parameters should be sent in the querystring, not the request body.

GET - HTTP | MDN

Note: Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined.

For .NET Core, you can use the Microsoft.AspNetCore.WebUtilities.QueryHelpers class to append the parameters to the URL:

```<code>Dictionary<string, string> parameters = new()
{
    ["ordername"] = "pizza-1",
    ["siteid"] = "1",
};

string url = QueryHelpers.AppendQueryString("Search/order", parameters);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
using var response = await client.SendAsync(request);
</code>```

Body:
I'm writing a simple dotnet core API, under search controller which like below :

[HttpGet("order")]
public async Task <Order> SearchOrder(string ordername, int siteid) {
    return await service.getorder(ordername,siteid)
}

The swagger UI where the path https://devehost/search/order test pretty work, but when I use another client to call this api by below

client = new HttpClient {
    BaseAddress = new Uri("https://devehost")
};

var request = new HttpRequestMessage(HttpMethod.Get, "Search/order")  {
    Content = new FormUrlEncodedContent(
        new List<KeyValuePair<string, string>> {
            new("ordername", "pizza-1"),
            new("siteid", "1"),
       })
};

var response = await client.SendAsync(request);

The status code always return bad request. But the postman is work, can I know the problem inside?

Thank you

Body:
For a GET request, the parameters should be sent in the querystring, not the request body.

GET - HTTP | MDN

Note: Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined.

For .NET Core, you can use the Microsoft.AspNetCore.WebUtilities.QueryHelpers class to append the parameters to the URL:

Dictionary<string, string> parameters = new()
{
    ["ordername"] = "pizza-1",
    ["siteid"] = "1",
};

string url = QueryHelpers.AppendQueryString("Search/order", parameters);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
using var response = await client.SendAsync(request);


问:
Reduce Pollyfill
I was playing around with this array reduce polyfill and I'm just confused why is he/she using apply. I know that apply adds this context in the execution. But I don't know why we need it here, I just tried without it, and it works fine too.

```<code>Array.prototype.reduce = function (cb, initialValue) {
  console.log('inside my reducer');
  if (!cb || typeof cb !== 'function') throw TypeError();
  var len = this.length;
  var i = 0;
  console.log('this', this);
  if (typeof initialValue === 'undefined' || initialValue === null) {
    initialValue = this[0];
    ++i;
  }

  for (; i < len; i++) {
    initialValue = cb.apply(this, [initialValue, this[i], i, this]);

    //comment the line above and uncomment this line and it will work fine
    //initialValue = cb(initialValue, this[i]);

  }

  return initialValue;
};
</code>```
```<code>[1, 2, 1, 1].reduce((a, b) => a + b, 0); => 5
</code>```

So, I'm a little confused, if anyone could share some insights it'll be apreciated.
Thanks!

答:
Wherever you got that polyfill, it's incorrect, in a couple of ways but in particular that initialValue = cb.apply(this, [initialValue, this[i], i, this]); should be using undefined, not this, in the first argument. reduce always calls its callback with this set to undefined (it'll end up being the global object if the callback is in loose mode rather than strict mode). So either initialValue = cb.apply(undefined, [initialValue, this[i], i, this]); or (more directly) initialValue = cb(initialValue, this[i], i, this);

Separately, it makes no sense to use apply and create an array to provide to it rather than using call with the discrete values it already has. Also, continuing to use something called initialValue for the accumulator is, at best, misleading. And it doesn't handle it correctly if you do [].reduce(x => x) (it should throw an error, not return undefined [note no seed value]).

So basically, I wouldn't put much faith in that polyfill, since it's providing the array, rather than undefined, as this during callbacks.

Title: Reduce Pollyfill

Body:
I was playing around with this array reduce polyfill and I'm just confused why is he/she using apply. I know that apply adds this context in the execution. But I don't know why we need it here, I just tried without it, and it works fine too.

Array.prototype.reduce = function (cb, initialValue) {
  console.log('inside my reducer');
  if (!cb || typeof cb !== 'function') throw TypeError();
  var len = this.length;
  var i = 0;
  console.log('this', this);
  if (typeof initialValue === 'undefined' || initialValue === null) {
    initialValue = this[0];
    ++i;
  }

  for (; i < len; i++) {
    initialValue = cb.apply(this, [initialValue, this[i], i, this]);

    //comment the line above and uncomment this line and it will work fine
    //initialValue = cb(initialValue, this[i]);

  }

  return initialValue;
};

[1, 2, 1, 1].reduce((a, b) => a + b, 0); => 5

So, I'm a little confused, if anyone could share some insights it'll be apreciated.
Thanks!


问:
Dynamically insert a command into an existing notebook in Databricks
Off the back this great answer in this post:
Create a notebook inside another notebook in Databricks Dynamically using Python
where it was shown how to create an entirely new notebook dynamically, my question is on inserting a command into an existing notebook.

Given that

```<code>ctx = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson())
notebook_path = ctx['extraContext']['notebook_path']

content = "some code"
</code>```

is it possible to append content into the notebook at notebook_path?

答:
There is no separate separate API for appending a code to the notebook. But you can use Workspace API to export given notebook, decode base64-encoded content, append the code, and import it again with overwrite parameter set to the true.

It's better to add following line:

```<code># COMMAND ----------

</code>```

to the begin of your new code so it will be treated as a new cell in the notebook.

Also, the permissions of the notebook could be reset, and if you want to avoid that, then you can use Notebook Permissions API to retrieve current permissions, and then set it back after import.

Body:
Off the back this great answer in this post:
Create a notebook inside another notebook in Databricks Dynamically using Python
where it was shown how to create an entirely new notebook dynamically, my question is on inserting a command into an existing notebook.

Given that

ctx = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson())
notebook_path = ctx['extraContext']['notebook_path']

content = "some code"

is it possible to append content into the notebook at notebook_path?

Body:
There is no separate separate API for appending a code to the notebook. But you can use Workspace API to export given notebook, decode base64-encoded content, append the code, and import it again with overwrite parameter set to the true.

It's better to add following line:

# COMMAND ----------

to the begin of your new code so it will be treated as a new cell in the notebook.

Also, the permissions of the notebook could be reset, and if you want to avoid that, then you can use Notebook Permissions API to retrieve current permissions, and then set it back after import.


问:
what is the reason for this error and how to solve it

add method produce error saya his expression has a type of 'void' so its value can't be used.

```<code> Future addtocart({
    String? productID,
    BuildContext? context,
  }) async {
    List<String>? cartitems = ["gabbage"];
    await _firestore
        .collection("Users")
        .doc(_currentUser!.uid)
        .collection("Cart")
        .doc(_currentUser!.uid)
        .get()
        .then((doc) {
      if (doc.data()!["UserCart"].contains(productID)) {
        Fluttertoast.showToast(
          msg: 'Product is already in the cart',
          gravity: ToastGravity.CENTER,
        );
      } else {
        _firestore
            .collection("Users")
            .doc(_currentUser!.uid)
            .collection("Cart")
            .doc(_currentUser!.uid)
            .update({"UserCart": cartitems.add(productID!)});
      }
    });
  }
}
</code>```

答:
Instead of cartitems.add(productID!), you can do FieldValue.arrayUnion(productID!).
You can find the documentation of FieldView here: https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/FieldValue-class.html

Body:
add method produce error saya his expression has a type of 'void' so its value can't be used.

 Future addtocart({
    String? productID,
    BuildContext? context,
  }) async {
    List<String>? cartitems = ["gabbage"];
    await _firestore
        .collection("Users")
        .doc(_currentUser!.uid)
        .collection("Cart")
        .doc(_currentUser!.uid)
        .get()
        .then((doc) {
      if (doc.data()!["UserCart"].contains(productID)) {
        Fluttertoast.showToast(
          msg: 'Product is already in the cart',
          gravity: ToastGravity.CENTER,
        );
      } else {
        _firestore
            .collection("Users")
            .doc(_currentUser!.uid)
            .collection("Cart")
            .doc(_currentUser!.uid)
            .update({"UserCart": cartitems.add(productID!)});
      }
    });
  }
}


问:
Multiplication over one column like f.sum
I have a column in a data frame. I need to aggregate a column by multiplying the values in this column instead of sum them up.

```<code>ex = spark.createDataFrame([[1,2],[4,5]],['a','b'])
ex.show()
ex.agg(f.sum('a')).show()
</code>```

instead of sum I want to multiply column 'a' with syntax something like:

```<code>ex.agg(f.mul('a')).show()
</code>```

the workaround I thought of is:

```<code>ex.agg(f.exp(f.sum(f.log('a')))).show()
</code>```

however calculating exp(sum(log)) might be not efficient enough

The result should be 4.
What is most efficient way?

答:
When I see limitations in the python Spark API I always take a look at higher order functions as they give you access to functionality that might not be yet integrated to PySpark. Also, they generally give much better performance against UDFs as you use optimized native Spark operations. You can read more about higher-order functions here: https://medium.com/@danniesim/faster-and-more-concise-than-udf-spark-functions-and-higher-order-functions-with-pyspark-31d31de5fed8.

For your problem you could use f.aggegate, you can find some examples in the Spark documentation: https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.aggregate.html#pyspark.sql.functions.aggregate. Here for reference how to aggregate values by multiplying:

```<code>ex.agg(f.aggregate('a', f.lit(1.0), lambda acc, x: acc * x))
</code>```

EDIT: f.aggregate is available from PySpark 3.1.0, in case you have a previous version you can do the following (again, another higher-order function to use the aggregate from the Spark SQL API: https://spark.apache.org/docs/latest/api/sql/#aggregate):

```<code>ex
.agg(f.collect_list('a').alias('a'))
.withColumn('a', f.expr("aggregate(a, CAST(1.0 AS DOUBLE), (acc, x) -> acc * x, acc -> acc)"))
</code>```

Like this you use only native spark API but needless to say, really looks way too complicated for just multiplying values over a group.

Body:
I have a column in a data frame. I need to aggregate a column by multiplying the values in this column instead of sum them up.

ex = spark.createDataFrame([[1,2],[4,5]],['a','b'])
ex.show()
ex.agg(f.sum('a')).show()

instead of sum I want to multiply column 'a' with syntax something like:

ex.agg(f.mul('a')).show()

the workaround I thought of is:

ex.agg(f.exp(f.sum(f.log('a')))).show()

however calculating exp(sum(log)) might be not efficient enough

The result should be 4.
What is most efficient way?

Body:
When I see limitations in the python Spark API I always take a look at higher order functions as they give you access to functionality that might not be yet integrated to PySpark. Also, they generally give much better performance against UDFs as you use optimized native Spark operations. You can read more about higher-order functions here: https://medium.com/@danniesim/faster-and-more-concise-than-udf-spark-functions-and-higher-order-functions-with-pyspark-31d31de5fed8.

For your problem you could use f.aggegate, you can find some examples in the Spark documentation: https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.aggregate.html#pyspark.sql.functions.aggregate. Here for reference how to aggregate values by multiplying:

ex.agg(f.aggregate('a', f.lit(1.0), lambda acc, x: acc * x))

EDIT: f.aggregate is available from PySpark 3.1.0, in case you have a previous version you can do the following (again, another higher-order function to use the aggregate from the Spark SQL API: https://spark.apache.org/docs/latest/api/sql/#aggregate):

ex
.agg(f.collect_list('a').alias('a'))
.withColumn('a', f.expr("aggregate(a, CAST(1.0 AS DOUBLE), (acc, x) -> acc * x, acc -> acc)"))

Like this you use only native spark API but needless to say, really looks way too complicated for just multiplying values over a group.


问:
Error removing directory which is not empty
I'm trying to delete a directory when all the tests finish with an after, and I get the following error:

```<code>fs.rmdir is not a function
</code>```

Here is mi code:

```<code>after(() => {
        const fs = require('fs');
        const dir = '../../../../../../downloads';

        fs.rmdir(dir, { recursive: true }, (err) => {
            if (err) {
                throw err;
            }
        });
    })
</code>```

答:
The reason is fs is a Node library, but you are trying to use it in the browser.

For Node code, use a task

/cypress/plugins/index.js

const fs = require('f')

module.exports = (on, config) => {
  on('task', {
    clearDownloads(message) {
      const fs = require('fs');
      const dir = '../../../../../../downloads';

      fs.rm(dir, { recursive: true }, (err) => {
        if (err) {
          throw err;
        }
      });
      return null
    },
  })
}
```

But there's a couple of configuration items that seem to do this job for you

Ref Configuration - Downloads

downloadsFolder - Path to folder where files downloaded during a test are saved

trashAssetsBeforeRuns - Whether Cypress will trash assets within the downloadsFolder, screenshotsFolder, and videosFolder before tests run with cypress run.

Body:
I'm trying to delete a directory when all the tests finish with an after, and I get the following error:

fs.rmdir is not a function

Here is mi code:

after(() => {
        const fs = require('fs');
        const dir = '../../../../../../downloads';

        fs.rmdir(dir, { recursive: true }, (err) => {
            if (err) {
                throw err;
            }
        });
    })

Body:
The reason is fs is a Node library, but you are trying to use it in the browser.

For Node code, use a task

/cypress/plugins/index.js

const fs = require('f')

module.exports = (on, config) => {
  on('task', {
    clearDownloads(message) {
      const fs = require('fs');
      const dir = '../../../../../../downloads';

      fs.rm(dir, { recursive: true }, (err) => {
        if (err) {
          throw err;
        }
      });
      return null
    },
  })
}

But there's a couple of configuration items that seem to do this job for you

Ref Configuration - Downloads

downloadsFolder - Path to folder where files downloaded during a test are saved

trashAssetsBeforeRuns - Whether Cypress will trash assets within the downloadsFolder, screenshotsFolder, and videosFolder before tests run with cypress run.


问:
React Query get error status code in global onError handler
When creating the queryClient I want to create a global onError handler that refreshes my access token when the error response code is 401. But I don't know how the status code is accessible on the returned error in the onError handler.

Below is my global onError handler and I only need to access the response code in the if statement to refresh my token at the appropriate time.

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: async (error, query) => {
      // How to get status code fo error
      if (error.status === 401) {
        console.log("Refreshing Token");
        await api.get("/api/refresh-token");
        queryClient.refetchQueries(query.queryKey);
      }
    },
  }),
});
```

答:
Error type is "unknown", you need to map this type. I am using fetch to do the requests and can map the error as "Response" object. If you need to consult the content of de error, could print with JSON.stringfy.</p>
```<code>  queryCache: new QueryCache({
onError: (error) => {
  // JSON.stringify(error) if you are not secure and need to see the content, could print the error in strinfy
  const response = error as Response
  console.log('---------------------------------')
  console.log(response.status) // 401
  console.log(response.type) // default
  console.log(response.ok) // false
  console.log('---------------------------------')
}})
</code>```

Body:
Error type is "unknown", you need to map this type. I am using fetch to do the requests and can map the error as "Response" object. If you need to consult the content of de error, could print with JSON.stringfy.

  queryCache: new QueryCache({
onError: (error) => {
  // JSON.stringify(error) if you are not secure and need to see the content, could print the error in strinfy
  const response = error as Response
  console.log('---------------------------------')
  console.log(response.status) // 401
  console.log(response.type) // default
  console.log(response.ok) // false
  console.log('---------------------------------')
}})


问:
Updating tinymce editor text between components
So I'm using the tinymce editor for Vue. I'm displaying one Editor in the parent component, and then rendering another Editor in the child which reactively displays what has been typed in the parent. The problem I'm running into is that the child is one character behind. I tried making the editor content its own variable in the child instead of being passed via props, but I couldn't figure out a way to update correctly while also saving the HTML tags that tinymce adds.

Here's what I have:

The parent component:

```<code>                        <Editor
                          v-model="body"
                          api-key=****
                          model-events="change keydown blur focus paste undo redo"
                          :init="{
                            height: 300,
                            menubar: false,
                            nonbreaking_force_tab: true,
                            branding: false,
                            init_instance_callback: function (editor) {
                              editor.on('Change', function (e) {
                                setHasChanges(); //this just says the form has updates
                              });
                            },
                            plugins: [
                              'advlist autolink lists link image charmap',
                              'searchreplace visualblocks code fullscreen',
                              'print preview anchor insertdatetime media',
                              'paste code help wordcount table'
                            ],
                            toolbar:
                              'undo redo | formatselect | bold italic | \
                            bullist numlist | \
                            alignleft aligncenter alignright outdent indent | help'
                          }"
                        >
                        </Editor>
</code>```

And the child:

```<code>        <Editor
          :value="body"
          api-key=***
          model-events="change keydown blur focus paste undo redo"
          disabled="true"
          :init="{
            menubar: false,
            branding: false,
            toolbar: false,
            statusbar: false,
            content_style:
              'body { font-size: 12px; line-height: 1.35; margin: 10px auto 0; display: block; position: relative; height: 100px; overflow-x: hidden }'
          }"
        >
        </Editor>
</code>```

So if the editor of the parent component had this:

```<code><h2>Here is a title!</h2>
<ul>
 <li>and a bullet point</li>
 <li>and another</li>
</ul>
</code>```

The child would display:

Here is a title!

and a bullet point

and another

How can I update the child reactively while still keeping the HTML tags?

答: So I figured it out. All I had to do was add "input" into the model-events of the editor on the parent component.</p>

Body:
So I'm using the tinymce editor for Vue. I'm displaying one Editor in the parent component, and then rendering another Editor in the child which reactively displays what has been typed in the parent. The problem I'm running into is that the child is one character behind. I tried making the editor content its own variable in the child instead of being passed via props, but I couldn't figure out a way to update correctly while also saving the HTML tags that tinymce adds.

Here's what I have:

The parent component:

                        <Editor
                          v-model="body"
                          api-key=****
                          model-events="change keydown blur focus paste undo redo"
                          :init="{
                            height: 300,
                            menubar: false,
                            nonbreaking_force_tab: true,
                            branding: false,
                            init_instance_callback: function (editor) {
                              editor.on('Change', function (e) {
                                setHasChanges(); //this just says the form has updates
                              });
                            },
                            plugins: [
                              'advlist autolink lists link image charmap',
                              'searchreplace visualblocks code fullscreen',
                              'print preview anchor insertdatetime media',
                              'paste code help wordcount table'
                            ],
                            toolbar:
                              'undo redo | formatselect | bold italic | \
                            bullist numlist | \
                            alignleft aligncenter alignright outdent indent | help'
                          }"
                        >
                        </Editor>

And the child:

        <Editor
          :value="body"
          api-key=***
          model-events="change keydown blur focus paste undo redo"
          disabled="true"
          :init="{
            menubar: false,
            branding: false,
            toolbar: false,
            statusbar: false,
            content_style:
              'body { font-size: 12px; line-height: 1.35; margin: 10px auto 0; display: block; position: relative; height: 100px; overflow-x: hidden }'
          }"
        >
        </Editor>

So if the editor of the parent component had this:

Here is a title!

and a bullet point

and another

The child would display:

Here is a title!

and a bullet point

and another

How can I update the child reactively while still keeping the HTML tags?


问:
How to register custom program to handle mailto protocol on Windows 7
OK, it might be a problem with my system but I'm having a very difficult time getting Windows 7 to recognize my custom exe as the default handler of the mailto protocol.

First, I've seen this:
Register Windows program with the mailto protocol programmatically

Next, I've seen these:

How to Register an Internet Browser or Email Client With the Windows Start Menu

Registering an Application to a URL Protocol

I've added what seemed the appropriate registry entries but I still get Windows Live Mail coming up every time I click a mailto link (whether in a browser or via the Run window). I've set the registry entries for all users and for the current user, still it doesn't work.

When I go to the 'default programs' app and scroll down to the mailto protocol, I only see Outlook and Windows Live Mail listed. My custom app doesn't even appear.

I figure that it's either something special with Windows 7 or it's something with my computer.

My custom app is a WinForms .Net app but I don't think that matters.

Any ideas are greatly welcome.

答: How can I add a custom url handler on Windows. Like iTunes itms:// Related but not.</p>

ContentLicense: CC BY-SA 3.0


问:
3rd argument is ignored when I use memcpy in C
I'm a beginner in C and try to use memcpy to send byte in order to transfer data to server. It seems like no matter what I choose for 3rd argument. It's always the same.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    char myChar[100] = "Hello world! ABC is an online sandbox that makes it easy to try out";
    char myChar2[100];

    memcpy(myChar2, myChar, 3);

    printf("%s", myChar);

    return 0;
}
</code>```

This is the result.

Hello world! ABC is an online sandbox that makes it easy to try out

答:
memcpy is working correctly.
The problem with your code is that you are printing myChar instead of myChar2.

```<code>printf("%s", myChar2); // Hel
</code>```

Working example

Body:
I'm a beginner in C and try to use memcpy to send byte in order to transfer data to server. It seems like no matter what I choose for 3rd argument. It's always the same.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    char myChar[100] = "Hello world! ABC is an online sandbox that makes it easy to try out";
    char myChar2[100];

    memcpy(myChar2, myChar, 3);

    printf("%s", myChar);

    return 0;
}

This is the result.

Hello world! ABC is an online sandbox that makes it easy to try out

Body:
memcpy is working correctly.
The problem with your code is that you are printing myChar instead of myChar2.

printf("%s", myChar2); // Hel

Working example


问:
Hide portainer container from containers list
How can I hide the portainer container from the Portainer's container list?

答:
Inside a console, run:

```<code>docker pull portainer/portainer-ce:latest && \
echo "FROM portainer/portainer-ce:latest" | docker build --label hidden="true" -t "portainer/portainer-ce:latest" -
</code>```

This will create a new image of Portainer, with the label hidden="true" applied.

Then, re-install the Portainer's docker container:

```<code>docker stop portainer && \
docker rm portainer && \
docker run -d -p 8000:8000 -p 9000:9000 \
    --name=portainer --restart=always \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v portainer_data:/data portainer/portainer-ce
</code>```

Open Portainer at http://localhost:8000, go to "Settings" (bottom left), at the "Hidden containers" section, and add an entry with name=hidden, value=true:

Now the portainer's container won't be visible at the containers list.

Body:
Inside a console, run:

docker pull portainer/portainer-ce:latest && \
echo "FROM portainer/portainer-ce:latest" | docker build --label hidden="true" -t "portainer/portainer-ce:latest" -

This will create a new image of Portainer, with the label hidden="true" applied.

Then, re-install the Portainer's docker container:

docker stop portainer && \
docker rm portainer && \
docker run -d -p 8000:8000 -p 9000:9000 \
    --name=portainer --restart=always \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v portainer_data:/data portainer/portainer-ce

Open Portainer at http://localhost:8000, go to "Settings" (bottom left), at the "Hidden containers" section, and add an entry with name=hidden, value=true:

Now the portainer's container won't be visible at the containers list.


问:
Why does my mockito failed test when actual result same as the expected result? flutter
I'm using Mockito in flutter application and want to add some test cases:

this run failed while the actual result is the same as expected result, here's my test file:

@GenerateMocks([ResumeParserDataSource])
void main() {
  late MockResumeParserDataSource resumeParserDataSource;
  late ResumeParserController resumeParserController;
  late ResumeParserRepo resumeParserRepo;

  setUp(() async {
    Get.reset();
    resumeParserDataSource = MockResumeParserDataSource();
    resumeParserRepo =
        Get.put(ResumeParserRepo(dataSource: resumeParserDataSource));
    resumeParserController = Get.put(ResumeParserController());
  });

  group('Upload resume that uploaded into API:\n', () {
    test(
        '~succeed state~ api get response and parsed it into model JSON "ParsedDetailsResume"',
        () async {
      when(resumeParserRepo
              .getResumeDetailsAfterParsing(ResumeParserTestUtil.fileName))
          .thenAnswer((_) async => Right(
              ResumeParserTestUtil.parsedResumeDetailsFunction(
                  ResumeParserTestUtil.parsedResumeDetailsModel1)));
      await resumeParserController
          .parseResumeToAPI(ResumeParserTestUtil.fileName);
      await waitForAPIResponse();
      expect(
          resumeParserController.parsedResume.value,
          some(ResumeParserTestUtil.parsedResumeDetailsFunction(
              ResumeParserTestUtil.parsedResumeDetailsModel1)));
      expect(resumeParserController.error.value, none());
    });
  });
}
```
<p>here's my <code>ResumeParserController</code>:</p>
<pre class="lang-dart prettyprint-override"><code>
class ResumeParserController extends GetxController {
  static ResumeParserController get to => Get.find();
  final resumeParserRepo = ResumeParserRepo.to;
  Rx<Option<ParsedResumeDetails>> parsedResume =
      Rx<Option<ParsedResumeDetails>>(none());

  Future<Either<DioError, ParsedResumeDetails>> parseResumeToAPI(
      String fileName,
      {User? user}) async {
    var result = await resumeParserRepo.getResumeDetailsAfterParsing(
      fileName,
      user: user,
    );
    return result.fold(
      (l) => Left(l),
      (newParsedResume) async {
        error.value = none();
        parsedResume.value = some(newParsedResume);
        update();
        return Right(newParsedResume);
      },
    );
  }
}
</code>```

and here's my json model in ResumeParserTestUtil:

class ResumeParserTestUtil {

  static String fileName = "12989801ahsduiabsdui9123ajd.pdf";

  static ParsedResumeDetails parsedResumeDetailsFunction(
      Map<String, dynamic> response,
      {User? user}) {
    var userSkills = response['data']['userSkills'] == null
        ? [PublicUserSkill.empty()]
        : List.from(response['data']['userSkills'])
            .map((e) => PublicUserSkill.fromJson(e["skill"]))
            .toList();
    var userEducations = response['data']['educations'] == null
        ? [EducationParsed.empty()]
        : List.from(response['data']['educations'])
            .map((e) => EducationParsed.fromJson(e))
            .toList();

    var experiences = response['data']['experiences'] == null
        ? [ExperiencesParsed.empty()]
        : List.from(response['data']['experiences'])
            .map((e) => ExperiencesParsed.fromJson(e))
            .toList();
    return ParsedResumeDetails(
      user: user,
      userSkills:
          userSkills.map(mapPublicUserSkillToSkillWithUserSkill).toList(),
      userEducation: userEducations,
      userWorkExperience: experiences,
    );
  }

  static Map<String, dynamic> parsedResumeDetailsModel1 = {
    "data": {
      "experiences": [
        {
          "startDate": null,
          "endDate": null,
          "isPresent": false,
          "organization": "Unnamed company",
          "type": "WORK"
        }
      ],
      "userSkills": [
        {
          "skill": {
            "id": "7963a547-3980-47d6-8ffc-c9e311152d9b",
            "name": "Bachelors Degree > Bachelors Degree Economics",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null,
          },
        },
        {
          "skill": {
            "id": "05516ee5-1706-4296-aaa3-f3386767dec6",
            "name":
                "Bachelors Degree > Bachelors Degree Information Engineering and Media",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null,
          }
        },
        {
          "skill": {
            "id": "0baaa115-a770-42f5-ad54-291ffa42a11c",
            "name": "Bachelors Degree > Bachelors Degree Literature",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null
          }
        },
        {
          "skill": {
            "id": "7a4ca05f-8d75-44c5-b012-5a0298160903",
            "name": "Bachelors Degree > Bachelors Degree Mathematics",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null,
          },
        },
        {
          "skill": {
            "id": "b29215d5-c3cf-4b62-82df-2ee5db1c160c",
            "name": "Bachelors Degree > Bachelors Degree history",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null
          }
        }
      ],
      "educations": [
        {
          "startDate": null,
          "endDate": null,
          "type": "EDUCATION",
          "isPresent": true,
          "study": {
            "id": "572502d1-fb5c-4876-8985-2c4278b98a8b",
            "name":
                "Information Engineering and Media, history, Economics, Literature, Mathematics",
            "createdAt": "",
            "updatedAt": ""
          },
          "school": {
            "id": "f54c85dd-f51e-4715-a393-dbcea6edbed7",
            "name": "Adamson University",
            "domain": "adamson.edu.ph",
            "website": "http://www.adamson.edu.ph/",
            "state": null,
            "type": null,
            "CountryCode": "PH",
            "createdAt": null,
            "updatedAt": null
          },
          "degree": {
            "id": "63dd0edf-9193-4ac0-b693-ae561873e4a3",
            "name": "Bachelor",
            "createdAt": "",
            "updatedAt": ""
          }
        },
        {
          "startDate": null,
          "endDate": null,
          "type": "EDUCATION",
          "isPresent": true,
          "school": {
            "id": "1dedeca8-154b-4e8f-a867-d359616d996c",
            "name": "Adipala Junior High School",
            "domain": null,
            "website": null,
            "state": null,
            "type": null,
            "CountryCode": null,
            "createdAt": "",
            "updatedAt": null
          }
        },
        {
          "startDate": null,
          "endDate": null,
          "type": "EDUCATION",
          "isPresent": true,
          "school": {
            "id": "38420130-dac4-4a3c-a1bc-cea4777054c1",
            "name": "Unnamed school",
            "domain": null,
            "website": null,
            "state": null,
            "type": null,
            "CountryCode": null,
            "createdAt": null,
            "updatedAt": null
          }
        }
      ]
    }
  };
}
```

and this was the result:

Expected: Some:<Some(ParsedResumeDetails([EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION)], [ExperiencesParsed(false, null, Unnamed company, null, WORK)], [Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill'], null))>

Actual: Some:<Some(ParsedResumeDetails([EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION)], [ExperiencesParsed(false, null, Unnamed company, null, WORK)], [Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill'], null))>

package:test_api

✖ Upload resume that uploaded into API:
~succeed state~ api get response and parsed it into model JSON "ParsedDetailsResume"

Exited (1)

Any thoughts on this? Thanks!

答:
Ran into same issue trying test async call, where it was failing because I set expected value wrapped in a Future.value()

Solution in this case is to :

extract the value from the async call first with await

then do the check on raw value, without any notion of Future<>

eg:

```<code>test('test SomeService()', () async {

  final actual = await someService.getSomeList();

  expect(actual, []);
});
</code>```

Body:
I'm using Mockito in flutter application and want to add some test cases:

this run failed while the actual result is the same as expected result, here's my test file:

@GenerateMocks([ResumeParserDataSource])
void main() {
  late MockResumeParserDataSource resumeParserDataSource;
  late ResumeParserController resumeParserController;
  late ResumeParserRepo resumeParserRepo;

  setUp(() async {
    Get.reset();
    resumeParserDataSource = MockResumeParserDataSource();
    resumeParserRepo =
        Get.put(ResumeParserRepo(dataSource: resumeParserDataSource));
    resumeParserController = Get.put(ResumeParserController());
  });

  group('Upload resume that uploaded into API:\n', () {
    test(
        '~succeed state~ api get response and parsed it into model JSON "ParsedDetailsResume"',
        () async {
      when(resumeParserRepo
              .getResumeDetailsAfterParsing(ResumeParserTestUtil.fileName))
          .thenAnswer((_) async => Right(
              ResumeParserTestUtil.parsedResumeDetailsFunction(
                  ResumeParserTestUtil.parsedResumeDetailsModel1)));
      await resumeParserController
          .parseResumeToAPI(ResumeParserTestUtil.fileName);
      await waitForAPIResponse();
      expect(
          resumeParserController.parsedResume.value,
          some(ResumeParserTestUtil.parsedResumeDetailsFunction(
              ResumeParserTestUtil.parsedResumeDetailsModel1)));
      expect(resumeParserController.error.value, none());
    });
  });
}

here's my ResumeParserController:

class ResumeParserController extends GetxController {
  static ResumeParserController get to => Get.find();
  final resumeParserRepo = ResumeParserRepo.to;
  Rx<Option<ParsedResumeDetails>> parsedResume =
      Rx<Option<ParsedResumeDetails>>(none());

  Future<Either<DioError, ParsedResumeDetails>> parseResumeToAPI(
      String fileName,
      {User? user}) async {
    var result = await resumeParserRepo.getResumeDetailsAfterParsing(
      fileName,
      user: user,
    );
    return result.fold(
      (l) => Left(l),
      (newParsedResume) async {
        error.value = none();
        parsedResume.value = some(newParsedResume);
        update();
        return Right(newParsedResume);
      },
    );
  }
}

and here's my json model in ResumeParserTestUtil:

class ResumeParserTestUtil {

  static String fileName = "12989801ahsduiabsdui9123ajd.pdf";

  static ParsedResumeDetails parsedResumeDetailsFunction(
      Map<String, dynamic> response,
      {User? user}) {
    var userSkills = response['data']['userSkills'] == null
        ? [PublicUserSkill.empty()]
        : List.from(response['data']['userSkills'])
            .map((e) => PublicUserSkill.fromJson(e["skill"]))
            .toList();
    var userEducations = response['data']['educations'] == null
        ? [EducationParsed.empty()]
        : List.from(response['data']['educations'])
            .map((e) => EducationParsed.fromJson(e))
            .toList();

    var experiences = response['data']['experiences'] == null
        ? [ExperiencesParsed.empty()]
        : List.from(response['data']['experiences'])
            .map((e) => ExperiencesParsed.fromJson(e))
            .toList();
    return ParsedResumeDetails(
      user: user,
      userSkills:
          userSkills.map(mapPublicUserSkillToSkillWithUserSkill).toList(),
      userEducation: userEducations,
      userWorkExperience: experiences,
    );
  }

  static Map<String, dynamic> parsedResumeDetailsModel1 = {
    "data": {
      "experiences": [
        {
          "startDate": null,
          "endDate": null,
          "isPresent": false,
          "organization": "Unnamed company",
          "type": "WORK"
        }
      ],
      "userSkills": [
        {
          "skill": {
            "id": "7963a547-3980-47d6-8ffc-c9e311152d9b",
            "name": "Bachelors Degree > Bachelors Degree Economics",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null,
          },
        },
        {
          "skill": {
            "id": "05516ee5-1706-4296-aaa3-f3386767dec6",
            "name":
                "Bachelors Degree > Bachelors Degree Information Engineering and Media",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null,
          }
        },
        {
          "skill": {
            "id": "0baaa115-a770-42f5-ad54-291ffa42a11c",
            "name": "Bachelors Degree > Bachelors Degree Literature",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null
          }
        },
        {
          "skill": {
            "id": "7a4ca05f-8d75-44c5-b012-5a0298160903",
            "name": "Bachelors Degree > Bachelors Degree Mathematics",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null,
          },
        },
        {
          "skill": {
            "id": "b29215d5-c3cf-4b62-82df-2ee5db1c160c",
            "name": "Bachelors Degree > Bachelors Degree history",
            "popularity": "0",
            "flagRecount": false,
            "createdAt": null,
            "updatedAt": null
          }
        }
      ],
      "educations": [
        {
          "startDate": null,
          "endDate": null,
          "type": "EDUCATION",
          "isPresent": true,
          "study": {
            "id": "572502d1-fb5c-4876-8985-2c4278b98a8b",
            "name":
                "Information Engineering and Media, history, Economics, Literature, Mathematics",
            "createdAt": "",
            "updatedAt": ""
          },
          "school": {
            "id": "f54c85dd-f51e-4715-a393-dbcea6edbed7",
            "name": "Adamson University",
            "domain": "adamson.edu.ph",
            "website": "http://www.adamson.edu.ph/",
            "state": null,
            "type": null,
            "CountryCode": "PH",
            "createdAt": null,
            "updatedAt": null
          },
          "degree": {
            "id": "63dd0edf-9193-4ac0-b693-ae561873e4a3",
            "name": "Bachelor",
            "createdAt": "",
            "updatedAt": ""
          }
        },
        {
          "startDate": null,
          "endDate": null,
          "type": "EDUCATION",
          "isPresent": true,
          "school": {
            "id": "1dedeca8-154b-4e8f-a867-d359616d996c",
            "name": "Adipala Junior High School",
            "domain": null,
            "website": null,
            "state": null,
            "type": null,
            "CountryCode": null,
            "createdAt": "",
            "updatedAt": null
          }
        },
        {
          "startDate": null,
          "endDate": null,
          "type": "EDUCATION",
          "isPresent": true,
          "school": {
            "id": "38420130-dac4-4a3c-a1bc-cea4777054c1",
            "name": "Unnamed school",
            "domain": null,
            "website": null,
            "state": null,
            "type": null,
            "CountryCode": null,
            "createdAt": null,
            "updatedAt": null
          }
        }
      ]
    }
  };
}

and this was the result:

Expected: Some:<Some(ParsedResumeDetails([EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION)], [ExperiencesParsed(false, null, Unnamed company, null, WORK)], [Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill'], null))>

Actual: Some:<Some(ParsedResumeDetails([EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION), EducationParsed(true, null, null, null, EDUCATION)], [ExperiencesParsed(false, null, Unnamed company, null, WORK)], [Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill', Instance of 'SkillWithUserSkill'], null))>

package:test_api

✖ Upload resume that uploaded into API:
~succeed state~ api get response and parsed it into model JSON "ParsedDetailsResume"

Exited (1)

Any thoughts on this? Thanks!

Body:
Ran into same issue trying test async call, where it was failing because I set expected value wrapped in a Future.value()

Solution in this case is to :

extract the value from the async call first with await

then do the check on raw value, without any notion of Future<>

eg:

test('test SomeService()', () async {

  final actual = await someService.getSomeList();

  expect(actual, []);
});


问:
How can I change particular registry owner in C#
I want to read and write the key

```<code>HKEY_CLASSES_ROOT\CLSID\{1eeb5b5a-06fb-4732-96b3-975c0194eb39}\InProcServer32
</code>```

The key's default owner is SYSTEM,I can change it manually in regedit but, I want my program can do this(change the owner of Registry)
I have tried the code below:

```<code>try
{
    string user = Environment.UserDomainName + "\\" + Environment.UserName;
    RegistryKey rk = Registry.ClassesRoot.OpenSubKey(@"CLSID\{1eeb5b5a-06fb-4732-96b3-975c0194eb39}\InProcServer32",
                      RegistryKeyPermissionCheck.ReadWriteSubTree,
                      RegistryRights.ChangePermissions);
    RegistrySecurity rs = new RegistrySecurity();
    RegistryAccessRule rar = new RegistryAccessRule(user,
                                 RegistryRights.FullControl,
                                 AccessControlType.Allow);
    rs.AddAccessRule(rar);
    rk.SetAccessControl(rs);
    rk.Close();
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

Console.WriteLine("test");

try
{
    var subKey = Registry.ClassesRoot.OpenSubKey(@"CLSID\{1eeb5b5a-06fb-4732-96b3-975c0194eb39}\InProcServer32", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
    subKey.SetValue("", @"%SystemRoot%\system32\explorerframe.dll", RegistryValueKind.ExpandString);
                    }catch (Exception ex) { Console.WriteLine(ex.Message);
}

</code>```

Both the operation failed with:

not allow requested registry privilidge.

I have also tried the code on Microsoft docs but it didn't work.
https://learn.microsoft.com/zh-cn/dotnet/api/microsoft.win32.registrykey.setaccesscontrol?view=dotnet-plat-ext-3.1

How can I get the ownership for my program?

答:
I got my answer when I asked the same question on MSDN.Link:
https://learn.microsoft.com/en-us/answers/questions/726748/how-can-i-change-particular-registry-owner-in-c.html

Answer From Castorix31：

A way is with Win32 APIs (tested on Windows 10 21H1, as Admin (Manifest)) :

```<code>if (!EnablePrivilege(SE_TAKE_OWNERSHIP_NAME, true))
     return;

 string sName = "Christian";
 System.Security.Principal.NTAccount ntAccount = new System.Security.Principal.NTAccount(sName);
 string sSid = ntAccount.Translate(typeof(System.Security.Principal.SecurityIdentifier)).Value;
 // S-1-5-21-3423049853-1102793660-1424913857-1001
 IntPtr pSid = IntPtr.Zero;
 ConvertStringSidToSid(sSid, out pSid);
 IntPtr hKey = IntPtr.Zero;
 uint dwErr = RegOpenKeyEx((IntPtr)HKEY_CLASSES_ROOT, "CLSID\\{1eeb5b5a-06fb-4732-96b3-975c0194eb39}\\InProcServer32", 0, KEY_WOW64_64KEY | WRITE_OWNER, ref hKey);
 if (dwErr == 0)
 {
     uint dwRet = SetSecurityInfo(hKey,
           SE_OBJECT_TYPE.SE_REGISTRY_KEY,
           OWNER_SECURITY_INFORMATION,
           pSid,
           IntPtr.Zero,
           IntPtr.Zero,
           IntPtr.Zero);
     RegCloseKey(hKey);
 }
</code>```

Utility function :

```<code> // From MS SDK : Win7Samples\winbase\bootconfigurationdata\bcdsamplelib\Utils.cs
 private bool EnablePrivilege(string lpszPrivilege, bool bEnablePrivilege)
 {
     bool retval = false;
     int ltkpOld = 0;
     IntPtr hToken = IntPtr.Zero;
     TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();
     tkp.Privileges = new int[3];
     TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();
     tkpOld.Privileges = new int[3];
     LUID tLUID = new LUID();
     tkp.PrivilegeCount = 1;
     if (bEnablePrivilege)
         tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
     else
         tkp.Privileges[2] = 0;
     if (LookupPrivilegeValue(null, lpszPrivilege, out tLUID))
     {
         System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
         if (proc.Handle != IntPtr.Zero)
         {
             if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken) != false)
             {
                 tkp.PrivilegeCount = 1;
                 tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
                 tkp.Privileges[1] = tLUID.HighPart;
                 tkp.Privileges[0] = tLUID.LowPart;
                 const int bufLength = 256;
                 IntPtr tu = Marshal.AllocHGlobal(bufLength);
                 Marshal.StructureToPtr(tkp, tu, true);
                 if (AdjustTokenPrivileges(hToken, false, tu, bufLength, IntPtr.Zero, ref ltkpOld) != false)
                 {
                     int nErr = Marshal.GetLastWin32Error();
                     // successful AdjustTokenPrivileges doesn't mean privilege could be    changed
                     //ERROR_NOT_ALL_ASSIGNED   1300(0x514)
                     if (nErr == 0)
                     {
                         retval = true; // Token changed
                     }
                 }
                 TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tu, typeof(TOKEN_PRIVILEGES));
                 Marshal.FreeHGlobal(tu);
             }
         }
     }
     if (hToken != IntPtr.Zero)
     {
         CloseHandle(hToken);
     }
     return retval;
 }
</code>```

Declarations :

```<code> [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
 public static extern uint RegOpenKeyEx(IntPtr hKey, string lpSubKey, uint ulOptions, int samDesired, ref IntPtr phkResult);
 public const int HKEY_CURRENT_USER = unchecked((int)0x80000001);
 public const int HKEY_CLASSES_ROOT = unchecked((int)0x80000000);
 public const int KEY_WOW64_64KEY = 0x0100;
 public const int WRITE_OWNER = 0x00080000;
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
 public static extern uint RegCloseKey(IntPtr hKey);
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
 public static extern bool LookupPrivilegeValue([In] string lpSystemName, [In] string lpName, [Out] out LUID Luid);
 [StructLayout(LayoutKind.Sequential)]
 public struct LUID
 {
     public int LowPart;
     public int HighPart;
 }
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
 public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, IntPtr NewState, int BufferLength, IntPtr PreviousState, ref int ReturnLength);
 [StructLayout(LayoutKind.Sequential)]
 public struct LUID_AND_ATTRIBUTES
 {
     public LUID Luid;
     public int Attributes;
 }
 [StructLayout(LayoutKind.Sequential)]
 internal struct TOKEN_PRIVILEGES
 {
     internal int PrivilegeCount;
     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
     internal int[] Privileges;
 }
 public const int TOKEN_ASSIGN_PRIMARY = 0x1;
 public const int TOKEN_DUPLICATE = 0x2;
 public const int TOKEN_IMPERSONATE = 0x4;
 public const int TOKEN_QUERY = 0x8;
 public const int TOKEN_QUERY_SOURCE = 0x10;
 public const int TOKEN_ADJUST_PRIVILEGES = 0x20;
 public const int TOKEN_ADJUST_GROUPS = 0x40;
 public const int TOKEN_ADJUST_DEFAULT = 0x80;
 public const int TOKEN_ALL_ACCESS = TOKEN_ASSIGN_PRIMARY
       + TOKEN_DUPLICATE + TOKEN_IMPERSONATE + TOKEN_QUERY
       + TOKEN_QUERY_SOURCE + TOKEN_ADJUST_PRIVILEGES
       + TOKEN_ADJUST_GROUPS + TOKEN_ADJUST_DEFAULT;
 public const string SE_RESTORE_NAME = "SeRestorePrivilege";
 public const string SE_DEBUG_NAME = "SeDebugPrivilege";
 public const string SE_TCB_NAME = "SeTcbPrivilege";
 public const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege";
 public const int SE_PRIVILEGE_ENABLED_BY_DEFAULT = (0x00000001);
 public const int SE_PRIVILEGE_ENABLED = (0x00000002);
 public const int SE_PRIVILEGE_REMOVED = (0X00000004);
 public const int SE_PRIVILEGE_USED_FOR_ACCESS = unchecked((int)0x80000000);
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
 public static extern bool OpenProcessToken(IntPtr hProcess, uint desiredAccess, out IntPtr hToken);
 [DllImport("Kernel32.dll", SetLastError = true)]
 public static extern bool CloseHandle(IntPtr hObject);
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
 public static extern uint SetSecurityInfo(IntPtr handle, SE_OBJECT_TYPE ObjectType, uint SecurityInfo,
     IntPtr psidOwner, IntPtr psidGroup, IntPtr pDacl, IntPtr pSacl);
 public const int OWNER_SECURITY_INFORMATION = 0x00000001;
 public enum SE_OBJECT_TYPE
 {
     SE_UNKNOWN_OBJECT_TYPE = 0,
     SE_FILE_OBJECT,
     SE_SERVICE,
     SE_PRINTER,
     SE_REGISTRY_KEY,
     SE_LMSHARE,
     SE_KERNEL_OBJECT,
     SE_WINDOW_OBJECT,
     SE_DS_OBJECT,
     SE_DS_OBJECT_ALL,
     SE_PROVIDER_DEFINED_OBJECT,
     SE_WMIGUID_OBJECT,
     SE_REGISTRY_WOW64_32KEY,
     SE_REGISTRY_WOW64_64KEY,
 }
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
 public static extern bool ConvertStringSidToSid(string StringSid, out IntPtr Sid);
</code>```

Body:
I want to read and write the key

HKEY_CLASSES_ROOT\CLSID\{1eeb5b5a-06fb-4732-96b3-975c0194eb39}\InProcServer32

The key's default owner is SYSTEM,I can change it manually in regedit but, I want my program can do this(change the owner of Registry)
I have tried the code below:

try
{
    string user = Environment.UserDomainName + "\\" + Environment.UserName;
    RegistryKey rk = Registry.ClassesRoot.OpenSubKey(@"CLSID\{1eeb5b5a-06fb-4732-96b3-975c0194eb39}\InProcServer32",
                      RegistryKeyPermissionCheck.ReadWriteSubTree,
                      RegistryRights.ChangePermissions);
    RegistrySecurity rs = new RegistrySecurity();
    RegistryAccessRule rar = new RegistryAccessRule(user,
                                 RegistryRights.FullControl,
                                 AccessControlType.Allow);
    rs.AddAccessRule(rar);
    rk.SetAccessControl(rs);
    rk.Close();
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

Console.WriteLine("test");

try
{
    var subKey = Registry.ClassesRoot.OpenSubKey(@"CLSID\{1eeb5b5a-06fb-4732-96b3-975c0194eb39}\InProcServer32", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
    subKey.SetValue("", @"%SystemRoot%\system32\explorerframe.dll", RegistryValueKind.ExpandString);
                    }catch (Exception ex) { Console.WriteLine(ex.Message);
}

Both the operation failed with:

not allow requested registry privilidge.

I have also tried the code on Microsoft docs but it didn't work.
https://learn.microsoft.com/zh-cn/dotnet/api/microsoft.win32.registrykey.setaccesscontrol?view=dotnet-plat-ext-3.1

How can I get the ownership for my program?

Body:
I got my answer when I asked the same question on MSDN.Link:
https://learn.microsoft.com/en-us/answers/questions/726748/how-can-i-change-particular-registry-owner-in-c.html

Answer From Castorix31：

A way is with Win32 APIs (tested on Windows 10 21H1, as Admin (Manifest)) :

if (!EnablePrivilege(SE_TAKE_OWNERSHIP_NAME, true))
     return;

 string sName = "Christian";
 System.Security.Principal.NTAccount ntAccount = new System.Security.Principal.NTAccount(sName);
 string sSid = ntAccount.Translate(typeof(System.Security.Principal.SecurityIdentifier)).Value;
 // S-1-5-21-3423049853-1102793660-1424913857-1001
 IntPtr pSid = IntPtr.Zero;
 ConvertStringSidToSid(sSid, out pSid);
 IntPtr hKey = IntPtr.Zero;
 uint dwErr = RegOpenKeyEx((IntPtr)HKEY_CLASSES_ROOT, "CLSID\\{1eeb5b5a-06fb-4732-96b3-975c0194eb39}\\InProcServer32", 0, KEY_WOW64_64KEY | WRITE_OWNER, ref hKey);
 if (dwErr == 0)
 {
     uint dwRet = SetSecurityInfo(hKey,
           SE_OBJECT_TYPE.SE_REGISTRY_KEY,
           OWNER_SECURITY_INFORMATION,
           pSid,
           IntPtr.Zero,
           IntPtr.Zero,
           IntPtr.Zero);
     RegCloseKey(hKey);
 }

Utility function :

 // From MS SDK : Win7Samples\winbase\bootconfigurationdata\bcdsamplelib\Utils.cs
 private bool EnablePrivilege(string lpszPrivilege, bool bEnablePrivilege)
 {
     bool retval = false;
     int ltkpOld = 0;
     IntPtr hToken = IntPtr.Zero;
     TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();
     tkp.Privileges = new int[3];
     TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();
     tkpOld.Privileges = new int[3];
     LUID tLUID = new LUID();
     tkp.PrivilegeCount = 1;
     if (bEnablePrivilege)
         tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
     else
         tkp.Privileges[2] = 0;
     if (LookupPrivilegeValue(null, lpszPrivilege, out tLUID))
     {
         System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
         if (proc.Handle != IntPtr.Zero)
         {
             if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken) != false)
             {
                 tkp.PrivilegeCount = 1;
                 tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
                 tkp.Privileges[1] = tLUID.HighPart;
                 tkp.Privileges[0] = tLUID.LowPart;
                 const int bufLength = 256;
                 IntPtr tu = Marshal.AllocHGlobal(bufLength);
                 Marshal.StructureToPtr(tkp, tu, true);
                 if (AdjustTokenPrivileges(hToken, false, tu, bufLength, IntPtr.Zero, ref ltkpOld) != false)
                 {
                     int nErr = Marshal.GetLastWin32Error();
                     // successful AdjustTokenPrivileges doesn't mean privilege could be    changed
                     //ERROR_NOT_ALL_ASSIGNED   1300(0x514)
                     if (nErr == 0)
                     {
                         retval = true; // Token changed
                     }
                 }
                 TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tu, typeof(TOKEN_PRIVILEGES));
                 Marshal.FreeHGlobal(tu);
             }
         }
     }
     if (hToken != IntPtr.Zero)
     {
         CloseHandle(hToken);
     }
     return retval;
 }

Declarations :

 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
 public static extern uint RegOpenKeyEx(IntPtr hKey, string lpSubKey, uint ulOptions, int samDesired, ref IntPtr phkResult);
 public const int HKEY_CURRENT_USER = unchecked((int)0x80000001);
 public const int HKEY_CLASSES_ROOT = unchecked((int)0x80000000);
 public const int KEY_WOW64_64KEY = 0x0100;
 public const int WRITE_OWNER = 0x00080000;
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
 public static extern uint RegCloseKey(IntPtr hKey);
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
 public static extern bool LookupPrivilegeValue([In] string lpSystemName, [In] string lpName, [Out] out LUID Luid);
 [StructLayout(LayoutKind.Sequential)]
 public struct LUID
 {
     public int LowPart;
     public int HighPart;
 }
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
 public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, IntPtr NewState, int BufferLength, IntPtr PreviousState, ref int ReturnLength);
 [StructLayout(LayoutKind.Sequential)]
 public struct LUID_AND_ATTRIBUTES
 {
     public LUID Luid;
     public int Attributes;
 }
 [StructLayout(LayoutKind.Sequential)]
 internal struct TOKEN_PRIVILEGES
 {
     internal int PrivilegeCount;
     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
     internal int[] Privileges;
 }
 public const int TOKEN_ASSIGN_PRIMARY = 0x1;
 public const int TOKEN_DUPLICATE = 0x2;
 public const int TOKEN_IMPERSONATE = 0x4;
 public const int TOKEN_QUERY = 0x8;
 public const int TOKEN_QUERY_SOURCE = 0x10;
 public const int TOKEN_ADJUST_PRIVILEGES = 0x20;
 public const int TOKEN_ADJUST_GROUPS = 0x40;
 public const int TOKEN_ADJUST_DEFAULT = 0x80;
 public const int TOKEN_ALL_ACCESS = TOKEN_ASSIGN_PRIMARY
       + TOKEN_DUPLICATE + TOKEN_IMPERSONATE + TOKEN_QUERY
       + TOKEN_QUERY_SOURCE + TOKEN_ADJUST_PRIVILEGES
       + TOKEN_ADJUST_GROUPS + TOKEN_ADJUST_DEFAULT;
 public const string SE_RESTORE_NAME = "SeRestorePrivilege";
 public const string SE_DEBUG_NAME = "SeDebugPrivilege";
 public const string SE_TCB_NAME = "SeTcbPrivilege";
 public const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege";
 public const int SE_PRIVILEGE_ENABLED_BY_DEFAULT = (0x00000001);
 public const int SE_PRIVILEGE_ENABLED = (0x00000002);
 public const int SE_PRIVILEGE_REMOVED = (0X00000004);
 public const int SE_PRIVILEGE_USED_FOR_ACCESS = unchecked((int)0x80000000);
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
 public static extern bool OpenProcessToken(IntPtr hProcess, uint desiredAccess, out IntPtr hToken);
 [DllImport("Kernel32.dll", SetLastError = true)]
 public static extern bool CloseHandle(IntPtr hObject);
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
 public static extern uint SetSecurityInfo(IntPtr handle, SE_OBJECT_TYPE ObjectType, uint SecurityInfo,
     IntPtr psidOwner, IntPtr psidGroup, IntPtr pDacl, IntPtr pSacl);
 public const int OWNER_SECURITY_INFORMATION = 0x00000001;
 public enum SE_OBJECT_TYPE
 {
     SE_UNKNOWN_OBJECT_TYPE = 0,
     SE_FILE_OBJECT,
     SE_SERVICE,
     SE_PRINTER,
     SE_REGISTRY_KEY,
     SE_LMSHARE,
     SE_KERNEL_OBJECT,
     SE_WINDOW_OBJECT,
     SE_DS_OBJECT,
     SE_DS_OBJECT_ALL,
     SE_PROVIDER_DEFINED_OBJECT,
     SE_WMIGUID_OBJECT,
     SE_REGISTRY_WOW64_32KEY,
     SE_REGISTRY_WOW64_64KEY,
 }
 [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
 public static extern bool ConvertStringSidToSid(string StringSid, out IntPtr Sid);


问:
Fitting a sine wave model on POSIXt data and plotting using Ggplot2
Long-time reader, first-time asker here :)

I have some data collected at specific times and dates, and there is reason to hypothesize the data roughly follows a 24-hour cycle. I would like to fit a sine wave model on my data as a function of time, so that it is possible to test if future data points fall on the predicted pattern.

I have read this, this and this response but they are not solving my problem because in my case, I'm hoping to keep the x-axis data in POSIXct date-time format. That's how the data is collected and using this format makes for an easily interpreted plot.

Here's some reproducible data that is identical to my real data:

```<code>time <- c("2022-01-01 09:20:00", "2022-01-02 11:10:00",
          "2022-01-02 18:37:00", "2022-01-03 14:01:00",
          "2022-01-05 06:50:00", "2022-01-06 17:03:00")

time <- as.POSIXct(time)

value <- c(3, 6, 2, 8, 4, 1)
</code>```

These are plotted fine in base R:

```<code>plot(time, value)
</code>```

However, now I run into trouble when I try to construct a sine regression model that would fit the time series. I'm also struggling to fully understand the parameters required by nls function. Based on the previous examples, I have tried this approach (with comments on how I understand it working):

```<code>res <- nls(value ~ A * sin(omega * time + phi) + C,        # This is the basic sine-function format
           data = data.frame(time, value),                 # This defines the data used
           start = list(A = 1, omega = 1, phi = 1, C = 1)) # This gives nls the starting values?
</code>```

Here, I get an error message: "Error in Ops.POSIXt(omega, time) : '*' not defined for "POSIXt" objects" which I interpret as meaning the specific date format I would like to use is not acceptable for this type of approach. I know this, because if I simply replace the time variable with a dummy vector of integers, the model works fine and I'm able to plot it as follows:

```<code>time2 <- c(1, 2, 3, 4, 5, 6)
res <- nls(value ~ A * sin(omega * time2 + phi) + C,
       data = data.frame(time, value),
       start=list(A=1, omega=1, phi=1, C=1))

coefs <- coef(res)

fit <- function(x, a, b, c, d) {a * sin(b * x + c) + d}

plot(time2, value)
curve(fit(x, a = coefs["A"], b = coefs["omega"],
             c = coefs["phi"], d = coefs["C"]), add=TRUE,
             lwd=2, col="red")
</code>```

I know I'm on the right track but my main question is, how can I do the above process while maintaining the time variable in POSIXct format?

As mentioned, my main order of business would be to plot the data using Ggplot2, but I can't even begin to try that before I solve the initial problem. However, any pointers on how to get started with that are greatly appreciated! :)

答:
I would probably just generate a numeric number of days from an arbitrary origin time and use that. You can then modify your fit function so that it converts date-times to predicted values. You can then easily make a data frame of predictions from your model and plot that.

df <- data.frame(time = time, value = value)

origin <- as.POSIXct("2022-01-01 00:00:00")

df$days <- as.numeric(difftime(time, origin, unit = "day"))

res <- nls(value ~ A * sin(omega * days + phi) + C,
           data = df,
           start = list(A = 1, omega = 1, phi = 1, C = 1))

fit <- function(res, newdata) {

  x <- as.numeric(difftime(origin, newdata$time, units = "days"))
  C <- as.list(coef(res))
  C$A * sin(C$omega * x + C$phi) + C$C
}

new_df <- data.frame(time = origin + as.difftime(new_times, units = "days"))
new_df$value <- fit(res, new_df)

ggplot(df, aes(time, value)) +
  geom_point() +
  geom_line(data = new_df, colour = "gray") +
  theme_bw()
```

Body:
Long-time reader, first-time asker here :)

I have some data collected at specific times and dates, and there is reason to hypothesize the data roughly follows a 24-hour cycle. I would like to fit a sine wave model on my data as a function of time, so that it is possible to test if future data points fall on the predicted pattern.

I have read this, this and this response but they are not solving my problem because in my case, I'm hoping to keep the x-axis data in POSIXct date-time format. That's how the data is collected and using this format makes for an easily interpreted plot.

Here's some reproducible data that is identical to my real data:

time <- c("2022-01-01 09:20:00", "2022-01-02 11:10:00",
          "2022-01-02 18:37:00", "2022-01-03 14:01:00",
          "2022-01-05 06:50:00", "2022-01-06 17:03:00")

time <- as.POSIXct(time)

value <- c(3, 6, 2, 8, 4, 1)

These are plotted fine in base R:

plot(time, value)

However, now I run into trouble when I try to construct a sine regression model that would fit the time series. I'm also struggling to fully understand the parameters required by nls function. Based on the previous examples, I have tried this approach (with comments on how I understand it working):

res <- nls(value ~ A * sin(omega * time + phi) + C,        # This is the basic sine-function format
           data = data.frame(time, value),                 # This defines the data used
           start = list(A = 1, omega = 1, phi = 1, C = 1)) # This gives nls the starting values?

Here, I get an error message: "Error in Ops.POSIXt(omega, time) : '*' not defined for "POSIXt" objects" which I interpret as meaning the specific date format I would like to use is not acceptable for this type of approach. I know this, because if I simply replace the time variable with a dummy vector of integers, the model works fine and I'm able to plot it as follows:

time2 <- c(1, 2, 3, 4, 5, 6)
res <- nls(value ~ A * sin(omega * time2 + phi) + C,
       data = data.frame(time, value),
       start=list(A=1, omega=1, phi=1, C=1))

coefs <- coef(res)

fit <- function(x, a, b, c, d) {a * sin(b * x + c) + d}

plot(time2, value)
curve(fit(x, a = coefs["A"], b = coefs["omega"],
             c = coefs["phi"], d = coefs["C"]), add=TRUE,
             lwd=2, col="red")

I know I'm on the right track but my main question is, how can I do the above process while maintaining the time variable in POSIXct format?

As mentioned, my main order of business would be to plot the data using Ggplot2, but I can't even begin to try that before I solve the initial problem. However, any pointers on how to get started with that are greatly appreciated! :)


问:
CSRF cookie error after Django 3.2 update (DRF with token authentication)
I was looking to update my app backend from Django 3.1.14 (working fine but no longer supported) to a newer version (I tried both 3.2 and 4.0), but after updating I started getting a CSRF cookie error.

Forbidden (CSRF cookie not set.): /api-token-auth/

Does anybody by any chance know what's changed in Django in regard to CSRF, and how to avoid the errors?

I was under the impression that CSRF is not enforced when using Django Rest Framework with token authentication. I tried anyway to remove the 'django.middleware.csrf.CsrfViewMiddleware' middleware, to add @csrf_exempt to all the views, deleted all existing tokens and logged out of Django admin, but to no avail. My DRF configuration in settings.py is as follows:

```<code>INSTALLED_APPS = [
    'rest_framework',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}
</code>```

Edit: my own answer below

答:
The urlpatterns order in urls.py was the problem. This answer helped.

If the Django admin url is above the api urls, any api request will not even reach these apis and Django will throw the CSRF cookie error.

Working in Django 3.1, but not working in Django 3.2:

```<code>urlpatterns = [
    path('', admin.site.urls),
    url(r'^api-token-auth/', views.MyLoginToken.as_view()),
    url(r'^', include('myapp.backend.urls')),
]
</code>```

Working in Django 3.2:

```<code>urlpatterns = [
    url(r'^', include('myapp.backend.urls')),  # move CSRF exempt apis to the top
    url(r'^api-token-auth/', views.MyLoginToken.as_view()),
    path('', admin.site.urls),  # move CSRF protected endpoints to the end
]
</code>```

I couldn't find any documentation for this breaking change from Django 3.1 to Django 3.2.

Body:
I was looking to update my app backend from Django 3.1.14 (working fine but no longer supported) to a newer version (I tried both 3.2 and 4.0), but after updating I started getting a CSRF cookie error.

Forbidden (CSRF cookie not set.): /api-token-auth/

Does anybody by any chance know what's changed in Django in regard to CSRF, and how to avoid the errors?

I was under the impression that CSRF is not enforced when using Django Rest Framework with token authentication. I tried anyway to remove the 'django.middleware.csrf.CsrfViewMiddleware' middleware, to add @csrf_exempt to all the views, deleted all existing tokens and logged out of Django admin, but to no avail. My DRF configuration in settings.py is as follows:

INSTALLED_APPS = [
    'rest_framework',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

Edit: my own answer below

Body:
The urlpatterns order in urls.py was the problem. This answer helped.

If the Django admin url is above the api urls, any api request will not even reach these apis and Django will throw the CSRF cookie error.

Working in Django 3.1, but not working in Django 3.2:

urlpatterns = [
    path('', admin.site.urls),
    url(r'^api-token-auth/', views.MyLoginToken.as_view()),
    url(r'^', include('myapp.backend.urls')),
]

Working in Django 3.2:

urlpatterns = [
    url(r'^', include('myapp.backend.urls')),  # move CSRF exempt apis to the top
    url(r'^api-token-auth/', views.MyLoginToken.as_view()),
    path('', admin.site.urls),  # move CSRF protected endpoints to the end
]

I couldn't find any documentation for this breaking change from Django 3.1 to Django 3.2.


问:
Break While Loop adding "last" to

In WordPress, I'm using this:

```<code>while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
echo "<div class='test'>test</div>";
<?php endwhile; ?>
</code>```

I'd now like it so for every 2nd element, it would add the "last" class to the div, so the final code could be:

```<code><div class='test'>test</div>
<div class='test last'>test</div>
<div class='test'>test</div>
<div class='test last'>test</div>
<div class='test'>test</div>
<div class='test last'>test</div>.....
</code>```

Many thanks for any pointers.

答:
You can also use WordPress' built-in post count field, $wp_query->current_post</p>

```<code><?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
   <div class="test <?=$wp_query->current_post % 2 == 0 ? "last" : "";?>">test</div>
<?php endwhile; ?>
</code>```

Title: Break While Loop adding "last" to <div>

Body:
In WordPress, I'm using this:

while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
echo "
test
";
<?php endwhile; ?>

I'd now like it so for every 2nd element, it would add the "last" class to the div, so the final code could be:

test

test

test

test

test

test
.....

Many thanks for any pointers.

Body:
You can also use WordPress' built-in post count field, $wp_query->current_post

<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
   <div class="test <?=$wp_query->current_post % 2 == 0 ? "last" : "";?>">test</div>
<?php endwhile; ?>


问:
Error Vue.js "Cannot read property 'props' of undefined"
Did everything on gorails tutorial, but something wrong.
error message in Chrome:

```<code>Uncaught TypeError: Cannot read property 'props' of undefined
    at normalizeProps (vue.runtime.esm.js?ff9b:1291)
    at mergeOptions (vue.runtime.esm.js?ff9b:1363)
    at mergeOptions (vue.runtime.esm.js?ff9b:1372)
    at Vue$3.Vue._init (vue.runtime.esm.js?ff9b:4268)
    at new Vue$3 (vue.runtime.esm.js?ff9b:4384)
    at HTMLDocument.eval (hello_vue.js?94ab:29)
    at Object.t.dispatch (turbolinks.self-)
    at r.t.Controller.r.notifyApplicationAfterPageLoad ...)
    at r.t.Controller.r.pageLoaded (t...)
    at turbolinks.self...
</code>```

Hello_vue file:

```<code>import Vue from 'vue'
import TurbolinksAdapter from "vue-turbolinks"
import VueResource from "vue-resource"

Vue.use(VueResource);

document.addEventListener('turbolinks:load', () => {

    Vue.http.headers.common["X-CSRF-Token"] = document.querySelector('meta[name="csrf-token"]').getAttribute("content");

  var element = document.getElementById("team-form")

  if(element != null){

    var team = JSON.parse(element.dataset.team);
    var players_attributes = JSON.parse(element.dataset.playersAttributes);
    players_attributes.forEach(function(player){
        player._destroy = null
    })
    team.players_attributes = players_attributes;

    var app = new Vue({
        el: element,
        mixins: [TurbolinksAdapter],
        data: function(){
            return { team: team }
        },
        methods: {
            addPlayer: function(){
                team.players_attributes.push({
                id: null,
                name: "",
                _destroy: null
                })
            }
        }
    });
  }
});
</code>```

as I understand, an error in the initialization of the App object, but I can not understand in what exactly. I kind of did it right.

答:
Probably late to the party and since this was the second answer google showed, thought this would help someone!

If anyone faced this because of provide/inject, I might probably have to do with vue2 / vue3. I read articles on provide/inject in vue3 and used it in my vue2 project ♂

I was using reactive in vue2 like:

```<code>import { reactive } from 'vue'

provide() {
  return {
    loadingState: new reactive(() => this.loadingState)
  }
}
</code>```

Later changed it to:

```<code>provide() {
  return {
    loadingState: this.loadingState
  }
}
</code>```

Body:
Did everything on gorails tutorial, but something wrong.
error message in Chrome:

Uncaught TypeError: Cannot read property 'props' of undefined
    at normalizeProps (vue.runtime.esm.js?ff9b:1291)
    at mergeOptions (vue.runtime.esm.js?ff9b:1363)
    at mergeOptions (vue.runtime.esm.js?ff9b:1372)
    at Vue$3.Vue._init (vue.runtime.esm.js?ff9b:4268)
    at new Vue$3 (vue.runtime.esm.js?ff9b:4384)
    at HTMLDocument.eval (hello_vue.js?94ab:29)
    at Object.t.dispatch (turbolinks.self-)
    at r.t.Controller.r.notifyApplicationAfterPageLoad ...)
    at r.t.Controller.r.pageLoaded (t...)
    at turbolinks.self...

Hello_vue file:

import Vue from 'vue'
import TurbolinksAdapter from "vue-turbolinks"
import VueResource from "vue-resource"

Vue.use(VueResource);

document.addEventListener('turbolinks:load', () => {

    Vue.http.headers.common["X-CSRF-Token"] = document.querySelector('meta[name="csrf-token"]').getAttribute("content");

  var element = document.getElementById("team-form")

  if(element != null){

    var team = JSON.parse(element.dataset.team);
    var players_attributes = JSON.parse(element.dataset.playersAttributes);
    players_attributes.forEach(function(player){
        player._destroy = null
    })
    team.players_attributes = players_attributes;

    var app = new Vue({
        el: element,
        mixins: [TurbolinksAdapter],
        data: function(){
            return { team: team }
        },
        methods: {
            addPlayer: function(){
                team.players_attributes.push({
                id: null,
                name: "",
                _destroy: null
                })
            }
        }
    });
  }
});

as I understand, an error in the initialization of the App object, but I can not understand in what exactly. I kind of did it right.

Body:
Probably late to the party and since this was the second answer google showed, thought this would help someone!

If anyone faced this because of provide/inject, I might probably have to do with vue2 / vue3. I read articles on provide/inject in vue3 and used it in my vue2 project ♂

I was using reactive in vue2 like:

import { reactive } from 'vue'

provide() {
  return {
    loadingState: new reactive(() => this.loadingState)
  }
}

Later changed it to:

provide() {
  return {
    loadingState: this.loadingState
  }
}


问:
PYTHON 3.6.0 & DJANGO 3.5.0 'module' object is not iterable when running django website to the server
So i'm gonna run my Django project with python manage.py runserver but suddenly there comes an error like these:

```<code>Exception in thread django-main-thread:
Traceback (most recent call last):
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 395, in check
    include_deployment_checks=include_deployment_checks,
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'project_settings.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
</code>```

And there is my project.settings.urls

```<code>"""project_settings URL Configuration
"""
from django.contrib import admin
from django.urls import path, include

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', include('ml_app.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

And here are my ml_app.urls

```<code>        """project_settings URL Configuration """
from django.contrib import admin
from django.urls import path, include
from . import views
from .views import about, index, predict_page,cuda_full

        app_name = 'ml_app' handler404 = views.handler404

        urlpatterns = [
            path('', index, name='home'),
            path('about/', about, name='about'),
            path('predict/', predict_page, name='predict'),
            path('cuda_full/',cuda_full,name='cuda_full'),
    ]
</code>```

Does someone know how to fix that error? It's pretty important for my final test =(

答:
I think your app urls.py should be somethings like this:</p>
```<code>        """project_settings URL Configuration """
from django.contrib import admin
from django.urls import path, include
from your-app-name import views

        app_name = 'ml_app' handler404 = views.handler404

        urlpatterns = [
            path('', views.index, name='home'),
            path('about/', views.about, name='about'),
            path('predict/', views.predict_page, name='predict'),
            path('cuda_full/',views.cuda_full,name='cuda_full'),
    ]
</code>```

Body:
So i'm gonna run my Django project with python manage.py runserver but suddenly there comes an error like these:

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 395, in check
    include_deployment_checks=include_deployment_checks,
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\ITHB MIT\TUGAS AKHIR\PRACTICE\program\Django Application\venv\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'project_settings.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

And there is my project.settings.urls

"""project_settings URL Configuration
"""
from django.contrib import admin
from django.urls import path, include

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', include('ml_app.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And here are my ml_app.urls

        """project_settings URL Configuration """
from django.contrib import admin
from django.urls import path, include
from . import views
from .views import about, index, predict_page,cuda_full

        app_name = 'ml_app' handler404 = views.handler404

        urlpatterns = [
            path('', index, name='home'),
            path('about/', about, name='about'),
            path('predict/', predict_page, name='predict'),
            path('cuda_full/',cuda_full,name='cuda_full'),
    ]

Does someone know how to fix that error? It's pretty important for my final test =(

Body:
I think your app urls.py should be somethings like this:

        """project_settings URL Configuration """
from django.contrib import admin
from django.urls import path, include
from your-app-name import views

        app_name = 'ml_app' handler404 = views.handler404

        urlpatterns = [
            path('', views.index, name='home'),
            path('about/', views.about, name='about'),
            path('predict/', views.predict_page, name='predict'),
            path('cuda_full/',views.cuda_full,name='cuda_full'),
    ]