<commit_before>const riot = require('riot');
const route = require('riot-route').default;
const WebSocketEvents = require('./helpers/web-socket-events');
const StreamingRest = require('./helpers/StreamingRest');

(async () => {

	const mixin = {};

	// userId

	const userIdElement = document.getElementsByName('frost-userId').item(0);
	if (userIdElement != null)
		mixin.userId = userIdElement.content;

	mixin.getLoginStatus = () => mixin.userId != null;

	// WebSocket (ログインされている時のみ)

	if (mixin.getLoginStatus()) {
		const secure = location.protocol == 'https:';

		let webSocket;
		try {
			webSocket = await WebSocketEvents.connectAsync(`${secure ? 'wss' : 'ws'}://${location.host}`);
			webSocket.addEventListener('close', (ev) => { console.log('close:', ev); });
			webSocket.addEventListener('error', (ev) => { console.log('error:', ev); });
			WebSocketEvents.init(webSocket);
			mixin.webSocket = webSocket;
		}
		catch (err) {
			alert('WebSocketの接続に失敗しました');
			console.log(err);
			return;
			// noop
		}

		const streamingRest = new StreamingRest(webSocket);
		try {
			const rest = await streamingRest.requestAsync('get', `/users/${mixin.userId}`);
			mixin.user = rest.response.user;
		}
		catch (err) {
			alert('ユーザー情報の取得に失敗しました');
			console.log(err);
			return;
		}
	}

	// siteKey

	const siteKeyElement = document.getElementsByName('frost-siteKey').item(0);
	if (siteKeyElement != null)
		mixin.siteKey = siteKeyElement.content;

	// csrf

	const csrfElement = document.getElementsByName('frost-csrf').item(0);
	if (csrfElement != null)
		mixin.csrf = csrfElement.content;

	// central observer

	const central = riot.observable();
	mixin.central = central;

	// routings

	const changePage = (pageId, params) => {
		central.trigger('change-page', pageId, params || {});
	};

	route.base('/');

	route('', () =>
		changePage(mixin.getLoginStatus() ? 'home' : 'entrance'));

	route('general', () => {
		if (!mixin.getLoginStatus()) {
			changePage('error', { message: 'forbidden' });
			return;
		}
		changePage('home', { timelineType: 'general' });
	});

	route('dev', () =>
		changePage('dev'));

	route('userlist', () =>
		changePage('userlist'));

	route('users/*', (screenName) =>
		changePage('user', { screenName }));

	route('posts/*', (postId) =>
		changePage('post', { postId }));

	route('*', () =>
		changePage('error', { message: 'page not found' }));

	// loading components

	// - general
	require('./tags/frost-logout-button.tag');
	require('./tags/frost-post-status.tag');
	require('./tags/frost-timeline.tag');
	require('./tags/frost-hint.tag');
	// - container
	require('./tags/frost-container.tag');
	require('./tags/frost-global-nav.tag');
	require('./tags/frost-page-switcher.tag');
	require('./tags/frost-footer.tag');
	// - entrance
	require('./tags/frost-page-entrance.tag');
	require('./tags/frost-form-login.tag');
	require('./tags/frost-form-signup.tag');
	// - home
	require('./tags/frost-page-home.tag');
	require('./tags/frost-home-logo.tag');
	require('./tags/frost-form-create-status.tag');
	// - user
	require('./tags/frost-page-user.tag');
	require('./tags/frost-follow-button.tag');
	require('./tags/frost-tabs-user-page.tag');
	// - userlist
	require('./tags/frost-page-userlist.tag');
	// - post
	require('./tags/frost-page-post.tag');
	// - dev
	require('./tags/frost-page-dev.tag');
	require('./tags/frost-applications.tag');
	require('./tags/frost-form-create-application.tag');
	// - error
	require('./tags/frost-page-error.tag');

	// recaptcha

	const recaptchaAsync = () => new Promise((resolve) => {
		const t = setInterval(() => {
			if (mixin.siteKey == null || typeof grecaptcha != 'undefined') {
				clearInterval(t);
				resolve();
			}
		}, 50);
	});
	await recaptchaAsync();

	// mount

	riot.mixin(mixin);
	riot.mount('frost-container');

	// start routing

	route.start(true);

})().catch(err => {
	console.log('何かがおかしいよ');
	console.log(err);
});
<commit_msg>update<commit_after>const riot = require('riot');
const route = require('riot-route').default;
const WebSocketEvents = require('./helpers/web-socket-events');
const StreamingRest = require('./helpers/StreamingRest');

(async () => {

	const mixin = {};

	// userId

	const userIdElement = document.getElementsByName('frost-userId').item(0);
	if (userIdElement != null)
		mixin.userId = userIdElement.content;

	mixin.getLoginStatus = () => mixin.userId != null;

	// WebSocket (ログインされている時のみ)

	if (mixin.getLoginStatus()) {
		const secure = location.protocol == 'https:';

		let webSocket;
		try {
			webSocket = await WebSocketEvents.connectAsync(`${secure ? 'wss' : 'ws'}://${location.host}`);
			webSocket.addEventListener('close', (ev) => { console.log('close:', ev); });
			webSocket.addEventListener('error', (ev) => { console.log('error:', ev); });
			WebSocketEvents.init(webSocket);
			mixin.webSocket = webSocket;
		}
		catch (err) {
			alert('WebSocketの接続に失敗しました');
			console.log(err);
			return;
		}

		const streamingRest = new StreamingRest(webSocket);
		try {
			const rest = await streamingRest.requestAsync('get', `/users/${mixin.userId}`);
			mixin.user = rest.response.user;
		}
		catch (err) {
			alert('ユーザー情報の取得に失敗しました');
			console.log(err);
			return;
		}
	}

	// siteKey

	const siteKeyElement = document.getElementsByName('frost-siteKey').item(0);
	if (siteKeyElement != null)
		mixin.siteKey = siteKeyElement.content;

	// csrf

	const csrfElement = document.getElementsByName('frost-csrf').item(0);
	if (csrfElement != null)
		mixin.csrf = csrfElement.content;

	// central observer

	mixin.central = riot.observable();

	// routings

	const changePage = (pageId, params) => {
		mixin.central.trigger('change-page', pageId, params || {});
	};

	route.base('/');

	route('', () =>
		changePage(mixin.getLoginStatus() ? 'home' : 'entrance'));

	route('general', () => {
		if (!mixin.getLoginStatus()) {
			changePage('error', { message: 'forbidden' });
			return;
		}
		changePage('home', { timelineType: 'general' });
	});

	route('dev', () =>
		changePage('dev'));

	route('userlist', () =>
		changePage('userlist'));

	route('users/*', (screenName) =>
		changePage('user', { screenName }));

	route('posts/*', (postId) =>
		changePage('post', { postId }));

	route('*', () =>
		changePage('error', { message: 'page not found' }));

	// loading components

	// - general
	require('./tags/frost-logout-button.tag');
	require('./tags/frost-post-status.tag');
	require('./tags/frost-timeline.tag');
	require('./tags/frost-hint.tag');
	// - container
	require('./tags/frost-container.tag');
	require('./tags/frost-global-nav.tag');
	require('./tags/frost-page-switcher.tag');
	require('./tags/frost-footer.tag');
	// - entrance
	require('./tags/frost-page-entrance.tag');
	require('./tags/frost-form-login.tag');
	require('./tags/frost-form-signup.tag');
	// - home
	require('./tags/frost-page-home.tag');
	require('./tags/frost-home-logo.tag');
	require('./tags/frost-form-create-status.tag');
	// - user
	require('./tags/frost-page-user.tag');
	require('./tags/frost-follow-button.tag');
	require('./tags/frost-tabs-user-page.tag');
	// - userlist
	require('./tags/frost-page-userlist.tag');
	// - post
	require('./tags/frost-page-post.tag');
	// - dev
	require('./tags/frost-page-dev.tag');
	require('./tags/frost-applications.tag');
	require('./tags/frost-form-create-application.tag');
	// - error
	require('./tags/frost-page-error.tag');

	// recaptcha

	const recaptchaAsync = () => new Promise((resolve) => {
		const t = setInterval(() => {
			if (mixin.siteKey == null || typeof grecaptcha != 'undefined') {
				clearInterval(t);
				resolve();
			}
		}, 50);
	});
	await recaptchaAsync();

	// mount

	riot.mixin(mixin);
	riot.mount('frost-container');

	// start routing

	route.start(true);

})().catch(err => {
	console.log('何かがおかしいよ');
	console.log(err);
});
<|endoftext|>


