问:
Does an implicit typecast in Java have an effect on the order of operations?
I have a snippet from my code where a statement that seems like it should evaluate to "false" actually returns true.

```<code>        long composite = -1L;

        ArrayList<Long> primes = new ArrayList<Long>();
        ArrayList<Long> squares = new ArrayList<Long>();
        squares.add(1L);
        primes.add(2L);
        primes.add(3L);

        for (long i = 4; composite == -1L; i++) {
            double sqrt_max = Math.sqrt((double) i);
            if (sqrt_max == (int) sqrt_max) squares.add(i);
            if (i % 2 == 0) continue;
            boolean prime = true;
            for (int j = 0; primes.get(j) <= sqrt_max; j++) {
                if (i % primes.get(j) == 0) {// number is not prime
                    prime = false;
                    break;
                }
            }
            if (prime) { // number is prime
                primes.add(i);
            }
            else {
                boolean conjTrue = false;
                for (Long l : primes) {
                    ListIterator<Long> it = squares.listIterator(squares.size() - 1);
                    while (it.hasPrevious()) {
                        long m = it.previous();
                        if (l + 2L * m == i) {
                            conjTrue = true;
                            break;
                        }
                        else if (l + 2L * m < i) break;
                    }
                    if (conjTrue) break;
                }
                if (!conjTrue) composite = i;
            }
        }

        System.out.println("\nAnswer: " + composite);
</code>```

As it stands, this code works fine (I finished debugging), but I found a problem that I could not explain and I wanted to learn.

The relational statement else if (l + 2L * m < i), when the variables evaluate to (19 + 2 * 9 < 27) -> (38 < 27) (obviously false) would evaluate to true if the code was instead else if (l + 2 * m < i). Note the 2L is replaced with a 2 (int). I even used a print statement directly after the else if to test the value of the boolean l + 2 * m < i and would get true.

Something about being within the else if conditional parentheses and the implicit typecast caused the relation to erroneously evaluate to true. Within other contexts it would compute correctly. What could cause this issue?

答:
To simplify your question,

It seems that you are suggesting that

```<code>    Long l = 19L;
    Long m = 9L;
    long i = 27;
    System.out.println(l + 2L * m < i);
</code>```

would print true.

output

```<code>false
</code>```

Body:
I have a snippet from my code where a statement that seems like it should evaluate to "false" actually returns true.

        long composite = -1L;

        ArrayList<Long> primes = new ArrayList<Long>();
        ArrayList<Long> squares = new ArrayList<Long>();
        squares.add(1L);
        primes.add(2L);
        primes.add(3L);

        for (long i = 4; composite == -1L; i++) {
            double sqrt_max = Math.sqrt((double) i);
            if (sqrt_max == (int) sqrt_max) squares.add(i);
            if (i % 2 == 0) continue;
            boolean prime = true;
            for (int j = 0; primes.get(j) <= sqrt_max; j++) {
                if (i % primes.get(j) == 0) {// number is not prime
                    prime = false;
                    break;
                }
            }
            if (prime) { // number is prime
                primes.add(i);
            }
            else {
                boolean conjTrue = false;
                for (Long l : primes) {
                    ListIterator<Long> it = squares.listIterator(squares.size() - 1);
                    while (it.hasPrevious()) {
                        long m = it.previous();
                        if (l + 2L * m == i) {
                            conjTrue = true;
                            break;
                        }
                        else if (l + 2L * m < i) break;
                    }
                    if (conjTrue) break;
                }
                if (!conjTrue) composite = i;
            }
        }

        System.out.println("\nAnswer: " + composite);

As it stands, this code works fine (I finished debugging), but I found a problem that I could not explain and I wanted to learn.

The relational statement else if (l + 2L * m < i), when the variables evaluate to (19 + 2 * 9 < 27) -> (38 < 27) (obviously false) would evaluate to true if the code was instead else if (l + 2 * m < i). Note the 2L is replaced with a 2 (int). I even used a print statement directly after the else if to test the value of the boolean l + 2 * m < i and would get true.

Something about being within the else if conditional parentheses and the implicit typecast caused the relation to erroneously evaluate to true. Within other contexts it would compute correctly. What could cause this issue?

Body:
To simplify your question,

It seems that you are suggesting that

    Long l = 19L;
    Long m = 9L;
    long i = 27;
    System.out.println(l + 2L * m < i);

would print true.

output

false


来源: stackexchange

问:
How to get the target fps of requestAnimationFrame?
I have an animation loop run by requestAnimationFrame.

On my computer, the time between frames obtained this way are more or less 16.667ms corresponding to 60fps. However, https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame states that it doesn't necessarily run at a fixed speed and may try to match the device screen refresh rate which could be 90 or 120 or more these days.

Now what I want to do is to measure the time between frames and simplify the animation on low performance devices if the hardware can't keep up, in pseudocode:

```<code>if (elapsed_frame_time > (1000 / magical_function_to_get_the_target_fps_of_requestAnimationFrame()) {
    animation.particles *= 0.9;
}
</code>```

I suppose I could just measure it over a few empty requestAnimationFrame ticks to get the approximate nominal time but is there anything in the standard library that would just tell me what the interval or fps should be?

答:
No there is nothing that let us know the "optimal" frequency of requestAnimationFrame (rAF).

Even measuring it by checking a few rounds is not an exact science. You may very well be measuring while an other app is eating all the available process of the device, your user may be scrolling the page which may have dramatic influence on rAF, you will definitely have outliers and it will be near impossible to tell between a 59.9Hz monitor and a 60Hz one for instance.

So if you really have to go this route

Be sure to use an average FPS, based on a big enough sample and to ignore the first call (because browsers actually execute the callback directly from a non-animated document).

Check the callback's timestamp, since this will represent the time the monitor sent its V-Sync signal and shouldn't be influenced by other scripts on the page.

Probably wait at least a few dropped frames before intervening.

Remember that some users may have dual-monitor systems with various refresh-rates.

Expect some edge cases and browser bugs.

ContentLicense: CC BY-SA 4.0

Body:
I have an animation loop run by requestAnimationFrame.

On my computer, the time between frames obtained this way are more or less 16.667ms corresponding to 60fps. However, https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame states that it doesn't necessarily run at a fixed speed and may try to match the device screen refresh rate which could be 90 or 120 or more these days.

Now what I want to do is to measure the time between frames and simplify the animation on low performance devices if the hardware can't keep up, in pseudocode:

