it('should fulfill a transfer twice without error', function * () { const id = uuid() const fulfillStub = sinon.stub() this.pluginA.on('outgoing_fulfill', fulfillStub) yield this.pluginA.sendTransfer(Object.assign({ id: id, amount: '1', executionCondition: condition, expiresAt: makeExpiry(timeout) }, transferA)) yield this.pluginB.fulfillCondition(id, fulfillment) yield this.pluginB.fulfillCondition(id, fulfillment) sinon.assert.calledTwice(fulfillStub) })
socket.on('addagent', function(agentname){ if ((agentname != null) && (agentname!="")){ // store the username in the socket session for this client socket.isuser = false; socket.agentname = agentname; // store the room name in the socket session for this client var idroom = uuid(); // Se toma el identificador como id del room currentroom = idroom; socket.room = idroom; //cantidad = 0 esta cantidad if (agentnames.length == 0){ agentnames[0] = ({"nombre":agentname, "cantidad":0, "idroom":idroom}); // add the client's username to the global list //rooms[0] = agentname; } else{ agentnames.push ({"nombre":agentname, "cantidad":0, "idroom":idroom}); // add the client's username to the global list //rooms[agentname] = agentname; } // Obtener numero de rooms que puede atender el agente // send client to room por default socket.join(idroom); //socket.join(agentname+'02'); // echo to client they've connected socket.emit('updatechat', 'MENSAJERO RTC', 'AGENTE: ' + agentname,''); // echo to room 1 that a person has connected to their room socket.broadcast.to(idroom).emit('updatechat', 'MENSAJERO RTC', agentname + ' es el agente disponible en esta sala', ''); socket.emit('updaterooms', agentnames, agentname); socket.emit('conectedagent',idroom); console.log('Se conecto el agente: ' + agentname); } });
const task = (state, action) => { switch (action.type) { case ADD_TASK: return { id: uuid(), name: action.task.name, state: 'to-do' } case START_TASK: if (state.id !== action.taskId) { return state } return Object.assign({}, state, { state: 'in-progress' }) default: return state } }
const project = (state, action) => { switch (action.type) { case ADD_PROJECT: return { id: uuid(), name: action.name, tasks: calculateCounters([]) } case ADD_TASK: case START_TASK: if (state.id !== action.id) { return state } return Object.assign({}, state, { tasks: tasks(state.tasks, action) }) default: return state } }
it('should fulfill a transfer after being unsuccessful', function * () { const id = uuid() const promise = new Promise(resolve => this.pluginA.once('outgoing_fulfill', resolve)) yield this.pluginA.sendTransfer(Object.assign({ id: id, amount: '1', executionCondition: condition, expiresAt: makeExpiry(timeout) }, transferA)) yield this.pluginB.fulfillCondition(id, 'garbage') .catch((e) => { assert.equal(e.name, 'InvalidFieldsError') }) yield this.pluginB.fulfillCondition(id, fulfillment) yield promise })
it('should reject for an incomplete transfer', function (done) { const id = uuid() this.pluginB.once('incoming_prepare', (transfer) => { assert.equal(transfer.id, id) assert.equal(transfer.ledger, this.prefix) this.pluginA.getFulfillment(id) .catch((e) => { assert.equal(e.name, 'MissingFulfillmentError') done() }).catch(done) }) this.pluginA.sendTransfer(Object.assign({ id: id, amount: '1', executionCondition: condition, expiresAt: makeExpiry(timeout) }, transferA)).catch(done) })
it('should not reject transfer with condition as sender', function (done) { const id = uuid() this.pluginB.once('incoming_prepare', (transfer) => { assert.equal(transfer.id, id) assert.equal(transfer.ledger, this.prefix) this.pluginA.rejectIncomingTransfer(id, rejectionMessage) .catch((e) => { assert.equal(e.name, 'NotAcceptedError') done() }) .catch(done) }) this.pluginA.sendTransfer(Object.assign({ id: id, amount: '1', executionCondition: condition, expiresAt: makeExpiry(timeout) }, transferA)).catch(done) })
router.post('/v2/upload', upload.single('file'), function (req, res, next) { if (req.file.path) { var id = uuid(); var obj = { id: id, issueType: null, priority: null, attachement: req.file, description: null, iemail: null } factory.insert(obj, function (err, data) { if (err) { res.json({ isSuccess: false, info: err }); return; } res.json({ isSuccess: true, info: data }); }) } else { res.json({ isSuccess: false, info: 'file not found!' }); } });
Ambisafe.generateAccount = function (currency, password, salt) { var account, key, keyPair, iv; if (!currency || !password) { console.log('ERR: currency and password are required'); return; } if (!salt) { salt = uuid4(); } key = Ambisafe.deriveKey(password, salt); account = new Ambisafe.Account(); account.set('key', key); account.set('salt', salt); if (currency) { account.set('currency', currency); } keyPair = Ambisafe.generateKeyPair(); account.set('private_key', keyPair.private_key); account.set('public_key', keyPair.public_key); iv = Ambisafe.generateRandomValue(16); account.set('iv', iv); account.set('data', Ambisafe.encrypt( new Buffer(account.get('private_key'), 'hex'), iv, key )); return account; };
it('should notify the receiver of a fulfillment', function (done) { const id = uuid() this.pluginB.once('incoming_fulfill', (transfer) => { assert.equal(transfer.id, id) assert.equal(transfer.ledger, this.prefix) done() }) this.pluginB.once('incoming_prepare', (transfer) => { assert.equal(transfer.id, id) assert.equal(transfer.ledger, this.prefix) this.pluginB.fulfillCondition(id, fulfillment) .catch(done) }) this.pluginA.sendTransfer(Object.assign({ id: id, amount: '1', executionCondition: condition, expiresAt: makeExpiry(timeout) }, transferA)) })
it('should reject a transfer with a condition', function (done) { const id = uuid() this.pluginA.once('outgoing_reject', (transfer, reason) => { assert.equal(transfer.id, id) assert.equal(transfer.ledger, this.prefix) assert.deepEqual(reason, rejectionMessage) done() }) this.pluginB.once('incoming_prepare', (transfer) => { assert.equal(transfer.id, id) assert.equal(transfer.ledger, this.prefix) this.pluginB.rejectIncomingTransfer(id, rejectionMessage) }) this.pluginA.sendTransfer(Object.assign({ id: id, amount: '1', executionCondition: condition, expiresAt: makeExpiry(timeout) }, transferA)).catch(done) })
it('should not reject an optimistic transfer', function (done) { const id = uuid() this.pluginB.once('incoming_transfer', (transfer) => { assert.equal(transfer.id, id) assert.equal(transfer.amount - 0, 1.0) assert.equal(transfer.account, transferB.account) this.pluginB.rejectIncomingTransfer(id, rejectionMessage) .then(() => { assert(false) }) .catch((e) => { assert.equal(e.name, 'TransferNotConditionalError') done() }) .catch(done) }) this.pluginA.sendTransfer(Object.assign({ id: id, amount: '1' }, transferA)).catch(done) })
function createItem(itemName) { return {thingId: "markandrew:" + uuid(), attributes: {name: itemName, type: "purchase"}}; }
socket.on('adduser', function(username){ // cuando un usuario se conecta se produce este evento socket.posRoom =''; if ((username != null) && (username !="")){ // store the username in the socket session for this client socket.username = username; // store the room name in the socket session for this client //se genera un identificador para el room var waitforagent = true; var idroom = uuid(); // Se toma el identificador como id del room currentroom = idroom; agentroom = '0'; //Se busca al agente disponible de los agentes conectados for (var agentname in agentnames){ //console.log(agentnames[agentname].nombre); if (agentnames[agentname].cantidad < 3 ){ agentnames[agentname].cantidad = agentnames[agentname].cantidad + 1; console.log(agentnames[agentname].cantidad); socket.posRoom = ("0" + agentnames[agentname].cantidad).slice(-2); agentroom = agentnames[agentname].idroom; waitforagent = false; break; } } // Sino encontro agente disponible se manda a la lista de espera. if (waitforagent){ //Se agrega a la lista de usuario para que if (userlist.length == 0){ userlist[0] = ({"nombre":username, "idroom":currentroom}); // add the client's username to the wait list } else{ userlist.push ({"nombre":username, "idroom":currentroom}); // add the client's username to the wait list console.log(userlist); } socket.isuser = true; socket.room = currentroom; // add the client's username to the global list if (usernames.length == 0){ usernames[0] = ({"nombre":username, "socketid":socket.id}); // add the client's username to the wait list } else{ usernames.push ({"nombre":username, "socketid":socket.id}); // add the client's username to the wait list } //usernames[username] = username; // send client to room 1 socket.join(currentroom); socket.emit('updatechat', 'MENSAJERO RTC', 'Todos nuestros agentes estan ocupados, por favor espere'); } else{ console.log(currentroom); // Si es usuario asigna un valor verdadero al flag socket.isuser = true; socket.room = currentroom; // add the client's username to the global list if (usernames.length == 0){ usernames[0] = ({"nombre":username, "socketid":socket.id}); // add the client's username to the wait list } else{ usernames.push ({"nombre":username, "socketid":socket.id}); // add the client's username to the wait list } //usernames[username] = username; // send client to room 1 socket.join(currentroom); // eco al room del agente //socket.broadcast.to(agentna).emit('newuser', 'MENSAJERO RTC',username, currentroom, socket.posRoom); // eco al room del agente socket.broadcast.to(agentroom).emit('newuser', 'MENSAJERO RTC',username, currentroom, socket.posRoom); // echo to client they've connected //El evento updatechat envia usuario que emite, Datos, Posicion (se descontinuara), ID del room (solo en caso de que el mensaje vaya para un usuario y no un agente) socket.emit('updatechat', 'MENSAJERO RTC', 'Te esta atendiendo ' + currentroom, socket.posRoom, currentroom); // echo to room 1 that a person has connected to their room socket.broadcast.to(agentroom).emit('updatechat', 'MENSAJERO RTC', username + ' se ha conectado a ' + currentroom, ''); socket.emit('updaterooms', agentnames, agentroom); console.log('Se conecto el usuario: ' + username); //var query = client.query("INSERT INTO msjsolicitudes(usuario,mensaje,fechahora) VALUES ($1,$2,CURRENT_TIMESTAMP)", [username,'se conecto el usuario'], function(err, result) { // console.log(result); // }) } } });
import uuid from 'uuid4' const initialState = { projects: [ { id: uuid(), name: 'Sample Project', tasks: { count: 0, todo: 0, inProgress: 0, list: [] } }, { id: uuid(), name: 'Another Project', tasks: { count: 0, todo: 0, inProgress: 0, list: [] } } ] } export default initialState
var Device=function(options){ this.name=options.name; this.port=options.port ||0 ; this.ip_address=options.ip_address || this.getIp(); this.root_url="http://"+this.ip_address; this.path=options.setup_xml||"/setup.xml"; this._location=this.root_url+":"+this.port+this.path this._ttl=options._ttl || 86400; this.serial=this.make_uuid(this.name); this.uuid=uuid(); this.persistent_uuid="Socket-1_0-"+this.serial; this.udn="uuid:"+this.persistent_uuid+"::urn:Belkin:device:**"; //this.udn="uuid:Socket-1_0-5916b697463686::urn:Belkin:device:**" this.actionHandler=options.actionHandler||{ "on":function(){console.log("turned on");return true}, "off":function(){console.log("turned off");return true} } var self=this; this.httpServer=require('http').createServer((request,res)=>{ var body=[]; var headers = request.headers; var method = request.method; var url = request.url; request.on('error', function(err) { console.error(err); }).on('data', function(chunk) { body.push(chunk); }).on('end', function() { body = Buffer.concat(body).toString(); // At this point, we have the headers, method, url and body, and can now // do whatever we need to in order to respond to this request. if (url.indexOf("/setup.xml")==0){ // Return the xml file res.writeHead(200,{ "CONTENT-TYPE":"text/xml", "SERVER":"Unspecified, UPnP/1.0, Unspecified" }) console.log("writing response"); res.write(XML_TEMPLATE(self.name,self.serial)) res.end(); }else if(headers["soapaction"]=="\"urn:Belkin:service:basicevent:1#SetBinaryState\""){ console.log("control"); console.log(body); if (body.indexOf("<BinaryState>1</BinaryState>")>-1){ // Turn on. TODO: use XML parser console.log(self.actionHandler['on']()); res.writeHead(200,defaultResposneHead()) }else if(body.indexOf("<BinaryState>0</BinaryState>")>-1){ // Trun off console.log(self.actionHandler['off']()); res.writeHead(200,defaultResposneHead()) }else{ res.writeHead(404,defaultResposneHead()) } res.end(); }else{ res.writeHead(200,defaultResposneHead()) res.end(); } }); }); }
function createStore(storeName) { return {thingId: "markandrew:" + uuid(), attributes: {name: storeName, type: "store"}}; }
async function main() { const mosques = await getMosquesFromJAKIM(); const updatedMosques = []; const removedMosques = []; for (let id of currentDataKeys) { const currentItem = currentData[id]; if (currentItem.type !== "Mosque" || (currentItem.address && currentItem.address.indexOf("Malaysia ") === -1)) { continue; } const matchedItem = mosques.filter((item) => { return currentItem.source_musolla_id === item.id || currentItem.location === item.location; }); if (matchedItem.length === 0) { removedMosques.push(currentItem); delete currentData[currentItem.uuid]; } else { const item = matchedItem[0]; currentData[id].name = item.name; currentData[id].address = item.address; if (item.phone) { currentData[id].contact = item.phone; } else { delete currentData[id].contact; } if (item.desc) { currentData[id].remarks = item.desc; } if (item.directions) { currentData[id].directions = item.directions; } if (item.provision) { currentData[id].provision = item.provision; } item.updatedAt = moment().format(); updatedMosques.push(currentData[id]); } }; if (updatedMosques.length !== 0) { console.log("Updated Mosques (" + updatedMosques.length + "):"); // console.log(updatedMosques); } console.log(""); if (removedMosques.length !== 0) { console.log("Removed Mosques (" + removedMosques.length + "):"); // console.log(removedMosques); } console.log(""); const newMosques = []; const newMosquesId = []; for (let item of mosques) { if (newMosquesId.indexOf(item.id) > -1) { continue; } const matchedItem = currentMosques.filter((currentItem) => { return currentItem.source_musolla_id === item.id || currentItem.location === item.location; }); if (matchedItem.length === 0) { const newItem = { address: item.address, contact: item.phone, createdAt: moment().format(), location: item.location, name: item.name, type: 'Mosque', updatedAt: moment().format(), uuid: uuid(), geohash: '', remarks: item.desc, source_musolla_id: item.id, provision: item.provision, directions: item.directions, }; newMosques.push(newItem); newMosquesId.push(item.id); newItem.geohash = ngeohash.encode(newItem.location.latitude, newItem.location.longitude, 10); currentData[newItem.uuid] = newItem; } }; if (newMosques.length !== 0) { console.log("New Mosques (" + newMosques.length + "):"); // console.log(newMosques); } fs.writeFileSync('../data.json', JSON.stringify(currentData, null, 2)); };
function getId() { return uuid(); }