How can i round up price value in bean shell?
For example:902.7 TO 903 OR 902.0 to 902
I have written below code,But it just takes off .00 from the code,i.e. if there is 92.00,It ll remove .00.But if there is 92.37,It wont change at all
String priceAdder(String Price,double per)
{
prcv= Float.parseFloat(Price);
prec=per*1/100;
prec=prcv*prec;
if(prec>95.00)
{
prec=95.00;
}
price=prcv+prec;
price=price.toString();
String[] ppr=price.split("\\.");
if(ppr[1].length()==1)
{
ppr[1]=ppr[1]+"0";
price=ppr[0]+"."+ppr[1];
}
else
{ //System.out.println("The value ppr[1]:"+ppr[1]);
if(Character.getNumericValue(ppr[1].charAt(2))>=5)
{
Integer tadd=Integer.parseInt(ppr[1].substring(0,2))+1;
if(tadd.toString().length()==1)
{
tad="0"+tadd.toString();
}else{
tad=tadd.toString();
}
price=ppr[0]+"."+tad.toString();
}
else
{
price=ppr[0]+"."+ppr[1].substring(0,2);
}
// price=ppr[0]+"."+ppr[1].substring(0,2);
}
return price.toString();
}
Something like:
originalPrice = Double.parseDouble(price);
roundedPrice = Math.round(originalPrice);
return String.valueOf(roundedPrice);
Should round your price to the nearest whole number. See Math.round() JavaDoc for more information.
Demo:
Be aware that starting from JMeter 3.1 it is recommended to use JSR223 Elements and Groovy language for any form of scripting so consider migrating to JSR223 Test Elements on next available opportunity.
Related
I am attempting to write either an array function or a dynamic array to Excel via a UDF written in Excel DNA (v.0.34). My result is always a single value instead of the array. What am I doing wrong?
[ExcelFunction(Name = "WriteTestArray")]
public static object[,] WriteTestArray()
{
try
{
return new object[2, 2] { { "one", "two" }, { "three", "four" } };
}
catch
{
return new object[,] { { ExcelError.ExcelErrorValue } };
}
}
For array functions to work with Excel (before the 'dynamic array' support that comes one day in a future version) you need to select the target range, then type in your formula and press Ctrl+Shift+Enter to commit it as an array formula. It will be indicated by curly brackets when displayed - e.g. {=MyFunc(...)}
Problem Description
I am writing a geb/spock spec which fetches test data from DB2 into a map (the map variable is called "preFilledFields" - see the "MySpec" class further down).
This map is then being iterated over, and for each iteration I check too see if the value matches one in a row on the page.
When I perform the assertion above accessing the module object attributes, then the average execution time per assertion is approx. 5-6 seconds. If I perform the assertion using selectors directly, then the average execution time per assertion is approx. 70-80 ms. See the "MyPage" class for more details regarding the assertions.
Does anyone know what could be the cause of this? Is the bad performance a result of my code, or is there a general problem with regards to performance when using modules in geb?
Appreciate any help and input I can get.
Code:
My "RowModule" class looks like this:
class RowModule extends Module {
static final PREDEFINED_ATTR = "data-predefined-amount"
static content = {
cell { $("td", it) }
description { cell(0).text() }
rubrikNum { cell(1).text().toInteger() }
preDefinedAmount { cell(0).parent("tr").$("td[$PREDEFINED_ATTR]").attr("$PREDEFINED_ATTR") }
inputField { cell(0).parent("tr").$("td input") ?: false }
dataType{ cell(0).parent("tr").attr("data-type") }
}
}
My Page class looks like this:
class MyPage extends Page {
static url = "<some_url>"
static at = { $("h1").text() == "<some_text>" }
static content = {
submitButton { $("input", name:"<some_name>") }
myPageItems {
$("table tr").collect { it.module(RowModule) }
}
}
void verifyPrePopulatedFields(name, amount) {
long now = System.currentTimeMillis();
assert amount == selvangivelseItems.find { it.dataType== name}.preDefinedAmount.toInteger()
//assert amount == $("tr[data-type='" + name+ "']").$(".skts-tooltip-holder").text().toInteger()
println "Execution time" + (System.currentTimeMillis() - now) + " ms"
}
void submit() { submitTaxReturnButton.click() }
}
My Spec file looks like this:
class MySpec extends GebReportingSpec {
#Unroll
def "field #name is pre-populated with amount #amount from the database"() {
expect:
page(MyPage) verifyPrePopulatedFields(name, amount)
where:
name << preFilledFields.keySet()
amount << preFilledFields.values()
}
}
There are no general performance problems with using modules in Geb, at least none that I know of. Your selectors on the other hand are definitely suboptimal.
Firstly by doing myPageItems.find { it.dataType == name } you are iterating over all rows in your table and executing 3 WebDriver commands (that is http request between your test and the browser that is being driven) for each of them. You could improve the selector for dataType to dataType { attr("data-type") } (not 100% sure here because I don't see your DOM structure but this is what logic would suggest) but it would still mean potentially making a lot of requests. You should instead add a site content definition like this:
myItem { dataType ->
$("table tr[data-type='$dataType']").module(RowModule)
}
And then use it like:
assert amount == myPageItem(name).preDefinedAmount.toInteger()
Secondly you can simplify and improve performance of your selectors in the module (if my assumptions about your DOM are correct):
static content = {
cell { $("td", it) }
description { cell(0).text() }
rubrikNum { cell(1).text().toInteger() }
preDefinedAmount { $("td[$PREDEFINED_ATTR]").attr("$PREDEFINED_ATTR") }
inputField { $("td input") ?: false }
dataType{ attr("data-type") }
}
You should avoid using multiple selectors for things that can be found using a single selector or using unnecessary selectors because they will always carry a performance penalty.
My application is in Asp.Net coded in C# and i'm using LINQ for database transactions. My requirement is to get the Max value of the records saved in a certain table, for this i'm using Max() method.
Below is my controller code :
[HttpPost]
public ActionResult Create(Entity_Name Entity_Object)
{
if (Entity_Object.Condition == true)
{
My required code
}
else
{
var get_Max_Number = db.Entity_Name.ToList();
long Max_Number = 0;
if (get_Max_Number.Count() > 0)
{
Max_Number = Convert.ToInt64(get_Max_Number.Max());
}
My required code
}
}
My issue is when i remove the If-else condition then the same Max() method query works perfect, but when i add the If-else statement then i gets the following error.
Error:
At least one object must implement IComparable.
What i tried :
I attempted to remove the If-Else
I placed the Max() method logic above the If-else
Placing the Max() method above If-Else
[HttpPost]
public ActionResult Create(Entity_Name Entity_Object)
{
var get_Max_Number = db.Entity_Name.ToList();
long Max_Number = 0;
if (get_Max_Number.Count() > 0)
{
Max_Number = Convert.ToInt64(get_Max_Number.Max());
}
if (Entity_Object.Condition == true)
{
My required code
}
else
{
My required code
}
}
Max() needs to know what you're getting the maximum of. If you're Entity_Name class contains a number of properties (strings, ints etc...) then you need to tell it what to get the Maximum on the basis of.
Another thing, you're connecting to a DB via Linq from the looks of things, but executing your Count() & Max() functions in memory after you've retrieved the entire contents of the database table. This will be very inefficient as the table grows in size. LinqToSql & LinqToEF support pushing those functions down to the database level. I'd recommend changing your code to the following.
[HttpPost]
public ActionResult Create(Entity_Name Entity_Object)
{
if (Entity_Object.Condition == true)
{
//My required code
}
else
{
long Max_Number = 0;
if(db.Entity_Name.Count() > 0)
{
Max_Number = Convert.ToInt64(
db.Entity_Name.Max(x => x.PropertyToGetMaxOf)
);
}
//My required code
}
}
I am testing my code with PHPunit. My code has several ordering-methods: by name, age, count and random. Below the implementation and test for sorting by count. These are pretty trivial.
class Cloud {
//...
public function sort($by_property) {
usort($this->tags, array($this, "cb_sort_by_{$by_property}"));
return $this;
}
private function cb_sort_by_name($a, $b) {
$al = strtolower($a->get_name());
$bl = strtolower($b->get_name());
if ($al == $bl) {
return 0;
}
return ($al > $bl) ? +1 : -1;
}
/**
* Sort Callback. High to low
*/
private function cb_sort_by_count($a, $b) {
$ac = $a->get_count();
$bc = $b->get_count();
if ($ac == $bc) {
return 0;
}
return ($ac < $bc) ? +1 : -1;
}
}
Tested with:
/**
* Sort by count. Highest count first.
*/
public function testSortByCount() {
//Jane->count: 200, Blackbeard->count: 100
//jane and blackbeard are mocked "Tags".
$this->tags = array($this->jane, $this->blackbeard);
$expected_order = array("jane", "blackbeard");
$given_order = array();
$this->object->sort("count");
foreach($this->object->get_tags() as $tag) {
$given_order[] = $tag->get_name();
}
$this->assertSame($given_order, $expected_order);
}
But now, I want to add "random ordering"
/**
* Sort random.
*/
public function testSortRandom() {
//what to test? That "shuffle" got called? That the resulting array
// has "any" ordering?
}
The implementation could be anything from calling shuffle($this->tags) to a usort callback that returns 0,-1 or +1 randomly. Performance is an issue, but testability is more important.
How to test that the array got ordered randomly? AFAIK it is very hard to stub global methods like shuffle.
Assuming you are using shuffle your method should look like this
sortRandom() {
return shuffle($this->tags);
}
Well, you don't need to test if keys are shuffled but if array is still returned.
function testSortRandom(){
$this->assertTrue(is_array($this->object->sortRandom()));
}
You should test your code, not php core code.
This is actually not really possible in any meaningful sense. If you had a list with just a few items in, then it'd be entirely possible that sorting by random would indeed look like it's sorted by any given field (and as it happens the odds of it being in the same order as sorting by any other field are pretty high if you don't have too many elements)
Unit testing a sort operation seems a bit daft if you ask me though if the operation doesn't actually manipulate the data in any way. Feels like unit testing for the sake of it rather than because it's actually measuring that something works as intended.
I decided to implement this with a global-wrapper:
class GlobalWrapper {
public function shuffle(&$array);
shuffle($array);
}
}
In the sort, I call shuffle through that wrapper:
public function sort($by_property) {
if ($by_property == "random") {
$this->global_wrapper()->shuffle($this->tags);
}
//...
}
Then, in the tests I can mock that GlobalWrapper and provide stubs for global functions that are of interest. In this case, all I am interested in, is that the method gets called, not what it outputs[1].
public function testSortRandomUsesShuffle() {
$global = $this->getMock("GlobalWrapper", array("shuffle"));
$drupal->expects($this->once())
->method("shuffle");
$this->object->set_global_wrapper($drupal);
$this->object->sort("random");
}
[1] In reality I have Unit Tests for this wrapper too, testing the parameters and the fact it does a call-by-ref. Also, this wrapper was already implemented (and called DrupalWrapper) to allow me to stub certain global functions provided by a third party (Drupal). This implementation allows me to pass in the wrapper using a set_drupal() and fetch it using drupal(). In above examples, I have called these set_global_wrapper() and global_wrapper().
I would like to check to make sure two fields are not equal and one is greater then the other. Say yearBorn and yearMarried. They cannot be equal and yearMarried must be greater then yearBorn.
You can use a 2-parameter custom validator that has access to both the value being validated and the entire instance:
static constraints = {
yearMarried validator: { year, instance ->
if (year == instance.yearBorn) {
return 'i18n.code.for.equal.value'
}
if (year <= instance.yearBorn) {
return 'i18n.code.for.born.after.married'
}
}
}