Strange issue on reduce function - mapreduce

I always have reduce issue on practicing, like following map and reduce, if I add more document or add more field to emit in the map and reduce like following. it will return values as [], not sure what occur this?
problemNumber : doc.problemNumber,
UserId: idv,
event : doc.event
......
Map
function(doc) {
if(doc.event){
var idv = null;
for (var idu in doc.Data.users){
if (doc.eventData.users[idu].userTypeCode == "M"){
idv = doc.Data.users[idu].UserId;
}
}
var newDoc = {
problemNumber : doc.problemNumber,
UserId: idv,
event : doc.event
};
emit(null, newDoc);
}
}
Reduce
function(keys, values, rereduce) {
var result = [];
var closeMap = {};
for (var i=0; i<values.length; i++){
var doc = values[i];
if (doc.event=='CLOSE'){
closeMap[doc.problemNumber] = 1;
}
}
for (var i=0; i<values.length; i++){
var doc = values[i];
if (doc.event=='OPEN'){
if (closeMap[doc.problemNumber]){
doc.event = 'CLOSE';
}
result.push(doc);
}
}
return result;
}

Related

Add an another attribute to an existing List in Flutter

I have been trying many ways to add an isChecked: false attribute to every list inside the _filterOptions List in my Flutter Project. I couldn't find any solution to this. If there is any solution I am happy to see it.
List<dynamic> _filters = [];
List<List<dynamic>> _filterOptions =[];
var filters =
await json.decode(data)["getProductsByStore"]["aggregations"];
for(int i = 0; i < filters.length; i++){
_filters.add(filters[i]["label"]);
_filterOptions.add(filters[i]["options"]);
}
//print(filters[0]["options"]);
//print(_filters);
print(_filterOptions);
I am getting this kind of nested list when printed and I want to add the attribute to every list.
as an example:
[[{count: 3, label: 30-40, value: 30_40, isChecked:false}], [{count: 2, label: Bagged , value: 50, isChecked:false},{...},{...}...]]
Create Model class with your data and bool isChecked
class ModelClass{
String? label;
int? count;
List? options;
bool? isChecked;
ModelClass({this.label, this.count , this.options, this.isChecked = false});
ModelClass.fromJson(Map<String, dynamic> json){
label = json['label'];
count = json['count'];
options = json['options'];
}
}
then you can add data like below code
List<ModelClass> list = [];
void function()async{
List<dynamic> _filters = [];
List<List<dynamic>?> _filterOptions =[];
var filters =
await json.decode(data)["getProductsByStore"]["aggregations"];
for(int i = 0; i < filters.length; i++){
ModelClass modelClass = ModelClass.fromJson(filters[i]);
list.add(modelClass);
_filters.add(modelClass.label);
_filterOptions.add(modelClass.options);
}
print(list[0].options);
print(list[0].isChecked);
}
if you want to modify isChecked for some specific index
list[0].isChecked = false;
Just add these lines.
class YourWrapperClass {
YourWrapperClass({this.filterOptions = const [], this.isChecked = false});
List<List<dynamic>> filterOptions;
bool isChecked;
}
YourWrapperClass filterWrapper = YourWrapperClass(filterOptions: _filterOptions, isChecked: false);
And use this wrapper class object whenever ya need to access _filterOptions.
But, I would more rather recommend using the WrapperClass on the list elements, like so.
class YourWrapperClass {
YourWrapperClass({this.filterOption = const [], this.filter="", this.isChecked = false});
List<dynamic> filterOption;
dynamic filter;
bool isChecked;
}
List<YourWrapperClass> list = [];
var filters =
await json.decode(data)["getProductsByStore"]["aggregations"];
for(int i = 0; i < filters.length; i++){
list.add(YourWrapperClass(filterOption:filters[i]["options"], filter:filters[i]["label"], isChecked=false));
_filterOptions.add(filters[i]["options"]);
}

Trying to fill in a List of class

