<commit_before>var _ = require('underscore');
module.exports = function(options) {
    var schema = newSchema(options);
    options = options || {};
    if (!options.newResource) {
        delete schema.properties.properties.properties.id;
        delete schema.properties.properties.properties.email;
    }
    return schema;
}

function newSchema(options) {
    function msg(key) {
        return options.getMessage(key);
    }
    return {
        properties : {
            'geometry' : {
                label : msg('field.geometry.coordinates'),
                type : 'object',
                required : true,
                properties : {
                    coordinates : {
                        label : msg('field.geometry.coordinates.label'),
                        description : msg('field.geometry.coordinates'),
                        type : 'array',
                        minItems : 2,
                        maxItems : 2,
                        required : true,
                        messages : {
                            required : msg('field.geometry.coordinates.required')
                        },
                    },
                }
            },
            'properties' : {
                label : msg('field.properties'),
                type : 'object',
                required : true,
                messages : {
                    required : msg('field.properties.required'),
                },
                properties : {
                    name : {
                        label : msg('field.name'),
                        description : msg('field.name.description'),
                        type : 'string',
                        required : true,
                        messages : {
                            required : msg('field.name.required'),
                            allowEmpty : msg('field.name.allowEmpty')
                        }
                    },
                    id : {
                        label : msg('field.id'),
                        description : msg('field.id.description'),
                        type : 'string',
                        required : true,
                        messages : {
                            required : msg('field.id.required'),
                            allowEmpty : msg('field.id.allowEmpty'),
                            conform : msg('field.id.conform'),
                        },
                        conform : function(v) {
                            if (!v)
                                return false;
                            if (v.length < 3)
                                return false;
                            var ids = options.getAllIdentifiers() || {};
                            return !_.has(ids, v);
                        }
                    },
                    taxID : {
                        description : msg('field.taxID'),
                        type : 'string',
                        required : false,
                        messages : {
                            conform : msg('field.taxID.msg.conform'),
                        },
                        conform : function(v) {
                            if (!v || !v.length)
                                return true;
                            if (v.length != 14)
                                return false;
                            if (!v.match(/^\d+$/))
                                return false;
                            return true;

                            var result = checkLuhn(v);
                            return result;
                            function checkLuhn(imei) {
                                var digits = [ 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 ];
                                var val = (imei.split('').reduce(function(sum,
                                        d, n) {
                                    return (n === (imei.length - 1) ? 0 : sum) + //
                                    parseInt((n % 2) ? d : digits[d]);
                                }, 0));
                                return (val % 10) == 0;
                            }
                        }
                    },
                    email : {
                        label : msg('field.email'),
                        description : msg('field.email.descripton'),
                        type : 'string',
                        format : 'email',
                        required : true,
                        messages : {
                            required : msg('field.email.required'),
                            allowEmpty : msg('field.email.allowEmpty'),
                            format : msg('field.email.msg.format'),
                        }
                    },
                    description : {
                        label : msg('field.description'),
                        description : msg('field.description.descripton'),
                        type : 'string',
                        maxLength : 250,
                        required : true,
                        messages : {
                            required : msg('field.description.required'),
                            allowEmpty : msg('field.description.allowEmpty'),
                            minLength : msg('field.description.minLength'),
                            maxLength : msg('field.description.maxLength')
                        }
                    },
                    category : {
                        label : msg('field.category'),
                        description : msg('field.category.description'),
                        type : 'string',
                        enum : options.getCategoryKeys(),
                        required : true
                    },
                    tags : {
                        label : msg('field.tags.label'),
                        description : msg('field.tags'),
                        minItems : 1,
                        maxItems : 5,
                        uniqueItems : true,
                        type : 'array',
                        required : true,
                        messages : {
                            minItems : msg('field.tags.minItems'),
                            required : msg('field.tags.required'),
                            allowEmpty : msg('field.tags.allowEmpty'),
                        }
                    },
                    address : {
                        label : msg('field.address'),
                        description : msg('field.address.description'),
                        type : 'string',
                        required : true,
                        messages : {
                            required : msg('field.address.msg.required'),
                            allowEmpty : msg('field.address.msg.allowEmtpy'),
                        }
                    },
                    postcode : {
                        label : msg('field.postcode'),
                        description : msg('field.postcode.description'),
                        type : 'integer',
                        allowEmpty : false,
                        required : true,
                        messages : {
                            required : msg('field.postcode.msg.required'),
                            allowEmpty : msg('field.postcode.msg.allowEmpty'),
                            conform : msg('field.postcode.msg.conform')
                        },
                        conform : function(v) {
                            try {
                                v = parseInt(v);
                                v += '';
                                var dept = v.substring(0, 2);
                                var idfDepts = ['75', '77', '78', '91', '92', '93', '94', '95'];
                                return v.length === 5 && idfDepts.indexOf(dept) >= 0;
                            } catch (e) {
                                return false;
                            }
                        }
                    },
                    city : {
                        label : msg('field.city'),
                        description : msg('field.city.description'),
                        type : 'string',
                        required : true,
                        messages : {
                            required : msg('field.city.msg.required'),
                            allowEmpty : msg('field.city.msg.allowEmpty')
                        }
                    },
                    url : {
                        label : msg('field.url'),
                        description : msg('field.url.description'),
                        type : 'string',
                        required : true,
                        pattern : /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})(:\d+)?\/?([\/\da-z\s\.-]+)*(\?.*)?$/i,
                        messages : {
                            required : msg('field.url.msg.required'),
                            allowEmpty : msg('field.url.msg.allowEmpty'),
                            format : msg('field.url.msg.format'),
                            pattern : msg('field.url.msg.format'),
                        }
                    },
                    creationyear : {
                        label : msg('field.creationyear'),
                        description : msg('field.creationyear.description'),
                        type : 'number',
                        required : true,
                        conform : function(v) {
                            try {
                                v = parseInt(v);
                                return v >= 1900
                                        && v <= new Date().getFullYear();
                            } catch (e) {
                                return false;
                            }
                        },
                        messages : {
                            conform : msg('field.messages'),
                            type : msg('field.messages.description'),
                        }
                    },
                    twitter : {
                        label : msg('field.twitter'),
                        description : msg('field.twitter.description'),
                        type : 'string',
                    },
                    facebook : {
                        label : msg('field.facebook'),
                        description : msg('field.facebook.description'),
                        type : 'string',
                        conform : function(v) {
                            return !!v
                                    && v
                                            .match(/^https?:\/\/([^\.]*)\.?facebook\.com\/.*$/g);
                        },
                        messages : {
                            conform : msg('field.facebook.msg.confirm')
                        }
                    },
                    googleplus : {
                        label : msg('field.googleplus'),
                        description : msg('field.googleplus.description'),
                        type : 'string',
                        required : false,
                        conform : function(v) {
                            return !!v
                                    && v
                                            .match(/^https?:\/\/plus\.google\.\w+\/.*$/g);
                        },
                        messages : {
                            conform : msg('field.googleplus.msg.conform'),
                        }
                    },
                    linkedin : {
                        label : msg('field.linkedin'),
                        description : msg('field.linkedin.description'),
                        type : 'string',
                        required : false,
                        conform : function(v) {
                            return !!v
                                    && v
                                            .match(/^https?:\/\/([^\.]*)\.?linkedin\.\w+\/.*$/g);
                        },
                        messages : {
                            conform : msg('field.linkedin.msg.conform'),
                        }
                    },
                    viadeo : {
                        label : msg('field.viadeo'),
                        description : msg('field.viadeo.description'),
                        type : 'string',
                        required : false,
                        conform : function(v) {
                            return !!v
                                    && v
                                            .match(/^https?:\/\/\w+\.viadeo\.\w+\/.*$/g);
                        },
                        messages : {
                            conform : msg('field.viadeo.msg.conform')
                        }
                    }
                }
            },
        }
    };
}
<commit_msg>- in the entity-form, the min/max items for geo coordinates were commented out as the corresponding error message cannot be understood easily<commit_after>var _ = require('underscore');
module.exports = function(options) {
    var schema = newSchema(options);
    options = options || {};
    if (!options.newResource) {
        delete schema.properties.properties.properties.id;
        delete schema.properties.properties.properties.email;
    }
    return schema;
}

