Dialogflow and twillio show different results - twilio

Hi we have created a bot making use of dialogflow for controlling natural language and twillio handles the text messaging in the form of whatsapps. We have the following code in our dialogflow fulfillment
const {Firestore} = require('#google-cloud/firestore');
const functions = require('firebase-functions');
const {WebhookClient } = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
const {
dialogflow,
Image,
} = require('actions-on-google');
// Create an app instance
const app = dialogflow({
debug: true
});
app.intent('greeting', (conv) => {
console.log('hi');
//agent.add("My ID: " + conv.parameters.my_id.toString());
});
var name = null;
// initialise DB connection
var firebase = require("firebase-admin");
var firebaseConfig = {
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function handleName(agent) {
let names = agent.parameters.person;
var temp = names;
// agent.add(agent.requestSource);
var name2 = agent.getContext('1_1_name');
name = name2;
var newData={
name:names.name
};
if((temp != null && temp.name.length < 256 && temp.name.length > 2)){
let myref = firebase.database().ref('Person');
let mGroupId = firebase.database().ref('Person').push().getKey();
return true;
}
else{
agent.add('Invalid name or surname. Please try again');
return false;
}
}
function handleWelcome(agent){
//agent.add(new Image('https://s3.amazonaws.com/botsociety.prod.us/e3d2e0b03f28399a62654d8f52bade457_welcomescreenpng.png'));
agent.add("How can we help you?\n1: Funeral cover family option\n2: Funeral cover nominated option\n3: Add beneficiaries to existing cover\n4: Claim\n5: Contact Details");
//agent.add(sessionId);
return true;
}
function done(agent) {
//agent.add(JSON.parse(agent.parameters).toString());
agent.add("Lol wut");
}
function handleID(agent) {
agent.add('I am a banana.');
const id = agent.parameters.my_id;
var tempID = id.toString();
var valid = true;
if (tempID.length == 13){
}else{
agent.add('Invalid RSA ID number. Please try again');
return false;
}
//Only numerical
for (let x = 0; x < tempID.length; x++){
const d = tempID.charCodeAt(x);
if (d < 48 || d > 57)
valid = false;
}
//Valid citizenship value
if (tempID[10] > 1)
valid = false;
//Odd
var uneven = 0;
for (var x = 0; x <= 10; x += 2){
uneven += parseInt(tempID[x]);
}
//Even
var temp = "";
for (x = 1; x <= 11; x += 2){
temp += tempID[x].toString();
}
var even = parseInt(temp) * 2;
temp = even.toString();
var finalEven = 0;
for (x = 0; x < temp.length; x++){
finalEven += parseInt(temp[x]);
}
//total
var total = finalEven + uneven;
var actualValue = 10 - (total % 10);
//final check
if ((actualValue.toString() !== tempID[12].toString()))
valid = false;
//decide what to do
if (valid){
let myref = firebase.database().ref('Person');
var newData = {
id: id
};
}
else{
agent.add('Invalid RSA ID number. Please try again');
return false;
}
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
//Names
intentMap.set('1_1_name', handleName);
intentMap.set('1_1_spouse_name', handleName);
intentMap.set('2_1_name', handleName);
intentMap.set('2_beneficiary_name', handleName);
intentMap.set('3_3_name', handleName);
intentMap.set('beneficiary_name_intent', handleName);
intentMap.set('c_2_c_1_name', handleName);
intentMap.set('c_2_c_2_name', handleName);
intentMap.set('c_3_c_1_name', handleName);
intentMap.set('c_3_c_2_name', handleName);
intentMap.set('c_3_c_3_name', handleName);
intentMap.set('c_4_c_1_name', handleName);
intentMap.set('c_4_c_2_name', handleName);
intentMap.set('c_4_c_3_name', handleName);
intentMap.set('c_4_c_4_name', handleName);
intentMap.set('child_1_name_intent', handleName);
//IDs
intentMap.set('1_1_id', handleID);
intentMap.set('1_1_spouse_id', handleID);
intentMap.set('2_1_id', handleID);
intentMap.set('2_beneficiary_id', handleID);
intentMap.set('3_3_id', handleID);
intentMap.set('beneficiary_id_intent', handleID);
intentMap.set('c_2_c_1_id', handleID);
intentMap.set('c_2_c_2_id', handleID);
intentMap.set('c_3_c_1_id', handleID);
intentMap.set('c_3_c_2_id', handleID);
intentMap.set('c_3_c_3_id', handleID);
intentMap.set('c_4_c_1_id', handleID);
intentMap.set('c_4_c_2_id', handleID);
intentMap.set('c_4_c_3_id', handleID);
intentMap.set('c_4_c_4_id', handleID);
intentMap.set('child_1_id_intent', handleID);
intentMap.set('anything_else_no', done);
// intentMap.set('your intent name here', yourFunctionHandler);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
}}
Now the method I am most concerned with is the following.
function handleID(agent) {
agent.add('I am a banana.');
const id = agent.parameters.my_id;
var tempID = id.toString();
var valid = true;
if (tempID.length == 13){
}else{
agent.add('Invalid RSA ID number. Please try again');
return false;
}
//Only numerical
for (let x = 0; x < tempID.length; x++){
const d = tempID.charCodeAt(x);
if (d < 48 || d > 57)
valid = false;
}
//Valid citizenship value
if (tempID[10] > 1)
valid = false;
//Odd
var uneven = 0;
for (var x = 0; x <= 10; x += 2){
uneven += parseInt(tempID[x]);
}
//Even
var temp = "";
for (x = 1; x <= 11; x += 2){
temp += tempID[x].toString();
}
var even = parseInt(temp) * 2;
temp = even.toString();
var finalEven = 0;
for (x = 0; x < temp.length; x++){
finalEven += parseInt(temp[x]);
}
//total
var total = finalEven + uneven;
var actualValue = 10 - (total % 10);
//final check
if ((actualValue.toString() !== tempID[12].toString()))
valid = false;
//decide what to do
if (valid){
let myref = firebase.database().ref('Person');
var newData = {
id: id
};
}
else{
agent.add('Invalid RSA ID number. Please try again');
return false;
}
}
This function is meant for validating an ID that the user provides us and works perfectly within the testing system within dialogflow test console. It is also connected to a twillio account and when we whatsapp a certain number it acts in the same way. However the validate ID function does not seem to work within twillio. It works perfectly when tested in the console but does not work well when the user uses the twillio whatsapp number.
Any suggestions as to way it does not work with the twillio integration? Thank you very much.
Edit when looking through the firebase logs I get the following error message
Error: No responses defined for platform: twilio
at WebhookClient.send_ (/srv/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:488:13)
at promise.then (/srv/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:306:38)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)