I'm really sorry I'm such a beginner...
At the end I just have a list of 8 TimeCardDayStrip with the same name/position when it'd supposed to be the 8 different names/roles.
I don't understand what I'm doing wrong here:
thank you very much
'''
class TimeCardDayStrip {
String name, position;
DateTime day;
#override
String toString(){
return '{ $this.name, $this.position }';
}
}
void main() {
var tcds = TimeCardDayStrip();
var listOfTcds = [];
List<String> names, roles;
names = ["Michael", "Gunnell", "Byrne", "Aspromonte", "Davis", "Adam Jordan", "Mirko"];
roles = ["Director", "Vice", "President", "1ST", "KEY 2ND", "2ND", "BASECAMP PA", "PA", " PA", "Add'l PA"];
for (int i = 0; i < names.length; i++) {
tcds.name = names[i];
tcds.position = roles[i];
listOfTcds.add(tcds);
// checking the list as it creates
print(listOfTcds[i].name+' is '+listOfTcds[i].position);
}
//print the list of card to check
print('print the list of time card to check');
for (int x = 0; x < listOfTcds.length; x++){
print (listOfTcds.elementAt(x).name);
}
}
'''
If you just want to print out each name:
Put this within the loop (you should create new object each loop instead of updating the same one)
for (int i = 0; i < names.length; i++) {
var tcds = TimeCardDayStrip();
tcds.name = names[i];
tcds.position = roles[i];
listOfTcds.add(tcds);
// checking the list as it creates
print('${listOfTcds[i].name} is ${listOfTcds[i].position}');
}
Then later
listOfTcds[x].name
If you want to display stuff:
#override
Widget build(BuildContext ctx) {
return ListView.builder(
itemCount: listOfTcds.length,
itemBuilder: (context, index) {
return CustomTile(item: listOfTcds[index]);
},
);
}
I believe you need to declare the tcds as Tcds = new TimecardDayStrip() and not just tcds = TimeCardDayStrip() or you are just changing the same object and not creating a new instance.

Replacing Google Doc text with Spreadsheet Data using RegEx

