问:
Removing duplicates from an vector is giving unexpected results

Given a vector of integers, iterate through the vector and check whether there are more than one of the same number. In that case, remove them so that only a single index of the vector contains that number. Here are a few examples:

```<code>vector<int> arr {1,1,1,1}
When arr is printed out the result should be 1.

vector<int> arr {1,2,1,2}
When arr is printed out the result should be 1,2.

vector<int> arr {1,3,2}
When arr is printed out the result should be 1,3,2.
</code>```

I know there are many solutions regarding this, but I want to solve it using my method. The solutions I've looked at use a lot of built-in functions, which I don't want to get too comfortable with as a beginner. I want to practice my problem-solving skills.

This is my code:

```<code>#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> arr {1,1,1,1,2,1,1,1,1,1};

    for (int i {}; i < arr.size(); ++i)
    {
        int counter {};

        for (int j {}; j < arr.size(); ++j)
        {
            if (arr.at(i) == arr.at(j))
            {
                counter++;

                if (counter > 1)
                    arr.erase(arr.begin()+j);
            }
        }
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        cout << value << endl;
    }

    return 0;
}
</code>```

The thing is that it works for the most part, except a few cases which have me confused.

For instance:

```<code>vector<int> arr {1,1,1,1,2,1,1,1,1,1}
When arr is printed out the result is 1,2,1 instead of 1,2.
</code>```

However, in this case:

```<code>vector<int> arr {1,1,1,1,2,1,1,1}
When arr is printed out the result is 1,2.
</code>```

It seems to work in the vast majority of cases, but when a number repeats itself a lot of times in the vector, it seems to not work, and I can't seem to find a reason for this.

I am now asking you to firstly tell me the cause of the problem, and then to give me guidance on how I should tackle this problem using my solution.

答:
The machine I'm using has a pre C++11 compiler so this is an answer in the old fashioned C++.  The easy way around this is to erase backwards.  That way you don't have to worry about the size.  Also, instead of using a for loop, which may be optimised, use a while loop.</p>
```<code>#include <iostream>
#include <vector>

int main()
{
    int dummy[] = {1,1,1,1,2,1,1,1,1,1};
    std::vector<int> arr(dummy, dummy + sizeof(dummy)/sizeof(dummy[0]));

    size_t ii = 0;
    while (ii < arr.size())
    {
        // Save the value for a little efficiency
        int value = arr[ii];

        // Go through backwards only as far as ii.
        for (size_t jj = arr.size() - 1; jj > ii; --jj)
        {
            if (value == arr[jj])
                arr.erase(arr.begin() + jj);
        }
        ++ii;
    }

//Prints out the vector arr

    for (size_t ii = 0; ii < arr.size(); ++ii)
    {
        std::cout << arr[ii] << std::endl;
    }

    return 0;
}
</code>```

Body:
Given a vector of integers, iterate through the vector and check whether there are more than one of the same number. In that case, remove them so that only a single index of the vector contains that number. Here are a few examples:

vector<int> arr {1,1,1,1}
When arr is printed out the result should be 1.

vector<int> arr {1,2,1,2}
When arr is printed out the result should be 1,2.

vector<int> arr {1,3,2}
When arr is printed out the result should be 1,3,2.

I know there are many solutions regarding this, but I want to solve it using my method. The solutions I've looked at use a lot of built-in functions, which I don't want to get too comfortable with as a beginner. I want to practice my problem-solving skills.

This is my code:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> arr {1,1,1,1,2,1,1,1,1,1};

    for (int i {}; i < arr.size(); ++i)
    {
        int counter {};

        for (int j {}; j < arr.size(); ++j)
        {
            if (arr.at(i) == arr.at(j))
            {
                counter++;

                if (counter > 1)
                    arr.erase(arr.begin()+j);
            }
        }
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        cout << value << endl;
    }

    return 0;
}

The thing is that it works for the most part, except a few cases which have me confused.

For instance:

vector<int> arr {1,1,1,1,2,1,1,1,1,1}
When arr is printed out the result is 1,2,1 instead of 1,2.

However, in this case:

vector<int> arr {1,1,1,1,2,1,1,1}
When arr is printed out the result is 1,2.

It seems to work in the vast majority of cases, but when a number repeats itself a lot of times in the vector, it seems to not work, and I can't seem to find a reason for this.

I am now asking you to firstly tell me the cause of the problem, and then to give me guidance on how I should tackle this problem using my solution.

Body:
The machine I'm using has a pre C++11 compiler so this is an answer in the old fashioned C++.  The easy way around this is to erase backwards.  That way you don't have to worry about the size.  Also, instead of using a for loop, which may be optimised, use a while loop.

#include <iostream>
#include <vector>

int main()
{
    int dummy[] = {1,1,1,1,2,1,1,1,1,1};
    std::vector<int> arr(dummy, dummy + sizeof(dummy)/sizeof(dummy[0]));

    size_t ii = 0;
    while (ii < arr.size())
    {
        // Save the value for a little efficiency
        int value = arr[ii];

        // Go through backwards only as far as ii.
        for (size_t jj = arr.size() - 1; jj > ii; --jj)
        {
            if (value == arr[jj])
                arr.erase(arr.begin() + jj);
        }
        ++ii;
    }

//Prints out the vector arr

    for (size_t ii = 0; ii < arr.size(); ++ii)
    {
        std::cout << arr[ii] << std::endl;
    }

    return 0;
}


来源: stackexchange

问:
jQuery review DOM and react
I have a bunch of DIVs which are the feed in a portfolio which has a filtering system which shows and hides the DIVs - this works well - I am adapting this system to look at the DIVs that match the filter clicked on and then style them with a new class with jQuery. CSS nth-of-type does not work, as it recognizes the hidden divs and thus messes up my custom layout, so I need a reliable way of checking the list of DIVs and applying the new class ONLY to those which do not have the inline style "transform: scale(0.001)" applied to them - this inline style is applied by the filtering system which I don't want to mess around with - so am looking for a way of adding a new class to the DIVS which don't have "transform: scale(0.001)" applied each time the filter buttons are clicked.

The classes I want to add are "itemPOS1" to the first div without the transform applied, then "itemPOS2" to the 2nd, etc etc... so the list of DIVS below would look like this on initial load:

```<code><div>Project 1</div>
<div>Project 2</div>
<div>Project 3</div>
<div>Project 4</div>
<div>Project 5</div>
</code>```

Then after clicking on a filter the list could look like this:

```<code><div>Project 1</div>
<div style="transform: scale(0.001)">Project 2</div>
<div style="transform: scale(0.001)">Project 3</div>
<div>Project 4</div>
<div style="transform: scale(0.001)">Project 5</div>
</code>```

In which case - the list would then look like this once I have added the new classes to those DIVS which are suitable:

```<code><div class="itemPOS1">Project 1</div>
<div style="transform: scale(0.001)">Project 2</div>
<div style="transform: scale(0.001)">Project 3</div>
<div class="itemPOS2">Project 4</div>
<div style="transform: scale(0.001)">Project 5</div>
</code>```

So, in the front end - the user would just see "Project 1" and "Project 4"....

I cant seem to get this to work well - I was using:

```<code>$('div:visible:eq(0)').addClass('itemPOS1');
$('div:visible:eq(1)').addClass('itemPOS2');
$('div:visible:eq(2)').addClass('itemPOS3');
$('div:visible:eq(3)').addClass('itemPOS4');
</code>```

but its not reliable as sometimes it applies classes to DIVs which have the transform: scale(0.001) applied and thus makes the rendering of the projects wrong as the class names get added incorrectly. I was hoping to find a way to only apply the adding class logic to those divs which did not have "transform: scale(0.001)" applied to them...

I also want to add itemPOS1, 2, 3, 4 and 5 to each 5 DIVs that dont have the inline transform applied - so for example - the 6th DIV that should have the class applied should get itemPOS1 not itemPOS6

Any thoughts?

In essence looking for:

if div does not have transform: scale(0.001) then add class itemPOSX

X starting at 1 for 1st div, then 2 for 2nd... up to 5th, then 6th div has itemPOS1, div 7 has itemPO2 etc...

$('div:visible:eq(0)').addClass('itemPOS1');
$('div:visible:eq(1)').addClass('itemPOS2');
$('div:visible:eq(2)').addClass('itemPOS3');
$('div:visible:eq(3)').addClass('itemPOS4');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>basic set</h2>
<div>Project 1</div>
<div>Project 2</div>
<div>Project 3</div>
<div>Project 4</div>
<div>Project 5</div>
<h2>test set filtered:</h2>
<div>Project 1</div>
<div style="transform: scale(0.001)">Project 2</div>
<div style="transform: scale(0.001)">Project 3</div>
<div>Project 4</div>
<div style="transform: scale(0.001)">Project 5</div></code>```

答:
First off: these are not "hidden" as such.
Visible vs hidden reference: Difference between :hidden and :not(:visible) in jQuery

they have this:

What I did (roughly)

Here I do some manipulation of your classes and a bit more, show how to select just those (which is your question). NOTE: if you click the second button a second time it gets the NEW first one...

$(function() {
  $("#make-obvious-stuff").on('click', function() {
    // select by those with the style transform
    let these = $("[style='transform: scale(0.001)']");
    // now do some stuff with them
    // show how many:
    $(this).after("
Found:" + these.length + "
");
    // give class to first one
    these.first().addClass("make-obvious");
    // wrap those NOT the first one; see them do nothing
    these.not().first().wrap("

");
    // does nothing:
    these.not().first().show(); // does nothing
    // remove the transform on first one: NOW we see it.
    these.first().css("transform", "");

  });

  $("#do-stuff").on('click', function() {
    // do what was asked: (but this does little perhaps?
    let these = $("[style='transform: scale(0.001)']");
    these.eq(0).addClass('itemPOS1');
    these.eq(1).addClass('itemPOS2');// this overrides the style with !important (that is a bad pattern to adopt)
    these.eq(2).addClass('itemPOS3');
    these.eq(4).addClass('itemPOS4');
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.make-obvious {
  border: solid lime 1px;
  background-color: #ffdddd;
  padding: 1rem;
}

.wrapped: {
  border: solid blue 2px;
  padding: 2rem;
  background-color: #ddffdd;
}

.found {
  margin: 1rem;
  padding: 1rem;
  border: 1px solid black;
}

.itemPOS1 {
  background-color: #ddddff;
}
.itemPOS2 {
  background-color: #ffddff;
  transform: scale(1)!important;
}</code>```