Related

Dart: Class members seem to be wrong when access from a separate class

Anyone know if this is a Dart bug or is it my misunderstanding of how Dart coding works?
I am learning Dart to investigate feasibility of eventually using Flutter; however, while exploring the language, I found a weird behavior (maybe a bug). I tried repro'ing it by writing a similar pattern of code, but have yet to figure out what causes it. In the attached code, I wrote a quicksort class. In that class, it counts the number of times the "sort" method is recursed and saves the count in a class member called "recurseCount".
From the main() class, if I use the QuickSort class directly, I have no issue getting back the recurseCount member; however, if I call it from a different class (called "Tester"), I do not get the correct value for "recurseCount". Why would calling a class from a separate class cause members to not provide the correct values?
import 'package:test/test.dart';
import 'dart:math' as _math;
// ***********************
enum SortOrder { ascending, descending, unsorted }
class QuickSort {
List list = [];
SortOrder sortOrder = SortOrder.unsorted;
int recurseCount = 0;
QuickSort({this.list}) {
if (list != null && list.length > 1) {
list = sort(useRandomPivot: true);
}
}
List sort(
{List iList,
int leftIndex = 0,
int rightIndex,
bool useRandomPivot = true}) {
if (iList != null) list = iList;
if (list.isEmpty) return [];
rightIndex ??= list.length - 1;
if (rightIndex > list.length - 1) rightIndex = list.length - 1;
if (leftIndex < rightIndex) {
recurseCount++;
var partitionIndex =
_partition(leftIndex, rightIndex, useRandomPivot: useRandomPivot);
if (partitionIndex == -1) {
//already sorted List
if (sortOrder == SortOrder.ascending) {
return list;
} else {
//SortOrder.descending
list = list.reversed.toList(); // Time Complexity of O(n)
sortOrder = SortOrder.ascending;
return list;
}
} else {
sort(leftIndex: leftIndex, rightIndex: partitionIndex - 1);
sort(leftIndex: partitionIndex + 1, rightIndex: rightIndex);
}
} else {
sortOrder = SortOrder.ascending;
}
return list;
}
int _partition(int leftIndex, int rightIndex, {bool useRandomPivot = true}) {
// in case the array is already sorted from the start; only run through the partition'ing one time
// note: regardless of ascending or descending order
if (leftIndex == 0 && rightIndex >= list.length - 1) {
sortOrder = checkSorting(list);
if (sortOrder != SortOrder.unsorted) {
return -1;
}
if (useRandomPivot) {
var random = _math.Random();
var randomIndex = random.nextInt(rightIndex - leftIndex);
_swapElements(randomIndex, rightIndex);
}
}
int pivotVal = list[rightIndex]; //select the last item as the pivot
var headIndex = leftIndex - 1;
for (var scanIndex = leftIndex; scanIndex < rightIndex; scanIndex++) {
if (list[scanIndex] <= pivotVal) {
headIndex++;
_swapElements(headIndex, scanIndex);
}
}
var partitionIndex = headIndex + 1;
_swapElements(partitionIndex, rightIndex);
return partitionIndex;
}
void _swapElements(position1, position2) {
int tempVal = list[position1];
list[position1] = list[position2];
list[position2] = tempVal;
}
SortOrder checkSorting(List arr) {
var isAsc = true;
var isDesc = true;
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i] < arr[i + 1]) isDesc = false;
if (arr[i] > arr[i + 1]) isAsc = false;
if (!isDesc && !isAsc) break; // not sorted Asc or Desc
}
if (isAsc) {
return SortOrder.ascending;
} else if (isDesc) return SortOrder.descending;
return SortOrder.unsorted;
}
}
// ***********************TESTS*********************************
num log2(num n) => _math.log(n) / _math.ln2;
List getRandomIntList({int min = 0, int max = 10000, int len}) {
var random = _math.Random();
var tempList = List(len);
for (var i = 0; i < len; i++) {
tempList[i] = random.nextInt(max - min);
}
return tempList;
}
class Tester {
static num _runControlTest(List list) {
var stopwatch = Stopwatch();
stopwatch.start();
list.sort();
stopwatch.stop();
return stopwatch.elapsedMicroseconds;
}
static void runTests(List list, String groupName,
{bool useRandomPivot = false, bool sortFromConstructor = false}) {
// CONTROL
var controlElapsedTimeMicroSec = 0;
controlElapsedTimeMicroSec = _runControlTest(list);
// END CONTROL
var expectedRecursionCountLogN = log2(list.length).ceil();
var expectedRecursionCountNLogN = list.length * expectedRecursionCountLogN;
var qs = QuickSort();
var stopwatch = Stopwatch();
stopwatch.start();
list =
qs.sort(iList: list, useRandomPivot: useRandomPivot); // METHOD TO TEST
stopwatch.stop();
var elapsedTimeMicroSec = stopwatch.elapsedMicroseconds;
var recursionCount = qs
.recurseCount; //NOTE (BUG in Dart?): unable to get the recurseCount correctly from within this class/method
group(groupName, () {
var testSubject =
'Time Taken: ${controlElapsedTimeMicroSec} microseconds';
var reason =
'The built in sort took ${controlElapsedTimeMicroSec} microseconds, while the test took ${elapsedTimeMicroSec}.';
test(testSubject, () {
expect(
elapsedTimeMicroSec, lessThanOrEqualTo(controlElapsedTimeMicroSec),
reason: reason);
});
testSubject =
'Time Complexity: ${recursionCount} vs ${expectedRecursionCountNLogN}';
reason =
'Time Complexity of ${recursionCount} is greater than either range (LogN) ${expectedRecursionCountLogN} or (N*LogN) ${expectedRecursionCountNLogN}';
test(testSubject, () {
expect(recursionCount, lessThanOrEqualTo(expectedRecursionCountNLogN),
reason: reason);
});
});
}
}
void main() {
var min = 0;
var len = 1000000;
var max = len;
var originalList = getRandomIntList(min: min, max: max, len: len);
var list = List.from(originalList);
// BUG? When called within this Tester.runTests the sort method does NOT return the correct recurseCount
Tester.runTests(list, 'UNSORTED_RIGHT_PIVOT', useRandomPivot: false);
list = List.from(originalList);
var qs = QuickSort();
// When called directly from main() the sort method DOES return the correct recurseCount
var stopwatch = Stopwatch()..start();
qs.sort(iList: list, useRandomPivot: true); //METHOD TO TEST
stopwatch.stop();
group('UNSORTED_RANDOM_PIVOT', () {
test('Time Taken: ${stopwatch.elapsedMicroseconds} microseconds', () {
expect(stopwatch.elapsedMicroseconds,
lessThanOrEqualTo(Tester._runControlTest(originalList)));
});
var nLogN = (list.length * (log2(list.length).ceil()));
test('Time Complexity: ${qs.recurseCount} vs $nLogN', () {
expect(qs.recurseCount, lessThanOrEqualTo(nLogN));
});
});
}

