问:
RealityKit – Get a model entity from USDZ file
I haave a file (exists in main bundle with target membership checked) named matrix.usdz and need to load it with

```<code> do {
    let path = Bundle.main.path(forResource: "Matrix", ofType: "usdz")!

    let url = URL(fileURLWithPath: path)

    let assetsLoader = try Entity.load(contentsOf: url)
  }
  catch {
     print(error)
  }
</code>```

But it crashes with

Thread 1: signal SIGABRT

on this line

```<code>let assetsLoader = try Entity.load(contentsOf: url)
</code>```

Preview

答:
You have to create an anchor if you need to load an entity into your scene. In order to get a ModelEntity, you need to grab it from the scene hierarchy using .children[X] subscript.

```<code>import RealityKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!

    override func viewDidLoad() {
        super.viewDidLoad()
        do {
            let path = Bundle.main.path(forResource: "Matrix", ofType: "usdz")!

            let url = URL(fileURLWithPath: path)

            // Scene
            let scene = try Entity.load(contentsOf: url)
            print(scene)

            // Entity
            let entity = scene.children[0].........children[0] as! ModelEntity

            entity.model?.materials[0] = UnlitMaterial(color: .red)

            let anchor = AnchorEntity(plane: .any)
            anchor.addChild(scene)
            arView.scene.anchors.append(anchor)

         } catch {
             print(error)
         }
    }
}
</code>```

You can also get a model this way:

```<code>let modelEntity = try Entity.loadModel(contentsOf: url)

modelEntity.model?.materials[0] = UnlitMaterial(color: .red)
</code>```

P.S.

I should say that you have an obvious naming error – "Matrix" vs "matrix". Also Matrix.rcproject and Matrix.usdz are not the same. To load Matrix.rcproject (Reality Composer project) use the following approach:

```<code>// .rcproject
let scene = try! Matrix.loadCircle()

let circleEntity = scene.children[0]...........children[0] as! ModelEntity
</code>```

to load a USDZ model use this one:

```<code>// .usdz
let model = try! Entity.loadModel(named: "Matrix", in: nil)
</code>```

But as far as I know, you do not need an RC project, so export USDZ from Reality Composer.

To load .reality file use the following approach:

```<code>// .reality
let carModel = try! Entity.loadAnchor(named: "car")
print(carModel)

arView.scene.addAnchor(carModel)
</code>```

Here's your USDZ model on iOS simulator:

Body:
I haave a file (exists in main bundle with target membership checked) named matrix.usdz and need to load it with

 do {
    let path = Bundle.main.path(forResource: "Matrix", ofType: "usdz")!

    let url = URL(fileURLWithPath: path)

    let assetsLoader = try Entity.load(contentsOf: url)
  }
  catch {
     print(error)
  }

But it crashes with

Thread 1: signal SIGABRT

on this line

let assetsLoader = try Entity.load(contentsOf: url)

Preview

Body:
You have to create an anchor if you need to load an entity into your scene. In order to get a ModelEntity, you need to grab it from the scene hierarchy using .children[X] subscript.

import RealityKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!

    override func viewDidLoad() {
        super.viewDidLoad()
        do {
            let path = Bundle.main.path(forResource: "Matrix", ofType: "usdz")!

            let url = URL(fileURLWithPath: path)

            // Scene
            let scene = try Entity.load(contentsOf: url)
            print(scene)

            // Entity
            let entity = scene.children[0].........children[0] as! ModelEntity

            entity.model?.materials[0] = UnlitMaterial(color: .red)

            let anchor = AnchorEntity(plane: .any)
            anchor.addChild(scene)
            arView.scene.anchors.append(anchor)

         } catch {
             print(error)
         }
    }
}

You can also get a model this way:

let modelEntity = try Entity.loadModel(contentsOf: url)

modelEntity.model?.materials[0] = UnlitMaterial(color: .red)

P.S.

I should say that you have an obvious naming error – "Matrix" vs "matrix". Also Matrix.rcproject and Matrix.usdz are not the same. To load Matrix.rcproject (Reality Composer project) use the following approach:

// .rcproject
let scene = try! Matrix.loadCircle()

let circleEntity = scene.children[0]...........children[0] as! ModelEntity

to load a USDZ model use this one:

// .usdz
let model = try! Entity.loadModel(named: "Matrix", in: nil)

But as far as I know, you do not need an RC project, so export USDZ from Reality Composer.

To load .reality file use the following approach:

// .reality
let carModel = try! Entity.loadAnchor(named: "car")
print(carModel)

arView.scene.addAnchor(carModel)

Here's your USDZ model on iOS simulator:


来源: stackexchange

问:
How to get the null value count/percentage for each columns in bigquery
TableName = 'Header'

As per below table details Reg_nbr has no null values so in output it is 0
, Reg_name is having 3 null values out of 6 records so output it is 50
and Reg_code has only null values so output it is 100

Please help on the query part - in bigquery

答:
Consider below approach

```<code>select
  100 * countif(Reg_nbr is null) / count(1) as Reg_nbr,
  100 * countif(Reg_Name is null) / count(1) as Reg_Name,
  100 * countif(Reg_Code is null) / count(1) as Reg_Code
from your_table
</code>```

if applied to sample data in your question - output is

ContentLicense: CC BY-SA 4.0

Body:
Consider below approach

select
  100 * countif(Reg_nbr is null) / count(1) as Reg_nbr,
  100 * countif(Reg_Name is null) / count(1) as Reg_Name,
  100 * countif(Reg_Code is null) / count(1) as Reg_Code
from your_table

if applied to sample data in your question - output is


问:
Is it possible to see if the connection parameter is a type of Interface Extension?
I am looking to execute something dependent on the type of connection it is.  But have not found a way.

```<code>const onSaveHandler = async (connection: Connection) => {
  if (connection is serial) { // do serial task }

  if (connection is ethernet) { //do ethernet task }
}

</code>```

All connections have ID, NAME, TYPE,....

```<code>export interface Connection {
  [CONNECTION_ID_KEY]: number;
  [CONNECTION_NAME_KEY]: string;
  [CONNECTION_TYPE_ID_KEY]: number;
  [CONNECTION_TYPE_NAME_KEY]?: string;
  [CONNECTION_COMM_INTERVAL_KEY]: number;
}
</code>```

Two classes extend:

```<code>export interface SerialConnection extends Connection {
  [COM_PORT_KEY]: number;
  [BAUD_RATE_KEY]: number;
  [DATA_BITS_KEY]: number;
  [STOP_BITS_KEY]: number;
  [PARITY_KEY]: number;
}

export interface EthernetConnection extends Connection {
  [IP_ADDRESS_KEY]: string;
  [PORT_NUMBER_KEY]: number;
}
</code>```

To see what I am trying to achieve
https://codesandbox.io/s/mbuqb

答:
You need to make a discriminated union here. That means a union of objects that share a common property. That common property then has a different type for each member of the union.

For example:

```<code>export interface CommonConnection {
  common: string
}

export interface SerialConnection extends CommonConnection {
  connectionType: 'serial'
  COM_PORT: number;
  BAUD_RATE: number;
}

export interface EthernetConnection extends CommonConnection {
  connectionType: 'ethernet'
  IP_ADDRESS: string;
  PORT_NUMBER: number;
}

export type Connection = SerialConnection | EthernetConnection
</code>```

Now you can test the connectionType property at runtime, and typescript will cast your value to the right type for you.

```<code>const onSaveHandler = async (connection: Connection) => {
  if (connection.connectionType === 'serial') {
    console.log(connection.COM_PORT) // can fetch serial property
  }

  if (connection.connectionType === 'ethernet') {
    console.log(connection.IP_ADDRESS) // can fetch ethernet property
  }
}
</code>```

Playground

Body:
I am looking to execute something dependent on the type of connection it is.  But have not found a way.

