Add map elements to list with a loop - list

I am trying to populate a list with maps created from objects in a query/findAllBy... I always end up with list of maps identical to the last map in the loop.
I have set break points and stepped through the method and found that 1) the data returned from the query is correct, 2) as I step through the loop the data is inserted into the map(s) correctly, 3) the failure comes when inserting the map into the list. All the methods I've used to insert elements into a list (.add, .push, <<, list[(i)] = map, etc) end up overwriting all the previous elements in the list.
Please help. I don't know why this is happening. Hopefully this is an easy one for someone out there.
def shiftRecords = Shift.findAllByUserAndStartTimeBetween( userInstance, startDate, endDate )
ArrayList allShifts = new ArrayList()
LinkedHashMap thisShift = new LinkedHashMap()
def size = shiftRecords.size()
for ( int i = 0; i < size; i++ ){
thisShift["id"] = shiftRecords[(i)].id
thisShift["user"] = shiftRecords[(i)].user
thisShift["startTime"] = shiftRecords[(i)].startTime
thisShift["posCode"] = shiftRecords[(i)].posCode
thisShift["deptCode"] = shiftRecords[(i)].deptCode
thisShift["billingIDX"] = shiftRecords[(i)].billingIDX
Position thisPos = Position.findByPositionCode( thisShift.posCode )
thisShift["posTitle"] = thisPos.shortTitle
thisShift["deptTitle"] = thisPos.departmentTitle
allShifts.add( (i), thisShift )
}
I need the results of allShifts to be a list of maps with the selected data pulled from the Shift query results. I've tried using shiftRecords.each and eachWithIndex. The problem happens with any type of loop at the point where thisShift map is inserted into allShifts. It doesnt just insert one instance of the map, but replaces all list elements with the current thisShift map.

def shiftRecords = Shift.findAllByUserAndStartTimeBetween(
userInstance, startDate, endDate )
ArrayList allShifts = new ArrayList()
def size = shiftRecords.size()
for ( int i = 0; i < size; i++ ){
LinkedHashMap thisShift = new LinkedHashMap()
thisShift["id"] = shiftRecords[(i)].id
thisShift["user"] = shiftRecords[(i)].user
thisShift["startTime"] = shiftRecords[(i)].startTime
thisShift["posCode"] = shiftRecords[(i)].posCode
thisShift["deptCode"] = shiftRecords[(i)].deptCode
thisShift["billingIDX"] = shiftRecords[(i)].billingIDX
Position thisPos = Position.findByPositionCode( thisShift.posCode )
thisShift["posTitle"] = thisPos.shortTitle
thisShift["deptTitle"] = thisPos.departmentTitle
allShifts << thisShift
}
You need to create a new map each time you iterate over shiftRecords. Although, the above code can be overly simplified in groovy as below:
def shiftRecords = Shift.findAllByUserAndStartTimeBetween(
userInstance, startDate, endDate )
def allShifts = []
shiftRecords.each{
def thisShift = [:]
thisShift.id = it.id
thisShift.user = it.user
thisShift.startTime = it.startTime
thisShift.posCode = it.posCode
thisShift.deptCode = it.deptCode
thisShift.billingIDX = it.billingIDX
Position thisPos = Position.findByPositionCode( thisShift.posCode )
thisShift.posTitle = thisPos.shortTitle
thisShift.deptTitle = thisPos.departmentTitle
allShifts << thisShift
}

Try:
def shiftRecords = Shift.findAllByUserAndStartTimeBetween( userInstance, startDate, endDate )
def allShifts = shiftRecords.collect { it ->
def pos = Position.findByPositionCode( it.posCode )
[ id : it.id,
user : it.user,
startTime : it.startTime,
posCode : it.posCode,
deptCode : it.deptCode,
billingIDX : it.billingIDX,
posTitle : pos.shortTitle,
deptTitle : pos.departmentTitle ]
}

Related

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

Assert operator to count before and after from various variable