if (elapsed_frame_time > (1000 / magical_function_to_get_the_target_fps_of_requestAnimationFrame()) {
    animation.particles *= 0.9;
}

I suppose I could just measure it over a few empty requestAnimationFrame ticks to get the approximate nominal time but is there anything in the standard library that would just tell me what the interval or fps should be?


问:
A href pointed to nowhere added # to url
I have a href which pointed to #

```<code><a href="#" id="bla" >Bla<a>
</code>```

I have onclick function which displaying popup on click on that a href.

```<code>function doingClick()
{
   //display popup
   return false;
}
</code>```

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

答:
Instead of adding a href, you could add a style="cursor:pointer;"
this has the same effect of displaying it like a hyperlink, without the in-page anchor effect.</p>

```<code><a id="bla" onclick="return doingClick()" style="cursor:pointer;">Link</a>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a href which pointed to #

Bla

I have onclick function which displaying popup on click on that a href.

function doingClick()
{
   //display popup
   return false;
}

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

Body:
Instead of adding a href, you could add a style="cursor:pointer;"
this has the same effect of displaying it like a hyperlink, without the in-page anchor effect.

<a id="bla" onclick="return doingClick()" style="cursor:pointer;">Link</a>


问:
Identifying feature polygons along a GeoJSON LingString (MapBox)
I've got the whole world divided into polygons (GEOJSON - FeatureCollection - MultiPolygon). Those polygons are FIRs (Flight Information Regions). Placed a LineString on the map I need to understand through which polygons it passes through. The LineString represents the flight plan of an aircraft.

I'm including a screenshot to better represent how it works:

I wonder what would be the best way to find all those polygons.

This is my FIR Feature Collection:

I've got multiple lines, so they are added as a GEOJSON MultiLineString, but in the end each one is a LineString.

So far the idea that I have is to use https://turfjs.org/docs/#along and call it every N amount of distance (e.g. 10 km) and call MapBox QueryRenderedFeatures (https://docs.mapbox.com/mapbox-gl-js/api/map/#map#queryrenderedfeatures) to get each feature, but I'm not sure if that's the best approach, I've got issues with that function and I'm not sure if it will work if some of the polygons are not in the screen view for long routes.

I would appreciate any help or indication, I tried to find more information on it, but I'm not sure if I'm searching for it correctly, it seems like something people have experienced in the past.

答:
So, if you find yourself in a situation where you need to calculate what Polygon or MultiPolygon are being passed through by a LineString, then here is the solution that I came with and which worked for me:

Assure your coordinates are of type LineString, use https://turfjs.org/docs/#lineString if necessary

Create an array of coordinates along that line https://turfjs.org/docs/#along, for e.g. starting from the beginning, loop every N kilometers/miles, until the end of the LineString

Loop your polygons https://turfjs.org/docs/#pointsWithinPolygon to see which points are within it, if there is at least one point, it means that the line crossed it.

I hope this will help anyone in the future. I hope someone else will be able to share any more elegant solutions if there are any.


问:
Why the bufferedREader is close after call to another funcation. How can I write that I can read after callin another function
Why is BufferedReader closed after calling another method? How can I read after calling another method? After execution of method add() the reader is closed and reader into main throwing NullPointerException(closed).

Quweston was solved. Into another method I made readers too and after calling method with reader(into try with resorces) both reader closed.
I solve this by deleting all readers and made one into one static methos with static reader for all programm.

public class Main {
    public static void main(String[] args) {
        ReaderIn reader = new ReaderIn();
        while (true) {
            System.out.println("Input the action (add, remove, import, export, ask, exit):");
            String switchTrigger = null;
            try {
                switchTrigger = new BufferedReader(new InputStreamReader(System.in)).readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (switchTrigger == null) {
                System.out.println("SwitchTrigger is null.");
                System.exit(0);
            }
            switch (switchTrigger) {
                case "add":
                    add();
                    break;
                case "remove":
                    remove();
                    break;
                case "import":
                    importCardFromFile();
                    break;
                case "export":
                    export();
                    break;
                case "ask":
                    ask();
                    break;
                case "exit":
                    System.out.println("Bye bye!");
                    System.exit(0);
                    break;
                default:
                    break;
            }
        }
    }
```

答: I solve this problem by deleting Reader into another methods (into add(), remove()) and creat one method with one reader for all program.</p>


问:
Simulating coin tosses on a fixed time scale and increasing the # of steps
I've written out some basic (and commonly used code) to simulate Weiner processes. Recently, I looked at Paul Wilmott Introduces Quantitative Finance (IInd edition, Chp 5, page 122) where a chart shows the impact of increasing the number of steps (while keeping T fixed at 1) on the coin toss experiment.
I'm not quite sure how to create this chart.

The code is rather basic, but I'll share it:

```<code>def brownian(num_steps):
    w = np.ones(num_steps)
    for i in range(1, num_steps):
        yi = np.random.choice([-1, 1])
        # dW
        w[i] = w[i-1]  + yi/np.sqrt(num_steps)
    return w
</code>```

The problem is that I don't quite know how to make the num steps fit into the interval [0, 1] (i.e. the length of time on the x axis in the picture).
Would appreciate some guidance
Thanks

答:
You can try this:

```<code>import numpy as np
import matplotlib.pyplot as plt

def brownian(num_steps):
    rng = np.random.default_rng()
    w = np.cumsum(2 * rng.integers(0, 2, num_steps-1) - 1)
    return np.r_[0, w] / np.sqrt(num_steps)

num_steps = 50
plt.style.use('seaborn-whitegrid')
plt.plot(np.linspace(0, 1, num_steps), brownian(num_steps))
plt.show()
</code>```

It gives:

Body:
I've written out some basic (and commonly used code) to simulate Weiner processes. Recently, I looked at Paul Wilmott Introduces Quantitative Finance (IInd edition, Chp 5, page 122) where a chart shows the impact of increasing the number of steps (while keeping T fixed at 1) on the coin toss experiment.
I'm not quite sure how to create this chart.

The code is rather basic, but I'll share it:

def brownian(num_steps):
    w = np.ones(num_steps)
    for i in range(1, num_steps):
        yi = np.random.choice([-1, 1])
        # dW
        w[i] = w[i-1]  + yi/np.sqrt(num_steps)
    return w

The problem is that I don't quite know how to make the num steps fit into the interval [0, 1] (i.e. the length of time on the x axis in the picture).
Would appreciate some guidance
Thanks

Body:
You can try this:

import numpy as np
import matplotlib.pyplot as plt

def brownian(num_steps):
    rng = np.random.default_rng()
    w = np.cumsum(2 * rng.integers(0, 2, num_steps-1) - 1)
    return np.r_[0, w] / np.sqrt(num_steps)

num_steps = 50
plt.style.use('seaborn-whitegrid')
plt.plot(np.linspace(0, 1, num_steps), brownian(num_steps))
plt.show()

It gives:


问:
How to save a name as a variable when saving a Data frame file?
I have to save several files at a time.

It is saved as .txt using .to_csv.

The following method is used to save the Data Frames of position, energy, number, event, and height.

```<code>position.to_csv('/HDD1/abc_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/abc_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/abc_height.txt',index=False,sep=" ")
</code>```

Let's check the save file name above. They contain 'abc'.
I want to replace 'abc' with the variable 'A = abc' without having to write it down many times.

In other words, it should be as follows.

```<code>A = abc
postion.to_csv('/HDD1/A_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/A_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/A_height.txt',index=False,sep=" ")
</code>```

Is there a way to save files using variables as above?

答:
Are you looking for f-strings?</p>
```<code>A = 'abc'
postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")
</code>```

Body:
I have to save several files at a time.

It is saved as .txt using .to_csv.

The following method is used to save the Data Frames of position, energy, number, event, and height.

position.to_csv('/HDD1/abc_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/abc_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/abc_height.txt',index=False,sep=" ")

Let's check the save file name above. They contain 'abc'.
I want to replace 'abc' with the variable 'A = abc' without having to write it down many times.

In other words, it should be as follows.

A = abc
postion.to_csv('/HDD1/A_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/A_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/A_height.txt',index=False,sep=" ")

Is there a way to save files using variables as above?

Body:
Are you looking for f-strings?

A = 'abc'
postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")


答:
can use an f-string. Let

```<code>A = 'abc'

postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_number.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")

</code>```

EDIT
Aditional (don't know if pythonic) you can create dictionary with all your dataFrames and call this a simplier way:

```<code>dataFrames = {'position':position,
              'energy':energy,
              'number':number,
              'event':event,
              'height':height
             }

A = 'abc'
dir = '/HHD1'

for key,val in dataFrames.items():
    val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ")
</code>```

The last one liner is the same as:

```<code>[val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ") for key, val in dataFrames.items()]
</code>```

I think the first way is more pythonic, but not sure

Title: How to save a name as a variable when saving a Data frame file?

Body:
can use an f-string. Let

A = 'abc'

postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_number.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")

EDIT
Aditional (don't know if pythonic) you can create dictionary with all your dataFrames and call this a simplier way:

dataFrames = {'position':position,
              'energy':energy,
              'number':number,
              'event':event,
              'height':height
             }

A = 'abc'
dir = '/HHD1'

for key,val in dataFrames.items():
    val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ")

The last one liner is the same as:

[val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ") for key, val in dataFrames.items()]

I think the first way is more pythonic, but not sure


问:
Google visualization line chart missing Y axis
I am new to javascript and the Google Visualization library. I've created a line chart as below 1, but cannot get the Y Axis to display anything; I'm looking for the axis itself to be drawn, along with the values from the Data Table.

Here's my code (the chart labels are changed from the screenshot, but nothing more):

```<code>google.setOnLoadCallback(drawLineChart);
function drawLineChart(){var data=google.visualization.arrayToDataTable(
    [
        [
            'Day',
            'Label 1','Label 2','Label 3','Label 4','Label 5',
            'Label 6','Label 7','Label 8','Label 9','Label 10',
        ],
        ['19 Aug 2013',1,0,0,0,0,0],
        ['20 Aug 2013',2,2,2,0,0,0],
        ['21 Aug 2013',5,5,0,6,5,0],
        ['22 Aug 2013',1,4,3,2,0,0],
        ['23 Aug 2013',0,0,0,4,0,0],
        ['24 Aug 2013',3,2,1,2,0,15],
        ['25 Aug 2013',1,2,1,2,0,0],
        ['26 Aug 2013',3,1,2,1,0,0],
        ['27 Aug 2013',0,0,3,2,0,1]
    ]);

    var options = {
        title:'Title',
        legend:{position:'bottom'},
        curveType:'none',
        interpolateNulls:true,
        chartArea:{left:0,top:10,width:"100%"}
    };

    var chart=new google.visualization.LineChart(document.getElementById('visits_by_day1'));chart.draw(data,options);}
</code>```

Body:
I am new to javascript and the Google Visualization library. I've created a line chart as below 1, but cannot get the Y Axis to display anything; I'm looking for the axis itself to be drawn, along with the values from the Data Table.

Here's my code (the chart labels are changed from the screenshot, but nothing more):

google.setOnLoadCallback(drawLineChart);
function drawLineChart(){var data=google.visualization.arrayToDataTable(
    [
        [
            'Day',
            'Label 1','Label 2','Label 3','Label 4','Label 5',
            'Label 6','Label 7','Label 8','Label 9','Label 10',
        ],
        ['19 Aug 2013',1,0,0,0,0,0],
        ['20 Aug 2013',2,2,2,0,0,0],
        ['21 Aug 2013',5,5,0,6,5,0],
        ['22 Aug 2013',1,4,3,2,0,0],
        ['23 Aug 2013',0,0,0,4,0,0],
        ['24 Aug 2013',3,2,1,2,0,15],
        ['25 Aug 2013',1,2,1,2,0,0],
        ['26 Aug 2013',3,1,2,1,0,0],
        ['27 Aug 2013',0,0,3,2,0,1]
    ]);

    var options = {
        title:'Title',
        legend:{position:'bottom'},
        curveType:'none',
        interpolateNulls:true,
        chartArea:{left:0,top:10,width:"100%"}
    };

    var chart=new google.visualization.LineChart(document.getElementById('visits_by_day1'));chart.draw(data,options);}

Body:
I have similar issue. But, in my case, I am NOT using chartArea option at all. Hence, I doubt @asgallant's explanation is correct.

The following is my code:

<script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = new google.visualization.DataTable();
    // Declare columns
    data.addColumn('date', 'Date');
    data.addColumn('number', 'MM8');
    data.addColumn('number', 'S&P');

    data.addRows([[new Date('01/03/2017'),98517.96,100278.03],[new Date('01/10/2017'),99606.27,100769.69],[new Date('01/17/2017'),97409.55,100724.83],[new Date('01/24/2017'),101596.78,101265.78],[new Date('01/31/2017'),103283.59,101212.49],[new Date('02/07/2017'),106136.74,101843.6],[new Date('02/14/2017'),102568.42,103820.0],[new Date('02/21/2017'),102253.38,105054.7],[new Date('02/28/2017'),98587.77,104977.42],[new Date('03/07/2017'),97623.69,105188.38],[new Date('03/14/2017'),99571.71,105057.8],[new Date('03/21/2017'),98026.27,104106.02],[new Date('03/28/2017'),100641.93,104752.24],[new Date('04/04/2017'),98556.17,104822.86],[new Date('04/11/2017'),99200.09,104539.5],[new Date('04/18/2017'),98695.49,104024.75],[new Date('04/25/2017'),102622.71,106086.42],[new Date('05/02/2017'),100472.95,106200.12],[new Date('05/09/2017'),98574.4,106455.5],[new Date('05/16/2017'),106159.07,106622.05],[new Date('05/23/2017'),104296.55,106522.12],[new Date('05/30/2017'),105035.88,107165.67],[new Date('06/06/2017'),107811.48,107894.94],[new Date('06/13/2017'),110670.8,108384.37],[new Date('06/20/2017'),110152.66,108236.92],[new Date('06/27/2017'),109044.62,107453.02],[new Date('07/03/2017'),108633.82,107880.72],[new Date('07/11/2017'),111239.13,107726.16],[new Date('07/18/2017'),113238.32,109284.19],[new Date('07/25/2017'),114516.89,110017.9],[new Date('08/01/2017'),114235.76,109983.26],[new Date('08/08/2017'),118583.33,109919.74],[new Date('08/15/2017'),117029.48,109461.84],[new Date('08/22/2017'),115461.52,108924.44],[new Date('08/29/2017'),113553.88,108648.63],[new Date('09/05/2017'),112772.29,109161.61],[new Date('09/12/2017'),113241.54,110877.3],[new Date('09/19/2017'),116056.94,111328.98],[new Date('09/26/2017'),114991.2,110893.29],[new Date('10/03/2017'),119650.15,112569.45],[new Date('10/10/2017'),119326.16,113282.73],[new Date('10/17/2017'),124032.6,113670.02],[new Date('10/24/2017'),125599.48,114103.94],[new Date('10/31/2017'),126408.48,114376.19],[new Date('11/07/2017'),126213.65,115059.27],[new Date('11/14/2017'),128414.88,114536.52],[new Date('11/21/2017'),132050.66,115431.9],[new Date('11/28/2017'),133242.73,116675.92],[new Date('12/05/2017'),130042.14,116788.29],[new Date('12/12/2017'),130220.51,118322.33],[new Date('12/19/2017'),133182.72,119093.34],[new Date('12/26/2017'),133313.89,119050.26],[new Date('01/02/2018'),133892.53,119730.23]
    ]);

    var options = {
      title: 'Portfolio Performance Comparison',
      curveType: 'function',
      legend: { position: 'bottom' },
      hAxis: {
        format: 'M/d/yy'
        }
     };

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

    chart.draw(data, options);
  }
</script>

resulted graph


问:
How to remove temp tables from logic in stored procedure query
I need to improve the stored procedure sample code shown here to remove all temp tables, by using one query code or CTE maybe?

Note that it is necessary to create the first temp table to get specific users ID list, then create the second temp table with another specific criteria, then join with both temp tables created to get the final results table.

```<code>SELECT
    Column_1,
    Column_2,
    Column_3
INTO
    #TempTable_1
FROM
    TABLE_1
WHERE
    Column_1 = 1

SELECT
    Column_1,
    Column_4,
    Column_5,
    Column_6
INTO
    #TempTable_2
FROM
    TABLE_2
WHERE
    Column_4 = 4

SELECT
    A.Column_1,
    A.Column_2,
    A.Column_3,
    B.Column_4,
    B.Column_5,
    B.Column_6
FROM
    #TempTable_2 B
INNER JOIN
    #TempTable_1 A ON A.Column_1 = B.Column_1
</code>```

答:
In addition to Dale's sub-query, you can use a CTE</p>
```<code>with cte1 as (
SELECT
    Column_1,
    Column_2,
    Column_3
FROM TABLE_1
WHERE Column_1 = 1
),  cte2 as (
SELECT
    Column_1,
    Column_4,
    Column_5,
    Column_6
FROM TABLE_2
WHERE Column_4 = 4
)
SELECT
    A.Column_1,
    A.Column_2,
    A.Column_3,
    B.Column_4,
    B.Column_5,
    B.Column_6
FROM cte2 B
INNER JOIN cte1 A ON A.Column_1 = B.Column_1
</code>```

Body:
I need to improve the stored procedure sample code shown here to remove all temp tables, by using one query code or CTE maybe?

Note that it is necessary to create the first temp table to get specific users ID list, then create the second temp table with another specific criteria, then join with both temp tables created to get the final results table.

SELECT
    Column_1,
    Column_2,
    Column_3
INTO
    #TempTable_1
FROM
    TABLE_1
WHERE
    Column_1 = 1

SELECT
    Column_1,
    Column_4,
    Column_5,
    Column_6
INTO
    #TempTable_2
FROM
    TABLE_2
WHERE
    Column_4 = 4

SELECT
    A.Column_1,
    A.Column_2,
    A.Column_3,
    B.Column_4,
    B.Column_5,
    B.Column_6
FROM
    #TempTable_2 B
INNER JOIN
    #TempTable_1 A ON A.Column_1 = B.Column_1

Body:
In addition to Dale's sub-query, you can use a CTE

with cte1 as (
SELECT
    Column_1,
    Column_2,
    Column_3
FROM TABLE_1
WHERE Column_1 = 1
),  cte2 as (
SELECT
    Column_1,
    Column_4,
    Column_5,
    Column_6
FROM TABLE_2
WHERE Column_4 = 4
)
SELECT
    A.Column_1,
    A.Column_2,
    A.Column_3,
    B.Column_4,
    B.Column_5,
    B.Column_6
FROM cte2 B
INNER JOIN cte1 A ON A.Column_1 = B.Column_1


问:
Xamarin Forms WebView Navigated event not firing consistently on iOS
I have a Xamarin Forms ContentPage that has a WebView and an ActivityIndicator. I've wired up event handlers to to the WebView Navigating and Navigated events to activate and de-activate the ActivityIndicator. This all works great on Android. On iOS, the Navigating event fires multiple times as the page loads, but the Navigated event does not fire consistently with it. This often leaves the ActivityIndicator in a perpetually activated state. Has anyone found a fix or workaround that doesn't involve a custom WebView render or is a custom renderer the only way to go? If a custom renderer is required, does anyone have an example that works for this purpose?

Updated: Added the code here as requested.

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:FFXPubXam.ViewModels"
             x:Class="FFXPubXam.Views.WebPage"
             x:Name="root"
             Shell.NavBarIsVisible="false">
    <ContentPage.Content>
        <Grid>
            <WebView x:Name="WebViewControl"
             Source="{Binding Url}"
             Navigating="WebViewControl_Navigating"
             Navigated="WebViewControl_Navigated" />
            <ActivityIndicator x:Name="activity"
                               IsRunning="False"
                               IsEnabled="False"
                               IsVisible="False"
                               HeightRequest="40"
                               WidthRequest="100"
                               VerticalOptions="CenterAndExpand"
                               HorizontalOptions="CenterAndExpand"
                               Color="{DynamicResource FFX_Blue4}"
                               BackgroundColor="Transparent"/>
        </Grid>
    </ContentPage.Content>
</ContentPage>

using FFXPubXam.Helpers;
using FFXPubXam.ViewModels;
using System;
using Xamarin.Forms;

namespace FFXPubXam.Views
{
    public partial class WebPage : ContentPage
    {
        public WebPage(string arg)
        {
            InitializeComponent();
            BindingContext = new WebPageViewModel(arg);
        }

        protected override void OnAppearing()
        {
            ToggleActivityIndicator(true);

            base.OnAppearing();
        }

        private void WebViewControl_Navigating(object sender, WebNavigatingEventArgs e)
        {
            ToggleActivityIndicator(true);
        }

        private void WebViewControl_Navigated(object sender, WebNavigatedEventArgs e)
        {
            ToggleActivityIndicator(false);
        }

        private void ToggleActivityIndicator(bool state)
        {
            activity.IsRunning = state;
            activity.IsEnabled = state;
            activity.IsVisible = state;
        }
    }
}
</code>```

答:
I've found that the target attribute of HTML links displayed in Xamarin WebViews can stop the Navigating event from firing if set to _blank. A simple if hacky fix is just to remove them in code like this:

```<code>var htmlSource = new HtmlWebViewSource();
// remove target="_blank" to make Navigating event fire:
htmlSource.Html = htmlString.Replace("target=\"_blank\"", "").Replace("target='_blank'", "");

webView.Source = htmlSource;
</code>```

Or else you could remove them from your HTML source.

Body:
I have a Xamarin Forms ContentPage that has a WebView and an ActivityIndicator. I've wired up event handlers to to the WebView Navigating and Navigated events to activate and de-activate the ActivityIndicator. This all works great on Android. On iOS, the Navigating event fires multiple times as the page loads, but the Navigated event does not fire consistently with it. This often leaves the ActivityIndicator in a perpetually activated state. Has anyone found a fix or workaround that doesn't involve a custom WebView render or is a custom renderer the only way to go? If a custom renderer is required, does anyone have an example that works for this purpose?

Updated: Added the code here as requested.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:FFXPubXam.ViewModels"
             x:Class="FFXPubXam.Views.WebPage"
             x:Name="root"
             Shell.NavBarIsVisible="false">
    <ContentPage.Content>
        <Grid>
            <WebView x:Name="WebViewControl"
             Source="{Binding Url}"
             Navigating="WebViewControl_Navigating"
             Navigated="WebViewControl_Navigated" />
            <ActivityIndicator x:Name="activity"
                               IsRunning="False"
                               IsEnabled="False"
                               IsVisible="False"
                               HeightRequest="40"
                               WidthRequest="100"
                               VerticalOptions="CenterAndExpand"
                               HorizontalOptions="CenterAndExpand"
                               Color="{DynamicResource FFX_Blue4}"
                               BackgroundColor="Transparent"/>
        </Grid>
    </ContentPage.Content>
</ContentPage>

using FFXPubXam.Helpers;
using FFXPubXam.ViewModels;
using System;
using Xamarin.Forms;

namespace FFXPubXam.Views
{
    public partial class WebPage : ContentPage
    {
        public WebPage(string arg)
        {
            InitializeComponent();
            BindingContext = new WebPageViewModel(arg);
        }

        protected override void OnAppearing()
        {
            ToggleActivityIndicator(true);

            base.OnAppearing();
        }

        private void WebViewControl_Navigating(object sender, WebNavigatingEventArgs e)
        {
            ToggleActivityIndicator(true);
        }

        private void WebViewControl_Navigated(object sender, WebNavigatedEventArgs e)
        {
            ToggleActivityIndicator(false);
        }

        private void ToggleActivityIndicator(bool state)
        {
            activity.IsRunning = state;
            activity.IsEnabled = state;
            activity.IsVisible = state;
        }
    }
}

Body:
I've found that the target attribute of HTML links displayed in Xamarin WebViews can stop the Navigating event from firing if set to _blank. A simple if hacky fix is just to remove them in code like this:

var htmlSource = new HtmlWebViewSource();
// remove target="_blank" to make Navigating event fire:
htmlSource.Html = htmlString.Replace("target=\"_blank\"", "").Replace("target='_blank'", "");

webView.Source = htmlSource;

Or else you could remove them from your HTML source.


问:
I cannot change font-color in TextField component from Material UI
I cannot change font-color in TextField Material UI component. I try to do it using createTheme() and when I add class '& .MuiOutlinedInput-input' in code sandbox font-color changes as it should, but when I apply it to the app code it doesn't work.
Will appreciate Your support.
Below is the implementation:

```<code>const theme = createTheme({
components: {
    MuiOutlinedInput: {
        styleOverrides: {
            root: {
                backgroundColor: `#EDEDED`,
                '& .MuiOutlinedInput-notchedOutline': {
                    border: 'none',
                },
                '&.Mui-focused': {
                    '& .MuiOutlinedInput-notchedOutline': {
                        border: 'none',
                    },
                },
                '& .MuiOutlinedInput-input': {
                    padding: '10px',
                    fontSize: '13px',
                    color: 'red',
                },
            },
        },
    },
},
</code>```

});

```<code><ThemeProvider theme={theme}>
                            <InputForm
                                name={'phoneNumber'}
                                id={'phoneNumber'}
                                label={phoneNumberLabelTxt}
                                disabled={isDisabledInputs}
                            />
                        </ThemeProvider>
</code>```

答:
Your code worked in my local repo. however if its not working for you then try below code which also worked for me.</p>
```<code>'&.MuiOutlinedInput-root': { // no space between & and .
    padding: '10px',
    fontSize: '13px',
    color: 'red',
},
</code>```

Body:
I cannot change font-color in TextField Material UI component. I try to do it using createTheme() and when I add class '& .MuiOutlinedInput-input' in code sandbox font-color changes as it should, but when I apply it to the app code it doesn't work.
Will appreciate Your support.
Below is the implementation:

const theme = createTheme({
components: {
    MuiOutlinedInput: {
        styleOverrides: {
            root: {
                backgroundColor: `#EDEDED`,
                '& .MuiOutlinedInput-notchedOutline': {
                    border: 'none',
                },
                '&.Mui-focused': {
                    '& .MuiOutlinedInput-notchedOutline': {
                        border: 'none',
                    },
                },
                '& .MuiOutlinedInput-input': {
                    padding: '10px',
                    fontSize: '13px',
                    color: 'red',
                },
            },
        },
    },
},

});