basic set

Project 1

Project 2

Project 3

Project 4

Project 5

test set filtered:

Project 1

Project 2

Project 3

Project 4

Project 5

Click me first:
<button id="do-stuff">Do Stuff</button> Click me Second:
<button id="make-obvious-stuff">Make Obvious</button>```

ContentLicense: CC BY-SA 4.0

Title: jQuery review DOM and react

Body:
I have a bunch of DIVs which are the feed in a portfolio which has a filtering system which shows and hides the DIVs - this works well - I am adapting this system to look at the DIVs that match the filter clicked on and then style them with a new class with jQuery. CSS nth-of-type does not work, as it recognizes the hidden divs and thus messes up my custom layout, so I need a reliable way of checking the list of DIVs and applying the new class ONLY to those which do not have the inline style "transform: scale(0.001)" applied to them - this inline style is applied by the filtering system which I don't want to mess around with - so am looking for a way of adding a new class to the DIVS which don't have "transform: scale(0.001)" applied each time the filter buttons are clicked.

The classes I want to add are "itemPOS1" to the first div without the transform applied, then "itemPOS2" to the 2nd, etc etc... so the list of DIVS below would look like this on initial load:

Project 1

Project 2

Project 3

Project 4

Project 5

Then after clicking on a filter the list could look like this:

Project 1

Project 2

Project 3

Project 4

Project 5

In which case - the list would then look like this once I have added the new classes to those DIVS which are suitable:

Project 1

Project 2

Project 3

Project 4

Project 5

So, in the front end - the user would just see "Project 1" and "Project 4"....

I cant seem to get this to work well - I was using:

$('div:visible:eq(0)').addClass('itemPOS1');
$('div:visible:eq(1)').addClass('itemPOS2');
$('div:visible:eq(2)').addClass('itemPOS3');
$('div:visible:eq(3)').addClass('itemPOS4');

but its not reliable as sometimes it applies classes to DIVs which have the transform: scale(0.001) applied and thus makes the rendering of the projects wrong as the class names get added incorrectly. I was hoping to find a way to only apply the adding class logic to those divs which did not have "transform: scale(0.001)" applied to them...

I also want to add itemPOS1, 2, 3, 4 and 5 to each 5 DIVs that dont have the inline transform applied - so for example - the 6th DIV that should have the class applied should get itemPOS1 not itemPOS6

Any thoughts?

In essence looking for:

if div does not have transform: scale(0.001) then add class itemPOSX

X starting at 1 for 1st div, then 2 for 2nd... up to 5th, then 6th div has itemPOS1, div 7 has itemPO2 etc...

$('div:visible:eq(0)').addClass('itemPOS1');
$('div:visible:eq(1)').addClass('itemPOS2');
$('div:visible:eq(2)').addClass('itemPOS3');
$('div:visible:eq(3)').addClass('itemPOS4');

basic set

Project 1

Project 2

Project 3

Project 4

Project 5

test set filtered:

Project 1

Project 2

Project 3

Project 4

Project 5

Body:
First off: these are not "hidden" as such.
Visible vs hidden reference: Difference between :hidden and :not(:visible) in jQuery

they have this:

What I did (roughly)

Here I do some manipulation of your classes and a bit more, show how to select just those (which is your question). NOTE: if you click the second button a second time it gets the NEW first one...

$(function() {
  $("#make-obvious-stuff").on('click', function() {
    // select by those with the style transform
    let these = $("[style='transform: scale(0.001)']");
    // now do some stuff with them
    // show how many:
    $(this).after("<div class='found'>Found:" + these.length + "</div>");
    // give class to first one
    these.first().addClass("make-obvious");
    // wrap those NOT the first one; see them do nothing
    these.not().first().wrap("<div class='wrapped'></div>");
    // does nothing:
    these.not().first().show(); // does nothing
    // remove the transform on first one: NOW we see it.
    these.first().css("transform", "");

  });

  $("#do-stuff").on('click', function() {
    // do what was asked: (but this does little perhaps?
    let these = $("[style='transform: scale(0.001)']");
    these.eq(0).addClass('itemPOS1');
    these.eq(1).addClass('itemPOS2');// this overrides the style with !important (that is a bad pattern to adopt)
    these.eq(2).addClass('itemPOS3');
    these.eq(4).addClass('itemPOS4');
  });
})

.make-obvious {
  border: solid lime 1px;
  background-color: #ffdddd;
  padding: 1rem;
}

.wrapped: {
  border: solid blue 2px;
  padding: 2rem;
  background-color: #ddffdd;
}

.found {
  margin: 1rem;
  padding: 1rem;
  border: 1px solid black;
}

.itemPOS1 {
  background-color: #ddddff;
}
.itemPOS2 {
  background-color: #ffddff;
  transform: scale(1)!important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>basic set</h2>
<div>Project 1</div>
<div>Project 2</div>
<div>Project 3</div>
<div>Project 4</div>
<div>Project 5</div>
<h2>test set filtered:</h2>
<div>Project 1</div>
<div style="transform: scale(0.001)">Project 2</div>
<div style="transform: scale(0.001)">Project 3</div>
<div>Project 4</div>
<div style="transform: scale(0.001)">Project 5</div>
Click me first:
<button id="do-stuff">Do Stuff</button> Click me Second:
<button id="make-obvious-stuff">Make Obvious</button>


问:
How can I get the "smart sharpen" effect on my images with python?
I am wondering how to smart sharpen an image using python or any  related image library like ndimage ,skimage or even PIL.I could find methods that actually sharpen my image but with a lot of noise and pixelating when zooming in .So since I know Photoshop I tried to get that smart sharpen effect which sharpens the image with a less noising and with a nice sweet contrast through python but I failed.

Notes:-

(1) methods has been tested:-

```<code>>>> # The 1st Method:
>>> import Image
>>> import ImageFilter
>>> image.filter(ImageFilter.SHARPEN)
>>> Image.filter(ImageFilter.EDGE_ENHANCE_MORE)    #Look down:1st image created

>>> # The 2nd Method:
>>> blurred_l=scipy.ndimage.gaussian_filter(b,3)
>>> filter_blurred_l = scipy.ndimage.gaussian_filter(blurred_l, 1)
>>> alpha =30
>>> sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l)

>>> # The 3rd Method:
>>> shar=imfilter(Image,'sharpen')               #Look down:2nd image created
</code>```

(2) I found a piece of code but it's in Perl . I only know Python In here  or  directly
(3) Here are 2 of the sharpened image using above methods the third done with smartsharp:

Original

Original image http://imageshack.us/a/img600/6640/babyil.jpg

First ....................................................................second

1st http://imageshack.us/a/img803/3897/sharp1.png  2nd http://imageshack.us/a/img809/2235/sharp2.png

third MY GOAL>that's the effect I want

3rd http://imageshack.us/a/img832/4563/smartsharp.jpg

(4) Here are the tool I used to create the third image above:

smrsharpm http://imageshack.us/a/img210/2747/smartsharpentoolm.jpg    smrsharp http://imageshack.us/a/img193/490/smartsharpentool.jpg

答:
Well this is a rather old question and this is probably not the right answer either, but I was looking to do this with Photoshop 2020 and a python script and I had a hard time finding scattered information on how to do this so I'll post this anyway if anyone ever needs something like and this could help them.

First of all I used this python library : https://photoshop-python-api.readthedocs.io/en/0.14.0/index.html
With this API i was able to recreate basically any filter in photoshop with a python script.

Then I needed to find the string IDs for the actions to create the scripts, for this I used the Scripting Listener plugin that i found here : https://helpx.adobe.com/photoshop/kb/downloadable-plugins-and-content.html#ScriptingListenerplugin

I tried following the guide for Windows, but it actually didn't work
at first, at step 4 you actually have to put the 3 folders that you
extract from the ZIP in the "Plug-Ins" folder "Program
Files\Adobe\Adobe Photoshop 2020\Plug-ins" just like mac-os.

Then is just a matter of executing whatever filter in photoshop and get the JS or VBS log from the listener and converting it in python.

This is an example of the JS log for the Smart Sharpen:

```<code>var idsmartSharpen = stringIDToTypeID( "smartSharpen" );
var desc186 = new ActionDescriptor();
var idpresetKind = stringIDToTypeID( "presetKind" );
var idpresetKindType = stringIDToTypeID( "presetKindType" );
var idpresetKindCustom = stringIDToTypeID( "presetKindCustom" );
desc186.putEnumerated( idpresetKind, idpresetKindType, idpresetKindCustom );
var iduseLegacy = stringIDToTypeID( "useLegacy" );
desc186.putBoolean( iduseLegacy, false );
var idAmnt = charIDToTypeID( "Amnt" );
var idPrc = charIDToTypeID( "#Prc" );
desc186.putUnitDouble( idAmnt, idPrc, 100.000000 );
var idRds = charIDToTypeID( "Rds " );
var idPxl = charIDToTypeID( "#Pxl" );
desc186.putUnitDouble( idRds, idPxl, 1.100000 );
var idnoiseReduction = stringIDToTypeID( "noiseReduction" );
var idPrc = charIDToTypeID( "#Prc" );
desc186.putUnitDouble( idnoiseReduction, idPrc, 50.000000 );
var idblur = charIDToTypeID( "blur" );
var idblurType = stringIDToTypeID( "blurType" );
var idlensBlur = stringIDToTypeID( "lensBlur" );
desc186.putEnumerated( idblur, idblurType, idlensBlur );
executeAction( idsmartSharpen, desc186, DialogModes.NO );
</code>```

In python I just copied the log and changed a few things like this:

```<code>import photoshop.api as ps

app = ps.Application()
docRef = app.activeDocument

