Calculate price in DialogFow Es - javascript

So im trying to get this code to work and get a price from the values obtained in this case "alto" and "ancho" so it'll be Dimensiones= alto * ancho then multiply the result and get the final price= dimensiones * 175
function calcularPrecio(agent) {
// Obtenemos los valores de alto y ancho del parámetro de Dialogflow
const { alto, ancho } = agent.parameters;
// Convertimos los valores de string a número
const altura = Number(alto);
const anchura = Number(ancho);
// Calculamos las dimensiones y el precio total
const dimensiones = altura * anchura;
const precioUnidad = 175;
const precioTotal = dimensiones * precioUnidad;

Related

my update of the prototype "string" cannot be printed to with log

I dont get how I can remove a list of words from a string using this type of formalism:
string.my_function(parameter[])
text_val = "je vous appel concernant le truc rouge"
String.prototype.clean_string = function (stop_words) {
for (i = 0; i < stop_words.length; i++)
{
this.split(stop_words[i]).join('');
}
};
console.log(text_val.clean_string(['concernant','le']));
I have un undefined as a result and I don't get why.
I expect the result:
"je vous appel truc rouge"
I would use filter to strip the stop_words and then join the result:
text_val = "je vous appel concernant le truc rouge";
String.prototype.clean_string = function (stop_words) {
let splitted = this.split(' ');
for (i = 0; i < stop_words.length; i++) {
splitted = splitted.filter(w => w != stop_words[i]);
}
return splitted.join(' ');
};
console.log(text_val.clean_string(['concernant','le']));

Loop opening a spreadsheet, and copying from sheet a to sheet b

I just don't understand where the problem is,
must be super simple but this does not work.
Sorry for the newbee question.
function GoGetData() {
var ss =
SpreadsheetApp.openById("1tyfIzGNDZr4JK9kYwABDMLBvK7B3jJ4r2wQfMOIPd3I");
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = ss.getSheetByName('List des dossiers du Folder') // Sheet=liste des dossiers
for(var i=1; i>3; i++)
{
Logger.log(i);
var IdShpread = sheet.getRange(i,2,1,1); // va prender l,adresse de La sheet
var source = SpreadsheetApp.openById(IdShpread); // open la sheet avec les data
var sourcesheet = source.getSheetByName('regroup');
var targetsheet = source.getSheetByName('worksheet');
// Copy de l'ensemble de la Sheet
var rangeValues = sourcesheet.getRange("A1:L1000").copyTo(targetsheet.getRange("A1:L1000"), {contentsOnly: true});
//pour copier seulement certaines parties a netraliser apres
//var rangeValues = sourcesheet.getRange("D7:K7").copyTo(targetsheet.getRange("D7:K7"), {contentsOnly: true});
}
}
To retrieve the sheet Ids, which are located in the cells of your range, you need to use the method getValue(). Modify your script as following:
function GoGetData() {
var ss = SpreadsheetApp.openById("1tyfIzGNDZr4JK9kYwABDMLBvK7B3jJ4r2wQfMOIPd3I");
var sheet = ss.getSheetByName('List des dossiers du Folder') // Sheet=liste des dossiers
for(var i=1; i<=3; i++) {
var IdShpread = sheet.getRange(i,2,1,1).getValue(); // va prender l,adresse de La sheet
var source = SpreadsheetApp.openById(IdShpread); // open la sheet avec les data
var sourcesheet = source.getSheetByName('regroup');
var targetsheet = source.getSheetByName('worksheet');
sourcesheet.getRange("A1:L1000").copyTo(targetsheet.getRange("A1:L1000"), {contentsOnly: true});
}
}
Try this:
function GoGetData() {
var ss=SpreadsheetApp.openById("1tyfIzGNDZr4JK9kYwABDMLBvK7B3jJ4r2wQfMOIPd3I");
var sh=ss.getSheetByName('List des dossiers du Folder');
for(var i=1;i<3;i++) {
Logger.log(i);
var IdShpread=sh.getRange(i,2,1,1);
var source=SpreadsheetApp.openById(IdShpread);
var sourcesheet=source.getSheetByName('regroup');
var targetsheet=source.getSheetByName('worksheet');
sourcesheet.getRange("A1:L1000").copyTo(targetsheet.getRange("A1:L1000"), {contentsOnly: true});
}
}

All positions of the array are modified to the same value

I'm newbie programming in JavaScript and I have some problems with an array:
When I do a data exchange between an array and another position to position in a loop, all the positions of the array are converted to the same value. That is, the array positions are the same as the last added object.
I leave the code to help me to know what is happening:
.controller("UserAndEditLanguagePanel", function (usersFactory, userLanguagesFactory, LanguageFactory) {
var vm = this;
vm.userSesion = {};
var objAux = {};
objAux.langname = "";
objAux.level = "";
vm.lenguajesUsuario = new Array();
vm.funciones = {
cargarPerfil: function () {
usersFactory.obtenerUsuarioSesion().then(function (respuesta) {
vm.userSesion.idu = respuesta.idu;
vm.userSesion.username = respuesta.username;
vm.userSesion.email = respuesta.email;
console.log("Se han obtenido los datos de usuario de la sesión correctamente. Respuesta: ", respuesta);
userLanguagesFactory.obtenerLenguagesUsuarios().then(function (lenguajesUsuarios) {
console.log("Se han obtenidos los datos de los lenguajes de los usuarios. Respuesta: ", lenguajesUsuarios);
LanguageFactory.obtenerLenguajes().then(function (listaLenguajes) {
console.log("Se han traido los datos de los lenguajes. Respuesta: ", listaLenguajes);
console.log(lenguajesUsuarios);
for (var i = 0; i < lenguajesUsuarios.length; i++) {
if (lenguajesUsuarios[i].idu == vm.userSesion.idu) {
objAux.langname = listaLenguajes[lenguajesUsuarios[i].idl].langname;
objAux.level = lenguajesUsuarios[i].level;
vm.lenguajesUsuario.push(objAux);
}
}
Thank you very much in advance!
Need to initialise the object of objAux inside for loop and and dont crete and initialise the same object before the for loop it will work and fine.
.controller("UserAndEditLanguagePanel", function (usersFactory, userLanguagesFactory, LanguageFactory) {
var vm = this;
vm.userSesion = {};
//comment to below object creation and initialisation of object "objAux "
/*var objAux = {};
objAux.langname = "";
objAux.level = "";*/
vm.lenguajesUsuario = new Array();
vm.funciones = {
cargarPerfil: function () {
usersFactory.obtenerUsuarioSesion().then(function (respuesta) {
vm.userSesion.idu = respuesta.idu;
vm.userSesion.username = respuesta.username;
vm.userSesion.email = respuesta.email;
console.log("Se han obtenido los datos de usuario de la sesión correctamente. Respuesta: ", respuesta);
userLanguagesFactory.obtenerLenguagesUsuarios().then(function (lenguajesUsuarios) {
console.log("Se han obtenidos los datos de los lenguajes de los usuarios. Respuesta: ", lenguajesUsuarios);
LanguageFactory.obtenerLenguajes().then(function (listaLenguajes) {
console.log("Se han traido los datos de los lenguajes. Respuesta: ", listaLenguajes);
console.log(lenguajesUsuarios);
for (var i = 0; i < lenguajesUsuarios.length; i++) {
if (lenguajesUsuarios[i].idu == vm.userSesion.idu) {
var objAux = {
langname:'',
level:''
}
objAux.langname = listaLenguajes[lenguajesUsuarios[i].idl].langname;
objAux.level = lenguajesUsuarios[i].level;
vm.lenguajesUsuario.push(objAux);
}
}

add element JSON

I want to add new element to JSON ...
var estudiantes = [
{"Nombre":"Fernando","Codigo":"F50","Nota":100}
];
and this is the function to add the element, but doesnt works ...
function addEstudiantes(){
var nombre = prompt("Ingrese el nombre del estudiante: ");
var codigo = prompt("Ingrese el codigo del estudiante: ");
var nota = prompt("Ingrese la nota del estudiante: ");
/*agregar registro al JSON*/
var objeto = JSON.parse(estudiantes);
objeto.push('{"Nombre":"'+nombre+'","Codigo":"'+codigo+'","Nota":'+nota+'}');
estudiantes = JSON.stringify(objeto);
}
Your problem is that you aren't working with json, you are working with a javascript array of objects but trying to push json string instead of object into it
Try
function addEstudiantes(){
var nombre = prompt("Ingrese el nombre del estudiante: ");
var codigo = prompt("Ingrese el codigo del estudiante: ");
var nota = prompt("Ingrese la nota del estudiante: ");
// create new object
var objeto = {"Nombre":nombre,"Codigo":codigo,"Nota":nota};
//push object into array
estudiantes.push( objeto);
}
if you are working in js, you dont need work this like a string , you need work this with objects.
var linea= [];
var persona = new Object();
var objeto = new Object();
function addEstudiantes(){
var nombre = prompt("Ingrese el nombre del estudiante: ");
var codigo = prompt("Ingrese el codigo del estudiante: ");
var nota = prompt("Ingrese la nota del estudiante: ");
// create new object
persona.nombre=nombre;
persona.codigo=codigo;
persona.nota=nota;
linea.push(persona);
}
function generarjson(){
objeto.estudiantes=linea;
alert(JSON.stringify(objeto));
}
<button onclick="addEstudiantes();">Agregar estudiante</button>
<button onclick="generarjson();">Generar JSON</button>

zoom slider doesn't appears on my google map

First of all, I've also tried with Google Map APi zoom bar not showing, but with no success at all, so I'll tell you my problem. Ok, the code is as follows:
var datos = '<%=coorNom%>';
var origen='<%=origen%>';
var vAPIKey = '<%=APIKey%>';
var vLangmap = '<%=langmap%>';
var mapcoords;
$(document).ready(function() {
var script = document.createElement("script");
var gurl = "http://www.google.com/jsapi?callback=loadMapscoord&key=" + vAPIKey + "&oe=UTF8&ie=UTF8&hl=" + vLangmap;
script.src = gurl;
document.getElementsByTagName("head")[0].appendChild(script);
});
// Se utiliza esta función para no tener que cargar cada vez el api desde google maps y ya tenerlo descargado en el cliente
function loadMapscoord(){
setTimeout("google.load('maps', '2.x', {'callback':initMapcoord});", 100);
}
function initMapcoord(){
window.onunload=google.maps.Unload;
mapcoords = new google.maps.Map2(document.getElementById("mapa"));
mapcoords.enableDoubleClickZoom();
mapcoords.enableContinuousZoom();
mapcoords.enableScrollWheelZoom();
var mapControl = new google.maps.MapTypeControl();
mapcoords.addControl(mapControl);
var zoomControl = new google.maps.LargeMapControl();
mapcoords.addControl(zoomControl);
initializeCoords();
// Tenemos que esperar a cargar el mapa para ocultar la capa y mostrar la info.
if (origen == "info"){
parent.cuerpo(origen, 'localizacion');
}
}
function initializeCoords() {
mapcoords.clearOverlays();
mapcoords.closeInfoWindow();
mapcoords.setMapType(G_NORMAL_MAP);
mapcoords.setCenter(new google.maps.LatLng(0,0),0);
var bounds = new google.maps.LatLngBounds();
var markers = new Array(); //Array de marcadores
//Obtenemos la estructura de datos
var numcoords = datos.split('|');
for (var x = 0; x < numcoords.length-1; x++){
var coord = numcoords[x].split('#')[0];
var lat = coord.split('**')[0];
var lon = coord.split('**')[1];
if ((lat != undefined) && (lat != '') && (lon != undefined) && (lon != '')){
markers.push({latlng: new google.maps.LatLng( parseFloat( lat ), parseFloat( lon ) ), name: numcoords[x].split('#')[1]} );
}
}
//creamos los distintos marcadores y los asociamos al mapa
for (var z in markers){
marker = createMarker(markers[z]);
mapcoords.addOverlay(marker);
}
//Calculamos el centro y zoom adecuados para el mapcoords
for (var i in markers){
bounds.extend(markers[i].latlng);
}
mapcoords.setCenter(bounds.getCenter(), mapcoords.getBoundsZoomLevel(bounds) - 7);
if (origen == "imprimir"){
setTimeout("parent.imprime();",300);
}
}
</script>
The problem is that I've got the map, everything works fine, but I haven't got the zoom control slider, and I need it. You can see the line with var zoomControl = new google.maps.LargeMapControl();, and I understand it should work, and show the slider, but "au contrair", the two button, for zoom in and out, are together, with no slider between them.
Please..., can anybody tell me how to fix it? or what am I doing wrong?
Thanks a lot in advance.

Categories