问:
Selecting multiple radio buttons (through jquery, javasscript?)
I currently have a form with lets say 5 radio button entries (see below).
What im looking archive is the following:
- Being able to choose multiple radio buttons - lets say 3 and submit the form.

Currently I got it working fine with PHP, SQL, but im only able to choose one radiobutton and submit that.

I figure it would also come in handy being able to deselect a radio button in case you wrongly click one.

My guess is that this can be done through some javascript? Any suggestions? Online examples perhaps?

```<code><form id="pollform" action="poll.php" method="post">
<input id="option-1" type="radio" value="1" name="poll">
<label for="option-1">Select option 1</label>

<input id="option-2" type="radio" value="2" name="poll">
<label for="option-2">Select option 2</label>

<input id="option-3" type="radio" value="3" name="poll">
<label for="option-3">Select option 3</label>

<input id="option-4" type="radio" value="4" name="poll">
<label for="option-4">Select option 4</label>

<input id="option-5" type="radio" value="5" name="poll">
<label for="option-5">Select option 5</label>
</form>
</code>```

答: Radio buttons are designed for only 1 item to be selected, use checkboxes instead.</p>

Body:
I currently have a form with lets say 5 radio button entries (see below).
What im looking archive is the following:
- Being able to choose multiple radio buttons - lets say 3 and submit the form.

Currently I got it working fine with PHP, SQL, but im only able to choose one radiobutton and submit that.

I figure it would also come in handy being able to deselect a radio button in case you wrongly click one.

My guess is that this can be done through some javascript? Any suggestions? Online examples perhaps?

<form id="pollform" action="poll.php" method="post">
<input id="option-1" type="radio" value="1" name="poll">
Select option 1

<input id="option-2" type="radio" value="2" name="poll">
Select option 2

<input id="option-3" type="radio" value="3" name="poll">
Select option 3

<input id="option-4" type="radio" value="4" name="poll">
Select option 4

<input id="option-5" type="radio" value="5" name="poll">
Select option 5
</form>


来源: stackexchange

问:
Is there a way to stop the user from typing in a textbox after they enter a bad character?
I don't want to disable the input box, I'd like to either delete the bad character or allow the user to delete it.

So far I've tried to set the max length of the input to the length where the bad character was entered, but I was still able to type after that.

Here is a sample of the function I'm working on:

```<code>function validateCharacterName() {
var value = document.getElementById("characterName").value;
var message = document.getElementById("characterNameMessage");
var button = document.getElementById("confirmButton")

if (value.length <= 1) {
    message.innerText = "Name must be two or more characters."
    disableButton(button)
} else {
    for (var counter = 0 ; counter < value.length; counter++) {
        var character = value.charAt(counter);

        if (isAlpha(character) && !isDigit(character)) {
            message.innerText = "";
            enableButton(button);
        } else {
            message.innerText = "Character '" + character + "' is invalid.";
            disableButton(button);
        }
     }
}
</code>```

}

答:
The recommended way to ensure the entered text only contains expected characters is using the the pattern attribute. This works slightly different than you suggest, but will be more in line of what the user would expect, as it is a very common way how to do this. Here you can see this in action.

To be specific here is an example how you avoid the letter "a":

```<code><input type="text" pattern="[^a]*" title="Please avoid the letter 'a'">
</code>```

The pattern attribute uses regular expressions. This does need some getting used to, but is rather powerful. In this case the ^ insider the [] means "not". The a means "a" and the * means allow any number of appearances of the previous thing. In summary this means allow any number of any character not being an "a".

You might want to use a whitelist approach rather than a blacklist approach. For example to allow any Latin letters you could use:

```<code><input type="text" pattern="[a-zA-Z]*" title="Please use letters only">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I don't want to disable the input box, I'd like to either delete the bad character or allow the user to delete it.

So far I've tried to set the max length of the input to the length where the bad character was entered, but I was still able to type after that.

Here is a sample of the function I'm working on:

function validateCharacterName() {
var value = document.getElementById("characterName").value;
var message = document.getElementById("characterNameMessage");
var button = document.getElementById("confirmButton")

if (value.length <= 1) {
    message.innerText = "Name must be two or more characters."
    disableButton(button)
} else {
    for (var counter = 0 ; counter < value.length; counter++) {
        var character = value.charAt(counter);

        if (isAlpha(character) && !isDigit(character)) {
            message.innerText = "";
            enableButton(button);
        } else {
            message.innerText = "Character '" + character + "' is invalid.";
            disableButton(button);
        }
     }
}

}

Body:
The recommended way to ensure the entered text only contains expected characters is using the the pattern attribute. This works slightly different than you suggest, but will be more in line of what the user would expect, as it is a very common way how to do this. Here you can see this in action.

To be specific here is an example how you avoid the letter "a":

<input type="text" pattern="[^a]*" title="Please avoid the letter 'a'">

The pattern attribute uses regular expressions. This does need some getting used to, but is rather powerful. In this case the ^ insider the [] means "not". The a means "a" and the * means allow any number of appearances of the previous thing. In summary this means allow any number of any character not being an "a".

You might want to use a whitelist approach rather than a blacklist approach. For example to allow any Latin letters you could use:

<input type="text" pattern="[a-zA-Z]*" title="Please use letters only">


问:
Creating a subgraph using Cypher projection
I am trying to create a subgraph of my graph using Cypher projection because I want to use the GDS library. First, I am creating a subgraph using Cypher query which works perfectly fine. Here is the query:

```<code>// Filter for only recurrent events
WITH [path=(m:IDHcodel)--(n:Tissue)
WHERE (m.node_category = 'molecular' AND n.event_class = 'Recurrence')
    AND NOT EXISTS((m)--(:Tissue{event_class:'Primary'})) | m] AS recur_events

// Obtain the sub-network with 2 or more patients in edges
MATCH p=(m1)-[r:hasIDHcodelPatients]->(m2)
WHERE (m1 IN recur_events AND m2 IN recur_events AND r.total_common_patients >= 2)
WITH COLLECT(p) AS all_paths
WITH [p IN all_paths | nodes(p)] AS path_nodes, [p IN all_paths | relationships(p)]  AS path_rels
RETURN apoc.coll.toSet(apoc.coll.flatten(path_nodes)) AS subgraph_nodes, apoc.coll.flatten(path_rels) AS subgraph_rels
</code>```

So far so good. Now all I am trying to do is a Cypher projection by sending the subgraph nodes and subgraph rels as parameters in the GDS create query and this gives me a null pointer exception:

```<code>// All the above lines except using WITH instead of RETRUN in the last line. ie.,

...

WITH apoc.coll.toSet(apoc.coll.flatten(path_nodes)) AS subgraph_nodes, apoc.coll.flatten(path_rels) AS subgraph_rels

// Call gds library to create a graph by sending subgraph_nodes and subgraph_rels as parameters
CALL gds.graph.create.cypher(
    'example',
    'MATCH (n) where n in $sn RETURN id(n) as id',
    'MATCH ()-[r]-() where r in $sr RETURN r.start as source , r.end as target',
    {parameters: {sn: subgraph_nodes, sr: subgraph_rels} }
) YIELD graphName AS graph, nodeQuery, nodeCount AS nodes, relationshipQuery, relationshipCount AS rels

RETURN graph
</code>```

What could be wrong? Thanks.

答:
To access start and end node of a relationship, there is a slightly different syntax that you are using:

```<code>WITH apoc.coll.toSet(apoc.coll.flatten(path_nodes)) AS subgraph_nodes, apoc.coll.flatten(path_rels) AS subgraph_rels

// Call gds library to create a graph by sending subgraph_nodes and subgraph_rels as parameters
CALL gds.graph.create.cypher(
    'example',
    'MATCH (n) where n in $sn RETURN id(n) as id',
    'MATCH ()-[r]-() where r in $sr RETURN id(startNode(r)) as source , id(endNode(r)) as target',
    {parameters: {sn: subgraph_nodes, sr: subgraph_rels} }
) YIELD graphName AS graph, nodeQuery, nodeCount AS nodes, relationshipQuery, relationshipCount AS rels

RETURN graph
</code>```

This is what I noticed, hopefully this is the only error.

Body:
I am trying to create a subgraph of my graph using Cypher projection because I want to use the GDS library. First, I am creating a subgraph using Cypher query which works perfectly fine. Here is the query:

// Filter for only recurrent events
WITH [path=(m:IDHcodel)--(n:Tissue)
WHERE (m.node_category = 'molecular' AND n.event_class = 'Recurrence')
    AND NOT EXISTS((m)--(:Tissue{event_class:'Primary'})) | m] AS recur_events

// Obtain the sub-network with 2 or more patients in edges
MATCH p=(m1)-[r:hasIDHcodelPatients]->(m2)
WHERE (m1 IN recur_events AND m2 IN recur_events AND r.total_common_patients >= 2)
WITH COLLECT(p) AS all_paths
WITH [p IN all_paths | nodes(p)] AS path_nodes, [p IN all_paths | relationships(p)]  AS path_rels
RETURN apoc.coll.toSet(apoc.coll.flatten(path_nodes)) AS subgraph_nodes, apoc.coll.flatten(path_rels) AS subgraph_rels

So far so good. Now all I am trying to do is a Cypher projection by sending the subgraph nodes and subgraph rels as parameters in the GDS create query and this gives me a null pointer exception:

// All the above lines except using WITH instead of RETRUN in the last line. ie.,

...

WITH apoc.coll.toSet(apoc.coll.flatten(path_nodes)) AS subgraph_nodes, apoc.coll.flatten(path_rels) AS subgraph_rels

// Call gds library to create a graph by sending subgraph_nodes and subgraph_rels as parameters
CALL gds.graph.create.cypher(
    'example',
    'MATCH (n) where n in $sn RETURN id(n) as id',
    'MATCH ()-[r]-() where r in $sr RETURN r.start as source , r.end as target',
    {parameters: {sn: subgraph_nodes, sr: subgraph_rels} }
) YIELD graphName AS graph, nodeQuery, nodeCount AS nodes, relationshipQuery, relationshipCount AS rels

RETURN graph

What could be wrong? Thanks.

Body:
To access start and end node of a relationship, there is a slightly different syntax that you are using:

WITH apoc.coll.toSet(apoc.coll.flatten(path_nodes)) AS subgraph_nodes, apoc.coll.flatten(path_rels) AS subgraph_rels

// Call gds library to create a graph by sending subgraph_nodes and subgraph_rels as parameters
CALL gds.graph.create.cypher(
    'example',
    'MATCH (n) where n in $sn RETURN id(n) as id',
    'MATCH ()-[r]-() where r in $sr RETURN id(startNode(r)) as source , id(endNode(r)) as target',
    {parameters: {sn: subgraph_nodes, sr: subgraph_rels} }
) YIELD graphName AS graph, nodeQuery, nodeCount AS nodes, relationshipQuery, relationshipCount AS rels

RETURN graph

This is what I noticed, hopefully this is the only error.


问:
How to write curl --form using python requests
I want to translate this curl command to python and I am having issue to write form properly:

```<code>     "https://gitlab.example.com/api/v4/projects/1/variables/NEW_VARIABLE" --form "value=updated value"
</code>```

I tried :

```<code>       files = {'file': ('somename.csv',  'value=updated value')}