def SmartSharpen(amount: int, radius: float, denoise: float):
    idsmartSharpen = app.stringIDToTypeID( "smartSharpen" );
    desc179 = ps.ActionDescriptor();
    idpresetKind = app.stringIDToTypeID( "presetKind" );
    idpresetKindType = app.stringIDToTypeID( "presetKindType" );
    idpresetKindCustom = app.stringIDToTypeID( "presetKindCustom" );
    desc179.putEnumerated( idpresetKind, idpresetKindType, idpresetKindCustom );

    iduseLegacy = app.stringIDToTypeID( "useLegacy" );
    desc179.putBoolean( iduseLegacy, False );

    idAmnt = app.charIDToTypeID( "Amnt" );
    idPrc = app.charIDToTypeID( "#Prc" );
    desc179.putUnitDouble( idAmnt, idPrc, amount );

    idRds = app.charIDToTypeID( "Rds " );
    idPxl = app.charIDToTypeID( "#Pxl" );
    desc179.putUnitDouble( idRds, idPxl, radius );

    idnoiseReduction = app.stringIDToTypeID( "noiseReduction" );
    idPrc = app.charIDToTypeID( "#Prc" );
    desc179.putUnitDouble( idnoiseReduction, idPrc, denoise );

    idblur = app.charIDToTypeID( "blur" );
    idblurType = app.stringIDToTypeID( "blurType" );
    idlensBlur = app.stringIDToTypeID( "lensBlur" );
    desc179.putEnumerated( idblur, idblurType, idlensBlur );

    app.executeAction( idsmartSharpen, desc179, 3 );

SmartSharpen(50, 1.1, 100)
</code>```

Actually in the python library there was already an example for the Smart Sharpening but with its EventID.SmartSharpen i wasn't getting the same results for some reason. Also to change the blur type you have to know the actual stringID, which unless there's a documentation somewhere that I wasn't able to find, I was only able to get it from the logs.

To end this, an unrelated note to this question, for some filter that i needed like "Reduce Noise", the class "ActionList" is used but in the python library currently is not implemented yet, for now I managed by simply creating it myself by simply coping the already present "ActionDescription" and changing the name and a few methods that I needed by following the documentation here: https://www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-cc-vbs-ref.pdf#ActionList.
I'll just put it here in case somebody may ever need this because I had a hard time finding anything about this:

```<code>"""This object provides an array-style mechanism for storing dta.

"""

# Import built-in modules
from pathlib import Path

# Import local modules
from photoshop.api._core import Photoshop
from photoshop.api.action_list import ActionList
from photoshop.api.action_reference import ActionReference
from photoshop.api.enumerations import DescValueType

class ActionList(Photoshop):
    object_name = "ActionList"

    def __init__(self):
        super().__init__()

    @property
    def count(self):
        """The number of keys contained in the descriptor."""
        return self.app.count

    def clear(self):
        """Clears the descriptor."""
        self.app.clear()

    def getBoolean(self, key: int) -> int:
        """Gets the text_font of a key of type boolean.

        Args:
            key (str): key of type boolean.

        Returns:
            bool: The text_font of a key of type boolean.

        """
        return self.app.getBoolean(key)

    def getClass(self, key):
        """Gets the text_font of a key of type class.

        Args:
            key (str): The key of type class.

        Returns:
            int: The text_font of a key of type class.

        """
        return self.app.getClass(key)

    def getData(self, key: int) -> int:
        """Gets raw byte data as a string value."""
        return self.app.getData(key)

    def getDouble(self, key: int) -> int:
        """Gets the value of a key of type double."""
        return self.app.getDouble(key)

    def getEnumerationType(self, index: int) -> int:
        """Gets the enumeration type of a key."""
        return self.app.getEnumerationType(index)

    def getEnumerationValue(self, index: int) -> int:
        """Gets the enumeration value of a key."""
        return self.app.getEnumerationValue(index)

    def getInteger(self, index: int) -> int:
        """Gets the value of a key of type integer."""
        return self.app.getInteger(index)

    def getKey(self, index: int) -> int:
        """Gets the ID of the key provided by index."""
        return self.app.getKey(index)

    def getLargeInteger(self, index: int) -> int:
        """Gets the value of a key of type large integer."""
        return self.app.getLargeInteger(index)

    def getList(self, index: int) -> ActionList:
        """Gets the value of a key of type list."""
        return ActionList(self.app.getList(index))

    def getObjectType(self, key: int) -> int:
        """Gets the class ID of an object in a key of type object."""
        return self.app.getObjectType(key)

    def getObjectValue(self, key: int) -> int:
        """Get the class ID of an object in a key of type object."""
        return self.app.getObjectValue(key)

    def getPath(self, key: int) -> Path:
        """Gets the value of a key of type."""
        return Path(self.app.getPath(key))

    def getReference(self, key: int) -> ActionReference:
        """Gets the value of a key of type."""
        return ActionReference(self.app.getReference(key))

    def getString(self, key: int) -> str:
        """Gets the value of a key of type."""
        return self.app.getString(key)

    def getType(self, key: int) -> DescValueType:
        """Gets the type of a key."""
        return DescValueType(self.app.getType(key))

    def getUnitDoubleType(self, key: int) -> int:
        """Gets the unit type of a key of type UnitDouble."""
        return self.app.getUnitDoubleType(key)

    def getUnitDoubleValue(self, key: int) -> int:
        """Gets the unit type of a key of type UnitDouble."""
        return self.app.getUnitDoubleValue(key)

    def hasKey(self, key: int) -> bool:
        """Checks whether the descriptor contains the provided key."""
        return self.app.hasKey(key)

    def isEqual(self, otherDesc) -> bool:
        """Determines whether the descriptor is the same as another descriptor.

        Args:
            otherDesc (.action_descriptor.ActionDescriptor):

        """
        return self.app.isEqual(otherDesc)

    def putBoolean(self, key: int, value: bool):
        """Sets the value for a key whose type is boolean."""
        self.app.putBoolean(key, value)

    def putClass(self, key: int, value: int):
        """Sets the value for a key whose type is class."""
        self.app.putClass(key, value)

    def putData(self, key: int, value: str):
        """Puts raw byte data as a string value."""
        self.app.putData(key, value)

    def putDouble(self, key: int, value: int):
        """Sets the value for a key whose type is double."""
        self.app.putDouble(key, value)

    def putEnumerated(self, key: int, enum_type: int, value: int):
        """Sets the enumeration type and value for a key."""
        self.app.putEnumerated(key, enum_type, value)

    def putInteger(self, key: int, value: int):
        """Sets the value for a key whose type is integer."""
        self.app.putInteger(key, value)

    def putLargeInteger(self, key: int, value: int):
        """Sets the value for a key whose type is large integer."""
        self.app.putLargeInteger(key, value)

    def putList(self, key: int, value: ActionList):
        """Sets the value for a key whose type is an ActionList object."""
        self.app.putList(key, value)

    def putObject(self, class_id: int, value):
        """Sets the value for a key whose type is an object."""
        self.app.putObject(class_id, value)

    def putPath(self, key: int, value: str):
        """Sets the value for a key whose type is path."""
        self.app.putPath(key, value)

    def putReference(self, key: int, value: ActionReference):
        """Sets the value for a key whose type is an object reference."""
        self.app.putReference(key, value)

    def putString(self, key: int, value: str):
        """Sets the value for a key whose type is string."""
        self.app.putString(key, value)

    def putUnitDouble(self, key: int, unit_id: int, value: int):
        """Sets the value for a key whose type is a unit value formatted as
        double."""
        self.app.putUnitDouble(key, unit_id, value)

    def toStream(self) -> str:
        """Gets the entire descriptor as as stream of bytes,
        for writing to disk."""
        return self.app.toSteadm()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am wondering how to smart sharpen an image using python or any  related image library like ndimage ,skimage or even PIL.I could find methods that actually sharpen my image but with a lot of noise and pixelating when zooming in .So since I know Photoshop I tried to get that smart sharpen effect which sharpens the image with a less noising and with a nice sweet contrast through python but I failed.

Notes:-

(1) methods has been tested:-

>>> # The 1st Method:
>>> import Image
>>> import ImageFilter
>>> image.filter(ImageFilter.SHARPEN)
>>> Image.filter(ImageFilter.EDGE_ENHANCE_MORE)    #Look down:1st image created

>>> # The 2nd Method:
>>> blurred_l=scipy.ndimage.gaussian_filter(b,3)
>>> filter_blurred_l = scipy.ndimage.gaussian_filter(blurred_l, 1)
>>> alpha =30
>>> sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l)

>>> # The 3rd Method:
>>> shar=imfilter(Image,'sharpen')               #Look down:2nd image created

(2) I found a piece of code but it's in Perl . I only know Python In here  or  directly
(3) Here are 2 of the sharpened image using above methods the third done with smartsharp:

Original

Original image http://imageshack.us/a/img600/6640/babyil.jpg

First ....................................................................second

1st http://imageshack.us/a/img803/3897/sharp1.png  2nd http://imageshack.us/a/img809/2235/sharp2.png

third MY GOAL>that's the effect I want

3rd http://imageshack.us/a/img832/4563/smartsharp.jpg

(4) Here are the tool I used to create the third image above:

smrsharpm http://imageshack.us/a/img210/2747/smartsharpentoolm.jpg    smrsharp http://imageshack.us/a/img193/490/smartsharpentool.jpg

Body:
Well this is a rather old question and this is probably not the right answer either, but I was looking to do this with Photoshop 2020 and a python script and I had a hard time finding scattered information on how to do this so I'll post this anyway if anyone ever needs something like and this could help them.

First of all I used this python library : https://photoshop-python-api.readthedocs.io/en/0.14.0/index.html
With this API i was able to recreate basically any filter in photoshop with a python script.

Then I needed to find the string IDs for the actions to create the scripts, for this I used the Scripting Listener plugin that i found here : https://helpx.adobe.com/photoshop/kb/downloadable-plugins-and-content.html#ScriptingListenerplugin

I tried following the guide for Windows, but it actually didn't work
at first, at step 4 you actually have to put the 3 folders that you
extract from the ZIP in the "Plug-Ins" folder "Program
Files\Adobe\Adobe Photoshop 2020\Plug-ins" just like mac-os.

Then is just a matter of executing whatever filter in photoshop and get the JS or VBS log from the listener and converting it in python.

