Groovy pointer to list - groovy

As I'm totally new to Groovy I have this problem I don't know how to solve:
I wan't to get a new value from a list, which list is depending of the value of the input string:
Simplified Example:
class NewStringValue
{
def getValue (inpList)
{
def list1 = ["L1V1","L1V2","L1V3"];
def list2 = ["L2V1","L2V2","L2V3","L2V4"];
def worklist = Here is my problem, how do I get Worklist to point to the correct list according to the value in InpList, see calling ex. below?
def i = 0;
def j = worklist.size-1;
while (i<=j)
{
// some code.......
newValue = worklist[i];
}
return newValue;}
Example of calling above
value = getValue("list1")

You can use a map, and look up the values based on the key passed in:
class NewStringValue {
def getValue(inpList) {
def lookup = [
list1: ["L1V1","L1V2","L1V3"],
list2: ["L2V1","L2V2","L2V3","L2V4"]
]
def worklist = lookup[inpList]
def newValue = ''
worklist.each {
newValue += it
}
newValue
}
}
new NewStringValue().getValue('list2')

Related

Jmeter Groovy creating new list by iterting from previous list

I have a list (tsts) which is dynamic and derived in separation operation but can look like below.
I would like to iterate through tsts and create a new list --> list1, only picking up up to say up to index 2. I have tried the for loop and even--> tsts.eachWithIndex { item, index -> for some reason my list1 only contains the last item?
import org.apache.jmeter.util.JMeterUtils;
import groovy.json.JsonSlurper;
def jsonResponse = null;
List<String> tsts = new ArrayList<String>()
tsts = [10, 11, 12];
str1 = "abc"
def map1 = [:]
def list1 = []
int TCcntr = 2;
cnt1 = 0
System.out.println("1 My Loop begins----------------");
for(int i = 0;i<TCcntr;i++) {
map1.clear()
map1.put(str1,tsts[cnt1].toInteger());
System.out.println("map1----> "+map1);
// list1.add(map1);
list1 = list1+map1;
System.out.println("list---> "+list1);
cnt1 = cnt1+1;
}
My output
1 My Loop begins----------------
map1----> [abc:10]
list---> [[abc:10]]
map1----> [abc:11]
list---> [[abc:11], [abc:11]]
why does list 1 keep picking up the last item iteration? it should look like this
list1----> [[abc:10], [abc:11]]
This worked, Thanks to Dimitri and Tim, I also learned other methods
tsts = [10, 11, 12, 13];
str1 = "abc"
def list1 = []
int TCcntr = 3;
for(int i = 1;i<TCcntr;i++) {
map1 =[:]
map1.put(str1,tsts[i].toInteger());
list1 = list1+map1;
}
output
list---> [[abc:11], [abc:12]]

Groovy create list of 2 maps from string

Hi i have this String which contains List of 2 strings. These 2 strings then contain 2 maps.
Example def listStr = '["{"isReal":true,"area":"a"}","{"isRefundable":false,"area":"b"}"]';
How can i get from this string list of 2 maps?
Result [{isReal=true},{isRefundable=false}]
JsonSlurper can do the job for you:
import groovy.json.JsonSlurper
JsonSlurper js = new JsonSlurper()
def listStr = '["{"isReal":true}","{"isRefundable":false}"]'
def res = []
listStr.eachMatch( /"(\{[^\{\}]+\})"/ ){ res << js.parseText( it[ 1 ] ) }
assert [[isReal:true], [isRefundable:false]] == res
If you want to have a map in the output, you can trasnform the res like:
Map map = res.collectEntries{ it }
assert [isReal:true, isRefundable:false] == map

Dictionary with functions versus dictionary with class

I'm creating a game where i have the data imported from a database, but i have a little problem...
Currently i get a copy of the data as a dictionary, which i need to pass as argument to my GUI, however i also need to process some data, like in this example:
I get the data as a dict (I've created the UseDatabase context manager and is working):
def get_user(name: str, passwd: str):
user = {}
user['name'] = name
user['passwd'] = passwd
with UseDatabase() as cursor:
_SQL = "SELECT id, cash, ruby FROM user WHERE name='Admin' AND password='adminpass'"
cursor.execute(_SQL)
res = cursor.fetchall()
if res:
user['id'] = res[0][0]
user['cash'] = res[0][1]
user['ruby'] = res[0][2]
return user
return res
.
.
.
def get_activities():
with UseDatabase() as cursor:
_SQL = "SELECT * FROM activities WHERE user_id='2'"
cursor.execute(_SQL)
res = cursor.fetchall()
if res:
ids = [i[0] for i in res]
activities = {}
for i in res:
activities[i[0]] = {'title':i[1],'unlock':i[2],'usr_progress':i[3]}
return (ids, activities)
return res
Need it as a dict in my GUI ("content" argument):
class SideBar:
def __init__(self, screen: 'pygame.display.set_mode()', box_width: int, box_height: int, content: dict, font: 'font = pygame.font.Font()'):
#content dict: {id: {'title':'','unlock':'','usr_progress':''},...}
self.box_width = box_width
self.box_height = box_height
self.box_per_screen = screen.get_height() // box_height
self.content = content
self.current_box = 1
self.screen = screen
self.font = font
self.generate_bar()
def generate_bar (self):
active = [i for i in self.content.keys() if i in range(self.current_box, self.current_box+self.box_per_screen)]
for i in range(self.box_per_screen):
gfxdraw.box(self.screen,pygame.Rect((0,i*self.box_height),(self.screen.get_width()/3,self.screen.get_height()/3)),(249,0,0,170))
self.screen.blit(self.font.render(str(active[i]) + ' - ' + self.content[active[i]]['title'], True, (255,255,255)),(10,i*self.box_height+4))
for i in range(self.box_per_screen):
pygame.draw.rect(self.screen,(50,0,0),pygame.Rect((0,i*self.box_height),(self.screen.get_width()/3,self.screen.get_height()/3)),2)
But still need to make some changes in the data:
def unlock_act(act_id):
if user['cash'] >= activities[act_id]['unlock'] and activities[act_id]['usr_progress'] == 0:
user['cash'] -= activities[act_id]['unlock']
activities[act_id]['usr_progress'] = 1
So the question is: in this situation should i keep a copy of the data as dict, and create a class with it plus the methods i need or use functions to edit the data inside the dict?

Read files in folder and then do something by groovy

I have write a script to read the file and then do something from specified path:
def file = new File(/"a.txt"/)
def s = []
s = file.filterLine { it.contains("project ")}
def array = []
def a = []
array << s.toString().split(/(<|=|:|"|,|\/>)/)
a = array.find{ it.contains("SYN_3-1_M5_integration")}
b = a.findAll { it.startsWith("SYN_3")}
println b.unique()
I just want to asked if I have a lot of txt file how can I use above code. I am a newbie in Groovy. Thanks in advance!
The following piece of code should do the job:
import groovy.io.FileType
new File('PATH_TO_FOLDER').eachFile(FileType.FILES) { file ->
def s = []
s = file.filterLine { it.contains("project ")}
def array = []
def a = []
array << s.toString().split(/(<|=|:|"|,|\/>)/)
println array.toString()
a = array.find{ it.contains("SYN_3-1_M5_integration")}
println a
b = a.findAll { it.startsWith("SYN_3")}
println b.unique()
}
Basically it iterates over each file in folder specified with PATH_TO_FOLDER and do the processing in the way it was posted.

Create Map from existing Map in Groovy

I have a Map
[email:[hus#gmail.com, vin#gmail.com], jobTitle:[SE, SD], isLaptopRequired:[on, on], phone:[9908899876, 7765666543], name:[hus, Vin]]
for which i need to have a another Map like
[hus:[hus#gmail.com,SE,99087665343],vin:[vin#gmail.com,SE,7765666543]]
How can do it in Groovy?
You could do it like:
def map = [email:['hus#gmail.com', 'vin#gmail.com'], jobTitle:['SE', 'SD'], isLaptopRequired:['on', 'on'], phone:['9908899876', '7765666543'], name:['hus', 'Vin']]
def result = [:]
map.name.eachWithIndex { name, idx ->
result << [ (name): map.values()*.getAt( idx ) - name ]
}
assert result == [hus:['hus#gmail.com', 'SE', 'on', '9908899876'], Vin:['vin#gmail.com', 'SD', 'on', '7765666543']]
Or, you could also do:
def result = [map.name,map.findAll { it.key != 'name' }.values().toList().transpose()].transpose().collectEntries()
But this is just less code at the expense of both readability and resource usage ;-)
The most visual solution i have:
def map = [email:['hus#gmail.com', 'vin#gmail.com'], jobTitle:['SE', 'SD'], isLaptopRequired:['on', 'on'], phone:['9908899876', '7765666543'], name:['hus', 'Vin']]
def names = map.name
def emails = map.email
def jobTitles = map.jobTitle
def isLaptopRequireds = map.isLaptopRequired //sorry for the variable name
def phones = map.phone
def result = [:]
for(i in 0..names.size()-1) {
result << [(names[i]): [emails[i], jobTitles[i], isLaptopRequireds[i], phones[i]]]
}
assert result == [hus:['hus#gmail.com', 'SE', 'on', '9908899876'], Vin:['vin#gmail.com', 'SD', 'on', '7765666543']]
}

Resources