<commit_before>var assert = require("assert"),
    ManagedObjectModel = require('./../lib/ManagedObjectModel'),
    ManagedObjectContext = require('./../lib/ManagedObjectContext'),
    PersistentStoreCoordinator = require('./../lib/PersistentStoreCoordinator'),
    moment = require('moment');

//var store_url = 'mysql://root@localhost/test';
var store_url = 'sqlite://:memory:';

describe('mysqlattributes',function(){
    var objectModel = new ManagedObjectModel(__dirname + '/schemes/attribute-test-model.yaml');
    var invalidObjectModel = new ManagedObjectModel(__dirname + '/schemes/attribute-invalid-test-model.yaml');
    it('should throw error for invalid model',function(done){
        storeCoordinator = new PersistentStoreCoordinator(invalidObjectModel,{logging:console.log});

        storeCoordinator.addStore(store_url);
        storeCoordinator.persistentStores[0].syncSchema({force:true},function(err){
            assert.throws(function(){
                if(err)throw err;
            },function(err){
                return err.message == 'unknown attribute type blah';
            })
            done()
        })
    })
    it('shouldn\'t throw error for valid model',function(done){
        storeCoordinator = new PersistentStoreCoordinator(objectModel,{logging:console.log});

        storeCoordinator.addStore(store_url);
        storeCoordinator.persistentStores[0].syncSchema({force:true},function(err){
            assert.ifError(err);
            done()
        })
    })
    describe('validation',function(){
        var storeCoordinator,timestamp = Math.round(Date.now() / 1000);
        var date = new Date(timestamp*1000);
        var transformableObject = {aa:'bb',date:(new Date())}
        function deleteAll(storeCoordinator,done){
            var context = new ManagedObjectContext(storeCoordinator)
            context.getObjects('Hello',function(err,objects){
                if(err)return done(err);
                objects.forEach(function(obj){
                    context.deleteObject(obj);
                })
                context.save(done);
            })
        }
        before(function(done){
            storeCoordinator = new PersistentStoreCoordinator(objectModel);
            storeCoordinator.addStore(store_url)
            storeCoordinator.persistentStores[0].syncSchema({force:true},function(err){
                if(err)return done(err);
                deleteAll(storeCoordinator,done);
            })
        })
//        after(function(done){
//            deleteAll(storeCoordinator,done);
//        })

        it('should create object with default values',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')
            assert.equal(obj.name,'defVal')
        })

        it('should create object and assign all valid values',function(done){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')
            assert.doesNotThrow(function(){
                obj.bool = true;
                obj.name = 'test';
                obj.int = 1600;
                obj.decim = 0.55;
                obj.float = 10.505;
                obj.double = 100.5054;
                obj.email = 'jackie@gmail.com';
                obj.url = 'http://www.google.com';
                obj.date = date;
                obj.timestamp = timestamp;
                obj.transformable = transformableObject;
            })
            context.save(done);
        })
        it('should load all attributes',function(done){
            var context = new ManagedObjectContext(storeCoordinator)
            context.getObjects('Hello',function(err,objects){
                if(err)return done(err);
                var obj = objects[0];
                assert.strictEqual(obj.bool,true,'bool value');
                assert.strictEqual(obj.name,'test');
                assert.strictEqual(obj.int,1600);
                assert.strictEqual(obj.decim,0.55);
                assert.strictEqual(obj.float,10.505);
                assert.strictEqual(obj.double,100.5054);
                assert.strictEqual(obj.email,'jackie@gmail.com');
                assert.strictEqual(obj.url,'http://www.google.com');
                assert.equal(obj.date.toISOString(),date.toISOString())
                assert.equal(obj.timestamp.toISOString(),(new Date(timestamp)).toISOString())
                assert.equal(JSON.stringify(obj.transformable),JSON.stringify(transformableObject))
                assert.equal(obj.getWorldID(),null)
                done();
            })
        })
        it('should create object and assign all valid values from object',function(done){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')
            assert.doesNotThrow(function(){
                obj.setValues({
                    bool:true,
                    name:'test',
                    int:1600,
                    decim: 0.55,
                    float: 10.505,
                    double: 100.5054,
                    email:'jackie@gmail.com',
                    url:'http://www.google.com',
                    timestamp: timestamp,
                    transformable: transformableObject
                })
            })
            context.save(done);
        })
        it('should load all attributes from persistent store',function(done){
            var context = new ManagedObjectContext(storeCoordinator)
            context.getObjects('Hello',function(err,objects){
                if(err)return done(err);
                var obj = objects[0];
                assert.strictEqual(obj.bool,true);
                assert.strictEqual(obj.name,'test');
                assert.strictEqual(obj.int,1600);
                assert.strictEqual(obj.decim,0.55);
                assert.strictEqual(obj.float,10.505);
                assert.strictEqual(obj.double,100.5054);
                assert.strictEqual(obj.email,'jackie@gmail.com');
                assert.strictEqual(obj.url,'http://www.google.com');
                assert.equal(obj.date.toISOString(),date.toISOString())
                assert.equal(obj.timestamp.toISOString(),(new Date(timestamp)).toISOString())
                assert.equal(JSON.stringify(obj.transformable),JSON.stringify(transformableObject))
                done();
            })
        })
        it('shouldn\'t assign (in)valid date value',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')
            assert.throws(function(){
                obj.date = 'this is not valid date';
            },'invalid string to date')
            assert.throws(function(){
                obj.date = 25; //this also
            },'integer to date')
            assert.doesNotThrow(function(){
                obj.date = null;
            })
            assert.doesNotThrow(function(){
                obj.date = new Date();
            })
            assert.doesNotThrow(function(){
                obj.date = (new Date()).toISOString();
            })
        })
        it('should transform date value from various formats',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            var date = new Date(Math.floor(Date.now()/1000)*1000);

            var formats = {};

            formats.isoFormat = date.toISOString()
            formats.nativeStringFormat = date.toString()
            formats.ddmmyyFormat = moment(date).format('YYYY-MM-DD HH:mm:ss');
            formats.ddmmyyFormatDashes = moment(date).format('YYYY/MM/DD HH:mm:ss');
            for(var i in formats){
                var _d = formats[i];
                assert.doesNotThrow(function(){
                    obj.date = _d;
                },i)
                assert.equal(obj.date.toISOString(),date.toISOString(),'format');
            }
        })
        it('shouldn\'t pass invalid string',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            assert.throws(function(){
                obj.shortString = '01234567890123456789' + '0';//max length is 20
            },'too long')
            assert.throws(function(){
                obj.shortString = 'a';//max length is 20
            },'too short')
            assert.throws(function(){
                obj.shortString = 'aAb';//max length is 20
            },'does not pass RegExp aAb')
            assert.throws(function(){
                obj.shortString = 'aBb';//max length is 20
            },'does not pass RegExp aBb')
            assert.doesNotThrow(function(){
                obj.shortString = 'aa';
            })
            assert.doesNotThrow(function(){
                obj.shortString = 'aaaa';
            })
        })
        it('should pass valid url',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            assert.throws(function(){
                obj.url = 'aa';
            })
            assert.throws(function(){
                obj.url = 'http://';
            })
            assert.throws(function(){
                obj.url = 'www.google.com';
            })
            assert.throws(function(){
                obj.url = 'sfgsg://www.google.com/aadfsdg';
            })
            assert.throws(function(){
                obj.setValues({url:'sfgsg://www.google.com/aadfsdg'});
            })
            assert.doesNotThrow(function(){
                obj.url = 'http://www.google.com';
            })
            assert.doesNotThrow(function(){
                obj.url = 'http://www.google.com/myfile';
            })
            assert.doesNotThrow(function(){
                obj.url = 'ftp://www.google.com/test/com.abcd';
            })
            assert.doesNotThrow(function(){
                obj.url = 'ftp://www.google.com/test/com.abcd?testmy&arg2=a';
            })
            assert.doesNotThrow(function(){
                obj.setValues({url:'ftp://www.google.com/test/com.abcd?testmy&arg2=a'});
            })
            assert.doesNotThrow(function(){
                obj.url = 'http://john:doe@www.google.com';
            })
        })
        it('should pass valid email',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            assert.throws(function(){
                obj.email = 'aa';
            })
            assert.throws(function(){
                obj.email = 'invalid email';
            })
            assert.throws(function(){
                obj.email = 'j@d.com';
            })
            assert.throws(function(){
                obj.email = 'john@doe.';
            })
            assert.throws(function(){
                obj.setValues({email:'john@doe.'});
            })
            assert.doesNotThrow(function(){
                obj.email = 'john@doe.com';
            })
            assert.doesNotThrow(function(){
                obj.email = 'jo.hn.do.e@doe.com';
            })
            assert.doesNotThrow(function(){
                obj.email = 'john.doe@gmail.com';
            })
        })
        it('should pass valid number',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            // double
            assert.throws(function(){
                obj.double = 'aa';
            })
            assert.doesNotThrow(function(){
                obj.double = 25.6134;
            })
            assert.doesNotThrow(function(){
                obj.double = '1.5';
            })
            assert.strictEqual(obj.double,1.5);
            // float
            assert.throws(function(){
                obj.float = 'aa';
            })
            assert.doesNotThrow(function(){
                obj.float = 25.6134;
            })
            assert.doesNotThrow(function(){
                obj.float = '1.5';
            })
            assert.strictEqual(obj.float,1.5);
            // int
            assert.throws(function(){
                obj.int = 'aa';
            })
            assert.throws(function(){
                obj.int = '25.689';
            })
            assert.throws(function(){
                obj.setValues({int:'25.689'});
            })
            assert.doesNotThrow(function(){
                obj.int = 25;
            })
            assert.doesNotThrow(function(){
                obj.int = '155';
            })
            assert.strictEqual(obj.int,155);
        })
        it('should pass valid boolean',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            // double
            assert.throws(function(){
                obj.bool = 'aa';
            })
            assert.throws(function(){
                obj.bool = 'my false';
            })
            assert.throws(function(){
                obj.setValues({bool:'my false'});
            })
            assert.doesNotThrow(function(){
                obj.bool = true;
            })
            assert.doesNotThrow(function(){
                obj.bool = false;
            })
            assert.doesNotThrow(function(){
                obj.bool = 'false';
            })
            assert.strictEqual(obj.bool,false);
            assert.doesNotThrow(function(){
                obj.bool = 'true';
            })
            assert.strictEqual(obj.bool,true);
            assert.doesNotThrow(function(){
                obj.bool = 'on';
            })
            assert.strictEqual(obj.bool,true);
            assert.doesNotThrow(function(){
                obj.bool = '1';
            })
            assert.strictEqual(obj.bool,true);
        })
    })
})<commit_msg>test name fix<commit_after>var assert = require("assert"),
    ManagedObjectModel = require('./../lib/ManagedObjectModel'),
    ManagedObjectContext = require('./../lib/ManagedObjectContext'),
    PersistentStoreCoordinator = require('./../lib/PersistentStoreCoordinator'),
    moment = require('moment');