<ThemeProvider theme={theme}>
                            <InputForm
                                name={'phoneNumber'}
                                id={'phoneNumber'}
                                label={phoneNumberLabelTxt}
                                disabled={isDisabledInputs}
                            />
                        </ThemeProvider>

Body:
Your code worked in my local repo. however if its not working for you then try below code which also worked for me.

'&.MuiOutlinedInput-root': { // no space between & and .
    padding: '10px',
    fontSize: '13px',
    color: 'red',
},


问:
SQL Server row_number function how to remove dups based on each date within a range
I have a query that will have duplicate entries. It looks for all event messages (text) within the month. The same message can exist from a provider for a patient within a single day and I want to remove those. I do not want to remove any messages that could be identical but happened on a different day. Is that possible?

答:
Thanks Mattias W. This seems to work. Adding the extra row_number parameters and converting the date with an order by on ptnbr_name seemed to help.
Also, the group by in or commented seemed to have no change to the number of records so that was good to know. Appreciate it. :)
select * from (
select distinct PtNbr_name
,row_number() over(partition by
event_message,provider,convert(varchar(8),date/time,112) order by PtNbr_name) rn
from table ) x
where x.rn = 1</p>


问:
Deploying multiple stored procedures to Cosmos using Bicep
I'm deploying Cosmos via bicep templates.  Mostly everything is parameterised.  We have found a way to deploy multiple stored procedures described below.