and
        files = {}
        files['value'] = 'updated value'
and
files = dict(value=value_to_update)
</code>```

The whole example:

```<code>        url = 'https://gitlab.com/api/v4/projects/1/variables/bla?filter[environment_scope]=production'
        headers = {
            'content-type': 'application/json',
            'PRIVATE-TOKEN': '<token>'
        }
        files = dict(value=value_to_update)
        x = requests.put(url, headers=headers, files=files)
</code>```

Solved: This is how whole request in python using requests should look like
```</p>
```   headers = {
        'PRIVATE-TOKEN': '<token>',
    }

    files = {
        'value': (None, 'update value'),
    }

    response = requests.put('https://gitlab.com/api/v4/projects/1/variables/variableKey', headers=headers, files=files)
```
``````

答:
this is the conversion to python requests:</p>
```<code>import requests

files = {
    'value': (None, 'updated value'),
}

response = requests.post('https://gitlab.example.com/api/v4/projects/1/variables/NEW_VARIABLE', files=files)
</code>```

Body:
I want to translate this curl command to python and I am having issue to write form properly:

     "https://gitlab.example.com/api/v4/projects/1/variables/NEW_VARIABLE" --form "value=updated value"

I tried :

       files = {'file': ('somename.csv',  'value=updated value')}

and
        files = {}
        files['value'] = 'updated value'
and
files = dict(value=value_to_update)

The whole example:

        url = 'https://gitlab.com/api/v4/projects/1/variables/bla?filter[environment_scope]=production'
        headers = {
            'content-type': 'application/json',
            'PRIVATE-TOKEN': '<token>'
        }
        files = dict(value=value_to_update)
        x = requests.put(url, headers=headers, files=files)

Solved: This is how whole request in python using requests should look like
```

   headers = {
        'PRIVATE-TOKEN': '<token>',
    }

    files = {
        'value': (None, 'update value'),
    }

    response = requests.put('https://gitlab.com/api/v4/projects/1/variables/variableKey', headers=headers, files=files)

Body:
this is the conversion to python requests:

import requests

files = {
    'value': (None, 'updated value'),
}

response = requests.post('https://gitlab.example.com/api/v4/projects/1/variables/NEW_VARIABLE', files=files)


问:
Convert object to an array of objects?
I have an object that looks like this:

```<code>{
  "1": "Technology",
  "2": "Startup",
  "3": "IT",
}
</code>```

and I need to convert it to an array of objects that would look like this:

```<code>[
  {id: 1, name: "Technology"},
  {id: 2, name: "Startup"},
  {id: 3, name: "IT"}
]
</code>```

What would be the cleanest & efficient way to do this?

答:
Nowadays you can use Object.entries() to turn an object into an array of key-value pairs (also stored as an array).

This allows us to take advantage of array destructuring so we can make this a nice one-liner:

const obj = {
  "1": "Technology",
  "2": "Startup",
  "3": "IT",
};

const result = Object.entries(obj).map(([id, name]) => ({id: +id, name}));

console.log(result);```

Adding in a unary plus (+) to turn the id (which is a string) into a number.

ContentLicense: CC BY-SA 3.0

Title: Convert object to an array of objects?

Body:
I have an object that looks like this:

{
  "1": "Technology",
  "2": "Startup",
  "3": "IT",
}

and I need to convert it to an array of objects that would look like this:

[
  {id: 1, name: "Technology"},
  {id: 2, name: "Startup"},
  {id: 3, name: "IT"}
]

What would be the cleanest & efficient way to do this?

Body:
Nowadays you can use Object.entries() to turn an object into an array of key-value pairs (also stored as an array).

This allows us to take advantage of array destructuring so we can make this a nice one-liner:

const obj = {
  "1": "Technology",
  "2": "Startup",
  "3": "IT",
};

const result = Object.entries(obj).map(([id, name]) => ({id: +id, name}));

console.log(result);

Adding in a unary plus (+) to turn the id (which is a string) into a number.


问:
XSL: change attribute value of an element whose parent element attribute has a specific value
I want to modify an XML file created by Tableau using an XSL transformation.

What I need is to change the formula value of the calculation element only if the parent element has the value "ifShow" in the caption attribute.

my XML is of the form:

```<code><?xml version='1.0' encoding='utf-8' ?>
<!-- build 20212.21.1112.1433 -->
<workbook source-build='2021.2.5 (20212.21.1112.1433)' source-platform='win' version='18.1' xml:base='https://tableau.company.com' xmlns:user='http://www.tableausoftware.com/xml/user'>
  <datasources>
    <datasource caption='V_Tableau_CommercialLayer' inline='true' name='sqlproxy' version='18.1'>
      <column caption='Month' datatype='string' name='[Calculation_36]' role='dimension' type='nominal'>
        <calculation class='tableau' formula='no change' />
      </column>
      <column caption='ifShow' datatype='string' name='[Calculation_40]' role='dimension' type='nominal'>
        <calculation class='tableau' formula='old code' />
      </column>
     </datasource>
  </datasources>
</workbook>
</code>```

Desired output:

```<code><?xml version='1.0' encoding='utf-8' ?>
<!-- build 20212.21.1112.1433 -->
<workbook source-build='2021.2.5 (20212.21.1112.1433)' source-platform='win' version='18.1' xml:base='https://tableau.company.com' xmlns:user='http://www.tableausoftware.com/xml/user'>
  <datasources>
    <datasource caption='V_Tableau_CommercialLayer' inline='true' name='sqlproxy' version='18.1'>
      <column caption='Month' datatype='string' name='[Calculation_36]' role='dimension' type='nominal'>
        <calculation class='tableau' formula='no change' />
      </column>
      <column caption='ifShow' datatype='string' name='[Calculation_40]' role='dimension' type='nominal'>
        <calculation class='tableau' formula='new code' />
      </column>
     </datasource>
  </datasources>
</workbook>
</code>```

The XSL I am using is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:param name="pNewFormula" select="'new code'"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="column/@caption[. ='ifShow']/calculation">
        <xsl:attribute name="formula">
            <xsl:value-of select="$pNewFormula"/>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>