const onSaveHandler = async (connection: Connection) => {
  if (connection is serial) { // do serial task }

  if (connection is ethernet) { //do ethernet task }
}

All connections have ID, NAME, TYPE,....

export interface Connection {
  [CONNECTION_ID_KEY]: number;
  [CONNECTION_NAME_KEY]: string;
  [CONNECTION_TYPE_ID_KEY]: number;
  [CONNECTION_TYPE_NAME_KEY]?: string;
  [CONNECTION_COMM_INTERVAL_KEY]: number;
}

Two classes extend:

export interface SerialConnection extends Connection {
  [COM_PORT_KEY]: number;
  [BAUD_RATE_KEY]: number;
  [DATA_BITS_KEY]: number;
  [STOP_BITS_KEY]: number;
  [PARITY_KEY]: number;
}

export interface EthernetConnection extends Connection {
  [IP_ADDRESS_KEY]: string;
  [PORT_NUMBER_KEY]: number;
}

To see what I am trying to achieve
https://codesandbox.io/s/mbuqb

Body:
You need to make a discriminated union here. That means a union of objects that share a common property. That common property then has a different type for each member of the union.

For example:

export interface CommonConnection {
  common: string
}

export interface SerialConnection extends CommonConnection {
  connectionType: 'serial'
  COM_PORT: number;
  BAUD_RATE: number;
}

export interface EthernetConnection extends CommonConnection {
  connectionType: 'ethernet'
  IP_ADDRESS: string;
  PORT_NUMBER: number;
}

export type Connection = SerialConnection | EthernetConnection

Now you can test the connectionType property at runtime, and typescript will cast your value to the right type for you.

const onSaveHandler = async (connection: Connection) => {
  if (connection.connectionType === 'serial') {
    console.log(connection.COM_PORT) // can fetch serial property
  }

  if (connection.connectionType === 'ethernet') {
    console.log(connection.IP_ADDRESS) // can fetch ethernet property
  }
}

<a href="https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgYQgFsiIlCklhsYEy4BvAKDjm2NKQC44BnGKMgDmTAL5MmoSLEQo0WXHADKaBJgA2FKjTpI4oVEgAmvAhzJbqtes1btKV3QBUAnmGA8A5L1UbPLAgB5AFkAfQAFQIAlJx4kAFciACM0AG4AgCEAQQBVABFQqKynAFE4xJSodPFJcGh4ZFQMHDwSmAALNCoYSx16A2BjU0ISCzJtaz1bNnHHMld3L2AOruX-VgBJcNCsvLyokqUlHn5BJCF01kiY0IA5HOCMkqjy5LSxCSl6uBg3PF7JnAALzKXyaWZ9PQAHzgbU6UG6AN0Ens-DgZCUmAAbsAABKYYzqNDAuCYXguJDYOAACnsE10PCRZAAlMCAHyMOABBDoGl0uZIAB0-MhCzwQIlcG8YM8rOmdjIvAgRMF6ggQlpEMmgvwIQi0ScrIA9Ea2AS4Ohlth2nwwXAwFAIO5YC4AjVWDy+VrdMLvfM-sDJZ5lvDurLGAEFUglSq1RqRdqtjs9gcjsbTdhzZaYNb9CsEct7Y7nb83R8gA" rel="nofollow noreferrer">Playground


问:
JQuery UI Autocomplete not working in ASP.NET MVC
I am trying to implement an autocomplete in ASP.NET MVC 3, following this post
but I really can't get it to work. I have looked at a series of other posts and blogs, but no success so far.

I have a DB table which contains regions (in Japanese), like so:

1 ハイチ; 2 ドミニカ共和国; 3 南アフリカ

basically a [key, Name] pair.

In my repository I am doing the following call:

```<code>public IQueryable<Region> GetAllRegions()
    {
        return db.Regions;
    }
</code>```

Getting the raw data, which I pass to the controller, pair down the data according to input and the concatenate to a string like so:

```<code>    public class RegionsController : Controller
{
    Region_Repository rr = new Region_Repository();

    public string FindRegions(string q)
    {
        List<string> regions = rr.GetAllRegions().Select(r => r.Name).Where(s => s.StartsWith(q)).ToList();

        return string.Join("\n", regions);
    }

}
</code>```

The controller when accessed via server/Regions/FindRegions/?q=ハ return a page with the single entry "ハイチ" as expected.

On the page I have a textbox with id "#NewRegion" and the script

```<code><script type="text/javascript">
$(document).ready(function () {
    $("#NewRegion").autocomplete('@Url.Action("FindRegions", "Regions")');
})
</script>
</code>```

which I placed underneath the textbox.

I have references to JQuery and JQueryUI from Google API which work since I am executing other JQuery and using the JQueryUI datepicker successfully on this page.

I tried placing the script in a separate file and hardcoding the url as '/Regions/FindRegions', but no change. I had a look in firebug (second day only, so not very proficient at using it yet) and the script doesn't seem to get executed.
The controller is called fine when accessed via URL, but anything I enter into the textbox does not get passed to the controller...

Can anybody see anything wrong with this?

答:
According to the dark depths of the jQuery UI documentation, the parameter used when passing the autocomplete string to the server is called term, not q.

Update: And also, initialize with autocomplete({source: "@(...url...)"}).

Update 2: And also, return the type of data the Autocomplete widget expects, a JSON array of strings or a JSON array of objects.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement an autocomplete in ASP.NET MVC 3, following this post
but I really can't get it to work. I have looked at a series of other posts and blogs, but no success so far.

I have a DB table which contains regions (in Japanese), like so:

1 ハイチ; 2 ドミニカ共和国; 3 南アフリカ

basically a [key, Name] pair.

In my repository I am doing the following call:

public IQueryable<Region> GetAllRegions()
    {
        return db.Regions;
    }

Getting the raw data, which I pass to the controller, pair down the data according to input and the concatenate to a string like so:

    public class RegionsController : Controller
{
    Region_Repository rr = new Region_Repository();

    public string FindRegions(string q)
    {
        List<string> regions = rr.GetAllRegions().Select(r => r.Name).Where(s => s.StartsWith(q)).ToList();

        return string.Join("\n", regions);
    }

}

The controller when accessed via server/Regions/FindRegions/?q=ハ return a page with the single entry "ハイチ" as expected.

On the page I have a textbox with id "#NewRegion" and the script

which I placed underneath the textbox.

I have references to JQuery and JQueryUI from Google API which work since I am executing other JQuery and using the JQueryUI datepicker successfully on this page.

I tried placing the script in a separate file and hardcoding the url as '/Regions/FindRegions', but no change. I had a look in firebug (second day only, so not very proficient at using it yet) and the script doesn't seem to get executed.
The controller is called fine when accessed via URL, but anything I enter into the textbox does not get passed to the controller...

Can anybody see anything wrong with this?


问:
How to put list values into two separate columns
This is the code I am working with currently.

```<code>data = {'ID': ['O1', 'O2', 'O3', 'O4'],'DATE': ['2010-09-09','2010-10-15','2011-02-09','2011-08-12'], 'RESULT': [1160, 6112, 21175, 10830]}
df = pd.DataFrame(data) #putting into a dataframe
grouped=df.groupby('ID')['RESULT','DATE'].apply(list) #groupby method and putting into list
</code>```

Running this code gives me the following table.

```<code>ID
O1    [1160,  2010-09-09]
O2    [6112,  2010-10-15]
O3    [21175, 2011-02-09]
O4    [10830, 2011-08-12]
</code>```

I want the [RESULT, DATE] to be separated so the format becomes as below.

```<code>ID    VL      DATES
O1    1160    2010-09-09
O2    6112    2010-10-15
O3    21175   2011-02-09
O4    10830   2011-08-12
</code>```

There are more than 100 rows so I am looking for a suitable way to put them in the table shown above.

答:
You can just call tolist on the result and pass that to pd.DataFrame (here I'm using pipe to make it a nice one-liner):

```<code>>>> df.groupby('ID')[['RESULT','DATE']].apply(list).pipe(lambda x: pd.DataFrame(x.tolist(), index=x.index, columns=['VL', 'DATE']))
        VL  DATE
ID
O1  RESULT  DATE
O2  RESULT  DATE
O3  RESULT  DATE
O4  RESULT  DATE
</code>```

Body:
This is the code I am working with currently.

data = {'ID': ['O1', 'O2', 'O3', 'O4'],'DATE': ['2010-09-09','2010-10-15','2011-02-09','2011-08-12'], 'RESULT': [1160, 6112, 21175, 10830]}
df = pd.DataFrame(data) #putting into a dataframe
grouped=df.groupby('ID')['RESULT','DATE'].apply(list) #groupby method and putting into list

Running this code gives me the following table.

ID
O1    [1160,  2010-09-09]
O2    [6112,  2010-10-15]
O3    [21175, 2011-02-09]
O4    [10830, 2011-08-12]

I want the [RESULT, DATE] to be separated so the format becomes as below.

ID    VL      DATES
O1    1160    2010-09-09
O2    6112    2010-10-15
O3    21175   2011-02-09
O4    10830   2011-08-12

There are more than 100 rows so I am looking for a suitable way to put them in the table shown above.

Body:
You can just call tolist on the result and pass that to pd.DataFrame (here I'm using pipe to make it a nice one-liner):

>>> df.groupby('ID')[['RESULT','DATE']].apply(list).pipe(lambda x: pd.DataFrame(x.tolist(), index=x.index, columns=['VL', 'DATE']))
        VL  DATE
ID
O1  RESULT  DATE
O2  RESULT  DATE
O3  RESULT  DATE
O4  RESULT  DATE


问:
Extract elements from dynamic list as increases or decreases in python
Hello i have a dynamic list which increases or decreases accordingly from the extracted data from a site with BeautifulSoup

```<code>mylist = [a,b,c,d,.......]
</code>```

how can i make the following fstring to be dynamic as the list increases or decreases?

```<code>fstr = print(f"the forecast for the week is (choose number): {nl}1. {mylist[0]}{nl}2. {mylist[1]}{nl}3. {mylist[2]}{nl}4. {mylist[3]}{nl}5. Show all week")
</code>```

As you can see i want the elements of mylist to be seperated by \nl in the fstring and not join it to a string.
Is this possible?

the Output is

```<code>the forecast for the week is (choose number):
1. Tuesday 08  2022
2. Wednesday 09  2022
3. Thursday 10  2022
4. Friday 11  2022
</code>```

答:
```<code>myCommaSeparatedValues = ', '.join(myList)
</code>```

This should work, then insert this list into your fstr variable:

```<code>fstr = f"Show the following {myCommaSeparatedValues}"
</code>```

NOTE: never call a variable list since you are overwriting the built-in class list. Call it myList instead.

In Python to print a newline you have to use the standard char '\n'.

I assume you have a nested list with this structure:

```<code>myList = [
    ['1', 'Monday', '08', 2022],
    ['2', 'Tuesday', '09', 2022]
]
</code>```

You can print as you expected this way:

```<code>fstr = "The forecast for the week is (choose number):"
for i in myList:
    fstr += f"\n{' '.join(i)}"
print(fstr)
</code>```

Body:
Hello i have a dynamic list which increases or decreases accordingly from the extracted data from a site with BeautifulSoup

mylist = [a,b,c,d,.......]

how can i make the following fstring to be dynamic as the list increases or decreases?

fstr = print(f"the forecast for the week is (choose number): {nl}1. {mylist[0]}{nl}2. {mylist[1]}{nl}3. {mylist[2]}{nl}4. {mylist[3]}{nl}5. Show all week")

As you can see i want the elements of mylist to be seperated by \nl in the fstring and not join it to a string.
Is this possible?

the Output is

the forecast for the week is (choose number):
1. Tuesday 08  2022
2. Wednesday 09  2022
3. Thursday 10  2022
4. Friday 11  2022

Body:
myCommaSeparatedValues = ', '.join(myList)

This should work, then insert this list into your fstr variable:

fstr = f"Show the following {myCommaSeparatedValues}"

NOTE: never call a variable list since you are overwriting the built-in class list. Call it myList instead.

In Python to print a newline you have to use the standard char '\n'.

I assume you have a nested list with this structure:

myList = [
    ['1', 'Monday', '08', 2022],
    ['2', 'Tuesday', '09', 2022]
]

You can print as you expected this way:

fstr = "The forecast for the week is (choose number):"
for i in myList:
    fstr += f"\n{' '.join(i)}"
print(fstr)


答:
you could use the join method:

```<code>mylist = [1,2,3,4,5]
fstr = f'show this: {', '.join(mylist)}'
</code>```

or you could do this:

```<code>fstr = f'show this: {str(mylist).removeprefix("[").removesuffix("]")}'
</code>```

output:

```<code>show this: 1, 2, 3, 4, 5
</code>```

to dynamically change the list, you would have a updater function, witch would update the values:

```<code>def update(values):
    globals()["fstr"] = f'show this: {', '.join(list1+values)}'
</code>```

but is not or you could pass the entire list instead:

```<code>def update(mylist):
    globals()["fstr"] = f'show this: {', '.join(mylist)}'
</code>```

to update them constantly, you would need a loop, like:

```<code>while updating:
    ... # updating the values
</code>```

Title: Extract elements from dynamic list as increases or decreases in python

Body:
you could use the join method:

mylist = [1,2,3,4,5]
fstr = f'show this: {', '.join(mylist)}'

or you could do this:

fstr = f'show this: {str(mylist).removeprefix("[").removesuffix("]")}'

output:

show this: 1, 2, 3, 4, 5

to dynamically change the list, you would have a updater function, witch would update the values:

def update(values):
    globals()["fstr"] = f'show this: {', '.join(list1+values)}'

but is not or you could pass the entire list instead:

def update(mylist):
    globals()["fstr"] = f'show this: {', '.join(mylist)}'

to update them constantly, you would need a loop, like:

while updating:
    ... # updating the values


问:
Swap adjacent element in a linked list
While seeing a programming interview site, I came across code which swap adjacent elements in a linked list, but I found it to be a bit wrong. Below is the code.

```<code>void swap (struct list **list1)
{
    struct list *cur, *tmp, *next;
    cur = *list1;
    if (cur && cur->next)
        *list1 = cur->next;

    //To make sure that we have at least two more elements to be swapped.
    while (cur && cur->next)
    {
        next = cur->next;
        tmp = next->next;
        next->next = cur;
        //We have to make 1->next as 4 in above example (figure).

        if (tmp)
            cur->next = tmp->next;
        cur = tmp;
    }
    return;
}
</code>```

Now for me, the condition if (temp) is not right here. Is that assessment correct?

Suppose we do have a linked list like:

```<code>  1->2->3->4->NULL
</code>```

Now our objective is to make a linked list like:

```<code>2->1->4->3->NULL
</code>```

My worry is if the if (temp) is there in our code, we can't assign null at end of the linked list.

答:
Yes, you are right that there's a bug in the function - cur->next isn't updated correctly in all cases.

I personally find the local variable names tmp and next not particularly helpful and actively confusing in the case of next. Those names make it hard for me to keep track in my head of what's going on as I read through the function.

I find that the names node1, node2, and node3 work better to for me to keep a mental picture of which node is being manipulated.  I wouldn't be surprised if other people disagree, though.

Here's a reworked version of the function that I find more readable, and more importantly that I believe is correct.

```<code>void swap (struct list **head)
{
    struct list *node1 = *head;
    struct list *node2 = node1 ? node1->next : NULL;

    // handle degenerate cases
    if (!node2) {
        // no elements or only one element on the list
        //  nothing to do...
        return;
    }

    // fix-up list head to what will be the new first node on list
    *head = node2;

    // while there are at least 2 more elements to be swapped
    while (node1 && node2) {
        struct list* node3 = node2->next;

        // get a pointer to the node that will be the remainder of the
        //  list after the remainder of the list is processed.
        //
        // This will be NULL, node3, or 'node4' depending on whether
        //  there are 0 , 1 or 2+ nodes following node1 and node2
        struct list* remainder = (node3 && node3->next) ? node3->next : node3;

        node1->next = remainder;
        node2->next = node1;

        // prepare pointers to the next two nodes to be swapped
        node1 = node3;
        node2 = node3 ? node3->next : NULL;
    }

    return;
}
</code>```

Title: Swap adjacent element in a linked list

Body:
While seeing a programming interview site, I came across code which swap adjacent elements in a linked list, but I found it to be a bit wrong. Below is the code.

void swap (struct list **list1)
{
    struct list *cur, *tmp, *next;
    cur = *list1;
    if (cur && cur->next)
        *list1 = cur->next;

    //To make sure that we have at least two more elements to be swapped.
    while (cur && cur->next)
    {
        next = cur->next;
        tmp = next->next;
        next->next = cur;
        //We have to make 1->next as 4 in above example (figure).

        if (tmp)
            cur->next = tmp->next;
        cur = tmp;
    }
    return;
}

Now for me, the condition if (temp) is not right here. Is that assessment correct?

Suppose we do have a linked list like:

  1->2->3->4->NULL

Now our objective is to make a linked list like:

2->1->4->3->NULL

My worry is if the if (temp) is there in our code, we can't assign null at end of the linked list.

Body:
Yes, you are right that there's a bug in the function - cur->next isn't updated correctly in all cases.

I personally find the local variable names tmp and next not particularly helpful and actively confusing in the case of next. Those names make it hard for me to keep track in my head of what's going on as I read through the function.

I find that the names node1, node2, and node3 work better to for me to keep a mental picture of which node is being manipulated.  I wouldn't be surprised if other people disagree, though.

Here's a reworked version of the function that I find more readable, and more importantly that I believe is correct.

void swap (struct list **head)
{
    struct list *node1 = *head;
    struct list *node2 = node1 ? node1->next : NULL;

    // handle degenerate cases
    if (!node2) {
        // no elements or only one element on the list
        //  nothing to do...
        return;
    }

    // fix-up list head to what will be the new first node on list
    *head = node2;

    // while there are at least 2 more elements to be swapped
    while (node1 && node2) {
        struct list* node3 = node2->next;

        // get a pointer to the node that will be the remainder of the
        //  list after the remainder of the list is processed.
        //
        // This will be NULL, node3, or 'node4' depending on whether
        //  there are 0 , 1 or 2+ nodes following node1 and node2
        struct list* remainder = (node3 && node3->next) ? node3->next : node3;

        node1->next = remainder;
        node2->next = node1;

        // prepare pointers to the next two nodes to be swapped
        node1 = node3;
        node2 = node3 ? node3->next : NULL;
    }

    return;
}


问:
T-SQL pivot where clause
in SQL Server i want PIVOT a table and add a WHERE clause but i cant figure out the syntax.

The data

```<code>dbo.SOME_VIEW
YEAR  AMOUNT
====================
2014  1
2013  2
2012  5.6
2011  574
2010  123
</code>```

The Query

```<code>SELECT
    *
FROM SOME_VIEW
PIVOT (SUM(AMOUNT) FOR [YEAR] IN ([2012], [2013], [2014])) AS PIVOTED
</code>```

Now i want to get from the view only the row with the year that i will PIVOT so i want to add

WHERE YEAR IN (2012, 2013, 2014)

What i have tried

Put WHERE after FROM SOME_VIEW

```<code>SELECT
    *
FROM SOME_VIEW WHERE YEAR IN (2012, 2013, 2014)
PIVOT (SUM(AMOUNT) FOR [YEAR] IN ([2012], [2013], [2014])) AS PIVOTED
</code>```

i get: Incorrect syntax near the keyword 'PIVOT'. When i add the WHERE at the end end i get Invalid column name 'YEAR'.

Question

Where can i add the WHERE clause when i use PIVOT?

Why

For performance. In the view i have years from 1990 but i want only the last thre years. I expect when i add a where i improve performance.

答:
I know exactly where is your problem, since I am jut facing it right now.
The WHERE Clause and the PIVOT Clause don't like each other. So, PIVOT cannot come Directly after WHERE, unless there is a barrier between them.
This say, you MUST wrap your SELECT Clause as a Subquery of another SELECT Clause, like this:

SELECT * FROM

(

SELECT
*
FROM SOME_VIEW
WHERE YEAR IN (2012, 2013, 2014)

)

PIVOT (SUM(AMOUNT) FOR [YEAR] IN ([2012], [2013], [2014])) AS PIVOTED

WITH COMMENTS

SELECT * FROM --Master Query you should add

(

SELECT * -- This is the query you had before

FROM SOME_VIEW

WHERE YEAR IN (2012, 2013, 2014)

) -- End of the Master Query. This is the barrier between the WHERE and the PIVOT. After this parenthesis, you can now safely call you PIVOT Clause.

PIVOT (SUM(AMOUNT) FOR [YEAR] IN ([2012], [2013], [2014])) AS PIVOTED

Title: T-SQL pivot where clause

Body:
in SQL Server i want PIVOT a table and add a WHERE clause but i cant figure out the syntax.

The data

dbo.SOME_VIEW
YEAR  AMOUNT
====================
2014  1
2013  2
2012  5.6
2011  574
2010  123

The Query

SELECT
    *
FROM SOME_VIEW
PIVOT (SUM(AMOUNT) FOR [YEAR] IN ([2012], [2013], [2014])) AS PIVOTED

Now i want to get from the view only the row with the year that i will PIVOT so i want to add

WHERE YEAR IN (2012, 2013, 2014)

What i have tried

Put WHERE after FROM SOME_VIEW

SELECT
    *
FROM SOME_VIEW WHERE YEAR IN (2012, 2013, 2014)
PIVOT (SUM(AMOUNT) FOR [YEAR] IN ([2012], [2013], [2014])) AS PIVOTED

i get: Incorrect syntax near the keyword 'PIVOT'. When i add the WHERE at the end end i get Invalid column name 'YEAR'.

Question

Where can i add the WHERE clause when i use PIVOT?

Why

For performance. In the view i have years from 1990 but i want only the last thre years. I expect when i add a where i improve performance.


问:
No acceptable C compiler found in $PATH when installing python
I'm trying to install a new Python environment on my shared hosting. I follow the steps written in this post:

```<code>mkdir ~/src
wget http://www.python.org/ftp/python/2.7.1/Python-2.7.1.tgz
tar -zxvf Python-2.7.1.tar.gz
cd Python-2.7.1
mkdir ~/.localpython
./configure --prefix=/home/<user>/.localpython
make
make install
</code>```

After coming to the ./configure --prefix=/home/<user>/.localpython command, I get the following output:

```<code>checking for --enable-universalsdk... no
checking for --with-universal-archs... 32-bit
checking MACHDEP... linux3
checking EXTRAPLATDIR...
checking machine type as reported by uname -m... x86_64
checking for --without-gcc... no
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/home3/mikos89/Python-2.7.1':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details.
</code>```

How can this problem be solved? I've been trying to find a solution for 3 hours, but I'm still stuck in one place.

UPDATE

Hostgator does not allow gcc on their shared accounts:

答:
In a shared hosting, gcc compiler is disabled by default (in a terminal write gcc --version and it must return 'Permission denied' if installed...). It's very important to the next step.

Now, contact the support team and request to add your user id to 'compiler group'. This solves your problem and other - for example, you will be able to execute 'make' and 'make install' without problems, install the pillow library, etc.

Forget about 'sudo' or 'apk' commands. They are also disabled by default.

Body:
I'm trying to install a new Python environment on my shared hosting. I follow the steps written in this post:

mkdir ~/src
wget http://www.python.org/ftp/python/2.7.1/Python-2.7.1.tgz
tar -zxvf Python-2.7.1.tar.gz
cd Python-2.7.1
mkdir ~/.localpython
./configure --prefix=/home/<user>/.localpython
make
make install

After coming to the ./configure --prefix=/home/<user>/.localpython command, I get the following output:

checking for --enable-universalsdk... no
checking for --with-universal-archs... 32-bit
checking MACHDEP... linux3
checking EXTRAPLATDIR...
checking machine type as reported by uname -m... x86_64
checking for --without-gcc... no
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/home3/mikos89/Python-2.7.1':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details.

How can this problem be solved? I've been trying to find a solution for 3 hours, but I'm still stuck in one place.

UPDATE

Hostgator does not allow gcc on their shared accounts:


问:
CSS crashes when I reload page
I am building a site with Gatsby.
I am using a component that imports a script and returns a form.
The problem is, that after you loaded the page that shows the form, and then you click to any other page and go back to that form page, the css fully crashes for the entire site and you have to refresh the whole page.
To check out what I mean click this link https://baerenherz.org/, go to the dark blue button on the very right of the menu, then click to any other navigation site and then click again on the blue button (jetzt-spenden).

Here is my component for the donation form :

```<code>import React, { useState, useEffect } from "react"
import {Helmet} from "react-helmet"

import Loading from "./Loading"

function Child() {
  return(
    <div style={{width: "75%", margin: "4em auto"}} >
      <Helmet>
        <script type='text/javascript' aysnc>
          {` window.rnw.tamaro.runWidget('.dds-widget-container', {language: 'de'}) `}
        </script>
      </Helmet>
      <div className="dds-widget-container"></div>
    </div>
  )
}

function RaiseNow() {
  const [loaded, setLoaded] = useState(false)

  useEffect(() => {
    const scriptTag = document.createElement('script')
    scriptTag.src='https://tamaro.raisenow.com/xxx/latest/widget.js'
    scriptTag.addEventListener('load', ()=> setLoaded(true))
    document.body.appendChild(scriptTag)
    return ()=>{
      scriptTag.removeEventListener(); // check if necessary
      setLoaded(false) // check if necessary
    }

  }, []);

  return (
    <>
      {loaded ? <Child /> : <Loading/>}
    </>
  )
      }

export default RaiseNow
</code>```

What I noticed is, that the second time you visit the page, the Loading.... component does not even show anymore.. the Layout is displayed but as soon as the form shows, it crashes...

Since I cannot solve this issue since literally last year I would really appreciate any help with this. Thank you in advance.

答:
Apparently, your script is breaking React's hydration when the component should be mounted/unmounted. There's no "clean" solution if there's no React-based script available. The problem here is that your script is manipulating the DOM while React manages the virtual DOM (vDOM). Changes in the DOM outside React's scope are not listened to by React and vice versa.

That said, I'd try forcing the loading and rendering of your widget each time the page loads. Something like:

```<code>function RaiseNow() {
  const [loaded, setLoaded] = useState(false)

  useEffect(() => {
    const scriptTag = document.createElement('script')
    scriptTag.src='https://tamaro.raisenow.com/xxx/latest/widget.js'
    scriptTag.addEventListener('load', ()=> setLoaded(true))
    document.body.appendChild(scriptTag)
    window.rnw.tamaro.runWidget('.dds-widget-container', {language: 'de'})
     return ()=>{
      scriptTag.removeEventListener('load', setLoaded(false)); // check if necessary
      setLoaded(false) // check if necessary
    }

  }, []);

  return (
    <>
      {loaded ? <Child /> : <Loading/>}
    </>
  )
}

export default RaiseNow
</code>```

Without a CodeSandbox it's difficult to guess how the code will behave but what it's important is to detach and clean up the listeners when the component is removed from the UI to avoid breaking React's hydration process, in the return statement. From the useEffect docs:

The clean-up function runs before the component is removed from the UI
to prevent memory leaks. Additionally, if a component renders multiple
times (as they typically do), the previous effect is cleaned up before
executing the next effect. In our example, this means a new
subscription is created on every update. To avoid firing an effect on
every update, refer to the next section.

There, besides removing the listeners from the script, you can also set the loading state to false.

I've also removed the second useEffect because the idea to avoid the CSS breaking is to force the loading of the script in each page rendering. It's not an optimal solution but it may work for you. The ideal solution would be using React-based dependencies.

Another thing to take into account is to delay the trigger of your rnw.tamaro script until the DOM tree is loaded, by moving it from the Helmet to the useEffect. This should ensure that your div and the window are available.

Title: CSS crashes when I reload page

Body:
I am building a site with Gatsby.
I am using a component that imports a script and returns a form.
The problem is, that after you loaded the page that shows the form, and then you click to any other page and go back to that form page, the css fully crashes for the entire site and you have to refresh the whole page.
To check out what I mean click this link https://baerenherz.org/, go to the dark blue button on the very right of the menu, then click to any other navigation site and then click again on the blue button (jetzt-spenden).

Here is my component for the donation form :

import React, { useState, useEffect } from "react"
import {Helmet} from "react-helmet"

import Loading from "./Loading"

function Child() {
  return(

      <Helmet>

      </Helmet>

  )
}

function RaiseNow() {
  const [loaded, setLoaded] = useState(false)

  useEffect(() => {
    const scriptTag = document.createElement('script')
    scriptTag.src='https://tamaro.raisenow.com/xxx/latest/widget.js'
    scriptTag.addEventListener('load', ()=> setLoaded(true))
    document.body.appendChild(scriptTag)
    return ()=>{
      scriptTag.removeEventListener(); // check if necessary
      setLoaded(false) // check if necessary
    }

  }, []);

  return (
    <>
      {loaded ? <Child /> : <Loading/>}
    </>
  )
      }

export default RaiseNow

What I noticed is, that the second time you visit the page, the Loading.... component does not even show anymore.. the Layout is displayed but as soon as the form shows, it crashes...

Since I cannot solve this issue since literally last year I would really appreciate any help with this. Thank you in advance.

Body:
Apparently, your script is breaking React's hydration when the component should be mounted/unmounted. There's no "clean" solution if there's no React-based script available. The problem here is that your script is manipulating the DOM while React manages the virtual DOM (vDOM). Changes in the DOM outside React's scope are not listened to by React and vice versa.

That said, I'd try forcing the loading and rendering of your widget each time the page loads. Something like:

function RaiseNow() {
  const [loaded, setLoaded] = useState(false)

  useEffect(() => {
    const scriptTag = document.createElement('script')
    scriptTag.src='https://tamaro.raisenow.com/xxx/latest/widget.js'
    scriptTag.addEventListener('load', ()=> setLoaded(true))
    document.body.appendChild(scriptTag)
    window.rnw.tamaro.runWidget('.dds-widget-container', {language: 'de'})
     return ()=>{
      scriptTag.removeEventListener('load', setLoaded(false)); // check if necessary
      setLoaded(false) // check if necessary
    }

  }, []);

  return (
    <>
      {loaded ? <Child /> : <Loading/>}
    </>
  )
}

export default RaiseNow

Without a CodeSandbox it's difficult to guess how the code will behave but what it's important is to detach and clean up the listeners when the component is removed from the UI to avoid breaking React's hydration process, in the return statement. From the useEffect docs:

The clean-up function runs before the component is removed from the UI
to prevent memory leaks. Additionally, if a component renders multiple
times (as they typically do), the previous effect is cleaned up before
executing the next effect. In our example, this means a new
subscription is created on every update. To avoid firing an effect on
every update, refer to the next section.

There, besides removing the listeners from the script, you can also set the loading state to false.

I've also removed the second useEffect because the idea to avoid the CSS breaking is to force the loading of the script in each page rendering. It's not an optimal solution but it may work for you. The ideal solution would be using React-based dependencies.

Another thing to take into account is to delay the trigger of your rnw.tamaro script until the DOM tree is loaded, by moving it from the Helmet to the useEffect. This should ensure that your div and the window are available.


问:
Find all substrings within a string with overlap
Hi im trying to find all overlapping substrings in  a string here is my code its only finding nonrepeating ACA.</p>

```<code>$haystack = "ACAAGACACATGCCACATTGTCC";
$needle = "ACA";
echo preg_match_all("/$needle/", $haystack, $matches);
</code>```

答:
Here a script to find all occurences of a substring, also the overlapping ones.

```<code>    $haystack = "ACAAGACACATGCCACATTGTCC";
    $needle   = "ACA";

    $positions    = [];
    $needle_len   = strlen($needle);
    $haystack_len = strlen($haystack);

    for ($i = 0; $i <= $haystack_len; $i++) {
        if( substr(substr($haystack,$i),0,$needle_len) == $needle){
            $positions[]=$i;
        }
    }
    print_r($positions);
</code>```

Output: Array ( 0, 5, 7, 14 )

Body:
Hi im trying to find all overlapping substrings in  a string here is my code its only finding nonrepeating ACA.

$haystack = "ACAAGACACATGCCACATTGTCC";
$needle = "ACA";
echo preg_match_all("/$needle/", $haystack, $matches);

Body:
Here a script to find all occurences of a substring, also the overlapping ones.

    $haystack = "ACAAGACACATGCCACATTGTCC";
    $needle   = "ACA";

    $positions    = [];
    $needle_len   = strlen($needle);
    $haystack_len = strlen($haystack);

    for ($i = 0; $i <= $haystack_len; $i++) {
        if( substr(substr($haystack,$i),0,$needle_len) == $needle){
            $positions[]=$i;
        }
    }
    print_r($positions);

Output: Array ( 0, 5, 7, 14 )


问:
Entity Framework loading child collection with sort order
I have two tables a parent and a child table. The child table has a column sortorder (a numeric value). Because of the missing support of the EF to persist a IList inclusive the sort order without exposing the sortorder (see: Entity Framework persisting child collection sort order) my child class has also a property SortOrder, so that i can store the children with the sort order.

In contrast to the author of the referenced question I try to load the children always sorted. So if I load a parent instance I expect, that the child collection is sorted by sort order. How can I achieve this behaviour with the Code First Fluent API and POCO's?

Hint: It's not an option to call .Sort(...) on the child collection.

答:
In EF core 5 and 6:</p>
```<code>var results = await DbSet.Where(t => <your condition>)
                         .Include(t => t.Children.OrderBy(child => child.YourProperty))
                         .ToListAsync(cancellationToken);
</code>```

Body:
In EF core 5 and 6:

var results = await DbSet.Where(t => <your condition>)
                         .Include(t => t.Children.OrderBy(child => child.YourProperty))
                         .ToListAsync(cancellationToken);


问:
Buttons are not spaced with css present
I'm having a problem with buttons in CSS.

Between the first two I get the right distance, but between the second and the third I get two buttons joined (attached) (as in the picture).

How can I solve this problem?

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="buttons">
  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />
</div></code>```

答:
#container {
            display: flex;
            //justify-content:space-around;
        }

        .butts, form {
            margin-left: 10px;

        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
        <form action="createArt.html">
            <input type="submit" value="ADD" >
        </form>

        <input class='butts'type="button" value="EDIT" >

        <input class='butts' type="button" value="DELETE" >
    </div></code>```

Title: Buttons are not spaced with css present

Body:
I'm having a problem with buttons in CSS.

Between the first two I get the right distance, but between the second and the third I get two buttons joined (attached) (as in the picture).

How can I solve this problem?

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}

  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />

Body:
#container {
            display: flex;
            //justify-content:space-around;
        }

        .butts, form {
            margin-left: 10px;

        }

<div id="container">
        <form action="createArt.html">
            <input type="submit" value="ADD" >
        </form>

        <input class='butts'type="button" value="EDIT" >

        <input class='butts' type="button" value="DELETE" >
    </div>


问:
how to call derived function using base class object
```<code>class Parent
{
    public int GetNo()
    {
        return 1;
    }
}

class Child : Parent
{
    public Child()
    {

    }

    public int GetNo()
    {
        return 2;
    }
}

Parent p = new Child();
p.GetNo();
</code>```

But it calls Base.GetNo(). I know if I use virutal in base it will call Child.GetNo()
But i can't use virutal in Base becuase i have to derive my class from base which is already distributed in DLL.So there's no way i can modify the existing functions of base class.

Any sugguestions are valued.
Thanks

答:
You can cast it:

```<code>((Child)p).GetNo();
</code>```

or

```<code>if(p is Child)
    (p as Child).GetNo();
</code>```

Body:
class Parent
{
    public int GetNo()
    {
        return 1;
    }
}

class Child : Parent
{
    public Child()
    {

    }

    public int GetNo()
    {
        return 2;
    }
}

Parent p = new Child();
p.GetNo();

But it calls Base.GetNo(). I know if I use virutal in base it will call Child.GetNo()
But i can't use virutal in Base becuase i have to derive my class from base which is already distributed in DLL.So there's no way i can modify the existing functions of base class.

Any sugguestions are valued.
Thanks

Body:
You can cast it:

((Child)p).GetNo();

or

if(p is Child)
    (p as Child).GetNo();


问:
Why Enum's HasFlag method need boxing?
I am reading "C# via CLR" and on page 380, there's a note saying the following:

Note  The Enum class defines a HasFlag method defined as follows

public Boolean HasFlag(Enum flag);

Using this method, you could rewrite the call to Console.WriteLine like this:

Console.WriteLine("Is {0} hidden? {1}", file, attributes.HasFlag(FileAttributes.Hidden));

However, I recommend that you avoid the HasFlag method for this reason:

Since it takes a
  parameter of type Enum, any value you pass to it must be boxed, requiring a memory allocation ."

I can not understand this bolded statement -- why "

any value you pass to it must be boxed

The flag parameter type is Enum, which is a value type, why would there be boxing? The "any value you pass to it must be boxed" should mean boxing happens when you pass value type to parameter Enum flag, right?

答:
As suggested by Timo the solution of Martin Tilo Schmitz can be implemented without the need for the /unsafe switch:

public static bool HasAnyFlag<E>(this E lhs, E rhs) where E : unmanaged, Enum
{
    switch (Unsafe.SizeOf<E>())
    {
    case 1:
        return (Unsafe.As<E, byte>(ref lhs) & Unsafe.As<E, byte>(ref rhs)) != 0;
    case 2:
        return (Unsafe.As<E, ushort>(ref lhs) & Unsafe.As<E, ushort>(ref rhs)) != 0;
    case 4:
        return (Unsafe.As<E, uint>(ref lhs) & Unsafe.As<E, uint>(ref rhs)) != 0;
    case 8:
        return (Unsafe.As<E, ulong>(ref lhs) & Unsafe.As<E, ulong>(ref rhs)) != 0;
    default:
        throw new Exception("Size does not match a known Enum backing type.");
    }
}
```

The NuGet System.Runtime.CompilerServices.Unsafe is required to compile this with .NET Framework.

Performance

I have to mention that any generic implementation is still almost an order of magnitude slower than a native check, i.e. ((int)lhs & (int)rhs) != 0.
I guess taking the reference of lhs, rhs prevents optimization of the storage of the function variables.
The runtime dispatch of the enum size adds another overhead.

But it is still one order of magnitude faster than HasFlag.

And well, the performance benefit is almost zero comapred to HasFlag if optimizations are turned off in a debug build.

There is no significant difference between using unsafe { } and using class Unsafe in optimized (release) builds. Only without optimizations class Unsafe is almost as slow as HasFlag.

Using a delegate as supercat recommended is no reasonable option since the resulting function pointer call is slow on most CPU architectures and even more it completely prevents inlining.

MethodImplOptions.AggressiveInlining adds no value.

Conclusion

There is still no really fast and readable implementation for testing flags in enums.

Title: Why Enum's HasFlag method need boxing?

Body:
As suggested by Timo the solution of Martin Tilo Schmitz can be implemented without the need for the /unsafe switch:

public static bool HasAnyFlag<E>(this E lhs, E rhs) where E : unmanaged, Enum
{
    switch (Unsafe.SizeOf<E>())
    {
    case 1:
        return (Unsafe.As<E, byte>(ref lhs) & Unsafe.As<E, byte>(ref rhs)) != 0;
    case 2:
        return (Unsafe.As<E, ushort>(ref lhs) & Unsafe.As<E, ushort>(ref rhs)) != 0;
    case 4:
        return (Unsafe.As<E, uint>(ref lhs) & Unsafe.As<E, uint>(ref rhs)) != 0;
    case 8:
        return (Unsafe.As<E, ulong>(ref lhs) & Unsafe.As<E, ulong>(ref rhs)) != 0;
    default:
        throw new Exception("Size does not match a known Enum backing type.");
    }
}

The NuGet System.Runtime.CompilerServices.Unsafe is required to compile this with .NET Framework.

Performance

I have to mention that any generic implementation is still almost an order of magnitude slower than a native check, i.e. ((int)lhs & (int)rhs) != 0.
I guess taking the reference of lhs, rhs prevents optimization of the storage of the function variables.
The runtime dispatch of the enum size adds another overhead.

But it is still one order of magnitude faster than HasFlag.

And well, the performance benefit is almost zero comapred to HasFlag if optimizations are turned off in a debug build.

There is no significant difference between using unsafe { } and using class Unsafe in optimized (release) builds. Only without optimizations class Unsafe is almost as slow as HasFlag.

Using a delegate as supercat recommended is no reasonable option since the resulting function pointer call is slow on most CPU architectures and even more it completely prevents inlining.

MethodImplOptions.AggressiveInlining adds no value.

Conclusion

There is still no really fast and readable implementation for testing flags in enums.


问:
How do I format a url string to pass into stored procedure
I created the below stored procedure in sql server that requires 3 parameters: Date, URL, & Table Name:

```<code>ALTER PROCEDURE [stg].[usp_Delete_Data]
    (@DateLookBack date,
     @siteUrl nvarchar(100),
     @tableName SYSNAME)
AS
BEGIN
    SET QUOTED_IDENTIFIER ON

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    DECLARE @sql NVARCHAR(MAX);

    SET @sql = N'DELETE FROM ' + CONCAT('[stg].[',@tableName,']') +
                'WHERE date = ' + FORMAT(@DateLookBack, 'yyyyMMdd')  +
                'AND siteUrl = ' + @siteUrl

    EXEC sp_executesql @Sql
END
</code>```

When I pass in a url, like 'https://stackoverflow.com', I get an error message:

Incorrect syntax near 'https:'

How do I format the url string so that it can pass into the query successfully?

答:
To find such issue, all you need is to PRINT the query before you use it! You could examine the query which is executed, if you printed it first.

Replace the commend Exec sp_executesql @Sql with the command PRINT @Sql and examine the query you get.

In your case, after you do it, then when you execute the procedure using the following command, then I can see all the issues.

```<code>EXECUTE dbo.[usp_Delete_Data]
    @DateLookBack = '2022-02-27' ,@siteUrl = 'https://stackoverflow.com' , @tableName = 'c'
GO
</code>```

The printed text which we get is: DELETE FROM [stg].[c]WHERE date = 20220227and siteUrl = https://stackoverflow.com

Now we can go over the errors (yes there are multiple errors here) one by one

(1) Notice that the 'WHERE date = ' missing a space before the "where" which might combine the word "where" with the table name that comes before it. You need to add space like ' WHERE date = '

same with the part after the and siteUrl - missing space before the and

(2) Notice this part: siteUrl = https://stackoverflow.com. in the query you are building you do not have quotation marks around the text of the URL => this lead to the error message.

instead of 'and siteUrl = ' + @siteUrl it should be: 'and siteUrl = ''' + @siteUrl + ''''

(3) same issue you have with the date - you do not have quotation marks around the text of the date

instead of ' WHERE date = '  + format(@DateLookBack,'yyyyMMdd') it should be ' WHERE date = '''  + format(@DateLookBack,'yyyyMMdd') + ''''

So, after adding these fixes, you get the following SP (I use PRING instead of execute but you can change this back)

```<code>CREATE OR ALTER PROCEDURE [usp_Delete_Data] (
    @DateLookBack date,@siteUrl nvarchar(100), @tableName SYSNAME
) AS BEGIN

    SET QUOTED_IDENTIFIER ON
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    DECLARE @sql NVARCHAR(MAX);

    SET @sql = N'DELETE FROM ' + CONCAT('[stg].[',@tableName,']')
    --+ ' WHERE date = '  + format(@DateLookBack,'yyyyMMdd')
    + ' WHERE date = '''  + format(@DateLookBack,'yyyyMMdd') + ''''
    + ' and siteUrl = ''' + @siteUrl + ''''
    --+ 'and siteUrl = ' + @siteUrl
    PRINT @Sql
    --Exec sp_executesql @Sql
END
</code>```

and now if I execute the same query

```<code>EXECUTE dbo.[usp_Delete_Data]
    @DateLookBack = '2022-02-27' ,@siteUrl = 'https://stackoverflow.com' , @tableName = 'c'
GO
</code>```

It will print something that looks like:

```<code>DELETE FROM [stg].[c] WHERE date = '20220227'and siteUrl = 'https://stackoverflow.com'
</code>```

BUT! NOW WE CAN GO TO THE MOST PROBLEMATIC ISSUE! Your procedure is open to SQL Injection! You should NOT use such code.

You should use parameters whenever you can when you use sp_executesql and not combine text text. Read the documentation of sp_executesql on how to use parameters as input: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql

Body:
I created the below stored procedure in sql server that requires 3 parameters: Date, URL, & Table Name:

ALTER PROCEDURE [stg].[usp_Delete_Data]
    (@DateLookBack date,
     @siteUrl nvarchar(100),
     @tableName SYSNAME)
AS
BEGIN
    SET QUOTED_IDENTIFIER ON

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    DECLARE @sql NVARCHAR(MAX);

    SET @sql = N'DELETE FROM ' + CONCAT('[stg].[',@tableName,']') +
                'WHERE date = ' + FORMAT(@DateLookBack, 'yyyyMMdd')  +
                'AND siteUrl = ' + @siteUrl

    EXEC sp_executesql @Sql
END

When I pass in a url, like 'https://stackoverflow.com', I get an error message:

Incorrect syntax near 'https:'

How do I format the url string so that it can pass into the query successfully?

Body:
To find such issue, all you need is to PRINT the query before you use it! You could examine the query which is executed, if you printed it first.

Replace the commend Exec sp_executesql @Sql with the command PRINT @Sql and examine the query you get.

In your case, after you do it, then when you execute the procedure using the following command, then I can see all the issues.

EXECUTE dbo.[usp_Delete_Data]
    @DateLookBack = '2022-02-27' ,@siteUrl = 'https://stackoverflow.com' , @tableName = 'c'
GO

The printed text which we get is: DELETE FROM [stg].[c]WHERE date = 20220227and siteUrl = https://stackoverflow.com

Now we can go over the errors (yes there are multiple errors here) one by one

(1) Notice that the 'WHERE date = ' missing a space before the "where" which might combine the word "where" with the table name that comes before it. You need to add space like ' WHERE date = '

same with the part after the and siteUrl - missing space before the and

(2) Notice this part: siteUrl = https://stackoverflow.com. in the query you are building you do not have quotation marks around the text of the URL => this lead to the error message.

instead of 'and siteUrl = ' + @siteUrl it should be: 'and siteUrl = ''' + @siteUrl + ''''

(3) same issue you have with the date - you do not have quotation marks around the text of the date

instead of ' WHERE date = '  + format(@DateLookBack,'yyyyMMdd') it should be ' WHERE date = '''  + format(@DateLookBack,'yyyyMMdd') + ''''

So, after adding these fixes, you get the following SP (I use PRING instead of execute but you can change this back)

CREATE OR ALTER PROCEDURE [usp_Delete_Data] (
    @DateLookBack date,@siteUrl nvarchar(100), @tableName SYSNAME
) AS BEGIN

    SET QUOTED_IDENTIFIER ON
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    DECLARE @sql NVARCHAR(MAX);

    SET @sql = N'DELETE FROM ' + CONCAT('[stg].[',@tableName,']')
    --+ ' WHERE date = '  + format(@DateLookBack,'yyyyMMdd')
    + ' WHERE date = '''  + format(@DateLookBack,'yyyyMMdd') + ''''
    + ' and siteUrl = ''' + @siteUrl + ''''
    --+ 'and siteUrl = ' + @siteUrl
    PRINT @Sql
    --Exec sp_executesql @Sql
END

and now if I execute the same query

EXECUTE dbo.[usp_Delete_Data]
    @DateLookBack = '2022-02-27' ,@siteUrl = 'https://stackoverflow.com' , @tableName = 'c'
GO

It will print something that looks like:

DELETE FROM [stg].[c] WHERE date = '20220227'and siteUrl = 'https://stackoverflow.com'

BUT! NOW WE CAN GO TO THE MOST PROBLEMATIC ISSUE! Your procedure is open to SQL Injection! You should NOT use such code.

You should use parameters whenever you can when you use sp_executesql and not combine text text. Read the documentation of sp_executesql on how to use parameters as input: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql


问:
Change the way request parameters are interpreted
I use Requests to do some requests to an api.
I want to pass multiple value to a request parameter so I use a list like this:

```<code>params = {'test_key': [value1, value2]}
requests.get('example.com', params = params)
</code>```

The problem is that the module converts that into "example.com?test_key=value1&test_key=value2".
The api I use do not accept this format but wants something like "example.com?test_key=value1,value2"

How can I achieve that ?

答: As discussed in the comment section, using ','.join([value1, value2]) produces the desired string.

Body:
I use Requests to do some requests to an api.
I want to pass multiple value to a request parameter so I use a list like this:

params = {'test_key': [value1, value2]}
requests.get('example.com', params = params)

The problem is that the module converts that into "example.com?test_key=value1&test_key=value2".
The api I use do not accept this format but wants something like "example.com?test_key=value1,value2"

How can I achieve that ?


问:
tikz explain/annotate equation in LaTeX using straight arrows with right angles
Thanks to this excellent answer, I can get an equation as in this figure: with bent arrows. But what I really want is as in this figure: with right-angled arrows.

To simply write the code, you may start by modifying the code from here.

答:
Update: I've turned equation annotation into a LaTeX annotate-equations package (also on CTAN), which you might find useful.

Adapting Mike Renfro's answer
to straight edges is fairly straightforward: all I did was change from

\begin{tikzpicture}[overlay]
        \path[->]<1-> (nCPP) edge [bend left] (tCPP);
        \path[->]<2-> (nL) edge [bend left] (tL);
        \path[->]<3-> (nPPP) edge [out=0, in=0] (tPPP);
        \path[->]<4-> (nPP) edge [out=0, in=-90] (tPP);
\end{tikzpicture}
```
<p>to</p>
<pre class="lang-latex prettyprint-override"><code>\begin{tikzpicture}[overlay,->]
        \draw<1-> (nCPP) -| (tCPP);
        \draw<2-> (nL) -| (tL);
        \draw<3-> (nPPP) -| (tPPP);
        \draw<4-> (nPP) -| (tPP);
\end{tikzpicture}
</code>```

Changes explained:

replaced the edge and bend options with -| (there's also |- to bend at right angles the other way)

replaced \path with \draw to get the lines actually drawn

moved [->] into the tikzpicture environment options because for some reason it didn't work as \draw[->].

I've also set aspectratio=169 so there's enough space for the arrow for Predictor Prior Probability (it's also possible to work around that, but more hacky). This is what it looks like:

Body:
Update: I've turned equation annotation into a LaTeX annotate-equations package (also on CTAN), which you might find useful.

Adapting Mike Renfro's answer
to straight edges is fairly straightforward: all I did was change from

\begin{tikzpicture}[overlay]
        \path[->]<1-> (nCPP) edge [bend left] (tCPP);
        \path[->]<2-> (nL) edge [bend left] (tL);
        \path[->]<3-> (nPPP) edge [out=0, in=0] (tPPP);
        \path[->]<4-> (nPP) edge [out=0, in=-90] (tPP);
\end{tikzpicture}

to

\begin{tikzpicture}[overlay,->]
        \draw<1-> (nCPP) -| (tCPP);
        \draw<2-> (nL) -| (tL);
        \draw<3-> (nPPP) -| (tPPP);
        \draw<4-> (nPP) -| (tPP);
\end{tikzpicture}

Changes explained:

replaced the edge and bend options with -| (there's also |- to bend at right angles the other way)

replaced \path with \draw to get the lines actually drawn

moved [->] into the tikzpicture environment options because for some reason it didn't work as \draw[->].

I've also set aspectratio=169 so there's enough space for the arrow for Predictor Prior Probability (it's also possible to work around that, but more hacky). This is what it looks like:


问:
Dynamic Integration Runtime in Azure Data Factory (ADF)
I have multiple IR for each client. I want to use one pipeline to copy data from client SAP system to Blob.

I have created all the configuration variables like in below code but i am not able to create parameter for Integration Runtime variable.

Is there any JSON syntax where we can make it dynamic.

```<code>{
    "name": "LS_SAP_TBL",
    "type": "Microsoft.DataFactory/factories/linkedservices",
    "properties": {
        "type": "SapTable",
        "annotations": [],
        "typeProperties": {
            "clientId": "@{linkedService().ClientId}",
            "language": "",
            "sncMode": false,
            "userName": "@{linkedService().userName}",
            "password": {
                "type": "AzureKeyVaultSecret",
                "store": {
                    "referenceName": "KAJDSKJDHLSJDFHALKFD",
                    "type": "LinkedServiceReference"
                },
                "secretName": "@{linkedService().SecretName}"
            },
            "server": "@{linkedService().server}",
            "systemNumber": "@{linkedService().systemNumber}"
        },
        "connectVia": {
            "referenceName": "@IntegrationRuntime_Param - Need to pass this dynamically",
            "type": "IntegrationRuntimeReference"
        },
        "parameters": {
            "SecretName": {
                "type": "String"
            },
            "ClientId": {
                "type": "String"
            },
            "userName": {
                "type": "String"
            },
            "server": {
                "type": "String"
            },
            "systemNumber": {
                "type": "String"
            },
            "IntegrationRuntime_Param": {
                "type": "String"
            }
        }
    }
}```
```

答:
Yes, I second UtkarshPal's response. I hope we get this option ASAP.

In our case, we do have multiple ADFs (one per project), and each ADF has it's own SHIR.

The only method to reuse linked services with self hosted IR is to give all SHIRs the same name..

P.S. - If we are having multiple SHIRs within a single ADF, then it's not possible to have same name.

Body:
I have multiple IR for each client. I want to use one pipeline to copy data from client SAP system to Blob.

I have created all the configuration variables like in below code but i am not able to create parameter for Integration Runtime variable.

Is there any JSON syntax where we can make it dynamic.

{
    "name": "LS_SAP_TBL",
    "type": "Microsoft.DataFactory/factories/linkedservices",
    "properties": {
        "type": "SapTable",
        "annotations": [],
        "typeProperties": {
            "clientId": "@{linkedService().ClientId}",
            "language": "",
            "sncMode": false,
            "userName": "@{linkedService().userName}",
            "password": {
                "type": "AzureKeyVaultSecret",
                "store": {
                    "referenceName": "KAJDSKJDHLSJDFHALKFD",
                    "type": "LinkedServiceReference"
                },
                "secretName": "@{linkedService().SecretName}"
            },
            "server": "@{linkedService().server}",
            "systemNumber": "@{linkedService().systemNumber}"
        },
        "connectVia": {
            "referenceName": "@IntegrationRuntime_Param - Need to pass this dynamically",
            "type": "IntegrationRuntimeReference"
        },
        "parameters": {
            "SecretName": {
                "type": "String"
            },
            "ClientId": {
                "type": "String"
            },
            "userName": {
                "type": "String"
            },
            "server": {
                "type": "String"
            },
            "systemNumber": {
                "type": "String"
            },
            "IntegrationRuntime_Param": {
                "type": "String"
            }
        }
    }
}```


问:
Django-registration Admin
I've tried Django-registration, see this tutorial to create a full Login-system.

In the tutorials (see STEP 4), I need to update the file urls.py to:

```<code>from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
    (r'^accounts/', include('registration.urls')),
    (r'^$', direct_to_template,
            { 'template': 'index.html' }, 'index'),
)
</code>```

But when I do this, the Admin page is not available. When I chance

```<code>(r'^admin/(.*)', admin.site.root)
</code>```

in

```<code>(r'^admin/(.*)', admin.site.urls)
</code>```

The adminpage works; I could login, but I couldn't click on anything... So I couldn't see the registered users.

What am I doing wrong?

答:
admin.site.root was deprecated in Django 1.1, see release notes.

Do you couldn't click on anything because there aren't any links in admin?  If so then you have to login as superuser.

Also registration.urls is deprecated.  The new version of django-registration represents a complete rewrite of the previous codebase and improve flexibility so it is a good idea to use version from repository.  It has good quick-start guide.

Title: Django-registration Admin

Body:
I've tried Django-registration, see this tutorial to create a full Login-system.

In the tutorials (see STEP 4), I need to update the file urls.py to:

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
    (r'^accounts/', include('registration.urls')),
    (r'^$', direct_to_template,
            { 'template': 'index.html' }, 'index'),
)

But when I do this, the Admin page is not available. When I chance

(r'^admin/(.*)', admin.site.root)

in

(r'^admin/(.*)', admin.site.urls)

The adminpage works; I could login, but I couldn't click on anything... So I couldn't see the registered users.

What am I doing wrong?


问:
How to print symbols vertically in python?
I just want to print a symbol a certain amount of times vertically.

```<code>def draw_symbol():
        print()
        symbol = ""
        for num in range(8):
            symbol += "*"
        print(symbol)
        return

    draw_row()
</code>```

The output is  "*******"  but it is supposed to be vertical.

答:
```<code>def draw_symbol():
    for num in range(8):
        print("*")
    return
draw_symbol()
</code>```

would result in:

```<code>*
*
*
*
*
*
*
*
</code>```

Body:
I just want to print a symbol a certain amount of times vertically.

def draw_symbol():
        print()
        symbol = ""
        for num in range(8):
            symbol += "*"
        print(symbol)
        return

    draw_row()

The output is  "*******"  but it is supposed to be vertical.

Body:
def draw_symbol():
    for num in range(8):
        print("*")
    return
draw_symbol()

would result in:

*
*
*
*
*
*
*
*


问:
HTML show image if it exists and show nothing if it doesn't
I need to display an image on my HTML page but only if it exists on my computer (aka i give it a path and it checks). If it doesn't, then show nothing. How can I write a function that checks if the image exists, then if yes, display it if no, don't show anything?
I am using django as a back end.</p>

答: I think you should try os.path.exist</p>

Body: I think you should try os.path.exist


问:
VBA Excel SelectionChange Reading Target Range into array and returning column count
When a new selection of cells is made, I want to convert the range into an array for later use, and determine the number of columns selected.  This is the code I have, but I get a type mismatch error.  Can someone point me in the right direction?</p>
```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim arr As Variant
    Dim colcount As Long
    arr = Target
    colcount = UBound(arr, 2)
    Debug.Print colcount
End Sub
</code>```

答:
The error is due to Range.Value returning only a single value when the range only has a single cell.

If Target is a single cell, then Target will return a single value instead of an array. arr will be a single value and UBound(arr, 2) will error because arr is not an array.

You can use IsArray to check if arr is an array or not before attempting UBound. Also, if you intend to save these values for future use, you should define them as Module-Level variables.

Dim arr As Variant
Dim colcount As Long

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    arr = Target
    If IsArray(arr) Then
        colcount = UBound(arr, 2)
    Else
        colcount = 1
    End If
    Debug.Print colcount
End Sub
```

To fill colcount, other than UBound, you could also just do colcount = Target.Columns.Count which would also avoid needing to check IsArray.

Body:
When a new selection of cells is made, I want to convert the range into an array for later use, and determine the number of columns selected.  This is the code I have, but I get a type mismatch error.  Can someone point me in the right direction?

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim arr As Variant
    Dim colcount As Long
    arr = Target
    colcount = UBound(arr, 2)
    Debug.Print colcount
End Sub

Body:
The error is due to Range.Value returning only a single value when the range only has a single cell.

If Target is a single cell, then Target will return a single value instead of an array. arr will be a single value and UBound(arr, 2) will error because arr is not an array.

You can use IsArray to check if arr is an array or not before attempting UBound. Also, if you intend to save these values for future use, you should define them as Module-Level variables.

Dim arr As Variant
Dim colcount As Long

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    arr = Target
    If IsArray(arr) Then
        colcount = UBound(arr, 2)
    Else
        colcount = 1
    End If
    Debug.Print colcount
End Sub

To fill colcount, other than UBound, you could also just do colcount = Target.Columns.Count which would also avoid needing to check IsArray.


问:
Use a dictionary to find/replace exact terms in a tokenized pandas series
Using a dictionary, I need to find and replace terms in a pandas series according to the following criteria:

dictionary values are replacing dictionary keys wherever they are found in the pandas series (e.g., for example, in 'mastersphd': 'masters phd', the replacement outcome would be 'masters phd' wherever 'mastersphd' occurs)

maintain record integrity (i.e., can't use a bag of words approach because I need the unique records to remain intact.)

Only exact matches should be replaced (for example, if key:value is 'rf': 'random forest', the replacement should not turn 'performance' into 'perandom forestormance'); so regex=True is causing this, obviously)

The Data: term_fixes is the dictionary, and df['job_description'] is the tokenized series of interest

```<code>term_fixes = {'rf': 'random forest',
              'mastersphd': 'masters phd',
              'curiosity': 'curious',
              'trustworthy': 'ethical',
              'realise': 'realize'}

df = pd.DataFrame(data={'job_description': [['knowledge', 'of', 'algorithm', 'like', 'rf'],
                                            ['must', 'have', 'a', 'mastersphd'],
                                            ['trustworthy', 'and', 'possess', 'curiosity'],
                                            ['we', 'realise', 'performance', 'is', 'key']]})
</code>```

**Note: I have also (unsuccessfully) tried an untokenized data structure, but prefer tokenized since I have more NLP to do

```<code>df = pd.DataFrame(data={'job_description': ['knowledge of algorithm like rf',
                                            'must have a mastersphd',
                                            'must be trustworthy and possess curiosity',
                                            'we realise performance is critical']})
</code>```

**Desired Outcome (note that the 'rf' in performance is not replaced by 'random forest'):
df['job_description']

```<code>0    ['knowledge' 'of' 'algorithm' 'like' 'random' 'forest']
1                        ['must' 'have' 'a' 'masters' 'phd']
2          ['must' 'be' 'ethical' 'and' 'possess' 'curious']
3             ['we' 'realize' 'performance' 'is' 'critical']
</code>```

I have tried a number of approaches.
Fail: df['job_description'].replace(list(term_fixes.keys()), list(term_fixes.values()), regex=False, inplace=True)

Fail: df['job_description'].replace(dict(zip(list(term_fixes.keys()), list(term_fixes.values()))), regex=False, inplace=True)

Fail: df['job_description'] = df['job_description'].str.replace(term_fixes, regex=False)

Fail: df['job_description'] = df['job_description'].str.replace(str(term_fixes.keys()), str(term_fixes.values()), regex=True)

The closest I have come is:

```<code>df['job_description'] = df_jobs['job_description'].replace(term_fixes, regex=True)
</code>```

However, the regex=True flags on any match (like the 'rf' and 'performance' example above). Changing the flag to regex=False fails to replace anything, unfortunately. I looked in the documentation for another argument I could use, but no luck. Note that this uses the untokenized structure.

Any help would be much appreciated. Thanks!

答:
You could use something like the following to do so with the untokenized data.</p>
```<code>for k in term_fixes:
    df['job_description'] = (df['job_description'].str.replace(r'(^|(?<= )){}((?= )|$)'.format(k), term_fixes[k]))

print(df)
                             job_description
0  knowledge of algorithm like random forest
1                    must have a masters phd
2        must be ethical and possess curious
3         we realize performance is critical
</code>```

Body:
Using a dictionary, I need to find and replace terms in a pandas series according to the following criteria:

dictionary values are replacing dictionary keys wherever they are found in the pandas series (e.g., for example, in 'mastersphd': 'masters phd', the replacement outcome would be 'masters phd' wherever 'mastersphd' occurs)

maintain record integrity (i.e., can't use a bag of words approach because I need the unique records to remain intact.)

Only exact matches should be replaced (for example, if key:value is 'rf': 'random forest', the replacement should not turn 'performance' into 'perandom forestormance'); so regex=True is causing this, obviously)

The Data: term_fixes is the dictionary, and df['job_description'] is the tokenized series of interest

term_fixes = {'rf': 'random forest',
              'mastersphd': 'masters phd',
              'curiosity': 'curious',
              'trustworthy': 'ethical',
              'realise': 'realize'}

df = pd.DataFrame(data={'job_description': [['knowledge', 'of', 'algorithm', 'like', 'rf'],
                                            ['must', 'have', 'a', 'mastersphd'],
                                            ['trustworthy', 'and', 'possess', 'curiosity'],
                                            ['we', 'realise', 'performance', 'is', 'key']]})

**Note: I have also (unsuccessfully) tried an untokenized data structure, but prefer tokenized since I have more NLP to do

df = pd.DataFrame(data={'job_description': ['knowledge of algorithm like rf',
                                            'must have a mastersphd',
                                            'must be trustworthy and possess curiosity',
                                            'we realise performance is critical']})

**Desired Outcome (note that the 'rf' in performance is not replaced by 'random forest'):
df['job_description']

0    ['knowledge' 'of' 'algorithm' 'like' 'random' 'forest']
1                        ['must' 'have' 'a' 'masters' 'phd']
2          ['must' 'be' 'ethical' 'and' 'possess' 'curious']
3             ['we' 'realize' 'performance' 'is' 'critical']

I have tried a number of approaches.
Fail: df['job_description'].replace(list(term_fixes.keys()), list(term_fixes.values()), regex=False, inplace=True)

Fail: df['job_description'].replace(dict(zip(list(term_fixes.keys()), list(term_fixes.values()))), regex=False, inplace=True)

Fail: df['job_description'] = df['job_description'].str.replace(term_fixes, regex=False)

Fail: df['job_description'] = df['job_description'].str.replace(str(term_fixes.keys()), str(term_fixes.values()), regex=True)

The closest I have come is:

df['job_description'] = df_jobs['job_description'].replace(term_fixes, regex=True)

However, the regex=True flags on any match (like the 'rf' and 'performance' example above). Changing the flag to regex=False fails to replace anything, unfortunately. I looked in the documentation for another argument I could use, but no luck. Note that this uses the untokenized structure.

Any help would be much appreciated. Thanks!

Body:
You could use something like the following to do so with the untokenized data.

for k in term_fixes:
    df['job_description'] = (df['job_description'].str.replace(r'(^|(?<= )){}((?= )|$)'.format(k), term_fixes[k]))

print(df)
                             job_description
0  knowledge of algorithm like random forest
1                    must have a masters phd
2        must be ethical and possess curious
3         we realize performance is critical


问:
React Native TouchableHighlight onPress not working
I have tried everything to make this work. I have read all the answers and it never works for me. I am completely out of ideas.

Here is the function I am trying to call:

```<code>function handlePress() {
    console.log('test');
}
</code>```

Here is what I have tried:

This one does nothing:

```<code><TouchableHighlight
    onPress={() => { alert('You tapped the button!') }}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>
</code>```

This one triggers without me doing anything:

```<code><TouchableHighlight
    onPress={alert('You tapped the button!')}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>
</code>```

This one triggers without me doing anything:

```<code><TouchableHighlight
    onPress={handlePress()}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>
</code>```

This one does nothing:

```<code><TouchableHighlight
    onPress={() => {() => handlePress()}}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>
</code>```

This one does nothing:

```<code>    <TouchableHighlight
    onPress={() => handlePress()}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>
</code>```

This one does nothing:

```<code><TouchableHighlight
    onPress={handlePress}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>
</code>```

Can anyone help?

答:
I had done everything the same as you have. Only I have heavily relied on auto-import of VS code that TouchableHighlight was auto imported from react-native-gesture-handler rather it should be imported from react-native lib.

I changed it to react-native and it is working fine.

Wrong

Corrected

Body:
I have tried everything to make this work. I have read all the answers and it never works for me. I am completely out of ideas.

Here is the function I am trying to call:

function handlePress() {
    console.log('test');
}

Here is what I have tried:

This one does nothing:

<TouchableHighlight
    onPress={() => { alert('You tapped the button!') }}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one triggers without me doing anything:

<TouchableHighlight
    onPress={alert('You tapped the button!')}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one triggers without me doing anything:

<TouchableHighlight
    onPress={handlePress()}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one does nothing:

<TouchableHighlight
    onPress={() => {() => handlePress()}}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one does nothing:

    <TouchableHighlight
    onPress={() => handlePress()}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one does nothing:

<TouchableHighlight
    onPress={handlePress}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

Can anyone help?


问:
Select automatically a filter option after my page is loaded
I have a list of options which filters a range of pictures when the user click on it.

My page loads all pictures (there are lots of them to show together) and I would like to "simulate" a click on "Best Pictures" link to show only this gallery after the page is loaded.

```<code><ul id="filters" class="option-set" data-option-key="filter">
   <li class="type-work">Category</li>
   <li><a href="#filter" data-option-value=".best">Best Pictures</a></li>
   <li><a href="#filter" data-option-value=".beach">Beaches</a></li>
   <li><a href="#filter" data-option-value=".snow">Ski stations</a></li>
   <li><a href="#filter" data-option-value=".park">Parks</a></li>
</ul>
</code>```

答:
Try this command:

```<code>document.getElementById("myFilter").click();
</code>```

Or:

```<code>document.querySelector("[data-option-value=\u0022" + chosenFilter + "\u0022]").click();
</code>```

Body:
I have a list of options which filters a range of pictures when the user click on it.

My page loads all pictures (there are lots of them to show together) and I would like to "simulate" a click on "Best Pictures" link to show only this gallery after the page is loaded.

Category

Best Pictures

Beaches

Ski stations

Parks

Body:
Try this command:

document.getElementById("myFilter").click();

Or:

document.querySelector("[data-option-value=\u0022" + chosenFilter + "\u0022]").click();


问:
Max/Min/Avg returning array in that order
Can anyone tell me what I'm doing wrong? I am printing the array just not in the right order. How do i call it differently? This is javascript by the way.

Given an array x (e.g. [1,5, 10, -2]), create an algorithm (sets of instructions) that returns an array with the max, min, and average values ([max, min, avg]. ex [0,2,4] should return [4,0,2]).

My code:

```<code>function maxMinAvg(arr) {
    var newarr= [];
    var max = arr[0];
    var min = arr[0];
    sum = sum + arr[0];
    var avg = sum/arr.length;
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
        if (arr[i] < min) {
            min = arr[i];
        }
        sum = sum + arr[i];
    }
    newarr.push([max[i],min[i],avg[i]]);
}

return newarr;
</code>```

答:
```<code>function maxMinMean(arr: number[]) {
  if (!arr.length) return [NaN,NaN,NaN];
  arr.sort((a,b)=>a-b);
  return [
    arr.slice(-1)[0],
    arr[0],
    arr.reduce((sum, x) => sum + x,0) / arr.length,
  ];
}
</code>```

If you didn't want to modify the original array

```<code>function maxMinMean(arrIn: number[]) {
  if (!arrIn.length) return [NaN,NaN,NaN];
  var arr =[...arrIn].sort((a,b)=>a-b);
  return [
    arr.slice(-1)[0],
    arr[0],
    arr.reduce((sum, x) => sum + x,0) / arr.length,
  ];
}
</code>```

If you wanted fixed point strings

```<code>function maxMinMean(arr: number[]) {
  if (!arr.length) return [NaN,NaN,NaN];
  arr.sort((a,b)=>a-b);
  return [
    arr.slice(-1)[0],
    arr[0],
    arr.reduce((sum, x) => sum + x,0) / arr.length,
  ].map(f=>f.toFixed(2));
}
</code>```

Body:
Can anyone tell me what I'm doing wrong? I am printing the array just not in the right order. How do i call it differently? This is javascript by the way.

Given an array x (e.g. [1,5, 10, -2]), create an algorithm (sets of instructions) that returns an array with the max, min, and average values ([max, min, avg]. ex [0,2,4] should return [4,0,2]).

My code:

function maxMinAvg(arr) {
    var newarr= [];
    var max = arr[0];
    var min = arr[0];
    sum = sum + arr[0];
    var avg = sum/arr.length;
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
        if (arr[i] < min) {
            min = arr[i];
        }
        sum = sum + arr[i];
    }
    newarr.push([max[i],min[i],avg[i]]);
}

return newarr;

Body:
function maxMinMean(arr: number[]) {
  if (!arr.length) return [NaN,NaN,NaN];
  arr.sort((a,b)=>a-b);
  return [
    arr.slice(-1)[0],
    arr[0],
    arr.reduce((sum, x) => sum + x,0) / arr.length,
  ];
}

If you didn't want to modify the original array

function maxMinMean(arrIn: number[]) {
  if (!arrIn.length) return [NaN,NaN,NaN];
  var arr =[...arrIn].sort((a,b)=>a-b);
  return [
    arr.slice(-1)[0],
    arr[0],
    arr.reduce((sum, x) => sum + x,0) / arr.length,
  ];
}

If you wanted fixed point strings

function maxMinMean(arr: number[]) {
  if (!arr.length) return [NaN,NaN,NaN];
  arr.sort((a,b)=>a-b);
  return [
    arr.slice(-1)[0],
    arr[0],
    arr.reduce((sum, x) => sum + x,0) / arr.length,
  ].map(f=>f.toFixed(2));
}


问:
NavLink returns active to all links and no solution in SO seems to work
It seems none of the solutions presented elsewhere works, so I decided to ask. No matter what I do, I can't get the NavLinks to be rendered differently if they are active or not. I took the ternary operator straight from the part about NavLinks in react-router-dom's documentation and I'd try to create a function to avoid having all this code written three times, but before that I'd like to at least have the correct rendering working.

(side question: why does it break if I remove the Router tags from the return statement? They're there because, before I needed the NavLinks for different styling, I was using regular routes, but if I take them out it breaks with a message about useHref, something like that)

Here's my return statement and the styled-components below it:

```<code>return (
        <>
            <GlobalStyles />
            <Router>
                <Header />
                <Wrapper>
                    <NavBar>
                        <NavLink
                            to="/search"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Search song
                        </NavLink>
                        <NavLink
                            to="/weekly-thread"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Weekly thread
                        </NavLink>
                        <NavLink
                            to="/game"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Game
                        </NavLink>
                    </NavBar>
                </Wrapper>
            </Router>
        </>
    );
};

const Wrapper = styled.div`
    width: 100vw;
    height: 100vh;
    position: absolute;
    z-index: -1;
`;
const NavBar = styled.div`
    display: flex;
    padding: 20px 20px;
    position: relative;
    gap: 20px;
    font-size: 18px;
    a {
        text-decoration: none;
    }
    .nav-link {
        color: blue;
        &:inactive {
            color: black;
        }
    }
`;

</code>```

EDIT: it's getting weirder. After even simply pasting the code from the answer below and not getting any results, I tried to mess with the font size for the active NavLink. To my surprise, now something changed, but in totally bizarre way, as it made the first element stay as it were before and second and third got transformed just in terms of font size, but nothing else. When I click on the other NavLinks, the URL changes, but they remain the same: the first in the original size, the other two altered.

SECOND EDIT: Trying to debug this a little further, I've done this to one of my NavLinks and the result is very weird:

```<code><NavLink to="/search" exact className={(isActive) => {
    console.log(isActive);
    isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>
</code>```

Now, the first console.log returns the actual value of isActive, but the second and third console.logs always return, "foo", which is the second value in the ternary operator, even if I change "isActive === false" to "isActive === true", which should swap them. I have no idea what is going on here.

答:
You should be able to remove your className property from NavLink.

Remove:

```<code>className={(isActive) =>
    "nav-link" + (!isActive ? " inactive" : "")
}>
</code>```

It's unnecessary as React-Router already adds the .active class to the active link, so what you're doing with that property is no doubt creating the weirdness.

You can just style the a.active however you want.

Body:
It seems none of the solutions presented elsewhere works, so I decided to ask. No matter what I do, I can't get the NavLinks to be rendered differently if they are active or not. I took the ternary operator straight from the part about NavLinks in react-router-dom's documentation and I'd try to create a function to avoid having all this code written three times, but before that I'd like to at least have the correct rendering working.

(side question: why does it break if I remove the Router tags from the return statement? They're there because, before I needed the NavLinks for different styling, I was using regular routes, but if I take them out it breaks with a message about useHref, something like that)

Here's my return statement and the styled-components below it:

return (
        <>
            <GlobalStyles />
            <Router>

                <Wrapper>
                    <NavBar>
                        <NavLink
                            to="/search"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Search song
                        </NavLink>
                        <NavLink
                            to="/weekly-thread"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Weekly thread
                        </NavLink>
                        <NavLink
                            to="/game"
                            exact
                            className={(isActive) =>
                                "nav-link" + (!isActive ? " inactive" : "")
                            }>
                            Game
                        </NavLink>
                    </NavBar>
                </Wrapper>
            </Router>
        </>
    );
};

const Wrapper = styled.div`
    width: 100vw;
    height: 100vh;
    position: absolute;
    z-index: -1;
`;
const NavBar = styled.div`
    display: flex;
    padding: 20px 20px;
    position: relative;
    gap: 20px;
    font-size: 18px;
    a {
        text-decoration: none;
    }
    .nav-link {
        color: blue;
        &:inactive {
            color: black;
        }
    }
`;

EDIT: it's getting weirder. After even simply pasting the code from the answer below and not getting any results, I tried to mess with the font size for the active NavLink. To my surprise, now something changed, but in totally bizarre way, as it made the first element stay as it were before and second and third got transformed just in terms of font size, but nothing else. When I click on the other NavLinks, the URL changes, but they remain the same: the first in the original size, the other two altered.

SECOND EDIT: Trying to debug this a little further, I've done this to one of my NavLinks and the result is very weird:

<NavLink to="/search" exact className={(isActive) => {
    console.log(isActive);
    isActive === false ? console.log(isActive) : console.log("foo");
}}>Search song</NavLink>

Now, the first console.log returns the actual value of isActive, but the second and third console.logs always return, "foo", which is the second value in the ternary operator, even if I change "isActive === false" to "isActive === true", which should swap them. I have no idea what is going on here.

Body:
You should be able to remove your className property from NavLink.

Remove:

className={(isActive) =>
    "nav-link" + (!isActive ? " inactive" : "")
}>

It's unnecessary as React-Router already adds the .active class to the active link, so what you're doing with that property is no doubt creating the weirdness.

You can just style the a.active however you want.


问:
Browser not saving response cookies
Frond-end: React (react-admin) with Webpack

Back-end: NestJS / Express

I developed 3 routes (login, check and logout) that are beautifully working with Swagger UI, but when I try to use the 'login' route in my login page it doesn't save the cookie in the browser > application > storage > cookies

I'm setting the cookie on the back end with this code:

```<code>response.cookie('tk', 'Bearer ' + token, {
    domain: hostname, // localhost or 127.0.0.1
    path: "/",
    expires: oneMonthFromNowDate,
    httpOnly: true,
    secure: false,
    sameSite: true
});
</code>```

And in the front end I'm receiving a successfull response with the cookie assigned:

But it is not saving in the browser > application > storage > cookies!

答:
Looks like I was missing some kind of configuration...

Solved using Axios with "credentials: true" option.

Title: Browser not saving response cookies

Body:
Frond-end: React (react-admin) with Webpack

Back-end: NestJS / Express

I developed 3 routes (login, check and logout) that are beautifully working with Swagger UI, but when I try to use the 'login' route in my login page it doesn't save the cookie in the browser > application > storage > cookies

I'm setting the cookie on the back end with this code:

response.cookie('tk', 'Bearer ' + token, {
    domain: hostname, // localhost or 127.0.0.1
    path: "/",
    expires: oneMonthFromNowDate,
    httpOnly: true,
    secure: false,
    sameSite: true
});

And in the front end I'm receiving a successfull response with the cookie assigned:

But it is not saving in the browser > application > storage > cookies!