I am making a merge code to take data from my spreadsheet and populate merge tags in a Google Doc. The part of the code I am unable to write correctly is the part that writes the tags back to the Google Doc. I have been able to locate the tags but the code doesn't replace them.
Here is what I've written so far.
function mergeApplication() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Merge Data");
var range = sheet.getActiveRange();
var formSheet = ss.getSheetByName("Form Responses");
var lastRow = formSheet.getLastRow();
var lastColumn = sheet.getMaxColumns();
function checkAndComplete() {
var urlColumn = lastColumn;
var checkColumn = (urlColumn - 1);
var checkRange = sheet.getRange(2, checkColumn, (lastRow - 1), 1);
var check = checkRange.getBackgrounds();
var red = "#ff0404";
var yellow = "#ffec0a";
var green = "#3bec3b";
for (var i = 0; i < check.length; i++) {
if (check[i] == green) {
continue;
} else {
var statusCell = sheet.getRange((i+2), checkColumn, 1, 1);
var urlCell = sheet.getRange((i+2), urlColumn, 1, 1);
var dataRow = sheet.getRange((i+2), 1, 1, (lastColumn - 2));
function mergeTasks() {
function docCreator() {
// var templateConditionRange = sheet.getRange((i+2), column);
// var templateConditionCheck = templateConditionRange.getValues();
var docTemplate1 = DriveApp.getFileById(id);
// var docTemplate2 = DriveApp.getFileById(id);
// var docTemplate3 = DriveApp.getFileById(id);
var folderDestination = DriveApp.getFolderById(id);
var clientName = sheet.getRange((i+2), 3).getValue();
var date = sheet.getRange((i+2), 1).getValue();
// if (templateConditionCheck[i] == "") {
var docToUse = docTemplate1;
// }
// if (templateConditionCheck[i] == "") {
// var docToUse = docTemplate2;
// }
// if (templateConditionCheck[i] == "") {
// var docToUse = docTemplate3;
// }
var docName = "Merge Tester Doc for " + clientName + " [" + date + "]";
var docCopy = docToUse.makeCopy(docName, folderDestination);
var docId = docCopy.getId();
var docURL = DriveApp.getFileById(docId).getUrl();
var docToSend = DriveApp.getFileById(docId);
var docBody = DocumentApp.openById(docId).getBody().getText();
function tagReplace() {
var taggedArray = [docBody.match(/\<{2}[\w\d\S]+\>{2}/g)];
var headerArray = [sheet.getRange(1, 1, 1, (lastColumn - 2)).getValues()];
var dataArray = [dataRow.getValues()];
var strippedArray = [];
Logger.log("The preliminary length of taggedArray is " + taggedArray.length);
Logger.log(taggedArray);
function tagStrip() {
for (var t = 0; t < taggedArray.length; t++) {
var strippedString = taggedArray[t].slice(2, -3).toString();
strippedArray.push(strippedString);
Logger.log("The current strippedArray length is " + strippedArray.length);
}
Logger.log("The final strippedArray length is " + strippedArray.length);
Logger.log("The final taggedArray length is " + taggedArray.length);
Logger.log("The final, completed strippedArray is " + strippedArray);
}
function dataMatch() {
for (var s = 0; s < strippedArray.length;) {
for (var h = 0; h < headerArray.length;) {
if (strippedArray[s] == headerArray[h]) {
docBody.replaceText(taggedArray[s].String(), dataArray[h].String());
h=0;
s++;
} else {
h++;
}
}
}
}
tagStrip;
dataMatch;
}
function emailCreator() {
var emailTag = sheet.getRange((i+2), (urlColumn - 2)).getValue();
var emailBody = HtmlService.createHtmlOutputFromFile("Email Template").getContent();
var personalizers = clientName + " [" + date + "]";
var subject = "Merge Tester Email for " + personalizers;
MailApp.sendEmail(emailTag, subject, emailBody, {
name: "Christopher Anderson",
attachments: [docToSend],
html: emailBody,
});
}
tagReplace();
statusCell.setBackground(yellow);
emailCreator();
urlCell.setValue(docURL)
}
statusCell.setBackground(red);
docCreator();
statusCell.setBackground(green);
}
mergeTasks();
}
}
}
checkAndComplete();
}
The problem section is here:
function tagReplace() {
var taggedArray = [docBody.match(/\<{2}[\w\d\S]+\>{2}/g)];
var headerArray = [sheet.getRange(1, 1, 1, (lastColumn - 2)).getValues()];
var dataArray = [dataRow.getValues()];
var strippedArray = new Array();
Logger.log("The preliminary length of taggedArray is " + taggedArray.length);
Logger.log(taggedArray);
function tagStrip() {
for (var t = 0; t < taggedArray.length; t++) {
var strippedString = taggedArray[t].slice(2, -3).toString();
strippedArray.push(strippedString);
Logger.log("The current strippedArray length is " + strippedArray.length);
}
Logger.log("The final strippedArray length is " + strippedArray.length);
Logger.log("The final taggedArray length is " + taggedArray.length);
Logger.log("The final, completed strippedArray is " + strippedArray);
}
function dataMatch() {
for (var s = 0; s < strippedArray.length;) {
for (var h = 0; h < headerArray.length;) {
if (strippedArray[s] == headerArray[h]) {
docBody.replaceText(taggedArray[s].String(), dataArray[h].String());
h=0;
s++;
} else {
h++;
}
}
}
}
tagStrip;
dataMatch;
}
It doesn't even log anything having to do with strippedArray.
It seems to be skipping over that section entirely.
Am I using the correct method of completing this task and/or is there a simpler way of doing it?
It's worth mentioning that my tags in the doc have 2 "<>" around them. That's the reason for my RegEx looking how it does.
Also, when logging the .length of taggedArray, it returns a value of 1.
You never actually call tagStrip which is supposed to work on strippedArray.
You declare it with function tagStrip(){} and later you reference the function with tagStrip; but you never actually call it. The same is happening with dataMatch.
Try calling the two functions by writing
tagStrip();
dataMatch();
If you don't include the parentheses you don't call it you just run the function Objects as statements.
Here is a portion of code I use in my add-on Simply Send, I use the same <<>> merge tags.
//copy template
var mDocDrive = doc.makeCopy(title, folder);
var mDoc = DocumentApp.openById(mDocDrive.getId());
var mDocDriveApp = DriveApp.getFileById(mDoc.getId());
var docToAttach = mDoc.getUrl();
var driveToShare = mDocDriveApp;
// replace text inside template
var body = mDoc.getBody();
body.replaceText("<<SS Title>>", title);
body.replaceText("<<timestamp>>", lastR.timestamp);
body.replaceText("<<username>>", lastR.email);
for (i in lastR.theResponses){
var cur = lastR.theResponses[i];
var name = cur.title;
name = name.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); // this will allow fields that include special characters.
var response = cur.response;
var searchPattern = "<<"+name+">>";
body.replaceText(searchPattern, response);
}
// this will replace any unused tags with nothing.
var ques = getQuestionList();
for (j in ques){
var curq = ques[j].name;
curq = curq.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var searchPattern2 = "<<"+curq+">>";
body.replaceText(searchPattern2, "");
}
mDoc.saveAndClose();
//create pdf
if (mmDefaults.shareAs == "pdf"){
// uncomment if you want to make the pdf in the merge folder
var asPdf = mDoc.getAs('application/pdf');
asPdf.setName(mDoc.getName()+ ".pdf");
var pdf = DriveApp.createFile(asPdf);
folder.addFile(pdf);
DriveApp.removeFile(pdf);
mDocDriveApp.setTrashed(true);
var docToAttach = pdf;
driveToShare = pdf;
}