</code>```

However, this doesn't work and I do not know how to access the child node of the element column

Thank you very much for your support!

答:
How about:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="pNewFormula" select="'new code'"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="column[@caption='ifShow']/calculation/@formula">
    <xsl:attribute name="formula">
        <xsl:value-of select="$pNewFormula"/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
I want to modify an XML file created by Tableau using an XSL transformation.

What I need is to change the formula value of the calculation element only if the parent element has the value "ifShow" in the caption attribute.

my XML is of the form:

<?xml version='1.0' encoding='utf-8' ?>

<workbook source-build='2021.2.5 (20212.21.1112.1433)' source-platform='win' version='18.1' xml:base='https://tableau.company.com' xmlns:user='http://www.tableausoftware.com/xml/user'>
  <datasources>
    <datasource caption='V_Tableau_CommercialLayer' inline='true' name='sqlproxy' version='18.1'>
      <column caption='Month' datatype='string' name='[Calculation_36]' role='dimension' type='nominal'>
        <calculation class='tableau' formula='no change' />
      </column>
      <column caption='ifShow' datatype='string' name='[Calculation_40]' role='dimension' type='nominal'>
        <calculation class='tableau' formula='old code' />
      </column>
     </datasource>
  </datasources>
</workbook>

Desired output:

<?xml version='1.0' encoding='utf-8' ?>

<workbook source-build='2021.2.5 (20212.21.1112.1433)' source-platform='win' version='18.1' xml:base='https://tableau.company.com' xmlns:user='http://www.tableausoftware.com/xml/user'>
  <datasources>
    <datasource caption='V_Tableau_CommercialLayer' inline='true' name='sqlproxy' version='18.1'>
      <column caption='Month' datatype='string' name='[Calculation_36]' role='dimension' type='nominal'>
        <calculation class='tableau' formula='no change' />
      </column>
      <column caption='ifShow' datatype='string' name='[Calculation_40]' role='dimension' type='nominal'>
        <calculation class='tableau' formula='new code' />
      </column>
     </datasource>
  </datasources>
</workbook>

The XSL I am using is:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:param name="pNewFormula" select="'new code'"/>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="column/@caption[. ='ifShow']/calculation">
        <xsl:attribute name="formula">
            <xsl:value-of select="$pNewFormula"/>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

However, this doesn't work and I do not know how to access the child node of the element column

Thank you very much for your support!

Body:
How about:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="pNewFormula" select="'new code'"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="column[@caption='ifShow']/calculation/@formula">
    <xsl:attribute name="formula">
        <xsl:value-of select="$pNewFormula"/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>


问:
Using Numpy (np.linalg.svd) for Singular Value Decomposition
Im reading Abdi & Williams (2010) "Principal Component Analysis", and I'm trying to redo the SVD to attain values for further PCA.

The article states that following SVD:

X = P D Q^t

I load my data in a np.array X.

```<code>X = np.array(data)
P, D, Q = np.linalg.svd(X, full_matrices=False)
D = np.diag(D)
</code>```

But i do not get the above equality when checking with

```<code>X_a = np.dot(np.dot(P, D), Q.T)
</code>```

X_a and X are the same dimensions, but the values are not the same. Am I missing something, or is the functionality of the np.linalg.svd function not compatible somehow with the equation in the paper?

答: Though this post is quite old, I thought it deserves a crucial update. In the above answers, the right singular vectors (typically placed in columns of the matrix V) are said to be given directly as columns from np.linalg.svd(). However, this is incorrect. The matrix return from np.linalg.svd() is Vh, the hermitian or conjugate transpose of V, therefore the right singular vectors are in fact in the rows of Vh. Be careful with this as the matrix itself is square so you cannot determine this correctly using the shape, but you can use reconstruction to test if you are viewing the matrix correctly.</p>

Body:
Im reading Abdi & Williams (2010) "Principal Component Analysis", and I'm trying to redo the SVD to attain values for further PCA.

The article states that following SVD:

X = P D Q^t

I load my data in a np.array X.

X = np.array(data)
P, D, Q = np.linalg.svd(X, full_matrices=False)
D = np.diag(D)

But i do not get the above equality when checking with

X_a = np.dot(np.dot(P, D), Q.T)

X_a and X are the same dimensions, but the values are not the same. Am I missing something, or is the functionality of the np.linalg.svd function not compatible somehow with the equation in the paper?


问:
Adding multiple files with one command
I tried to give a sample of a list of my titles. Here it is:

'197. Module Introduction.txt' '198. Our Starting Setup.txt' "199. What's So Complex About Forms.txt" '200. Dealing With Form Submission & Getting User Input Values.txt' '201. Adding Basic Validation.txt' '202. Providing Validation Feedback.txt' '203. Handling the "was touched" State.txt' '204. React To Lost Focus.txt' '205. Refactoring & Deriving States.txt' '206. Managing The Overall Form Validity.txt' 'Assignment 5: Time to Practice: Forms.txt' '207. Adding A Custom Input Hook.txt' '208. Re-Using The Custom Hook.txt' '209. A Challenge For You.txt' '210. Applying Our Hook & Knowledge To A New Form.txt' '211. Summary.txt' '212. Bonus: Using useReducer.txt' '213. Module Resources'.txt

All those titles were in a text file named lectures.txt.

I wanted to create a series of titled blank text files in a folder I had already created to receive them. Each text file should have the specific titles as in that example list. Ultimately I would be creating nearly 500 files, but all of them would have very specific meaningful titles.

I tried to follow all the instructions I found on this forum and elsewhere, on a very long search for help. None of them directly addressed my problem.

They all gave answers for creating multiple files with meaningless names. I don't see the utility in creating a bunch of files named 1.txt, etc, or a.txt, or some combination with a leading standard meaningless lead like filename, or sample...

I may be wrong about that lack of usefulness, but at the very least, it's not what I tried to ask and get an answer for.

I already have the meaningful filenames I want, a lot of them. I want to create many empty text files with names that I already have.

The only remotely useful suggestion (for me) that I got was using touch from a linux or bash prompt.

I found that if I wrapped my titles in quotations and separated the titles by a single space I could get the touch command to kind of work. I also discovered that my file titles could not contain any forward slashes ("/"). Nobody explained to me that the titles had to be wrapped in quotes. I figured that out quickly. Nobody told me how to separate the filenames. I experimented until I found a separation that worked.

I tried some experimenting with the {} bracing and the touch command but wound up not being able to figure out how that could help me in my particular case.

Also, I don't know if it has to do with a buffer on the bash or in PowerShell (I tried using both the Git installation in Windows 10 and bash from PowerShell 7.2.1, but I found that only about seven titles in the list would be touched. The rest resulted in a command not found error.

I broke up the list into about seven titles each and ran touch on each of those filenames (my titles) list segments. That way, on that very list sample I display above from my lectures.txt file, I got my empty text files created successfully, even though I had to do it in three touch commands.

I may have confused some of the people who tried to help me by putting all the titles in a text file that I named lectures.txt.
The contents of that file were the titles I wanted for my text files. Thank you so much those who did reach out to me.

I had already found something that might work in bash but I couldn't get it to work. It was roughly on the line of

```<code>`touch prefix{1..3}.txt`
</code>```

This had the same problem that all the other command suggestions I found had as well, like

echo > filename.extension

The same for the apparently most popular

```<code>for /l %a in (1 1 10) do type nul > "%a.txt"
</code>```

which created ten files named 1.txt through 10.txt. That was not the least bit useful to me.

I know my question got voted down as being exceptionally bad, but I'm editing and adding what I found out, so maybe sort of answering my own question.

If you are looking to do what I'm trying to do, and not just create meaningless filenames, I hope you will find some of what I did helpful. Here's a list of suggested solutions of which NONE did I find useful.

https://techpp.com/2021/08/22/create-file-using...

https://www.quora.com/Can-you-create-multiple-f...

https://www.howtogeek.com/725207/how-to-create-...

How to create multiple empty files on cmd(Windows).

Create multiple files with Powershell?.

https://www.laptopmag.com/how-to/create-multipl...

答:
Remember that using space in bash is not recommended, but if you need to...

You can try something like that:

```<code>counter=1
for title in $(cat lectures.txt)
do
  touch "$counter - $title.txt"
  counter=$((counter+1))
done
</code>```

EDIT

I only added the title on lectures.txt

NEW EDIT

If lectures.txt has 1 title per line you can do this:

```<code>while IFS= read -r line || [ -n "$line" ]
do
  touch "$line"
done < lectures.txt
</code>```

Title: Adding multiple files with one command

Body:
I tried to give a sample of a list of my titles. Here it is:

'197. Module Introduction.txt' '198. Our Starting Setup.txt' "199. What's So Complex About Forms.txt" '200. Dealing With Form Submission & Getting User Input Values.txt' '201. Adding Basic Validation.txt' '202. Providing Validation Feedback.txt' '203. Handling the "was touched" State.txt' '204. React To Lost Focus.txt' '205. Refactoring & Deriving States.txt' '206. Managing The Overall Form Validity.txt' 'Assignment 5: Time to Practice: Forms.txt' '207. Adding A Custom Input Hook.txt' '208. Re-Using The Custom Hook.txt' '209. A Challenge For You.txt' '210. Applying Our Hook & Knowledge To A New Form.txt' '211. Summary.txt' '212. Bonus: Using useReducer.txt' '213. Module Resources'.txt

All those titles were in a text file named lectures.txt.

I wanted to create a series of titled blank text files in a folder I had already created to receive them. Each text file should have the specific titles as in that example list. Ultimately I would be creating nearly 500 files, but all of them would have very specific meaningful titles.

I tried to follow all the instructions I found on this forum and elsewhere, on a very long search for help. None of them directly addressed my problem.

They all gave answers for creating multiple files with meaningless names. I don't see the utility in creating a bunch of files named 1.txt, etc, or a.txt, or some combination with a leading standard meaningless lead like filename, or sample...

I may be wrong about that lack of usefulness, but at the very least, it's not what I tried to ask and get an answer for.

I already have the meaningful filenames I want, a lot of them. I want to create many empty text files with names that I already have.

The only remotely useful suggestion (for me) that I got was using touch from a linux or bash prompt.

I found that if I wrapped my titles in quotations and separated the titles by a single space I could get the touch command to kind of work. I also discovered that my file titles could not contain any forward slashes ("/"). Nobody explained to me that the titles had to be wrapped in quotes. I figured that out quickly. Nobody told me how to separate the filenames. I experimented until I found a separation that worked.

I tried some experimenting with the {} bracing and the touch command but wound up not being able to figure out how that could help me in my particular case.

Also, I don't know if it has to do with a buffer on the bash or in PowerShell (I tried using both the Git installation in Windows 10 and bash from PowerShell 7.2.1, but I found that only about seven titles in the list would be touched. The rest resulted in a command not found error.

I broke up the list into about seven titles each and ran touch on each of those filenames (my titles) list segments. That way, on that very list sample I display above from my lectures.txt file, I got my empty text files created successfully, even though I had to do it in three touch commands.

I may have confused some of the people who tried to help me by putting all the titles in a text file that I named lectures.txt.
The contents of that file were the titles I wanted for my text files. Thank you so much those who did reach out to me.

I had already found something that might work in bash but I couldn't get it to work. It was roughly on the line of

`touch prefix{1..3}.txt`

This had the same problem that all the other command suggestions I found had as well, like

echo > filename.extension

The same for the apparently most popular

for /l %a in (1 1 10) do type nul > "%a.txt"

which created ten files named 1.txt through 10.txt. That was not the least bit useful to me.

I know my question got voted down as being exceptionally bad, but I'm editing and adding what I found out, so maybe sort of answering my own question.

If you are looking to do what I'm trying to do, and not just create meaningless filenames, I hope you will find some of what I did helpful. Here's a list of suggested solutions of which NONE did I find useful.

https://techpp.com/2021/08/22/create-file-using...

https://www.quora.com/Can-you-create-multiple-f...

https://www.howtogeek.com/725207/how-to-create-...

How to create multiple empty files on cmd(Windows).

Create multiple files with Powershell?.

https://www.laptopmag.com/how-to/create-multipl...

Body:
Remember that using space in bash is not recommended, but if you need to...

You can try something like that:

counter=1
for title in $(cat lectures.txt)
do
  touch "$counter - $title.txt"
  counter=$((counter+1))
done

EDIT

I only added the title on lectures.txt

NEW EDIT

If lectures.txt has 1 title per line you can do this:

while IFS= read -r line || [ -n "$line" ]
do
  touch "$line"
done < lectures.txt


问:
Prevent Visual Studio from trying to parse typescript
Working on a project using Visual Studio as my IDE. It has an API component written in C#, and a webserver component that uses TypeScript.

I am using webpack to deal with the typescript compilation and would like to remove the Visual Studio build step from the typescript files.

Normally I wouldn't care if it was building them, but I am using Typescript > 1.8.4 which has language features that Visual Studio cannot understand which is making Visual Studio throw errors and prevent compilation. I found a workaround for this in this github issue thread but I have other developers cross team who are working on this and trying to coordinate a hack to make code among them will not work.

I have also tried removing the typescript imports line from the .csproj file, but whenever I add a new ts file, it adds the line back in.

Is there a way to completely shut down the typescript compilation/parsing step in Visual Studio and prevent it from coming back?

This in in VS 2015.

答:
It seems that the errors are triggered by IntelliSense and one can remove IntelliSense errors by simply filtering the list.

In case that other solutions doesn't help this is the key to clean up the error list, at least temporarily.


问:
Jackson disable typing for typed annotated classes
Let's say I have the following classes:

```<code>@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
@JsonSubTypes({ @JsonSubTypes.Type(value = Rabbit.class) })
abstract class Animal {
}

