Has anyone converted charts from AnyChart over to Google Charts? I'm trying to convert a table in a Grails project.
I can get the table to appear just fine along with some hard coded date but I can't get my array of data to appear. The concept of data between the two seem to be totally incompataible.
In AnyChart I could just do this and then add the data to the table.
var tableData = [
[null],
["Cheapest"],
["Highest"],
["Average"],
["Median"],
["Options"],
["Avg/50"],
["Stops [stops:total]"],
["Cheapest/Stops"],
["Star Profile Totals"],
["Cheapest Star Profiles"],
["GDS ID Totals"],
["Cheapest/GDS ID"],
["DynamicPrice Totals"],
["PRV Pricing Totals"],
["PUB Pricing Totals"],
["Cheapest/PricingType"],
["Contract Type Totals"],
["Cheapest/Contract"],
["CabinType Totals"],
["Cheapest/CabinType"],
["Arrival Port Totals"],
["Departure Port Totals"],
["Carrier Totals"],
["Cheapest/Carrier"],
["Avg Commission/Profile"],
["Itins w/Dyn Discount"],
["Opaque Totals"],
["Cheapest/Opaque"],
["Searched Contracts"]
];
var url1 = "${apiInstanceList[-1].serverName}";
var url2 = "${apiInstanceList[-2].serverName2}";
// now set up the data for the table
tableData.forEach(function(d){
<g:each in="${apiInstanceList.size() >= 2 ? apiInstanceList[-2..-1] : apiInstanceList}" var="apiInstance">
if (d[0] == null){
var url = url1;
d.push(d[1] == url ? url2 : url);
}else if(d[0] === "Cheapest" && ${apiInstance.cheapestPrice}){
d.push("$"+${apiInstance.cheapestPrice});
} else if (d[0] === "Highest") {
d.push("$"+${apiInstance.highestPrice});
} else if (d[0] === "Average"){
d.push("$"+${apiInstance.averagePrice});
} else if (d[0] === "Median"){
d.push("$"+${apiInstance.medianPrice});
} else if (d[0] === "Options"){
d.push(${apiInstance.totalOptions});
} else if (d[0] === "Avg/50") {
d.push("$"+${apiInstance.avg50});
} else if (d[0] === "Stops [stops:total]") {
var aoo = "${apiInstance.numberOfStops}";
d.push(aoo);
} else if (d[0] === "Star Profile Totals") {
var boo = "${apiInstance.profileNumbers}";
d.push(boo);
} else if (d[0] === "Cheapest/CabinType") {
var coo = "${apiInstance.cheapestByCabin}";
d.push(coo);
} else if (d[0] === "Contract Type Totals") {
var doo = "${apiInstance.contractTypeNumbers}";
d.push(doo);
} else if (d[0] === "DynamicPrice Totals") {
var eoo = "${apiInstance.dynamicNumbers}";
d.push(eoo);
} else if (d[0] === "PRV Pricing Totals") {
var foo = "${apiInstance.privatePricingTypeNumbers}";
d.push(foo);
} else if (d[0] === "PUB Pricing Totals") {
var goo = "${apiInstance.publicPricingTypeNumbers}";
d.push(goo);
} else if (d[0] === "Cheapest/PricingType") {
var ioo = "${apiInstance.cheapestByPassengerType}";
d.push(ioo);
} else if (d[0] === "CabinType Totals") {
var hoo = "${apiInstance.cabinNumbers}";
d.push(hoo);
} else if (d[0] === "Cheapest/Contract") {
var koo = "${apiInstance.cheapestByContractType}";
d.push(koo);
} else if (d[0] === "Arrival Port Totals") {
var loo = "${apiInstance.arrivalAirportTotals}";
d.push(loo);
} else if (d[0] === "Departure Port Totals") {
var moo = "${apiInstance.departureAirportTotals}";
d.push(moo);
} else if (d[0] === "Carrier Totals") {
var soo = "${apiInstance.carrierNumbers}";
d.push(soo);
} else if (d[0] === "Cheapest/Carrier") {
var too = "${apiInstance.cheapestByCarrier}";
d.push(too);
} else if (d[0] === "Cheapest Star Profiles") {
var noo = "${apiInstance.cheapestByProfileId}";
d.push(noo);
} else if (d[0] === "Cheapest/Stops") {
var ooo = "${apiInstance.cheapestByStops}";
d.push(ooo);
} else if (d[0] === "GDS ID Totals") {
var poo = "${apiInstance.gdsIdNumbers}";
d.push(poo);
} else if (d[0] === "Cheapest/GDS ID") {
var qoo = "${apiInstance.cheapestByGdsID}";
d.push(qoo);
} else if (d[0] === "Avg Commission/Profile") {
var roo = "${apiInstance.averageCommissionByStarProfileId}";
d.push(roo);
} else if (d[0] === "Itins w/Dyn Discount") {
var too = "${apiInstance.dynamicDiscountTotal}";
d.push(too)
} else if (d[0] === "Opaque Totals") {
var uoo = "${apiInstance.opaqueTotals}";
d.push(uoo)
} else if (d[0] === "Cheapest/Opaque") {
var voo = "${apiInstance.cheapestByOpaqueType}";
d.push(voo)
} else if (d[0] === "Searched Contracts") {
var soo = "${apiInstance.searchedContracts}";
d.push(soo);
}
</g:each>
});
But google charts are different. Hard coded it looks like this:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time Employee');
data.addRows([
['Mike', {v: 10000, f: '$10,000'}, true],
['Jim', {v:8000, f: '$8,000'}, false],
['Alice', {v: 12500, f: '$12,500'}, true],
['Bob', {v: 7000, f: '$7,000'}, true]
]);
Here is the code:
<script type="text/javascript">
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
//var data = new google.visualization.DataTable();
var tableData2 = new google.visualization.DataTable();
//data.addColumn('string', 'Name');
//data.addColumn('number', 'Salary');
//data.addColumn('boolean', 'Full Time Employee');
//data.addRows([
// ['Mike', {v: 10000, f: '$10,000'}, true],
// ['Jim', {v:8000, f: '$8,000'}, false],
// ['Alice', {v: 12500, f: '$12,500'}, true],
// ['Bob', {v: 7000, f: '$7,000'}, true]
//]);
tableData2 = [
[null],
["Cheapest"],
["Highest"],
["Average"],
["Median"],
["Options"],
["Avg/50"],
["Stops [stops:total]"],
["Cheapest/Stops"],
["Star Profile Totals"],
["Cheapest Star Profiles"],
["GDS ID Totals"],
["Cheapest/GDS ID"],
["DynamicPrice Totals"],
["PRV Pricing Totals"],
["PUB Pricing Totals"],
["Cheapest/PricingType"],
["Contract Type Totals"],
["Cheapest/Contract"],
["CabinType Totals"],
["Cheapest/CabinType"],
["Arrival Port Totals"],
["Departure Port Totals"],
["Carrier Totals"],
["Cheapest/Carrier"],
["Avg Commission/Profile"],
["Itins w/Dyn Discount"],
["Opaque Totals"],
["Cheapest/Opaque"],
["Searched Contracts"]
];
var url1 = "${apiInstanceList[-1].serverName}";
var url2 = "${apiInstanceList[-2].serverName2}";
// now set up the data for the table
tableData2.forEach(function(d){
<g:each in="${apiInstanceList.size() >= 2 ? apiInstanceList[-2..-1] : apiInstanceList}" var="apiInstance">
if (d[0] == null){
var url = url1;
d.push(d[1] == url ? url2 : url);
}else if(d[0] === "Cheapest" && ${apiInstance.cheapestPrice}){
d.push("$"+${apiInstance.cheapestPrice});
} else if (d[0] === "Highest") {
d.push("$"+${apiInstance.highestPrice});
} else if (d[0] === "Average"){
d.push("$"+${apiInstance.averagePrice});
} else if (d[0] === "Median"){
d.push("$"+${apiInstance.medianPrice});
} else if (d[0] === "Options"){
d.push(${apiInstance.totalOptions});
} else if (d[0] === "Avg/50") {
d.push("$"+${apiInstance.avg50});
} else if (d[0] === "Stops [stops:total]") {
var aoo = "${apiInstance.numberOfStops}";
d.push(aoo);
} else if (d[0] === "Star Profile Totals") {
var boo = "${apiInstance.profileNumbers}";
d.push(boo);
} else if (d[0] === "Cheapest/CabinType") {
var coo = "${apiInstance.cheapestByCabin}";
d.push(coo);
} else if (d[0] === "Contract Type Totals") {
var doo = "${apiInstance.contractTypeNumbers}";
d.push(doo);
} else if (d[0] === "DynamicPrice Totals") {
var eoo = "${apiInstance.dynamicNumbers}";
d.push(eoo);
} else if (d[0] === "PRV Pricing Totals") {
var foo = "${apiInstance.privatePricingTypeNumbers}";
d.push(foo);
} else if (d[0] === "PUB Pricing Totals") {
var goo = "${apiInstance.publicPricingTypeNumbers}";
d.push(goo);
} else if (d[0] === "Cheapest/PricingType") {
var ioo = "${apiInstance.cheapestByPassengerType}";
d.push(ioo);
} else if (d[0] === "CabinType Totals") {
var hoo = "${apiInstance.cabinNumbers}";
d.push(hoo);
} else if (d[0] === "Cheapest/Contract") {
var koo = "${apiInstance.cheapestByContractType}";
d.push(koo);
} else if (d[0] === "Arrival Port Totals") {
var loo = "${apiInstance.arrivalAirportTotals}";
d.push(loo);
} else if (d[0] === "Departure Port Totals") {
var moo = "${apiInstance.departureAirportTotals}";
d.push(moo);
} else if (d[0] === "Carrier Totals") {
var soo = "${apiInstance.carrierNumbers}";
d.push(soo);
} else if (d[0] === "Cheapest/Carrier") {
var too = "${apiInstance.cheapestByCarrier}";
d.push(too);
} else if (d[0] === "Cheapest Star Profiles") {
var noo = "${apiInstance.cheapestByProfileId}";
d.push(noo);
} else if (d[0] === "Cheapest/Stops") {
var ooo = "${apiInstance.cheapestByStops}";
d.push(ooo);
} else if (d[0] === "GDS ID Totals") {
var poo = "${apiInstance.gdsIdNumbers}";
d.push(poo);
} else if (d[0] === "Cheapest/GDS ID") {
var qoo = "${apiInstance.cheapestByGdsID}";
d.push(qoo);
} else if (d[0] === "Avg Commission/Profile") {
var roo = "${apiInstance.averageCommissionByStarProfileId}";
d.push(roo);
} else if (d[0] === "Itins w/Dyn Discount") {
var too = "${apiInstance.dynamicDiscountTotal}";
d.push(too)
} else if (d[0] === "Opaque Totals") {
var uoo = "${apiInstance.opaqueTotals}";
d.push(uoo)
} else if (d[0] === "Cheapest/Opaque") {
var voo = "${apiInstance.cheapestByOpaqueType}";
d.push(voo)
} else if (d[0] === "Searched Contracts") {
var soo = "${apiInstance.searchedContracts}";
d.push(soo);
}
</g:each>
});
//var table = new google.visualization.Table(document.getElementById('container3'));
//table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
var table = new google.visualization.Table(document.getElementById('container3'));
var data2 = google.visualization.arrayToDataTable(tableData2);
table.draw(data2, {showRowNumber: true, width: '100%', height: '100%'});
}
</script>
<div id="container3" style="width: 1350px; height: 1400px;"></div>
I'm not sure how to convert it over to Google charts. Any help vastly appreciated.
Related
I am trying to mask a Phone number in a input field, can somebody please help me in this regards. Here is my code for the html (or .hbs file)
<label class="control-label">Phone</label>
{{masked-input mask='(999) 999-9999'
value=model.Address.Phone
input-format='regex'
input-filter='\(*[0-9]{3}\) [0-9]{3}-[0-9]{4}'
input-filter-message='Phone number is not valid.'
class='form-control phone masked'
maxlength="14"}}
</div>
And my component definition is as below:
export default () => {
IMS.registerComponent("masked-input", {
tagName: 'input',
attrParams: ['required', 'title', 'name', 'placeholder'],
loaded: false,
prop: Ember.observer(
'required',
'title',
'name',
'placeholder',
'value',
function () {
var scope = this;
$(this.element).val(Ember.get(scope, 'value'));
var stamp = new Date();
if (Ember.get(scope, 'loaded') == true) {
var element = $(this.element);
var attrs = Ember.get(this, 'attrParams');
attrs.forEach(function (attr) {
var value = Ember.get(scope, attr);
if (value == '' | value == null) {
element.removeAttr(attr);
} else {
element.attr(attr, value);
}
})
}
}),
observeMask: Ember.observer('mask', function () {
var scope = this;
$(this.element).inputmask({
mask: Ember.get(scope, 'mask')
});
}),
didInsertElement: function () {
var scope = this;
setTimeout(function () {
var value = Ember.get(scope, 'value');
var element = $(scope.element);
var change = function () { Ember.set(scope, 'value', element.val()); }
element.val(Ember.get(scope, 'value'));
element.attr('type', 'text');
element.change(change);
Ember.set(scope, 'loaded', true);
scope.observeChanges();
element.inputmask({
mask: Ember.get(scope, 'mask')
});
element.attr('input-format', Ember.get(scope, 'input-format'));
element.attr('input-filter', Ember.get(scope, 'input-filter'));
element.attr('input-filter-message', Ember.get(scope, 'input-filter-message'));
}, 250);
}
})
}
I am trying to upgrade from an ancient version of ember 1.7 to the still ancient 1.13 and I am getting .js errors. I am not well versed with ember, to begin with, so all the help I can get will be appreciated.
I changed all instances of the code where it was using Ember.View.extend to Ember.Controller.extend
and since then, I am getting an error
Cannot read property 'noSignedUpAppts' of undefined.
Appt.Ember.js
function initEmberApp() {
Ember.Handlebars.registerBoundHelper('stringFormat', function (g11nString, str) {
return new Handlebars.SafeString(stringUtil.format(g11nString, str));
});
ApptApp = Ember.Application.create({
rootElement: "#appointmentWrapper"
});
ApptApp.Router.map(function () {
this.route("main", { path: '/' });
this.route("mainParam", { path: "/:val" });
this.route('mainId', { path: '/mainId/:appt_id' });
this.route('mainDirect', { path: '/mainDirect/:appt_id' });
this.route("schedule");
this.resource('userSchedule', { path: '/schedule/:user_id' });
this.route('scheduleId', { path: '/scheduleId/:appt_id' });
this.route('userScheduleId', { path: '/userScheduleId/:ids' });
this.route('scheduleSpecific');
this.route('scheduleSpecificId',{path: '/scheduleSpecificId/:appt_id'});
this.route('scheduleDate', { path: '/scheduleDate/:date' });
this.route('scheduleResource', { path: '/scheduleResource/:resource_id' });
this.route("settings");
this.route("campus");
this.route("noAccess");
});
ApptApp.history = {name:'',view:'',param:null, isSchedule:false}
initViews();
}
function initViews() {
initMain(ApptApp);
initSchedule(ApptApp);
initSettings(ApptApp);
initCampus(ApptApp);
initNoAccess(ApptApp);
}
ApptMain.js
function initMain(ApptApp) {
ApptApp.MainController = Ember.Controller.extend({
g11n: apptPortlet.g11n,
ableToEdit: apptPortlet.ableToEdit,
canManageSettings: apptPortlet.canManageSettings,
canAdmin: apptPortlet.canAdmin,
defaultDate: '',
showMySchedule: false,
apptId: '',
isDirect: false
});
ApptApp.MainParamRoute = Ember.Route.extend({
model: function (param) {
var date = moment(param.val.replace(/-/g, '/'));
return { defaultDate: (date.isValid() ? date.format('MM/DD/YYYY') : ''), showMySchedule: (param.val == 'myS') };
},
setupController: function (controller, model) {
this.controllerFor('main').set('defaultDate', model.defaultDate).set('showMySchedule', model.showMySchedule).set('apptId', '').set('isDirect',false);
},
renderTemplate: function () {
this.render('main');
}
});
ApptApp.MainIdRoute = Ember.Route.extend({
model: function (param) {
var items = param.appt_id.split('|');
var date = moment(items[1].replace(/-/g, '/'));
return { apptId: items[0], defaultDate: (date.isValid() ? date.format('MM/DD/YYYY') : '') };
},
setupController: function (controller, model) {
this.controllerFor('main').set('defaultDate', model.defaultDate).set('showMySchedule', false).set('apptId', model.apptId.toLowerCase()).set('isDirect', false);
},
renderTemplate: function () {
this.render('main');
}
});
ApptApp.MainDirectRoute = Ember.Route.extend({
model: function (param) {
var items = param.appt_id.split('|');
var date = moment(items[1].replace(/-/g, '/'));
return { apptId: items[0], defaultDate: (date.isValid() ? date.format('MM/DD/YYYY') : '') };
},
setupController: function (controller, model) {
this.controllerFor('main').set('defaultDate', model.defaultDate).set('showMySchedule', apptPortlet.apptSetting != 0).set('apptId', model.apptId.toLowerCase()).set('isDirect', true);
},
renderTemplate: function () {
this.render('main');
}
});
ApptApp.MainView = Ember.Component.extend({
didInsertElement: function() {
var controller = this.get('controller');
if (this.processRedirect(controller))
return;
this.renderView(controller);
},
renderView: function (controller, isRerender) {
if (isRerender) {
apptFullCal.destroy();
}
var g11n = controller.g11n;
apptFullCal.init({
data: {},
defaultDate: controller.defaultDate,
showMonth: true,
showWeekNav: true,
allowEditing: false,
calElem: $("#myCalendar"),
showWknd: apptPortlet.showWeekends,
updateWknd: apptPortlet.updateSettings,
g11n: controller.g11n,
listViewPageSize: apptPortlet.listViewPageSize,
noApptMesg: controller.g11n.noSignedUpAppts,
rerender: function () {
apptFullCal.reload();
$("#myNotifications").apptNotification('render');
},
editEvent: function(appt, isClick, revertFunc, rerenderAction) {
var resource = {};
if (appt.resourceId != '' && appt.resourceEdit)
resource = apptPortlet.getResource(appt.resourceId);
$.apptDetails({ controller: controller, appointment: appt, g11n: controller.g11n, resource: resource, canAddAttendees: apptPortlet.canAddAttendees, rerender: function () { rerenderAction(); $("#myNotifications").apptNotification('render'); } });
},
readonlySources: function (viewName) { return viewName == 'month' ? [{ url: 'rpc/appointmentsinfo/getcalendaraggregate' }] : [{ url: 'api/calendarevents?fullCalendar=true&filter=conflictable' }]; },
postApptRender: function (appt, elem, view) {
if (appt.isReadOnly) return;
var item = elem.find('.fc-content');
item.html(appt.isOwner ? appt.attendeeInfo : (appt.resourceId != '' ? appt.resourceName : appt.owner));
if (view.name != 'month') {
item.append($("<span class='fc-cus-event-info'>").html(appt.title));
}
if (appt.id == controller.apptId) {
controller.apptId = '';
apptFullCal.triggerClick(appt);
}
if (appt.newCommentCount > 0) {
var ctr = view.name == 'list' ? elem : item;
var comTxt = $("<span class='fc-comment'>").append($("<i class='fa fa-comment'/>")).append(view.name == 'list' ? stringUtil.format((appt.newCommentCount == 1 ? controller.g11n.newComment : controller.g11n.newComments), appt.newCommentCount) : '');
ctr.prepend(comTxt);
}
},
changeView: function(viewName) {
if (viewName == 'list')
$(".apptKeyInfo.otherEvents").hide();
else
$(".apptKeyInfo.otherEvents").show();
if (viewName == 'month')
$(".apptKeyInfo.otherEvents").removeClass("inactiveItem");
else
$(".apptKeyInfo.otherEvents").addClass("inactiveItem");
bindHelpText(g11n, viewName == 'list' ? '2' : (viewName == 'month' ? 0 : 1));
}
}, 'month');
bindHelpText(g11n, 0);
$("#myNotifications").apptNotification({
g11n: apptPortlet.g11n,
baseUrl: apptPortlet.baseUrl,
renderFullTxt: true,
callback: function(apptInfo) {
var date = moment(apptInfo.start);
if ((date.weekday() == 0 || date.weekday() == 6) && apptPortlet.showWeekends == false)
apptFullCal.showWeekends($("#myCalendar"), true, date);
controller.set('apptId', apptInfo.id);
apptFullCal.gotToDate('agendaDay', date);
}
});
$("#peopleChooser").peopleChooser({
peopleSource: 'rpc/appointmentsInfo/GetUserSearch',
watermark: controller.g11n.watermark,
onSelect: function(person) {
if (person.isResource)
controller.transitionTo('scheduleResource', person.id);
else
controller.transitionTo('userSchedule', { id: person.id, imgUrl: person.imgUrl, name: { full: person.fullName } });
}
});
if (controller.canManageSettings || controller.canAdmin)
$(".permissionAction").click(function() { ApptApp.history = { name: '', view: 'main', isSchedule: false }; });
var schLinkAction = this.bindScheduleLink;
$(".permHosts").hide();
if (apptPortlet.canManageSettings && (apptPortlet.apptSetting == 2 || (apptPortlet.apptSetting == 3 && apptPortlet.resourceId.length > 0))) {
var resource = apptPortlet.apptSetting == 2 ? null : apptPortlet.getResource(apptPortlet.resourceId);
if (apptPortlet.apptSetting == 2 || (resource != null && resource.canEdit)) {
$(".permHosts").show().find('a').html("<i class='fa fa-group'></i>" + (apptPortlet.apptSetting == 2 ? g11n.apptHosts : g11n.managersAndHosts))
.unbind('click').click(function(e) {
e.preventDefault();
$.apptManageHosts({
g11n: controller.g11n,
resource: resource,
isResource: resource != null,
portletId: apptPortlet.portletId,
onSave: function(res) {
if (apptPortlet.apptSetting == 2) {
apptPortlet.hosts = res;
schLinkAction(controller);
} else {
apptPortlet.hosts = res.hosts;
}
}});
});
}
}
if (controller.showMySchedule) {
$(".mySchedule").hide();
this.bindResourceInfo(controller);
} else {
$(".mySchedule").show();
}
this.bindSidebar(controller);
},
bindSidebar: function(controller) {
var campus = $(".campusWrapper").hide();
var myfac = $(".myFacWrapper").hide();
$.get('rpc/appointmentsinfo/getsidebarinfo/', function (sidebarInfo) {
if (sidebarInfo == null) return;
if (sidebarInfo.campusResources != null) {
var ul = campus.find('#campusResources').empty();
for (var key in sidebarInfo.campusResources) {
ul.append($("<li>").append($("<a href='#' class='activeItem apptStrong'>").data('id', key).html(sidebarInfo.campusResources[key]).click(function (e) { e.preventDefault(); controller.transitionTo('scheduleResource', $(this).data('id')); })));
}
if (ul.find('li').length > 0)
campus.show();
}
if (sidebarInfo.currentFaculty != null && sidebarInfo.currentFaculty.length > 0) {
myfac.show();
var container = myfac.find(".myFacUsers").empty();
$.each(sidebarInfo.currentFaculty, function (i, fac) {
var div = $("<div class='myFac'>");
div.append($("<a class='activeItem apptStrong'>").html(fac.name).click(function (e) { e.preventDefault(); controller.transitionTo('userSchedule', { id: fac.id, imgUrl: fac.imgUrl, name: { full: fac.name } }); }));
if (!fac.hasAvailAppts)
div.append($("<span class='pc-details'>").html(controller.g11n.noAppt));
$.each(fac.sections, function (j, sec) {
div.append($("<div class='inactiveItem itemInfo'>").html(sec));
});
container.append(div);
});
}
});
},
processRedirect: function (controller) {
if (apptPortlet.name == null) {
controller.transitionTo("noAccess");
return true;
}
if (controller.isDirect) return false;
var date = controller.defaultDate != null && controller.defaultDate != '' ? moment(controller.defaultDate).format('MM-DD-YYYY') : null;
if ((apptPortlet.resourceId != '' || apptPortlet.apptSetting == 2) && !controller.showMySchedule) {
var url = apptPortlet.apptSetting == 2 ? 'scheduleSpecific' : 'schedule';
if (controller.apptId != '' || date != null) {
controller.transitionTo(url + "Id", (controller.apptId + '|' + date));
}
else
controller.transitionTo(url);
return true;
}
else if (apptPortlet.apptSetting == 1 && !controller.showMySchedule && apptPortlet.hosts != null && apptPortlet.hosts.length > 0) {
var host = apptPortlet.hosts[0];
if (controller.apptId != '' || date != null) {
controller.transitionTo('userScheduleId', host.id + '_' + ((controller.apptId == '' ? ' ' : controller.apptId) + '|' + date));
}
else
controller.transitionTo('userSchedule', { id: host.id, imgUrl: host.imgUrl, name: { full: host.name } });
return true;
}
return false;
},
bindScheduleLink: function (controller) {
var showLink = false;
if (apptPortlet.resourceId != '') {
var resource = apptPortlet.getResource(apptPortlet.resourceId);
$(".scheduleLink").html(stringUtil.format(controller.g11n.bckToSchedule, resource.name)).unbind('click').click(function (e) { e.preventDefault(); controller.transitionTo('schedule'); });
showLink = true;
}
else if (apptPortlet.apptSetting == 1) {
var host = apptPortlet.hosts[0];
$(".scheduleLink").html(stringUtil.format(controller.g11n.bckToSchedule, host.name)).unbind('click').click(function (e) { e.preventDefault(); controller.transitionTo('userSchedule', { id: host.id, imgUrl: host.imgUrl, name: { full: host.name } }); });
showLink = true;
}
else if (apptPortlet.apptSetting == 2) {
var names = '';
var userCount = apptPortlet.hosts.length;
for (var i = 0; i < userCount; i++) {
names += " " + apptPortlet.hosts[i].name;
if (userCount > 1 && (userCount - i != 1)) {
names += userCount - i == 2 ? ", " + controller.g11n.and : ",";
}
}
$(".scheduleLink").html(stringUtil.format(controller.g11n.bckToSchedule, names)).unbind('click').click(function (e) { e.preventDefault(); controller.transitionTo('scheduleSpecific'); });
showLink = true;
}
if(showLink)
$(".bckToSchedule").show();
else
$(".bckToSchedule").hide();
},
bindResourceInfo: function (controller) {
this.bindScheduleLink(controller);
var ul = $("#userSchedules").empty();
if (apptPortlet.ableToEdit) {
ul.append($("<li>").append($("<a href='#' class='activeItem apptStrong'>").html(apptPortlet.name.full).click(function (e) { e.preventDefault(); controller.transitionTo('userSchedule', apptPortlet.id); })));
$(".rg-sidebar").show();
}
$.get('rpc/appointmentsInfo/GetMySchedules/', function (schedules) {
if (schedules == null) return;
for (var key in schedules) {
ul.append($("<li>").append($("<a href='#' class='activeItem apptStrong'>").data('id',key).html(schedules[key]).click(function (e) { e.preventDefault(); controller.transitionTo('scheduleResource', $(this).data('id')); })));
}
if (schedules.length > 0)
$(".rg-sidebar").show();
});
}
});
function bindHelpText(g11n, screen) {
$(".apptHelpWrapper").appointmentHelp({ g11n: g11n, isHost: apptPortlet.ableToEdit, portletId:apptPortlet.portletId, screen: screen });
}
}
I briefly used Ember 1.7 but only ever with ember-cli. Anyway, I can point out a couple of things I am pretty sure that you aren't doing correctly. First off:
I changed all instances of the code where it was using
Ember.View.extend to Ember.Controller.extend
This does not make any sense. These are not comparable. If you meant Ember.Component that would make more sense but there's still not a 1:1 similarity. I would recommend studying the Ember.View docs from 1.7 as well as that for components and controllers. You should also give a the Ember.View deprecation guide a read through. The recommended upgrade path is to convert views to components, but components are isolated contexts unlike Ember.View. I think you will have to pass the controller to the Ember.Component instance (would be better to pass the properties needed). Since Ember.Component extends Ember.View, you might not be able to pass via the controller property directly (I don't know if this would be problematic but I would probably avoid).
Accessing data via {{view.someProp}} or {{controller.thisThing}} can nearly always be replaced by proper use of data passing and block params. See the guide on differences in yielded blocks for a complete example of using block params over the {{view}} keyword.
I would recommend going all the way through the deprecations guide to understand what needs to change.
I create a ganache cli and initialize my accounts to have ethers using
ganache-cli -h "159.89.119.189" -a 3 -e "1000000000000000000000000000" --secure -u 0 -u 1 -u 2 -s 20
but after a couple of minutes, all accounts on the network are 0.
I'm not able to run any transactions or call contracts again.
A DApp i created connects to this private network
This is my app.js
App = {
web3Provider: null,
contracts: {},
account: 0x0,
coinbase: 0x0,
coinbase_amount: 0,
loading: false,
init: function () {
return App.initWeb3();
},
initWeb3: function () {
// initialize web3
if (typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
//App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
App.web3Provider = new Web3.providers.HttpProvider('http://159.89.119.189:8545');
}
web3 = new Web3(App.web3Provider);
App.getCoinbase();
return App.initContract();
},
hostname: function () {
return window.location.origin;
},
setAccount: function (address) {
App.account = address;
},
displayAccountInfo: function () {
// console.log(App);
if (App.account != 0) {
toastr.remove();
toastr.info('Getting Account Info', {timeOut: 300000});
$('#account').text(App.account);
App.getBalance();
}
},
getBalance: function() {
web3.eth.getBalance(App.account, function (err, balance) {
if (err === null) {
if(web3.fromWei(balance, "ether") == 0){
setTimeout(App.getBalance(), 60000);
} else {
console.log(web3.fromWei(balance, "ether"));
toastr.remove();
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
}
})
},
getCoinbase: function () {
web3.eth.getCoinbase(function (err, account) {
if (err === null) {
App.coinbase = account;
// $('#account').text(account);
web3.eth.getBalance(account, function (err, balance) {
if (err === null) {
App.coinbase_amount = web3.fromWei(balance, "ether").toNumber();
console.log(App.coinbase, App.coinbase_amount)
}
})
}
});
},
transfer: function() {
web3.personal.unlockAccount(App.coinbase, "pass12345", 100000, function (err, result) {
console.log(result)
console.log(err)
web3.personal.unlockAccount(App.account, "pass#123", 100000, function (err, result) {
web3.eth.sendTransaction({
from: App.coinbase,
to: App.account,
value: web3.toWei(10, "ether")
}, function (err, result) {
if (err == null) {
console.log("sent money");
console.log(result)
console.log(err)
web3.eth.getBalance(App.account, function (err, balance) {
if (err === null) {
console.log(web3.fromWei(balance, "ether") + " ETH");
}
})
}
else {
console.log(err);
}
})
});
});
},
register: function () {
let email = $('#inputEmail');
let fname = $('#inputFname');
let lname = $('#inputLname');
let password = $('#inputPassword');
let btnRegister = $('#btnRegister');
if (email.val() == "" || fname.val() == "" || lname.val() == "" || password.val() == "") {
toastr.error('Please fill all fields');
return false;
}
btnRegister.attr("disabled", 'disabled');
web3.personal.newAccount("pass#123", function (err, data) {
let address = data;
if (err === null) {
let postData = {
email: email.val(),
fname: fname.val(),
lname: lname.val(),
password: password.val(),
address: data
}
$.ajax({
method: "POST",
url: App.hostname() + "/register",
data: postData,
success: function (data) {
console.log(data)
if (data.status == "success") {
web3.personal.unlockAccount(address, "pass#123", 1000, function (err, result) {
web3.eth.sendTransaction({
from: App.coinbase,
to: address,
value: web3.toWei(10, "ether")
}, function (err, result) {
if (err == null) {
console.log("sent money");
console.log(result)
web3.eth.getBalance(App.coinbase, function (err, balance) {
if (err === null) {
console.log("coinbase "+web3.fromWei(balance, "ether") + " ETH");
}
})
web3.eth.getBalance(address, function (err, balance) {
if (err === null) {
console.log(web3.fromWei(balance, "ether") + " ETH");
}
})
}
else {
console.log(err);
}
toastr.success("Success.");
window.location.href = App.hostname();
})
});
} else {
toastr.error(data.data);
}
btnRegister.attr("disabled", false);
},
error: function (err) {
toastr.error('Error Registering');
btnRegister.attr("disabled", false);
}
});
} else {
toastr.error('Error Registering');
btnRegister.attr("disabled", false);
return false;
}
})
},
login: function () {
let email = $('#inputEmail');
let password = $('#inputPassword');
let btnLogin = $('#btnLogin');
if (email.val() == "" || password.val() == "") {
toastr.error('Please fill all fields');
return false;
}
btnLogin.attr("disabled", 'disabled');
let postData = {
email: email.val(),
password: password.val(),
}
$.ajax({
method: "POST",
url: App.hostname() + "/login",
data: postData,
success: function (data) {
console.log(data)
if (data.status == "success") {
toastr.success("Success.");
window.location.href = App.hostname();
} else {
toastr.error(data.data);
}
btnLogin.attr("disabled", false);
},
error: function (err) {
toastr.error('Error Registering');
btnLogin.attr("disabled", false);
}
});
},
initContract: function () {
$.getJSON('Chainlist.json', function (chainListArtifact) {
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.ChainList = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.ChainList.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function () {
// avoid re-entry
if (App.loading) {
return
}
App.loading = true
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.ChainList.deployed().then(function (instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function (articleIds) {
$('#articlesRow').empty();
for (var i = 0; i < articleIds.length; i++) {
var articleID = articleIds[i];
chainListInstance.articles(articleID.toNumber())
.then(function (article) {
App.displayArticle(article[0], article[1], article[3], article[4], article[5], article[6])
});
}
App.loading = false;
}).catch(function (err) {
console.error(err.message);
App.loading = false;
});
},
sellArticle: function () {
// retrieve the detail of the article
var _article_name = $('#article_name').val();
var _description = $('#article_description').val();
var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
const file = $('#article_image').prop('files')[0];
if ((_article_name.trim() == '') || (_price == 0)) {
// nothing to sell
return false;
}
const name = (+new Date()) + '-' + file.name;
const metadata = {
contentType: file.type
};
let ref = firebase.storage().ref();
const task = ref.child(name).put(file, metadata);
toastr.info('Processing.....', {timeOut: 30000});
task.then((snapshot) => {
const _image_url = snapshot.downloadURL;
console.log(_image_url);
web3.personal.unlockAccount(App.account, "pass#123", 1000, function (err, result) {
console.log(result);
console.log(err);
App.contracts.ChainList.deployed().then(function (instance) {
return instance.sellArticle(_article_name, _description, _price, _image_url, {
from: App.account,
gas: 500000
});
}).then(function (result) {
console.log(result);
$('#article_name').val("");
$('#article_description').val("");
$('#article_price').val("");
$('#article_image').val("");
}).catch(function (err) {
console.error(err);
});
});
}).catch((error) => {
console.error(error);
});
},
displayArticle: function (id, seller, name, description, price, image_url) {
var articlesRow = $('#articlesRow');
var etherPrice = web3.fromWei(price, "ether");
// retrieve the article template and fill it
var articleTemplate = $('#articleTemplate');
articleTemplate.find('.panel-title').text(name);
articleTemplate.find('.article-description').text(description);
articleTemplate.find('.article-price').text(etherPrice);
articleTemplate.find('.btn-image-url').attr('href', image_url);
articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
articleTemplate.find('.btn-buy').attr('data-id', id);
if (seller == App.account) {
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
} else {
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
// buyer
// var buyer = article[1];
// if (buyer == App.account) {
// buyer = "You";
// } else if (buyer == 0x0){
// buyer = "None yet"
// }
// articleTemplate.find('.article-buyer').text(buyer);
// add this article
toastr.clear();
$('#articlesRow').append(articleTemplate.html());
},
// listen to events triggered by the contract
listenToEvents: function () {
App.contracts.ChainList.deployed().then(function (instance) {
instance.LogSellArticle({}, {}).watch(function (error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._name + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function (error, event) {
if (!error) {
$('#sellBtn').attr("disabled", false);
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._name + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
// retrieve article price from data-value and process buyArticle function
buyArticle: function () {
event.preventDefault();
// retrieve article Price
toastr.info('Processing.....', {timeOut: 30000});
$(event.target).attr("disabled", 'disabled');
$('#sellBtn').attr("disabled", 'disabled');
var price = parseFloat($(event.target).data('value'));
var articleID = parseFloat($(event.target).data('id'));
web3.personal.unlockAccount(App.account, "pass#123", 1000, function (err, result) {
console.log(result);
console.log(err);
App.contracts.ChainList.deployed().then(function (instance) {
return instance.buyArticle(articleID, {
from: App.account,
value: web3.toWei(price, "ether"),
gas: 500000
}).catch(function (error) {
console.error(error);
})
});
});
}
};
$(function() {
$(window).load(function() {
App.init();
// Initialize Firebase
var config = {
apiKey: "AIzaSyAQp34HzZS_3xckuxcVcsUWgCu8_p7UzxA",
authDomain: "comflo-1518513183870.firebaseapp.com",
databaseURL: "https://comflo-1518513183870.firebaseio.com",
projectId: "comflo-1518513183870",
storageBucket: "comflo-1518513183870.appspot.com",
messagingSenderId: "798445619042"
};
firebase.initializeApp(config);
});
});
Same thing happens when i run a geth private server.
I'm using a node app with express.
I'm trying to create a skill with Alexa to read data from my DynamoDB table using either the scan or query function (or both).
The columns in my table are date, time and film name.
I'm new to this but I've managed to link my Lambda function to Alexa. I have also created a separate Lambda function that will recall data from my table when I configure test events, so when I input a specific date it will recall the corresponding film and time. However now i want to implement this into Alexa and am not sure how.
Here is my current code
console.log('Loading function');
var AWSregion = 'us-east-1'; // us-east-1
var AWS = require('aws-sdk');
var dclient = new AWS.DynamoDB.DocumentClient();
var getItems = (event, context, callback)=>{
dclient.get(event.params,(error,data)=>{
if(error){
callback(null,"error occurerd");
}
else{
callback(null,data);
}
});
};
exports.handler = getItems;
and the code i have to launch the skill in alexa is
exports.handler = (event, context, callback) => {
try {
var request = event.request;
if (request.type === "LaunchRequest") {
context.succeed(buildResponse({
speechText: "Welcome to H.S.S.M.I skill, what would you like to find",
repromptText: "I repeat, Welcome to my skill, what would you like to find",
endSession: false
}));
}
else if (request.type === "SessionEndedRequest") {
options.endSession = true;
context.succeed();
}
else {
context.fail("Unknown Intent type");
}
} catch (e) {
}
};
function buildResponse(options) {
var response = {
version: "1.0",
response: {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.speechText}</prosody></speak>`
},
shouldEndSession: options.endSession
}
};
if (options.repromptText) {
response.response.reprompt = {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.repromptText}</prosody></speak>`
}
};
}
return response;
}
I don't mind changing my table from DynamoDB to something else so long as I can recall the data.
Please try below code,
var DBHandler = require("./DBHandler")
var DBHandler = require("./DBHandler")
exports.handler = (event, context, callback) => {
try {
var request = event.request;
if (request.type === "LaunchRequest") {
context.succeed(buildResponse({
speechText: "Welcome to home remedy. Please tell me what is the problem you want remedy for?",
repromptText: "You can say for example, home remedy for headache",
endSession: false
}));
}
else if (request.type === "IntentRequest") {
let options = {};
if (request.intent.name === "Cinema") {
DBHandler.getItems(ID, function (err, data) {
if (err) {
context.fail(err);
} else {
if (data.Item !== undefined) {
options.speechText = data.Item.YOURFIELDHERE
options.endSession = true;
context.succeed(buildResponse(options));
} else {
options.speechText = `I am Sorry, I couldn't find any data! `
options.endSession = true;
context.succeed(buildResponse(options));
}
}
callback(null, data)
});
} else if (request.intent.name === "AMAZON.StopIntent" || request.intent.name === "AMAZON.CancelIntent") {
options.speechText = "ok, thanks for using my skill.";
options.endSession = true;
context.succeed(buildResponse(options));
}
else {
context.fail("Unknown Intent")
}
}
else if (request.type === "SessionEndedRequest") {
options.endSession = true;
context.succeed();
}
else {
context.fail("Unknown Intent type")
}
} catch (e) {
}
};
function buildResponse(options) {
var response = {
version: "1.0",
response: {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.speechText}</prosody></speak>`
},
shouldEndSession: options.endSession
}
};
if (options.repromptText) {
response.response.reprompt = {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.repromptText}</prosody></speak>`
}
};
}
return response;
}
and DBHandler would be,
const AWS = require('aws-sdk');
AWS.config.update({
region: "Location"
});
var docClient = new AWS.DynamoDB.DocumentClient()
var table = "TableName";
var getItems = (Id,callback) => {
var params = {
TableName: table,
Key: {
"Id": Id
}
};
docClient.get(params, function (err, data) {
callback(err, data);
});
};
module.exports = {
getItems
};
Im trying to create a skill that will scan or query my dynamodb table which includes a date column, filmanme, and time.
Here is the code i have so far.
console.log('Loading function');
var AWSregion = 'us-east-1'; // us-east-1
var AWS = require('aws-sdk');
var dclient = new AWS.DynamoDB.DocumentClient();
var getItems = (event, context, callback)=>{
dclient.get(event.params,(error,data)=>{
if(error){
callback(null,"error occurerd");
}
else{
callback(null,data);
}
});
};
exports.handler = getItems;
exports.handler = (event, context, callback) => {
try {
var request = event.request;
if (request.type === "LaunchRequest") {
context.succeed(buildResponse({
speechText: "Welcome to H.S.S.M.I skill, what would you like to find",
repromptText: "I repeat, Welcome to my skill, what would you like to find",
endSession: false
}));
}
else if (request.type === "IntentRequest") {
let options = {};
if (request.intent.name === "cinema") {
if (request.intent.slots.cimema !== undefined)
var sign = request.intent.slots.cinema.value;
//Check sign is valid
if (sign === undefined || sign === null) {
options.speechText = " sorry, i didn't understant your question. can you say that again?";
options.endSession = false;
context.succeed(buildResponse(options));
return;
}
if (request.intent.slots.zodiac !== undefined && !ValidateZodiacSign(sign)) {
options.speechText = ` The Zoadiac sign ${sign} is not a valid one. Please tell a valid zodiac sign .`;
options.endSession = false;
context.succeed(buildResponse(options));
return;
}
cinema(sign, function (cinema, error) {
if (error) {
context.fail(error);
options.speechText = "There has been a problem with the request.";
options.endSession = true;
context.succeed(buildResponse(options));
} else {
options.speechText = todaysFortune;
options.speechText += " . Have a nice day ahead . ";
options.sign = sign;
options.cardText = todaysFortune;
options.endSession = true;
context.succeed(buildResponse(options));
}
});
} else if (request.intent.name === "AMAZON.StopIntent" || request.intent.name === "AMAZON.CancelIntent") {
options.speechText = "ok, good bye.";
options.endSession = true;
context.succeed(buildResponse(options));
}
else if (request.intent.name === "AMAZON.HelpIntent") {
options.speechText = "My skill will read your table depending on what is asked. For example, you can ask what about a specific date. Please refer to skill description for all possible utterences.";
options.repromptText = "What is the data sign you want to know about today? If you want to exit from my skill please say stop or cancel."
options.endSession = false;
context.succeed(buildResponse(options));
}
else {
context.fail("Unknown Intent")
}
}
else if (request.type === "SessionEndedRequest") {
options.endSession = true;
context.succeed();
}
else {
context.fail("Unknown Intent type");
}
} catch (e) {
}
};
function buildResponse(options) {
var response = {
version: "1.0",
response: {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.speechText}</prosody></speak>`
},
shouldEndSession: options.endSession
}
};
if (options.repromptText) {
response.response.reprompt = {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.repromptText}</prosody></speak>`
}
};
}
return response;
}
function readDynamoItem(params, callback) {
var AWS = require('aws-sdk');
AWS.config.update({region: AWSregion});
var dynamodb = new AWS.DynamoDB();
console.log('reading item from DynamoDB table');
dynamodb.scan(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else{
console.log(data); // successful response
callback(JSON.stringify(data));
}
});
var docClient = new AWS.DynamoDB.DocumentClient();
//Get item by key
docClient.get(params, (err, data) => {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
callback(data.Item.message); // this particular row has an attribute called message
}
});
}
///////////////////////////////////////////////////////////////////////////////
and here is my DBHandlder
const AWS = require('aws-sdk');
AWS.config.update({
region: "'us-east-1'"
});
var docClient = new AWS.DynamoDB.DocumentClient();
var table = "Cinema";
var getItems = (Id,callback) => {
var params = {
TableName: "cinema",
Key: {
"Id": Id
}
};
docClient.get(params, function (err, data) {
callback(err, data);
});
};
module.exports = {
getItems
};
i'm very new to this and i cant find muchsupport online for the skill i want to produce or anything similar.
I created a lambda function which works and will find the corresponding movie when i configure the test function to find a specified date, however this does not work with alexa
any input is helpful.