function newSchema(options) {
    function msg(key) {
        return options.getMessage(key);
    }
    return {
        properties : {
            'geometry' : {
                label : msg('field.geometry.coordinates'),
                type : 'object',
                required : true,
                properties : {
                    coordinates : {
                        label : msg('field.geometry.coordinates.label'),
                        description : msg('field.geometry.coordinates'),
                        type : 'array',
                        // minItems : 2,
                        // maxItems : 2,
                        required : true,
                        messages : {
                            // minItems : msg('field.geometry.coordinates.required'),
                            // maxItems : msg('field.geometry.coordinates.required'),
                            required : msg('field.geometry.coordinates.required')
                        },
                    },
                }
            },
            'properties' : {
                label : msg('field.properties'),
                type : 'object',
                required : true,
                messages : {
                    required : msg('field.properties.required'),
                },
                properties : {
                    name : {
                        label : msg('field.name'),
                        description : msg('field.name.description'),
                        type : 'string',
                        required : true,
                        messages : {
                            required : msg('field.name.required'),
                            allowEmpty : msg('field.name.allowEmpty')
                        }
                    },
                    id : {
                        label : msg('field.id'),
                        description : msg('field.id.description'),
                        type : 'string',
                        required : true,
                        messages : {
                            required : msg('field.id.required'),
                            allowEmpty : msg('field.id.allowEmpty'),
                            conform : msg('field.id.conform'),
                        },
                        conform : function(v) {
                            if (!v)
                                return false;
                            if (v.length < 3)
                                return false;
                            var ids = options.getAllIdentifiers() || {};
                            return !_.has(ids, v);
                        }
                    },
                    taxID : {
                        description : msg('field.taxID'),
                        type : 'string',
                        required : false,
                        messages : {
                            conform : msg('field.taxID.msg.conform'),
                        },
                        conform : function(v) {
                            if (!v || !v.length)
                                return true;
                            if (v.length != 14)
                                return false;
                            if (!v.match(/^\d+$/))
                                return false;
                            return true;

                            var result = checkLuhn(v);
                            return result;
                            function checkLuhn(imei) {
                                var digits = [ 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 ];
                                var val = (imei.split('').reduce(function(sum,
                                        d, n) {
                                    return (n === (imei.length - 1) ? 0 : sum) + //
                                    parseInt((n % 2) ? d : digits[d]);
                                }, 0));
                                return (val % 10) == 0;
                            }
                        }
                    },
                    email : {
                        label : msg('field.email'),
                        description : msg('field.email.descripton'),
                        type : 'string',
                        format : 'email',
                        required : true,
                        messages : {
                            required : msg('field.email.required'),
                            allowEmpty : msg('field.email.allowEmpty'),
                            format : msg('field.email.msg.format'),
                        }
                    },
                    description : {
                        label : msg('field.description'),
                        description : msg('field.description.descripton'),
                        type : 'string',
                        maxLength : 250,
                        required : true,
                        messages : {
                            required : msg('field.description.required'),
                            allowEmpty : msg('field.description.allowEmpty'),
                            minLength : msg('field.description.minLength'),
                            maxLength : msg('field.description.maxLength')
                        }
                    },
                    category : {
                        label : msg('field.category'),
                        description : msg('field.category.description'),
                        type : 'string',
                        enum : options.getCategoryKeys(),
                        required : true
                    },
                    tags : {
                        label : msg('field.tags.label'),
                        description : msg('field.tags'),
                        minItems : 1,
                        maxItems : 5,
                        uniqueItems : true,
                        type : 'array',
                        required : true,
                        messages : {
                            minItems : msg('field.tags.minItems'),
                            required : msg('field.tags.required'),
                            allowEmpty : msg('field.tags.allowEmpty'),
                        }
                    },
                    address : {
                        label : msg('field.address'),
                        description : msg('field.address.description'),
                        type : 'string',
                        required : true,
                        messages : {
                            required : msg('field.address.msg.required'),
                            allowEmpty : msg('field.address.msg.allowEmtpy'),
                        }
                    },
                    postcode : {
                        label : msg('field.postcode'),
                        description : msg('field.postcode.description'),
                        type : 'integer',
                        allowEmpty : false,
                        required : true,
                        messages : {
                            required : msg('field.postcode.msg.required'),
                            allowEmpty : msg('field.postcode.msg.allowEmpty'),
                            conform : msg('field.postcode.msg.conform')
                        },
                        conform : function(v) {
                            try {
                                v = parseInt(v);
                                v += '';
                                var dept = v.substring(0, 2);
                                var idfDepts = ['75', '77', '78', '91', '92', '93', '94', '95'];
                                return v.length === 5 && idfDepts.indexOf(dept) >= 0;
                            } catch (e) {
                                return false;
                            }
                        }
                    },
                    city : {
                        label : msg('field.city'),
                        description : msg('field.city.description'),
                        type : 'string',
                        required : true,
                        messages : {
                            required : msg('field.city.msg.required'),
                            allowEmpty : msg('field.city.msg.allowEmpty')
                        }
                    },
                    url : {
                        label : msg('field.url'),
                        description : msg('field.url.description'),
                        type : 'string',
                        required : true,
                        pattern : /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})(:\d+)?\/?([\/\da-z\s\.-]+)*(\?.*)?$/i,
                        messages : {
                            required : msg('field.url.msg.required'),
                            allowEmpty : msg('field.url.msg.allowEmpty'),
                            format : msg('field.url.msg.format'),
                            pattern : msg('field.url.msg.format'),
                        }
                    },
                    creationyear : {
                        label : msg('field.creationyear'),
                        description : msg('field.creationyear.description'),
                        type : 'number',
                        required : true,
                        conform : function(v) {
                            try {
                                v = parseInt(v);
                                return v >= 1900
                                        && v <= new Date().getFullYear();
                            } catch (e) {
                                return false;
                            }
                        },
                        messages : {
                            conform : msg('field.messages'),
                            type : msg('field.messages.description'),
                        }
                    },
                    twitter : {
                        label : msg('field.twitter'),
                        description : msg('field.twitter.description'),
                        type : 'string',
                    },
                    facebook : {
                        label : msg('field.facebook'),
                        description : msg('field.facebook.description'),
                        type : 'string',
                        conform : function(v) {
                            return !!v
                                    && v
                                            .match(/^https?:\/\/([^\.]*)\.?facebook\.com\/.*$/g);
                        },
                        messages : {
                            conform : msg('field.facebook.msg.confirm')
                        }
                    },
                    googleplus : {
                        label : msg('field.googleplus'),
                        description : msg('field.googleplus.description'),
                        type : 'string',
                        required : false,
                        conform : function(v) {
                            return !!v
                                    && v
                                            .match(/^https?:\/\/plus\.google\.\w+\/.*$/g);
                        },
                        messages : {
                            conform : msg('field.googleplus.msg.conform'),
                        }
                    },
                    linkedin : {
                        label : msg('field.linkedin'),
                        description : msg('field.linkedin.description'),
                        type : 'string',
                        required : false,
                        conform : function(v) {
                            return !!v
                                    && v
                                            .match(/^https?:\/\/([^\.]*)\.?linkedin\.\w+\/.*$/g);
                        },
                        messages : {
                            conform : msg('field.linkedin.msg.conform'),
                        }
                    },
                    viadeo : {
                        label : msg('field.viadeo'),
                        description : msg('field.viadeo.description'),
                        type : 'string',
                        required : false,
                        conform : function(v) {
                            return !!v
                                    && v
                                            .match(/^https?:\/\/\w+\.viadeo\.\w+\/.*$/g);
                        },
                        messages : {
                            conform : msg('field.viadeo.msg.conform')
                        }
                    }
                }
            },
        }
    };
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import ToolTip from '../../components/ToolTip'
import Image from '../../components/Image'

class IdentityItem extends Component {
  static propTypes = {
    username: PropTypes.string,
    avatarUrl: PropTypes.string.isRequired,
    pending: PropTypes.bool.isRequired,
    ownerAddress: PropTypes.string.isRequired,
    canAddUsername: PropTypes.bool.isRequired,
    isDefault: PropTypes.bool,
    onClick: PropTypes.func.isRequired,
    router: PropTypes.object.isRequired,
    index: PropTypes.number.isRequired
  }

  constructor(props) {
    super(props)
    this.state = {}
  }

  render() {
    return (

        <ToolTip id="usernamePending">

Name registration in progress...

        </ToolTip>
        <ToolTip id="ownerAddress">

This is your identity address.

        </ToolTip>

            <Image
              src={this.props.avatarUrl}
              fallbackSrc="/images/avatar.png" className="rounded-circle img-cover"
              style={{ display: 'inline-block' }}
            />

                {this.props.canAddUsername ?
                   {
                      event.preventDefault()
                      event.stopPropagation()
                      this.props.router.push(`/profiles/i/add-username/${this.props.index}/search`)
                    }}
                  >
                   Add username

                 :

                    {this.props.username}
                    {this.props.pending ?

                      : null}

                }

                      {this.props.ownerAddress}

                {this.props.isDefault ?

                    Default ID

                :

                }

    )
  }
}

export default IdentityItem
<commit_msg>Add ID- prefix to identity address in all profiles page.<commit_after>import React, { Component, PropTypes } from 'react'
import ToolTip from '../../components/ToolTip'
import Image from '../../components/Image'

class IdentityItem extends Component {
  static propTypes = {
    username: PropTypes.string,
    avatarUrl: PropTypes.string.isRequired,
    pending: PropTypes.bool.isRequired,
    ownerAddress: PropTypes.string.isRequired,
    canAddUsername: PropTypes.bool.isRequired,
    isDefault: PropTypes.bool,
    onClick: PropTypes.func.isRequired,
    router: PropTypes.object.isRequired,
    index: PropTypes.number.isRequired
  }

  constructor(props) {
    super(props)
    this.state = {}
  }

  render() {
    return (

        <ToolTip id="usernamePending">

Name registration in progress...

        </ToolTip>
        <ToolTip id="ownerAddress">

This is your identity address.

        </ToolTip>

            <Image
              src={this.props.avatarUrl}
              fallbackSrc="/images/avatar.png" className="rounded-circle img-cover"
              style={{ display: 'inline-block' }}
            />

                {this.props.canAddUsername ?
                   {
                      event.preventDefault()
                      event.stopPropagation()
                      this.props.router.push(`/profiles/i/add-username/${this.props.index}/search`)
                    }}
                  >
                   Add username

                 :

                    {this.props.username}
                    {this.props.pending ?

                      : null}

                }

                      ID-{this.props.ownerAddress}

                {this.props.isDefault ?

                    Default ID

                :

                }

    )
  }
}

export default IdentityItem
<|endoftext|>


<commit_before>// (function(){
// 	var spotifyApi = new SpotifyWebApi();
// 	console.log(spotifyApi);

// 	// spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', function(err, data) {
// 	//   if (err) console.error(err);
// 	//   else console.log('Artist albums', data);
// 	// });

// 	// get an access token
// 	var myAccesstoken = 'AQDcMVnwInPth0Emqph-m42IOCJANzCtgrfaB47RbM5RSFUo-11iksysWGwA0lgqUe9Fm05zr-UEWtUJuYiuO8kZTmQuWMUsfTm7nadeycD84fxe1X9ysmI1ifQFLt7AC8gCg8DMd9jyJLKz6HNvM8fN06zSd3D31Bq2tv4MsP95gjWRY5HxRvemxMQo2d2tXwiRDNAv4XzSgd9t84pefM04kYnG3AncNxz_v3_CO_pHqMNiD4mZHQ';

// 	// set it in the wrapper
// 	var spotifyApi = new SpotifyWebApi();
// 	spotifyApi.setAccessToken(myAccesstoken);
// 	spotifyApi.getUserPlaylists(126955706)
// 	  .then(function(data) {
// 	    console.log('User playlists', data);
// 	  }, function(err) {
// 	    console.error(err);
// 	  });