class Rabbit {
}
</code>```

When serializing I usually need the type, hence the annotations.
I have a use case where I would like to serialize but without the type property. I don't want to make use of DTOs. I can't modify the annotations.

I tried to find an option in the ObjectMapper class to overwrite these annotations, but without success.

```<code>ObjectMapper serializer = new ObjectMapper();
serializer.deactivateDefaultTyping();
</code>```

Any ideas?

答:
The best way to achieve this is through a mixin.

Here's an example:

```<code>public class TestMe2 {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper1 = new ObjectMapper();
        System.out.println(mapper1.writeValueAsString(new Rabbit()));

        ObjectMapper mapper2 = new ObjectMapper();
        mapper2.addMixIn(Animal.class, NoTypes.class);
        System.out.println(mapper2.writeValueAsString(new Rabbit()));
    }

    static class Rabbit extends Animal {
    }

    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
    abstract static class Animal {
        public String name = "example";

    }

    @JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
    class NoTypes {
    }

}
</code>```

Body:
Let's say I have the following classes:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
@JsonSubTypes({ @JsonSubTypes.Type(value = Rabbit.class) })
abstract class Animal {
}

class Rabbit {
}

When serializing I usually need the type, hence the annotations.
I have a use case where I would like to serialize but without the type property. I don't want to make use of DTOs. I can't modify the annotations.

I tried to find an option in the ObjectMapper class to overwrite these annotations, but without success.

ObjectMapper serializer = new ObjectMapper();
serializer.deactivateDefaultTyping();

Any ideas?

Body:
The best way to achieve this is through a mixin.

Here's an example:

public class TestMe2 {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper1 = new ObjectMapper();
        System.out.println(mapper1.writeValueAsString(new Rabbit()));

        ObjectMapper mapper2 = new ObjectMapper();
        mapper2.addMixIn(Animal.class, NoTypes.class);
        System.out.println(mapper2.writeValueAsString(new Rabbit()));
    }

    static class Rabbit extends Animal {
    }

    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
    abstract static class Animal {
        public String name = "example";

    }

    @JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
    class NoTypes {
    }

}


问:
R: read_excel reads dates as numbers
I am importing an excel file from the Robert Koch Institute into R using readxl::read_excel. However, I am experiencing problems with a row that contains only dates. The date format is DD.MM.YYYY, but in the resulting data frame, they appear as seemingly arbitrary numeric values. Here is the code that I am using:

library(readxl)
df <- read_excel("path/to/Fallzahlen_Kum_Tab_Archiv.xlsx",
                                        sheet = "BL_7-Tage-Fallzahlen (fixiert)")
head(df)
```
<p>which returns the following output:</p>
<pre class="lang-r prettyprint-override"><code># A tibble: 6 x 494
  `Fallzahlen in d~  ...2  ...3  ...4  ...5  ...6  ...7  ...8  ...9 ...10 ...11 ...12 ...13 ...14 ...15
  <chr>             <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 NA                   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
2 NA                   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
3 NA                   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
4 NA                43957 43958 43959 43960 43961 43962 43963 43964 43965 43966 43967 43968 43969 43970
5 Baden-Württemberg   908   779   665   706   772   760   774   744   765   725   622   551   549   483
6 Bayern             1318  1246  1182  1223  1148  1151  1198  1194  1115  1022  1022   997   982   921
# ... with 479 more variables: ...16 <dbl>, ...
</code>```

In row number 4, you can see the dates that are clearly not imported correctly. I already tried col_types="text" and col_types="list", as this suggested in other posts, but this doesn't seem to change anything.

The excel file can be downloaded in the "Archiv" section of RKI's webpage and this should be the direct download link.

Title: R: read_excel reads dates as numbers

Body:
I am importing an excel file from the Robert Koch Institute into R using readxl::read_excel. However, I am experiencing problems with a row that contains only dates. The date format is DD.MM.YYYY, but in the resulting data frame, they appear as seemingly arbitrary numeric values. Here is the code that I am using:

library(readxl)
df <- read_excel("path/to/Fallzahlen_Kum_Tab_Archiv.xlsx",
                                        sheet = "BL_7-Tage-Fallzahlen (fixiert)")
head(df)

which returns the following output:

# A tibble: 6 x 494
  `Fallzahlen in d~  ...2  ...3  ...4  ...5  ...6  ...7  ...8  ...9 ...10 ...11 ...12 ...13 ...14 ...15
  <chr>             <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 NA                   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
2 NA                   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
3 NA                   NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
4 NA                43957 43958 43959 43960 43961 43962 43963 43964 43965 43966 43967 43968 43969 43970
5 Baden-Württemberg   908   779   665   706   772   760   774   744   765   725   622   551   549   483
6 Bayern             1318  1246  1182  1223  1148  1151  1198  1194  1115  1022  1022   997   982   921
# ... with 479 more variables: ...16 <dbl>, ...

In row number 4, you can see the dates that are clearly not imported correctly. I already tried col_types="text" and col_types="list", as this suggested in other posts, but this doesn't seem to change anything.

The excel file can be downloaded in the "Archiv" section of RKI's webpage and this should be the direct download link.

Body:
You can fix the data frame after loading it into R

# load data, replace ... with path and file
# dat <- read_xlsx(..., sheet="BL_7-Tage-Fallzahlen (fixiert)")
# get the dates
dates <- as.numeric(dat[4,])

# filter top rows with NAs
dat <- dat[5:nrow(dat),]

# put the dates as column names
colnames(dat)[-1] <- as.character(as.Date(dates[-1], origin="1899-12-30"))

head(dat)
# A tibble: 6 × 494
  `Fallzahlen in den letzte… `2020-05-06` `2020-05-07` `2020-05-08` `2020-05-09`
  <chr>                             <dbl>        <dbl>        <dbl>        <dbl>
1 Baden-Württemberg                   908          779          665          706
2 Bayern                             1318         1246         1182         1223
3 Berlin                              276          265          272          280
4 Brandenburg                         125          116          117          131
5 Bremen                              119          126          140          155
6 Hamburg                              95           85           86           89
# … with 489 more variables: 2020-05-10 <dbl>, 2020-05-11 <dbl>,
#   2020-05-12 <dbl>, 2020-05-13 <dbl>, 2020-05-14 <dbl>, 2020-05-15 <dbl>,
#   2020-05-16 <dbl>, 2020-05-17 <dbl>, 2020-05-18 <dbl>, 2020-05-19 <dbl>,
#   2020-05-20 <dbl>, 2020-05-21 <dbl>, 2020-05-22 <dbl>, 2020-05-23 <dbl>,
#   2020-05-24 <dbl>, 2020-05-25 <dbl>, 2020-05-26 <dbl>, 2020-05-27 <dbl>,
#   2020-05-28 <dbl>, 2020-05-29 <dbl>, 2020-05-30 <dbl>, 2020-05-31 <dbl>,
#   2020-06-01 <dbl>, 2020-06-02 <dbl>, 2020-06-03 <dbl>, 2020-06-04 <dbl>, …


问:
What does relationship owner means in bidirectional relationship?
I have a simple model with a Question and Choice object.

ONE Question has MANY CHOICE(S).

MANY Choice has ONE Question

There are two ways to implement that with Hibernate

Implementation One: The owner side is Choice

Question.java

```<code>@OneToMany (mappedBy="question")
private Set choices = new HashSet();
</code>```

Choice.java

```<code>@ManyToOne
@JoinColumn (name="QUESTION_ID")
private Question question;
</code>```

Implementation Two: The owner side is Question

Question.java

```<code>@OneToMany
@JoinColumn (name = "QUESTION_ID")
private Set choices = new HashSet();
</code>```

Choice.java

```<code>@ManyToOne
@JoinColumn (name="QUESTION_ID", updatable = false, insertable = false)
private Question question;
</code>```

What is the difference between the two implementation?

答:
Bidirectional relationships must follow these rules:

The inverse side must refer to its owning sideby using the mappedBy attribute

The owning side may have the inversedBy attribute

@ManyToOne is always the owning side of a bidirectional association

@OneToMany is always the inverse side of a bidirectional association

the owning side of a @OneToOne association is the entity with the table containing the foreign key

The many side of many-to-one bidirectional relationships must not define the mappedBy attribute

For many-to-many bidirectional relationships, either side may be the owning side

Body:
I have a simple model with a Question and Choice object.

ONE Question has MANY CHOICE(S).

MANY Choice has ONE Question

There are two ways to implement that with Hibernate

Implementation One: The owner side is Choice

Question.java

@OneToMany (mappedBy="question")
private Set choices = new HashSet();

Choice.java

@ManyToOne
@JoinColumn (name="QUESTION_ID")
private Question question;

Implementation Two: The owner side is Question

Question.java

@OneToMany
@JoinColumn (name = "QUESTION_ID")
private Set choices = new HashSet();

Choice.java

@ManyToOne
@JoinColumn (name="QUESTION_ID", updatable = false, insertable = false)
private Question question;

What is the difference between the two implementation?


问:
sin(), cos(), log10() (float) not found for target thumbv7em-none-eabihf
I'm using Rust 1.51 and this minimal crate:

#![no_std]

fn main() {
    let a = 2.0.cos();
}
```

I'm building it with cargo check --target thumbv7em-none-eabihf and the compiler complains with this message: no method named 'cos' found for type '{float}' in the current scope. Same for sin() and log10().

I found https://docs.rust-embedded.org/cortex-m-quickstart/cortex_m_quickstart/ and I would expect the above message for targets thumbv6m-none-eabi or thumbv7em-none-eabi but not for thumbv7em-none-eabihf which has FPU support.

How can I solve this?

答:
What @phip1611 said is correct, cos is no longer part of the core library and hence not usable in no_std out of the box. You can use libm directly OR via a std friendly wrapper using the num-traits crate with the libm feature enabled. This lets you write no_std code as you would write std code. E.g.

```<code># cargo.toml
num-traits = { version = "0.2", default-features = false, features = ["libm"] }
</code>```

And then in your code:

```<code>#![no_std]

#[allow(unused_imports)]
use num_traits::real::Real;