How to update record in local storage using ember data and localstorage adapter?

I am new to emberjs and making one simple CRUD application. I am using ember data and localstorage-adapter to save record in local storage of browser.
I am trying to update record using localstorage-adapter but it is throwing error.
I have listed my code here :
updatecontact: function(){//save data in local storage
var fname = this.obj_form_edit_data.get('cont_data.fname');
var lname = this.get('cont_data.lname');
var email = this.get('cont_data.email');
var contactno = this.get('cont_data.contactno');
var gendertype = ((this.get('isMale') == true) ? true : false);
var contactype = $(".selectpicker").val();
Grid.ModalModel.updateRecords({
fname: fname,
lname: lname,
email: email,
contactno: contactno,
gendertype: gendertype,
contactype: contactype
});
this.get('store').commit();
}
I am getting following error using above code :
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this);
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
delete m.proto;
finishChains(this);
this.init.apply(this, arguments);
} has no method 'updateRecords'
I am using following code to create new record which working fine :
savecontact: function(){//save data in local storage
var fname = this.obj_form_edit_data.get('cont_data.fname');
var lname = this.obj_form_edit_data.get('cont_data.lname');
var email = this.obj_form_edit_data.get('cont_data.email');
var contactno = this.obj_form_edit_data.get('cont_data.contactno');
var gendertype = ((this.get('isMale') == true) ? true : false);
var contactype = $(".selectpicker").text();
Grid.ModalModel.createRecord({
fname: fname,
lname: lname,
email: email,
contactno: contactno,
gendertype: gendertype,
contactype: contactype
});
this.get('store').commit();
}
You're using updateRecords as a plural, it should be updateRecord

computed properties not getting updated

Problem: the computed property "tnop" does not get updated when the controller modifies the "pages" array as shown below:
relevant book model code:
sections: []
tnop: function()
{
var n = 0;
var sections = this.get('sections');
if (!sections)
return n;
for (var i=0; i < sections.length; i++) {
n += sections[i].pages.length;
}
return n;
}.property('sections.#each.pages.length')
relevant controller code:
var sections = EM.model.getPath('book.sections');
var aps = EM.model.getPath("ps");
$.each(sections, function(si, section) {
var bp = [];
if (json && json.ia) {
bp = section.get("pages");
var ns = aps[json.ssi];
var lp = ns.get("lp");
var rp = ns.get("rp");
if (rp) {
bp.insertAt(lp.number-1, rp);
bp[lp.number-1] = rp;
}
if (lp) {
bp.insertAt(lp.number-1, lp);
bp[lp.number-1] = lp;
}
}
});
As it stands, you can't observe deeply nested paths off #each directly. Instead, you have to use nested #each proxies, as such:
property('sections.#each.pages.#each.length')
Had the same problem solved using with following code:
filters: [],
content: [],
filterFun: function()
{
}.property('content.#each', 'filters.#each').cacheable(),