Using dart to create a javascript library

The problem
I'm currently working on a JavaScript library, and in order to reduce the amount of bugs I thought that my library might benefit from using Dart's static typing mechanism. First, because my lib wasn't doing any interop neither with HTML nor with other JavaScript libraries, only pure javascript object manipulation stuff. However I didn't find any info on the net showing how it is possible to build a JS library using dart. So I've tried to do that myself, created initial dart file:
library Repo;
class Type {
final String name;
final TypeCategory category;
Type(String name, TypeCategory category) : name = name, category = category {
category.types[name] = this;
}
}
class TypeCategory {
final String name;
final Map<String, Type> types = new Map();
TypeCategory(this.name);
}
class Branch {
}
class Descriptor {
}
class TableDescriptor extends Descriptor {
TableDescriptor.ctor() {
}
}
class Repo {
Descriptor descriptor(String name) {
}
Branch branch(String name) {
}
void Merge() {
}
}
main() {
return Repo;
}
Compiled it to JavaScript using dart2js to see how I'm doing:
// Generated by dart2js, the Dart to JavaScript compiler version: 1.3.6.
// The code supports the following hooks:
// dartPrint(message):
// if this function is defined it is called instead of the Dart [print]
// method.
//
// dartMainRunner(main, args):
// if this function is defined, the Dart [main] method will not be invoked
// directly. Instead, a closure that will invoke [main], and its arguments
// [args] is passed to [dartMainRunner].
(function($) {
function dart(){ this.x = 0 }var A = new dart;
delete A.x;
var B = new dart;
delete B.x;
var C = new dart;
delete C.x;
var D = new dart;
delete D.x;
var E = new dart;
delete E.x;
var F = new dart;
delete F.x;
var G = new dart;
delete G.x;
var H = new dart;
delete H.x;
var J = new dart;
delete J.x;
var K = new dart;
delete K.x;
var L = new dart;
delete L.x;
var M = new dart;
delete M.x;
var N = new dart;
delete N.x;
var O = new dart;
delete O.x;
var P = new dart;
delete P.x;
var Q = new dart;
delete Q.x;
var R = new dart;
delete R.x;
var S = new dart;
delete S.x;
var T = new dart;
delete T.x;
var U = new dart;
delete U.x;
var V = new dart;
delete V.x;
var W = new dart;
delete W.x;
var X = new dart;
delete X.x;
var Y = new dart;
delete Y.x;
var Z = new dart;
delete Z.x;
function Isolate() {}
init();
$ = Isolate.$isolateProperties;
var $$ = {};
(function (reflectionData) {
"use strict";
function map(x){x={x:x};delete x.x;return x}
function processStatics(descriptor) {
for (var property in descriptor) {
if (!hasOwnProperty.call(descriptor, property)) continue;
if (property === "^") continue;
var element = descriptor[property];
var firstChar = property.substring(0, 1);
var previousProperty;
if (firstChar === "+") {
mangledGlobalNames[previousProperty] = property.substring(1);
var flag = descriptor[property];
if (flag > 0) descriptor[previousProperty].$reflectable = flag;
if (element && element.length) init.typeInformation[previousProperty] = element;
} else if (firstChar === "#") {
property = property.substring(1);
$[property]["#"] = element;
} else if (firstChar === "*") {
globalObject[previousProperty].$defaultValues = element;
var optionalMethods = descriptor.$methodsWithOptionalArguments;
if (!optionalMethods) {
descriptor.$methodsWithOptionalArguments = optionalMethods = {}
}
optionalMethods[property] = previousProperty;
} else if (typeof element === "function") {
globalObject[previousProperty = property] = element;
functions.push(property);
init.globalFunctions[property] = element;
} else if (element.constructor === Array) {
addStubs(globalObject, element, property, true, descriptor, functions);
} else {
previousProperty = property;
var newDesc = {};
var previousProp;
for (var prop in element) {
if (!hasOwnProperty.call(element, prop)) continue;
firstChar = prop.substring(0, 1);
if (prop === "static") {
processStatics(init.statics[property] = element[prop]);
} else if (firstChar === "+") {
mangledNames[previousProp] = prop.substring(1);
var flag = element[prop];
if (flag > 0) element[previousProp].$reflectable = flag;
} else if (firstChar === "#" && prop !== "#") {
newDesc[prop.substring(1)]["#"] = element[prop];
} else if (firstChar === "*") {
newDesc[previousProp].$defaultValues = element[prop];
var optionalMethods = newDesc.$methodsWithOptionalArguments;
if (!optionalMethods) {
newDesc.$methodsWithOptionalArguments = optionalMethods={}
}
optionalMethods[prop] = previousProp;
} else {
var elem = element[prop];
if (prop !== "^" && elem != null && elem.constructor === Array && prop !== "<>") {
addStubs(newDesc, elem, prop, false, element, []);
} else {
newDesc[previousProp = prop] = elem;
}
}
}
$$[property] = [globalObject, newDesc];
classes.push(property);
}
}
}
function addStubs(descriptor, array, name, isStatic, originalDescriptor, functions) {
var f, funcs = [originalDescriptor[name] = descriptor[name] = f = array[0]];
f.$stubName = name;
functions.push(name);
for (var index = 0; index < array.length; index += 2) {
f = array[index + 1];
if (typeof f != "function") break;
f.$stubName = array[index + 2];
funcs.push(f);
if (f.$stubName) {
originalDescriptor[f.$stubName] = descriptor[f.$stubName] = f;
functions.push(f.$stubName);
}
}
for (var i = 0; i < funcs.length; index++, i++) {
funcs[i].$callName = array[index + 1];
}
var getterStubName = array[++index];
array = array.slice(++index);
var requiredParameterInfo = array[0];
var requiredParameterCount = requiredParameterInfo >> 1;
var isAccessor = (requiredParameterInfo & 1) === 1;
var isSetter = requiredParameterInfo === 3;
var isGetter = requiredParameterInfo === 1;
var optionalParameterInfo = array[1];
var optionalParameterCount = optionalParameterInfo >> 1;
var optionalParametersAreNamed = (optionalParameterInfo & 1) === 1;
var isIntercepted = requiredParameterCount + optionalParameterCount != funcs[0].length;
var functionTypeIndex = array[2];
var unmangledNameIndex = 2 * optionalParameterCount + requiredParameterCount + 3;
var isReflectable = array.length > unmangledNameIndex;
if (getterStubName) {
f = tearOff(funcs, array, isStatic, name, isIntercepted);
f.getterStub = true;
if (isStatic) init.globalFunctions[name] = f;
originalDescriptor[getterStubName] = descriptor[getterStubName] = f;
funcs.push(f);
if (getterStubName) functions.push(getterStubName);
f.$stubName = getterStubName;
f.$callName = null;
if (isIntercepted) init.interceptedNames[getterStubName] = true;
}
if (isReflectable) {
for (var i = 0; i < funcs.length; i++) {
funcs[i].$reflectable = 1;
funcs[i].$reflectionInfo = array;
}
var mangledNames = isStatic ? init.mangledGlobalNames : init.mangledNames;
var unmangledName = array[unmangledNameIndex];
var reflectionName = unmangledName;
if (getterStubName) mangledNames[getterStubName] = reflectionName;
if (isSetter) {
reflectionName += "=";
} else if (!isGetter) {
reflectionName += ":" + requiredParameterCount + ":" + optionalParameterCount;
}
mangledNames[name] = reflectionName;
funcs[0].$reflectionName = reflectionName;
funcs[0].$metadataIndex = unmangledNameIndex + 1;
if (optionalParameterCount) descriptor[unmangledName + "*"] = funcs[0];
}
}
function tearOffGetterNoCsp(funcs, reflectionInfo, name, isIntercepted) {
return isIntercepted
? new Function("funcs", "reflectionInfo", "name", "H", "c",
"return function tearOff_" + name + (functionCounter++)+ "(x) {" +
"if (c === null) c = H.closureFromTearOff(" +
"this, funcs, reflectionInfo, false, [x], name);" +
"return new c(this, funcs[0], x, name);" +
"}")(funcs, reflectionInfo, name, H, null)
: new Function("funcs", "reflectionInfo", "name", "H", "c",
"return function tearOff_" + name + (functionCounter++)+ "() {" +
"if (c === null) c = H.closureFromTearOff(" +
"this, funcs, reflectionInfo, false, [], name);" +
"return new c(this, funcs[0], null, name);" +
"}")(funcs, reflectionInfo, name, H, null)
}
function tearOffGetterCsp(funcs, reflectionInfo, name, isIntercepted) {
var cache = null;
return isIntercepted
? function(x) {
if (cache === null) cache = H.closureFromTearOff(this, funcs, reflectionInfo, false, [x], name);
return new cache(this, funcs[0], x, name)
}
: function() {
if (cache === null) cache = H.closureFromTearOff(this, funcs, reflectionInfo, false, [], name);
return new cache(this, funcs[0], null, name)
}
}
function tearOff(funcs, reflectionInfo, isStatic, name, isIntercepted) {
var cache;
return isStatic
? function() {
if (cache === void 0) cache = H.closureFromTearOff(this, funcs, reflectionInfo, true, [], name).prototype;
return cache;
}
: tearOffGetter(funcs, reflectionInfo, name, isIntercepted);
}
var functionCounter = 0;
var tearOffGetter = (typeof dart_precompiled == "function")
? tearOffGetterCsp : tearOffGetterNoCsp;
if (!init.libraries) init.libraries = [];
if (!init.mangledNames) init.mangledNames = map();
if (!init.mangledGlobalNames) init.mangledGlobalNames = map();
if (!init.statics) init.statics = map();
if (!init.typeInformation) init.typeInformation = map();
if (!init.globalFunctions) init.globalFunctions = map();
if (!init.interceptedNames) init.interceptedNames = map();
var libraries = init.libraries;
var mangledNames = init.mangledNames;
var mangledGlobalNames = init.mangledGlobalNames;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var length = reflectionData.length;
for (var i = 0; i < length; i++) {
var data = reflectionData[i];
var name = data[0];
var uri = data[1];
var metadata = data[2];
var globalObject = data[3];
var descriptor = data[4];
var isRoot = !!data[5];
var fields = descriptor && descriptor["^"];
var classes = [];
var functions = [];
processStatics(descriptor);
libraries.push([name, uri, classes, functions, metadata, fields, isRoot,
globalObject]);
}
})
([
["Repo", "repo.dart", , F, {
"^": "",
main: function() {
return C.Type_Jeh;
}
},
1],
["_js_helper", "dart:_js_helper", , H, {
"^": "",
createRuntimeType: function($name) {
return new H.TypeImpl($name, null);
},
TypeImpl: {
"^": "Object;_typeName,_unmangledName"
}
}],
["dart.core", "dart:core", , P, {
"^": "",
Null: {
"^": "Object;"
},
Object: {
"^": ";"
}
}],
]);
Isolate.$finishClasses($$, $, null);
$$ = null;
// Runtime type support
// getInterceptor methods
C.Type_Jeh = H.createRuntimeType('Repo');
$.libraries_to_load = {};
$.Closure_functionCounter = 0;
$.BoundClosure_selfFieldNameCache = null;
$.BoundClosure_receiverFieldNameCache = null;
init.functionAliases = {};
;
init.metadata = [];
$ = null;
Isolate = Isolate.$finishIsolateConstructor(Isolate);
$ = new Isolate();
function convertToFastObject(properties) {
function MyClass() {};
MyClass.prototype = properties;
new MyClass();
return properties;
}
A = convertToFastObject(A);
B = convertToFastObject(B);
C = convertToFastObject(C);
D = convertToFastObject(D);
E = convertToFastObject(E);
F = convertToFastObject(F);
G = convertToFastObject(G);
H = convertToFastObject(H);
J = convertToFastObject(J);
K = convertToFastObject(K);
L = convertToFastObject(L);
M = convertToFastObject(M);
N = convertToFastObject(N);
O = convertToFastObject(O);
P = convertToFastObject(P);
Q = convertToFastObject(Q);
R = convertToFastObject(R);
S = convertToFastObject(S);
T = convertToFastObject(T);
U = convertToFastObject(U);
V = convertToFastObject(V);
W = convertToFastObject(W);
X = convertToFastObject(X);
Y = convertToFastObject(Y);
Z = convertToFastObject(Z);
// BEGIN invoke [main].
;(function (callback) {
if (typeof document === "undefined") {
callback(null);
return;
}
if (document.currentScript) {
callback(document.currentScript);
return;
}
var scripts = document.scripts;
function onLoad(event) {
for (var i = 0; i < scripts.length; ++i) {
scripts[i].removeEventListener("load", onLoad, false);
}
callback(event.target);
}
for (var i = 0; i < scripts.length; ++i) {
scripts[i].addEventListener("load", onLoad, false);
}
})(function(currentScript) {
init.currentScript = currentScript;
if (typeof dartMainRunner === "function") {
dartMainRunner(F.main, []);
} else {
F.main([]);
}
});
// END invoke [main].
function init() {
Isolate.$isolateProperties = {};
function generateAccessor(fieldDescriptor, accessors, cls) {
var fieldInformation = fieldDescriptor.split("-");
var field = fieldInformation[0];
var len = field.length;
var code = field.charCodeAt(len - 1);
var reflectable;
if (fieldInformation.length > 1)
reflectable = true;
else
reflectable = false;
code = code >= 60 && code <= 64 ? code - 59 : code >= 123 && code <= 126 ? code - 117 : code >= 37 && code <= 43 ? code - 27 : 0;
if (code) {
var getterCode = code & 3;
var setterCode = code >> 2;
var accessorName = field = field.substring(0, len - 1);
var divider = field.indexOf(":");
if (divider > 0) {
accessorName = field.substring(0, divider);
field = field.substring(divider + 1);
}
if (getterCode) {
var args = getterCode & 2 ? "receiver" : "";
var receiver = getterCode & 1 ? "this" : "receiver";
var body = "return " + receiver + "." + field;
var property = cls + ".prototype.get$" + accessorName + "=";
var fn = "function(" + args + "){" + body + "}";
if (reflectable)
accessors.push(property + "$reflectable(" + fn + ");\n");
else
accessors.push(property + fn + ";\n");
}
if (setterCode) {
var args = setterCode & 2 ? "receiver, value" : "value";
var receiver = setterCode & 1 ? "this" : "receiver";
var body = receiver + "." + field + " = value";
var property = cls + ".prototype.set$" + accessorName + "=";
var fn = "function(" + args + "){" + body + "}";
if (reflectable)
accessors.push(property + "$reflectable(" + fn + ");\n");
else
accessors.push(property + fn + ";\n");
}
}
return field;
}
Isolate.$isolateProperties.$generateAccessor = generateAccessor;
function defineClass(name, cls, fields) {
var accessors = [];
var str = "function " + cls + "(";
var body = "";
for (var i = 0; i < fields.length; i++) {
if (i != 0)
str += ", ";
var field = generateAccessor(fields[i], accessors, cls);
var parameter = "parameter_" + field;
str += parameter;
body += "this." + field + " = " + parameter + ";\n";
}
str += ") {\n" + body + "}\n";
str += cls + ".builtin$cls=\"" + name + "\";\n";
str += "$desc=$collectedClasses." + cls + ";\n";
str += "if($desc instanceof Array) $desc = $desc[1];\n";
str += cls + ".prototype = $desc;\n";
if (typeof defineClass.name != "string") {
str += cls + ".name=\"" + cls + "\";\n";
}
str += accessors.join("");
return str;
}
var inheritFrom = function() {
function tmp() {
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
return function(constructor, superConstructor) {
tmp.prototype = superConstructor.prototype;
var object = new tmp();
var properties = constructor.prototype;
for (var member in properties)
if (hasOwnProperty.call(properties, member))
object[member] = properties[member];
object.constructor = constructor;
constructor.prototype = object;
return object;
};
}();
Isolate.$finishClasses = function(collectedClasses, isolateProperties, existingIsolateProperties) {
var pendingClasses = {};
if (!init.allClasses)
init.allClasses = {};
var allClasses = init.allClasses;
var hasOwnProperty = Object.prototype.hasOwnProperty;
if (typeof dart_precompiled == "function") {
var constructors = dart_precompiled(collectedClasses);
} else {
var combinedConstructorFunction = "function $reflectable(fn){fn.$reflectable=1;return fn};\n" + "var $desc;\n";
var constructorsList = [];
}
for (var cls in collectedClasses) {
if (hasOwnProperty.call(collectedClasses, cls)) {
var desc = collectedClasses[cls];
if (desc instanceof Array)
desc = desc[1];
var classData = desc["^"], supr, name = cls, fields = classData;
if (typeof classData == "string") {
var split = classData.split("/");
if (split.length == 2) {
name = split[0];
fields = split[1];
}
}
var s = fields.split(";");
fields = s[1] == "" ? [] : s[1].split(",");
supr = s[0];
split = supr.split(":");
if (split.length == 2) {
supr = split[0];
var functionSignature = split[1];
if (functionSignature)
desc.$signature = function(s) {
return function() {
return init.metadata[s];
};
}(functionSignature);
}
if (typeof dart_precompiled != "function") {
combinedConstructorFunction += defineClass(name, cls, fields);
constructorsList.push(cls);
}
if (supr)
pendingClasses[cls] = supr;
}
}
if (typeof dart_precompiled != "function") {
combinedConstructorFunction += "return [\n " + constructorsList.join(",\n ") + "\n]";
var constructors = new Function("$collectedClasses", combinedConstructorFunction)(collectedClasses);
combinedConstructorFunction = null;
}
for (var i = 0; i < constructors.length; i++) {
var constructor = constructors[i];
var cls = constructor.name;
var desc = collectedClasses[cls];
var globalObject = isolateProperties;
if (desc instanceof Array) {
globalObject = desc[0] || isolateProperties;
desc = desc[1];
}
allClasses[cls] = constructor;
globalObject[cls] = constructor;
}
constructors = null;
var finishedClasses = {};
init.interceptorsByTag = Object.create(null);
init.leafTags = {};
function finishClass(cls) {
var hasOwnProperty = Object.prototype.hasOwnProperty;
if (hasOwnProperty.call(finishedClasses, cls))
return;
finishedClasses[cls] = true;
var superclass = pendingClasses[cls];
if (!superclass || typeof superclass != "string")
return;
finishClass(superclass);
var constructor = allClasses[cls];
var superConstructor = allClasses[superclass];
if (!superConstructor)
superConstructor = existingIsolateProperties[superclass];
var prototype = inheritFrom(constructor, superConstructor);
}
for (var cls in pendingClasses)
finishClass(cls);
};
Isolate.$lazy = function(prototype, staticName, fieldName, getterName, lazyValue) {
var sentinelUndefined = {};
var sentinelInProgress = {};
prototype[fieldName] = sentinelUndefined;
prototype[getterName] = function() {
var result = $[fieldName];
try {
if (result === sentinelUndefined) {
$[fieldName] = sentinelInProgress;
try {
result = $[fieldName] = lazyValue();
} finally {
if (result === sentinelUndefined) {
if ($[fieldName] === sentinelInProgress) {
$[fieldName] = null;
}
}
}
} else {
if (result === sentinelInProgress)
H.throwCyclicInit(staticName);
}
return result;
} finally {
$[getterName] = function() {
return this[fieldName];
};
}
};
};
Isolate.$finishIsolateConstructor = function(oldIsolate) {
var isolateProperties = oldIsolate.$isolateProperties;
function Isolate() {
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var staticName in isolateProperties)
if (hasOwnProperty.call(isolateProperties, staticName))
this[staticName] = isolateProperties[staticName];
function ForceEfficientMap() {
}
ForceEfficientMap.prototype = this;
new ForceEfficientMap();
}
Isolate.prototype = oldIsolate.prototype;
Isolate.prototype.constructor = Isolate;
Isolate.$isolateProperties = isolateProperties;
Isolate.$finishClasses = oldIsolate.$finishClasses;
return Isolate;
};
}
})()
//# sourceMappingURL=out.js.map
//# sourceMappingURL=out.js.map
And that's it, I've thrown away Dart because I didn't knew what to do with generated JS file, also I was frightened of potentially high amount of time required for keeping the resulting library interface clean and similar to one I'm using with JavaScript.
The question(s)
How do I expose class definitions created in Dart and later use them in JavaScript?
Do you think it's worth it going into Dart when nearly all potential library users will be using JS version instead? (Using dart is already not good for me due to difference in community sizes, this means that less people will find it easy to contribute to my library)
In your opinion, what should I do?
Even though Dart supports this use case, if you target JavaScript developers I would stick with JavaScript.
#AlexandreArdhuin shows in his answer to Expose Dart functions to javascript how you can make a Dart function available to JavaScript.
Under the dart-js-interop are many examples how to do function calls and pass data between Dart and JavaScript.
Wrap dart class into custom element, the Dart object auto expose to javascript.
Assume we have 2 Dart Classes, SlickGrid Class contains Column class in Dart
class SlickGrid{
List<Column> columns;
}
class Column{}
class GridWrap extends HtmlElement {
ShadowRoot shadowRoot;
SlickGrid grid; // here is your cool object
}
compile to javascript, and register custom element, then open javascript console,
//this is SlickGrid object
var grid= document.querySelector('cj-grid').grid;
// this is dart Column Object
var column = grid.columns.$index(0,0);
// call toString function in dart object that produce json string...
column.toString$0()