//var store_url = 'mysql://root@localhost/test';
var store_url = 'sqlite://:memory:';

describe('attributes',function(){
    var objectModel = new ManagedObjectModel(__dirname + '/schemes/attribute-test-model.yaml');
    var invalidObjectModel = new ManagedObjectModel(__dirname + '/schemes/attribute-invalid-test-model.yaml');
    it('should throw error for invalid model',function(done){
        storeCoordinator = new PersistentStoreCoordinator(invalidObjectModel,{logging:console.log});

        storeCoordinator.addStore(store_url);
        storeCoordinator.persistentStores[0].syncSchema({force:true},function(err){
            assert.throws(function(){
                if(err)throw err;
            },function(err){
                return err.message == 'unknown attribute type blah';
            })
            done()
        })
    })
    it('shouldn\'t throw error for valid model',function(done){
        storeCoordinator = new PersistentStoreCoordinator(objectModel,{logging:console.log});

        storeCoordinator.addStore(store_url);
        storeCoordinator.persistentStores[0].syncSchema({force:true},function(err){
            assert.ifError(err);
            done()
        })
    })
    describe('validation',function(){
        var storeCoordinator,timestamp = Math.round(Date.now() / 1000);
        var date = new Date(timestamp*1000);
        var transformableObject = {aa:'bb',date:(new Date())}
        function deleteAll(storeCoordinator,done){
            var context = new ManagedObjectContext(storeCoordinator)
            context.getObjects('Hello',function(err,objects){
                if(err)return done(err);
                objects.forEach(function(obj){
                    context.deleteObject(obj);
                })
                context.save(done);
            })
        }
        before(function(done){
            storeCoordinator = new PersistentStoreCoordinator(objectModel);
            storeCoordinator.addStore(store_url)
            storeCoordinator.persistentStores[0].syncSchema({force:true},function(err){
                if(err)return done(err);
                deleteAll(storeCoordinator,done);
            })
        })
//        after(function(done){
//            deleteAll(storeCoordinator,done);
//        })

        it('should create object with default values',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')
            assert.equal(obj.name,'defVal')
        })

        it('should create object and assign all valid values',function(done){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')
            assert.doesNotThrow(function(){
                obj.bool = true;
                obj.name = 'test';
                obj.int = 1600;
                obj.decim = 0.55;
                obj.float = 10.505;
                obj.double = 100.5054;
                obj.email = 'jackie@gmail.com';
                obj.url = 'http://www.google.com';
                obj.date = date;
                obj.timestamp = timestamp;
                obj.transformable = transformableObject;
            })
            context.save(done);
        })
        it('should load all attributes',function(done){
            var context = new ManagedObjectContext(storeCoordinator)
            context.getObjects('Hello',function(err,objects){
                if(err)return done(err);
                var obj = objects[0];
                assert.strictEqual(obj.bool,true,'bool value');
                assert.strictEqual(obj.name,'test');
                assert.strictEqual(obj.int,1600);
                assert.strictEqual(obj.decim,0.55);
                assert.strictEqual(obj.float,10.505);
                assert.strictEqual(obj.double,100.5054);
                assert.strictEqual(obj.email,'jackie@gmail.com');
                assert.strictEqual(obj.url,'http://www.google.com');
                assert.equal(obj.date.toISOString(),date.toISOString())
                assert.equal(obj.timestamp.toISOString(),(new Date(timestamp)).toISOString())
                assert.equal(JSON.stringify(obj.transformable),JSON.stringify(transformableObject))
                assert.equal(obj.getWorldID(),null)
                done();
            })
        })
        it('should create object and assign all valid values from object',function(done){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')
            assert.doesNotThrow(function(){
                obj.setValues({
                    bool:true,
                    name:'test',
                    int:1600,
                    decim: 0.55,
                    float: 10.505,
                    double: 100.5054,
                    email:'jackie@gmail.com',
                    url:'http://www.google.com',
                    timestamp: timestamp,
                    transformable: transformableObject
                })
            })
            context.save(done);
        })
        it('should load all attributes from persistent store',function(done){
            var context = new ManagedObjectContext(storeCoordinator)
            context.getObjects('Hello',function(err,objects){
                if(err)return done(err);
                var obj = objects[0];
                assert.strictEqual(obj.bool,true);
                assert.strictEqual(obj.name,'test');
                assert.strictEqual(obj.int,1600);
                assert.strictEqual(obj.decim,0.55);
                assert.strictEqual(obj.float,10.505);
                assert.strictEqual(obj.double,100.5054);
                assert.strictEqual(obj.email,'jackie@gmail.com');
                assert.strictEqual(obj.url,'http://www.google.com');
                assert.equal(obj.date.toISOString(),date.toISOString())
                assert.equal(obj.timestamp.toISOString(),(new Date(timestamp)).toISOString())
                assert.equal(JSON.stringify(obj.transformable),JSON.stringify(transformableObject))
                done();
            })
        })
        it('shouldn\'t assign (in)valid date value',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')
            assert.throws(function(){
                obj.date = 'this is not valid date';
            },'invalid string to date')
            assert.throws(function(){
                obj.date = 25; //this also
            },'integer to date')
            assert.doesNotThrow(function(){
                obj.date = null;
            })
            assert.doesNotThrow(function(){
                obj.date = new Date();
            })
            assert.doesNotThrow(function(){
                obj.date = (new Date()).toISOString();
            })
        })
        it('should transform date value from various formats',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            var date = new Date(Math.floor(Date.now()/1000)*1000);

            var formats = {};

            formats.isoFormat = date.toISOString()
            formats.nativeStringFormat = date.toString()
            formats.ddmmyyFormat = moment(date).format('YYYY-MM-DD HH:mm:ss');
            formats.ddmmyyFormatDashes = moment(date).format('YYYY/MM/DD HH:mm:ss');
            for(var i in formats){
                var _d = formats[i];
                assert.doesNotThrow(function(){
                    obj.date = _d;
                },i)
                assert.equal(obj.date.toISOString(),date.toISOString(),'format');
            }
        })
        it('shouldn\'t pass invalid string',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            assert.throws(function(){
                obj.shortString = '01234567890123456789' + '0';//max length is 20
            },'too long')
            assert.throws(function(){
                obj.shortString = 'a';//max length is 20
            },'too short')
            assert.throws(function(){
                obj.shortString = 'aAb';//max length is 20
            },'does not pass RegExp aAb')
            assert.throws(function(){
                obj.shortString = 'aBb';//max length is 20
            },'does not pass RegExp aBb')
            assert.doesNotThrow(function(){
                obj.shortString = 'aa';
            })
            assert.doesNotThrow(function(){
                obj.shortString = 'aaaa';
            })
        })
        it('should pass valid url',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            assert.throws(function(){
                obj.url = 'aa';
            })
            assert.throws(function(){
                obj.url = 'http://';
            })
            assert.throws(function(){
                obj.url = 'www.google.com';
            })
            assert.throws(function(){
                obj.url = 'sfgsg://www.google.com/aadfsdg';
            })
            assert.throws(function(){
                obj.setValues({url:'sfgsg://www.google.com/aadfsdg'});
            })
            assert.doesNotThrow(function(){
                obj.url = 'http://www.google.com';
            })
            assert.doesNotThrow(function(){
                obj.url = 'http://www.google.com/myfile';
            })
            assert.doesNotThrow(function(){
                obj.url = 'ftp://www.google.com/test/com.abcd';
            })
            assert.doesNotThrow(function(){
                obj.url = 'ftp://www.google.com/test/com.abcd?testmy&arg2=a';
            })
            assert.doesNotThrow(function(){
                obj.setValues({url:'ftp://www.google.com/test/com.abcd?testmy&arg2=a'});
            })
            assert.doesNotThrow(function(){
                obj.url = 'http://john:doe@www.google.com';
            })
        })
        it('should pass valid email',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            assert.throws(function(){
                obj.email = 'aa';
            })
            assert.throws(function(){
                obj.email = 'invalid email';
            })
            assert.throws(function(){
                obj.email = 'j@d.com';
            })
            assert.throws(function(){
                obj.email = 'john@doe.';
            })
            assert.throws(function(){
                obj.setValues({email:'john@doe.'});
            })
            assert.doesNotThrow(function(){
                obj.email = 'john@doe.com';
            })
            assert.doesNotThrow(function(){
                obj.email = 'jo.hn.do.e@doe.com';
            })
            assert.doesNotThrow(function(){
                obj.email = 'john.doe@gmail.com';
            })
        })
        it('should pass valid number',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            // double
            assert.throws(function(){
                obj.double = 'aa';
            })
            assert.doesNotThrow(function(){
                obj.double = 25.6134;
            })
            assert.doesNotThrow(function(){
                obj.double = '1.5';
            })
            assert.strictEqual(obj.double,1.5);
            // float
            assert.throws(function(){
                obj.float = 'aa';
            })
            assert.doesNotThrow(function(){
                obj.float = 25.6134;
            })
            assert.doesNotThrow(function(){
                obj.float = '1.5';
            })
            assert.strictEqual(obj.float,1.5);
            // int
            assert.throws(function(){
                obj.int = 'aa';
            })
            assert.throws(function(){
                obj.int = '25.689';
            })
            assert.throws(function(){
                obj.setValues({int:'25.689'});
            })
            assert.doesNotThrow(function(){
                obj.int = 25;
            })
            assert.doesNotThrow(function(){
                obj.int = '155';
            })
            assert.strictEqual(obj.int,155);
        })
        it('should pass valid boolean',function(){
            var context = new ManagedObjectContext(storeCoordinator)
            var obj = context.createObjectWithName('Hello')

            // double
            assert.throws(function(){
                obj.bool = 'aa';
            })
            assert.throws(function(){
                obj.bool = 'my false';
            })
            assert.throws(function(){
                obj.setValues({bool:'my false'});
            })
            assert.doesNotThrow(function(){
                obj.bool = true;
            })
            assert.doesNotThrow(function(){
                obj.bool = false;
            })
            assert.doesNotThrow(function(){
                obj.bool = 'false';
            })
            assert.strictEqual(obj.bool,false);
            assert.doesNotThrow(function(){
                obj.bool = 'true';
            })
            assert.strictEqual(obj.bool,true);
            assert.doesNotThrow(function(){
                obj.bool = 'on';
            })
            assert.strictEqual(obj.bool,true);
            assert.doesNotThrow(function(){
                obj.bool = '1';
            })
            assert.strictEqual(obj.bool,true);
        })
    })
})<|endoftext|>