This is an example of the JS log for the Smart Sharpen:

var idsmartSharpen = stringIDToTypeID( "smartSharpen" );
var desc186 = new ActionDescriptor();
var idpresetKind = stringIDToTypeID( "presetKind" );
var idpresetKindType = stringIDToTypeID( "presetKindType" );
var idpresetKindCustom = stringIDToTypeID( "presetKindCustom" );
desc186.putEnumerated( idpresetKind, idpresetKindType, idpresetKindCustom );
var iduseLegacy = stringIDToTypeID( "useLegacy" );
desc186.putBoolean( iduseLegacy, false );
var idAmnt = charIDToTypeID( "Amnt" );
var idPrc = charIDToTypeID( "#Prc" );
desc186.putUnitDouble( idAmnt, idPrc, 100.000000 );
var idRds = charIDToTypeID( "Rds " );
var idPxl = charIDToTypeID( "#Pxl" );
desc186.putUnitDouble( idRds, idPxl, 1.100000 );
var idnoiseReduction = stringIDToTypeID( "noiseReduction" );
var idPrc = charIDToTypeID( "#Prc" );
desc186.putUnitDouble( idnoiseReduction, idPrc, 50.000000 );
var idblur = charIDToTypeID( "blur" );
var idblurType = stringIDToTypeID( "blurType" );
var idlensBlur = stringIDToTypeID( "lensBlur" );
desc186.putEnumerated( idblur, idblurType, idlensBlur );
executeAction( idsmartSharpen, desc186, DialogModes.NO );

In python I just copied the log and changed a few things like this:

import photoshop.api as ps

app = ps.Application()
docRef = app.activeDocument

def SmartSharpen(amount: int, radius: float, denoise: float):
    idsmartSharpen = app.stringIDToTypeID( "smartSharpen" );
    desc179 = ps.ActionDescriptor();
    idpresetKind = app.stringIDToTypeID( "presetKind" );
    idpresetKindType = app.stringIDToTypeID( "presetKindType" );
    idpresetKindCustom = app.stringIDToTypeID( "presetKindCustom" );
    desc179.putEnumerated( idpresetKind, idpresetKindType, idpresetKindCustom );

    iduseLegacy = app.stringIDToTypeID( "useLegacy" );
    desc179.putBoolean( iduseLegacy, False );

    idAmnt = app.charIDToTypeID( "Amnt" );
    idPrc = app.charIDToTypeID( "#Prc" );
    desc179.putUnitDouble( idAmnt, idPrc, amount );

    idRds = app.charIDToTypeID( "Rds " );
    idPxl = app.charIDToTypeID( "#Pxl" );
    desc179.putUnitDouble( idRds, idPxl, radius );

    idnoiseReduction = app.stringIDToTypeID( "noiseReduction" );
    idPrc = app.charIDToTypeID( "#Prc" );
    desc179.putUnitDouble( idnoiseReduction, idPrc, denoise );

    idblur = app.charIDToTypeID( "blur" );
    idblurType = app.stringIDToTypeID( "blurType" );
    idlensBlur = app.stringIDToTypeID( "lensBlur" );
    desc179.putEnumerated( idblur, idblurType, idlensBlur );

    app.executeAction( idsmartSharpen, desc179, 3 );

SmartSharpen(50, 1.1, 100)

Actually in the python library there was already an example for the Smart Sharpening but with its EventID.SmartSharpen i wasn't getting the same results for some reason. Also to change the blur type you have to know the actual stringID, which unless there's a documentation somewhere that I wasn't able to find, I was only able to get it from the logs.

To end this, an unrelated note to this question, for some filter that i needed like "Reduce Noise", the class "ActionList" is used but in the python library currently is not implemented yet, for now I managed by simply creating it myself by simply coping the already present "ActionDescription" and changing the name and a few methods that I needed by following the documentation here: https://www.adobe.com/content/dam/acom/en/devnet/photoshop/pdfs/photoshop-cc-vbs-ref.pdf#ActionList.
I'll just put it here in case somebody may ever need this because I had a hard time finding anything about this:

"""This object provides an array-style mechanism for storing dta.

"""

# Import built-in modules
from pathlib import Path

# Import local modules
from photoshop.api._core import Photoshop
from photoshop.api.action_list import ActionList
from photoshop.api.action_reference import ActionReference
from photoshop.api.enumerations import DescValueType

class ActionList(Photoshop):
    object_name = "ActionList"

    def __init__(self):
        super().__init__()

    @property
    def count(self):
        """The number of keys contained in the descriptor."""
        return self.app.count

    def clear(self):
        """Clears the descriptor."""
        self.app.clear()

    def getBoolean(self, key: int) -> int:
        """Gets the text_font of a key of type boolean.

        Args:
            key (str): key of type boolean.

        Returns:
            bool: The text_font of a key of type boolean.

        """
        return self.app.getBoolean(key)

    def getClass(self, key):
        """Gets the text_font of a key of type class.

        Args:
            key (str): The key of type class.

        Returns:
            int: The text_font of a key of type class.

        """
        return self.app.getClass(key)

    def getData(self, key: int) -> int:
        """Gets raw byte data as a string value."""
        return self.app.getData(key)

    def getDouble(self, key: int) -> int:
        """Gets the value of a key of type double."""
        return self.app.getDouble(key)

    def getEnumerationType(self, index: int) -> int:
        """Gets the enumeration type of a key."""
        return self.app.getEnumerationType(index)

    def getEnumerationValue(self, index: int) -> int:
        """Gets the enumeration value of a key."""
        return self.app.getEnumerationValue(index)

    def getInteger(self, index: int) -> int:
        """Gets the value of a key of type integer."""
        return self.app.getInteger(index)

    def getKey(self, index: int) -> int:
        """Gets the ID of the key provided by index."""
        return self.app.getKey(index)

    def getLargeInteger(self, index: int) -> int:
        """Gets the value of a key of type large integer."""
        return self.app.getLargeInteger(index)

    def getList(self, index: int) -> ActionList:
        """Gets the value of a key of type list."""
        return ActionList(self.app.getList(index))

    def getObjectType(self, key: int) -> int:
        """Gets the class ID of an object in a key of type object."""
        return self.app.getObjectType(key)

    def getObjectValue(self, key: int) -> int:
        """Get the class ID of an object in a key of type object."""
        return self.app.getObjectValue(key)

    def getPath(self, key: int) -> Path:
        """Gets the value of a key of type."""
        return Path(self.app.getPath(key))

    def getReference(self, key: int) -> ActionReference:
        """Gets the value of a key of type."""
        return ActionReference(self.app.getReference(key))

    def getString(self, key: int) -> str:
        """Gets the value of a key of type."""
        return self.app.getString(key)

    def getType(self, key: int) -> DescValueType:
        """Gets the type of a key."""
        return DescValueType(self.app.getType(key))

    def getUnitDoubleType(self, key: int) -> int:
        """Gets the unit type of a key of type UnitDouble."""
        return self.app.getUnitDoubleType(key)

    def getUnitDoubleValue(self, key: int) -> int:
        """Gets the unit type of a key of type UnitDouble."""
        return self.app.getUnitDoubleValue(key)

    def hasKey(self, key: int) -> bool:
        """Checks whether the descriptor contains the provided key."""
        return self.app.hasKey(key)

    def isEqual(self, otherDesc) -> bool:
        """Determines whether the descriptor is the same as another descriptor.

        Args:
            otherDesc (.action_descriptor.ActionDescriptor):

        """
        return self.app.isEqual(otherDesc)

    def putBoolean(self, key: int, value: bool):
        """Sets the value for a key whose type is boolean."""
        self.app.putBoolean(key, value)

    def putClass(self, key: int, value: int):
        """Sets the value for a key whose type is class."""
        self.app.putClass(key, value)

    def putData(self, key: int, value: str):
        """Puts raw byte data as a string value."""
        self.app.putData(key, value)

    def putDouble(self, key: int, value: int):
        """Sets the value for a key whose type is double."""
        self.app.putDouble(key, value)

    def putEnumerated(self, key: int, enum_type: int, value: int):
        """Sets the enumeration type and value for a key."""
        self.app.putEnumerated(key, enum_type, value)

    def putInteger(self, key: int, value: int):
        """Sets the value for a key whose type is integer."""
        self.app.putInteger(key, value)

    def putLargeInteger(self, key: int, value: int):
        """Sets the value for a key whose type is large integer."""
        self.app.putLargeInteger(key, value)

    def putList(self, key: int, value: ActionList):
        """Sets the value for a key whose type is an ActionList object."""
        self.app.putList(key, value)

    def putObject(self, class_id: int, value):
        """Sets the value for a key whose type is an object."""
        self.app.putObject(class_id, value)

    def putPath(self, key: int, value: str):
        """Sets the value for a key whose type is path."""
        self.app.putPath(key, value)

    def putReference(self, key: int, value: ActionReference):
        """Sets the value for a key whose type is an object reference."""
        self.app.putReference(key, value)

    def putString(self, key: int, value: str):
        """Sets the value for a key whose type is string."""
        self.app.putString(key, value)

    def putUnitDouble(self, key: int, unit_id: int, value: int):
        """Sets the value for a key whose type is a unit value formatted as
        double."""
        self.app.putUnitDouble(key, unit_id, value)

    def toStream(self) -> str:
        """Gets the entire descriptor as as stream of bytes,
        for writing to disk."""
        return self.app.toSteadm()


问:
number format exception: for string "" when using <spring:bind> tag with form checkboxes
I'm using spring 3.0, in my jsp i have a couple of checkboxes (the normal ones <input type="checkbox" ....>). I'm using the <spring:bind path="businessL1"> to bind it with the bean with property String[] businessL1;
the checkboxes look something like this (in html) :-

```<code>  <input type="checkbox" value="2" name="businessL1[]">
</code>```

Now when every i try to submit the form the following exception is thrown:-

```<code>[org.apache.jsp.WEB_002dINF.jsp.error.GenericError_jsp] -  Generic Error:
    java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at
   org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:938)
at
   org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:900)
at........
</code>```

I'm have no conversions being done, everything is of String type.
the controller i'm using is a simple form controller
by the way the rest of the properties i.e the non checkbox type like text etc. are being set in the bean successfully.