i have codes to get database records, send test data (not shown in below codes),
and count before/after size.
can i do below assertion to do simple math calculation directly using the printIn result?
assert responseListAfter.size() == responseListBefore.size + results
this is the full codes
//count the DB records which State = New
String dbQuery = "SELECT COUNT(*) as count FROM dispenseorders.dispenseorder where status = 'true'"
List results = CustomKeywords.'swisslog.database.getSQLResults'(GlobalVariable.dbConnString , GlobalVariable.dbUsername , GlobalVariable.dbPassword ,GlobalVariable.dbDriver ,dbQuery )
println results
//Before Refresh. count number of records in Kafka Topic A
def TopicBefore = 'A'
def NewMessageBefore = consumeMessageBefore(TopicBefore)
def responseListBefore = new JsonSlurper().parseText(consumeMessageBefore.getResponseText())
def consumeMessageBefore(def topic) {
WS.sendRequest(findTestObject('Object Repository/Kafka/subscribe_to_topic_A', [('topic_name') : topic, ('KafkaRestName') : GlobalVariable.KafkaRestName
, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
return consumeMessageBefore = WS.sendRequestAndVerify(findTestObject('Object Repository/Kafka/consume_message_from_topic_for_DR',
[('KafkaRestName') : GlobalVariable.KafkaRestName, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
}
println('before Request Refresh: \n' + responseListBefore.size)
WebUI.delay(10)
//after Refresh. count number of records in Kafka Topic A
def TopicAfter = 'A'
def NewMessageAfter = consumeMessageAfter(TopicAfter)
def responseListAfter = new JsonSlurper().parseText(consumeMessageAfter.getResponseText())
def consumeMessageAfter(def topic) {
WS.sendRequest(findTestObject('Object Repository/Kafka/subscribe_to_topic_for_DR', [('topic_name') : topic, ('KafkaRestName') : GlobalVariable.KafkaRestName
, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
return consumeMessageAfter = WS.sendRequestAndVerify(findTestObject('Object Repository/Kafka/consume_message_from_topic_for_DR',
[('KafkaRestName') : GlobalVariable.KafkaRestName, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
}
println('after Request Refresh: \n' + responseListAfter.size)
//check total messages. After Refresh count = Before Refresh count + DB records
assert responseListAfter.size() == responseListBefore.size + results
results is a list, and you need a list size (int) to add it to other ints:
assert responseListAfter.size() == responseListBefore.size() + results.size()

how to add extra price to cart programmatically in prestahop 1.7

Am new to prestashop 1.7. I want to add extra cost for customization product on adding to cart in prestashop 1.7. Please any body help me.
add own customization data to cart.
$idProduct = Tools::getValue('pid'); // for me it's always one
$qty=Tools::getValue('qty'); // always add one item
$token = Tools::getValue('token');
$customData_front = Tools::getValue('front_view');
$customData_back = Tools::getValue('back_view');
$customData = Tools::getValue('customdata');
$attribute =Tools::getValue('id_product_attribute')
if (is_null($this->context->cart->id)) {
$this->context->cart->add();
$this->context->cookie->__set('id_cart', $this->context->cart->id);
}
// get cart id if exists
if ($this->context->cookie->id_cart)
{
$cart = new Cart($this->context->cookie->id_cart);
}
// create new cart if needed
if (!isset($cart) OR !$cart->id)
{
$cart = new Cart($this->context->cookie->id_cart);
$cart->id_customer = (int)($this->context->cookie->id_customer);
$cart->id_address_delivery = (int) (Address::getFirstCustomerAddressId($cart->id_customer));
$cart->id_address_invoice = $cart->id_address_delivery;
$cart->id_lang = (int)($this->context->cookie->id_lang);
$cart->id_currency = (int)($this->context->cookie->id_currency);
$cart->id_carrier = 1;
$cart->recyclable = 0;
$cart->gift = 0;
$cart->add();
$this->context->cookie->id_cart = (int)($cart->id);
}
$product = new Product((int)$idProduct);
if ($attribute > 0) {
$minimal_quantity = (int)Attribute::getAttributeMinimalQty($this->id_product_attribute);
} else {
$minimal_quantity = (int)$product->minimal_quantity;
}
// add customizatated text
$check =serialize($customData);
$id_address_delivery = $cart->id_address_delivery;
$customization = $this->context->cart->addTextFieldToProduct((int)($idProduct), 9, Product::CUSTOMIZE_TEXTFIELD, serialize($customData));
$exising_customization = Db::getInstance()->executeS('SELECT id_customization FROM '._DB_PREFIX_.'customized_data ORDER BY id_customization DESC LIMIT 0,1');
$customization = $exising_customization[0]['id_customization'];
Db::getInstance()->execute('UPDATE ps_customization SET in_cart = 1, id_product_attribute = '.$attribute.',id_address_delivery='.$id_address_delivery.',quantity='.$minimal_quantity.' WHERE id_customization = ' .$customization);
// get product to add into cart
$productToAdd = new Product((int)($idProduct), true, (int)($this->context->cookie->id_lang));
$cart->update();
$this->context->cart->updateQty((int)($qty),(int)($idProduct),(int)($attribute),$customization,'up',(int)($id_address_delivery));
$cart->update();
In that I want add additional cost every customization.

NetSuite - error closing return authorization using web services

Within NetSuite when trying to close out Return Authorization line items i receive the following error message:
INSUFFICIENT_PERMISSION
"You do not have permissions to set a value for element item.quantityreceived due to one of the following reasons: 1) The field is read-only; 2) An associated feature is disabled; 3) The field is available either when a record is created or updated, but not in both cases."
Here is the code:
//Pull down the RA in order to work with the line items in question
RecordRef rec = new RecordRef();
rec.internalId = internalId;
rec.type = RecordType.returnAuthorization;
rec.typeSpecified = true;
ReadResponse response = _service.get(rec);
//create the object from the response record returned
ReturnAuthorization ra = (ReturnAuthorization)response.record;
//cancel the order by updating the qty of each item to zero.
WriteResponse res = null;
ReturnAuthorizationItem[] raItemList = ra.itemList.item;
for (int lineCounter = 0; lineCounter < raItemList.Length; lineCounter++)
{
//only if the qty received is zero are we closing out the item(setting qty to zero)
if (raItemList[lineCounter].quantityReceived == 0)
{
raItemList[lineCounter].quantity = 0;
raItemList[lineCounter].quantitySpecified = true;
}
}
//create a new object and add all the changes in order to update the order lines
ReturnAuthorization updRa = new ReturnAuthorization();
updRa.internalId = internalId;
updRa.itemList = new ReturnAuthorizationItemList();
updRa.itemList.item = new ReturnAuthorizationItem[raItemList.Length];
updRa.itemList.item = raItemList;
res = _service.update(updRa);
I am trying to update the line quantity to zero, which in affect will close the Return Authorization if everything has been zeroed out. Question is how do i correct this permissions issue in order to run this update. I have tried setting other fields on this same call. No matter which field i try and update i get the same error message. This is running under an admin account and all permissions look fine as far as i can see. In fact i am running this very same logic against the SaleOrder object to close out Sales Orders with no issues.
Any help would be much appreciated.
Thanks,
Billy
You can't directly edit that line item field. That field is maintained by Netsuite and reflects Item Receipts received against the RA.
If you want to close the RA without receiving just set the line item column field "Closed" to true.
After looking at this a little closer here is the solution:
Replace the if statement in the loop with this:
//only if the qty received and returned are zero do we close out the item(setting qty to zero)
if (raItemList[lineCounter].quantityReceived == 0 && raItemList[lineCounter].quantityBilled == 0)
{
raItemList[lineCounter].quantity = 0;
raItemList[lineCounter].quantitySpecified = true;
raItemList[lineCounter].isClosed = true;
raItemList[lineCounter].isClosedSpecified = true;
raItemList[lineCounter].quantityReceivedSpecified = false;
raItemList[lineCounter].quantityBilledSpecified = false;
raItemList[lineCounter].costEstimateSpecified = false;
}
else
{
raItemList[lineCounter].quantityReceivedSpecified = false;
raItemList[lineCounter].quantityBilledSpecified = false;
raItemList[lineCounter].costEstimateSpecified = false;
}
I am guessing that the fields i had to specific as false are fields that cannot be edited, hence the need to disclude them from the update.
This is a better sample. Note the comment re orderline
/Pull down the RA in order to work with the line items in question
RecordRef rec = new RecordRef();
rec.internalId = internalId;
rec.type = RecordType.returnAuthorization;
rec.typeSpecified = true;
ReadResponse response = _service.get(rec);
//create the object from the response record returned
ReturnAuthorization ra = (ReturnAuthorization)response.record;
//cancel the order by updating the qty of each item to zero.
WriteResponse res = null;
ReturnAuthorizationItem[] raItemList = ra.itemList.item;
ReturnAuthorization updRa = new ReturnAuthorization();
updRa.internalId = internalId;
updRa.itemList = new ReturnAuthorizationItemList();
ReturnAuthorizationItem[] updateItems = new ReturnAuthorizationItem[raItemList.Length];
for (int lineCounter = 0; lineCounter < raItemList.Length; lineCounter++)
{
updateItems[lineCounter].line = raItemList[lineCounter].line; // you'll need to test this. Setting only the line should result in no changes to the RA line items that are not to be closed. use the &xml=T view before and after to make sure orderline (hidden) is still populated properly.
//only if the qty received is zero are we closing out the item(setting qty to zero)
if (raItemList[lineCounter].quantityReceived == 0)
{
updateItems[lineCounter].isClosed = true;
// raItemList[lineCounter].quantitySpecified = true; // is quantitySpecified a field? it wasn't as of the 2012.2 endpoint
}
}
//create a new object and add all the changes in order to update the order lines
updRa.itemList.item = updateItems;
res = _service.update(updRa);

URLEncode variable Parsing from String to Array as3

Ok! I have a flashVar variable that is coming into Flash, its URL encoded but I have already decoded it. My problem is I want the set of variables to be pushed into an array.
Let's say the variables are
"&text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter
Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
and so on...
What I want is the variables to go into an array like
myArray[0].text = Enter Text...
myArray[0].size = 18]
myArray[0].font = Arial
myArray[0].color = 0
myArray[0].rotation = 0
myArray[0].y = 360
myArray[0].x = 640
myArray[1].text = ...........
.............................
.............................
myArray[n].text = ...........
I think there must be some way to do this. Most probably I'm thinking regular expression, but I'm pretty bad at regular expression. Please some help would be very very appreciated.
Thank You!
You don't have to decode your query string, just use the URLVariables object - it will do all the decoding for you. Then iterate over its dynamic properties to create your array. Use a RegExp to find the index numbers at the end of your variable keys:
function parseURLVariables( query:String ) : Array {
var vars:URLVariables = new URLVariables (query);
var arr:Array = [];
for (var key : String in vars) {
var splitIndex : int = key.search(/[0-9]+$/);
var name:String = key.substr (0,splitIndex);
var indexNumber:int = parseInt ( key.substr(splitIndex));
arr[indexNumber] ||= {};
arr[indexNumber][name] = vars[key];
}
return arr;
}
Since your query string starts with a an ampersand, you might have to use parseURLVariables ( myString.substr(1)), otherwise the URLVariables object will throw an error, complaining that the query string is not valid (it has to be url encoded, and start with a variable key).
you may use split method of string to something like this;
var astrKeyValue: Array = url.Split( "&" );
in this way each value in astrKeyValue is string keyvalue ( for example font1=Arial )
after than you may split each item with "=" and will get pair key and value ( for key - font1 and for value - arial)
so this code maybe will work for you
var str = "text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
var a : Array = str.split( "&" );
var newArr: Array = new Array()
for each ( var str1 in a )
{
var t: Array = str1.split( "=" );
newArr[ t[0] ] = t[1];
}
trace( newArr.text0 ) // -> Enter Text...
Here is a solution for you from me,
//your string data should be like this, there should be a seperate seperator (i've used pipe sign |) for each element which will be converted to an object and then pushed to the array
var strData:String = "text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640|text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640";
var myArray:Array = new Array();
var _tmpArr:Array = strData.split("|");
//populating the array
for(var i:int=0;i<_tmpArr.length;i++)
{
myArray.push(strToObj(_tmpArr[i]));
}
trace(myArray.length);
// coverts chunk of string to object with all key and value in it
function strToObj(str:String):Object
{
var obj:Object = new Object();
var tmpArr:Array = str.split('&');
for (var i:int = 0; i < tmpArr.length; i++)
{
var _arr:Array = String(tmpArr[i]).split('=');
var key:String = String(_arr[0]);
var val:String = String(_arr[1]);
obj[key] = val;
trace(key+" = "+val);
}
trace("----");
return obj;
}