<commit_before>"use strict";

describe("attributes.es6", function () {

    var basePath;

    before(function () {
        if (gpf.host() === gpf.hosts.browser) {
            if (config.httpPort === 0) {
                // published version
                basePath = "/gpf/test-resources/require";
            } else {
                // local version
                basePath = "/test/require";
            }
        } else {
            // Execution path is always the root folder of the project
            basePath = "test/require";
        }
        gpf.require.configure({
            base: basePath
        });
    });

    if (gpf.internals) {

        describe("(internal) _gpfRequireEs6DecoratorExtract", function () {
            var _gpfRequireEs6DecoratorExtract = gpf.internals._gpfRequireEs6DecoratorExtract;

            it("detects decorators", function () {
                var decorators = _gpfRequireEs6DecoratorExtract([
                    "class Test {",
                    "  @decorator",
                    "  constructor () {",
                    "  }",
                    "}"
                ].join("\n"));
                assert(decorators.length === 1);
            });
        });

    }

    describe("Defining attributes on an ES6 class through gpf.require.define", function () {

        beforeEach(function () {
            gpf.require.configure({
                clearCache: true
            });
        });

        it("loads js file defining a class with attributes", function (done) {
            gpf.require.define({
                classes: "es6/class_with_attributes.js"
            }, function (require) {

                var
                    Attribute = require.classes.Attribute,
                    Test = require.classes.Test;

                var attributes = gpf.attributes.get(Test);
                assert(Object.keys(attributes).length === 1);
                assert(attributes.id.length === 1);
                assert(attributes.id[0] instanceof Attribute);
                assert(attributes.id[0].value === 1);

                done();

            }).then(undefined, done);
        });

    });

});
<commit_msg>Decorator 'import' is no more needed (#296)<commit_after>"use strict";

describe("attributes.es6", function () {

    var basePath;

    before(function () {
        if (gpf.host() === gpf.hosts.browser) {
            if (config.httpPort === 0) {
                // published version
                basePath = "/gpf/test-resources/require";
            } else {
                // local version
                basePath = "/test/require";
            }
        } else {
            // Execution path is always the root folder of the project
            basePath = "test/require";
        }
        gpf.require.configure({
            base: basePath
        });
    });

    describe("Defining attributes on an ES6 class through gpf.require.define", function () {

        beforeEach(function () {
            gpf.require.configure({
                clearCache: true
            });
        });

        it("loads js file defining a class with attributes", function (done) {
            gpf.require.define({
                classes: "es6/class_with_attributes.js"
            }, function (require) {

                var
                    Attribute = require.classes.Attribute,
                    Test = require.classes.Test,
                    attributes = gpf.attributes.get(Test);

                assert(Object.keys(attributes).length === 1);
                assert(attributes.id.length === 1);
                assert(attributes.id[0] instanceof Attribute);
                assert(attributes.id[0].value === 1);

                done();

            }).then(undefined, done);
        });

    });

});
<|endoftext|>


<commit_before>(function($) {
    "use strict";
    var style = {
            "menuStyle": {
                "position": "absolute",
                "backgroundColor": "#ffffff",
                "opacity": "1",
                "top": "-50px",
                "right": "0px",
                "zIndex": "500",
                "color": "#000000",
                "padding": "3px",
                "border": "1px solid #000000",
                "font-family": "verdana,sans-serif",
                "font-size": "0.8em"
            }
        },
        menu = $("

")
                   .hide()
                   .css(style.menuStyle),
        timeoutId = undefined;

    function hideMenu() {
        menu.animate({ "top": "-50px" }, 100, function() { menu.hide(); });
    }

    function showMenu() {
        if (timeoutId) {
            window.clearTimeout(timeoutId);
            timeoutId = undefined;
        }
        if (!menu.is(":visible")) {
            menu.show();
            menu.animate({ "top": "0px" }, 200);
        }
        timeoutId = window.setTimeout(hideMenu, 500);
    }

    function elementFor(id, label, initialState, changeHandler) {
        var ele = $("<input type='checkbox'/>").attr("id", id).attr("name", id),
            labelEle = $("").attr("for", id).text(label);

        ele.attr("checked", initialState);
        ele.bind("change", function() { changeHandler(ele.prop("checked")); });

        menu.append(ele);
        menu.append(labelEle);
        menu.append($("
"));
    }

    function buildMenuFor(entries) {
        menu.empty();
        $.each(entries, function(index, entry) {
            elementFor("flymenu-" + index, entry.label, entry.initialState, entry.changeHandler);
        });
    }

    $(document).ready(function() {
        menu.appendTo("body");
    });

    $.fn.flyMenu = function(entries) {
        buildMenuFor(entries);
        $(this).bind("mousemove", function(event) {
            if (event.pageY < 200 && event.pageX > ($("body").width() - 200)) {
                showMenu();
                return false;
            }
            return true;
        });
        return this;
    };
})(jQuery);
<commit_msg>do not fly away the menu if the user has their mouse over the top of it<commit_after>(function($) {
    "use strict";
    var style = {
            "menuStyle": {
                "position": "absolute",
                "backgroundColor": "#ffffff",
                "opacity": "1",
                "top": "-50px",
                "right": "0px",
                "zIndex": "500",
                "color": "#000000",
                "padding": "3px",
                "border": "1px solid #000000",
                "font-family": "verdana,sans-serif",
                "font-size": "0.8em"
            }
        },
        menu = $("

")
                   .hide()
                   .css(style.menuStyle),
        mouseover = false,
        timeoutId = undefined;

    function hideMenu() {
        if (!mouseover) {
            menu.animate({ "top": "-50px" }, 100, function() { menu.hide(); });
        }
    }

    function showMenu() {
        if (timeoutId) {
            window.clearTimeout(timeoutId);
            timeoutId = undefined;
        }
        if (!menu.is(":visible")) {
            menu.show();
            menu.animate({ "top": "0px" }, 200);
        }
        timeoutId = window.setTimeout(hideMenu, 500);
    }

    function elementFor(id, label, initialState, changeHandler) {
        var ele = $("<input type='checkbox'/>").attr("id", id).attr("name", id),
            labelEle = $("").attr("for", id).text(label);

        ele.attr("checked", initialState);
        ele.bind("change", function() { changeHandler(ele.prop("checked")); });

        menu.append(ele);
        menu.append(labelEle);
        menu.append($("
"));
    }

    function buildMenuFor(entries) {
        menu.empty();
        $.each(entries, function(index, entry) {
            elementFor("flymenu-" + index, entry.label, entry.initialState, entry.changeHandler);
        });
    }

    $(document).ready(function() {
        menu.appendTo("body");
    });

    $.fn.flyMenu = function(entries) {
        buildMenuFor(entries);
        $(this).bind("mousemove", function(event) {
            if (event.pageY < 200 && event.pageX > ($("body").width() - 200)) {
                showMenu();
                return false;
            }
            return true;
        });
        menu.bind("mouseenter", function(){ mouseover = true; });
        menu.bind("mouseleave", function(){ mouseover = false; });
        return this;
    };
})(jQuery);
<|endoftext|>


<commit_before>
steal('funcunit/qunit', 'jquery/event/resize').then(function() {

	module("jquery/event/resize")

	test("resize hits only children in order", function() {
		var ids = []
		record = function( ev ) {
			ids.push(this.id ? this.id : this)
		},
			divs = $("#qunit-test-area").html("

").find('div').bind('resize', record);

		$(document.body).bind('resize', record);

		$("#qunit-test-area").children().eq(0).trigger("resize");

		same(ids, ['1', '1.1', '1.2'])

		ids = [];
		$("#qunit-test-area").trigger("resize");
		same(ids, [document.body, '1', '1.1', '1.2', '2']);

		ids = [];
		$(window).trigger("resize");
		same(ids, [document.body, '1', '1.1', '1.2', '2']);

		$(document.body).unbind('resize', record);
	});

	test("resize stopping prop", function() {
		var ids = []
		record = function( ev ) {

			ids.push(this.id ? this.id : this)
			if ( this.id == '1' ) {
				ev.stopPropagation();
			}
		},
			divs = $("#qunit-test-area").html("

").find('div').bind('resize', record);

		$(document.body).bind('resize', record);

		$(window).trigger("resize");
		same(ids, [document.body, '1', '2']);

		$(document.body).unbind('resize', record);
	});

	test("resize event cascades from target", function() {

		var ids = [],
			record = function( ev ) {
				ids.push(this.id ? this.id : this);
			},

			divs = $("#qunit-test-area").html("

");

		divs.find("#1\\.1\\.1").bind("resize", record);
		divs.find("#1").bind("resize", record);

		$("#1\\.1").trigger("resize", [false]);
		same(ids, ['1.1.1']);

		$("#qunit-test-area").empty();
	});

})<commit_msg>test that resize event propagates extra data<commit_after>
steal('funcunit/qunit', 'jquery/event/resize').then(function() {

	module("jquery/event/resize")

	test("resize hits only children in order", function() {
		var ids = []
		record = function( ev ) {
			ids.push(this.id ? this.id : this)
		},
			divs = $("#qunit-test-area").html("

").find('div').bind('resize', record);

		$(document.body).bind('resize', record);

		$("#qunit-test-area").children().eq(0).trigger("resize");

		same(ids, ['1', '1.1', '1.2'])

		ids = [];
		$("#qunit-test-area").trigger("resize");
		same(ids, [document.body, '1', '1.1', '1.2', '2']);

		ids = [];
		$(window).trigger("resize");
		same(ids, [document.body, '1', '1.1', '1.2', '2']);

		$(document.body).unbind('resize', record);
	});

	test("resize stopping prop", function() {
		var ids = []
		record = function( ev ) {

			ids.push(this.id ? this.id : this)
			if ( this.id == '1' ) {
				ev.stopPropagation();
			}
		},
			divs = $("#qunit-test-area").html("

").find('div').bind('resize', record);

		$(document.body).bind('resize', record);

		$(window).trigger("resize");
		same(ids, [document.body, '1', '2']);

		$(document.body).unbind('resize', record);
	});

	test("resize event cascades from target", function() {

		var ids = [],
			record = function( ev ) {
				ids.push(this.id ? this.id : this);
			},

			divs = $("#qunit-test-area").html("

");

		divs.find("#1\\.1\\.1").bind("resize", record);
		divs.find("#1").bind("resize", record);

		$("#1\\.1").trigger("resize", [false]);
		same(ids, ['1.1.1']);

		$("#qunit-test-area").empty();
	});

	test('resize event propagates data on trigger', function(){
		var captured;

		$('#qunit-test-area').html('

');

		$('#1').resize(function(ev, data){
			captured = data.foo;
		});

		$('#1').trigger('resize', { foo: 'bar' });

		equal(captured, 'bar');

		$('#qunit-test-area').empty();
	});
})<|endoftext|>


<commit_before>'use strict';
const sails = require('sails');

before(function(done) {

  // Increase the Mocha timeout so that Sails has enough time to lift.
  this.timeout(10000);
  require('babel-register')();
  require('babel-polyfill');
  global.Promise = require('bluebird');

  sails.lift({
    environment: 'test',
    port: 1234,
    connections: {
      default: 'testDB',
      testDB: {
        adapter: 'sails-mongo',
        host: 'localhost',
        port: 27017,
        user: '',
        password: '',
        database: 'porybox-test'
      },
    },
    models: {
      connection: 'testDB',
      migrate: 'drop'
    },
    connection: 'testDB',
    paths: { public: 'client', views: 'client' }
  }, function(err, server) {
    if (err) return done(err);
    // here you can load fixtures, etc.
    done(err, sails);
  });
});

after(function(done) {
  // here you can clear fixtures, etc.
  sails.lower(done);
});
<commit_msg>Remove unnecessary babel from tests<commit_after>'use strict';
const sails = require('sails');

before(function(done) {

  // Increase the Mocha timeout so that Sails has enough time to lift.
  this.timeout(10000);
  require('babel-register')();

  sails.lift({
    environment: 'test',
    port: 1234,
    connections: {
      default: 'testDB',
      testDB: {
        adapter: 'sails-mongo',
        host: 'localhost',
        port: 27017,
        user: '',
        password: '',
        database: 'porybox-test'
      },
    },
    models: {
      connection: 'testDB',
      migrate: 'drop'
    },
    connection: 'testDB',
    paths: { public: 'client', views: 'client' }
  }, function(err, server) {
    if (err) return done(err);
    // here you can load fixtures, etc.
    done(err, sails);
  });
});

after(function(done) {
  // here you can clear fixtures, etc.
  sails.lower(done);
});
<|endoftext|>


<commit_before>;( function () {

  //     UNDERSCORE PARTIAL (_.template)
  //
  //     Underscore.js 1.8.3
  //     http://underscorejs.org
  //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  //     Underscore may be freely distributed under the MIT license.

  var _ = {};

  // Current version.
  _.VERSION = '1.8.3_partial';

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
  };

  // When customizing `templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /(.)^/;

  // Certain characters need to be escaped so that they can be put into a
  // string literal.
  var escapes = {
    "'":      "'",
    '\\':     '\\',
    '\r':     'r',
    '\n':     'n',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  var escaper = /\\|'|\r|\n|\u2028|\u2029/g;

  var escapeChar = function(match) {
    return '\\' + escapes[match];
  };

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  // NB: `oldSettings` only exists for backwards compatibility.
  _.template = function(text, settings, oldSettings) {
    if (!settings && oldSettings) settings = oldSettings;
    //settings = _.defaults({}, settings, _.templateSettings);
    settings = _.templateSettings;

    // Combine delimiters into one regular expression via alternation.
    var matcher = RegExp([
      (settings.escape || noMatch).source,
      (settings.interpolate || noMatch).source,
      (settings.evaluate || noMatch).source
    ].join('|') + '|$', 'g');

    // Compile the template source, escaping string literals appropriately.
    var index = 0;
    var source = "__p+='";
    text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset).replace(escaper, escapeChar);
      index = offset + match.length;

      if (escape) {
        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
      } else if (interpolate) {
        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
      } else if (evaluate) {
        source += "';\n" + evaluate + "\n__p+='";
      }

      // Adobe VMs need the match returned to produce the correct offest.
      return match;
    });
    source += "';\n";

    // If a variable is not specified, place data values in local scope.
    if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

    source = "var __t,__p='',__j=Array.prototype.join," +
      "print=function(){__p+=__j.call(arguments,'');};\n" +
      source + 'return __p;\n';

    try {
      var render = new Function(settings.variable || 'obj', '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    var template = function(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled source as a convenience for precompilation.
    var argument = settings.variable || 'obj';
    template.source = 'function(' + argument + '){\n' + source + '}';

    return template;
  };

  // -------------------------

  var template = _.template( [
    '<section class="CG2-livecode" <% if ( isDeferredPlay ) { %>data-livecode-deferredplay<% } %> data-livecode-from-oldjade>',
      '
<%= title %>
',
      '
<%= text %>
',
      '',
        '
',
          '
',
            '<% if ( isDeferredPlay ) { %>',
              '
',
                'サンプルを停止する',
              '
',
            '<% } %>',
            // '
',
            //   'ソースコード：<%= fileName %>',
            // '
',
            '
<a href="<%= iframeSrc %>" target="_blank">',
              ' 新規タブで開く',
            '
',
          '
',
        '
',
      '',
      '
',
        '<iframe ',
          '<% if ( !isDeferredPlay ) { %> src="<%= iframeSrc %>" <% } %> ',
          'data-livecode-src="<%= iframeSrc %>" ',
          'width="<%= iframeWidth %>" ',
          'height="<%= iframeHeight %>" ',
          'style="<%= iframeStyle %>" ',
          'allowfullscreen="allowfullscreen" ',
        '>',
        '<% if ( isDeferredPlay ) { %>',
          '

',
        '<% } %>',
      '
',
    '
'
  ].join( '' ) );

  var $div = document.createElement( 'div' );

  var attach = function () {}

  window.addEventListener( 'DOMContentLoaded', function () {

    var $elAll = document.querySelectorAll( 'div.Demo' );

    Array.prototype.forEach.call( $elAll, function( $el ) {

      var $iframe        = $el.querySelector( 'iframe' );
      var $title         = $el.querySelector( 'div.Demo-title' );
      var $text          = $el.querySelector( 'div.Demo-comment' );
      var title          = $title ? $title.innerHTML : '';
      var text           = $text  ? $text.innerHTML  : '';
      var iframeSrc      = $iframe.getAttribute( 'src' );
      var iframeWidth    = $iframe.getAttribute( 'width' );
      var iframeHeight   = $iframe.getAttribute( 'height' );
      var iframeStyle    = $iframe.getAttribute( 'style' );
      var isDeferredPlay = $iframe.getAttribute( 'data-trigger' ) === 'data-trigger';

      var data = {
        title          : title,
        text           : text,
        iframeSrc      : iframeSrc,
        iframeWidth    : iframeWidth,
        iframeHeight   : iframeHeight,
        iframeStyle    : iframeStyle,
        isDeferredPlay : isDeferredPlay
      }

      var html = template( data );
      $div.innerHTML = html;
      var $livecore = $div.querySelector( '.CG2-livecode' );
      $el.parentNode.replaceChild( $livecore, $el );
      CG2.vent.dispatchEvent( { type: 'livecode-converted', element: $livecore } );

    } );

  } );

} )();
<commit_msg>旧本文iframeのクラス名を継承するように codegrid-app/issues/480<commit_after>;( function () {

  //     UNDERSCORE PARTIAL (_.template)
  //
  //     Underscore.js 1.8.3
  //     http://underscorejs.org
  //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  //     Underscore may be freely distributed under the MIT license.

  var _ = {};

  // Current version.
  _.VERSION = '1.8.3_partial';

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
  };

  // When customizing `templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /(.)^/;

  // Certain characters need to be escaped so that they can be put into a
  // string literal.
  var escapes = {
    "'":      "'",
    '\\':     '\\',
    '\r':     'r',
    '\n':     'n',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  var escaper = /\\|'|\r|\n|\u2028|\u2029/g;

  var escapeChar = function(match) {
    return '\\' + escapes[match];
  };

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  // NB: `oldSettings` only exists for backwards compatibility.
  _.template = function(text, settings, oldSettings) {
    if (!settings && oldSettings) settings = oldSettings;
    //settings = _.defaults({}, settings, _.templateSettings);
    settings = _.templateSettings;

    // Combine delimiters into one regular expression via alternation.
    var matcher = RegExp([
      (settings.escape || noMatch).source,
      (settings.interpolate || noMatch).source,
      (settings.evaluate || noMatch).source
    ].join('|') + '|$', 'g');

    // Compile the template source, escaping string literals appropriately.
    var index = 0;
    var source = "__p+='";
    text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset).replace(escaper, escapeChar);
      index = offset + match.length;

      if (escape) {
        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
      } else if (interpolate) {
        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
      } else if (evaluate) {
        source += "';\n" + evaluate + "\n__p+='";
      }

      // Adobe VMs need the match returned to produce the correct offest.
      return match;
    });
    source += "';\n";

    // If a variable is not specified, place data values in local scope.
    if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

    source = "var __t,__p='',__j=Array.prototype.join," +
      "print=function(){__p+=__j.call(arguments,'');};\n" +
      source + 'return __p;\n';

    try {
      var render = new Function(settings.variable || 'obj', '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    var template = function(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled source as a convenience for precompilation.
    var argument = settings.variable || 'obj';
    template.source = 'function(' + argument + '){\n' + source + '}';

    return template;
  };

  // -------------------------

  var template = _.template( [
    '<section class="CG2-livecode" <% if ( isDeferredPlay ) { %>data-livecode-deferredplay<% } %> data-livecode-from-oldjade>',
      '
<%= title %>
',
      '
<%= text %>
',
      '',
        '
',
          '
',
            '<% if ( isDeferredPlay ) { %>',
              '
',
                'サンプルを停止する',
              '
',
            '<% } %>',
            // '
',
            //   'ソースコード：<%= fileName %>',
            // '
',
            '
<a href="<%= iframeSrc %>" target="_blank">',
              ' 新規タブで開く',
            '
',
          '
',
        '
',
      '',
      '
',
        '<iframe ',
          '<% if ( !isDeferredPlay ) { %> src="<%= iframeSrc %>" <% } %> ',
          'data-livecode-src="<%= iframeSrc %>" ',
          'class="<%= iframeClass %>"',
          'width="<%= iframeWidth %>" ',
          'height="<%= iframeHeight %>" ',
          'style="<%= iframeStyle %>" ',
          'allowfullscreen="allowfullscreen" ',
        '>',
        '<% if ( isDeferredPlay ) { %>',
          '

',
        '<% } %>',
      '
',
    '
'
  ].join( '' ) );

  var $div = document.createElement( 'div' );

  var attach = function () {}

  window.addEventListener( 'DOMContentLoaded', function () {

    var $elAll = document.querySelectorAll( 'div.Demo' );

    Array.prototype.forEach.call( $elAll, function( $el ) {

      var className = $iframe.getAttribute( 'class' );
      var modifierS = 'CG2-livecode__frame--small';
      var modifierL = 'CG2-livecode__frame--large';

      var $iframe        = $el.querySelector( 'iframe' );
      var $title         = $el.querySelector( 'div.Demo-title' );
      var $text          = $el.querySelector( 'div.Demo-comment' );
      var title          = $title ? $title.innerHTML : '';
      var text           = $text  ? $text.innerHTML  : '';
      var iframeClass    = /sizeS/.test( className ) ? modifierS : /sizeL/.test( className ) ? modifierL : '';
      var iframeSrc      = $iframe.getAttribute( 'src' );
      var iframeWidth    = $iframe.getAttribute( 'width' );
      var iframeHeight   = $iframe.getAttribute( 'height' );
      var iframeStyle    = $iframe.getAttribute( 'style' );
      var isDeferredPlay = $iframe.getAttribute( 'data-trigger' ) === 'data-trigger';

      var data = {
        title          : title,
        text           : text,
        iframeClass    : iframeClass,
        iframeSrc      : iframeSrc,
        iframeWidth    : iframeWidth,
        iframeHeight   : iframeHeight,
        iframeStyle    : iframeStyle,
        isDeferredPlay : isDeferredPlay
      }

      var html = template( data );
      $div.innerHTML = html;
      var $livecore = $div.querySelector( '.CG2-livecode' );
      $el.parentNode.replaceChild( $livecore, $el );
      CG2.vent.dispatchEvent( { type: 'livecode-converted', element: $livecore } );

    } );

  } );

} )();
<|endoftext|>


<commit_before>var request = require('request');
var forismatic = require('forismatic-node')();
var fs = require('fs');
var hexu = require('hexu');

var quotes = JSON.parse(fs.readFileSync(__dirname + "/data.json")) || [];
module.exports.quotes = quotes;

// console.log(hexu.blue("*** Ice is mining data ***"));
function pushData(cb) {
  quotes = quotes.filter(function(item, pos) {
    return quotes.indexOf(item) == pos;
  });
  fs.writeFile(__dirname + '/data.json', JSON.stringify(quotes), function (err) {
    cb();
  });
}

module.exports.addData = function(data) {
  quotes.push(data);
  fs.writeFile(__dirname + '/data.json', JSON.stringify(quotes), function (err) {});
}

function mineData() {
  request('http://quote.machinu.net/api', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        var obj = JSON.parse(body);
        if(obj.text.split(" ").length <= 10 && obj.text.split(" ").length >= 3) {
          console.log(hexu.green("\t Success \u2713 => ") + "Mined Data: " + obj.text);
          quotes.push(obj.text);
        }
      }
  });

  forismatic.getQuote(function (err, quote) {
    if(err) {
      throw err;
    }
    if(quote.quoteText.split(" ").length <= 10) {
      console.log(hexu.green("\t Success \u2713 => ") + "Mined Data: " + quote.quoteText);
      quotes.push(quote.quoteText);
    }
  });
}

setInterval(mineData, 2000);

process.on('SIGINT', function() {
    pushData(function() {
      process.exit();
    });
});
<commit_msg>don't mine<commit_after>var request = require('request');
var forismatic = require('forismatic-node')();
var fs = require('fs');
var hexu = require('hexu');

var quotes = JSON.parse(fs.readFileSync(__dirname + "/data.json")) || [];
module.exports.quotes = quotes;

// console.log(hexu.blue("*** Ice is mining data ***"));
function pushData(cb) {
  quotes = quotes.filter(function(item, pos) {
    return quotes.indexOf(item) == pos;
  });
  fs.writeFile(__dirname + '/data.json', JSON.stringify(quotes), function (err) {
    cb();
  });
}

module.exports.addData = function(data) {
  quotes.push(data);
  fs.writeFile(__dirname + '/data.json', JSON.stringify(quotes), function (err) {});
}

function mineData() {
  request('http://quote.machinu.net/api', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        var obj = JSON.parse(body);
        if(obj.text.split(" ").length <= 10 && obj.text.split(" ").length >= 3) {
          console.log(hexu.green("\t Success \u2713 => ") + "Mined Data: " + obj.text);
          quotes.push(obj.text);
        }
      }
  });

  forismatic.getQuote(function (err, quote) {
    if(err) {
      throw err;
    }
    if(quote.quoteText.split(" ").length <= 10) {
      console.log(hexu.green("\t Success \u2713 => ") + "Mined Data: " + quote.quoteText);
      quotes.push(quote.quoteText);
    }
  });
}

// setInterval(mineData, 2000);

process.on('SIGINT', function() {
    pushData(function() {
      process.exit();
    });
});
<|endoftext|>


<commit_before>define('app/models/machine', ['ember'],
    /**
     * Machine model
     *
     * Also check state mapping in config.py
     * @returns Class
     */
    function() {
        return Ember.Object.extend({
            id: null,

            imageId: null,

            image: null,
            name: null,
            backend: null,
            selected: false,
            hasKey: false,
            hasMonitoring: false,
            state: 'stopped',

            reboot: function(){
                log('Rebooting machine', this.name);

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=reboot',
                    success: function(data) {
                        that.set('state', 'rebooting');
                        info('Succesfully sent reboot to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending reboot to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending reboot to machine',
                                that.name);
                    }
                });
            },

            destroy: function(){
                log('Destroying machine', this.name);

                var that = this
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=destroy',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent destroy to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending destroy to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending destroy to machine',
                                that.name);
                    }
                });
            },

            start: function(){
                log('Starting machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=start',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent start to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending start to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending start to machine',
                                that.name);
                    }
                });
            },

            shutdown: function(){
                log('Stopping machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=stop',
                    success: function(data) {
                        that.set('state', 'stopped');
                        info('Successfully sent stop to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending stop to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending stop to machine',
                                that.name);
                    }
                });
            },

            shell: function(shell_command, callback){
                log('Sending', shell_command, 'to machine', this.name);

                var host;
                if (this.extra.dns_name) {
                    // it is an ec2 machine so it has dns_name
                    host = this.extra.dns_name;
                } else {
                    // if not in ec2, it should have a public ip
                    host = this.public_ips[0];
                }

                // In case of ec2, mist.io could have set this. Server can handle empty string.
                var ssh_user;
                try {
                    ssh_user = this.extra.tags.ssh_user;
                } catch (error) {
                    ssh_user = 'root';
                }

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                    type: 'POST',
                    data: {'host': host,
                           'ssh_user': ssh_user,
                           'command': shell_command},
                    success: function(data) {
                        if (data){
                            callback(data);
                        }
                        info('Successfully sent shell command', shell_command, 'to machine',
                                that.name, 'with result:\n', data);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error sending shell command ' +
                                shell_command + ' to machine ' + that.name);
                        error(textstate, errorThrown, 'when sending shell command',
                                shell_command, 'to machine', that.name);
                    }
                });

            },

            hasAlert : function(){
                //TODO when we have alerts
                return false;
            }.property('hasAlert'),

            startUptimeTimer: function() {
                var that = this;

                setInterval(function() {
                    if (that.get('state' != 'stopped') || !that.get('uptimeFromServer') ||
                        !that.get('uptimeChecked')) {

                        return;

                    } else {
                        that.set('uptime', that.get('uptimeFromServer') + (Date.now()
                                           - that.get('uptimeChecked')));
                    }
                }, 1000);
            },

            checkUptime: function(){
                if (this.state == 'running') {
                    var host;
                    if (this.extra.dns_name) {
                        // it is ec2 machine
                        host = this.extra.dns_name;
                    } else {
                        // if not ec2 it should have a public ip
                        host = this.public_ips[0];
                    }

                    // In case of ec2, mist.io could have set this. Server can handle empty string.
                    var ssh_user;
                    try {
                        ssh_user = this.extra.tags.ssh_user;
                    } catch (error) {
                        ssh_user = 'root';
                    }

                    var that = this;
                    $.ajax({
                        url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                        type: 'POST',
                        data: {'host': host,
                               'ssh_user': ssh_user,
                               'command': 'cat /proc/uptime'},
                        success: function(data) {
                            // also means in has a key
                            that.set('hasKey', true);
                            var resp = data.split(' ');
                            if (resp.length == 2) {
                                var uptime = parseFloat(resp[0]) * 1000;
                                that.set('uptimeChecked', Date.now());
                                that.set('uptimeFromServer', uptime);
                            }
                            info('Successfully got uptime', data, 'from machine', that.name);
                        },
                        error: function(jqXHR, textstate, errorThrown) {
                            that.set('hasKey', false);
                            Mist.notificationController.notify('Error getting uptime from machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'when getting uptime from machine',
                                    that.name);
                        }
                    });
                }
            },

            checkHasMonitoring: function(){
                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    success: function(data) {
                        log("machine has monitoring");
                        log(data);
                        if('monitoring' in data){
                            that.set('hasMonitoring', data.monitoring);
                        }
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                            Mist.notificationController.notify('Error checking monitoring of machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'while checking monitoring of machine',
                                    that.name);
                    }
                });
            },

            resetUptime: function() {
                if (this.state == 'stopped') {
                    this.set('uptime', 0);
                    this.uptimeTimer = false;
                } else {
                    if (this.get('uptime') == 0) {
                        this.checkUptime();
                    }
                }
            }.observes('state'),

            monitoringChanged: function(){
                var oldValue = !this.hasMonitoring;
                log("monitoring:  " + oldValue);

                var that = this;

                var host;
                if (this.extra.dns_name) {
                    // it is ec2 machine
                    host = this.extra.dns_name;
                } else {
                    // if not ec2 it should have a public ip
                    host = this.public_ips[0];
                }

                var payload = {
                   'monitoring': this.hasMonitoring,
                   'host': host,
                   'provider': this.backend.provider
                };

                $.ajax({
                    // TODO: this should point to https://mist.io/....
                    url: 'backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    dataType: 'json',
                    success: function(data) {

                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        that.set('hasMonitoring', oldValue);
                    }
                });
            }.observes('hasMonitoring'),

            init: function() {
                this._super();
                var that = this;
                this.backend.images.getImage(this.imageId, function(image) {
                    that.set('image', image);
                });
                this.startUptimeTimer();
                this.checkUptime();
                this.checkHasMonitoring();
            }

        });
    }
);
<commit_msg>Get uptime only for running machines.<commit_after>define('app/models/machine', ['ember'],
    /**
     * Machine model
     *
     * Also check state mapping in config.py
     * @returns Class
     */
    function() {
        return Ember.Object.extend({
            id: null,

            imageId: null,

            image: null,
            name: null,
            backend: null,
            selected: false,
            hasKey: false,
            hasMonitoring: false,
            state: 'stopped',

            reboot: function(){
                log('Rebooting machine', this.name);

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=reboot',
                    success: function(data) {
                        that.set('state', 'rebooting');
                        info('Succesfully sent reboot to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending reboot to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending reboot to machine',
                                that.name);
                    }
                });
            },

            destroy: function(){
                log('Destroying machine', this.name);

                var that = this
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=destroy',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent destroy to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending destroy to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending destroy to machine',
                                that.name);
                    }
                });
            },

            start: function(){
                log('Starting machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=start',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent start to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending start to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending start to machine',
                                that.name);
                    }
                });
            },

            shutdown: function(){
                log('Stopping machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=stop',
                    success: function(data) {
                        that.set('state', 'stopped');
                        info('Successfully sent stop to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending stop to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending stop to machine',
                                that.name);
                    }
                });
            },

            shell: function(shell_command, callback){
                log('Sending', shell_command, 'to machine', this.name);

                var host;
                if (this.extra.dns_name) {
                    // it is an ec2 machine so it has dns_name
                    host = this.extra.dns_name;
                } else {
                    // if not in ec2, it should have a public ip
                    host = this.public_ips[0];
                }

                // In case of ec2, mist.io could have set this. Server can handle empty string.
                var ssh_user;
                try {
                    ssh_user = this.extra.tags.ssh_user;
                } catch (error) {
                    ssh_user = 'root';
                }

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                    type: 'POST',
                    data: {'host': host,
                           'ssh_user': ssh_user,
                           'command': shell_command},
                    success: function(data) {
                        if (data){
                            callback(data);
                        }
                        info('Successfully sent shell command', shell_command, 'to machine',
                                that.name, 'with result:\n', data);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error sending shell command ' +
                                shell_command + ' to machine ' + that.name);
                        error(textstate, errorThrown, 'when sending shell command',
                                shell_command, 'to machine', that.name);
                    }
                });

            },

            hasAlert : function(){
                //TODO when we have alerts
                return false;
            }.property('hasAlert'),

            startUptimeTimer: function() {
                var that = this;

                setInterval(function() {
                    if (that.get('state' == 'running') && that.get('uptimeFromServer') &&
                        that.get('uptimeChecked')) {

                        that.set('uptime', that.get('uptimeFromServer') + (Date.now()
                                           - that.get('uptimeChecked')));
                    } else {
                        return;
                    }
                }, 1000);
            },

            checkUptime: function(){
                if (this.state == 'running') {
                    var host;
                    if (this.extra.dns_name) {
                        // it is ec2 machine
                        host = this.extra.dns_name;
                    } else {
                        // if not ec2 it should have a public ip
                        host = this.public_ips[0];
                    }

                    // In case of ec2, mist.io could have set this. Server can handle empty string.
                    var ssh_user;
                    try {
                        ssh_user = this.extra.tags.ssh_user;
                    } catch (error) {
                        ssh_user = 'root';
                    }

                    var that = this;
                    $.ajax({
                        url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                        type: 'POST',
                        data: {'host': host,
                               'ssh_user': ssh_user,
                               'command': 'cat /proc/uptime'},
                        success: function(data) {
                            // also means in has a key
                            that.set('hasKey', true);
                            var resp = data.split(' ');
                            if (resp.length == 2) {
                                var uptime = parseFloat(resp[0]) * 1000;
                                that.set('uptimeChecked', Date.now());
                                that.set('uptimeFromServer', uptime);
                            }
                            info('Successfully got uptime', data, 'from machine', that.name);
                        },
                        error: function(jqXHR, textstate, errorThrown) {
                            that.set('hasKey', false);
                            Mist.notificationController.notify('Error getting uptime from machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'when getting uptime from machine',
                                    that.name);
                        }
                    });
                }
            },

            checkHasMonitoring: function(){
                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    success: function(data) {
                        log("machine has monitoring");
                        log(data);
                        if('monitoring' in data){
                            that.set('hasMonitoring', data.monitoring);
                        }
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                            Mist.notificationController.notify('Error checking monitoring of machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'while checking monitoring of machine',
                                    that.name);
                    }
                });
            },

            resetUptime: function() {
                if (this.state == 'running') {
                    this.startUptimeTimer();
                    this.checkUptime();
                } else {
                    this.set('uptime', 0);
                    this.uptimeTimer = false;
                }
            }.observes('state'),

            monitoringChanged: function(){
                var oldValue = !this.hasMonitoring;
                log("monitoring:  " + oldValue);

                var that = this;

                var host;
                if (this.extra.dns_name) {
                    // it is ec2 machine
                    host = this.extra.dns_name;
                } else {
                    // if not ec2 it should have a public ip
                    host = this.public_ips[0];
                }

                var payload = {
                   'monitoring': this.hasMonitoring,
                   'host': host,
                   'provider': this.backend.provider
                };

                $.ajax({
                    // TODO: this should point to https://mist.io/....
                    url: 'backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    dataType: 'json',
                    success: function(data) {

                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        that.set('hasMonitoring', oldValue);
                    }
                });
            }.observes('hasMonitoring'),

            init: function() {
                this._super();
                var that = this;
                this.backend.images.getImage(this.imageId, function(image) {
                    that.set('image', image);
                });
                this.startUptimeTimer();
                this.checkUptime();
                this.checkHasMonitoring();
            }

        });
    }
);
<|endoftext|>