How to cast query string to int in Integration Request Body Mapping template? - velocity

#set($a = 10)
#set($b = 123)
#set($c = 456)
// If query string "q1" is not available then set $q1,$q2 to default values
#if($!input.params('q1') && $input.params('q1').empty)
#set($q1 = $b)
#set($q2 = $c)
// If query string "q1" available but not "q2" then add some value to $q1 and set it as $q2
#elseif($!input.params('q2') && $input.params('q2').empty)
#set($q1 = $input.params('q1'))
#set($q2 = $a + $q1 )
// If both query strings available then set them
#else
#set($q1 = $input.params('q1'))
#set($q2 = $input.params('q2'))
#end
I'm triying the above code in Integration request body mapping template. In second case where only q1 is specified as some number (let's say 10) then $q2 should be 22( 12 + 10) but it's becoming as 1210, I assume this is because those $q1 and $q2 are strings and they are getting combined.
So I tried to cast them using this answer, but I'm getting internal server error.
How can I cast string to int and them as integers?

The solution given in the other question works for me. Try this (just the second part of if-else):
#set($a = 10)
#set($q1 = $input.params('q1'))
#set($Integer = 0)
#set($q2 = $Integer.parseInt($q1) + $a)
{
"params" : {
"a" : "$a",
"q1" : "$q1",
"q2" : "$q2"
}
}

Related

Using List inside a postgres Query

i have a dynamic list.
list=['a','b','c','d' ..... ] so length may change
i want to compare these list values in a query
select * from student where name in(all the list values);
i want to pass list values into this query
how i can do this.. ??? please help
Thank you
In Postgres, you can use arrays. The syntax in the where clause looks like:
where name = any (array[1, 2, 3])
or
where name = any (list_parameter)
You can write a function that gets a list as a parameter and return a string like "'one', 'two','three'".
// need a string like this 'one', 'two'
private String arrayToSqlInChecker(List<String> loc_list) {
StringBuilder value = new StringBuilder("");
for (int i = 0; i < loc_list.size(); i++) {
value.append("'" + loc_list.get(i) + "'");
if (i != loc_list.size() - 1) {
value.append(",");
}
}
return value.toString();
}
And then you have to append this string into you PostgreSQL IN query
"id IN (" + this.arrayToSqlInChecker(loc_list) + ")"
You can also handle null or empty values in the function

Easiest way of defining and using of Global Variable