答:
As far as I understand, you don't need square brakets to bind checkbox values to String[]:

```<code><input type="checkbox" value="2" name="businessL1">
</code>```

Body:
I'm using spring 3.0, in my jsp i have a couple of checkboxes (the normal ones <input type="checkbox" ....>). I'm using the <spring:bind path="businessL1"> to bind it with the bean with property String[] businessL1;
the checkboxes look something like this (in html) :-

  <input type="checkbox" value="2" name="businessL1[]">

Now when every i try to submit the form the following exception is thrown:-

[org.apache.jsp.WEB_002dINF.jsp.error.GenericError_jsp] -  Generic Error:
    java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at
   org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:938)
at
   org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:900)
at........

I'm have no conversions being done, everything is of String type.
the controller i'm using is a simple form controller
by the way the rest of the properties i.e the non checkbox type like text etc. are being set in the bean successfully.

Body:
As far as I understand, you don't need square brakets to bind checkbox values to String[]:

<input type="checkbox" value="2" name="businessL1">


问:
Apply OData function on retrieved data in a query
I just started to work with Odata and I had an impression the OData querying is kind of flexible.

But in some cases I want to retrieve updated/newly calculated data on the fly. In my case this data is SalaryData values. At some point, I want them to be slightly tweaked with additional applied calculation function. And the critical point that this action must occur  on the retrieval of the data with the general request query.

But I don't know, is that applicable to use function in this case?
Ideally, I want to have the similar request:

/odata/Employee(1111)?$expand=SalaryData/CalculculationFunction(40)

Here I want to apply CalculculationFunction with parameters on SalaryData.
Is that possible to do it in OData in this way? Or should I create an entity set of salary data and retrieve calculated data directly using the query something like

/odata/SalaryData(1111)/CalculculationFunction(40)
But this way is least preferable for me, because I don't want to use id of SalaryData in request

Current example of the function I created:

```<code>[EnableQuery(MaxExpansionDepth = 10, MaxAnyAllExpressionDepth = 10)]
[HttpGet]
[ODataRoute("({key})/FloatingWindow(days={days})")]
public SingleResult<Models.SalaryData> MovingWindow([FromODataUri] Guid key, [FromODataUri] int days)
{
    if (days <= 0)
        return new SingleResult<Models.SalaryData>(Array.Empty<Models.SalaryData>().AsQueryable());
    var cachedSalaryData = GetAllowedSalaryData().FirstOrDefault(x => x.Id.Equals(key));
    var mappedSalaryData = mapper.Map<Models.SalaryData>(cachedSalaryData);
    mappedSalaryData = Models.SalaryData.FloatingWindowAggregation(days, mappedSalaryData);
    var salaryDataResult = new[] { mappedSalaryData };
    return new SingleResult<Models.SalaryData>(salaryDataResult.AsQueryable());
}
</code>```

答:
There is always an overlap between What is OData Compliant Routing vs What can I do with Routes in Web API. It is not always necessary to conform to the OData (V4) specification, but a non-conforming route will need custom logic on the client as well.

The common workaround for this type of request is to create Function endpoint bound to the Employee item that accepts the parameter input that will be used to materialize the data. The URL might look like this instead:

```<code>/odata/Employee(1111)/WithCalculatedSalary(40)?$expand=SalaryData
</code>```

This method could then internally call the existing MovingWindow function from the SalaryDataController to build the results. You could also engineer both functions to call a common set based routine.

The reason that you you should bind this function to the EmployeeController is that the primary identifying resource that correlates the resulting data together is the Employee.

In this way OData v4 compliant clients would still be able to execute this function and importantly would be able to discover it without any need for customisations.

If you didn't need to return the Employee resource as part of the response then you could still serve a collection of SalaryData from the EmployeeController:

```<code>/odata/Employee(1111)/CalculatedSalary(days=40)
</code>```
```<code>[EnableQuery(MaxExpansionDepth = 10, MaxAnyAllExpressionDepth = 10)]
[HttpGet]
[ODataRoute("({key})/FloatingWindow(days={days})")]
public IQueryable<Models.SalaryData> CalculatedSalary([FromODataUri] int key, [FromODataUri] int days)
{
    ...
}
</code>```
```<code>builder.EntitySet<Employee>("Employee")
       .EntityType
       .Function("CalculatedSalary")
       .ReturnsCollectionFromEntitySet<SalaryData>("SalaryData")
       .Parameter<int>("days");

</code>```

$compute and $search in ASP.NET Core OData 8

The OData v4.01 specification does have support for System Query Option $compute which was designed to enable clients to append computed values into the response structure, you could hijack this pipeline and define your own function that can be executed from a $compute clause, but the expectation is that system canonical functions are used with a combination of literal values and field references.

The ASP.Net implementation has only introduced support for this in the OData Lib v8 runtime, as yet I have not yet found a good example of how to implement custom functions, but syntactically it is feasible.

The same concept could be used to augment the $apply execution, if this calculation operates over a collection and effectively performs an aggregate evaluation, then $apply

It might be that your current CalculculationFunction can be translated directly into a $compute statement, otherwise if you promote some of the calculation steps (metadata) as columns in the schema (you might use SQL Computed Columns for this...) then $compute could be a viable option.

Body:
I just started to work with Odata and I had an impression the OData querying is kind of flexible.

But in some cases I want to retrieve updated/newly calculated data on the fly. In my case this data is SalaryData values. At some point, I want them to be slightly tweaked with additional applied calculation function. And the critical point that this action must occur  on the retrieval of the data with the general request query.

But I don't know, is that applicable to use function in this case?
Ideally, I want to have the similar request:

/odata/Employee(1111)?$expand=SalaryData/CalculculationFunction(40)

Here I want to apply CalculculationFunction with parameters on SalaryData.
Is that possible to do it in OData in this way? Or should I create an entity set of salary data and retrieve calculated data directly using the query something like

/odata/SalaryData(1111)/CalculculationFunction(40)
But this way is least preferable for me, because I don't want to use id of SalaryData in request

Current example of the function I created:

[EnableQuery(MaxExpansionDepth = 10, MaxAnyAllExpressionDepth = 10)]
[HttpGet]
[ODataRoute("({key})/FloatingWindow(days={days})")]
public SingleResult<Models.SalaryData> MovingWindow([FromODataUri] Guid key, [FromODataUri] int days)
{
    if (days <= 0)
        return new SingleResult<Models.SalaryData>(Array.Empty<Models.SalaryData>().AsQueryable());
    var cachedSalaryData = GetAllowedSalaryData().FirstOrDefault(x => x.Id.Equals(key));
    var mappedSalaryData = mapper.Map<Models.SalaryData>(cachedSalaryData);
    mappedSalaryData = Models.SalaryData.FloatingWindowAggregation(days, mappedSalaryData);
    var salaryDataResult = new[] { mappedSalaryData };
    return new SingleResult<Models.SalaryData>(salaryDataResult.AsQueryable());
}

Body:
There is always an overlap between What is OData Compliant Routing vs What can I do with Routes in Web API. It is not always necessary to conform to the OData (V4) specification, but a non-conforming route will need custom logic on the client as well.

The common workaround for this type of request is to create Function endpoint bound to the Employee item that accepts the parameter input that will be used to materialize the data. The URL might look like this instead:

/odata/Employee(1111)/WithCalculatedSalary(40)?$expand=SalaryData

This method could then internally call the existing MovingWindow function from the SalaryDataController to build the results. You could also engineer both functions to call a common set based routine.

The reason that you you should bind this function to the EmployeeController is that the primary identifying resource that correlates the resulting data together is the Employee.

In this way OData v4 compliant clients would still be able to execute this function and importantly would be able to discover it without any need for customisations.

If you didn't need to return the Employee resource as part of the response then you could still serve a collection of SalaryData from the EmployeeController:

/odata/Employee(1111)/CalculatedSalary(days=40)

[EnableQuery(MaxExpansionDepth = 10, MaxAnyAllExpressionDepth = 10)]
[HttpGet]
[ODataRoute("({key})/FloatingWindow(days={days})")]
public IQueryable<Models.SalaryData> CalculatedSalary([FromODataUri] int key, [FromODataUri] int days)
{
    ...
}

builder.EntitySet<Employee>("Employee")
       .EntityType
       .Function("CalculatedSalary")
       .ReturnsCollectionFromEntitySet<SalaryData>("SalaryData")
       .Parameter<int>("days");

$compute and $search in ASP.NET Core OData 8

The OData v4.01 specification does have support for System Query Option $compute which was designed to enable clients to append computed values into the response structure, you could hijack this pipeline and define your own function that can be executed from a $compute clause, but the expectation is that system canonical functions are used with a combination of literal values and field references.

The ASP.Net implementation has only introduced support for this in the OData Lib v8 runtime, as yet I have not yet found a good example of how to implement custom functions, but syntactically it is feasible.

The same concept could be used to augment the $apply execution, if this calculation operates over a collection and effectively performs an aggregate evaluation, then $apply

It might be that your current CalculculationFunction can be translated directly into a $compute statement, otherwise if you promote some of the calculation steps (metadata) as columns in the schema (you might use SQL Computed Columns for this...) then $compute could be a viable option.