Stream file from ftp in localhost working in azure no

Hi I using VisualStudio 2012 and I have created web site which reads info (from .csv) from external ftp site. When I running it on local host everything works fine, but then I deployed it to azure web sites it is not working, just show zeros everywhere were should be numbers. (Dont get info from ftp)
public static List<ApiClient.Models.StatsList> GetStatsData(string Ticket, DateTime start, DateTime end, int CampaignId, String CampaignName)
{
//--------------------------------------------------------------------------------------------------------
//Gets stats from GetAdsStats service (included: Banner id, impressions, and clicks)
//--------------------------------------------------------------------------------------------------------
List<ApiClient.Models.StatsList> FullList = GetAdStatsService.GetAdsStats(Ticket, start, end, CampaignId);
List<LikesDislikesList> LikeDislike = new List<LikesDislikesList>();
//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
string day;
string month;
if (DateTime.Today.AddDays(-1).Day.ToString().Count() == 1)
{
day = "0" + DateTime.Today.AddDays(-1).Day;
}
else
{
day = DateTime.Today.AddDays(-1).Day.ToString();
}
if (DateTime.Today.Month.ToString().Count() == 1)
{
month = "0" + DateTime.Today.Month;
}
else
{
month = DateTime.Today.Month.ToString();
}
try
{
string uri = "ftp://siteAdres" + CampaignName.Replace(" ", "_") + "_Optimizing_events_" + day + "-" + month + "-" + DateTime.Today.Year + ".csv";
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return FullList;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential("username", "password");
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader csvStream = new StreamReader(response.GetResponseStream());
//--------------------------------------------------------------------------------------------------------
//Read Likes/Dislikes from csv file stream
//--------------------------------------------------------------------------------------------------------
using (var rd = csvStream)
{
int iname = -1;
int ilikes = -1;
int idislikes = -1;
while (!rd.EndOfStream)
{
var raw = rd.ReadLine().Split((char)9);
if (rd.Peek() == -1)
{
break;
}
if (ilikes == -1 || idislikes == -1)
{
for (int i = 0; i < raw.Length; i++)
{
if (raw[i] == "Event name")
iname = i;
if (raw[i] == "Custom Event 14")
ilikes = i;
if (raw[i] == "Custom Event 15")
{
idislikes = i;
raw = rd.ReadLine().Split((char)9);
}
}
}
else
{
LikeDislike.Add(new LikesDislikesList() { Likes = Convert.ToInt32(raw[ilikes]), Dislikes = Convert.ToInt32(raw[idislikes]), Name = raw[iname] });
}
}
}
response.Close();
}
catch(Exception ex)
{
log4net.Config.XmlConfigurator.Configure();
log.Warn("GetAdStatsService.cs " + ex);
}
//--------------------------------------------------------------------------------------------------------
//Add like/dislike values for certain banners
//--------------------------------------------------------------------------------------------------------
foreach (var element in FullList)
{
foreach (var el in LikeDislike)
{
if (element.name == el.Name)
{
element.Likes = el.Likes;
element.Dislikes = el.Dislikes;
}
}
}
return FullList;
}
}
}
Check FtpWebResponse.StatusCode before calling response.GetResponseStream(). You are probably having come kind of connection error. My guess would be firewall settings on your Azure VM.