"first part" &&&& fun _ ->
let ident
"second part" &&&& fun _ ->
ident ....
I need to use variable "ident".
I just need to pass value of variable from first part of test to second one...
I want to ask you if there is any easy way how to define and use global variable or even if you have better (and easy) idea of doing that
Keep in mind, please, that I am a beginner, so I would prefer easier ones.
Global variables will often make your code difficult to work with - particularly if they are mutable.
Instead, consider returning the values you need to keep track of as composite values. An easy data type to start with would be a tuple:
let ``first part`` id =
let someOtherValue = "Foo"
someOtherValue, id + 1
This function takes an int (the current ID) as input, and returns string * int (a tuple where the first element is a string, and the second element and int) as output.
You can call it like this:
> let other, newId = ``first part`` 42;;
val other : string = "Foo"
val newId : int = 43
Notice that you can use pattern matching to immediately destructure the values into two named symbols: other and newId.
Your second function could also take an ID as input:
let ``second part`` id otherArgument =
// use id here, if you need it
"Bar"
You can call it like this, with the newId value from above:
> let result = ``second part`` newId "Baz";;
val result : string = "Bar"
If you find yourself doing this a lot, you can define a record for the purpose:
type Identifiable<'a> = { Id : int; Value : 'a }
Now you can begin to define higher-order functions to deal with such a type, such as e.g. a map function:
module Identifiable =
let map f x = { Id = x.Id; Value = f x.Value }
// Other functions go here...
This is a function that maps the Value of an Identifiable from one value to another, but preserves the identity.
Here's a simple example of using it:
> let original = { Id = 42; Value = "1337" };;
val original : Identifiable<string> = {Id = 42;
Value = "1337";}
> let result' = original |> Identifiable.map System.Int32.Parse;;
val result' : Identifiable<int> = {Id = 42;
Value = 1337;}
As you can see, it preserves the value 42, but changes the Value from a string to an int.
You can still change the ID explicitly, if you want to do that:
> let result'' = { result' with Id = 7 };;
val result'' : Identifiable<int> = {Id = 7;
Value = 1337;}
Since this was getting out of hand for comments this is how I would do it for an example
let mutable t = 0
let first =
t <- 1 + 1
//other stuff
let second =
//can use t here and it will have a value of 2
In some cases you have to use a ref:
let t = ref 0
let first =
t := 1 + 1
//other stuff
let second =
//can use t here and it will have a value of 2 -
// you use "!t" to get the value
If you define ident at the top of your file like this :
let ident = "foo"
// rest of your code using ident
ident are global and you can use in the next part of your file.
EDIT :
If ident wil change in the next part of your code, use this :
let ident = ref "foo"

DataContext.ExecuteQuery<object> returns object {}

I'm trying to write function for selecting optional columns in linq(columns that may not exist). The problem is in linq like this:
using (DataDataContext db = new DataDataContext()){
var collection = from t in table
select new
{
Nonoptional = t.A;
Optional = IsInDB("table","B") ? t.B : -1; //this is optional column
}}
Unfortunately, this won't work because the fragment near Optional will be translated to case statement and error arises that column not exists.
So i decided to "cover" it with function:
using (DataDataContext db = new DataDataContext()){
var collection = from t in table
select new
{
Nonoptional = t.A;
Optional = IsInDB("table","B") ? OptionalColumnValue<int>("table","B","id_table",t.id_table) : -1; //this is optional column
}}
I want this function to be universal. It should work like that" If there is no value or column is nullable and value is null then return default value for type.
I came up with something like this:
//table,column - obvious,id_column - PK column of table, id - id of currently processing record
public static T OptionalColumnValue<T>(string table,string column,string id_columm,int id) T t = default(T);
DataDataContext db = new DataDataContext();
IEnumerable<object> value = db.ExecuteQuery<object>("select " + column + " from " + table + " where " + id_columm + " = " + id.ToString());
List<object> valueList = value.ToList();
if (valueList.Count == 1)//here is the problem
t = (T)valueList.First();
return t;
}
When there is null value db.ExecuteQuery return something like object{}. I'm assuming this is "empty" object,with nothing really in there. I was thinking about checking for "emptiness" of this object( BTW this is not DBull).
When i realised that this is no way either with concrete value in this column(it cannot cast it to return correct type), then I tried db.ExecuteQuery<T>. Then concrete value - OK, null - Exception.
I thought, maybe Nullable<T> as return value. Nop, because string also can be T.
I don't know what to do next. Maybe there's another solution to this problem.

Cache a variable in groovy

When I try to access the len-variables at the end of the script I get this error: "Cannot iterate twice! If you want to iterate more that once, add _CACHE explicitely."
How can I fix that?
def src_str = query_string
def src_arr = src_str.split(' ')
def trg_arr = doc['my_index'].values
trg_arr_sorted = [:]
trg_arr.each {
_index['my_index'].get(it, _POSITIONS).each { pos ->
trg_arr_sorted[pos.position] = it
}
}
src_len = src_arr.length
def trg_len = trg_arr_sorted.size()
int[][] matrix = new int[src_len + 1][trg_len + 1]
(src_len + 1).times { matrix[it][0] = it }
(trg_len + 1).times { matrix[0][it] = it }
(1..src_len).each { i ->
(1..trg_len).each { j ->
matrix[i][j] = [matrix[i-1][j] + 1, matrix[i][j-1] + 1,
src_arr[i-1] == trg_arr_sorted[j-1] ? matrix[i-1][j-1] : matrix[i-1][j-1] + 1].min()
}
}
return 100 - (100 * matrix[src_len][trg_len] / max(src_len, trg_len)) // over here !!!
The code calculates a score using the levenshtein distance computed in words. It works perfect except of the scoring in the last line.
Okay problem is solved.
I explicitly had to declare cache and positions:
_index['lang'].get(it, _POSITIONS | _CACHE)
The error wasn't in the last line, but I thought so. I changed the script to debug it, but elasticsearch doesn't reload the new scipt instantly.