fn main() {
    let a = 2.0.cos();
}
</code>```

Body:
I'm using Rust 1.51 and this minimal crate:

#![no_std]

fn main() {
    let a = 2.0.cos();
}

I'm building it with cargo check --target thumbv7em-none-eabihf and the compiler complains with this message: no method named 'cos' found for type '{float}' in the current scope. Same for sin() and log10().

I found https://docs.rust-embedded.org/cortex-m-quickstart/cortex_m_quickstart/ and I would expect the above message for targets thumbv6m-none-eabi or thumbv7em-none-eabi but not for thumbv7em-none-eabihf which has FPU support.

How can I solve this?

Body:
What @phip1611 said is correct, cos is no longer part of the core library and hence not usable in no_std out of the box. You can use libm directly OR via a std friendly wrapper using the num-traits crate with the libm feature enabled. This lets you write no_std code as you would write std code. E.g.

# cargo.toml
num-traits = { version = "0.2", default-features = false, features = ["libm"] }

And then in your code:

#![no_std]

#[allow(unused_imports)]
use num_traits::real::Real;

fn main() {
    let a = 2.0.cos();
}


问:
Get ADUser attributes without Get-ADUser
Is it possible to get current users AD attributes without Get-ADUser?
Am new to powershell. I need to get few attributes like title, email & department for user.
I tried use :</p>
```<code>get-wmiobject  -Class win32_useraccount  -Filter "name='John.Doe'" | select *
PSComputerName     : NY-Z343
Status             : OK
Caption            : BEAZL-INC\john.doe
PasswordExpires    : False
__GENUS            : 2
__CLASS            : Win32_UserAccount
__SUPERCLASS       : Win32_Account
__DYNASTY          : CIM_ManagedSystemElement
__RELPATH          : Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
__PROPERTY_COUNT   : 16
__DERIVATION       : {Win32_Account, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER           : NY-Z343
__NAMESPACE        : rootcimv2
__PATH             : \BEAZL-INCrootcimv2:Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
AccountType        : 512
Description        : Dude account for gaming
Disabled           : False
Domain             : BEAZL-INC
FullName           : John Doe
InstallDate        :
LocalAccount       : False
Lockout            : False
Name               : john.doe
PasswordChangeable : True
PasswordRequired   : False
SID                : S-1-5-21-3384058-193304-10174538-501
SIDType            : 1
Scope              : System.Management.ManagementScope
Path               : \\NY-Z343\root\clmv2:Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
Options            : System.Management.ObjectGetOptions
ClassPath          : \\NY-Z34\root\clmv2:Win32_UserAccount
Properties         : {AccountType, Caption, Description, Disabled...}
SystemProperties   : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers         : {dynamic, Locale, provider, UUID}
Site               :
Container          :
</code>```

答:
Yes, you can use [adsisearcher], which is a type accelerator for .NET's DirectorySearcher class. This doesn't require installing anything additional.

Here's an example that will search for a user by the name attribute and return the title, mail, and department attributes:

```<code># This is the search filter
$searcher = [adsisearcher]"(&(objectClass=user)(objectCategory=person)(name=John.Doe))"

# List all the propterties you want to use
$searcher.PropertiesToLoad.AddRange(@("title", "mail", "department"))

# By default, it will search the same domain as the logged in user.
# If you need to search a different domain, uncomment and edit this line.
# $searcher.SearchRoot = [adsi]"LDAP://example.com"

$user = $searcher.FindOne()

$title = $user.Properties["title"][0]
</code>```

Body:
Is it possible to get current users AD attributes without Get-ADUser?
Am new to powershell. I need to get few attributes like title, email & department for user.
I tried use :

get-wmiobject  -Class win32_useraccount  -Filter "name='John.Doe'" | select *
PSComputerName     : NY-Z343
Status             : OK
Caption            : BEAZL-INC\john.doe
PasswordExpires    : False
__GENUS            : 2
__CLASS            : Win32_UserAccount
__SUPERCLASS       : Win32_Account
__DYNASTY          : CIM_ManagedSystemElement
__RELPATH          : Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
__PROPERTY_COUNT   : 16
__DERIVATION       : {Win32_Account, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER           : NY-Z343
__NAMESPACE        : rootcimv2
__PATH             : \BEAZL-INCrootcimv2:Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
AccountType        : 512
Description        : Dude account for gaming
Disabled           : False
Domain             : BEAZL-INC
FullName           : John Doe
InstallDate        :
LocalAccount       : False
Lockout            : False
Name               : john.doe
PasswordChangeable : True
PasswordRequired   : False
SID                : S-1-5-21-3384058-193304-10174538-501
SIDType            : 1
Scope              : System.Management.ManagementScope
Path               : \\NY-Z343\root\clmv2:Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
Options            : System.Management.ObjectGetOptions
ClassPath          : \\NY-Z34\root\clmv2:Win32_UserAccount
Properties         : {AccountType, Caption, Description, Disabled...}
SystemProperties   : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers         : {dynamic, Locale, provider, UUID}
Site               :
Container          :

Body:
Yes, you can use [adsisearcher], which is a type accelerator for .NET's DirectorySearcher class. This doesn't require installing anything additional.

Here's an example that will search for a user by the name attribute and return the title, mail, and department attributes:

# This is the search filter
$searcher = [adsisearcher]"(&(objectClass=user)(objectCategory=person)(name=John.Doe))"

# List all the propterties you want to use
$searcher.PropertiesToLoad.AddRange(@("title", "mail", "department"))

# By default, it will search the same domain as the logged in user.
# If you need to search a different domain, uncomment and edit this line.
# $searcher.SearchRoot = [adsi]"LDAP://example.com"

$user = $searcher.FindOne()

$title = $user.Properties["title"][0]


问:
How to retrieve widget sizes in app to make a preview of it depending on the device?
I am currently making a widget only application based on SwiftUI that allow users to show some type of informations as time, date etc..
In order to make my application functional I would like to make a preview of the widgets in the app view, also allowing users to set it up.

For now everything is working well, I can select a widget in my application and set it up so the widget updates as well.
However, I am facing a problem, after some researches I can’t seem to find a way that allows you to get the widgets sizes according to the device you are using.

I tried to use UIScreen.main.bounds.size but the aspect ratio between widgets sizes and devices sizes aren’t the same.

What I would like to do is making my widget preview adapt to the widgets sizes that the device is actually using. (in other words retrieve the widgets sizes depending on which device you are on)

Is there any solutions to do it dynamically or do I need to make a view for each devices? Thanks in advance.

答:
i added more sizes if you want.

to get the family value you can use: @SwiftUI.Environment(\.widgetFamily) var family from inside your View

```<code>    func widgetHeight(forFamily family:WidgetFamily) -> CGSize {
    // better to use getTimeline func context.displaySize before this one.

    switch family {
    case .systemSmall:
        switch UIScreen.main.bounds.size {
        case CGSize(width: 428, height: 926):   return CGSize(width:170, height: 170)
        case CGSize(width: 414, height: 896):   return CGSize(width:169, height: 169)
        case CGSize(width: 414, height: 736):   return CGSize(width:159, height: 159)
        case CGSize(width: 390, height: 844):   return CGSize(width:158, height: 158)
        case CGSize(width: 375, height: 812):   return CGSize(width:155, height: 155)
        case CGSize(width: 375, height: 667):   return CGSize(width:148, height: 148)
        case CGSize(width: 360, height: 780):   return CGSize(width:155, height: 155)
        case CGSize(width: 320, height: 568):   return CGSize(width:141, height: 141)
        default:                                return CGSize(width:155, height: 155)
        }
    case .systemMedium:
        switch UIScreen.main.bounds.size {
        case CGSize(width: 428, height: 926):   return CGSize(width:364, height: 170)
        case CGSize(width: 414, height: 896):   return CGSize(width:360, height: 169)
        case CGSize(width: 414, height: 736):   return CGSize(width:348, height: 159)
        case CGSize(width: 390, height: 844):   return CGSize(width:338, height: 158)
        case CGSize(width: 375, height: 812):   return CGSize(width:329, height: 155)
        case CGSize(width: 375, height: 667):   return CGSize(width:321, height: 148)
        case CGSize(width: 360, height: 780):   return CGSize(width:329, height: 155)
        case CGSize(width: 320, height: 568):   return CGSize(width:292, height: 141)
        default:                                return CGSize(width:329, height: 155)
        }
    case .systemLarge:
        switch UIScreen.main.bounds.size {
        case CGSize(width: 428, height: 926):   return CGSize(width:364, height: 382)
        case CGSize(width: 414, height: 896):   return CGSize(width:360, height: 379)
        case CGSize(width: 414, height: 736):   return CGSize(width:348, height: 357)
        case CGSize(width: 390, height: 844):   return CGSize(width:338, height: 354)
        case CGSize(width: 375, height: 812):   return CGSize(width:329, height: 345)
        case CGSize(width: 375, height: 667):   return CGSize(width:321, height: 324)
        case CGSize(width: 360, height: 780):   return CGSize(width:329, height: 345)
        case CGSize(width: 320, height: 568):   return CGSize(width:292, height: 311)
        default:                                return CGSize(width:329, height: 345)
        }

    default:                                return CGSize(width:329, height: 345)
    }
}
</code>```

Body:
i added more sizes if you want.

to get the family value you can use: @SwiftUI.Environment(\.widgetFamily) var family from inside your View

    func widgetHeight(forFamily family:WidgetFamily) -> CGSize {
    // better to use getTimeline func context.displaySize before this one.

    switch family {
    case .systemSmall:
        switch UIScreen.main.bounds.size {
        case CGSize(width: 428, height: 926):   return CGSize(width:170, height: 170)
        case CGSize(width: 414, height: 896):   return CGSize(width:169, height: 169)
        case CGSize(width: 414, height: 736):   return CGSize(width:159, height: 159)
        case CGSize(width: 390, height: 844):   return CGSize(width:158, height: 158)
        case CGSize(width: 375, height: 812):   return CGSize(width:155, height: 155)
        case CGSize(width: 375, height: 667):   return CGSize(width:148, height: 148)
        case CGSize(width: 360, height: 780):   return CGSize(width:155, height: 155)
        case CGSize(width: 320, height: 568):   return CGSize(width:141, height: 141)
        default:                                return CGSize(width:155, height: 155)
        }
    case .systemMedium:
        switch UIScreen.main.bounds.size {
        case CGSize(width: 428, height: 926):   return CGSize(width:364, height: 170)
        case CGSize(width: 414, height: 896):   return CGSize(width:360, height: 169)
        case CGSize(width: 414, height: 736):   return CGSize(width:348, height: 159)
        case CGSize(width: 390, height: 844):   return CGSize(width:338, height: 158)
        case CGSize(width: 375, height: 812):   return CGSize(width:329, height: 155)
        case CGSize(width: 375, height: 667):   return CGSize(width:321, height: 148)
        case CGSize(width: 360, height: 780):   return CGSize(width:329, height: 155)
        case CGSize(width: 320, height: 568):   return CGSize(width:292, height: 141)
        default:                                return CGSize(width:329, height: 155)
        }
    case .systemLarge:
        switch UIScreen.main.bounds.size {
        case CGSize(width: 428, height: 926):   return CGSize(width:364, height: 382)
        case CGSize(width: 414, height: 896):   return CGSize(width:360, height: 379)
        case CGSize(width: 414, height: 736):   return CGSize(width:348, height: 357)
        case CGSize(width: 390, height: 844):   return CGSize(width:338, height: 354)
        case CGSize(width: 375, height: 812):   return CGSize(width:329, height: 345)
        case CGSize(width: 375, height: 667):   return CGSize(width:321, height: 324)
        case CGSize(width: 360, height: 780):   return CGSize(width:329, height: 345)
        case CGSize(width: 320, height: 568):   return CGSize(width:292, height: 311)
        default:                                return CGSize(width:329, height: 345)
        }

    default:                                return CGSize(width:329, height: 345)
    }
}


问:
Recognize that an image does not belong to the other 2 prediction patterns ML.NET
I use the ML.NET Builder to train an image recognition of dogs and cats. Now, when I finish training I choose a picture of a dog or a cat to identify it will return the results.

The problem would be if I were to choose a photo of a flower that in my training library only had pictures of dogs and cats. So how do I know that the picture is not a dog or a cat?

答:
Taking from the project link posted in Indrit Kello answer:</p>
```<code>var input = new ModelInput();
input.ImageSource = imagePathTb.Text;
ModelOutput result = ConsumeModel.Predict(input);
float score = (result.Score[0] > result.Score[1] ? result.Score[0] : result.Score[1]);
if (score<.8)
{
   statusRtb.Text = $"Neither Cat nor Dog";
}
else
{
   statusRtb.Text =$"Predicted result: {result.Prediction} with a score {score}";
}
</code>```

Body:
Taking from the project link posted in Indrit Kello answer:

var input = new ModelInput();
input.ImageSource = imagePathTb.Text;
ModelOutput result = ConsumeModel.Predict(input);
float score = (result.Score[0] > result.Score[1] ? result.Score[0] : result.Score[1]);
if (score<.8)
{
   statusRtb.Text = $"Neither Cat nor Dog";
}
else
{
   statusRtb.Text =$"Predicted result: {result.Prediction} with a score {score}";
}


问:
.Net 2.0 Windows Service hangs during garbage collection
I have written a .Net (2.0) Windows Service used to send out pager messages to users (via serial port connections to 3rd party hardware).

The service periodically queries a database (OSI PI Historian), parses the values and decides whether to send a message based on the paresed values.

The service uses a lookup object (the values of which come from a SQL Server database and is refreshed every minute) to get user address values and the message string to send.

The service uses a number of Threading.Timers to trigger the periodic database calls and message sends.

The service is installed on a Windows 2003 machine which has .Net 2 SP2 installed.

The service works fine for about a week and then it hangs. No exceptions are recorded within the log (log4net).

I have take a number of dumps from the server and they all exhibit the same characteristics - a thread triggers GC but hangs indefinitely:

```<code>06aaf06c 7c827b99 77e61d1e 00004acc 00000000 ntdll!KiFastSystemCallRet
06aaf070 77e61d1e 00004acc 00000000 00000000 ntdll!ZwWaitForSingleObject+0xc
06aaf0e0 79e8c5f9 00004acc ffffffff 00000000 kernel32!WaitForSingleObjectEx+0xac
06aaf124 79e8c52f 00004acc ffffffff 00000000 mscorwks!PEImage::LoadImage+0x1af
06aaf174 79e8c54e ffffffff 00000000 00000000 mscorwks!CLREvent::WaitEx+0x117
06aaf188 79f2f88f ffffffff 00000000 00000000 mscorwks!CLREvent::Wait+0x17
06aaf1a8 79f2f8ca 7a3b9020 00000000 ffffffff mscorwks!SVR::gc_heap::user_thread_wait+0x50
06aaf1b8 79f2f806 00000000 7a3b8b18 00080101 mscorwks!WKS::gc_heap::wait_to_proceed+0xe
06aaf1cc 79f92f5a 00000000 00000000 00000000 mscorwks!WKS::gc_heap::garbage_collect+0x247
06aaf1f8 79f94e26 00000000 00000000 00000030 mscorwks!WKS::GCHeap::GarbageCollectGeneration+0x1a9
06aaf284 79f926ce 052c75c8 00000030 00000000 mscorwks!WKS::gc_heap::try_allocate_more_space+0x15b
06aaf298 79f92769 052c75c8 00000030 00000000 mscorwks!WKS::gc_heap::allocate_more_space+0x11
06aaf2b8 79e73291 052c75c8 0000002e 00000000 mscorwks!WKS::GCHeap::Alloc+0x3b
06aaf2d4 79e7d8d4 0000002e 00000000 00000000 mscorwks!Alloc+0x60
06aaf310 79e99056 0000000f b456b75e 00001ce3 mscorwks!SlowAllocateString+0x29
06aaf3b4 792bb2c1 00000000 0108082b 00001f40 mscorwks!FramedAllocateString+0xa1
    Stack shortened for bravity...
</code>```

Managed stack:

```<code>ESP       EIP
06aaf364 7c82847c [HelperMethodFrame: 06aaf364]
06aaf3bc 792bb2c1 System.String.CreateStringFromEncoding(Byte*, Int32, System.Text.Encoding)
06aaf3dc 792aaf2a System.Text.EncodingNLS.GetString(Byte[], Int32, Int32)
06aaf3fc 6522d131 System.Data.SqlClient.TdsParserStateObject.ReadStringWithEncoding(Int32, System.Text.Encoding, Boolean)
06aaf41c 656ca93e System.Data.SqlClient.TdsParser.ReadSqlStringValue(System.Data.SqlClient.SqlBuffer, Byte, Int32, System.Text.Encoding, Boolean, System.Data.SqlClient.TdsParserStateObject)
06aaf448 6522d925 System.Data.SqlClient.TdsParser.ReadSqlValue(System.Data.SqlClient.SqlBuffer, System.Data.SqlClient.SqlMetaDataPriv, Int32, System.Data.SqlClient.TdsParserStateObject)
06aaf474 656208b7 System.Data.SqlClient.SqlDataReader.ReadColumnData()
06aaf484 65620962 System.Data.SqlClient.SqlDataReader.ReadColumn(Int32, Boolean)
06aaf4b4 65221415 System.Data.SqlClient.SqlDataReader.GetValueInternal(Int32)
06aaf4c8 652213af System.Data.SqlClient.SqlDataReader.GetValue(Int32)
06aaf4f8 65220aec System.Data.SqlClient.SqlDataReader.get_Item(System.String)
06aaf504 03616b81 AlarmEventCollator.DataAccess.GetAllAlarmDetails()
06aaf564 03616a28 AlarmEventCollator.AlarmBuilder.buildLookups()
06aaf590 0361aa89 AlarmEventCollator.AlarmBuilder.pollLookups(System.Object)
06aaf5d0 792a83ff System.Threading._TimerCallback.TimerCallback_Context(System.Object)
06aaf5d8 792e019f System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
06aaf5f0 792a836b System.Threading._TimerCallback.PerformTimerCallback(System.Object)
06aaf77c 79e71b4c [GCFrame: 06aaf77c]
</code>```

The GC usually happens in the database parsing methods. All the other managed threads appear to hang - which would be consistent with the GC process.

I would appreciate any pointers. More information available on request.

答:
How many GC threads do we have in a .NET process running the Server version of the GC on a dual-core machine?

Two,  one per processor, or rather one per logical processor, so it would have been 4 if it was hyper threaded.  In a process running the workstation version of the GC we would have no dedicated GC threads, instead garbage collection runs on the thread initiating the GC as there is no point in switching to a different thread for garbage collection when you only have one proc/one thread doing the GC.

Chris Lyon has a good writeup about GC modes and also an interesting post about GC latency modes comming in Orcas.

Why is this important to you? Since different GC modes are optimized for different things, your memory usage, GC latency etc. may vary a lot depending on what GC mode you are using. For example a windows service by default gets the workstation GC, but if there is a lot of througput (lots of short lived allocs), you are probably a lot better off running the server GC for memory usage and perf.

Body:
I have written a .Net (2.0) Windows Service used to send out pager messages to users (via serial port connections to 3rd party hardware).

The service periodically queries a database (OSI PI Historian), parses the values and decides whether to send a message based on the paresed values.

The service uses a lookup object (the values of which come from a SQL Server database and is refreshed every minute) to get user address values and the message string to send.

The service uses a number of Threading.Timers to trigger the periodic database calls and message sends.

The service is installed on a Windows 2003 machine which has .Net 2 SP2 installed.

The service works fine for about a week and then it hangs. No exceptions are recorded within the log (log4net).

I have take a number of dumps from the server and they all exhibit the same characteristics - a thread triggers GC but hangs indefinitely:

06aaf06c 7c827b99 77e61d1e 00004acc 00000000 ntdll!KiFastSystemCallRet
06aaf070 77e61d1e 00004acc 00000000 00000000 ntdll!ZwWaitForSingleObject+0xc
06aaf0e0 79e8c5f9 00004acc ffffffff 00000000 kernel32!WaitForSingleObjectEx+0xac
06aaf124 79e8c52f 00004acc ffffffff 00000000 mscorwks!PEImage::LoadImage+0x1af
06aaf174 79e8c54e ffffffff 00000000 00000000 mscorwks!CLREvent::WaitEx+0x117
06aaf188 79f2f88f ffffffff 00000000 00000000 mscorwks!CLREvent::Wait+0x17
06aaf1a8 79f2f8ca 7a3b9020 00000000 ffffffff mscorwks!SVR::gc_heap::user_thread_wait+0x50
06aaf1b8 79f2f806 00000000 7a3b8b18 00080101 mscorwks!WKS::gc_heap::wait_to_proceed+0xe
06aaf1cc 79f92f5a 00000000 00000000 00000000 mscorwks!WKS::gc_heap::garbage_collect+0x247
06aaf1f8 79f94e26 00000000 00000000 00000030 mscorwks!WKS::GCHeap::GarbageCollectGeneration+0x1a9
06aaf284 79f926ce 052c75c8 00000030 00000000 mscorwks!WKS::gc_heap::try_allocate_more_space+0x15b
06aaf298 79f92769 052c75c8 00000030 00000000 mscorwks!WKS::gc_heap::allocate_more_space+0x11
06aaf2b8 79e73291 052c75c8 0000002e 00000000 mscorwks!WKS::GCHeap::Alloc+0x3b
06aaf2d4 79e7d8d4 0000002e 00000000 00000000 mscorwks!Alloc+0x60
06aaf310 79e99056 0000000f b456b75e 00001ce3 mscorwks!SlowAllocateString+0x29
06aaf3b4 792bb2c1 00000000 0108082b 00001f40 mscorwks!FramedAllocateString+0xa1
    Stack shortened for bravity...

Managed stack:

ESP       EIP
06aaf364 7c82847c [HelperMethodFrame: 06aaf364]
06aaf3bc 792bb2c1 System.String.CreateStringFromEncoding(Byte*, Int32, System.Text.Encoding)
06aaf3dc 792aaf2a System.Text.EncodingNLS.GetString(Byte[], Int32, Int32)
06aaf3fc 6522d131 System.Data.SqlClient.TdsParserStateObject.ReadStringWithEncoding(Int32, System.Text.Encoding, Boolean)
06aaf41c 656ca93e System.Data.SqlClient.TdsParser.ReadSqlStringValue(System.Data.SqlClient.SqlBuffer, Byte, Int32, System.Text.Encoding, Boolean, System.Data.SqlClient.TdsParserStateObject)
06aaf448 6522d925 System.Data.SqlClient.TdsParser.ReadSqlValue(System.Data.SqlClient.SqlBuffer, System.Data.SqlClient.SqlMetaDataPriv, Int32, System.Data.SqlClient.TdsParserStateObject)
06aaf474 656208b7 System.Data.SqlClient.SqlDataReader.ReadColumnData()
06aaf484 65620962 System.Data.SqlClient.SqlDataReader.ReadColumn(Int32, Boolean)
06aaf4b4 65221415 System.Data.SqlClient.SqlDataReader.GetValueInternal(Int32)
06aaf4c8 652213af System.Data.SqlClient.SqlDataReader.GetValue(Int32)
06aaf4f8 65220aec System.Data.SqlClient.SqlDataReader.get_Item(System.String)
06aaf504 03616b81 AlarmEventCollator.DataAccess.GetAllAlarmDetails()
06aaf564 03616a28 AlarmEventCollator.AlarmBuilder.buildLookups()
06aaf590 0361aa89 AlarmEventCollator.AlarmBuilder.pollLookups(System.Object)
06aaf5d0 792a83ff System.Threading._TimerCallback.TimerCallback_Context(System.Object)
06aaf5d8 792e019f System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
06aaf5f0 792a836b System.Threading._TimerCallback.PerformTimerCallback(System.Object)
06aaf77c 79e71b4c [GCFrame: 06aaf77c]

The GC usually happens in the database parsing methods. All the other managed threads appear to hang - which would be consistent with the GC process.

I would appreciate any pointers. More information available on request.


问:
The method 'read' isn't defined for the type 'BuildContext'.?
```<code>    class MyLoginButton extends StatelessWidget {
      final int loginTag;
      final Stream<User> stream;

      const MyLoginButton({Key? key, required this.loginTag, required this.stream})
          : super(key: key);

      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Padding(
            padding: const EdgeInsets.all(smallPadding),
            child: StreamBuilder<User>(
                stream: stream,
                builder: (context, snapshot) {
                  /// this is test mode without firebase auth
                  if (context.read(loginModeProvider).state) {
                    SchedulerBinding.instance!
                        .addPostFrameCallback((timeStamp) async {
                      /// mock loading
                      await Future<void>.delayed(const Duration(seconds: 1));
                      await Navigator.pushReplacement(
                          context,
                          MyLoadingRoute<void>(
                              duration: Duration(milliseconds: 500),
                              builder: (context) => MainPage(
                                    heroTag: loginTag,
                                    user: null,
                                  )));
                    });

    }
</code>```

The method 'read' isn't defined for the type 'BuildContext'.

答:
Add Provider import:</p>
```<code>import 'package:provider/provider.dart';
</code>```

Body:
    class MyLoginButton extends StatelessWidget {
      final int loginTag;
      final Stream<User> stream;

      const MyLoginButton({Key? key, required this.loginTag, required this.stream})
          : super(key: key);

      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Padding(
            padding: const EdgeInsets.all(smallPadding),
            child: StreamBuilder<User>(
                stream: stream,
                builder: (context, snapshot) {
                  /// this is test mode without firebase auth
                  if (context.read(loginModeProvider).state) {
                    SchedulerBinding.instance!
                        .addPostFrameCallback((timeStamp) async {
                      /// mock loading
                      await Future<void>.delayed(const Duration(seconds: 1));
                      await Navigator.pushReplacement(
                          context,
                          MyLoadingRoute<void>(
                              duration: Duration(milliseconds: 500),
                              builder: (context) => MainPage(
                                    heroTag: loginTag,
                                    user: null,
                                  )));
                    });

    }

The method 'read' isn't defined for the type 'BuildContext'.

Body:
Add Provider import:

import 'package:provider/provider.dart';


问:
You are providing a function without a theme in the context. One of the parent elements needs to use a ThemeProvider
I am creating a Navbar in a Project. In my Project I use

mui/icons-material: ^5.2.5

mui/material: ^5.2.6

mui/styles: ^5.2.3

Now My folder structure is

Root.jsx

Navbar.jsx

styles.js

I am having an error of

```<code>The `styles` argument provided is invalid.
You are providing a function without a theme in the context.
One of the parent elements needs to use a ThemeProvider.
</code>```

I have tried to fix with

Add ThemeProvider at Root.jsx

Remove from Root.jsx & Add at Navbar.jsx

& Others

Note: I don't know Material UI. Please help me to get out from this error. Here I am providing my code.

Code

Code of Root.jsx

import React from 'react'
import Navbar from './Navbar'

const Root = () => {
    return (
        <>
            <Navbar />
        </>
 )}
export default Root
```
<ul>
<li>Code of <code>Navbar.jsx</code></li>
</ul>
<pre class="lang-js prettyprint-override"><code>import React from 'react'
import { AppBar, Menu, MenuItem, Toolbar, Typography, IconButton, Badge } from '@mui/material'
import { ShoppingCart } from '@mui/icons-material'
import useStyles from './styles'
import Logo from '../../images/logo.png'

const Navbar = () => {

    const classes = useStyles()

    return (
        <>
            <AppBar className={classes.appBar} position='fixed' color='inherit'>
                <Toolbar>
                    <Typography className={classes.title} variant='h6' color='inherit'>
                        <img className={classes.image} alt='Tech Cart' src={Logo} height='25px' />
                        Tech Cart
                    </Typography>
                    <div className={classes.grow} />
                    <div className={classes.button}>
                        <IconButton aria-label='Show cart products' color='inherit'>
                            <Badge badgeContent={2} color='secondary'>
                                <ShoppingCart />
                            </Badge>
                        </IconButton>
                    </div>
                </Toolbar>
            </AppBar>
        </>
    )
}
export default Navbar
</code>```

Code of style.js

import {
    makeStyles
} from '@mui/styles'
import {
    alpha
} from '@mui/material/styles'

const drawerWidth = 0;

export default makeStyles((theme) => ({
    appBar: {
        boxShadow: 'none',
        borderBottom: '1px solid rgba(0, 0, 0, 0.12)',
        [theme.breakpoints.up('sm')]: {
            width: `calc(100% - ${drawerWidth}px)`,
            marginLeft: drawerWidth,
        },
    },
    title: {
        flexGrow: 1,
        alignItems: 'center',
        display: 'flex',
        textDecoration: 'none',
    },
    image: {
        marginRight: '10px',
    },
    menuButton: {
        marginRight: theme.spacing(2),
        [theme.breakpoints.up('sm')]: {
            display: 'none',
        },
    },
    grow: {
        flexGrow: 1,
    },
    search: {
        position: 'relative',
        borderRadius: theme.shape.borderRadius,
        backgroundColor: alpha(theme.palette.common.white, 0.15),
        '&:hover': {
            backgroundColor: alpha(theme.palette.common.white, 0.25),
        },
        marginRight: theme.spacing(2),
        marginLeft: 0,
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            width: 'auto',
        },
    },
    searchIcon: {
        padding: theme.spacing(0, 2),
        height: '100%',
        position: 'absolute',
        pointerEvents: 'none',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    inputRoot: {
        color: 'inherit',
    },
    inputInput: {
        padding: theme.spacing(1, 1, 1, 0),
        // vertical padding + font size from searchIcon
        paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
        transition: theme.transitions.create('width'),
        width: '100%',
        [theme.breakpoints.up('md')]: {
            width: '20ch',
        },
    },
}));
```

答:
I also ran into this issue. These are the steps I followed to solve the issue:

Add following import in the component that will use mui:
import

Next, create a theme.
createTheme

Wrap the component within Themeprovider and pass the theme to it:
themeprovider

Body:
I am creating a Navbar in a Project. In my Project I use

mui/icons-material: ^5.2.5

mui/material: ^5.2.6

mui/styles: ^5.2.3

Now My folder structure is

Root.jsx

Navbar.jsx

styles.js

I am having an error of

The `styles` argument provided is invalid.
You are providing a function without a theme in the context.
One of the parent elements needs to use a ThemeProvider.

I have tried to fix with

Add ThemeProvider at Root.jsx

Remove from Root.jsx & Add at Navbar.jsx

& Others

Note: I don't know Material UI. Please help me to get out from this error. Here I am providing my code.

Code

Code of Root.jsx

import React from 'react'
import Navbar from './Navbar'

const Root = () => {
    return (
        <>
            <Navbar />
        </>
 )}
export default Root

Code of Navbar.jsx

import React from 'react'
import { AppBar, Menu, MenuItem, Toolbar, Typography, IconButton, Badge } from '@mui/material'
import { ShoppingCart } from '@mui/icons-material'
import useStyles from './styles'
import Logo from '../../images/logo.png'

const Navbar = () => {

    const classes = useStyles()

    return (
        <>
            <AppBar className={classes.appBar} position='fixed' color='inherit'>
                <Toolbar>
                    <Typography className={classes.title} variant='h6' color='inherit'>

                        Tech Cart
                    </Typography>

                        <IconButton aria-label='Show cart products' color='inherit'>
                            <Badge badgeContent={2} color='secondary'>
                                <ShoppingCart />
                            </Badge>
                        </IconButton>

                </Toolbar>
            </AppBar>
        </>
    )
}
export default Navbar

Code of style.js

import {
    makeStyles
} from '@mui/styles'
import {
    alpha
} from '@mui/material/styles'

const drawerWidth = 0;

export default makeStyles((theme) => ({
    appBar: {
        boxShadow: 'none',
        borderBottom: '1px solid rgba(0, 0, 0, 0.12)',
        [theme.breakpoints.up('sm')]: {
            width: `calc(100% - ${drawerWidth}px)`,
            marginLeft: drawerWidth,
        },
    },
    title: {
        flexGrow: 1,
        alignItems: 'center',
        display: 'flex',
        textDecoration: 'none',
    },
    image: {
        marginRight: '10px',
    },
    menuButton: {
        marginRight: theme.spacing(2),
        [theme.breakpoints.up('sm')]: {
            display: 'none',
        },
    },
    grow: {
        flexGrow: 1,
    },
    search: {
        position: 'relative',
        borderRadius: theme.shape.borderRadius,
        backgroundColor: alpha(theme.palette.common.white, 0.15),
        '&:hover': {
            backgroundColor: alpha(theme.palette.common.white, 0.25),
        },
        marginRight: theme.spacing(2),
        marginLeft: 0,
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            width: 'auto',
        },
    },
    searchIcon: {
        padding: theme.spacing(0, 2),
        height: '100%',
        position: 'absolute',
        pointerEvents: 'none',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    inputRoot: {
        color: 'inherit',
    },
    inputInput: {
        padding: theme.spacing(1, 1, 1, 0),
        // vertical padding + font size from searchIcon
        paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
        transition: theme.transitions.create('width'),
        width: '100%',
        [theme.breakpoints.up('md')]: {
            width: '20ch',
        },
    },
}));


问:
Unable to Convert cURL to python requests
I'm struggling to convert the below command into a python requests script. The objective is to query this API for their vehicle MOT history(UK) based on their registration, represented below as ZZ99ABC. I've an API key and confirmed via a cURL try that my access is working.

```<code>curl -H "Accept: application/json+v6" -H "x-api-key: <my_api_key>" \https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests\?registration=ZZ99ABC
</code>```

So far my attempt is producing a 403 response, missing an authentication token.

```<code>import requests
import json

reg = "ZZ99ABC"
url = f"https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests"
payload = {'registration': reg}
headers = {'x-api-key': '<my_api_key>',
            'Accept': 'application/json+v6'}

r = requests.post(url, data=json.dumps(payload), headers=headers)
</code>```

Any ideas where I potentially got this wrong?

Thank you in advance

requests.__version__ == '2.26.0'
python --version == 3.9.2

答:
this suppose to work:</p>
```<code>import requests

headers = {
    'Accept': 'application/json+v6',
    'x-api-key': '<my_api_key>',
}

params = (
    ('registration', 'ZZ99ABC'),
)

response = requests.get('/https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests/', headers=headers, params=params)
</code>```

Body:
I'm struggling to convert the below command into a python requests script. The objective is to query this API for their vehicle MOT history(UK) based on their registration, represented below as ZZ99ABC. I've an API key and confirmed via a cURL try that my access is working.

curl -H "Accept: application/json+v6" -H "x-api-key: <my_api_key>" \https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests\?registration=ZZ99ABC

So far my attempt is producing a 403 response, missing an authentication token.

import requests
import json

reg = "ZZ99ABC"
url = f"https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests"
payload = {'registration': reg}
headers = {'x-api-key': '<my_api_key>',
            'Accept': 'application/json+v6'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

Any ideas where I potentially got this wrong?

Thank you in advance

requests.__version__ == '2.26.0'
python --version == 3.9.2

Body:
this suppose to work:

import requests

headers = {
    'Accept': 'application/json+v6',
    'x-api-key': '<my_api_key>',
}

params = (
    ('registration', 'ZZ99ABC'),
)

response = requests.get('/https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests/', headers=headers, params=params)


问:
React - How to get client coordinates on canvas properly? (drawing a straight line with mouse)
I got to make "drawing a line" works, but this line wouldn't start from where my mouse starts, rather it'd start from very beginning {x: 0, y:0}. How to draw a line starting from where my mouse clicks?

I already used e.nativeEvent.offsetX and e.nativeEvent.offsetY for getting client X and Y, and this is used for just drawing feature, but I'm stuck how I can utilize it for drawing line, or changing my draw a line code for making it work. Thank you in advanced!

```<code>const canvasRef = useRef(null);
  const ctxRef = useRef(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [lineWidth, setLineWidth] = useState(5);
  const [lineColor, setLineColor] = useState("black");

  let startPosition = {x: 0, y: 0};
  let lineCoordinates = {x: 0, y: 0};

  const getClientOffset = (e) => {
    const {pageX, pageY} = e.touches ? e.touches[0] : e;
    const x = pageX - canvasRef.offsetLeft;
    const y = pageY - canvasRef.offsetTop;

    return {
       x,
       y
    }
  }

  const drawLine = () => {
   ctxRef.current.beginPath();
   ctxRef.current.moveTo(startPosition.x, startPosition.y);
   ctxRef.current.lineTo(lineCoordinates.x, lineCoordinates.y);
   ctxRef.current.stroke();
}

  useLayoutEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    ctx.strokeStyle = lineColor;
    ctx.lineWidth = lineWidth;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctxRef.current = ctx;
  }, [lineColor, lineWidth]);

  const handleMouseDown = (e) => {
    setIsDrawing(true);

    // const posX = e.nativeEvent.offsetX;
    // const posY = e.nativeEvent.offsetY;

    // ctxRef.current.beginPath();
    // ctxRef.current.moveTo(
    //   posX,
    //   posY
    // );
    startPosition = getClientOffset(e);
  }

  const handleMouseMove = (e) => {
    if (!isDrawing) {
      return;
    }
    ctxRef.current.lineTo(
      e.nativeEvent.offsetX,
      e.nativeEvent.offsetY
    );
    ctxRef.current.stroke();

    lineCoordinates = getClientOffset(e);
    drawLine();
  }

  const handleMouseUp = () => {
    ctxRef.current.closePath();
    setIsDrawing(false);
  }
</code>```

答:
The issue is let startPosition and let lineCoordinates – on each render update React will reinitialize these variables with {x: 0, y:0}. In order to remember any value you must use useState().

I tried it out in a demo
https://codesandbox.io/s/crazy-breeze-xj26c?file=/src/App.js

Body:
I got to make "drawing a line" works, but this line wouldn't start from where my mouse starts, rather it'd start from very beginning {x: 0, y:0}. How to draw a line starting from where my mouse clicks?

I already used e.nativeEvent.offsetX and e.nativeEvent.offsetY for getting client X and Y, and this is used for just drawing feature, but I'm stuck how I can utilize it for drawing line, or changing my draw a line code for making it work. Thank you in advanced!

const canvasRef = useRef(null);
  const ctxRef = useRef(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [lineWidth, setLineWidth] = useState(5);
  const [lineColor, setLineColor] = useState("black");

  let startPosition = {x: 0, y: 0};
  let lineCoordinates = {x: 0, y: 0};

  const getClientOffset = (e) => {
    const {pageX, pageY} = e.touches ? e.touches[0] : e;
    const x = pageX - canvasRef.offsetLeft;
    const y = pageY - canvasRef.offsetTop;

    return {
       x,
       y
    }
  }

  const drawLine = () => {
   ctxRef.current.beginPath();
   ctxRef.current.moveTo(startPosition.x, startPosition.y);
   ctxRef.current.lineTo(lineCoordinates.x, lineCoordinates.y);
   ctxRef.current.stroke();
}

  useLayoutEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    ctx.strokeStyle = lineColor;
    ctx.lineWidth = lineWidth;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctxRef.current = ctx;
  }, [lineColor, lineWidth]);

  const handleMouseDown = (e) => {
    setIsDrawing(true);

    // const posX = e.nativeEvent.offsetX;
    // const posY = e.nativeEvent.offsetY;

    // ctxRef.current.beginPath();
    // ctxRef.current.moveTo(
    //   posX,
    //   posY
    // );
    startPosition = getClientOffset(e);
  }

  const handleMouseMove = (e) => {
    if (!isDrawing) {
      return;
    }
    ctxRef.current.lineTo(
      e.nativeEvent.offsetX,
      e.nativeEvent.offsetY
    );
    ctxRef.current.stroke();

    lineCoordinates = getClientOffset(e);
    drawLine();
  }

  const handleMouseUp = () => {
    ctxRef.current.closePath();
    setIsDrawing(false);
  }


问:
Angular Http Interceptor: catchError and return success
I have an Http Interceptor (Angular 7) that catches errors. Is it possible to catch the error and based on some contidition, returns a success instead of the error? My current code.</p>

```<code>export class RequestInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError( response => {
        if(someCondition) {
           //return something that won't throw an error
        }
        return of(response)
      })
    )

  }
}
</code>```

答:
Even though this is not recommended, creating a success response from catchError can be done using HttpResponse class,

```<code>return next.handle(request)
    .pipe(
        catchError((error: HttpErrorResponse) => {
            return of(new HttpResponse({ body: {}, status: 0 }));
        })
    )
</code>```

Body:
I have an Http Interceptor (Angular 7) that catches errors. Is it possible to catch the error and based on some contidition, returns a success instead of the error? My current code.

export class RequestInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError( response => {
        if(someCondition) {
           //return something that won't throw an error
        }
        return of(response)
      })
    )

  }
}

Body:
Even though this is not recommended, creating a success response from catchError can be done using HttpResponse class,

return next.handle(request)
    .pipe(
        catchError((error: HttpErrorResponse) => {
            return of(new HttpResponse({ body: {}, status: 0 }));
        })
    )