// })();

//create the json object that's gonna populate the carousel img title descr playlist id
//work on api so that the api calls the right playlist
$(document).ready(function () {

var genres = [
	{
		image:'https://i.scdn.co/image/c7201f157a9e9c34397a59fe8e966a5bc2e37333',
		title: 'My playlist title',
		description:'My genre description',
		button: 'url',
		playlistid:'4VxLxeHYwneGkyUCZPStxo'
	},
	{
		image:'https://i.scdn.co/image/c7201f157a9e9c34397a59fe8e966a5bc2e37333',
		title: 'My playlist title',
		description:'My genre description',
		button: 'url',
		playlistid:'4VxLxeHYwneGkyUCZPStxo'
	},

	{
		image:'https://i.scdn.co/image/c7201f157a9e9c34397a59fe8e966a5bc2e37333',
		title: 'My playlist title',
		description:'My genre description',
		button: 'url',
		playlistid:'4VxLxeHYwneGkyUCZPStxo'
	}
]

genres.forEach(function(d) {
	console.log('this is image source', d.image);
    // add image tag
    var thumbnailsrc = $("<img>").attr('src', d.image);
    $('.thumbnail').append.thumbnailsrc;

    console.log('thumbnails source from object', thumbnailsrc)

});

});//document ready function

<commit_msg>class 17 hosting your files<commit_after>// (function(){
// 	var spotifyApi = new SpotifyWebApi();
// 	console.log(spotifyApi);

// 	// spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', function(err, data) {
// 	//   if (err) console.error(err);
// 	//   else console.log('Artist albums', data);
// 	// });

// 	// get an access token
// 	var myAccesstoken = 'AQDcMVnwInPth0Emqph-m42IOCJANzCtgrfaB47RbM5RSFUo-11iksysWGwA0lgqUe9Fm05zr-UEWtUJuYiuO8kZTmQuWMUsfTm7nadeycD84fxe1X9ysmI1ifQFLt7AC8gCg8DMd9jyJLKz6HNvM8fN06zSd3D31Bq2tv4MsP95gjWRY5HxRvemxMQo2d2tXwiRDNAv4XzSgd9t84pefM04kYnG3AncNxz_v3_CO_pHqMNiD4mZHQ';

// 	// set it in the wrapper
// 	var spotifyApi = new SpotifyWebApi();
// 	spotifyApi.setAccessToken(myAccesstoken);
// 	spotifyApi.getUserPlaylists(126955706)
// 	  .then(function(data) {
// 	    console.log('User playlists', data);
// 	  }, function(err) {
// 	    console.error(err);
// 	  });

// })();

//create the json object that's gonna populate the carousel img title descr playlist id
//work on api so that the api calls the right playlist
$(document).ready(function () {

var genres = [
	{
		image:'https://i.scdn.co/image/c7201f157a9e9c34397a59fe8e966a5bc2e37333',
		title: 'My playlist title',
		description:'My genre description',
		button: 'url',
		playlistid:'4VxLxeHYwneGkyUCZPStxo'
	},
	{
		image:'https://i.scdn.co/image/c7201f157a9e9c34397a59fe8e966a5bc2e37333',
		title: 'My playlist title',
		description:'My genre description',
		button: 'url',
		playlistid:'4VxLxeHYwneGkyUCZPStxo'
	},

	{
		image:'https://i.scdn.co/image/c7201f157a9e9c34397a59fe8e966a5bc2e37333',
		title: 'My playlist title',
		description:'My genre description',
		button: 'url',
		playlistid:'4VxLxeHYwneGkyUCZPStxo'
	}
]

genres.forEach(function(d) {
	console.log('this is image source', d.image);
    // add image tag
    var thumbnailsrc = $("<img>").attr('src', d.image);
    $('.thumbnail').append(thumbnailsrc);
    console.log('thumbnails source from object', thumbnailsrc)

});

});//document ready function

<|endoftext|>


<commit_before>
var assert = require('assert')
  , ref = require('ref')
  , ffi = require('../')

describe('ffi_cif', function () {

  afterEach(gc)

  it('should return a Buffer representing the `ffi_cif` instance', function () {
    var cif = ffi.CIF(ref.types.void, [ ])
    assert(Buffer.isBuffer(cif))
  })

  it('should throw an Error when given an invalid ABI argument', function () {
    assert.throws(function () {
      ffi.CIF(ref.types.void, [], -1)
    }, /FFI_BAD_ABI/)
  })

})
<commit_msg>test: better error checking on the CIF bad ABI test<commit_after>
var assert = require('assert')
  , ref = require('ref')
  , ffi = require('../')

describe('ffi_cif', function () {

  afterEach(gc)

  it('should return a Buffer representing the `ffi_cif` instance', function () {
    var cif = ffi.CIF(ref.types.void, [ ])
    assert(Buffer.isBuffer(cif))
  })

  it('should throw an Error when given an invalid ABI argument', function () {
    assert.throws(function () {
      ffi.CIF(ref.types.void, [], -1)
    }, function (err) {
      assert(err.message.indexOf('FFI_BAD_ABI') !== -1)
      assert.equal('FFI_BAD_ABI', err.code)
      assert.equal(ffi.Bindings.FFI_BAD_ABI, err.errno)
      return true
    })
  })

})
<|endoftext|>


<commit_before>import test from 'ava'
import execa from 'execa'
import { resolve } from 'path'
import { readFileSync, unlinkSync } from 'fs'
import svgsus from '..'