Why can I not find journalentries using their RefNumber in Quickbooks SDK?

I boiled this down to a simple example that always fails using QB Enterprise. (Oddly, I could swear this code used to work.)
Create a journal entry via SDK with a specific ref number "PTD1234"
Search for that specific journal entry in the same code block
Observe, no results found?
However, if I change the process to create the same journal entry by hand in QB, then the search code below works correctly and finds the journal entry.
Quickbooks qb = new Quickbooks();
qb.Connect(this);
IMsgSetRequest msr = qb.sm.CreateMsgSetRequest("US", 7, 0);
msr.Attributes.OnError = ENRqOnError.roeStop;
IJournalEntryAdd jea = msr.AppendJournalEntryAddRq();
jea.TxnDate.SetValue(new DateTime(2013, 3, 1));
jea.RefNumber.SetValue("PTD1234");
IJournalCreditLine jcl = jea.ORJournalLineList.Append().JournalCreditLine;
jcl.Amount.SetValue(1);
jcl.AccountRef.FullName.SetValue("Credit Card Batches:Paymentech");
jcl.EntityRef.FullName.SetValue("CHASE PAYMENTECH");
IJournalDebitLine jdl = jea.ORJournalLineList.Append().JournalDebitLine;
jdl.Amount.SetValue(1);
jdl.AccountRef.FullName.SetValue("Chase Deposits EUR");
jdl.EntityRef.FullName.SetValue("CHASE PAYMENTECH");
IMsgSetResponse msp = qb.sm.DoRequests(msr);
IResponse resp = msp.ResponseList.GetAt(0);
if (resp.StatusCode != 0)
{
Log("-------------\r\nError during test");
Log(resp.StatusMessage);
}
IJournalEntryRet jet = null;
msr = qb.sm.CreateMsgSetRequest("US", 7, 0);
msr.Attributes.OnError = ENRqOnError.roeStop;
IJournalEntryQuery q = msr.AppendJournalEntryQueryRq();
q.metaData.SetValue(ENmetaData.mdNoMetaData);
q.ORTxnQuery.TxnFilter.ORRefNumberFilter.RefNumberFilter.RefNumber.SetValue("PTD1234");
q.ORTxnQuery.TxnFilter.ORRefNumberFilter.RefNumberFilter.MatchCriterion.SetValue(ENMatchCriterion.mcContains);
q.ORTxnQuery.TxnFilter.AccountFilter.ORAccountFilter.FullNameList.Add("Chase Deposits EUR");
q.IncludeLineItems.SetValue(false);
msp = qb.sm.DoRequests(msr);
if (msp.ResponseList.Count > 0)
{
IResponseList rl = msp.ResponseList;
if (rl.Count >= 1)
{
IResponse r = rl.GetAt(0);
if (r.Detail == null)
Log("Fail: Detail was null");
if (r.StatusCode != 0)
Log("Fail: Status code was not zero");
if (r.Type.GetValue() == (short)ENResponseType.rtJournalEntryQueryRs)
{
IJournalEntryRetList crl = (IJournalEntryRetList)r.Detail;
if (crl != null && crl.Count == 1)
jet = crl.GetAt(0);
}
}
}
if (jet != null)
Log("Success!");
qb.Cleanup();
For unknown reasons, some journalentries won't show up using a JournalEntryQuery and the TxnFilter.ORRefNumberFilter.RefNumberFilter. However, a workaround is to use the ORTxnQuery.RefNumberList and then cycle through the Journal Lines and make sure the account matches.
public bool GetExactJournalTransaction(string sRefNum, string sAccount, out IJournalEntryRet jet)
{
jet = null;
IMsgSetRequest msr = sm.CreateMsgSetRequest("US", 4, 0);
msr.Attributes.OnError = ENRqOnError.roeStop;
IJournalEntryQuery q = msr.AppendJournalEntryQueryRq();
q.metaData.SetValue(ENmetaData.mdNoMetaData);
q.ORTxnQuery.RefNumberList.Add(sRefNum);
q.IncludeLineItems.SetValue(true);
IMsgSetResponse resp = sm.DoRequests(msr);
if (resp.ResponseList.Count == 0)
return false;
IResponseList rl = resp.ResponseList;
if (rl.Count == 1)
{
IResponse r = rl.GetAt(0);
if (r.Detail == null)
return false;
if (r.StatusCode != 0)
return false;
if (r.Type.GetValue() == (short)ENResponseType.rtJournalEntryQueryRs)
{
IJournalEntryRetList crl = (IJournalEntryRetList)r.Detail;
if (crl != null)
{
for (int i = 0; i < crl.Count; i++)
{
jet = crl.GetAt(i);
for (int j = 0; j < jet.ORJournalLineList.Count; j++)
{
IORJournalLine l = jet.ORJournalLineList.GetAt(j);
if (l.JournalCreditLine != null && l.JournalCreditLine.AccountRef.FullName.GetValue() == sAccount)
return true;
else if (l.JournalDebitLine != null && l.JournalDebitLine.AccountRef.FullName.GetValue() == sAccount)
return true;
}
}
}
}
}
return false;
}