Formatted date filter in CGridView

I display my date in CGridView as: "22.6.2012 22:53" with:
array('name' => 'date',
'value' => date("j.n.Y G:i", strtotime($model->date))
),
But in my filter, I need to search in this format (which is in the database) to get results: "2012-06-22 22:53".
How can I make my filter to work in the format that is displayed in my CGridView? I've searched for an answer but haven't found one, I've also tried adding the date function in my model search() for this attribute:
$criteria->compare('date', date("j.n.Y G:i", strtotime($this->date), true);
but then I just get an empty list :)
Help would be greatly appreciated.
To begin with, you should not be using the value property to control the formatting of dates. The proper way is to set the type property to 'date' and, if you do not do this already, set CApplication.language to target the appropriate locale.
For the filter it would be best for the user if you use a CJuiDatePicker widget to let the user visually pick the date; there's a short and to-the-point guide on how to do that here.
Update:
Formatting columns with type == 'date' is done through CGridView.formatter, for which if you do not explicitly set a value the default is whatever the 'format' application component is. So you can specify and configure a CFormatter on the spot, or if you want to use the application's formatter but with slight modifications you can do
$formatter = clone Yii::app()->format;
$formatter->dateFormat = 'whatever'; // or $formatter->dateTimeFormat
and then assign this instance to CGridView.formatter.
compare() makes a sql sentence with the input, so I had to change the input to my wanted format.
my function:
function changeDateToDBformat($datum) {
if (strstr($datum, '.') || strstr($datum, ':')) {
$formats = array('!j.n', '!j.n.Y', '!j.n.Y H:i', '!n.Y H:i', '!n.Y', '!H:i', '!j.n.Y H', '!n.Y H', '!Y H:i', '!Y H');
$date = false;
foreach ($formats as $format) {
$date = DateTime::createFromFormat($format, $datum);
if (!($date === false)) {
$izbraniFormat = $format;
break;
}
}
if (!$date === false) {
$datum1 = $date->format('Y-m-d H:i');
$date2 = DateTime::createFromFormat(substr($izbraniFormat, 1, strlen($izbraniFormat)), $datum);
$datum2 = $date2->format('Y-m-d H:i');
$datumcas1 = explode(' ', $datum1);
$datumcas2 = explode(' ', $datum2);
$prvidatum = explode('-', $datumcas1[0]);
$drugidatum = explode('-', $datumcas2[0]);
$koncniDatum = '';
for ($a = 0; $a < sizeof($prvidatum); $a++) {
if ($prvidatum[$a] == $drugidatum[$a])
$koncniDatum .= '-' . $prvidatum[$a];
}
$koncniCas = '';
$prvicas = explode('-', $datumcas1[1]);
$drugicas = explode('-', $datumcas2[1]);
for ($a = 0; $a < sizeof($prvicas); $a++) {
if ($prvicas[$a] == $drugicas[$a])
$koncniCas .= ':' . $prvicas[$a];
}
$koncniDatum = substr($koncniDatum, 1, strlen($koncniDatum));
if (strlen($koncniCas) > 0)
$koncniDatum .= ' ' . substr($koncniCas, 1, strlen($koncniCas));
$datum = $koncniDatum;
}
}
return $datum;
}
//translations:
//izbrani == selected
//datum == date
//cas == time
//koncni == end
//prvi == first
//drugi == second
With this, a user can enter date in the format "j.n.Y H:i" and also just portions of this format (j.n, n.Y, Y H:i,...).
I would like to thank Jon and nickb for help! link
Like many others I also struggled with this, well displaying the grid wasn't the problem, but filtering in the localized datetime was!
So I created my own formatter, used it in the search() function of my models (when passing the search parameters to compare()) and it works like a charm.
I can now filter on date/datetime fields in any localization (I use Dutch):
"30-12-2018" becomes "2018-12-30"
">30-12-2018" becomes ">2018-12-30"
"30-12-2018 23:59:49" becomes "2018-12-30 23:59:49"
">=30-12-2018 23:59:49" becomes ">=2018-12-30 23:59:49"
My localization:
// dateFormat['short'] = 'dd-MM-yyyy'
// timeFormat['medium'] = 'HH:mm:ss'
Yii::app()->format->datetimeFormat = strtr(Yii::app()->locale->dateTimeFormat,
array("{0}" => Yii::app()->locale->getTimeFormat('medium'),
"{1}" => Yii::app()->locale->getDateFormat('short')));
Yii::app()->format->dateFormat = 'short';
Yii::app()->format->timeFormat = 'medium';
My CGridView contains the following date time column:
'mutation_date_time:dateTime'
And (a snippet of) my own formatter with some handy functions:
class Formatter extends CLocalizedFormatter
{
public function formatWithoutSearchOperator($value)
{
// This snippet is taken from CDbCriteria->compare()
if(preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/',$value,$matches))
{
$value=$matches[2];
$op=$matches[1];
}
else
$op='';
return $value;
}
public function formatOnlySearchOperator($value)
{
// This snippet is taken from CDbCriteria->compare()
if(preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/',$value,$matches))
{
$value=$matches[2];
$op=$matches[1];
}
else
$op='';
return $op;
}
/*
* Format a localized datetime back to a database datetime (Y-m-d H:i:s).
* If a comparison operator is given, it is preserved. So strip it if you need to save the date in the database.
* If no time given, it's also not returned (MySQL database appends '00:00:00' as time to it upon saving).
* With this function the following localized datetimes just work like the stock datetime filters:
* - "30-12-2018" becomes "2018-12-30"
* - "30-12-2018 " becomes "1970-01-01" (note the extra space in input)
* - ">30-12-2018" becomes ">2018-12-30"
* - "30-12-2018 23:59:49" becomes "2018-12-30 23:59:49"
* - ">=30-12-2018 23:59:49" becomes ">=2018-12-30 23:59:49"
*
* For save() and afterFind() integration see:
* https://github.com/YetOpen/i18n-datetime-behavior
*/
public function formatToDatabaseDatetime($value)
{
// get the comparison operator from the string:
$comparator = $this->onlySearchOperator($value);
// get the datetime without the comparison operator:
$datetime = $this->withoutSearchOperator($value);
// parse the given datetime according to the locale format to a timestamp
$datetime_parsed = CDateTimeParser::parse(
$datetime,
strtr(
Yii::app()->locale->datetimeFormat,
array(
"{0}" => Yii::app()->locale->getTimeFormat(Yii::app()->format->timeFormat),
"{1}" => Yii::app()->locale->getDateFormat(Yii::app()->format->dateFormat)
)
)
);
// if its not a valid date AND time, check if it can be parsed to a date only:
if($datetime_parsed === false)
{
$date_parsed = CDateTimeParser::parse(
$datetime,
Yii::app()->locale->getDateFormat(Yii::app()->format->dateFormat)
);
}
// If no time part given, also output only the date
if($datetime_parsed===false)
{
$transformed = date(
'Y-m-d',
$date_parsed
);
}
else
{
$transformed = date(
'Y-m-d H:i:s',
$datetime_parsed
);
}
return $comparator . $transformed;
}
}
And within my search() function in my CActiveRecord model I use the following to compare the localized datetime with the records in the database:
$criteria->compare('mutation_date_time',Yii::app()->format->toDatabaseDateTime(trim($this->mutation_date_time)),true);
Please note the trim() there, that's by design (see function description formatToDatabaseDateTime()).
A big difference with filtering directly in correct database format: an invalid date converts to "1970-01-01"!
I highly appreciate feedback and I really hope my code helps somebody!