test('bin/svgsus', t => run(t).catch(io => t.regex(io.stdout, /Usage: /)))
test('bin/svgsus cashapelayer < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus jade < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus pug < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus svg < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus uibezierpath < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus uibezierpath < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus svgsymbol --stripStyle < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus svgsymbol --invalidOption < test/fixtures/coin.original.svg', t => run(t).catch(io => t.falsy(io.stout) && t.regex(io.stderr, /Usage: /)))
test('bin/svgsus missing < test/fixtures/coin.original.svg', t => run(t).catch(io => t.falsy(io.stout) && t.regex(io.stderr, /not a valid format/)))
test('bin/svgsus pug test/fixtures/coin.original.svg', t => run(t).then(cleanup('coin.original.pug')))
test('bin/svgsus pug test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).then(cleanup('coin.original.pug', 'logo-defs.original.pug')))
test('bin/svgsus pug --output test/fixtures -- test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).then(cleanup('test/fixtures/coin.original.pug', 'test/fixtures/logo-defs.original.pug')))
test('bin/svgsus cashapelayer --output ca-multi.swift test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).then(cleanup('ca-multi.swift')))
test('bin/svgsus cashapelayer --output ca-single.swift < test/fixtures/coin.original.svg', t => run(t).then(cleanup('ca-single.swift')))
test('bin/svgsus uibezierpath --output ui-single.swift < test/fixtures/coin.original.svg', t => run(t).then(cleanup('ui-single.swift')))
test('bin/svgsus svg --output svg-single.svg test/fixtures/coin.original.svg', t => run(t).then(cleanup('svg-single.svg')))
test('bin/svgsus svg --output svg-fail-single.svg test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).catch(io => t.regex(io.stderr, /multiple files require --output to be a directory/)))
test('bin/svgsus svg test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).then(cleanup('coin.original.svg', 'logo-defs.original.svg')))

Object.keys(svgsus).forEach(format => {
  const ext = svgsus[format].extension

  // all formats should be able to take stdin and write to an output file
  test(`bin/svgsus ${format} --output ${format}-stdin${ext} < test/fixtures/coin.original.svg`, t =>
    run(t).then(cleanup(`${format}-stdin${ext}`))
  )

  // all formats should be able to take a single file and write to an output file
  test(`bin/svgsus ${format} --output ${format}-single${ext} test/fixtures/coin.original.svg`, t =>
    run(t).then(cleanup(`${format}-single${ext}`))
  )

  if (['cashapelayer', 'css', 'uibezierpath', 'svgsymbol'].indexOf(format) === -1) {
    // formats that handle multi by writing multiple files
    test.serial(`bin/svgsus ${format} test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg`, t =>
      run(t).then(cleanup(`coin.original${ext}`, `logo-defs.original${ext}`))
    )

    test(`bin/svgsus ${format} --output a-file${ext} test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg`, t =>
      run(t).catch(io => t.regex(io.stderr, /multiple files require --output to be a directory/))
    )
  } else {
    // formats that handle multi by writing to single file
    test(`bin/svgsus ${format} --output ${format}-multi${ext} test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg`, t =>
      run(t).then(cleanup(`${format}-multi${ext}`))
    )

    test.serial(`bin/svgsus ${format} test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg`, t =>
      run(t).then(cleanup(format === 'css' || format === 'svgsymbol' ? `coin-original+1${ext}` : `coinOriginal+1${ext}`))
    )
  }
})

function run(t) {
  const args = t.title.split(' ')
  const cmd = resolve(__dirname, '..', args.shift())
  const opts = {}

  if (args.indexOf('<') !== -1) {
    const file = args.pop()
    opts.input = readFileSync(resolve(file), 'utf8')
    args.pop()
  }

  return execa(cmd, args, opts)
}

function cleanup() {
  const paths = [].slice.call(arguments).map(path => resolve(__dirname, '..', path))
  return () => new Promise(resolve => {
    paths.forEach(path => unlinkSync(path))
    resolve()
  })
}
<commit_msg>Linting<commit_after>import test from 'ava'
import execa from 'execa'
import { resolve } from 'path'
import { readFileSync, unlinkSync } from 'fs'
import svgsus from '..'

test('bin/svgsus', t => run(t).catch(io => t.regex(io.stdout, /Usage: /)))
test('bin/svgsus cashapelayer < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus jade < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus pug < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus svg < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus uibezierpath < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus uibezierpath < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus svgsymbol --stripStyle < test/fixtures/coin.original.svg', t => run(t))
test('bin/svgsus svgsymbol --invalidOption < test/fixtures/coin.original.svg', t => run(t).catch(io => t.falsy(io.stout) && t.regex(io.stderr, /Usage: /)))
test('bin/svgsus missing < test/fixtures/coin.original.svg', t => run(t).catch(io => t.falsy(io.stout) && t.regex(io.stderr, /not a valid format/)))
test('bin/svgsus pug test/fixtures/coin.original.svg', t => run(t).then(cleanup('coin.original.pug')))
test('bin/svgsus pug test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).then(cleanup('coin.original.pug', 'logo-defs.original.pug')))
test('bin/svgsus pug --output test/fixtures -- test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).then(cleanup('test/fixtures/coin.original.pug', 'test/fixtures/logo-defs.original.pug')))
test('bin/svgsus cashapelayer --output ca-multi.swift test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).then(cleanup('ca-multi.swift')))
test('bin/svgsus cashapelayer --output ca-single.swift < test/fixtures/coin.original.svg', t => run(t).then(cleanup('ca-single.swift')))
test('bin/svgsus uibezierpath --output ui-single.swift < test/fixtures/coin.original.svg', t => run(t).then(cleanup('ui-single.swift')))
test('bin/svgsus svg --output svg-single.svg test/fixtures/coin.original.svg', t => run(t).then(cleanup('svg-single.svg')))
test('bin/svgsus svg --output svg-fail-single.svg test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).catch(io => t.regex(io.stderr, /multiple files require --output to be a directory/)))
test('bin/svgsus svg test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg', t => run(t).then(cleanup('coin.original.svg', 'logo-defs.original.svg')))

Object.keys(svgsus).forEach(format => {
  const ext = svgsus[format].extension

  // all formats should be able to take stdin and write to an output file
  test(`bin/svgsus ${format} --output ${format}-stdin${ext} < test/fixtures/coin.original.svg`, t =>
    run(t).then(cleanup(`${format}-stdin${ext}`))
  )

  // all formats should be able to take a single file and write to an output file
  test(`bin/svgsus ${format} --output ${format}-single${ext} test/fixtures/coin.original.svg`, t =>
    run(t).then(cleanup(`${format}-single${ext}`))
  )

  if (['cashapelayer', 'css', 'uibezierpath', 'svgsymbol'].indexOf(format) === -1) {
    // formats that handle multi by writing multiple files
    test.serial(`bin/svgsus ${format} test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg`, t =>
      run(t).then(cleanup(`coin.original${ext}`, `logo-defs.original${ext}`))
    )

    test(`bin/svgsus ${format} --output a-file${ext} test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg`, t =>
      run(t).catch(io => t.regex(io.stderr, /multiple files require --output to be a directory/))
    )
  } else {
    // formats that handle multi by writing to single file
    test(`bin/svgsus ${format} --output ${format}-multi${ext} test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg`, t =>
      run(t).then(cleanup(`${format}-multi${ext}`))
    )

    test.serial(`bin/svgsus ${format} test/fixtures/coin.original.svg test/fixtures/logo-defs.original.svg`, t =>
      run(t).then(cleanup(format === 'css' || format === 'svgsymbol' ? `coin-original+1${ext}` : `coinOriginal+1${ext}`))
    )
  }
})

function run (t) {
  const args = t.title.split(' ')
  const cmd = resolve(__dirname, '..', args.shift())
  const opts = {}

  if (args.indexOf('<') !== -1) {
    const file = args.pop()
    opts.input = readFileSync(resolve(file), 'utf8')
    args.pop()
  }

  return execa(cmd, args, opts)
}

function cleanup () {
  const paths = [].slice.call(arguments).map(path => resolve(__dirname, '..', path))
  return () => new Promise(resolve => {
    paths.forEach(path => unlinkSync(path))
    resolve()
  })
}
<|endoftext|>


<commit_before>/* eslint node/no-unsupported-features: 0 */
import fs from 'fs';
import {resolve} from 'path';
import write from 'temp-write';
import readPkg from 'read-pkg';
import execa from 'execa';
import test from 'ava';

global.Promise = Promise;

const cli = resolve('../exbox.js');
const ver = readPkg.sync('..').version;

const site = 'test.app';
const dir = 'test/dir';
const local = '~/local';

// turn on DEBUG messages
test.before(() => {
	process.env.DEBUG = 'exbox';
	process.env.EXBOXTEMP = 'temp-exbox-home';
});

test('dummy test', async t => {
	const filepath = await write('console.log(0)\n', 'x.js');
	t.is(fs.readFileSync(filepath, 'utf8').trim(), 'console.log(0)');
});

test('exbox.version: `--version` ok', async t => {
	const out = await execa.stdout(cli, ['--version']);
	t.is(out, ver, 'works: full `--version`');
});

test('exbox.version: `-V` ok', async t => {
	const out = await execa.stdout(cli, ['-V']);
	t.is(out, ver);
});

test('exbox.version: `-v` throws', async t => {
	t.throws(execa.stdout(cli, ['-v']));
});

test('exbox.help: `-h` ok', async t => {
	const out = await execa.stdout(cli, ['-h']);
	t.regex(out, /Usage: exbox <command>/);
});

test('exbox.help: `--help` ok', async t => {
	const out = await execa.stdout(cli, ['--help']);
	t.regex(out, /Usage: exbox <command>/);
});

test('exbox.help: `-H` throws', async t => {
	t.throws(execa.stdout(cli, ['-H']));
});

test('exbox.help: `init --help` ok', async t => {
	const out = await execa.stdout(cli, ['init', '--help']);
	t.regex(out, /Usage: init/);
});

test('exbox.help: `domain --help` ok', async t => {
	const out = await execa.stdout(cli, ['domain', '--help']);
	t.regex(out, /Examples:/);
});

test('exbox.init: debugger', async t => {
	const out = await execa.stdout(cli, ['init']);
	t.is(out, '[DEBUG] initializing ExBox!');
});

test('exbox.domain: requires `site`', async t => {
	const err = await t.throws(execa.stdout(cli, ['domain']));
	t.regex(err.message, /error: missing required argument/);
});

test('exbox.domain: requires `dir`', async t => {
	const err = await t.throws(execa.stdout(cli, ['domain', site]));
	t.regex(err.message, /error: missing required argument/);
});

test('exbox.domain: debugger', async t => {
	const out = await execa.stdout(cli, ['domain', site, dir]);
	t.is(out, `[DEBUG] domain: use ssl: false. site: ${site}. dir: ${dir}.`);
});

test('exbox.folder: requires `local`', async t => {
	const err = await t.throws(execa.stdout(cli, ['folder']));
	t.regex(err.message, /error: missing required argument/);
});

test('exbox.folder: requires `dir`', async t => {
	const err = await t.throws(execa.stdout(cli, ['folder', local]));
	t.regex(err.message, /error: missing required argument/);
});

test('exbox.folder: debugger', async t => {
	const out = await execa.stdout(cli, ['folder', local, dir]);
	t.is(out, `[DEBUG] folder: local: ${local}. dir: ${dir}.`);
});
<commit_msg>tests cleanup, remove the EXBOXTEMP dir<commit_after>/* eslint node/no-unsupported-features: 0 */
import fs from 'fs';
import {resolve} from 'path';
import write from 'temp-write';
import readPkg from 'read-pkg';
import execa from 'execa';
import test from 'ava';

global.Promise = Promise;

const cli = resolve('../exbox.js');
const ver = readPkg.sync('..').version;

const site = 'test.app';
const dir = 'test/dir';
const local = '~/local';

// turn on DEBUG messages
test.before(() => {
	process.env.DEBUG = 'exbox';
	process.env.EXBOXTEMP = 'temp-exbox-home';
});

// cleanup: delete the EXBOXTEMP dir
test.after(() => {
	execa('rm', ['-rf', resolve(__dirname, '..', process.env.EXBOXTEMP)]);
});

test('dummy test', async t => {
	const filepath = await write('console.log(0)\n', 'x.js');
	t.is(fs.readFileSync(filepath, 'utf8').trim(), 'console.log(0)');
});

test('exbox.version: `--version` ok', async t => {
	const out = await execa.stdout(cli, ['--version']);
	t.is(out, ver, 'works: full `--version`');
});

test('exbox.version: `-V` ok', async t => {
	const out = await execa.stdout(cli, ['-V']);
	t.is(out, ver);
});

test('exbox.version: `-v` throws', async t => {
	t.throws(execa.stdout(cli, ['-v']));
});

test('exbox.help: `-h` ok', async t => {
	const out = await execa.stdout(cli, ['-h']);
	t.regex(out, /Usage: exbox <command>/);
});

test('exbox.help: `--help` ok', async t => {
	const out = await execa.stdout(cli, ['--help']);
	t.regex(out, /Usage: exbox <command>/);
});

test('exbox.help: `-H` throws', async t => {
	t.throws(execa.stdout(cli, ['-H']));
});

test('exbox.help: `init --help` ok', async t => {
	const out = await execa.stdout(cli, ['init', '--help']);
	t.regex(out, /Usage: init/);
});

test('exbox.help: `domain --help` ok', async t => {
	const out = await execa.stdout(cli, ['domain', '--help']);
	t.regex(out, /Examples:/);
});

test('exbox.init: debugger', async t => {
	const out = await execa.stdout(cli, ['init']);
	t.is(out, '[DEBUG] initializing ExBox!');
});

test('exbox.domain: requires `site`', async t => {
	const err = await t.throws(execa.stdout(cli, ['domain']));
	t.regex(err.message, /error: missing required argument/);
});

test('exbox.domain: requires `dir`', async t => {
	const err = await t.throws(execa.stdout(cli, ['domain', site]));
	t.regex(err.message, /error: missing required argument/);
});

test('exbox.domain: debugger', async t => {
	const out = await execa.stdout(cli, ['domain', site, dir]);
	t.is(out, `[DEBUG] domain: use ssl: false. site: ${site}. dir: ${dir}.`);
});

test('exbox.folder: requires `local`', async t => {
	const err = await t.throws(execa.stdout(cli, ['folder']));
	t.regex(err.message, /error: missing required argument/);
});

test('exbox.folder: requires `dir`', async t => {
	const err = await t.throws(execa.stdout(cli, ['folder', local]));
	t.regex(err.message, /error: missing required argument/);
});

test('exbox.folder: debugger', async t => {
	const out = await execa.stdout(cli, ['folder', local, dir]);
	t.is(out, `[DEBUG] folder: local: ${local}. dir: ${dir}.`);
});
<|endoftext|>


<commit_before>var Embark = require('../lib/index');
var Cmd = require('../lib/cmd');

var passingLines = function () {
  var lines = [];
  lines.push('Initializing Embark Template....');
  lines.push('Installing packages.. this can take a few seconds');
  lines.push('Init complete');
  return lines;
};

describe('embark.Cmd', function () {
  var cmd = new Cmd(Embark);
  var pl = passingLines();
  var appname = 'deleteapp';

  describe('#new', function () {
    this.timeout(0);
    it('it should create an app with a `name` argument set', function (done) {
      cmd.newApp(appname, function (output) {
        var lines = output.split('\n');
        console.log(lines);
        assert.equal(lines[0], pl[0]);
        assert.equal(lines[1], pl[1]);
        assert.equal(lines[2], pl[2]);
        assert.equal(lines[3], 'App ready at ./' + appname);
        done();
      });
    });

    it('it should prompt when given an empty app name', function (done) {
      cmd.newApp(undefined, function (output) {
        var lines = output.split('\n');
        console.log(lines);
        process.stdout.write(appname);
        assert.equal(lines[0], pl[0]);
        done();
      });
    });

  });
});<commit_msg>stdout -> stdin<commit_after>var Embark = require('../lib/index');
var Cmd = require('../lib/cmd');

var passingLines = function () {
  var lines = [];
  lines.push('Initializing Embark Template....');
  lines.push('Installing packages.. this can take a few seconds');
  lines.push('Init complete');
  return lines;
};

describe('embark.Cmd', function () {
  var cmd = new Cmd(Embark);
  var pl = passingLines();
  var appname = 'deleteapp';

  describe('#new', function () {
    this.timeout(0);
    it('it should create an app with a `name` argument set', function (done) {
      cmd.newApp(appname, function (output) {
        var lines = output.split('\n');
        console.log(lines);
        assert.equal(lines[0], pl[0]);
        assert.equal(lines[1], pl[1]);
        assert.equal(lines[2], pl[2]);
        assert.equal(lines[3], 'App ready at ./' + appname);
        done();
      });
    });

    it('it should prompt when given an empty app name', function (done) {
      cmd.newApp(undefined, function (output) {
        var lines = output.split('\n');
        console.log(lines);
        process.stdin.write(appname + '\n');
        assert.equal(lines[0], pl[0]);
        done();
      });
    });

  });
});<|endoftext|>


<commit_before>describe('css template tag', () => {

    const compare = (title, expression, result) => {
        it(title, () => {
            expect(expression,
                `\n${
                    JSON.stringify(expression, true, '\t')
                }\n\t^ should have been ...\n${
                    JSON.stringify(result, null, '\t')
                }\n`)
                .to.deep.equal(result);
        });
    }

    // Taken from samples/hn-reader
    const BRAND_COLOR = '#abcdef';
    compare(
        'general sanity check',
        css`display: block; margin-bottom: 24px; cursor: pointer; .listing { display: flex; flex-direction: row; align-items: center; justify-content: flex-start; width: 100%; &:hover .stats { background: ${BRAND_COLOR}; color: #fff; transform: translate(0, -4px); &::after { background: #fff; } } } .mono { font-family: 'Menlo', 'Monaco', monospace; } .meta { font-size: .9em; opacity: .7; span { display: inline-block; margin: 0 4px; } } .url { overflow: hidden; text-overflow: ellipsis; font-size: .8em; } .content { color: #777; font-size: 1em; } a.stats { height: 64px; width: 64px; flex-shrink: 0; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; overflow: hidden; border-radius: 6px; background: #eee; transition: background .2s, transform .2s; position: relative; text-decoration: none; color: #333; &::after { content: ''; display: block; height: 1px; background: #555; width: 52px; position: absolute; top: 31.5px; left: 6px; } } .score, .comments { height: 32px; width: 100%; line-height: 32px; } .synopsis { margin-left: 12px; flex-shrink: 1; overflow: hidden; } .previewWrapper { display: block; width: 100%; max-width: 500px; margin: 0 auto; } .preview { position: relative; margin: 18px auto 0 auto; width: 100%; height: 0; padding-bottom: 75%; box-shadow: 0 0 0 3px ${BRAND_COLOR}; box-sizing: border-box; transition: opacity .2s; .loadingIndicator { position: absolute; z-index: -1; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 1.3em; text-align: center; width: 100%; color: ${BRAND_COLOR}; } img { box-sizing: border-box; width: 100%; } &:hover { opacity: .7; } }`,
        {'display': 'block', 'margin-bottom': '24px', 'cursor': 'pointer', '.listing': {'display': 'flex', 'flex-direction': 'row', 'align-items': 'center', 'justify-content': 'flex-start', 'width': '100%', '&:hover .stats': {'background': BRAND_COLOR, 'color': '#fff', 'transform': 'translate(0, -4px)', '&::after': {'background': '#fff'}}}, '.mono': {'font-family': '\'Menlo\', \'Monaco\', monospace'}, '.meta': {'font-size': '.9em', 'opacity': '.7', 'span': {'display': 'inline-block', 'margin': '0 4px'}}, '.url': {'overflow': 'hidden', 'text-overflow': 'ellipsis', 'font-size': '.8em'}, '.content': {'color': '#777', 'font-size': '1em'}, 'a.stats': {'height': '64px', 'width': '64px', 'flex-shrink': '0', 'text-align': 'center', 'display': 'flex', 'flex-direction': 'column', 'align-items': 'center', 'justify-content': 'center', 'overflow': 'hidden', 'border-radius': '6px', 'background': '#eee', 'transition': 'background .2s, transform .2s', 'position': 'relative', 'text-decoration': 'none', 'color': '#333', '&::after': {'content': '\'\'', 'display': 'block', 'height': '1px', 'background': '#555', 'width': '52px', 'position': 'absolute', 'top': '31.5px', 'left': '6px'}}, '.score, .comments': {'height': '32px', 'width': '100%', 'line-height': '32px'}, '.synopsis': {'margin-left': '12px', 'flex-shrink': '1', 'overflow': 'hidden'}, '.previewWrapper': {'display': 'block', 'width': '100%', 'max-width': '500px', 'margin': '0 auto'}, '.preview': {'position': 'relative', 'margin': '18px auto 0 auto', 'width': '100%', 'height': '0', 'padding-bottom': '75%', 'box-shadow': '0 0 0 3px ' + BRAND_COLOR, 'box-sizing': 'border-box', 'transition': 'opacity .2s', '.loadingIndicator': {'position': 'absolute', 'z-index': '-1', 'top': '50%', 'left': '50%', 'transform': 'translate(-50%, -50%)', 'font-size': '1.3em', 'text-align': 'center', 'width': '100%', 'color': BRAND_COLOR}, 'img': {'box-sizing': 'border-box', 'width': '100%'}, '&:hover': {'opacity': '.7'}}}
    );

    compare(
        'empty input',
        css``,
        {},
    );

    compare(
        'newlines in input',
        css`
            font-size: 16px;
        `,
        {'font-size': '16px'}
    );

    compare(
        'newlines in input (from cache -- testing cache)',
        css`
            font-size: 16px;
        `,
        {'font-size': '16px'}
    );

    compare(
        'nested quotes',
        css`a: 'b "'cd ef"g"'; x: y-z`,
        {
            'a': '\'b "\'cd ef"g"\'',
            'x': 'y-z',
        }
    );

    compare(
        'should carry over escaped single quotes',
        css`a: 'I\\'m doing well! What\\'s up?'`,
        {
            'a': '\'I\\\'m doing well! What\\\'s up?\'',
        }
    );

    compare(
        'should carry over escaped double quotes',
        css`a: "I\\"m doing well! What\\"s up?"`,
        {
            'a': '"I\\\"m doing well! What\\\"s up?"',
        }
    );

    compare(
        'should respect escaped single quotes with significant chars inside',
        css`a: 'I\\'m doing so well! }:{ ;{'`,
        {
            'a': '\'I\\\'m doing so well! }:{ ;{\'',
        }
    );

    compare(
        'missing semicolon on dangling rule',
        css`
        x {
            y: z
        }
        a: b;
        c: d
        `,
        {
            'x': {
                'y': 'z',
            },
            'a': 'b',
            'c': 'd',
        }
    );

    compare(
        'braces inside quoted strings',
        css`a: b; c: {
            d: 'e}f;g{}';
            x: 'e}f:g{}';
        }`,
        {
            'a': 'b',
            'c': {
                'd': '\'e}f;g{}\'',
                'x': '\'e}f:g{}\'',
            },
        }
    );

    compare(
        'quotes inside quotes',
        css`a: 'b\'c"abc'`,
        {
            'a': '\'b\'c"abc\'',
        }
    );

    compare(
        'multiline values',
        css`font-family: system-ui,
'Helvetica',
'Roboto',
sans-serif;`,
        {
            'font-family': 'system-ui, \'Helvetica\', \'Roboto\', sans-serif',
        }
    );

    compare(
        'pseudoselector support',
        css`
        &:hover {
            cursor: pointer;
        }
        `,
        {
            '&:hover': {
                'cursor': 'pointer',
            },
        }
    );

    compare(
        'pseudoelement support',
        css`
        &::after {
            text-decoration: underline;
        }
        `,
        {
            '&::after': {
                'text-decoration': 'underline',
            },
        }
    );

    compare(
        'multi-selector support',
        css`
        p, i, b > i {
            color: blue;
        }
        `,
        {
            'p, i, b > i': {
                'color': 'blue',
            },
        }
    );

    compare(
        'media query support with min/max-width',
        css`
        @media only screen and (max-width: 600px) {
            h1 {
                font-weight: bold;
            }
        }
        `,
        {
            '@media only screen and (max-width: 600px)': {
                'h1': {
                    'font-weight': 'bold',
                },
            },
        }
    );

    compare(
        'keyframes support',
        css`
        @keyframes animation-name {
            0% {
                color: red;
            }
            50% {
                color: blue;
            }
            100% {
                color: green;
            }
        }
        `,
        {
            '@keyframes animation-name': {
                '0%': {
                    'color': 'red',
                },
                '50%': {
                    'color': 'blue',
                },
                '100%': {
                    'color': 'green',
                },
            },
        }
    );

    describe('graceful failure', () => {

        const noThrow = (title, fn) => {
            it(title, () => expect(fn).to.not.throw());
        }

        noThrow(
            'empty key',
            () => css`: x`
        );

        noThrow(
            'empty value',
            () => css`y: `
        );

        noThrow(
            'newline in key',
            () => css`a
            b: c`
        );

        noThrow(
            'newline in value',
            () => css`a: b
            c`
        );

        noThrow(
            'unclosed brace',
            () => css`a: {b: c`
        );

        noThrow(
            'unexpected closing brace',
            () => css`a: }b`
        );

    });

});
<commit_msg>Pass linter<commit_after>describe('css template tag', () => {

    const compare = (title, expression, result) => {
        it(title, () => {
            expect(expression,
                `\n${
                    JSON.stringify(expression, true, '\t')
                }\n\t^ should have been ...\n${
                    JSON.stringify(result, null, '\t')
                }\n`)
                .to.deep.equal(result);
        });
    }

    // Taken from samples/hn-reader
    const BRAND_COLOR = '#abcdef';
    compare(
        'general sanity check',
        css`display: block; margin-bottom: 24px; cursor: pointer; .listing { display: flex; flex-direction: row; align-items: center; justify-content: flex-start; width: 100%; &:hover .stats { background: ${BRAND_COLOR}; color: #fff; transform: translate(0, -4px); &::after { background: #fff; } } } .mono { font-family: 'Menlo', 'Monaco', monospace; } .meta { font-size: .9em; opacity: .7; span { display: inline-block; margin: 0 4px; } } .url { overflow: hidden; text-overflow: ellipsis; font-size: .8em; } .content { color: #777; font-size: 1em; } a.stats { height: 64px; width: 64px; flex-shrink: 0; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; overflow: hidden; border-radius: 6px; background: #eee; transition: background .2s, transform .2s; position: relative; text-decoration: none; color: #333; &::after { content: ''; display: block; height: 1px; background: #555; width: 52px; position: absolute; top: 31.5px; left: 6px; } } .score, .comments { height: 32px; width: 100%; line-height: 32px; } .synopsis { margin-left: 12px; flex-shrink: 1; overflow: hidden; } .previewWrapper { display: block; width: 100%; max-width: 500px; margin: 0 auto; } .preview { position: relative; margin: 18px auto 0 auto; width: 100%; height: 0; padding-bottom: 75%; box-shadow: 0 0 0 3px ${BRAND_COLOR}; box-sizing: border-box; transition: opacity .2s; .loadingIndicator { position: absolute; z-index: -1; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 1.3em; text-align: center; width: 100%; color: ${BRAND_COLOR}; } img { box-sizing: border-box; width: 100%; } &:hover { opacity: .7; } }`,
        {'display': 'block', 'margin-bottom': '24px', 'cursor': 'pointer', '.listing': {'display': 'flex', 'flex-direction': 'row', 'align-items': 'center', 'justify-content': 'flex-start', 'width': '100%', '&:hover .stats': {'background': BRAND_COLOR, 'color': '#fff', 'transform': 'translate(0, -4px)', '&::after': {'background': '#fff'}}}, '.mono': {'font-family': '\'Menlo\', \'Monaco\', monospace'}, '.meta': {'font-size': '.9em', 'opacity': '.7', 'span': {'display': 'inline-block', 'margin': '0 4px'}}, '.url': {'overflow': 'hidden', 'text-overflow': 'ellipsis', 'font-size': '.8em'}, '.content': {'color': '#777', 'font-size': '1em'}, 'a.stats': {'height': '64px', 'width': '64px', 'flex-shrink': '0', 'text-align': 'center', 'display': 'flex', 'flex-direction': 'column', 'align-items': 'center', 'justify-content': 'center', 'overflow': 'hidden', 'border-radius': '6px', 'background': '#eee', 'transition': 'background .2s, transform .2s', 'position': 'relative', 'text-decoration': 'none', 'color': '#333', '&::after': {'content': '\'\'', 'display': 'block', 'height': '1px', 'background': '#555', 'width': '52px', 'position': 'absolute', 'top': '31.5px', 'left': '6px'}}, '.score, .comments': {'height': '32px', 'width': '100%', 'line-height': '32px'}, '.synopsis': {'margin-left': '12px', 'flex-shrink': '1', 'overflow': 'hidden'}, '.previewWrapper': {'display': 'block', 'width': '100%', 'max-width': '500px', 'margin': '0 auto'}, '.preview': {'position': 'relative', 'margin': '18px auto 0 auto', 'width': '100%', 'height': '0', 'padding-bottom': '75%', 'box-shadow': '0 0 0 3px ' + BRAND_COLOR, 'box-sizing': 'border-box', 'transition': 'opacity .2s', '.loadingIndicator': {'position': 'absolute', 'z-index': '-1', 'top': '50%', 'left': '50%', 'transform': 'translate(-50%, -50%)', 'font-size': '1.3em', 'text-align': 'center', 'width': '100%', 'color': BRAND_COLOR}, 'img': {'box-sizing': 'border-box', 'width': '100%'}, '&:hover': {'opacity': '.7'}}}
    );

    compare(
        'empty input',
        css``,
        {},
    );

    compare(
        'newlines in input',
        css`
            font-size: 16px;
        `,
        {'font-size': '16px'}
    );

    compare(
        'newlines in input (from cache -- testing cache)',
        css`
            font-size: 16px;
        `,
        {'font-size': '16px'}
    );

    compare(
        'nested quotes',
        css`a: 'b "'cd ef"g"'; x: y-z`,
        {
            'a': '\'b "\'cd ef"g"\'',
            'x': 'y-z',
        }
    );

    compare(
        'should carry over escaped single quotes',
        css`a: 'I\\'m doing well! What\\'s up?'`,
        {
            'a': '\'I\\\'m doing well! What\\\'s up?\'',
        }
    );

    compare(
        'should carry over escaped double quotes',
        css`a: "I\\"m doing well! What\\"s up?"`,
        {
            'a': '"I\\"m doing well! What\\"s up?"',
        }
    );

    compare(
        'should respect escaped single quotes with significant chars inside',
        css`a: 'I\\'m doing so well! }:{ ;{'`,
        {
            'a': '\'I\\\'m doing so well! }:{ ;{\'',
        }
    );

    compare(
        'missing semicolon on dangling rule',
        css`
        x {
            y: z
        }
        a: b;
        c: d
        `,
        {
            'x': {
                'y': 'z',
            },
            'a': 'b',
            'c': 'd',
        }
    );

    compare(
        'braces inside quoted strings',
        css`a: b; c: {
            d: 'e}f;g{}';
            x: 'e}f:g{}';
        }`,
        {
            'a': 'b',
            'c': {
                'd': '\'e}f;g{}\'',
                'x': '\'e}f:g{}\'',
            },
        }
    );

    compare(
        'quotes inside quotes',
        css`a: 'b\'c"abc'`,
        {
            'a': '\'b\'c"abc\'',
        }
    );

    compare(
        'multiline values',
        css`font-family: system-ui,
'Helvetica',
'Roboto',
sans-serif;`,
        {
            'font-family': 'system-ui, \'Helvetica\', \'Roboto\', sans-serif',
        }
    );

    compare(
        'pseudoselector support',
        css`
        &:hover {
            cursor: pointer;
        }
        `,
        {
            '&:hover': {
                'cursor': 'pointer',
            },
        }
    );

    compare(
        'pseudoelement support',
        css`
        &::after {
            text-decoration: underline;
        }
        `,
        {
            '&::after': {
                'text-decoration': 'underline',
            },
        }
    );

    compare(
        'multi-selector support',
        css`
        p, i, b > i {
            color: blue;
        }
        `,
        {
            'p, i, b > i': {
                'color': 'blue',
            },
        }
    );

    compare(
        'media query support with min/max-width',
        css`
        @media only screen and (max-width: 600px) {
            h1 {
                font-weight: bold;
            }
        }
        `,
        {
            '@media only screen and (max-width: 600px)': {
                'h1': {
                    'font-weight': 'bold',
                },
            },
        }
    );

    compare(
        'keyframes support',
        css`
        @keyframes animation-name {
            0% {
                color: red;
            }
            50% {
                color: blue;
            }
            100% {
                color: green;
            }
        }
        `,
        {
            '@keyframes animation-name': {
                '0%': {
                    'color': 'red',
                },
                '50%': {
                    'color': 'blue',
                },
                '100%': {
                    'color': 'green',
                },
            },
        }
    );

    describe('graceful failure', () => {

        const noThrow = (title, fn) => {
            it(title, () => expect(fn).to.not.throw());
        }

        noThrow(
            'empty key',
            () => css`: x`
        );

        noThrow(
            'empty value',
            () => css`y: `
        );

        noThrow(
            'newline in key',
            () => css`a
            b: c`
        );

        noThrow(
            'newline in value',
            () => css`a: b
            c`
        );

        noThrow(
            'unclosed brace',
            () => css`a: {b: c`
        );

        noThrow(
            'unexpected closing brace',
            () => css`a: }b`
        );

    });

});
<|endoftext|>


<commit_before>/*
 * Storage Expires
 *
 * Key expiration for any storage interface (defaults to LocalStorage)
*/

var assign = require('./util/assign');
var lsWrapper = require('./util/ls-wrapper');

// StorageExpires
// --------------

// Decorate storage interface with key-expiration by prepending a timestamp to writes.
module.exports = function(storage) {

  if (typeof storage === 'undefined') {
    storage = lsWrapper;
  }

  return assign({}, storage, {

    // Fetch and serialize the value for a given key. Delete the key if it's expired or
    // does not comply with the protocol.
    get: function(key) {
      var storageExpires = this,
          data = storage.get.apply(this, arguments) || '',
          fail = function() { storageExpires.unset(key); },
          ref, expires, value;

      // Fail if `value` doesn't comply with expirable-key protocol.
      if (typeof data != 'string') return fail();

      ref = this.decode(data);
      expires = ref[0];

      try { value = this.deserialize(ref[1]); }
      catch (e) { return fail(); }

      // `undefined` does not comply with protocol.
      if (typeof expires === 'undefined') {
        return fail();
      // -1 means no expiration.
      } else if (expires != -1) {
        if (new Date(expires) < new Date) return fail();
      }

      return value;
    },

    set: function(key, value, options) {
      return storage.set(key, this.encode(this.serialize(value), options));
    },

    serialize: function(value) {
      return JSON.stringify(value);
    },

    deserialize: function(data) {
      return JSON.parse(data);
    },

    // Prepend a timestamp to any value.
    encode: function(value, options) {
      var e;
      options = options || {};
      value = (+options.expires || -1) + ' ' + value;
      return value;
    },

    // Parse the timestamp and value, returning [undefined, undefined] if the value
    // does not comply with the protocol.
    decode: function(data) {
      var index, expires,
          fail = function() { return [undefined, undefined]; };

      if (!data) return fail();

      index = data.indexOf(' ');

      if (index === -1) return fail();

      expires = parseInt(data.substring(0, index), 10);
      data = data.substring(index + 1);

      // Check for NaN
      if (expires != +expires) return fail();

      return [expires, data];
    }

  });

};
<commit_msg>Move try..catch into deserialize so external use doesn't have to worry about malformed data<commit_after>/*
 * Storage Expires
 *
 * Key expiration for any storage interface (defaults to LocalStorage)
*/

var assign = require('./util/assign');
var lsWrapper = require('./util/ls-wrapper');

// StorageExpires
// --------------

// Decorate storage interface with key-expiration by prepending a timestamp to writes.
module.exports = function(storage) {

  if (typeof storage === 'undefined') {
    storage = lsWrapper;
  }

  return assign({}, storage, {

    // Fetch and serialize the value for a given key. Delete the key if it's expired or
    // does not comply with the protocol.
    get: function(key) {
      var storageExpires = this,
          data = storage.get.apply(this, arguments) || '',
          fail = function() { storageExpires.unset(key); },
          ref, expires, value;

      // Fail if `value` doesn't comply with expirable-key protocol.
      if (typeof data != 'string') return fail();

      ref = this.decode(data);
      expires = ref[0];
      value = this.deserialize(ref[1]);

      // `undefined` does not comply with protocol.
      if (typeof expires === 'undefined' || typeof value === 'undefined') {
        return fail();
      // -1 means no expiration.
      } else if (expires != -1) {
        if (new Date(expires) < new Date) return fail();
      }

      return value;
    },

    set: function(key, value, options) {
      return storage.set(key, this.encode(this.serialize(value), options));
    },

    serialize: function(value) {
      return JSON.stringify(value);
    },

    deserialize: function(data) {
      try {
        return JSON.parse(data);
      } catch (e) {
        return;
      }
    },

    // Prepend a timestamp to any value.
    encode: function(value, options) {
      var e;
      options = options || {};
      value = (+options.expires || -1) + ' ' + value;
      return value;
    },

    // Parse the timestamp and value, returning [undefined, undefined] if the value
    // does not comply with the protocol.
    decode: function(data) {
      var index, expires,
          fail = function() { return [undefined, undefined]; };

      if (!data) return fail();

      index = data.indexOf(' ');

      if (index === -1) return fail();

      expires = parseInt(data.substring(0, index), 10);
      data = data.substring(index + 1);

      // Check for NaN
      if (expires != +expires) return fail();

      return [expires, data];
    }

  });

};
<|endoftext|>


<commit_before>const LexFixture = require('../fixtures/LexFixture');

const LexService = require('../../service/LexService');
const sinon = require('sinon');
const Bluebird = require('bluebird');

let sandbox;

describe('#LexService', () => {
  beforeEach(() => {
    sandbox = sinon.sandbox.create();
  });

  afterEach(() => (sandbox.restore()));

  describe('#Params Validation', () => {
    it('should fail if the nextAction is null', () => {
      return LexService.buildResponse('', null).should.be.rejectedWith('nextAction is required');
    });
  });

  describe('#Business Logic', () => {
    // it('should succeed and return a valid response object', () => {
    //   const session = {
    //     completedDistractions: LexFixture.newCompletedArray()
    //   };
    //   const nextAction = LexFixture.newDistractionObj();
    //
    //   return Bluebird.resolve()
    //     .then(() => LexService.buildResponse(session, nextAction))
    //     .then(res => LexFixture.validate(res));
    // });
  });
});
<commit_msg>Update FeelingScore tests<commit_after>const LexService = require('../../service/LexService');
const sinon = require('sinon');

let sandbox;

describe('#LexService', () => {
  beforeEach(() => {
    sandbox = sinon.sandbox.create();
  });

  afterEach(() => (sandbox.restore()));

  describe('#Params Validation', () => {
    it('should fail if the nextAction is null', () => {
      return LexService.buildResponse('', null).should.be.rejectedWith('nextAction is required');
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var sqlAction = require("./mysql.js"); //mysql 配置文件
var redis = require("redis");
var client = redis.createClient();
var i = 0;
function sql() {
	client.lrange('frameworks', 0, i, function(err, reply) {
		console.log(reply); // ['angularjs', 'backbone']
		if(reply) {
			sqlAction.insert('INSERT IGNORE INTO list(name,magnet,infoHash,size,catch_date,hot,download_count,file_number,content_file) VALUES ?',[JSON.parse(reply)],function (err, vals, fields) {
				i++;
				sql();
			});
		}
	});
}

sql();<commit_msg>add loop<commit_after>'use strict';

var sqlAction = require("./mysql.js"); //mysql 配置文件
var redis = require("redis");
var client = redis.createClient();
var i = 1;
function sql() {
	client.lrange('frameworks', 0, i, function(err, reply) {
		console.log(reply); // ['angularjs', 'backbone']
		if(reply) {
			sqlAction.insert('INSERT IGNORE INTO list(name,magnet,infoHash,size,catch_date,hot,download_count,file_number,content_file) VALUES ?',[JSON.parse(reply[0])],function (err, vals, fields) {
				i++;
				sql();
			});
		}
	});
}

sql();<|endoftext|>


<commit_before>/**
 * @flow
 * All About Olaf
 * iOS Home page
 */

import React from 'react'
import {ScrollView, StyleSheet, StatusBar} from 'react-native'

import {connect} from 'react-redux'
import * as c from '../components/colors'
import sortBy from 'lodash/sortBy'
import type {TopLevelViewPropsType} from '../types'
import type {ViewType} from '../views'
import {allViews} from '../views'
import {Column} from '../components/layout'
import {partitionByIndex} from '../../lib/partition-by-index'
import {HomeScreenButton, CELL_MARGIN} from './button'
import {trackedOpenUrl} from '../components/open-url'
import {EditHomeButton, OpenSettingsButton} from '../components/nav-buttons'

type Props = TopLevelViewPropsType & {
  order: string[],
  views: ViewType[],
}

function HomePage({navigation, order, views = allViews}: Props) {
  const sortedViews = sortBy(views, view => order.indexOf(view.view))

  const columns = partitionByIndex(sortedViews)

  return (
    <ScrollView
      overflow="hidden"
      alwaysBounceHorizontal={false}
      showsHorizontalScrollIndicator={false}
      showsVerticalScrollIndicator={false}
      contentContainerStyle={styles.cells}
    >
      <StatusBar barStyle="light-content" backgroundColor={c.gold} />

      {columns.map((contents, i) =>
        <Column key={i} flex={1}>
          {contents.map(view =>
            <HomeScreenButton
              key={view.view}
              view={view}
              onPress={() => {
                if (view.type === 'url') {
                  return trackedOpenUrl({url: view.url, id: view.view})
                } else {
                  return navigation.navigate(view.view)
                }
              }}
            />,
          )}
        </Column>,
      )}
    </ScrollView>
  )
}
HomePage.navigationOptions = ({navigation}) => {
  return {
    title: 'All About Olaf',
    headerBackTitle: 'Home',
    headerLeft: <OpenSettingsButton navigation={navigation} />,
    headerRight: <EditHomeButton navigation={navigation} />,
  }
}

function mapStateToProps(state) {
  return {
    order: state.homescreen.order,
  }
}
export default connect(mapStateToProps)(HomePage)

const styles = StyleSheet.create({
  cells: {
    marginHorizontal: CELL_MARGIN / 2,
    marginTop: CELL_MARGIN / 2,
    paddingBottom: CELL_MARGIN / 2,

    flexDirection: 'row',
  },
})
<commit_msg>store the homescreen column style in a stylesheet<commit_after>/**
 * @flow
 * All About Olaf
 * iOS Home page
 */

import React from 'react'
import {ScrollView, StyleSheet, StatusBar} from 'react-native'

import {connect} from 'react-redux'
import * as c from '../components/colors'
import sortBy from 'lodash/sortBy'
import type {TopLevelViewPropsType} from '../types'
import type {ViewType} from '../views'
import {allViews} from '../views'
import {Column} from '../components/layout'
import {partitionByIndex} from '../../lib/partition-by-index'
import {HomeScreenButton, CELL_MARGIN} from './button'
import {trackedOpenUrl} from '../components/open-url'
import {EditHomeButton, OpenSettingsButton} from '../components/nav-buttons'

type Props = TopLevelViewPropsType & {
  order: string[],
  views: ViewType[],
}

function HomePage({navigation, order, views = allViews}: Props) {
  const sortedViews = sortBy(views, view => order.indexOf(view.view))

  const columns = partitionByIndex(sortedViews)

  return (
    <ScrollView
      overflow="hidden"
      alwaysBounceHorizontal={false}
      showsHorizontalScrollIndicator={false}
      showsVerticalScrollIndicator={false}
      contentContainerStyle={styles.cells}
    >
      <StatusBar barStyle="light-content" backgroundColor={c.gold} />

      {columns.map((contents, i) =>
        <Column key={i} style={styles.column}>
          {contents.map(view =>
            <HomeScreenButton
              key={view.view}
              view={view}
              onPress={() => {
                if (view.type === 'url') {
                  return trackedOpenUrl({url: view.url, id: view.view})
                } else {
                  return navigation.navigate(view.view)
                }
              }}
            />,
          )}
        </Column>,
      )}
    </ScrollView>
  )
}
HomePage.navigationOptions = ({navigation}) => {
  return {
    title: 'All About Olaf',
    headerBackTitle: 'Home',
    headerLeft: <OpenSettingsButton navigation={navigation} />,
    headerRight: <EditHomeButton navigation={navigation} />,
  }
}

function mapStateToProps(state) {
  return {
    order: state.homescreen.order,
  }
}
export default connect(mapStateToProps)(HomePage)

const styles = StyleSheet.create({
  cells: {
    marginHorizontal: CELL_MARGIN / 2,
    marginTop: CELL_MARGIN / 2,
    paddingBottom: CELL_MARGIN / 2,

    flexDirection: 'row',
  },
  column: {
    flex: 1,
  },
})
<|endoftext|>


<commit_before>
var async = require('..');

exports['map and then'] = function (test) {
    test.async();

    var total = 0;

    var seq = async()
        .map(function (item) {
            return item * item;
        })
        .then(function (data) {
            test.ok(data);
            test.ok(Array.isArray(data));
            test.equal(data.length, 3);
            test.equal(data[0], 1);
            test.equal(data[1], 4);
            test.equal(data[2], 9);

            test.done();
        });

    test.ok(seq);
    test.strictEqual(seq.run([1,2,3]), seq);
}

exports['map with async fn and then'] = function (test) {
    test.async();

    var total = 0;

    var seq = async()
        .map(function (item, next) {
            next(null, item * item);
        })
        .then(function (data) {
            test.ok(data);
            test.ok(Array.isArray(data));
            test.equal(data.length, 3);
            test.equal(data[0], 1);
            test.equal(data[1], 4);
            test.equal(data[2], 9);

            test.done();
        });

    test.ok(seq);
    test.strictEqual(seq.run([1,2,3]), seq);
}

exports['map empty array with async fn and then'] = function (test) {
    test.async();

    var total = 0;

    var seq = async()
        .map(function (item, next) {
            next(null, item * item);
        })
        .then(function (data) {
            test.ok(data);
            test.ok(Array.isArray(data));
            test.equal(data.length, 0);

            test.done();
        });

    test.ok(seq);
    test.strictEqual(seq.run([]), seq);
}
<commit_msg>Additional test, map with error<commit_after>
var async = require('..');

exports['map and then'] = function (test) {
    test.async();

    var total = 0;

    var seq = async()
        .map(function (item) {
            return item * item;
        })
        .then(function (data) {
            test.ok(data);
            test.ok(Array.isArray(data));
            test.equal(data.length, 3);
            test.equal(data[0], 1);
            test.equal(data[1], 4);
            test.equal(data[2], 9);

            test.done();
        });

    test.ok(seq);
    test.strictEqual(seq.run([1,2,3]), seq);
}

exports['map with async fn and then'] = function (test) {
    test.async();

    var total = 0;

    var seq = async()
        .map(function (item, next) {
            next(null, item * item);
        })
        .then(function (data) {
            test.ok(data);
            test.ok(Array.isArray(data));
            test.equal(data.length, 3);
            test.equal(data[0], 1);
            test.equal(data[1], 4);
            test.equal(data[2], 9);

            test.done();
        });

    test.ok(seq);
    test.strictEqual(seq.run([1,2,3]), seq);
}

exports['map empty array with async fn and then'] = function (test) {
    test.async();

    var total = 0;

    var seq = async()
        .map(function (item, next) {
            next(null, item * item);
        })
        .then(function (data) {
            test.ok(data);
            test.ok(Array.isArray(data));
            test.equal(data.length, 0);

            test.done();
        });

    test.ok(seq);
    test.strictEqual(seq.run([]), seq);
}

exports['map with error'] = function (test) {
    test.async();

    var total = 0;

    var seq = async()
        .map(function (item, next) {
            if (item == 2)
                next("error", null);
            else
                next(null, item * item);
        })
        .then(function (data) {
            test.fail();
        })
        .fail(function (err) {
            test.equal(err, "error");

            test.done();
        });

    test.ok(seq);
    test.strictEqual(seq.run([1,2,3]), seq);
}

<|endoftext|>


<commit_before>var config = require(__dirname+'/../config.js');

var r = require('rethinkdb');
var assert = require('assert');

var connections = {};
var TEST_DB = 'reqlitetest';
var TEST_TABLE = 'reqlitetestselectingdata';
var MISSING_ID = 'nonExistingId';
var MISSING_FIELD = 'nonExistingField';
var MISSING_INDEX = 'nonExistingIndex';
var COMPLEX_OBJECT = {
  id: 1,
  foo: 2,
  buzz: {
    hello: [10, 11, 12],
    world: {
      nested: 100,
      field: 200
    },
    bonjour: [
      {monde: 1000, ciao: 4000},
      {monde: 2000, ciao: 5000},
      {monde: 3000, ciao: 6000},
    ]
  },
}

var compare = require(__dirname+'/util.js').generateCompare(connections);

describe('new.js', function(){
  before(function(done) {
    setTimeout(function() { // Delay for nodemon to restart the server
      r.connect(config.rethinkdb).bind({}).then(function(conn) {
        connections.rethinkdb = conn;
        return r.connect(config.reqlite);
      }).then(function(conn) {
        connections.reqlite = conn;
        this.query = r.dbCreate(TEST_DB);
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).tableDrop(TEST_TABLE)
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).tableCreate(TEST_TABLE)
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).table(TEST_TABLE).insert([
          {id: 1, foo: 10, bar: [100, 101, 102], optional: 1},
          {id: 2, foo: 20, bar: [200, 201, 202], optional: 2},
          {id: 3, foo: 30, bar: [300, 301, 302], optional: 2},
          {id: 4, foo: 40, bar: [400, 401, 402]},
        ]);
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).table(TEST_TABLE).indexCreate('foo')
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).table(TEST_TABLE).indexCreate('bar')
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).table(TEST_TABLE).indexCreate('barmulti', r.row('bar'), {multi: true})
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
      //TODO add and test a geo index
        done();
      });
    }, 300)
  });

  //TODO Uncomment r.range - 5
  /*
  it('http - 1', function(done) {
    var query = r.http('http://httpbin.org/get');
    compare(query, done);
  })

  it('http - 2', function(done) {
    var query = r.expr([1,2,3, r.http('http://httpbin.org/get')]);
    compare(query, done);
  })

  it('http - 3', function(done) {
    var query = r.error(r.http('http://httpbin.org/'));
    compare(query, done);
  })

  it('http - 3', function(done) {
    var query = r.db(TEST_DB).table(r.http('http://httpbin.org/'));
    compare(query, done);
  })
  */

  it('eq - 1', function(done) {
    var query = r.expr([{id: 10}, {id: 22}, {id: 3}, {id: 1}, {id: 23}, {id: 4}, {id: 211}, {id: 3},{id: 5}]).orderBy('id');
    //compare(query, done);
  });

  /*
    compare(query, done, function(e) { console.log(''); console.log(e); return e; });
  */
});

<commit_msg>Disable test/new.js<commit_after>var config = require(__dirname+'/../config.js');

var r = require('rethinkdb');
var assert = require('assert');

var connections = {};
var TEST_DB = 'reqlitetest';
var TEST_TABLE = 'reqlitetestselectingdata';
var MISSING_ID = 'nonExistingId';
var MISSING_FIELD = 'nonExistingField';
var MISSING_INDEX = 'nonExistingIndex';
var COMPLEX_OBJECT = {
  id: 1,
  foo: 2,
  buzz: {
    hello: [10, 11, 12],
    world: {
      nested: 100,
      field: 200
    },
    bonjour: [
      {monde: 1000, ciao: 4000},
      {monde: 2000, ciao: 5000},
      {monde: 3000, ciao: 6000},
    ]
  },
}

var compare = require(__dirname+'/util.js').generateCompare(connections);

describe('new.js', function(){
  before(function(done) {
    setTimeout(function() { // Delay for nodemon to restart the server
      r.connect(config.rethinkdb).bind({}).then(function(conn) {
        connections.rethinkdb = conn;
        return r.connect(config.reqlite);
      }).then(function(conn) {
        connections.reqlite = conn;
        this.query = r.dbCreate(TEST_DB);
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).tableDrop(TEST_TABLE)
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).tableCreate(TEST_TABLE)
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).table(TEST_TABLE).insert([
          {id: 1, foo: 10, bar: [100, 101, 102], optional: 1},
          {id: 2, foo: 20, bar: [200, 201, 202], optional: 2},
          {id: 3, foo: 30, bar: [300, 301, 302], optional: 2},
          {id: 4, foo: 40, bar: [400, 401, 402]},
        ]);
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).table(TEST_TABLE).indexCreate('foo')
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).table(TEST_TABLE).indexCreate('bar')
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
        this.query = r.db(TEST_DB).table(TEST_TABLE).indexCreate('barmulti', r.row('bar'), {multi: true})
        return this.query.run(connections.rethinkdb);
      }).catch(function() { // ignore errors
      }).finally(function() {
        return this.query.run(connections.reqlite);
      }).catch(function() { // ignore errors
      }).finally(function() {
      //TODO add and test a geo index
        done();
      });
    }, 300)
  });

  //Test playground

  /*
  it('eq - 1', function(done) {
    var query = r.expr([{id: 10}, {id: 22}, {id: 3}, {id: 1}, {id: 23}, {id: 4}, {id: 211}, {id: 3},{id: 5}]).orderBy('id');
    compare(query, done);
  });
  */

  /*
    compare(query, done, function(e) { console.log(''); console.log(e); return e; });
  */
});

<|endoftext|>