Define an array in the bicep

```<code>param storedProcedureData array = []
</code>```

then in the resource section loop around the data:

```<code>resource cosmosStoredProcedures 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/storedProcedures@2021-06-15' = [for storedProcedure in storedProcedureData: {
  parent: cosmosSQLContainers
  name: storedProcedure.name
  properties: {
    resource: {
      id: storedProcedure.name
      body: storedProcedure.body
    }
  }
}]
</code>```

I have a json file with the stored procedure code in like this:

```<code>[
  {
    "name": "sp1",
    "body": "function sp1 etc"
  },
  {
    "name": "sp2",
    "body": "function sp2 etc"
  }
]
</code>```

and call it like this from powershell using az commands:

```<code>az deployment group create --resource-group rgname `
--name testdeployment `
--template-file "C:\GitHub\bicep\cosmosdb\main.bicep" `
--parameters "C:\GitHub\bicep\cosmosdb\cosmosMain.parameters.json" `
--parameters storedProcedureData=$storedProcedureData
</code>```

where the stored procedure data is a variable:

```<code>$storedProcedureData=(Get-Content "C:\GitHub\bicep\cosmosdb\storedproc.json")
</code>```

Question is - is there a better way!!! And what if I have multiple containers ...

答:
I suggest that you make of Bicep's modules to accommodate your looping concerns, as Bicep can't itself loop over a nested loop, but can call a module within a loop that itself does other work within a loop.

