Can't get source and target uuid's of a connection's endpoints - jsplumb

I want to reach source and target uuid's of a connection's endpoints in "beforeDrop" event.
I tried;
instance.bind("beforeDrop", function (info) {
alert(info.connection.source.getUuid())
});
But it does not work. How can I reach them?

getUuid() is the Endpoint Class method, so:
instance.bind("beforeDrop", function (info) {
alert(info.connection.endpoints[0].getUuid());
return true; /* if you need to establish connection */
});
But if you need to get endpoints uuids of already established connection the best way will be to use "connectionDragStop" event:
instance.bind("connectionDragStop", function(conn, ev) {
var uuids = conn.getUuids();
});

Related

interaction between the oracle smart contract and the oracle service

I want to use this code to recover the temperature and return the result to the smart contract
contract CMCOracle {
// Contract owner address public owner;
// BTC Marketcap Storage uint public btcMarketCap;
// Callback function event CallbackGetBTCCap();
function CMCOracle() public {
owner = msg.sender;
}
function updateWe() public {
// Calls the callback function
CallbackGetBTCCap();
}
function setBTCCap(uint cap) public {
// If it isn't sent by a trusted oracle
// a.k.a ourselves, ignore it
require(msg.sender == owner);
btcMarketCap = cap;
}
function getBTCCap() constant public returns (uint) {
return btcMarketCap;
}
}
var fetch = require('fetch')
var OracleContract = require('./build/contracts/CMCOracle.json')
var contract = require('truffle-contract')
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('https://localhost:8545'));
// Truffle abstraction to interact with our
// deployed contract
var oracleContract = contract(OracleContract);
oracleContract.setProvider(web3.currentProvider);
// Dirty hack for web3#1.0.0 support for localhost testrpc
// see https://github.com/trufflesuite/truffle-contract/issues/56#issuecomment-331084530
if (typeof oracleContract.currentProvider.sendAsync !== "function") {
oracleContract.currentProvider.sendAsync = function() {
return oracleContract.currentProvider.send.apply(
oracleContract.currentProvider, arguments
);
};
}
// Get accounts from web3 web3.eth.getAccounts((err, accounts) => {
oracleContract.deployed().then((oracleInstance) => {
// Watch event and respond to event
// With a callback function
oracleInstance.CallbackGetBTCCap()
.watch((err, event) => {
// Fetch data
// and update it into the contract
fetch.fetchUrl('https://api.coinmarketcap.com/v1/global/',(err, m, b)=> {
const cmcJson = JSON.parse(b.toString());
const btcMarketCap = parseInt(cmcJson.total_market_cap_usd);
// Send data back contract on-chain
oracleInstance.setBTCCap(btcMarketCap, {from: accounts[0]});
})
})
}).catch((err) => { console.log(err) });
but I can't understand how to change the code.
How does the smart contract pass a city whose temperature I want to know to the oracle service?
What API does the oracle service use to fetch the temperature from the external source?
How should i change this code?
source: https://kndrck.co/posts/ethereum_oracles_a_simple_guide/
A smart contract does not interact with the API but the Oracle itself. Normally, it should have been two different contracts like one of the contracts should be separated from the external world. Oracle contract is the API for blockchain, which is basically residing in the blockchain. You can reach out to the contract by means of contract wrapper libraries (web3j, ethereumj)
The contract wrapper will fetch the data from API as JSON. And then the application will convert the data into primitive data that has been defined in the Solidity language. Once it is done, data will send via emit-event functions continuously to the blockchain as long as the application fetched data from the API. In the end, you will have a deterministic database source so that you can copy this source and transfer another place as it is.
For instance, you may change the API endpoint called "https://api.coinmarketcap.com/v1/global/" with "api.openweathermap.org/data/2.5/weather" and data structures (link: https://openweathermap.org/current).

Sails JS: How to store and access current user data?

I already checked a lot of references and found good sources like this one: Get current user from inside the model in Sails. So I'm asking for best practices and your experiences.
As I've developed a quite complex platform based on JWT-Authentication I have to fix the major mistake to store the current user data (while user requests something) on my sails instance. I know that this leads to major security leaks (for more than one user).
The question is: How can I store and access current user data without passing the session object through almost all methods I've created?
Is passing the session object around through all helpers, utilities etc. the only way to solve this? Instead of using a centralized Service like: UserService.getCurrentUser();
Any help is highly appreciated. Thanks!
If you're asking if there's a way to globalize the user data so that it's magically available to all your methods, the short answer is that there's no safe way to do this in Node (let alone in Sails.js). Node's single-threaded nature makes it impossible to maintain state in that way.
Some folks have solved this in Sails by using a globally-applied policy that looks up the user and adds it to the request:
// api/policies/fetch-user.js
module.exports = function fetchUserPolicy (req, res, next) {
// Get the user ID out of the session.
var userId = req.session.userId;
// If there's no user logged in, just continue.
if (!userId) { return next(); }
// Look up the user by ID.
User.findOne({id: userId}).exec(function(err, user) {
if (err) { return res.serverError(err); }
if (!user) { return res.serverError(new Error('Could not find user in session!')); }
// Add the user info to the request.
req.user = user;
// Continue the request.
return next();
});
};
There's nothing wrong with this code, but we don't recommend it because best practice is to use policies purely for access control. Instead, you can do pretty much the same exact thing in a custom hook:
// api/hooks/fetch-user.js
module.exports = function fetchUserHook(sails) {
return {
// Add some routes to the app.
routes: {
// Add these routes _before_ anything defined in `config/routes.js`.
before: {
// Add a route that will match everything (using skipAssets to...skip assets!)
'/*': {
fn: function(req, res, next) {
// Get the user ID out of the session.
var userId = req.session.userId;
// If there's no user logged in, just continue.
if (!userId) { return next(); }
// Look up the user by ID.
User.findOne({id: userId}).exec(function(err, user) {
if (err) { return res.serverError(err); }
if (!user) { return res.serverError(new Error('Could not find user in session!')); }
// Add the user info to the request.
req.user = user;
// Continue the request.
return next();
});
},
skipAssets: true
}
}
}
};
};
Either way, you'll still need to pass req around to any methods that want to use the user info that was fetched.

Event each time component becomes visible

Is there a way in Angular2 to have an event fired when my component becomes visible?
It is placed in a tabcontrol and I want to be notified when the user switches. I'd like my component to fire an event.
What I finally did (which is not very beautiful but works while I don't have a better way to do it...) is to use the ngAfterContentChecked() callback and handle the change myself.
#ViewChild('map') m;
private isVisible: boolean = false;
ngAfterContentChecked(): void
{
if (this.isVisible == false && this.m.nativeElement.offsetParent != null)
{
console.log('isVisible switched from false to true');
this.isVisible = true;
this.Refresh();
}
else if (this.isVisible == true && this.m.nativeElement.offsetParent == null)
{
console.log('isVisible switched from true to false');
this.isVisible = false;
}
}
There is no such event, but if you're using a tab control, the proper way to do this would be to create a tab change #Output for your tab control if it's custom, otherwise, most tab controls (like ng-bootstrap) have some tab change event as well.
If your component has to be aware of this, you can use this tab change event to detect which tab is visible, and if you know which tab is visible, you also know if your component is visible or not. So you can do something like this:
onTabChange(event) {
this.currentTab = /** Get current tab */;
}
And then you can send it to your component itself if you have an input:
#Input() activated: boolean = false;
And then you can apply it with:
<my-component [activated]="currentTab == 'tabWithComponent'"></my-component>
Now you can listen to OnChanges to see if the model value activated changed to true.
You can also refactor this to use a service with an Observable like this:
#Injectable()
export class TabService {
observable: Observable<any>;
observer;
constructor() {
this.observable = Observable.create(function(observer) {
this.observer = observer;
});
}
}
When a component wishes to listen to these changes, it can subscribe to tabService.observable. When your tab changes, you can push new items to it with tabService.observer.next().
You can use the ngAfterViewInit() callback
https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
Update
The new Intersection Observer API can be used for that
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
See also https://stackoverflow.com/a/44670818/217408
For those watching at home, you can now use ngAfterContentInit() for this, at least on Ionic anyway.
https://angular.io/guide/lifecycle-hooks
Best way to work around this limitation of Angular is to use a shared service that provides a Subject your component can subscribe to. That way new values could be pushed onto the Observable and the components which subscribe get the newest data and can act accordingly.
Fyi: The difference between a normal Observable and a Subject is that a Subject is multicast whereas an Observable could only be subscribed to by one Subscriber.
As a small example I show you a possible implementation of a shared-service and following the subscription inside the component that needs this new data.
Shared-service:
// ...
private actualNumberSubject = new Subject<number>()
public actualNumber$ = this.actualNumberSubject.asObservable()
/**
* #info CONSTRUCTOR
*/
constructor() {}
/**
* #info Set actual number
*/
setActualNumber(number: number) {
this.actualNumberSubject.next(internalNumber)
}
// ...
Push new value onto the subject from anywhere where shared.service is imported:
// ...
this.sharedService.setActualNumber(1)
Subscribe to sharedService.actualNumber$ in component to process/display that new data:
// ...
this.sharedService.actualNumber$.subscribe(number => {
console.log(number)
// e.g. load data freshly, etc.
})
// ...
I have the same purpose and cannot get a satisfy approach to it. The first answer will call so many times.
There is a compromised way I used, of course, not elegant either.
In parent component, I set a method:
parentClick() {
setTimeout(() => {
// TO-DO
This.commonService.childMethod();
}, time);
}
Maybe the method not accurate in time, but in some way, you reach the destiny.

Is it possible to add several handlers to the same socket.io.on event?

In my game application I would like to have general class for handling socket connection and authorization and several classes for event handling, in such a way:
//loading game/lobby/other socket routers
...
var socketRouter = function(server) {
var io = Io(server);
io.use(socketioJwt.authorize({
secret: config.secretKey,
handshake: true
}));
io.on("connection", function(socket) {
lobbySocketRouter(socket);
gameSocketRouter(socket);
//other routers
...
socket.on("disconnect", function() {
console.log("DISCONNECTED", socket.id);
});
});
};
It's not a problem to generate unique event names for different routers to not interfere with each other. The problem is in disconnect event - I want every router having possibility to perform right action on it. Is it correct to add own handler to disconnect event in every router like this so each of them would trigger:
//lobbySocketRouter
socket.on("disconnect", function() {
//handling lobbySocketRouter special actions
});
...
//gameSocketRouter
socket.on("disconnect", function() {
//handling gameSocketRouter special actions
});
?
I want every router having possibility to perform right action on it. Is it correct to add own handler to disconnect event in every router like this so each of them would trigger:
"route" I guess you're talking about the Namespaces, you can handle multiples "routers", and then treat each disconnection event depending on the Namespace.
I've wrote in my previous answer a template application to get multiple namespaces inside an Array:
socket.on('disconnect', disconnectCallback(socket,ns));
function disconnectCallback(socket,ns) {
return function(msg) {//we return a callback function
if(ns==="blabla") {
console.log("Disconnected from blabla");
socket.broadcast.send("It works! on blabla");
}
.
.
.
}
};
You can then create multiple disconnection behaviors based on the Namespace, hope it helps.
Please let me know if you need something else :-)

How can I ensure the writable flag is true before send()?

I am creating an abstraction layer for Dart WebSocket who is also protocol compatible with Socket.IO, but it has a problem I can not solve.
The follow code convert the HttpRequest into a WebSocket and save the socket instance on the Transport... Here you can see I change the value of the writable flag to true in order to inform the socket is open.
WebSocketTransformer.upgrade(req).then((socket) {
this._socket = socket;
this.writable = true;
this._socket.handleError(() {
this.onClose();
});
// start listen the socket;
socket.listen((packet) {
this.onData(packet);
});
}).catchError((Exception e) {
this.onError('Can\'t conenct with the socket.', e.toString());
});
(The full code can be founded here.)
When I debug the code first the debugger stops inside that closure and only then stops here, where the check is make but writable still false :/
void flush([_]) {
if (this._readyState != SocketStates.closed && this.transport.writable &&
!this._writeBuffer.isEmpty) {
(The full code can be founded here)
I really need help...
Your constructor makes an async call but doesn't return a future (not possible in a constructor)
WebSocketTransformer.upgrade(req).then
Use a static method instead which returns Future<WebSocketTransformer> or use an init method where you initiaize your class after creation.
There might be other problems but yor code does not show how you use your class therefore its hard to tell.

Resources