问:
Javascript alert function not displaying message after clicking button
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.</p>
```<code>    <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <style type="text/css">

      body {
        margin: 40px;
        font-family: 'Open Sans';
      }
      #fieldSize, #fieldCrust {
        width: 150px;
        float: left;
        border: none;
      }
       #fieldToppings {
         width: 350px;
         border: none;

       }
       fieldset {
         margin-top: 20px;
       }
      #toppings1 {
        float: left;
      }
      label {
        display: inline-block;
        width: 150px;
        margin: 7px;
        text-align: left;
      }
      input[type="text"] {
        width: 250px;
      }
      div {
        padding: 10px;
      }
      #btnOrder {
        width: auto;
        border-radius: 10px;
      }

    </style>
    <script type="text/javascript">

      function orderSubmit() {
        var name = document.getElementById("txtName").value;
        var phone = document.getElementById("txtPhone").value;
        phone = '(' + phone.substring(0,3) + ')' + phone.substring(3,6) + '-' + phone.substring(6);
        var address = document.getElementById("txtAddress").value;

        var msg = name + ", your order is being prepared. \n";
        msg+= "Your order will be delivered at " + address;
        msg+= "Your contact infromation is: " + phone "\n";
        msg+= "Order details: \n \n";

        for(var i = 0; i < document.frm1.rdoSize.length; i++) {
           if(document.frm1.rdoSize[i].checked) {
             var radioStateSize = document.frm1.rdoSize[i].value;
           }
        }
        for(var j = 0; j < document.frm1.rdoCrust.length; j++) {
           if(document.frm1.rdoCrust[j].checked) {
             var radioStateCrust = document.frm1.rdoCrust[j].value;
           }
        }
        msg+= radioStateSize + ' ' + radioStateCrust + " pizza with the following toppings: \n";

        var chkToppings = document.frm1.chkToppings;

        for(k=0; k < document.frm1.chkToppings; k++) {
           if(document.frm1.chkToppings[k].checked) {
           msg += document.frm1.chkToppings[k].value + ' ';
           }
        }
        alert(msg);
      }

    </script>

  </head>

  <body>
    <fieldset id="main">
      <legend><h2>Pizza Order!</h2></legend>

      <form name="frm1">
        <div>
          <label for="lblName">Name:</label>
          <input type="text" id="txtName">
        </div>

        <div>
          <label for="lblPhone">Phone Number:</label>
          <input type="text" id="txtPhone">
        </div>

        <div>
          <label for="lblAddress">Address:</label>
          <input type="text" id="txtAddress">
        </div>

      <fieldset id="fieldSize">
        <legend><strong>Size</strong></legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small <br>
          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium <br>
          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large <br>
      </fieldset>

      <fieldset id="fieldCrust">
        <legend><strong>Crust</strong></legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small <br>
          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed <br>
          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free <br>
      </fieldset>

      <fieldset id="fieldToppings">
        <legend><strong>Toppings</strong></legend>
          <div id="toppings1">
            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage <br>
            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken <br>
            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies <br>
          </div>
          <div id="toppings2">
            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms <br>
            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers <br>
            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta <br>
            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives <br>
            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions <br>
          </div>
      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>
  </body>
</html>
</code>```

答:
There are many problems with the solution you developed:

Used without defining the variable k in the for loop.

for(); statement prevents the block from executing depending on the loop.

In the solution below, both radio buttons and checkboxes are checked.

let submitButton = document.getElementById('btnOrder');
let nameElement = document.getElementById('txtName');
let phoneElement = document.getElementById('txtPhone');
let addressElement = document.getElementById('txtAddress');

function getPhoneValue(value) {
  let result = '(' + value.substring(0,3) + ')' + value.substring(3,6) + '-' + value.substring(6);
  return result;
}

function getRadioButtonValue(element) {
  let result;

  if(element !== null)
    result = element.value;
  else
    result = "null";

  return result;
}

submitButton.addEventListener('click', function(event) {
  let phone = getPhoneValue(phoneElement.value);
  var msg = `Name: ${nameElement.value} Address:  ${addressElement.value} Phone: ${phone}\n Order details: `;

  /* first radio button group */
  var radioStateSize = getRadioButtonValue(document.querySelector("input[name='rdoSize']:checked"));

  /* second radio button group */
  var radioStateCrust = getRadioButtonValue(document.querySelector("input[name='rdoCrust']:checked"));

  /* user notification */
  msg += `${radioStateSize} ${radioStateCrust} pizza with the following toppings:\n`;

  /* checkbox group */
  var chkToppings;
  var checkboxes = document.querySelectorAll("input[name='chkToppings']:checked");
  checkboxes.forEach((checkbox) => {
    msg += checkbox.value + " ";
  });

  console.clear();
  console.log(msg)
  alert(msg);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 40px;
  font-family: 'Open Sans';
}
#fieldSize, #fieldCrust {
  width: 150px;
  float: left;
  border: none;
}
 #fieldToppings {
   width: 350px;
   border: none;

 }
 fieldset {
   margin-top: 20px;
 }
#toppings1 {
  float: left;
}
label {
  display: inline-block;
  width: 150px;
  margin: 7px;
  text-align: left;
}
input[type="text"] {
  width: 250px;
}
div {
  padding: 10px;
}
#btnOrder {
  width: auto;
  border-radius: 10px;
}</code>```

  <fieldset id="main">
    <legend>
Pizza Order!
</legend>
      <form name="frm1">

          Name:
          <input type="text" id="txtName">

          Phone Number:
          <input type="text" id="txtPhone">

          Address:
          <input type="text" id="txtAddress">

      <fieldset id="fieldSize">
        <legend>Size</legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small

          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium

          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large

      </fieldset>

      <fieldset id="fieldCrust">
        <legend>Crust</legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small

          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed

          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free

      </fieldset>

      <fieldset id="fieldToppings">
        <legend>Toppings</legend>

            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage

            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken

            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies

            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms

            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers

            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta

            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives

            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions

      </fieldset>
      <input type="button" id="btnOrder" value="Order">
    </form>
  </fieldset>
```

Body:
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.

    <!DOCTYPE html>

    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <fieldset id="main">
      <legend>
Pizza Order!
</legend>

      <form name="frm1">

          Name:
          <input type="text" id="txtName">

          Phone Number:
          <input type="text" id="txtPhone">

          Address:
          <input type="text" id="txtAddress">

      <fieldset id="fieldSize">
        <legend>Size</legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small

          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium

          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large

      </fieldset>

      <fieldset id="fieldCrust">
        <legend>Crust</legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small

          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed

          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free

      </fieldset>

      <fieldset id="fieldToppings">
        <legend>Toppings</legend>

            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage

            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken

            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies

            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms

            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers

            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta

            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives

            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions

      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>

Body:
There are many problems with the solution you developed:

Used without defining the variable k in the for loop.

for(); statement prevents the block from executing depending on the loop.

In the solution below, both radio buttons and checkboxes are checked.

let submitButton = document.getElementById('btnOrder');
let nameElement = document.getElementById('txtName');
let phoneElement = document.getElementById('txtPhone');
let addressElement = document.getElementById('txtAddress');

function getPhoneValue(value) {
  let result = '(' + value.substring(0,3) + ')' + value.substring(3,6) + '-' + value.substring(6);
  return result;
}

function getRadioButtonValue(element) {
  let result;

  if(element !== null)
    result = element.value;
  else
    result = "null";

  return result;
}

submitButton.addEventListener('click', function(event) {
  let phone = getPhoneValue(phoneElement.value);
  var msg = `Name: ${nameElement.value} Address:  ${addressElement.value} Phone: ${phone}\n Order details: `;

  /* first radio button group */
  var radioStateSize = getRadioButtonValue(document.querySelector("input[name='rdoSize']:checked"));

  /* second radio button group */
  var radioStateCrust = getRadioButtonValue(document.querySelector("input[name='rdoCrust']:checked"));

  /* user notification */
  msg += `${radioStateSize} ${radioStateCrust} pizza with the following toppings:\n`;

  /* checkbox group */
  var chkToppings;
  var checkboxes = document.querySelectorAll("input[name='chkToppings']:checked");
  checkboxes.forEach((checkbox) => {
    msg += checkbox.value + " ";
  });

  console.clear();
  console.log(msg)
  alert(msg);
});

body {
  margin: 40px;
  font-family: 'Open Sans';
}
#fieldSize, #fieldCrust {
  width: 150px;
  float: left;
  border: none;
}
 #fieldToppings {
   width: 350px;
   border: none;

 }
 fieldset {
   margin-top: 20px;
 }
#toppings1 {
  float: left;
}
label {
  display: inline-block;
  width: 150px;
  margin: 7px;
  text-align: left;
}
input[type="text"] {
  width: 250px;
}
div {
  padding: 10px;
}
#btnOrder {
  width: auto;
  border-radius: 10px;
}

<body>
  <fieldset id="main">
    <legend><h2>Pizza Order!</h2></legend>
      <form name="frm1">
        <div>
          <label for="lblName">Name:</label>
          <input type="text" id="txtName">
        </div>

        <div>
          <label for="lblPhone">Phone Number:</label>
          <input type="text" id="txtPhone">
        </div>

        <div>
          <label for="lblAddress">Address:</label>
          <input type="text" id="txtAddress">
        </div>

      <fieldset id="fieldSize">
        <legend><strong>Size</strong></legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small <br>
          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium <br>
          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large <br>
      </fieldset>

      <fieldset id="fieldCrust">
        <legend><strong>Crust</strong></legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small <br>
          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed <br>
          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free <br>
      </fieldset>

      <fieldset id="fieldToppings">
        <legend><strong>Toppings</strong></legend>
          <div id="toppings1">
            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage <br>
            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken <br>
            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies <br>
          </div>
          <div id="toppings2">
            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms <br>
            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers <br>
            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta <br>
            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives <br>
            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions <br>
          </div>
      </fieldset>
      <input type="button" id="btnOrder" value="Order">
    </form>
  </fieldset>
</body>


问:
Is there a way to convert time logged as Minutes:Seconds into numeric form?
I am working with a dataset that has time tracked as minutes:seconds (34:15 would be 34 minutes and 15 seconds) and its stored as a character currently. Is there a way to convert this to just minutes so that 34:15 would show up as 35.25?</p>

Body:
Solutions might include:

time <- c("4:30","2:20","34:15")

Base R:

c(as.matrix(read.table(text=time, sep=':')) %*% c(1,1/60))
[1]  4.500000  2.333333 34.250000

Lubridate:

 as.numeric(lubridate::ms(time))/60
 [1]  4.500000  2.333333 34.250000


问:
Why does adding a CSS file to Shiny navbarPage create a blank tab?
I am ultimately trying to add a background image and logo to my shiny app that utilizes the navbarPage layout. Adding a simple CSS file with the background image I want creates this blank li object in the navbar.

Even when the CSS file is completely blank, I get the same problem. Somehow, the mere inclusion of a CSS file creates the issue. Any clues?

I had working version before I needed to include the logo in the top left corner....