As such, might I suggest something like the following:

```<code>// cosmos-CreateStoredProcedure.bicep

@description('The stored procedures to register')
// {name: '<name>', body: '<body>'}
param StoredProcedureData array

@description('The name of the Cosmos account')
param CosmosAccountName string

@description('The name of the Cosmos SQL container')
param CosmosContainerName string

resource CosmosContainer 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2021-10-15' existing = {
  name: '${CosmosAccountName}/${CosmosContainerName}'
}

resource StoredProcs 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/storedProcedures@2021-06-15' = [for sp in StoredProcedureData: {
  parent: CosmosContainer
  name: sp.name
  properties: {
    resource: {
      id: sp.name
      body: sp.body
    }
  }
}]
</code>```

Now you've got a modularized Bicep file to which you can pass any number of stored procedures and it'll run on any Cosmos account and container you want.

So now this means that you've got an outer module that'll actually run against each of the sets of containers you want to deploy to. If you want to use an external file, create another file that maps everything out in the same manner.   Create an array in Powershell and push in an object of both the containerName value and the JSON value for each of the file paths you want to read in, then pass this array to set the StoredProcedures value in the template below.

This loops through each set of stored procedure objects in the array to call the inner module, then the inner module loops through the stored procs to actually store.

```<code>// cosmos-registerAllStoredProcedures.bicep

@description('The name of the Cosmos account')
param CosmosAccountName string

param StoredProcedures array = [
{
  containerName: 'containerA'
  storedProcecures: [
    'procedureAText'
    'procedureBText'
    'procedureCText'
  ]
}
{
  containerName: 'containerB'
  filePaths: [
    'procedureAText'
  ]
}
]

module DeployStoredProcedures './cosmos-CreateStoredProcedure.bicep' = [for (set, i) in StoredProcedures: {
  name: 'storedProcedures-${set.containerName}-${i}' //Might need to include the `i` value so the build knows this will yield a unique name
  params: {
    CosmosAccountName: CosmosAccountName
    CosmosContainerName: set.containerName
    StoredProcedureData: set.filePaths
  }
}]

</code>```

Body:
I'm deploying Cosmos via bicep templates.  Mostly everything is parameterised.  We have found a way to deploy multiple stored procedures described below.

Define an array in the bicep

param storedProcedureData array = []

then in the resource section loop around the data:

resource cosmosStoredProcedures 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/storedProcedures@2021-06-15' = [for storedProcedure in storedProcedureData: {
  parent: cosmosSQLContainers
  name: storedProcedure.name
  properties: {
    resource: {
      id: storedProcedure.name
      body: storedProcedure.body
    }
  }
}]

I have a json file with the stored procedure code in like this:

[
  {
    "name": "sp1",
    "body": "function sp1 etc"
  },
  {
    "name": "sp2",
    "body": "function sp2 etc"
  }
]

and call it like this from powershell using az commands:

az deployment group create --resource-group rgname `
--name testdeployment `
--template-file "C:\GitHub\bicep\cosmosdb\main.bicep" `
--parameters "C:\GitHub\bicep\cosmosdb\cosmosMain.parameters.json" `
--parameters storedProcedureData=$storedProcedureData

where the stored procedure data is a variable:

$storedProcedureData=(Get-Content "C:\GitHub\bicep\cosmosdb\storedproc.json")

Question is - is there a better way!!! And what if I have multiple containers ...

Body:
I suggest that you make of Bicep's modules to accommodate your looping concerns, as Bicep can't itself loop over a nested loop, but can call a module within a loop that itself does other work within a loop.

As such, might I suggest something like the following:

// cosmos-CreateStoredProcedure.bicep

@description('The stored procedures to register')
// {name: '<name>', body: '<body>'}
param StoredProcedureData array

@description('The name of the Cosmos account')
param CosmosAccountName string

@description('The name of the Cosmos SQL container')
param CosmosContainerName string

resource CosmosContainer 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2021-10-15' existing = {
  name: '${CosmosAccountName}/${CosmosContainerName}'
}

resource StoredProcs 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/storedProcedures@2021-06-15' = [for sp in StoredProcedureData: {
  parent: CosmosContainer
  name: sp.name
  properties: {
    resource: {
      id: sp.name
      body: sp.body
    }
  }
}]

Now you've got a modularized Bicep file to which you can pass any number of stored procedures and it'll run on any Cosmos account and container you want.

So now this means that you've got an outer module that'll actually run against each of the sets of containers you want to deploy to. If you want to use an external file, create another file that maps everything out in the same manner.   Create an array in Powershell and push in an object of both the containerName value and the JSON value for each of the file paths you want to read in, then pass this array to set the StoredProcedures value in the template below.

This loops through each set of stored procedure objects in the array to call the inner module, then the inner module loops through the stored procs to actually store.

// cosmos-registerAllStoredProcedures.bicep

@description('The name of the Cosmos account')
param CosmosAccountName string

param StoredProcedures array = [
{
  containerName: 'containerA'
  storedProcecures: [
    'procedureAText'
    'procedureBText'
    'procedureCText'
  ]
}
{
  containerName: 'containerB'
  filePaths: [
    'procedureAText'
  ]
}
]

module DeployStoredProcedures './cosmos-CreateStoredProcedure.bicep' = [for (set, i) in StoredProcedures: {
  name: 'storedProcedures-${set.containerName}-${i}' //Might need to include the `i` value so the build knows this will yield a unique name
  params: {
    CosmosAccountName: CosmosAccountName
    CosmosContainerName: set.containerName
    StoredProcedureData: set.filePaths
  }
}]


问:
Using PowerShell to send space character to desktop - to wake screen from sleep
I know the following 2 line PowerShell script sends a space character to a new "shell" object it creates.
Which does bring my sleeping screen out of its slumber.
But that opens, momentarily, a PowerShell window.  So, if the screen is truly asleep-not a problem.

But, there are times of the day when this will run when the screen isn't in a sleeping slumber.  Hence, when that happens, the user sees a very short annoying flash of the created Wscript.Shell

I'd like to just send the space keystroke to the desktop - to wake the sleeping screen.  Without the momentary opening and closing of the Wscript.Shell
i.e., send the " " character to "the desktop" and not to a new shell object.
Is this possible?
I know nothing (obviously) about writing PowerShell.

```<code>$myshell=New-Object -com "Wscript.Shell"
$myshell.sendkeys(" ")
</code>```

Perhaps there is a way the PowerShell script could know if the screen and/or computer is not in a sleep state, and therefore this could all just be avoided from running in that situation?
Any help is much appreciated.

答: It's being setup with a Powershell script to create a Task in task scheduler. That task then calls the 2 line PowerShell script to send the " " key, to wake the computer up just prior to the day's activity.</p>

Body:
I know the following 2 line PowerShell script sends a space character to a new "shell" object it creates.
Which does bring my sleeping screen out of its slumber.
But that opens, momentarily, a PowerShell window.  So, if the screen is truly asleep-not a problem.

But, there are times of the day when this will run when the screen isn't in a sleeping slumber.  Hence, when that happens, the user sees a very short annoying flash of the created Wscript.Shell

I'd like to just send the space keystroke to the desktop - to wake the sleeping screen.  Without the momentary opening and closing of the Wscript.Shell
i.e., send the " " character to "the desktop" and not to a new shell object.
Is this possible?
I know nothing (obviously) about writing PowerShell.

$myshell=New-Object -com "Wscript.Shell"
$myshell.sendkeys(" ")

Perhaps there is a way the PowerShell script could know if the screen and/or computer is not in a sleep state, and therefore this could all just be avoided from running in that situation?
Any help is much appreciated.


问:
Show Offscreen Object / Target Indicator in Reality Kit
I would like to have an indicator to let users know there is an AR object off screen (as suggested in the Human Interface Guidelines). How would I do this in RealityKit?</p>

答: You can use edge of the screen and add some icons(using swiftui or uikit) to let the user know that by orienting the device to that direction they will find a object.</p>


问:
How to select all inside node tag in XML via SQL
Required Output - Green mark data i want in my sql dataset

Can anyone help me please?

I would like to select all the nodes in xml and get its Key-Value and Value in my dataset.

I have tried but I can only get specific tag result.

I have numeric-entity, list-entity and string-entity in my xml and I want to get values from each tag.

So far I can get only one entity value but I don't know how I can write OR condition or something in query to get result from all the xmls tag.

