I write some simple app for windows 8 Metro UI with javascript. Because natural method from microsoft to use Sqlite with Javascript in Metro UI. I use 'doo' wrapper:
dooWrapper SQLite (github)
I create a method :
function addSomething(name) {
var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\a_db.sqlite';
SQLite3JS.openAsync(dbPath).then(function (db) {
return db.runAsync("INSERT INTO STH (nazwa) VALUES (:name)", { name: name }).
done(function () {
console.log('Add sth : ' + name);
db.close();
}, function (error) {
if (db) {
db.close();
}
console.log('ERROR Adding sth' + error.message);
})
});
}
I get error 'database is locked' I read about this error in documentation. But I have one question is other solution to add more rows without create 'insert' function with collections argument something like that : insert (array) ? I just want to use that function n-times without this error. That's possible?
Yes,it possible...i also got this error before....For that you just need to establish the database connection once...i have used this in my app and its working fine.
If there is no need of closing your db then then open database once like..
Add this code to default.js file
var myDatabase; //Global Variable
var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\db.sqlite';
//Create Table
SQLite3JS.openAsync(dbPath).then(function(db) {
myDatabase=db;
return db.runAsync('CREATE TABLE Item (name TEXT, price REAL, id INT PRIMARY KEY)');
});
Then you just need to use below code
// For Insert
return myDatabase.runAsync('INSERT INTO Item (name, price, id) VALUES ("'+ array[i].name+'", "48484", 1);
For array
var dbPromises = [];
var testArray = [];
//only for test purpose
//You can pass your array here directly
for (var a = 0; a < 300; a++) {
var obj = {
name: "Mango"+a,
price: 100+a,
id: a
};
testArray.push(obj);
}
for (var i = 0; i < testArray.length; i++) {
var query = 'INSERT OR REPLACE INTO Item (name, price, id) VALUES ("' + testArray[i].name + '",' + testArray[i].price + ',' + testArray[i].id + ')';
dbPromises.push(globalDatabase.allAsync(query));
}
WinJS.Promise.join(dbPromises).then(function () {
debugger;
}, function(err) {
debugger;
});
Above code is used only for less array size...bcz its taking too much time for insertion...
For fasst execution you should replace just below code
for (var i = 0; i < testArray.length; i++) {
var val = '("' + testArray[i].name + '",' + testArray[i].price + ',' + testArray[i].id + '),';
query = query + val;
if ((i + 1) % 300 == 0 || (i + 1) == testArray.length) {
query = query.replace(/,$/, "");
dbPromises.push(globalDatabase.allAsync(query));
query = 'INSERT OR REPLACE INTO Item (name, price, id) VALUES ';
}
}
Related
I'm trying to run a procedure which queries documents and adjusts some properties according to some rules which are decided by the parameters that I pass to the query.
function downsample(ageInDays, downsampleFactor) {
var collection = getContext().getCollection();
var responseBody = {
deleted: 0,
message: ""
};
var downsampledDocuments = [];
var count = 0;
collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r ' +
'WHERE (DATEDIFF(day, r.EventProcessedUtcTime, GETDATE()) > ' + ageInDays+ 'AND r.downsamplingFactor < ' + downsampleFactor + ')' +
'OR' +
'((DATEDIFF(day, r.EventProcessedUtcTime, GETDATE()) > ' + ageInDays + ' AND r.downsamplingFactor = null )' +
'ORDER BY r.did, r.resourceType ASC',
function (err, documents, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else perform the downsampling
if (!documents || !documents.length) {
var response = getContext().getResponse();
responseBody.message = "No documents found";
response.setBody(responseBody);
} else {
// We need to take into consideration that in a lot of cases, the data will already be downsampled so we
// example: previous downsampling factor of documents: 4, if a new downsampling is performed on these docs with factor 8 then we need to
var adjustedDownSamplingFactor;
if (documents[0].downsamplingFactor == null) {
adjustedDownSamplingFactor = downsampleFactor;
} else {
adjustedDownSamplingFactor = downsampleFactor / documents[0].downsamplingFactor;
}
var aggregatedDocument = documents[0];
var documentValueSum = 0;
var documentCount = 0;
var aggregatedDocumentValue = 0;
for(doc in documents){
if(!aggregatedDocument){
aggregatedDocument = doc;
}
if(documentCount >= adjustedDownSamplingFactor || aggregatedDocument.did !== doc.did || aggregatedDocument.resourceType !== doc.resourceType){
// preparing aggregated document
aggregatedDocumentValue = documentValueSum / documentCount;
aggregatedDocument.value = aggregatedDocumentValue;
aggregatedDocument.downsamplingFactor = downsampleFactor;
//Adding the downsampled data to the Array which will be uploaded to the cosmosdb
downsampledDocuments.push(aggregatedDocument);
aggregatedDocument = null;
documentCount = 0;
documentValueSum = 0;
continue;
}
documentValueSum += doc.value;
documentCount++;
}
var response = getContext().getResponse();
tryDelete(documents);
// Call the CRUD API to create a document.
tryCreate(downsampledDocuments[count], callback);
responseBody.message = "Downsampling was succesful"
response.setBody(responseBody);
}
});
So I'm not passing any documents to the query so I don't know which partition key I would have to supply to the stored procedure. Is there any way in which I can avoid having to supply a partition key? I'm calling this stored procedure from an API but keep getting a message that I should supply a partition key.
Is there any way in which I can avoid having to supply a partition
key?
Unfortunately no. You have to supply a partition key value.
Hi I'm currently working on a Twitter bot with the Twitter API and Node.JS. I want the bot to return all of my followers and some of their features in an javascript object. Something like :
{['id', 'screen_name', 'name', 'screen_name', 'followers_count',
'friends_count']}
RN my code is :
var Twitter = new TwitterPackage(config);
var options =
{
screen_name: 'mowsolicious',
};
Twitter.get('followers/ids', options, function (err, data) { // returns a list of ids
var nbFollowers = data.ids.length
var id = []
console.log(nbFollowers) // how many followers I have
for (i=0 ; i <= nbFollowers ; i++) {
ids = data.ids
var id = ids[i]
Twitter.get('users/show/' + id, function(err, data) {
console.log(id + " - " + data.name + " - " + data.screen_name + " - " + data.followers_count + " - " + data.friends_count)
})
}
})
I'm pretty sure something is terribly wrong with my method (more precisely when I put the Twitter.get thing in the loop) and it returns a bunch of undefined in the console.
I tried to work with the API doc but I'm experiencing some troubles understanding it. If someone could help that would be great.
Thank you
Most likely, you get undefined because the user is not found :
[ { code: 50, message: 'User not found.' } ]
Checking err variable would take care of that. But looking at GET followers/id documentation, you should use GET users/lookup to efficiently request mutliple user objects (up to 100 user per request with user id delimited by comma)
Also, I assume you'd like a unique callback to be called when all requests are completed, using Promises will take care of that :
var res_array = [];
function getUserInfo(id_list) {
return Twitter.get('users/lookup', {
"user_id": id_list
}).then(function(data) {
res_array.push(data);
})
.catch(function(error) {
throw error;
})
}
Twitter.get('followers/ids', function(err, data) {
if (err) {
console.log(err);
return;
}
console.log("total followers : " + data.ids.length);
var requestNum = Math.floor(data.ids.length / 100);
var remainder = data.ids.length % 100;
var promises_arr = [];
for (var i = 0; i < requestNum; i++) {
promises_arr.push(getUserInfo(data.ids.slice(i * 100, i * 100 + 100).join(",")));
}
if (remainder != 0) {
promises_arr.push(getUserInfo(data.ids.slice(requestNum * 100, requestNum * 100 + 100).join(",")));
}
Promise.all(promises_arr)
.then(function() {
for (var i in res_array) {
for (var j in res_array[i]) {
var user = res_array[i][j];
console.log(user.id + " - " +
user.name + " - " +
user.screen_name + " - " +
user.followers_count + " - " +
user.friends_count)
}
}
})
.catch(console.error);
})
List of followers can be retrieved with superface sdk , try it based on the example below
npm install #superfaceai/one-sdk
npx #superfaceai/cli install social-media/followers
const { SuperfaceClient } = require('#superfaceai/one-sdk');
const sdk = new SuperfaceClient();
async function run() {
// Load the installed profile
const profile = await sdk.getProfile('social-media/followers');
// Use the profile
const result = await profile
.getUseCase('GetFollowers')
.perform({
profileId: '429238130'
});
return result.unwrap();
}
run();
This works pretty fine
import fetch from 'node-fetch'
async function getFollowers(username) {
const response = await fetch(`https://api.twitter.com/1.1/followers/list.json?screen_name=${username}`, {
headers: {
Authorization: `Bearer ${<yourbearertoken>}`
}
});
// Parse the response as JSON
const data = await response.json();
return data.users;
}
const followers = await getFollowers("<username>");
So we have large data in JSON format.
We want to save it to a class (table) in our Parse app.
I wrote a JS script which can read the file and go through the JSON data.
But when is do the saving it all gets messed up. Its loops in the first one for ever. I understand that there is something called promise bt I don't understand how to use it? Can anyone help. My code is given below.
function processJson(result) {
object = JSON.parse(result);
verbose.textContent = "Read " + object.results.length + " objects";
var count = object.results.length;
var countAc = 0;
logger("To save: " + count);
i = 0;
while (i < count) {
if (object.results[i].areaType == 'ac') {
save(i).then(function (object) {
i = i + 1;
logger("Success: " + object.id);
});
} else {
logger("ac not found");
i = i + 1;
}
}
}
function save(i) {
logger("ac found");
var constituency = new Constituency();
constituency.set("points", object.results[i].points);
constituency.set("areaType", object.results[i].areaType);
constituency.set("name", object.results[i].name);
constituency.set("state", object.results[i].state);
constituency.set("index", object.results[i].index);
constituency.set("pc", object.results[i].pc);
constituency.set("center", object.results[i].center);
constituency.set("oldObjectId", object.results[i].objectId);
return constituency.save();
/*constituency.save().then(function(obj) {
// the object was saved successfully.
i = i + 1;
logger("Success: " + obj.id);
}, function(error) {
// the save failed.
logger(error.message);
i = i + 1;
});*/
}
I would do something like that:
function processJson(result) {
var object = JSON.parse(result);
for (var i = 0; i < object.results.legnth; i++){
var parseObject = createParseObjectFromJSONObject(object.results[i]);
parseObject.save(null).then(function(object){
console.log("object saved: " + object.id);
},function(error){
console.log("error: " + error);
});
}
}
function createParseObjectFromJSONObject(jsonObject){
var constituency = new Constituency();
constituency.set("points", jsonObject.points);
constituency.set("areaType", jsonObject.areaType);
constituency.set("name", jsonObject.name);
constituency.set("state", jsonObject.state);
constituency.set("index", jsonObject.index);
constituency.set("pc", jsonObject.pc);
constituency.set("center", jsonObject.center);
constituency.set("oldObjectId", jsonObject.objectId);
return constituency;
}
You can do it even better..
You can first push all the parse objects into array and then call saveAll to save all the parse objects in one request. This solution is good for < 1000 records .. if you have more than 1000 then you can do paging (first 1000 and saveAll, other 1000 and saveAll ....)
In this version your code will look like this:
function processJson(result) {
var object = JSON.parse(result);
var allObjects = [];
for (var i = 0; i < object.results.legnth; i++){
var parseObject = createParseObjectFromJSONObject(object.results[i]);
allObjects.push(parseObject);
}
// outside the loop we are ready to save all the objects in
// allObjects array in one service call!
if (allObjects.length > 0){
Parse.Object.saveAll(allObjects).then(function(){
console.log("all objects were saved!");
// all object ids are now available under the allObjects array..
},function(error){
console.log("error: " + error);
});
}
}
function createParseObjectFromJSONObject(jsonObject){
var constituency = new Constituency();
constituency.set("points", jsonObject.points);
constituency.set("areaType", jsonObject.areaType);
constituency.set("name", jsonObject.name);
constituency.set("state", jsonObject.state);
constituency.set("index", jsonObject.index);
constituency.set("pc", jsonObject.pc);
constituency.set("center", jsonObject.center);
constituency.set("oldObjectId", jsonObject.objectId);
return constituency;
}
Good Luck :)
I'm implementing the Cordova Sqlite plugin in a Ionic project, so far I've been able to create a database and table and make queries following the functions available through the ngCordova implementation.
I noticed there's a insertCollection function available, which I tried to test, I passed an array to it and even though the inserts are made, the entries are made with null.
This my example table definition:
CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)
I filled an array like this:
for(var i = 0; i < 250000; i++){
var index = i + 1;
firstname = firstname + ' ' + index;
var entry = {
'firstname' : firstname,
'lastname' : lastname
};
$scope.insertArray.push(entry);
}
And then made the insert like this:
$cordovaSQLite.insertCollection($rootScope.db, $scope.insertQuery, $scope.insertArray).then(function(res) {
console.log(res);
}, function (err) {
console.error(err);
});
Where insertQuery is the following:
INSERT INTO people (firstname, lastname) VALUES (?,?)
I made a select like this:
$scope.select = function() {
$scope.results = [];
var query = "SELECT firstname, lastname FROM people";
$cordovaSQLite.execute($rootScope.db, query).then(function(res) {
if(res.rows.length > 0) {
console.log('select was successful ' + res.rows.length + ' entries');
for(var i = 0; i < $scope.maxItemsToShow; i++){
$scope.results.push(res.rows.item(i));
}
} else {
console.log("No results found");
}
}, function (err) {
console.error(err);
});
}
I try to display the results on a ion-list but the values in firstname and lastname are null for all the items.
What is causing this problem?
The function insertCollection expects an array of arrays, not an array of records. The inner array must contain the values to insert in the order that the question marks (as place holders for the values) appear in the sql statement.
So you need to write:
for(var i = 0; i < 250000; i++){
var index = i + 1;
firstname = firstname + ' ' + index;
var entry = [firstname, lastname];
$scope.insertArray.push(entry);
}
I am developing a shopping cart system, where the user can add or remove products to his or her basket.
I am storing 2 things for each product in the product cookie: product barcode and price.
My code so far looks like this:
var addToBasketHandler = $(".add-product");
var removeFromBasketHandler = $(".unselect");
var Basket = {
select: function (box, cookie) {
box.addClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');
if ($.cookie(cookie) == undefined) {
$.cookie(cookie, ean + "~" + value);
} else if ($.cookie(cookie).indexOf(ean) == -1) {
$.cookie(cookie, $.cookie(cookie) + "|" + ean + "~" + value);
}
},
deselect: function (box, cookie) {
box.removeClass("selected");
// code to delete the cookie value
}
};
$(document).ready(function () {
$(addToBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.select(box, "productCookie");
});
$(removeFromBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.deselect(box, "productCookie");
});
});
And after adding 3 products to my cart, my cookie looks like this:
productCookie = 9918430821007~12.00 | 7C9918430831006~3.00 | 7C7501031311309~50.30
Please help on how I could remove only the selected product from this cookie list above.
FYI I am using jquery + jquery cookie
Try
deselect: function (box, cookie) {
box.removeClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');
var val = ean + "~" + value; //value to be removed
if ($.cookie(cookie) !== undefined) {
var cookie_val = $.cookie(cookie);
if (cookie_val.indexOf(val) !== -1) { //check value present in cookie
var arr = cookie_val.replace(' ', '').split('|'); //remove spaces and split with |
var index = arr.indexOf(val);//get index of value to be deleted
arr.splice(index, 1); //remove value from array
$.cookie(cookie, arr.join(' | ')); //convert array to sting using join and set value to cookie
}
}
}