Working version with background image but no logo:

答:
I had the same issue, there is an argument for the header in navbarPage called header. This will work when tags$header will put the css file in the navbar

```<code>             ui <- navbarPage('title,
                      header = inlcludeCSS('www/css/file/css'),
                      theme = shinytheme('flatly'),
                    .........
             ) # end UI
</code>```

Body:
I had the same issue, there is an argument for the header in navbarPage called header. This will work when tags$header will put the css file in the navbar

             ui <- navbarPage('title,
                      header = inlcludeCSS('www/css/file/css'),
                      theme = shinytheme('flatly'),
                    .........
             ) # end UI


问:
How to create page like general->about->legal in iphone setting preferences
i just want to create a page in setting preferences like the page which comes after pressing clicking on general -> about -> legal

help will be appreciated

答:
There is some vagueness in your question: are you looking to have a page in the Settings app to set up preferences or are you looking to have a legal disclaimer (or the likes of it) in the Settings app?

If it is the latter, I would suggest that you investigate a little further on whether if it is appropriate based on the iOS Human Interface Guideline.

If it is the earlier, you can read more about it here. It would require you to use a Settings bundle and NSUserDefaults class to access it.


问:
calculate bmi and output other inputs in python
I am working on a python code to calculate bmi and to perform other user inputs as well.
I have the code below using the OOP approach, but I think I am still missing some parts and is not working as expected. The expectations are:

Prompt the user repeatedly to enter a patient identification number (an int), patient name (a string), patient height in inches (a positive float), and patient weight in pounds (a positive float) until the user enters a negative number for the patient ID (see Step 5 below for more information on the requirement to repeat the inputs).

Be sure to check for validity of the input values for the height and the weight using while loop.

For each patient’s information entered, your code should compute the BMI. You must write a function to do this calculation. The function must accept the patient’s height (in inches) and weight (in pounds) as parameters and return the calculated BMI.

For each patient’s information entered, output a well-formatted result listing the patient’s ID, name, calculated BMI (output with 1 digit of precision) and associated category (Underweight, Obese, etc.). The use of f-strings to produce the formatted output is recommended.

Continue the process of gathering patient data until the user enters a negative number for the patient ID. Remember, this is a type of sentinel control that will require the use of a while loop to control the input process. Most of your application’s logic will effectively be contained within a large while loop (other than the required BMI function and a few other statements). You will have other loops and decision logic nested inside this sentinel control while loop.

With some googling and sort of modifying it.

```<code>class BodyMassIndex:

    def __init__(self, pid, name, weight, height):
        self.patient_id = pid
        self.name = name
        self.weight = weight
        self.height = height

    @property
    def body_mass_index(self):
        return round((self.weight * 703) / self.height ** 2, 1)

    @property
    def score(self):
        if 18.5 < self.body_mass_index < 25:
            return 'normal weight'
        elif 25 < self.body_mass_index < 30:
            return 'overweight'
        elif self.body_mass_index > 30:
            return 'obese'
        else:
            return 'underweight'

    def print_score(self):
        ##print('For {}:{}'.format(self.patient_id, self.name))
        print('Your Body Mass Index score is: {}'.format(self.body_mass_index))
        print('You are {}'.format(self.score))

def _get_user_info():
    while True:
        try:
            pid = int(input("Please enter your 5-digit patient id: "))
            p_name = str(input("Please enter patient first name and last name: "))
            weight = float(input('Enter weight in pounds: '))
            height = float(input('Enter height in inches: '))

            if 0 < weight and 0 < height < 107:
                return weight, height
            else:
                raise ValueError('Invalid height or weight. Let us start over.')
        except ValueError:
            print('Invalid height or weight input')
            continue

def calculate_bmi():
    pid, name, weight, height = _get_user_info()
    return BodyMassIndex(weight, height)

if __name__ == '__main__':
    bmi = calculate_bmi()
    bmi.print_score()
</code>```

After entering the four values, I get a valuetype error: expecting 4 but got 2, or something sounds like that. I appreciate your help in making this work.

答:
The problem lies in your _get_user_info function. I added the missing entries in the function below. Also, as Tim Roberts said, you don't need to wrap input with str. input function returns a string in python 3. Find the new code below</p>
```<code>def _get_user_info():
    while True:
        try:
            pid = int(input("Please enter your 5-digit patient id: "))
            p_name = input("Please enter patient first name and last name: ")
            weight = float(input('Enter weight in pounds: '))
            height = float(input('Enter height in inches: '))

            if 0 < weight and 0 < height < 107:
                return pid, p_name,weight, height
            else:
                raise ValueError('Invalid height or weight. Let us start over.')
        except ValueError:
            print('Invalid height or weight input')
            continue
</code>```

Body:
I am working on a python code to calculate bmi and to perform other user inputs as well.
I have the code below using the OOP approach, but I think I am still missing some parts and is not working as expected. The expectations are:

Prompt the user repeatedly to enter a patient identification number (an int), patient name (a string), patient height in inches (a positive float), and patient weight in pounds (a positive float) until the user enters a negative number for the patient ID (see Step 5 below for more information on the requirement to repeat the inputs).

Be sure to check for validity of the input values for the height and the weight using while loop.

For each patient’s information entered, your code should compute the BMI. You must write a function to do this calculation. The function must accept the patient’s height (in inches) and weight (in pounds) as parameters and return the calculated BMI.

For each patient’s information entered, output a well-formatted result listing the patient’s ID, name, calculated BMI (output with 1 digit of precision) and associated category (Underweight, Obese, etc.). The use of f-strings to produce the formatted output is recommended.

Continue the process of gathering patient data until the user enters a negative number for the patient ID. Remember, this is a type of sentinel control that will require the use of a while loop to control the input process. Most of your application’s logic will effectively be contained within a large while loop (other than the required BMI function and a few other statements). You will have other loops and decision logic nested inside this sentinel control while loop.

With some googling and sort of modifying it.

class BodyMassIndex:

    def __init__(self, pid, name, weight, height):
        self.patient_id = pid
        self.name = name
        self.weight = weight
        self.height = height

    @property
    def body_mass_index(self):
        return round((self.weight * 703) / self.height ** 2, 1)

    @property
    def score(self):
        if 18.5 < self.body_mass_index < 25:
            return 'normal weight'
        elif 25 < self.body_mass_index < 30:
            return 'overweight'
        elif self.body_mass_index > 30:
            return 'obese'
        else:
            return 'underweight'

    def print_score(self):
        ##print('For {}:{}'.format(self.patient_id, self.name))
        print('Your Body Mass Index score is: {}'.format(self.body_mass_index))
        print('You are {}'.format(self.score))

def _get_user_info():
    while True:
        try:
            pid = int(input("Please enter your 5-digit patient id: "))
            p_name = str(input("Please enter patient first name and last name: "))
            weight = float(input('Enter weight in pounds: '))
            height = float(input('Enter height in inches: '))

            if 0 < weight and 0 < height < 107:
                return weight, height
            else:
                raise ValueError('Invalid height or weight. Let us start over.')
        except ValueError:
            print('Invalid height or weight input')
            continue

def calculate_bmi():
    pid, name, weight, height = _get_user_info()
    return BodyMassIndex(weight, height)

if __name__ == '__main__':
    bmi = calculate_bmi()
    bmi.print_score()

After entering the four values, I get a valuetype error: expecting 4 but got 2, or something sounds like that. I appreciate your help in making this work.

Body:
The problem lies in your _get_user_info function. I added the missing entries in the function below. Also, as Tim Roberts said, you don't need to wrap input with str. input function returns a string in python 3. Find the new code below

def _get_user_info():
    while True:
        try:
            pid = int(input("Please enter your 5-digit patient id: "))
            p_name = input("Please enter patient first name and last name: ")
            weight = float(input('Enter weight in pounds: '))
            height = float(input('Enter height in inches: '))

            if 0 < weight and 0 < height < 107:
                return pid, p_name,weight, height
            else:
                raise ValueError('Invalid height or weight. Let us start over.')
        except ValueError:
            print('Invalid height or weight input')
            continue


问:
Using a function to print an input one letter at a time
I am making a game/quiz in Python, but ran into a small issue. I made a function to print one letter at a time, but when I use that function for an input, it does not work and prints all at once. I've tried making a string for the input and multiple other things. To fix this temporarily, I have just been printing my question, and then using an input function to make an input, but I'm wondering if there is a better way. Here is my code:</p>
```<code>import time
import sys

def input1():
    input("")

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()
</code>```

答:
This will display the input and oneprint it:

import time
import sys

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
oneprint("\nLet's get started. What is my favorite color?")
oneprint(input("\n"))
```
<hr />
<p>This will hide the input, and <code>oneprint</code> it:</p>
<pre class="lang-py prettyprint-override"><code>import time
import sys
from getpass import getpass

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
oneprint("\nLet's get started. What is my favorite color?")
oneprint(getpass("\n>"))
</code>```

Where getpass is a password formatted input

Body:
I am making a game/quiz in Python, but ran into a small issue. I made a function to print one letter at a time, but when I use that function for an input, it does not work and prints all at once. I've tried making a string for the input and multiple other things. To fix this temporarily, I have just been printing my question, and then using an input function to make an input, but I'm wondering if there is a better way. Here is my code:

import time
import sys

def input1():
    input("")

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
q1 = "\nLet's get started. What is my favorite color?"
oneprint(q1)
input1()

Body:
This will display the input and oneprint it:

import time
import sys

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
oneprint("\nLet's get started. What is my favorite color?")
oneprint(input("\n"))

This will hide the input, and oneprint it:

import time
import sys
from getpass import getpass

def oneprint(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.05)

oneprint("Welcome. This is a very easy test. Do as you are told.")
time.sleep(3)
oneprint("\nLet's get started. What is my favorite color?")
oneprint(getpass("\n>"))

Where getpass is a password formatted input


问:
AttributeError: 'Series' object has no attribute 'lower'
Here's my code

actual = actual.apply(lambda x:x.lower())

Here's the error