This is my xml and the query I have written:

```<code>--Query
WITH XMLNAMESPACES(DEFAULT 'urn:guru.cincom.com-Hierarchy')
SELECT t.ID

      ,T0.Color.value('@name','nvarchar(max)') AS EntityName
      ,T0.Color.value('(key-value/text())[1]','nvarchar(max)') AS EntityValue
FROM ConfigurationDnaItem t
CROSS APPLY (SELECT CAST(t.Value AS XML)) As A(AllNodes)
CROSS APPLY A.AllNodes.nodes('/hierarchy/nodes/numeric-entity[not(values/value/key-value[text() = "N/A" or text() = "NA" or text() = "Nil"])]') AS T0(Color)
where t.id = 'BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67';
</code>```

Xml

enter image description here

```<code><?xml version="1.0" encoding="utf-16"?>
<hierarchy name="DGTrailerDimensionH" xmlns="urn:guru.cincom.com-Hierarchy">
  <nodes>
    <numeric-entity name="UnitLength">
      <key-value>14500</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[14500]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Overall Length]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <list-entity name="UnitHeightList">
      <values>
        <value>
          <key-value><![CDATA[4300]]></key-value>
          <characteristics>
            <characteristic name="Value" type="list"><![CDATA[4300]]></characteristic>
            <characteristic name="Description" type="string"><![CDATA[4300]]></characteristic>
            <characteristic name="DGName" type="string"><![CDATA[Overall Height]]></characteristic>
          </characteristics>
        </value>
      </values>
      <extended-properties />
    </list-entity>
    <numeric-entity name="CoamingHeight">
      <key-value>25</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[25]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Coaming Height above main]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <list-entity name="TurntableHeightList">
      <values>
        <value>
          <key-value><![CDATA[1270]]></key-value>
          <characteristics>
            <characteristic name="Value" type="list"><![CDATA[1270]]></characteristic>
            <characteristic name="Description" type="string"><![CDATA[1270]]></characteristic>
            <characteristic name="DGName" type="string"><![CDATA[Skidplate Height]]></characteristic>
          </characteristics>
        </value>
      </values>
      <extended-properties />
    </list-entity>
    <numeric-entity name="ApertureHeight">
      <key-value>2725</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[2725]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Aperture Height]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="ApertureLength">
      <key-value>14200</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[14200]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Aperture Length]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="FifthWheelLocationNum">
      <key-value>0</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Turntable Location]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="SuspensionLocation">
      <key-value>9350</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[9350]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Suspension Location]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="SuspensionSpreadNum">
      <key-value>2700</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[2700]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Suspension spread]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <string-entity name="KingPinLocationStr">
      <key-value><![CDATA[1550]]></key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[1550]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[King Pin Position]]></characteristic>
      </characteristics>
      <extended-properties />
    </string-entity>
    <numeric-entity name="RearApertureHeight">
      <key-value>0</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Rear Aperture Height]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="DropDeckHeightNum">
      <key-value>0</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Drop Deck Height]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
  </nodes>
</hierarchy>

  [1]: Out required - Green mark i want in data set.
</code>```

答:
Please try the following solution. It is following the same minimal reproducible example paradigm. You copy it to SSMS as-is, run it, and it is working.

Though I don't understand the XPath expression predicate:

```<code>[not(values/value/key-value[text() = ("N/A","NA","Nil")])]
</code>```

Please clarify what you are trying to filter out.

SQL

```<code>-- DDL and sample data population, start
DECLARE @tbl TABLE (ID UNIQUEIDENTIFIER PRIMARY KEY, [value] NVARCHAR(MAX));
INSERT INTO @tbl (ID, value) VALUES
('BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67'
, N'<?xml version="1.0" encoding="utf-16"?>
<hierarchy name="DGTrailerDimensionH" xmlns="urn:guru.cincom.com-Hierarchy">
    <nodes>
        <numeric-entity name="UnitLength">
            <key-value>14500</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[14500]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Overall Length]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <list-entity name="UnitHeightList">
            <values>
                <value>
                    <key-value><![CDATA[4300]]></key-value>
                    <characteristics>
                        <characteristic name="Value" type="list"><![CDATA[4300]]></characteristic>
                        <characteristic name="Description" type="string"><![CDATA[4300]]></characteristic>
                        <characteristic name="DGName" type="string"><![CDATA[Overall Height]]></characteristic>
                    </characteristics>
                </value>
            </values>
            <extended-properties/>
        </list-entity>
        <numeric-entity name="CoamingHeight">
            <key-value>25</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[25]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Coaming Height above main]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <list-entity name="TurntableHeightList">
            <values>
                <value>
                    <key-value><![CDATA[1270]]></key-value>
                    <characteristics>
                        <characteristic name="Value" type="list"><![CDATA[1270]]></characteristic>
                        <characteristic name="Description" type="string"><![CDATA[1270]]></characteristic>
                        <characteristic name="DGName" type="string"><![CDATA[Skidplate Height]]></characteristic>
                    </characteristics>
                </value>
            </values>
            <extended-properties/>
        </list-entity>
        <numeric-entity name="ApertureHeight">
            <key-value>2725</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[2725]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Aperture Height]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="ApertureLength">
            <key-value>14200</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[14200]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Aperture Length]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="FifthWheelLocationNum">
            <key-value>0</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Turntable Location]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="SuspensionLocation">
            <key-value>9350</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[9350]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Suspension Location]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="SuspensionSpreadNum">
            <key-value>2700</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[2700]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Suspension spread]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <string-entity name="KingPinLocationStr">
            <key-value><![CDATA[1550]]></key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[1550]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[King Pin Position]]></characteristic>
            </characteristics>
            <extended-properties/>
        </string-entity>
        <numeric-entity name="RearApertureHeight">
            <key-value>0</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Rear Aperture Height]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="DropDeckHeightNum">
            <key-value>0</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Drop Deck Height]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
    </nodes>
</hierarchy>');
-- DDL and sample data population, end

WITH XMLNAMESPACES(DEFAULT 'urn:guru.cincom.com-Hierarchy')
SELECT t.ID
    , p.value('@name','nvarchar(max)') AS EntityName
    , p.value('(.//key-value/text())[1]','nvarchar(max)') AS EntityValue
    , c.value('(characteristic[@name="Value"]/text())[1]','nvarchar(max)') AS char_Value
    , c.value('(characteristic[@name="DGName"]/text())[1]','nvarchar(max)') AS char_GName
    , c.value('(characteristic[@name="Description"]/text())[1]','nvarchar(max)') AS char_desc
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST(t.Value AS XML)) AS A(AllNodes)
CROSS APPLY A.AllNodes.nodes('/hierarchy/nodes/*[not(values/value/key-value[text() = ("N/A","NA","Nil")])]') AS t0(p)
CROSS APPLY t0.p.nodes('.//characteristics') AS t1(c)
WHERE t.id = 'BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67';
</code>```

Output

```<code>+--------------------------------------+-----------------------+-------------+------------+---------------------------+-----------+
|                  ID                  |      EntityName       | EntityValue | char_Value |        char_GName         | char_desc |
+--------------------------------------+-----------------------+-------------+------------+---------------------------+-----------+
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | UnitLength            |       14500 |      14500 | Overall Length            | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | UnitHeightList        |        4300 |       4300 | Overall Height            | 4300      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | CoamingHeight         |          25 |         25 | Coaming Height above main | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | TurntableHeightList   |        1270 |       1270 | Skidplate Height          | 1270      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | ApertureHeight        |        2725 |       2725 | Aperture Height           | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | ApertureLength        |       14200 |      14200 | Aperture Length           | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | FifthWheelLocationNum |           0 |          0 | Turntable Location        | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | SuspensionLocation    |        9350 |       9350 | Suspension Location       | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | SuspensionSpreadNum   |        2700 |       2700 | Suspension spread         | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | KingPinLocationStr    |        1550 |       1550 | King Pin Position         | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | RearApertureHeight    |           0 |          0 | Rear Aperture Height      | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | DropDeckHeightNum     |           0 |          0 | Drop Deck Height          | NULL      |
+--------------------------------------+-----------------------+-------------+------------+---------------------------+-----------+
</code>```

Body:
Required Output - Green mark data i want in my sql dataset

Can anyone help me please?

I would like to select all the nodes in xml and get its Key-Value and Value in my dataset.

I have tried but I can only get specific tag result.

I have numeric-entity, list-entity and string-entity in my xml and I want to get values from each tag.

So far I can get only one entity value but I don't know how I can write OR condition or something in query to get result from all the xmls tag.

This is my xml and the query I have written:

--Query
WITH XMLNAMESPACES(DEFAULT 'urn:guru.cincom.com-Hierarchy')
SELECT t.ID

      ,T0.Color.value('@name','nvarchar(max)') AS EntityName
      ,T0.Color.value('(key-value/text())[1]','nvarchar(max)') AS EntityValue