How to populate a Listfield with results from a Autocomplete field using Blackberry API

How can we populate a Listfield in blackberry with results from a Autocomplete field using Blackberry API(JDE 5)
This is the code to get Contacts, returns a vector containing string array..
contact[0] is name, contact[1] is email and contact[2] is contact number..
read elements from vector and set autocompleteField:Example: http://docs.blackberry.com/en/developers/deliverables/18125/Autocomplete_text_field_1200231_11.jsp
private Vector getContacts() {
Vector result = new Vector();
try {
BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration enumx = contactList.items();
while (enumx.hasMoreElements()) {
BlackBerryContact c = (BlackBerryContact) enumx.nextElement();
String[] contact = new String[3];
if (contactList.isSupportedField(BlackBerryContact.NAME)) {
String[] name = c.getStringArray(BlackBerryContact.NAME, 0);
String firstName = name[Contact.NAME_GIVEN];
String lastName = name[Contact.NAME_FAMILY];
System.out.println("this is contact..........." + firstName);
contact[0] = firstName + " " + lastName;
}
if (contactList.isSupportedField(BlackBerryContact.EMAIL)) {
StringBuffer emails = new StringBuffer();
int emailCount = c.countValues(BlackBerryContact.EMAIL);
for (int i = 0; i < emailCount; i++) {
String email = c.getString(BlackBerryContact.EMAIL, i);
if (email != null) {
emails.append(email.trim());
emails.append("; ");
}
}
contact[1] = emails.toString();
}
if ((contactList.isSupportedField(BlackBerryContact.TEL)) && (c.countValues(BlackBerryContact.TEL) > 0)) {
int numValues = 0;
try {
numValues = c.countValues(BlackBerryContact.TEL);
} catch (Exception localException) {
}
String mobileNumber = "";
String homeNumber = "";
String workNumber = "";
for (int i = 0; i < numValues; ++i) {
if (c.getAttributes(BlackBerryContact.TEL, i) == BlackBerryContact.ATTR_WORK)
workNumber = c.getString(BlackBerryContact.TEL, i);
else if (c.getAttributes(BlackBerryContact.TEL, i) == BlackBerryContact.ATTR_HOME)
homeNumber = c.getString(BlackBerryContact.TEL, i);
else if (c.getAttributes(BlackBerryContact.TEL, i) == BlackBerryContact.ATTR_MOBILE)
mobileNumber = c.getString(BlackBerryContact.TEL, i);
}
if (!mobileNumber.equalsIgnoreCase(""))
contact[2] = mobileNumber.toString();
else if (!homeNumber.equalsIgnoreCase(""))
contact[2] = homeNumber.toString();
else if (!workNumber.equalsIgnoreCase(""))
contact[2] = workNumber.toString();
}
result.addElement(contact);
}
} catch (PIMException ex) {
ex.printStackTrace();
}
return result;
}
There's a sample app provided with the developer tools that demonstrates the use of this field. From your developer tools directory go to samples/com/rim/samples/device/ui/autocompletefielddemo and you'll see the AutoCompleteFieldDemo.java app.

Resources