```<code>/.local/lib/python3.6/site-packages/pandas/core/frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   7550             kwds=kwds,
   7551         )
-> 7552         return op.get_result()
   7553
   7554     def applymap(self, func) -> "DataFrame":

~/.local/lib/python3.6/site-packages/pandas/core/apply.py in get_result(self)
    183             return self.apply_raw()
    184
--> 185         return self.apply_standard()
    186
    187     def apply_empty_result(self):

~/.local/lib/python3.6/site-packages/pandas/core/apply.py in apply_standard(self)
    274
    275     def apply_standard(self):
--> 276         results, res_index = self.apply_series_generator()
    277
    278         # wrap results

~/.local/lib/python3.6/site-packages/pandas/core/apply.py in apply_series_generator(self)
    303                 for i, v in enumerate(series_gen):
    304                     # ignore SettingWithCopy here in case the user mutates
--> 305                     results[i] = self.f(v)
    306                     if isinstance(results[i], ABCSeries):
    307                         # If we have a view on v, we need to make a copy because

<ipython-input-94-4585873426da> in <lambda>(x)
      1 import pandas as pd
      2 actual = pd.read_csv("Data Rumah Sakit.csv", error_bad_lines=False, sep = ";")
----> 3 actual = actual.apply(lambda x:x.lower())
      4 actual["Rumah Sakit"] = actual["Rumah Sakit"].str.replace('[^\w\s]','')

~/.local/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5139             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5140                 return self[name]
-> 5141             return object.__getattribute__(self, name)
   5142
   5143     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'lower'
</code>```

答:
Use .str.lower instead of just .lower:

```<code>actual = actual.apply(lambda x:x.str.lower())
</code>```

Body:
Here's my code

actual = actual.apply(lambda x:x.lower())

Here's the error

/.local/lib/python3.6/site-packages/pandas/core/frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   7550             kwds=kwds,
   7551         )
-> 7552         return op.get_result()
   7553
   7554     def applymap(self, func) -> "DataFrame":

~/.local/lib/python3.6/site-packages/pandas/core/apply.py in get_result(self)
    183             return self.apply_raw()
    184
--> 185         return self.apply_standard()
    186
    187     def apply_empty_result(self):

~/.local/lib/python3.6/site-packages/pandas/core/apply.py in apply_standard(self)
    274
    275     def apply_standard(self):
--> 276         results, res_index = self.apply_series_generator()
    277
    278         # wrap results

~/.local/lib/python3.6/site-packages/pandas/core/apply.py in apply_series_generator(self)
    303                 for i, v in enumerate(series_gen):
    304                     # ignore SettingWithCopy here in case the user mutates
--> 305                     results[i] = self.f(v)
    306                     if isinstance(results[i], ABCSeries):
    307                         # If we have a view on v, we need to make a copy because

<ipython-input-94-4585873426da> in <lambda>(x)
      1 import pandas as pd
      2 actual = pd.read_csv("Data Rumah Sakit.csv", error_bad_lines=False, sep = ";")
----> 3 actual = actual.apply(lambda x:x.lower())
      4 actual["Rumah Sakit"] = actual["Rumah Sakit"].str.replace('[^\w\s]','')

~/.local/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5139             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5140                 return self[name]
-> 5141             return object.__getattribute__(self, name)
   5142
   5143     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'lower'

Body:
Use .str.lower instead of just .lower:

actual = actual.apply(lambda x:x.str.lower())


问:
Elasticsearch search term aggregation
I have the following mappings:

{
  mappings: {
    properties: {
      id: { type: "keyword" },
      tags: {
        properties: {
          text: { type: "text" },
          keyword: { type: "keyword" },
        },
      },
    },
  },
}
```
<p>Here is some example data:</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    id: '05070ff6-a7f1-4fad-ad70-e91fd87d58fb',
    tags: ['these','are','some','tags']
  },
  {
    id: '4843beba-4621-474f-bd80-281300fd0091',
    tags: ['abc']
  }
]
</code>```

My query looks like this:

{
  "size": 0,
  "query": {
    "bool": {
      "must": {
        "bool": {
          "should": [
            {
              "match": {
                "tags.text": "are"
              }
            },
            {
              "prefix": {
                "tags.text": "are"
              }
            },
            {
              "wildcard": {
                "tags.text": {
                  "value": "*are*",
                  "case_insensitive": true
                }
              }
            },
            {
              "wildcard": {
                "tags.text": {
                  "value": "*are",
                  "case_insensitive": true
                }
              }
            },
            {
              "wildcard": {
                "tags.text": {
                  "value": "are*",
                  "case_insensitive": true
                }
              }
            }
          ]
        }
      }
    }
  },
  "aggs": {
    "uniq_tags": {
      "terms": {
        "field": "tags.keyword",
        "size": 500
      }
    }
  }
}
```

I would expect the response to return ['are'] but it instead returns ['these', 'are, 'some, 'tags'].

I know I need to aggregate before filtering but my issue is that I need to filter on tags.text but Elasticsearch wants me to aggregate on tags.keyword. I'm not sure how to format the query to accomplish this.

答:
If you want to get only matching tags back you should use nested field with nested query

Aggregations only work on keyword fields (there is a way to apply them to text fields with fielddata parameter but this is not recommended) so you'll have to run query on tags.text but aggregations on tags (or whatever it will be with nested)

Title: Elasticsearch search term aggregation

Body:
I have the following mappings:

{
  mappings: {
    properties: {
      id: { type: "keyword" },
      tags: {
        properties: {
          text: { type: "text" },
          keyword: { type: "keyword" },
        },
      },
    },
  },
}

Here is some example data:

[
  {
    id: '05070ff6-a7f1-4fad-ad70-e91fd87d58fb',
    tags: ['these','are','some','tags']
  },
  {
    id: '4843beba-4621-474f-bd80-281300fd0091',
    tags: ['abc']
  }
]

My query looks like this:

{
  "size": 0,
  "query": {
    "bool": {
      "must": {
        "bool": {
          "should": [
            {
              "match": {
                "tags.text": "are"
              }
            },
            {
              "prefix": {
                "tags.text": "are"
              }
            },
            {
              "wildcard": {
                "tags.text": {
                  "value": "*are*",
                  "case_insensitive": true
                }
              }
            },
            {
              "wildcard": {
                "tags.text": {
                  "value": "*are",
                  "case_insensitive": true
                }
              }
            },
            {
              "wildcard": {
                "tags.text": {
                  "value": "are*",
                  "case_insensitive": true
                }
              }
            }
          ]
        }
      }
    }
  },
  "aggs": {
    "uniq_tags": {
      "terms": {
        "field": "tags.keyword",
        "size": 500
      }
    }
  }
}

I would expect the response to return ['are'] but it instead returns ['these', 'are, 'some, 'tags'].

I know I need to aggregate before filtering but my issue is that I need to filter on tags.text but Elasticsearch wants me to aggregate on tags.keyword. I'm not sure how to format the query to accomplish this.


问:
WPF Vector based interface
I'm working on a new C# application using WPF. I was under the impression that WPF was vector based and that text/buttons would be drawn in a resolution independent way. When running my application it’s fairly obvious that my application isn’t being drawn using vectors. Some of the text gets fairly blocky, and when using the windows magnifying glass you can see rough edges on everything.

Is there something special I need to do  in my application to turn vector drawing on? Or is something wrong with my specific machine? (I'm running Windows Vista x64 with the latest graphics drivers)

答:
The magnifying glass in Vista isn't particularly clever. It just blows up the already rasterized image from your screen. To see that a text box is actually vector based, try adjusting your DPI settings.

EDIT: From the comments, it seems like the magnifying glass in Vista is supposed to do vector scaling after all. It certainly doesn't on this computer (Vista 32-bit), so I may be having the same issues. DPI scaling works, though...

OwnerDisplayName: Varin

ContentLicense: CC BY-SA 2.5

Title: WPF Vector based interface

OwnerDisplayName: Tormod Fjeldskår

LastEditorDisplayName: Tormod Fjeldskår


问:
How to Create oracle PL/SQL function to store/retrieve data from table
i am beginner so i am confusing about what should i write in return type.

and how to write function to select all records from  particular ID

2   shadik  27  25-05-14    4000    pakistan
1   AKSHAY  28  30-04-20    2000    INDIA
3   GAURANG 25  06-05-20    4000    USA
4   NIRAV   23  16-11-14    1000    CANADA
5   VEER    29  26-12-19    5000    DUBAI
```

答:
Though this is a bit more custom you can return rows from a function using a type.</p>
```<code>
create or replace type myRecordType
 as object
 ( x int,
 y date,
 z varchar2(25)
 )

create or replace type myTableType
 as table of myRecordType;
/

create or replace function my_function return myTableType
 as
 some_data myTableType := myTabletype();
 begin
 for i in 1 .. 10 loop
 some_data.extend;
 some_data(i) :=
 myRecordType( i, sysdate+i, 'record ' || i );
 end loop;
 return some_data;
 end;
 /

select * from TABLE ( cast( my_function() as mytableType ) )
 /

X    Y    Z
1    09-FEB-22    record 1
2    10-FEB-22    record 2
3    11-FEB-22    record 3
4    12-FEB-22    record 4
5    13-FEB-22    record 5
6    14-FEB-22    record 6
7    15-FEB-22    record 7
8    16-FEB-22    record 8
9    17-FEB-22    record 9
10    18-FEB-22    record 10

</code>```

Body:
Though this is a bit more custom you can return rows from a function using a type.

create or replace type myRecordType
 as object
 ( x int,
 y date,
 z varchar2(25)
 )

create or replace type myTableType
 as table of myRecordType;
/

create or replace function my_function return myTableType
 as
 some_data myTableType := myTabletype();
 begin
 for i in 1 .. 10 loop
 some_data.extend;
 some_data(i) :=
 myRecordType( i, sysdate+i, 'record ' || i );
 end loop;
 return some_data;
 end;
 /

select * from TABLE ( cast( my_function() as mytableType ) )
 /

X    Y    Z
1    09-FEB-22    record 1
2    10-FEB-22    record 2
3    11-FEB-22    record 3
4    12-FEB-22    record 4
5    13-FEB-22    record 5
6    14-FEB-22    record 6
7    15-FEB-22    record 7
8    16-FEB-22    record 8
9    17-FEB-22    record 9
10    18-FEB-22    record 10