FROM ConfigurationDnaItem t
CROSS APPLY (SELECT CAST(t.Value AS XML)) As A(AllNodes)
CROSS APPLY A.AllNodes.nodes('/hierarchy/nodes/numeric-entity[not(values/value/key-value[text() = "N/A" or text() = "NA" or text() = "Nil"])]') AS T0(Color)
where t.id = 'BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67';

Xml

enter image description here

<?xml version="1.0" encoding="utf-16"?>
<hierarchy name="DGTrailerDimensionH" xmlns="urn:guru.cincom.com-Hierarchy">
  <nodes>
    <numeric-entity name="UnitLength">
      <key-value>14500</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[14500]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Overall Length]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <list-entity name="UnitHeightList">
      <values>
        <value>
          <key-value><![CDATA[4300]]></key-value>
          <characteristics>
            <characteristic name="Value" type="list"><![CDATA[4300]]></characteristic>
            <characteristic name="Description" type="string"><![CDATA[4300]]></characteristic>
            <characteristic name="DGName" type="string"><![CDATA[Overall Height]]></characteristic>
          </characteristics>
        </value>
      </values>
      <extended-properties />
    </list-entity>
    <numeric-entity name="CoamingHeight">
      <key-value>25</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[25]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Coaming Height above main]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <list-entity name="TurntableHeightList">
      <values>
        <value>
          <key-value><![CDATA[1270]]></key-value>
          <characteristics>
            <characteristic name="Value" type="list"><![CDATA[1270]]></characteristic>
            <characteristic name="Description" type="string"><![CDATA[1270]]></characteristic>
            <characteristic name="DGName" type="string"><![CDATA[Skidplate Height]]></characteristic>
          </characteristics>
        </value>
      </values>
      <extended-properties />
    </list-entity>
    <numeric-entity name="ApertureHeight">
      <key-value>2725</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[2725]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Aperture Height]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="ApertureLength">
      <key-value>14200</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[14200]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Aperture Length]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="FifthWheelLocationNum">
      <key-value>0</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Turntable Location]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="SuspensionLocation">
      <key-value>9350</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[9350]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Suspension Location]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="SuspensionSpreadNum">
      <key-value>2700</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[2700]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Suspension spread]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <string-entity name="KingPinLocationStr">
      <key-value><![CDATA[1550]]></key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[1550]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[King Pin Position]]></characteristic>
      </characteristics>
      <extended-properties />
    </string-entity>
    <numeric-entity name="RearApertureHeight">
      <key-value>0</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Rear Aperture Height]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
    <numeric-entity name="DropDeckHeightNum">
      <key-value>0</key-value>
      <characteristics>
        <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
        <characteristic name="DGName" type="string"><![CDATA[Drop Deck Height]]></characteristic>
      </characteristics>
      <extended-properties />
    </numeric-entity>
  </nodes>
</hierarchy>

  [1]: Out required - Green mark i want in data set.

Body:
Please try the following solution. It is following the same minimal reproducible example paradigm. You copy it to SSMS as-is, run it, and it is working.

Though I don't understand the XPath expression predicate:

[not(values/value/key-value[text() = ("N/A","NA","Nil")])]

Please clarify what you are trying to filter out.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID UNIQUEIDENTIFIER PRIMARY KEY, [value] NVARCHAR(MAX));
INSERT INTO @tbl (ID, value) VALUES
('BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67'
, N'<?xml version="1.0" encoding="utf-16"?>
<hierarchy name="DGTrailerDimensionH" xmlns="urn:guru.cincom.com-Hierarchy">
    <nodes>
        <numeric-entity name="UnitLength">
            <key-value>14500</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[14500]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Overall Length]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <list-entity name="UnitHeightList">
            <values>
                <value>
                    <key-value><![CDATA[4300]]></key-value>
                    <characteristics>
                        <characteristic name="Value" type="list"><![CDATA[4300]]></characteristic>
                        <characteristic name="Description" type="string"><![CDATA[4300]]></characteristic>
                        <characteristic name="DGName" type="string"><![CDATA[Overall Height]]></characteristic>
                    </characteristics>
                </value>
            </values>
            <extended-properties/>
        </list-entity>
        <numeric-entity name="CoamingHeight">
            <key-value>25</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[25]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Coaming Height above main]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <list-entity name="TurntableHeightList">
            <values>
                <value>
                    <key-value><![CDATA[1270]]></key-value>
                    <characteristics>
                        <characteristic name="Value" type="list"><![CDATA[1270]]></characteristic>
                        <characteristic name="Description" type="string"><![CDATA[1270]]></characteristic>
                        <characteristic name="DGName" type="string"><![CDATA[Skidplate Height]]></characteristic>
                    </characteristics>
                </value>
            </values>
            <extended-properties/>
        </list-entity>
        <numeric-entity name="ApertureHeight">
            <key-value>2725</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[2725]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Aperture Height]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="ApertureLength">
            <key-value>14200</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[14200]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Aperture Length]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="FifthWheelLocationNum">
            <key-value>0</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Turntable Location]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="SuspensionLocation">
            <key-value>9350</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[9350]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Suspension Location]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="SuspensionSpreadNum">
            <key-value>2700</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[2700]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Suspension spread]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <string-entity name="KingPinLocationStr">
            <key-value><![CDATA[1550]]></key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[1550]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[King Pin Position]]></characteristic>
            </characteristics>
            <extended-properties/>
        </string-entity>
        <numeric-entity name="RearApertureHeight">
            <key-value>0</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Rear Aperture Height]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
        <numeric-entity name="DropDeckHeightNum">
            <key-value>0</key-value>
            <characteristics>
                <characteristic name="Value" type="list"><![CDATA[0]]></characteristic>
                <characteristic name="DGName" type="string"><![CDATA[Drop Deck Height]]></characteristic>
            </characteristics>
            <extended-properties/>
        </numeric-entity>
    </nodes>
</hierarchy>');
-- DDL and sample data population, end

WITH XMLNAMESPACES(DEFAULT 'urn:guru.cincom.com-Hierarchy')
SELECT t.ID
    , p.value('@name','nvarchar(max)') AS EntityName
    , p.value('(.//key-value/text())[1]','nvarchar(max)') AS EntityValue
    , c.value('(characteristic[@name="Value"]/text())[1]','nvarchar(max)') AS char_Value
    , c.value('(characteristic[@name="DGName"]/text())[1]','nvarchar(max)') AS char_GName
    , c.value('(characteristic[@name="Description"]/text())[1]','nvarchar(max)') AS char_desc
FROM @tbl AS t
CROSS APPLY (SELECT TRY_CAST(t.Value AS XML)) AS A(AllNodes)
CROSS APPLY A.AllNodes.nodes('/hierarchy/nodes/*[not(values/value/key-value[text() = ("N/A","NA","Nil")])]') AS t0(p)
CROSS APPLY t0.p.nodes('.//characteristics') AS t1(c)
WHERE t.id = 'BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67';

Output

+--------------------------------------+-----------------------+-------------+------------+---------------------------+-----------+
|                  ID                  |      EntityName       | EntityValue | char_Value |        char_GName         | char_desc |
+--------------------------------------+-----------------------+-------------+------------+---------------------------+-----------+
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | UnitLength            |       14500 |      14500 | Overall Length            | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | UnitHeightList        |        4300 |       4300 | Overall Height            | 4300      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | CoamingHeight         |          25 |         25 | Coaming Height above main | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | TurntableHeightList   |        1270 |       1270 | Skidplate Height          | 1270      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | ApertureHeight        |        2725 |       2725 | Aperture Height           | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | ApertureLength        |       14200 |      14200 | Aperture Length           | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | FifthWheelLocationNum |           0 |          0 | Turntable Location        | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | SuspensionLocation    |        9350 |       9350 | Suspension Location       | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | SuspensionSpreadNum   |        2700 |       2700 | Suspension spread         | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | KingPinLocationStr    |        1550 |       1550 | King Pin Position         | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | RearApertureHeight    |           0 |          0 | Rear Aperture Height      | NULL      |
| BA84B6C7-B6F7-4FC9-9DD8-8C9022513A67 | DropDeckHeightNum     |           0 |          0 | Drop Deck Height          | NULL      |
+--------------------------------------+-----------------------+-------------+------------+---------------------------+-----------+


问:
Anonymous type in medium trust, works with Reflection not with Expressions
I'm doing custom projections on Linq queries in Medium Trust and I get a MethodAccessException or TypeAccessException complaining about reflection and security rights.

I've simplified the code to the following:

```<code>var anon1 = new { Name = "Bill Gates" };
var ctor = anon1.GetType().GetConstructors().First();

// With native Reflection it works
var anon2 = ctor.Invoke(new object[] { "Steve Ballmer" });

var expr = Expression.New(ctor, Expression.Constant("Scott Guthrie"));
var lamb = Expression.Lambda(expr);      // This throws in Medium Trust

var anon3 = lamb.Compile().DynamicInvoke();

anon1.ToString();        // --> { Name = Bill Gates }
anon2.ToString();        // --> { Name = Steve Ballmer }
anon3.ToString();        // --> { Name = Scott Guthrie }
</code>```

In Full Trust, anon2 and anon3 will be created. In Medium Trust only anon2 will be created.

Another similar situation did not solve the issue

答:
This is caused because anonymous types are created as internal by the compiler.  That means code outside of your assembly won't be able to access the types.  When you do the reflection yourself, all the calls are coming from your assembly so it is allowed.  But when you introduce expressions, the calls start coming from framework DLLs and so they get stopped.

An easy way to solve problems of this nature is with the InternalsVisibleTo attribute.  By just adding this:

```<code>[assembly: InternalsVisibleTo("System.Core")]
</code>```

you'll be able to create the lambda.  However, when you go to compile it, you get a similar permission exception.  In that case, the Compile method ends up triggering some code in mscorlib.dll to try to access your type.  I tried adding:

```<code>[assembly: InternalsVisibleTo("mscorlib")]
</code>```

but that didn't seem to work.  I think it might have to do with the fact that mscorlib is strongly signed.  According to the documentation of InternalsVisislbeTo:

Both the current assembly and the friend assembly must be unsigned, or
  both must be signed with a strong name.

Perhaps if your code was signed, it would work.  Or perhaps you don't even need the call to Compile() - maybe that was just for testing?  Adding the reference to System.Core is worth a try.

Body:
I'm doing custom projections on Linq queries in Medium Trust and I get a MethodAccessException or TypeAccessException complaining about reflection and security rights.

I've simplified the code to the following:

var anon1 = new { Name = "Bill Gates" };
var ctor = anon1.GetType().GetConstructors().First();

// With native Reflection it works
var anon2 = ctor.Invoke(new object[] { "Steve Ballmer" });

var expr = Expression.New(ctor, Expression.Constant("Scott Guthrie"));
var lamb = Expression.Lambda(expr);      // This throws in Medium Trust

var anon3 = lamb.Compile().DynamicInvoke();

anon1.ToString();        // --> { Name = Bill Gates }
anon2.ToString();        // --> { Name = Steve Ballmer }
anon3.ToString();        // --> { Name = Scott Guthrie }

In Full Trust, anon2 and anon3 will be created. In Medium Trust only anon2 will be created.

Another similar situation did not solve the issue

Body:
This is caused because anonymous types are created as internal by the compiler.  That means code outside of your assembly won't be able to access the types.  When you do the reflection yourself, all the calls are coming from your assembly so it is allowed.  But when you introduce expressions, the calls start coming from framework DLLs and so they get stopped.

An easy way to solve problems of this nature is with the InternalsVisibleTo attribute.  By just adding this:

[assembly: InternalsVisibleTo("System.Core")]

you'll be able to create the lambda.  However, when you go to compile it, you get a similar permission exception.  In that case, the Compile method ends up triggering some code in mscorlib.dll to try to access your type.  I tried adding:

[assembly: InternalsVisibleTo("mscorlib")]

but that didn't seem to work.  I think it might have to do with the fact that mscorlib is strongly signed.  According to the documentation of InternalsVisislbeTo:

Both the current assembly and the friend assembly must be unsigned, or
  both must be signed with a strong name.

Perhaps if your code was signed, it would work.  Or perhaps you don't even need the call to Compile() - maybe that was just for testing?  Adding the reference to System.Core is worth a try.


问:
How to remove parentheses and all data within using Pandas/Python?
I have a dataframe where I want to remove all parentheses and stuff inside it.

I checked out :
 How can I remove text within parentheses with a regex?

Where the answer to remove the data was

```<code>re.sub(r'\([^)]*\)', '', filename)
</code>```

I tried this as well as

```<code>re.sub(r'\(.*?\)', '', filename)
</code>```

However, I got an error: expected a string or buffer

When I tried using the column df['Column Name'] I got no item named 'Column Name'

I checked the dataframe using df.head() and it showed up as a clean table with the column names as what I wanted them to be....however when I use the re expression to remove the (stuff) it isn't recognizing the column name that I have.

I normally use

```<code>df['name'].str.replace(" ()","")
</code>```

However, I want to remove the parentheses and what is inside....How can I do this using either regex or pandas?

Thanks!

Here is the solution I used...thanks for the help!

```<code>All['Manufacturer Standard Name'] = All['Manufacturer Standard Name'].str.replace(r"\(.*\)","")
</code>```

答:
All the answers above seem great; However, the following links provide a better understanding.
a) https://docs.python.org/3/howto/regex.html#regex-howto
b) https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html

To summarize, to replace a unwanted character, you have to use the pandas.DataFrame.replace function. For instance to remove [] from a dataframe, one can do the following.

```<code>import re
p=re.compile('\[]') %% regular expression for matching [] (see reference (a)
result.replace(to_replace=p,value="",inplace=False,regex=True) %%For a dataframe named result, this way one can replace [] with "". see reference (b)
</code>```

Body:
I have a dataframe where I want to remove all parentheses and stuff inside it.

I checked out :
 How can I remove text within parentheses with a regex?

Where the answer to remove the data was

re.sub(r'\([^)]*\)', '', filename)

I tried this as well as

re.sub(r'\(.*?\)', '', filename)

However, I got an error: expected a string or buffer

When I tried using the column df['Column Name'] I got no item named 'Column Name'

I checked the dataframe using df.head() and it showed up as a clean table with the column names as what I wanted them to be....however when I use the re expression to remove the (stuff) it isn't recognizing the column name that I have.

I normally use

df['name'].str.replace(" ()","")

However, I want to remove the parentheses and what is inside....How can I do this using either regex or pandas?

Thanks!

Here is the solution I used...thanks for the help!

All['Manufacturer Standard Name'] = All['Manufacturer Standard Name'].str.replace(r"\(.*\)","")

Body:
All the answers above seem great; However, the following links provide a better understanding.
a) https://docs.python.org/3/howto/regex.html#regex-howto
b) https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html

To summarize, to replace a unwanted character, you have to use the pandas.DataFrame.replace function. For instance to remove [] from a dataframe, one can do the following.

import re
p=re.compile('\[]') %% regular expression for matching [] (see reference (a)
result.replace(to_replace=p,value="",inplace=False,regex=True) %%For a dataframe named result, this way one can replace [] with "". see reference (b)


问:
How can I make python recognize a word and separate it into a new column?
I would like to know if there is a way for python to recognize the colors of each record and separate them into a separate column.

That is, we have the following data:

```<code>ID  CODE        DESCRIPTION                     PRICE
1   85473254        Mountain jacket blue        30,99
2   54123654        Boots pink                  23.45
3   45236574        Buff sky blue               20.50
4   12547835        All set mountain black      90.99
</code>```

And I want to get the following:

```<code>ID  CODE            DESCRIPTION             COLOR       PRICE
1   85473254        Mountain jacket         Blue        30,99
2   54123654        Boots                   Pink        23.45
3   45236574        Buff                   Sky blue     20.50
4   12547835        All set mountain        Black       90.99
</code>```

Maybe there is any way to train python with a dataset of colors so that it recognizes and separates each color of every registry?

Thanks for your help.

答:
You could maintain a list of all possible colors, and then form a regex alternation of that.  Then, use str.extract to find the color in each description.

colors = ['sky blue', 'pink', 'blue', 'black']
regex = r'\b(' + '|'.join(colors) + r')$'
df["COLOR"] = df["DESCRIPTION"].str.extract(regex, flags=re.I)
```

Body:
I would like to know if there is a way for python to recognize the colors of each record and separate them into a separate column.

That is, we have the following data:

ID  CODE        DESCRIPTION                     PRICE
1   85473254        Mountain jacket blue        30,99
2   54123654        Boots pink                  23.45
3   45236574        Buff sky blue               20.50
4   12547835        All set mountain black      90.99

And I want to get the following:

ID  CODE            DESCRIPTION             COLOR       PRICE
1   85473254        Mountain jacket         Blue        30,99
2   54123654        Boots                   Pink        23.45
3   45236574        Buff                   Sky blue     20.50
4   12547835        All set mountain        Black       90.99

Maybe there is any way to train python with a dataset of colors so that it recognizes and separates each color of every registry?

Thanks for your help.


问:
How to display MDN reference in JavaScript file
I have a strange problem in my vocode

My editor has disabled the refences and the definition that is shown from MDN not in HTML nor CSS  but it is only in my JavaScript file

I have made many things like :
write two following lines in settings.JSON and no thing happens

"editor.hover.enabled": true,
"editor.hover.delay": 300,

I has installed intellisense and the same result no thing changed

I need to show it when hovering

答:
See this ref.

There is no official support for  MDN reference for javascript until now.

This extension may help to some extent.