<commit_before>(function () {
    "use strict";

    angular.module("services")
        .factory("Prototyper", Prototyper);

    Prototyper.$inject = [
        'userConstants',
        'DocumentLabels',
        'DocumentKinds',
        'documentFieldsRules',
        'documentOrigins'
    ];

    function Prototyper(userConstants, DocumentLabels, DocumentKinds, documentFieldsRules, documentOrigins) {
        const service = {
            toUserModel: toUserModel,
            toUsersCollection: applyToAll(toUserModel),
            toGroupModel: toGroupModel,
            toGroupsCollection: applyToAll(toGroupModel),
            toDocumentModel: toDocumentModel,
            toDocumentsCollection: applyToAll(toDocumentModel),
            toCollaborationModel: toCollaborationModel,
            toCollaborationsCollection: applyToAll(toCollaborationModel),
            toMembershipModel: toMembershipModel,
            toMembershipsCollection: applyToAll(toMembershipModel),
            toAuthorshipModel: toAuthorshipModel,
            toAuthorshipsCollection: applyToAll(toAuthorshipModel),
            toInstituteModel: toInstituteModel,
            toInstitutesCollection: applyToAll(toInstituteModel),
            toTagLabelModel: toTagLabelModel,
            toTagLabelsCollection: applyToAll(toTagLabelModel),
        };
        const userPrototype = {
            getAliases: function () {
                return this.aliases.map(a => a.str);
            },
            getDisplayName: function () {
                var name = this.name ? this.name : "";
                var surname = this.surname ? this.surname : "";
                var fullName = _.trim(name + " " + surname);
                return fullName;
            },
            getType: function () {
                return 'user';
            },
            getCollaborationGroups: function () {
                return _.map(this.collaborations, 'group');
            },
            isAdmin: function () {
                return this.role === userConstants.role.ADMINISTRATOR;
            },
            admins: function (group) {
                var administeredGroupsId = _.map(this.administratedGroups, 'id');
                return _.includes(administeredGroupsId, group.id);
            },
            getExternalConnectors: function () {
                var connectors = [];
                var publicationsConnector = {value: 'publications', label: 'Publications', enabled: true};
                var scopusConnector = {value: 'scopus', label: 'Scopus', enabled: !!this.scopusId};
                connectors.push(publicationsConnector);
                connectors.push(scopusConnector);
                return connectors;
            },
            getNewDocument: function (documentTypeObj) {
                var documentData = {
                    draftCreator: this.id,
                    kind: DocumentKinds.DRAFT,
                    type: documentTypeObj.key,
                    sourceType: documentTypeObj.defaultSource,
                    origin: documentOrigins.SCIENTILLA
                };
                return documentPrototype.create(documentData);
            },
            getProfileUrl: function () {
                return '/users/' + this.id;
            },
            getTagsByDocument: function (document) {
                if (!document.tagLabels || !document.userTags)
                    return [];

                var filteredUserTags = document.userTags.filter(function (ut) {
                    return ut.researchEntity === this.id;
                }.bind(this));

                return document.tagLabels.filter(function (tagLabel) {
                    return !!filteredUserTags.find(function (ut) {
                        return tagLabel.id === ut.tagLabel;
                    });
                });
            },
            isInternal: function () {
                return _.endsWith(this.username, '@iit.it');
            }
        };
        const groupPrototype = {
            getDisplayName: function () {
                return this.name;
            },
            getType: function () {
                return 'group';
            },
            getExternalConnectors: function () {
                var connectors = [];
                var publicationsConnector = {
                    value: 'publications',
                    label: 'Publications',
                    enabled: !!this.publicationsAcronym
                };
                var scopusConnector = {value: 'scopus', label: 'Scopus', enabled: !!this.scopusId};
                connectors.push(publicationsConnector);
                connectors.push(scopusConnector);
                return connectors;
            },
            getNewDocument: function (documentTypeObj) {
                var documentData = {
                    draftCreator: this.id,
                    kind: DocumentKinds.DRAFT,
                    type: documentTypeObj.key,
                    sourceType: documentTypeObj.defaultSource,
                    origin: documentOrigins.SCIENTILLA
                };
                return documentPrototype.create(documentData);
            },
            getProfileUrl: function () {
                return '/groups/' + this.id;
            },
            getTagsByDocument: function (document) {
                if (!document.groupTagLabels || !document.groupTags)
                    return [];

                var filteredGroupTags = document.groupTags.filter(function (gt) {
                    return gt.researchEntity === this.id;
                }.bind(this));

                return document.groupTagLabels.filter(function (tagLabel) {
                    return !!filteredGroupTags.find(function (gt) {
                        return tagLabel.id === gt.tagLabel;
                    });
                });
            },
            getActiveMembers: function () {
                return this.members.filter(u => {
                    const userMembersihp = this.memberships.find(m => m.user === u.id);
                    return userMembersihp && userMembersihp.synchronized && userMembersihp.active;
                });
            },
            getCollaborators: function () {
                return this.members.filter(u => {
                    const userMembersihp = this.memberships.find(m => m.user === u.id);
                    return userMembersihp && !userMembersihp.synchronized && userMembersihp.active;
                });
            },
            getFormerMembers: function () {
                return this.members.filter(u => {
                    const userMembersihp = this.memberships.find(m => m.user === u.id);
                    return userMembersihp && !userMembersihp.active;
                });
            },
            getResearchDomain: function () {
                const researchDomain = this.attributes
                    .filter(a => a.category === 'research_domain')
                    .reduce((res, a) => {
                        const ga = this.groupAttributes.find(ga => ga.attribute === a.id);
                        if (ga.extra.type === 'main') return a;
                        return res;
                    }, null);

                if (_.isObject(researchDomain))
                    return researchDomain.value;
            },
            getInteractions: function () {
                const interactionsGroupAttributes = this.groupAttributes.filter(ga => ga.extra.type === 'interaction');
                const interactions = this.attributes
                    .filter(a => a.category === 'research_domain')
                    .reduce((res, a) => {
                        const groupAttribute = interactionsGroupAttributes.find(ga => ga.attribute === a.id);
                        if (groupAttribute)
                            res.push(a);
                        return res;
                    }, []);

                return interactions.map(i => i.value);
            }
        };

        const documentPrototype = {
            UNKNOWN_DOCUMENT: 0,
            USER_DOCUMENT: 1,
            GROUP_DOCUMENT: 2,
            labels: [],
            fields: [
                'authorsStr',
                'title',
                'year',
                'itSource',
                'source',
                'issue',
                'volume',
                'pages',
                'articleNumber',
                'doi',
                'abstract',
                'type',
                'sourceType',
                'scopusId',
                'wosId',
                'authorships',
                'affiliations',
                'institutes',
                'synchronized',
                'origin'
            ],
            create: function (documentData) {
                var fields = _.union(['kind', 'draftCreator', 'draftGroupCreator'], documentPrototype.fields);
                var document = _.pick(documentData, fields);
                _.extend(document, documentPrototype);
                return document;
            },
            isValid: function () {
                const requiredFields = [
                    'authorsStr',
                    'title',
                    'year',
                    'type',
                    'sourceType'
                ];
                // TODO: refactor, invited_talk should be read by a service;
                const invitedTalkType = 'invited_talk';
                if (this.type === invitedTalkType)
                    requiredFields.push('itSource');
                else
                    requiredFields.push('source');

                return _.every(requiredFields, v => this[v]) &&
                    _.every(documentFieldsRules, (rule, k) => {
                        if (!this[k]) return rule.allowNull;
                        return rule.regex.test(this[k]);
                    });
            },
            getAllCoauthors: function () {
                return this.authors;
            },
            getType: function () {
                if (!!this.owner)
                    return this.USER_DOCUMENT;
                else if (!!this.groupOwner)
                    return this.GROUP_DOCUMENT;
                else
                    return this.UNKNOWN_DOCUMENT;
            },
            getAuthors: function () {
                if (!this.authorsStr)
                    return [];

                return this.authorsStr.replace(/\s+et all\s*$/i, '').split(/,\s*/).map(_.trim);
            },
            getUcAuthors: function () {
                var authors = this.getAuthors();
                var ucAuthors = _.map(authors, function (a) {
                    return a.toUpperCase();
                });
                return ucAuthors;
            },
            getDisplayName: function () {
                return this.getDisplayName();
            },
            getUserIndex: function (user) {
                const authors = this.getAuthors().map(a => a.toLocaleLowerCase());
                const aliases = user.getAliases().map(a => a.toLocaleLowerCase());
                return _.findIndex(authors, a => aliases.includes(a));
            },
            copyDocument: function (document, creator) {
                var excludedFields = ['kind', 'draftCreator', 'draftGroupCreator'];

                var documentTypeObj = {
                    key: document.type,
                    defaultSource: document.sourceType
                };

                var newDoc = creator.getNewDocument(documentTypeObj);

                _.forEach(documentPrototype.fields, function (key) {
                    if (_.includes(excludedFields, key))
                        return;

                    newDoc[key] = document[key];
                });

                return newDoc;
            },
            addLabel: function (label) {
                if (!this.hasLabel(label))
                    this.labels.push(label);
            },
            removeLabel: function (label) {
                _.remove(this.labels, function (t) {
                    return t === label;
                });
            },
            hasLabel: function (label) {
                return this.labels.includes(label);
            },
            isDiscarded: function () {
                return this.hasLabel(DocumentLabels.DISCARDED);
            },
            isUnverifying: function () {
                return this.hasLabel(DocumentLabels.UVERIFYING);
            },
            getInstituteIdentifier: function (instituteIndex) {
                const base26Chars = "0123456789abcdefghijklmnopqrstuvwxyz".split("");
                const alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
                const alphabetMapper = {};
                alphabet.forEach((v, i) => alphabetMapper[base26Chars[i]] = v);
                const base26Value = instituteIndex.toString(alphabet.length).split('');
                if (base26Value.length > 1)
                    base26Value[0] = base26Chars[base26Chars.indexOf(base26Value[0]) - 1];

                return base26Value.map(c => alphabetMapper[c]).join('');
            },
            isSuggested: function (researchEntity) {
                const f = researchEntity.getType() === 'user' ? 'authors' : 'groups';
                return (this.kind === DocumentKinds.VERIFIED || this.isExternal()) && !this[f].some(re => re.id === researchEntity.id);
            },
            isDraft: function () {
                return this.kind === DocumentKinds.DRAFT;
            },
            isVerified: function (researchEntity) {
                const f = researchEntity.getType() === 'user' ? 'authors' : 'groups';
                return this[f].some(re => re.id === researchEntity.id);
            },
            isExternal: function () {
                return this.kind === DocumentKinds.EXTERNAL;
            },
            hasValidScopusId: function () {
                if (!this.scopusDocumentMetadata || !this.scopusDocumentMetadata[0]) return true;
                return !this.scopusDocumentMetadata[0].data.scopusDocumentMetadata;
            },
            getStringKind(researchEntity) {
                if (this.isSuggested(researchEntity))
                    return 'Suggested';
                if (this.isDraft())
                    return 'Draft';
                if (this.isVerified(researchEntity))
                    return 'Verified';
            },
            getComparisonDuplicate() {
                return this.getComparisonDuplicates()[0];
            },
            getComparisonDuplicates() {
                let duplicates;
                if (this.isDraft())
                    duplicates = this.duplicates;
                else
                    duplicates = this.duplicates.filter(d => d.duplicateKind === 'v');
                duplicates.sort((a, b) => {
                    if (a.duplicateKind === DocumentKinds.VERIFIED)
                        return -1;
                    if (b.duplicateKind === DocumentKinds.VERIFIED)
                        return 1;
                    return 0;
                });
                return _.uniqBy(duplicates, 'duplicate');
            }
        };

        const membershipPrototype = {
            getDisplayName: function () {
                if (_.isFunction(this.user.getDisplayName))
                    return this.user.getDisplayName();
                else
                    return '';
            }
        };

        const collaborationPrototype = {
            getDisplayName: function () {
                if (_.isFunction(this.group.getDisplayName))
                    return this.group.getDisplayName();
                else
                    return '';
            }
        };

        const authorshipPrototype = {};

        const institutePrototype = {
            getDisplayName: function () {
                return this.name;
            }
        };

        const tagLabelPrototype = {
            getDisplayName: function () {
                return this.value;
            }
        };

        function initializeAffiliations(document) {
            _.forEach(document.authorships, a => {
                if (a.affiliations)
                    return;
                const authorships = _.filter(document.affiliations, {authorship: a.id});
                const institutes = _.filter(document.institutes, i => authorships.some(a => a.institute === i.id));
                a.affiliations = institutes;
            });
        }

        function applyToAll(fun) {
            return function (elems) {
                _.forEach(elems, fun);
                return elems;
            };
        }

        function toUserModel(user) {
            _.defaultsDeep(user, userPrototype);
            service.toDocumentsCollection(user.documents);
            service.toGroupsCollection(user.memberships);
            service.toGroupsCollection(user.administratedGroups);
            service.toCollaborationsCollection(user.collaborations);
            return user;
        }

        function toGroupModel(group) {
            _.defaultsDeep(group, groupPrototype);
            service.toUsersCollection(group.members);
            service.toUsersCollection(group.administrators);
            service.toUsersCollection(group.pis);
            service.toUsersCollection(group.allMembers);
            service.toDocumentsCollection(group.documents);
            service.toGroupsCollection(group.childGroups);
            return group;
        }

        function toDocumentModel(document) {
            initializeAffiliations(document);
            _.defaultsDeep(document, documentPrototype);
            checkDuplicates(document);
            service.toUsersCollection(document.authors);
            service.toTagLabelsCollection(document.tagLabels);
            service.toTagLabelsCollection(document.groupTagLabels);
            service.toAuthorshipsCollection(document.authorships);
            return document;
        }

        function checkDuplicates(document) {
            document.isComparable = (
                    document.isDraft() &&
                    document.duplicates.length
                ) ||
                (
                    !document.isDraft() &&
                    document.duplicates &&
                    document.duplicates.length &&
                    document.duplicates.some(d => d.duplicateKind === 'v')
                );
        }

        function toMembershipModel(membership) {
            _.defaultsDeep(membership, membershipPrototype);
            service.toUserModel(membership.user);
            return membership;
        }

        function toCollaborationModel(collaboration) {
            _.defaultsDeep(collaboration, collaborationPrototype);
            service.toGroupModel(collaboration.group);
            return collaboration;
        }

        function toAuthorshipModel(authorship) {
            _.defaultsDeep(authorship, authorshipPrototype);
            service.toInstitutesCollection(authorship.affiliations);
            return authorship;
        }

        function toInstituteModel(institute) {
            _.defaultsDeep(institute, institutePrototype);
            return institute;
        }

        function toTagLabelModel(tagLabel) {
            _.defaultsDeep(tagLabel, tagLabelPrototype);
            return tagLabel;
        }

        return service;
    }
})();
<commit_msg>Fixed bug on hasValidScopusId<commit_after>(function () {
    "use strict";

    angular.module("services")
        .factory("Prototyper", Prototyper);

    Prototyper.$inject = [
        'userConstants',
        'DocumentLabels',
        'DocumentKinds',
        'documentFieldsRules',
        'documentOrigins'
    ];

    function Prototyper(userConstants, DocumentLabels, DocumentKinds, documentFieldsRules, documentOrigins) {
        const service = {
            toUserModel: toUserModel,
            toUsersCollection: applyToAll(toUserModel),
            toGroupModel: toGroupModel,
            toGroupsCollection: applyToAll(toGroupModel),
            toDocumentModel: toDocumentModel,
            toDocumentsCollection: applyToAll(toDocumentModel),
            toCollaborationModel: toCollaborationModel,
            toCollaborationsCollection: applyToAll(toCollaborationModel),
            toMembershipModel: toMembershipModel,
            toMembershipsCollection: applyToAll(toMembershipModel),
            toAuthorshipModel: toAuthorshipModel,
            toAuthorshipsCollection: applyToAll(toAuthorshipModel),
            toInstituteModel: toInstituteModel,
            toInstitutesCollection: applyToAll(toInstituteModel),
            toTagLabelModel: toTagLabelModel,
            toTagLabelsCollection: applyToAll(toTagLabelModel),
        };
        const userPrototype = {
            getAliases: function () {
                return this.aliases.map(a => a.str);
            },
            getDisplayName: function () {
                var name = this.name ? this.name : "";
                var surname = this.surname ? this.surname : "";
                var fullName = _.trim(name + " " + surname);
                return fullName;
            },
            getType: function () {
                return 'user';
            },
            getCollaborationGroups: function () {
                return _.map(this.collaborations, 'group');
            },
            isAdmin: function () {
                return this.role === userConstants.role.ADMINISTRATOR;
            },
            admins: function (group) {
                var administeredGroupsId = _.map(this.administratedGroups, 'id');
                return _.includes(administeredGroupsId, group.id);
            },
            getExternalConnectors: function () {
                var connectors = [];
                var publicationsConnector = {value: 'publications', label: 'Publications', enabled: true};
                var scopusConnector = {value: 'scopus', label: 'Scopus', enabled: !!this.scopusId};
                connectors.push(publicationsConnector);
                connectors.push(scopusConnector);
                return connectors;
            },
            getNewDocument: function (documentTypeObj) {
                var documentData = {
                    draftCreator: this.id,
                    kind: DocumentKinds.DRAFT,
                    type: documentTypeObj.key,
                    sourceType: documentTypeObj.defaultSource,
                    origin: documentOrigins.SCIENTILLA
                };
                return documentPrototype.create(documentData);
            },
            getProfileUrl: function () {
                return '/users/' + this.id;
            },
            getTagsByDocument: function (document) {
                if (!document.tagLabels || !document.userTags)
                    return [];

                var filteredUserTags = document.userTags.filter(function (ut) {
                    return ut.researchEntity === this.id;
                }.bind(this));

                return document.tagLabels.filter(function (tagLabel) {
                    return !!filteredUserTags.find(function (ut) {
                        return tagLabel.id === ut.tagLabel;
                    });
                });
            },
            isInternal: function () {
                return _.endsWith(this.username, '@iit.it');
            }
        };
        const groupPrototype = {
            getDisplayName: function () {
                return this.name;
            },
            getType: function () {
                return 'group';
            },
            getExternalConnectors: function () {
                var connectors = [];
                var publicationsConnector = {
                    value: 'publications',
                    label: 'Publications',
                    enabled: !!this.publicationsAcronym
                };
                var scopusConnector = {value: 'scopus', label: 'Scopus', enabled: !!this.scopusId};
                connectors.push(publicationsConnector);
                connectors.push(scopusConnector);
                return connectors;
            },
            getNewDocument: function (documentTypeObj) {
                var documentData = {
                    draftCreator: this.id,
                    kind: DocumentKinds.DRAFT,
                    type: documentTypeObj.key,
                    sourceType: documentTypeObj.defaultSource,
                    origin: documentOrigins.SCIENTILLA
                };
                return documentPrototype.create(documentData);
            },
            getProfileUrl: function () {
                return '/groups/' + this.id;
            },
            getTagsByDocument: function (document) {
                if (!document.groupTagLabels || !document.groupTags)
                    return [];

                var filteredGroupTags = document.groupTags.filter(function (gt) {
                    return gt.researchEntity === this.id;
                }.bind(this));

                return document.groupTagLabels.filter(function (tagLabel) {
                    return !!filteredGroupTags.find(function (gt) {
                        return tagLabel.id === gt.tagLabel;
                    });
                });
            },
            getActiveMembers: function () {
                return this.members.filter(u => {
                    const userMembersihp = this.memberships.find(m => m.user === u.id);
                    return userMembersihp && userMembersihp.synchronized && userMembersihp.active;
                });
            },
            getCollaborators: function () {
                return this.members.filter(u => {
                    const userMembersihp = this.memberships.find(m => m.user === u.id);
                    return userMembersihp && !userMembersihp.synchronized && userMembersihp.active;
                });
            },
            getFormerMembers: function () {
                return this.members.filter(u => {
                    const userMembersihp = this.memberships.find(m => m.user === u.id);
                    return userMembersihp && !userMembersihp.active;
                });
            },
            getResearchDomain: function () {
                const researchDomain = this.attributes
                    .filter(a => a.category === 'research_domain')
                    .reduce((res, a) => {
                        const ga = this.groupAttributes.find(ga => ga.attribute === a.id);
                        if (ga.extra.type === 'main') return a;
                        return res;
                    }, null);

                if (_.isObject(researchDomain))
                    return researchDomain.value;
            },
            getInteractions: function () {
                const interactionsGroupAttributes = this.groupAttributes.filter(ga => ga.extra.type === 'interaction');
                const interactions = this.attributes
                    .filter(a => a.category === 'research_domain')
                    .reduce((res, a) => {
                        const groupAttribute = interactionsGroupAttributes.find(ga => ga.attribute === a.id);
                        if (groupAttribute)
                            res.push(a);
                        return res;
                    }, []);

                return interactions.map(i => i.value);
            }
        };

        const documentPrototype = {
            UNKNOWN_DOCUMENT: 0,
            USER_DOCUMENT: 1,
            GROUP_DOCUMENT: 2,
            labels: [],
            fields: [
                'authorsStr',
                'title',
                'year',
                'itSource',
                'source',
                'issue',
                'volume',
                'pages',
                'articleNumber',
                'doi',
                'abstract',
                'type',
                'sourceType',
                'scopusId',
                'wosId',
                'authorships',
                'affiliations',
                'institutes',
                'synchronized',
                'origin'
            ],
            create: function (documentData) {
                var fields = _.union(['kind', 'draftCreator', 'draftGroupCreator'], documentPrototype.fields);
                var document = _.pick(documentData, fields);
                _.extend(document, documentPrototype);
                return document;
            },
            isValid: function () {
                const requiredFields = [
                    'authorsStr',
                    'title',
                    'year',
                    'type',
                    'sourceType'
                ];
                // TODO: refactor, invited_talk should be read by a service;
                const invitedTalkType = 'invited_talk';
                if (this.type === invitedTalkType)
                    requiredFields.push('itSource');
                else
                    requiredFields.push('source');

                return _.every(requiredFields, v => this[v]) &&
                    _.every(documentFieldsRules, (rule, k) => {
                        if (!this[k]) return rule.allowNull;
                        return rule.regex.test(this[k]);
                    });
            },
            getAllCoauthors: function () {
                return this.authors;
            },
            getType: function () {
                if (!!this.owner)
                    return this.USER_DOCUMENT;
                else if (!!this.groupOwner)
                    return this.GROUP_DOCUMENT;
                else
                    return this.UNKNOWN_DOCUMENT;
            },
            getAuthors: function () {
                if (!this.authorsStr)
                    return [];

                return this.authorsStr.replace(/\s+et all\s*$/i, '').split(/,\s*/).map(_.trim);
            },
            getUcAuthors: function () {
                var authors = this.getAuthors();
                var ucAuthors = _.map(authors, function (a) {
                    return a.toUpperCase();
                });
                return ucAuthors;
            },
            getDisplayName: function () {
                return this.getDisplayName();
            },
            getUserIndex: function (user) {
                const authors = this.getAuthors().map(a => a.toLocaleLowerCase());
                const aliases = user.getAliases().map(a => a.toLocaleLowerCase());
                return _.findIndex(authors, a => aliases.includes(a));
            },
            copyDocument: function (document, creator) {
                var excludedFields = ['kind', 'draftCreator', 'draftGroupCreator'];

                var documentTypeObj = {
                    key: document.type,
                    defaultSource: document.sourceType
                };

                var newDoc = creator.getNewDocument(documentTypeObj);

                _.forEach(documentPrototype.fields, function (key) {
                    if (_.includes(excludedFields, key))
                        return;

                    newDoc[key] = document[key];
                });

                return newDoc;
            },
            addLabel: function (label) {
                if (!this.hasLabel(label))
                    this.labels.push(label);
            },
            removeLabel: function (label) {
                _.remove(this.labels, function (t) {
                    return t === label;
                });
            },
            hasLabel: function (label) {
                return this.labels.includes(label);
            },
            isDiscarded: function () {
                return this.hasLabel(DocumentLabels.DISCARDED);
            },
            isUnverifying: function () {
                return this.hasLabel(DocumentLabels.UVERIFYING);
            },
            getInstituteIdentifier: function (instituteIndex) {
                const base26Chars = "0123456789abcdefghijklmnopqrstuvwxyz".split("");
                const alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
                const alphabetMapper = {};
                alphabet.forEach((v, i) => alphabetMapper[base26Chars[i]] = v);
                const base26Value = instituteIndex.toString(alphabet.length).split('');
                if (base26Value.length > 1)
                    base26Value[0] = base26Chars[base26Chars.indexOf(base26Value[0]) - 1];

                return base26Value.map(c => alphabetMapper[c]).join('');
            },
            isSuggested: function (researchEntity) {
                const f = researchEntity.getType() === 'user' ? 'authors' : 'groups';
                return (this.kind === DocumentKinds.VERIFIED || this.isExternal()) && !this[f].some(re => re.id === researchEntity.id);
            },
            isDraft: function () {
                return this.kind === DocumentKinds.DRAFT;
            },
            isVerified: function (researchEntity) {
                const f = researchEntity.getType() === 'user' ? 'authors' : 'groups';
                return this[f].some(re => re.id === researchEntity.id);
            },
            isExternal: function () {
                return this.kind === DocumentKinds.EXTERNAL;
            },
            hasValidScopusId: function () {
                if (!this.scopusDocumentMetadata || !this.scopusDocumentMetadata[0]) return true;
                return !this.scopusDocumentMetadata[0].data.scopusIdInvalid;
            },
            getStringKind(researchEntity) {
                if (this.isSuggested(researchEntity))
                    return 'Suggested';
                if (this.isDraft())
                    return 'Draft';
                if (this.isVerified(researchEntity))
                    return 'Verified';
            },
            getComparisonDuplicate() {
                return this.getComparisonDuplicates()[0];
            },
            getComparisonDuplicates() {
                let duplicates;
                if (this.isDraft())
                    duplicates = this.duplicates;
                else
                    duplicates = this.duplicates.filter(d => d.duplicateKind === 'v');
                duplicates.sort((a, b) => {
                    if (a.duplicateKind === DocumentKinds.VERIFIED)
                        return -1;
                    if (b.duplicateKind === DocumentKinds.VERIFIED)
                        return 1;
                    return 0;
                });
                return _.uniqBy(duplicates, 'duplicate');
            }
        };

        const membershipPrototype = {
            getDisplayName: function () {
                if (_.isFunction(this.user.getDisplayName))
                    return this.user.getDisplayName();
                else
                    return '';
            }
        };

        const collaborationPrototype = {
            getDisplayName: function () {
                if (_.isFunction(this.group.getDisplayName))
                    return this.group.getDisplayName();
                else
                    return '';
            }
        };

        const authorshipPrototype = {};

        const institutePrototype = {
            getDisplayName: function () {
                return this.name;
            }
        };

        const tagLabelPrototype = {
            getDisplayName: function () {
                return this.value;
            }
        };

        function initializeAffiliations(document) {
            _.forEach(document.authorships, a => {
                if (a.affiliations)
                    return;
                const authorships = _.filter(document.affiliations, {authorship: a.id});
                const institutes = _.filter(document.institutes, i => authorships.some(a => a.institute === i.id));
                a.affiliations = institutes;
            });
        }

        function applyToAll(fun) {
            return function (elems) {
                _.forEach(elems, fun);
                return elems;
            };
        }

        function toUserModel(user) {
            _.defaultsDeep(user, userPrototype);
            service.toDocumentsCollection(user.documents);
            service.toGroupsCollection(user.memberships);
            service.toGroupsCollection(user.administratedGroups);
            service.toCollaborationsCollection(user.collaborations);
            return user;
        }

        function toGroupModel(group) {
            _.defaultsDeep(group, groupPrototype);
            service.toUsersCollection(group.members);
            service.toUsersCollection(group.administrators);
            service.toUsersCollection(group.pis);
            service.toUsersCollection(group.allMembers);
            service.toDocumentsCollection(group.documents);
            service.toGroupsCollection(group.childGroups);
            return group;
        }

        function toDocumentModel(document) {
            initializeAffiliations(document);
            _.defaultsDeep(document, documentPrototype);
            checkDuplicates(document);
            service.toUsersCollection(document.authors);
            service.toTagLabelsCollection(document.tagLabels);
            service.toTagLabelsCollection(document.groupTagLabels);
            service.toAuthorshipsCollection(document.authorships);
            return document;
        }

        function checkDuplicates(document) {
            document.isComparable = (
                    document.isDraft() &&
                    document.duplicates.length
                ) ||
                (
                    !document.isDraft() &&
                    document.duplicates &&
                    document.duplicates.length &&
                    document.duplicates.some(d => d.duplicateKind === 'v')
                );
        }

        function toMembershipModel(membership) {
            _.defaultsDeep(membership, membershipPrototype);
            service.toUserModel(membership.user);
            return membership;
        }

        function toCollaborationModel(collaboration) {
            _.defaultsDeep(collaboration, collaborationPrototype);
            service.toGroupModel(collaboration.group);
            return collaboration;
        }

        function toAuthorshipModel(authorship) {
            _.defaultsDeep(authorship, authorshipPrototype);
            service.toInstitutesCollection(authorship.affiliations);
            return authorship;
        }

        function toInstituteModel(institute) {
            _.defaultsDeep(institute, institutePrototype);
            return institute;
        }

        function toTagLabelModel(tagLabel) {
            _.defaultsDeep(tagLabel, tagLabelPrototype);
            return tagLabel;
        }

        return service;
    }
})();
<|endoftext|>


<commit_before>import { WitDriver } from 'calamars';
const { getEntity, getEntityValue, getEntityMeta } = WitDriver;
import router from '../../../src/router';
import { replies } from '../../../replies';
import { version } from '../../../package.json';
import { createStore } from '../../../src/store';

const options = {
    id: process.env.WIT_APP_ID,
    serverToken: process.env.WIT_SERVER_TOKEN
};

const wit = new WitDriver(options);
const store = createStore();

const getOutcome = async q => {
    const witResult = await wit.query(q);
    return witResult.outcomes[0];
};

// # Commands

const startCommand = async t => {
    const outcome = await getOutcome('/start');
    t.is(router(outcome), replies.start);
};

const versionCommand = async t => {
    const outcome = await getOutcome('/version');
    t.is(router(outcome), replies.version(version));
};

const helpCommand = async t => {
    const outcome = await getOutcome('/help');
    t.is(router(outcome), replies.help);
};

const restartCommand = async t => {
    const outcome = await getOutcome('/restart');
    t.is(router(outcome, { store }), replies.restart);
};

// # Interactions

const greeting = async t => {
    const outcome1 = await getOutcome('Olá');
    const outcome2 = await getOutcome('Oi');
    const outcome3 = await getOutcome('Bom dia bot');
    t.is(router(outcome1), replies.greeting.noUsername);
    t.is(router(outcome2), replies.greeting.noUsername);
    t.is(router(outcome3), replies.greeting.noUsername);
};

const greetingWithUsername = async t => {
    const outcome = await getOutcome('Oi');
    const from = { username: 'George' };
    t.is(router(outcome, { from }), replies.greeting.username(from.username));
};

const goodbye = async t => {
    const outcome1 = await getOutcome('Obrigado.');
    const outcome2 = await getOutcome('Tchau.');
    const outcome3 = await getOutcome('Valeu bot!');
    t.is(router(outcome1), replies.close);
    t.is(router(outcome2), replies.close);
    t.is(router(outcome3), replies.close);
};

// # Trips

const tripIntent = async t => {
    const expressions = [
        'Quero viajar.',
        'Passagem',
        'Preciso viajar',
        'Horários de ônibus',
        'Você sabe horarios de ônibus?',
        'Viagem'
    ];
    const outcomes = await Promise.all(expressions.map(
            expression => getOutcome(expression)
    ));
    return outcomes.map((outcome, i) => t.is(
        getEntityValue(outcome, 'trip'), 'info', `Expression: ${expressions[i]}`
    ));
};

const tripIntentDestination = async t => {
    const expressions = [
        'Quero viajar para santos.',
        'Passagem pra Atiabia tem?',
        'Preciso viajar com destino a marília, sp',
        'Horários de ônibus para ubatuba',
        'Partiu sampa?',
        'bora pro rio',
        'para jahu',
        'vamos para guarulhos'
    ];
    const outcomes = await Promise.all(expressions.map(
            expression => getOutcome(expression)
    ));
    return outcomes.forEach((outcome, i) => {
        const message = `Expression: ${expressions[i]}`;
        t.is(getEntityValue(outcome, 'trip'), 'info', message);
        t.truthy(getEntityValue(outcome, 'destination'), message);
        t.falsy(getEntityValue(outcome, 'origin'), message);
        t.falsy(getEntityValue(outcome, 'places'), message);
    });
};

const tripIntentOrigin = async t => {
    const expressions = [
        'de osasco',
        'Estou em Itatiba, quero uma passagem',
        'Horários de ônibus a partir de são carlos',
        'Origem sampa',
        'partindo de ribeirao preto, o que tem?',
        'passagens do rio',
        'Preciso viajar saindo de rio de janeiro, rj',
        'Quero viajar saindo de santos.'
    ];
    const outcomes = await Promise.all(expressions.map(
            expression => getOutcome(expression)
    ));
    return outcomes.forEach((outcome, i) => {
        const message = `Expression: ${expressions[i]}`;
        t.is(getEntityValue(outcome, 'trip'), 'info', message);
        t.truthy(getEntityValue(outcome, 'origin'), message);
        t.falsy(getEntityValue(outcome, 'destination'), message);
        t.falsy(getEntityValue(outcome, 'places'), message);
    });
};

const tripOriginDestination = async t => {
    const outcome1 = await getOutcome('horários de São Paulo para Rio de Janeiro');
    t.is(getEntityMeta(
        getEntity(outcome1, 'origin')).slugs[0],
        'sao-paulo-sp-todos');
    t.is(getEntityMeta(
        getEntity(outcome1, 'destination')).slugs[0],
        'rio-de-janeiro-rj-todos');
};

export {
    startCommand,
    versionCommand,
    helpCommand,
    restartCommand,
    greeting,
    greetingWithUsername,
    goodbye,
    tripIntent,
    tripIntentDestination,
    tripIntentOrigin,
    tripOriginDestination
};
<commit_msg>minor, sort test statements<commit_after>import { WitDriver } from 'calamars';
const { getEntity, getEntityValue, getEntityMeta } = WitDriver;
import router from '../../../src/router';
import { replies } from '../../../replies';
import { version } from '../../../package.json';
import { createStore } from '../../../src/store';

const options = {
    id: process.env.WIT_APP_ID,
    serverToken: process.env.WIT_SERVER_TOKEN
};

const wit = new WitDriver(options);
const store = createStore();

const getOutcome = async q => {
    const witResult = await wit.query(q);
    return witResult.outcomes[0];
};

// # Commands

const startCommand = async t => {
    const outcome = await getOutcome('/start');
    t.is(router(outcome), replies.start);
};

const versionCommand = async t => {
    const outcome = await getOutcome('/version');
    t.is(router(outcome), replies.version(version));
};

const helpCommand = async t => {
    const outcome = await getOutcome('/help');
    t.is(router(outcome), replies.help);
};

const restartCommand = async t => {
    const outcome = await getOutcome('/restart');
    t.is(router(outcome, { store }), replies.restart);
};

// # Interactions

const greeting = async t => {
    const outcome1 = await getOutcome('Olá');
    const outcome2 = await getOutcome('Oi');
    const outcome3 = await getOutcome('Bom dia bot');
    t.is(router(outcome1), replies.greeting.noUsername);
    t.is(router(outcome2), replies.greeting.noUsername);
    t.is(router(outcome3), replies.greeting.noUsername);
};

const greetingWithUsername = async t => {
    const outcome = await getOutcome('Oi');
    const from = { username: 'George' };
    t.is(router(outcome, { from }), replies.greeting.username(from.username));
};

const goodbye = async t => {
    const outcome1 = await getOutcome('Obrigado.');
    const outcome2 = await getOutcome('Tchau.');
    const outcome3 = await getOutcome('Valeu bot!');
    t.is(router(outcome1), replies.close);
    t.is(router(outcome2), replies.close);
    t.is(router(outcome3), replies.close);
};

// # Trips

const tripIntent = async t => {
    const expressions = [
        'Horários de ônibus',
        'Passagem',
        'Preciso viajar',
        'Quero viajar.',
        'Viagem',
        'Você sabe horarios de ônibus?'
    ];
    const outcomes = await Promise.all(expressions.map(
            expression => getOutcome(expression)
    ));
    return outcomes.map((outcome, i) => t.is(
        getEntityValue(outcome, 'trip'), 'info', `Expression: ${expressions[i]}`
    ));
};

const tripIntentDestination = async t => {
    const expressions = [
        'bora pro rio',
        'Horários de ônibus para ubatuba',
        'para jahu',
        'Partiu sampa?',
        'Passagem pra Atiabia tem?',
        'Preciso viajar com destino a marília, sp',
        'Quero viajar para santos.',
        'vamos para guarulhos'
    ];
    const outcomes = await Promise.all(expressions.map(
            expression => getOutcome(expression)
    ));
    return outcomes.forEach((outcome, i) => {
        const message = `Expression: ${expressions[i]}`;
        t.is(getEntityValue(outcome, 'trip'), 'info', message);
        t.truthy(getEntityValue(outcome, 'destination'), message);
        t.falsy(getEntityValue(outcome, 'origin'), message);
        t.falsy(getEntityValue(outcome, 'places'), message);
    });
};

const tripIntentOrigin = async t => {
    const expressions = [
        'de osasco',
        'Estou em Itatiba, quero uma passagem',
        'Horários de ônibus a partir de são carlos',
        'Origem sampa',
        'partindo de ribeirao preto, o que tem?',
        'passagens do rio',
        'Preciso viajar saindo de rio de janeiro, rj',
        'Quero viajar saindo de santos.'
    ];
    const outcomes = await Promise.all(expressions.map(
            expression => getOutcome(expression)
    ));
    return outcomes.forEach((outcome, i) => {
        const message = `Expression: ${expressions[i]}`;
        t.is(getEntityValue(outcome, 'trip'), 'info', message);
        t.truthy(getEntityValue(outcome, 'origin'), message);
        t.falsy(getEntityValue(outcome, 'destination'), message);
        t.falsy(getEntityValue(outcome, 'places'), message);
    });
};

const tripOriginDestination = async t => {
    const outcome1 = await getOutcome('horários de São Paulo para Rio de Janeiro');
    t.is(getEntityMeta(
        getEntity(outcome1, 'origin')).slugs[0],
        'sao-paulo-sp-todos');
    t.is(getEntityMeta(
        getEntity(outcome1, 'destination')).slugs[0],
        'rio-de-janeiro-rj-todos');
};

export {
    startCommand,
    versionCommand,
    helpCommand,
    restartCommand,
    greeting,
    greetingWithUsername,
    goodbye,
    tripIntent,
    tripIntentDestination,
    tripIntentOrigin,
    tripOriginDestination
};
<|endoftext|>


<commit_before>/* global Plotly*/
/* global  document */
/* global _*/
'use strict';

angular.module('metadatamanagementApp').directive('diagram',
  function($window, $timeout, $filter) {
    var link = function(scope, element) {
      scope.isNotLoaded = true;
      var data = [{
        marker: {
          color: '#006AB2'
        }
      }];

      var drawDiagram = function() {
        $timeout(function() {
          var layout = {
            margin: {
              l: 35,
              r: 35,
              t: 15,
              b: 30
            },
            width: document.getElementById('diagramContainer').offsetWidth -
              10
          };
          if (scope.language === 'de') {
            layout.separators = ',.';
          }
          scope.isNotLoaded = false;
          if (angular.element('diagram').length > 0) {
            Plotly.newPlot('diagram', data, _.cloneDeep(layout), {
              showLink: false,
              displayModeBar: true,
              modeBarButtonsToRemove: ['hoverClosestCartesian',
                'hoverCompareCartesian'
              ]
            });
          }
        }, 1000);
      };
      switch (scope.type) {
        case 'verhältnis':
        case 'ratio':
          if (scope.distribution.histogram) {
            var size = (scope.distribution.histogram.end -
              scope.distribution.histogram.start) /
              scope.distribution.histogram.numberOfBins;
            data[0].x = [];
            data[0].type = 'histogram';
            data[0].autobinx = false;
            data[0].xbins = {
              start: scope.distribution.histogram.start,
              end: scope.distribution.histogram.end,
              size: size
            };
            data[0].hoverinfo = 'text+y';
            data[0].text = [];
            for (var i = 0; i < scope.distribution.histogram.numberOfBins;
              i++) {
              data[0].text.push('[' + $filter('number')(scope.distribution
                .histogram.start + size * i, 2) + '; ' +
                $filter('number')(scope.distribution.histogram.start +
                  size * (i + 1), 2) + ')');
            }
            if (scope.distribution.validResponses) {
              for (var j = 0; j < scope.distribution.validResponses.length;
                j++) {
                for (var k = 0; k < scope.distribution.validResponses[j]
                  .absoluteFrequency; k++) {
                  data[0].x.push(scope.distribution.validResponses[j].value);
                }
              }
            }
          }
        break;
        default:
          data[0].x = [];
          data[0].text = [];
          data[0].y = [];
          data[0].type = 'bar';
          if (scope.distribution.validResponses) {
            scope.distribution.validResponses.forEach(function(obj) {
              var filteredText = $filter('variableDataType')(obj.value,
                scope.datatype);
              data[0].x.push(filteredText);
              try {
                data[0].text.push(obj.label[scope.language]);
              } catch (e) {
                data[0].text.push(filteredText);
              }
              data[0].y.push(obj.absoluteFrequency);
            });
          }
        break;
      }
      angular.element($window).on('resize', function() {
        $timeout(function() {
          var update = {
            width: document.getElementById('diagramContainer').offsetWidth
          };
          Plotly.relayout('diagram', update);
        }, 1000);
      });
      element.on('$destroy', function() {
        angular.element($window).off('resize');
      });
      drawDiagram();
    };
    return {
      restrict: 'E',
      templateUrl: 'scripts/variablemanagement/directives/diagram.html.tmpl',
      link: link,
      scope: {
        distribution: '=',
        language: '=',
        type: '=',
        datatype: '='
      }
    };
  });
<commit_msg>#1121 fixed plotly represention of numric values<commit_after>/* global Plotly*/
/* global  document */
/* global _*/
'use strict';

angular.module('metadatamanagementApp').directive('diagram',
  function($window, $timeout, $filter) {
    var link = function(scope, element) {
      scope.isNotLoaded = true;
      var data = [{
        marker: {
          color: '#006AB2'
        }
      }];

      var drawDiagram = function() {
        $timeout(function() {
          var layout = {
            margin: {
              l: 35,
              r: 35,
              t: 15,
              b: 30
            },
            width: document.getElementById('diagramContainer').offsetWidth -
              10
          };
          if (scope.language === 'de') {
            layout.separators = ',.';
          }
          scope.isNotLoaded = false;
          if (angular.element('diagram').length > 0) {
            Plotly.newPlot('diagram', data, _.cloneDeep(layout), {
              showLink: false,
              displayModeBar: true,
              modeBarButtonsToRemove: ['hoverClosestCartesian',
                'hoverCompareCartesian'
              ]
            });
          }
        }, 1000);
      };
      switch (scope.type) {
        case 'verhältnis':
        case 'ratio':
          if (scope.distribution.histogram) {
            var size = (scope.distribution.histogram.end -
              scope.distribution.histogram.start) /
              scope.distribution.histogram.numberOfBins;
            data[0].x = [];
            data[0].type = 'histogram';
            data[0].autobinx = false;
            data[0].xbins = {
              start: scope.distribution.histogram.start,
              end: scope.distribution.histogram.end,
              size: size
            };
            data[0].hoverinfo = 'text+y';
            data[0].text = [];
            for (var i = 0; i < scope.distribution.histogram.numberOfBins;
              i++) {
              data[0].text.push('[' + $filter('number')(scope.distribution
                .histogram.start + size * i, 2) + '; ' +
                $filter('number')(scope.distribution.histogram.start +
                  size * (i + 1), 2) + ')');
            }
            if (scope.distribution.validResponses) {
              for (var j = 0; j < scope.distribution.validResponses.length;
                j++) {
                for (var k = 0; k < scope.distribution.validResponses[j]
                  .absoluteFrequency; k++) {
                  data[0].x.push(scope.distribution.validResponses[j].value);
                }
              }
            }
          }
        break;
        default:
          data[0].x = [];
          data[0].text = [];
          data[0].y = [];
          data[0].type = 'bar';
          if (scope.distribution.validResponses) {
            scope.distribution.validResponses.forEach(function(obj) {
              var filteredText = $filter('variableDataType')(obj.value,
                scope.datatype);
              if (scope.datatype !== 'numeric') {
                data[0].x.push(filteredText);
              } else {
                data[0].x.push(obj.value);
              }
              try {
                data[0].text.push(obj.label[scope.language]);
              } catch (e) {
                data[0].text.push(filteredText);
              }
              data[0].y.push(obj.absoluteFrequency);
            });
          }
        break;
      }
      angular.element($window).on('resize', function() {
        $timeout(function() {
          var update = {
            width: document.getElementById('diagramContainer').offsetWidth
          };
          Plotly.relayout('diagram', update);
        }, 1000);
      });
      element.on('$destroy', function() {
        angular.element($window).off('resize');
      });
      drawDiagram();
    };
    return {
      restrict: 'E',
      templateUrl: 'scripts/variablemanagement/directives/diagram.html.tmpl',
      link: link,
      scope: {
        distribution: '=',
        language: '=',
        type: '=',
        datatype: '='
      }
    };
  });
<|endoftext|>


<commit_before>
var Event = require('./events.model.js');
var Bluebird = require('bluebird');
var request = Bluebird.promisify(require('request'));
var utils = require('./utils.js');
var commentController = require('../comments/comments.controller.js');

/********************* Module.exports *************************/

module.exports = {
  getAll: getAll,
  getOne: getOne,
  addOne: addOne,
  getLocal: getLocal,
  fetchBatchDataFromKimonoAPI: fetchBatchDataFromKimonoAPI,
  fetchBatchDataFromEventbriteAPI: fetchBatchDataFromEventbriteAPI,
  getCoordsFromAddress: getCoordsFromAddress,
  getAddressFromCoords: getAddressFromCoords,
  addManySpoofs: addManySpoofs
};

/******************** Generic DB interactions **********************/

function getAll(req, res) {
  Event.fetchAll()
  .then(function (collection) {
    utils.sendResponse(utils.formatAndTrimEventRecords(collection),res);
  });
}

function getOne(req, res) {
  Event.where({id:req.params.id}).fetch({
      withRelated: ['user', 'photos', 'comments']
    }).then(function (record) {
      if(record){
        utils.sendResponse(utils.formatAndTrimEventRecords([record])[0],res);
      } else {
        res.status(404).end('No event with that id.');
      }

  });
}

function addOne(req, res) {
  request(
    { method: 'POST',
      uri: process.env.PARSER_SERVER_URL + 'api/events/',
      form: req.body,
    })
  .then(function (response) {
    if(response[0].statusCode == 201){
      console.log('parser reports event saved.');
      res.status(201).end('event added.')
    } else {
      console.log('error: '+ response[0].statusCode);
    }
  });
}

function addManySpoofs(req,res){
  res.status(200).end();
  var numSpoofs = req.query.number;
  for(var i = 0; i < numSpoofs; i++){
    var newEvent = new Event({
      title: 'Spoof event #' + i,
      startTime: Date.now(),
      endTime: Date.now()+20000000,
      lat: utils.generateRandomLat(),
      lng: utils.generateRandomLong(),
      user_id: 1,
      info: 'info for spoof event #' + i,
      category: 'Party',
      streetAddress1: '1 Embarcadero Blvd',
      streetAddress2: 'Suite 101',
      city: 'San Francisco',
      state: 'CA',
      zipCode: '94102',
      price: Math.random()*100
    })
    .save();
  }
}

function getLocal(req, res) {

    //two dates are used to get modified
    var date1 = new Date();
    var date2 = new Date();

    //currentTime is used to keep track of current time
    var currentTime = Date.now();

    //beginningDate to current date at 3 a.m.
    var beginningDate = date1.setHours(3, 0, 0, 0);

    //endingDate to next day at 3 a.m.
    date2.setDate(date1.getDate() + 1);
    var endingDate = date2.setHours(3, 0, 0, 0);

  Event.query(function(qb){

    //Narrows down events based on specified location
    qb.whereBetween('lat', [Math.min(req.query.lat1,req.query.lat2),Math.max(req.query.lat1,req.query.lat2)]);
    qb.whereBetween('lng', [Math.min(req.query.lng1,req.query.lng2),Math.max(req.query.lng1,req.query.lng2)]);

    //Narrows down events within specified ISO8601 time
    qb.where('startTime', '<', endingDate)
      .andWhere('endTime', '>', beginningDate)
      .andWhere('endTime', '>', currentTime)
      .orWhere('endTime', null);
  })
  .fetchAll()
  .then(function (collection) {
    utils.sendResponse(utils.formatAndTrimEventRecords(collection),res);
  });
}

/************** Geocoding ******************/

//returns a promise of an http response.  parse the response like this:
//var coords = JSON.parse(res[0].body);
//coords will be a lat, lng tuple like [44.5, -122.67]
function getCoordsFromAddress(address) {
  return request( process.env.GEOCODING_SERVER_URL + 'geo/geocode?address=' + address);
}

//returns a promise of an http response.  parse the response like this:
//var address = JSON.parse(res[0].body);
//'address' will be an object with fields like addressLine1, city, state, zipCode, etc.
function getAddressFromCoords(coords) {
  return request( process.env.GEOCODING_SERVER_URL + 'geo/reverseGeocode?lat=' + coords[0] + '&lng=' + coords[1]);
}

/************** Kimono API functions ******************/

function fetchBatchDataFromKimonoAPI(req, res) {
  request( process.env.PARSER_SERVER_URL + 'api/events/kimono')
  .then(function(response){
    if(response[0].statusCode == 201){
      var msg = 'parser acknowledges request to run Kimono fetching';
      console.log(msg);
      res.status(201).end(msg);
    } else {
      var errorMsg = 'parser reports error regarding Kimono fetch request';
      console.log(errorMsg);
      res.status(400).end(errorMsg);
    }
  });
}

/************** Eventbrite API functions ******************/

function fetchBatchDataFromEventbriteAPI(req, res){
  request( process.env.PARSER_SERVER_URL + 'api/events/eventbrite')
  .then(function(response){
    if(response[0].statusCode == 201){
      var msg = 'parser acknowledges request to run Eventbrite fetching';
      console.log(msg);
      res.status(201).end(msg);
    } else {
      var errorMsg = 'parser reports error regarding Eventbrite fetch request';
      console.log(errorMsg);
      res.status(400).end(errorMsg);
    }
  });
}

<commit_msg>send new event id back to client (fixed)<commit_after>
var Event = require('./events.model.js');
var Bluebird = require('bluebird');
var request = Bluebird.promisify(require('request'));
var utils = require('./utils.js');
var commentController = require('../comments/comments.controller.js');

/********************* Module.exports *************************/

module.exports = {
  getAll: getAll,
  getOne: getOne,
  addOne: addOne,
  getLocal: getLocal,
  fetchBatchDataFromKimonoAPI: fetchBatchDataFromKimonoAPI,
  fetchBatchDataFromEventbriteAPI: fetchBatchDataFromEventbriteAPI,
  getCoordsFromAddress: getCoordsFromAddress,
  getAddressFromCoords: getAddressFromCoords,
  addManySpoofs: addManySpoofs
};

/******************** Generic DB interactions **********************/

function getAll(req, res) {
  Event.fetchAll()
  .then(function (collection) {
    utils.sendResponse(utils.formatAndTrimEventRecords(collection),res);
  });
}

function getOne(req, res) {
  Event.where({id:req.params.id}).fetch({
      withRelated: ['user', 'photos', 'comments']
    }).then(function (record) {
      if(record){
        utils.sendResponse(utils.formatAndTrimEventRecords([record])[0],res);
      } else {
        res.status(404).end('No event with that id.');
      }

  });
}

function addOne(req, res) {
  request(
    { method: 'POST',
      uri: process.env.PARSER_SERVER_URL + 'api/events/',
      form: req.body,
    })
  .then(function (response) {
    if(response[0].statusCode == 201){
      console.log('parser reports event saved.');
      res.status(201).end(response[0].body)
    } else {
      console.log('error: '+ response[0].statusCode);
    }
  });
}

function addManySpoofs(req,res){
  res.status(200).end();
  var numSpoofs = req.query.number;
  for(var i = 0; i < numSpoofs; i++){
    var newEvent = new Event({
      title: 'Spoof event #' + i,
      startTime: Date.now(),
      endTime: Date.now()+20000000,
      lat: utils.generateRandomLat(),
      lng: utils.generateRandomLong(),
      user_id: 1,
      info: 'info for spoof event #' + i,
      category: 'Party',
      streetAddress1: '1 Embarcadero Blvd',
      streetAddress2: 'Suite 101',
      city: 'San Francisco',
      state: 'CA',
      zipCode: '94102',
      price: Math.random()*100
    })
    .save();
  }
}

function getLocal(req, res) {

    //two dates are used to get modified
    var date1 = new Date();
    var date2 = new Date();

    //currentTime is used to keep track of current time
    var currentTime = Date.now();

    //beginningDate to current date at 3 a.m.
    var beginningDate = date1.setHours(3, 0, 0, 0);

    //endingDate to next day at 3 a.m.
    date2.setDate(date1.getDate() + 1);
    var endingDate = date2.setHours(3, 0, 0, 0);

  Event.query(function(qb){

    //Narrows down events based on specified location
    qb.whereBetween('lat', [Math.min(req.query.lat1,req.query.lat2),Math.max(req.query.lat1,req.query.lat2)]);
    qb.whereBetween('lng', [Math.min(req.query.lng1,req.query.lng2),Math.max(req.query.lng1,req.query.lng2)]);

    //Narrows down events within specified ISO8601 time
    qb.where('startTime', '<', endingDate)
      .andWhere('endTime', '>', beginningDate)
      .andWhere('endTime', '>', currentTime)
      .orWhere('endTime', null);
  })
  .fetchAll()
  .then(function (collection) {
    utils.sendResponse(utils.formatAndTrimEventRecords(collection),res);
  });
}

/************** Geocoding ******************/

//returns a promise of an http response.  parse the response like this:
//var coords = JSON.parse(res[0].body);
//coords will be a lat, lng tuple like [44.5, -122.67]
function getCoordsFromAddress(address) {
  return request( process.env.GEOCODING_SERVER_URL + 'geo/geocode?address=' + address);
}

//returns a promise of an http response.  parse the response like this:
//var address = JSON.parse(res[0].body);
//'address' will be an object with fields like addressLine1, city, state, zipCode, etc.
function getAddressFromCoords(coords) {
  return request( process.env.GEOCODING_SERVER_URL + 'geo/reverseGeocode?lat=' + coords[0] + '&lng=' + coords[1]);
}

/************** Kimono API functions ******************/

function fetchBatchDataFromKimonoAPI(req, res) {
  request( process.env.PARSER_SERVER_URL + 'api/events/kimono')
  .then(function(response){
    if(response[0].statusCode == 201){
      var msg = 'parser acknowledges request to run Kimono fetching';
      console.log(msg);
      res.status(201).end(msg);
    } else {
      var errorMsg = 'parser reports error regarding Kimono fetch request';
      console.log(errorMsg);
      res.status(400).end(errorMsg);
    }
  });
}

/************** Eventbrite API functions ******************/

function fetchBatchDataFromEventbriteAPI(req, res){
  request( process.env.PARSER_SERVER_URL + 'api/events/eventbrite')
  .then(function(response){
    if(response[0].statusCode == 201){
      var msg = 'parser acknowledges request to run Eventbrite fetching';
      console.log(msg);
      res.status(201).end(msg);
    } else {
      var errorMsg = 'parser reports error regarding Eventbrite fetch request';
      console.log(errorMsg);
      res.status(400).end(errorMsg);
    }
  });
}

<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp', [
  'ngRoute',
  'myApp.filters',
  'myApp.services',
  'myApp.directives',
  'myApp.controllers',
  'ngGrid',
  'geneHiveControllers',
  'geneHiveServices'
]).
config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
  $routeProvider.when('/jobRuns', {templateUrl: 'partials/jobRuns.html'});
  $routeProvider.when('/jobRuns/:jobRunId', {templateUrl: 'partials/jobRunDetails.html', controller: 'JobRunDetailsCtrl'});
  $routeProvider.otherwise({redirectTo: '/view1'});
}]);
<commit_msg>merging<commit_after>'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp', [
  'ngRoute',
  'myApp.filters',
  'myApp.services',
  'myApp.directives',
  'myApp.controllers',
  'ngGrid',
  'geneHiveControllers',
  'geneHive.UsersController',
  'geneHiveServices'
]).
config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
  $routeProvider.when('/jobRuns', {templateUrl: 'partials/jobRuns.html'});
	$routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'UsersCtrl'});
  $routeProvider.otherwise({redirectTo: '/view1'});
}]);
<|endoftext|>


<commit_before>var http     = require('http'),
    fs       = require('fs'),
    path     = require('path'),
    spawn    = require('child_process').spawn,
    express  = require('express'),
    pod      = require('../lib/api'),
    ghURL    = require('parse-github-url'),
    app      = express()

// late def, wait until pod is ready
var conf

// middlewares
var reloadConf = function (req, res, next) {
    conf = pod.reloadConfig()
    next()
}

var auth = express.basicAuth(function (user, pass) {
    var u = conf.web.username || 'admin',
        p = conf.web.password || 'admin'
    return user === u && pass === p
})

app.configure(function(){
    app.set('views', __dirname + '/views')
    app.set('view engine', 'ejs')
    app.use(express.favicon())
    app.use(reloadConf)
    app.use(app.router)
    app.use(express.static(path.join(__dirname, 'static')))
})

app.get('/', auth, function (req, res) {
    pod.listApps(function (err, list) {
        if (err) return res.end(err)
        res.render('index', {
            apps: list
        })
    })
})

app.get('/json', auth, function (req, res) {
    pod.listApps(function (err, list) {
        if (err) return res.end(err)
        res.json(list)
    })
})

app.post('/hooks/:appid', express.bodyParser(), function (req, res) {
    var appid = req.params.appid,
        payload = JSON.stringify(req.body),
        app = conf.apps[appid]

    try {
        payload = JSON.parse(payload)
    } catch (e) {
        return res.end(e.toString())
    }

    if (req.get('X-GitHub-Event') === 'ping') {
        if (ghURL(payload.repository.url).repopath === ghURL(app.remote).repopath) {
            return res.status(200).end()
        } else {
            return res.status(500).end()
        }
    }

    if (app && verify(req, app, payload)) {
        executeHook(appid, app, payload, function () {
            res.end()
        })
    } else {
        res.end()
    }
})

// listen when API is ready
pod.once('ready', function () {
    // load config first
    conf = pod.getConfig()
    // conditional open up jsonp based on config
    if (conf.web.jsonp === true) {
        app.get('/jsonp', function (req, res) {
            pod.listApps(function (err, list) {
                if (err) return res.end(err)
                res.jsonp(list)
            })
        })
    }
    app.listen(process.env.PORT || 19999)
})

// Helpers
function verify (req, app, payload) {
    // not even a remote app
    if (!app.remote) return
    // check repo match

    var repo = payload.repository
    var repoURL

    if (repo.links && /bitbucket\.org/.test(repo.links.html.href)) {
        console.log('\nreceived webhook request from: ' + repo.links.html.href)

        repoURL = repo.links.html.href
    } else {
        console.log('\nreceived webhook request from: ' + repo.url)

        repoURL = repo.url
    }

    if (!repoURL) return

    if (ghURL(repoURL).repopath !== ghURL(app.remote).repopath) {
        console.log('aborted.')
        return
    }

    var commit

    // support bitbucket webhooks payload structure
    if (/bitbucket\.org/.test(repoURL)) {
        commit = payload.push.changes[0].new

        commit.message = commit.target.message
    } else {
        // use gitlab's payload structure if detected
        commit = payload.head_commit ? payload.head_commit :
            payload.commits[payload.commits.length - 1];
    }

    if (!commit) return

    // skip it with [pod skip] message
    console.log('commit message: ' + commit.message)
    if (/\[pod skip\]/.test(commit.message)) {
        console.log('aborted.')
        return
    }
    // check branch match
    var ref = commit.name ? commit.name : payload.ref

    if (!ref) return

    var branch = ref.replace('refs/heads/', ''),
        expected = app.branch || 'master'
    console.log('expected branch: ' + expected + ', got branch: ' + branch)
    if (branch !== expected) {
        console.log('aborted.')
        return
    }
    return true
}

function executeHook (appid, app, payload, cb) {

    // set a response timeout to avoid GitHub webhooks
    // hanging up due to long build times
    var responded = false
    function respond (err) {
        if (!responded) {
            responded = true
            cb(err)
        }
    }
    setTimeout(respond, 3000)

    fs.readFile(path.resolve(__dirname, '../hooks/post-receive'), 'utf-8', function (err, template) {
        if (err) return respond(err)
        var hookPath = conf.root + '/temphook.sh',
            hook = template
                .replace(/\{\{pod_dir\}\}/g, conf.root)
                .replace(/\{\{app\}\}/g, appid)
        if (app.branch) {
            hook = hook.replace('origin/master', 'origin/' + app.branch)
        }
        fs.writeFile(hookPath, hook, function (err) {
            if (err) return respond(err)
            fs.chmod(hookPath, '0777', function (err) {
                if (err) return respond(err)
                console.log('excuting github webhook for ' + appid + '...')
                var child = spawn('bash', [hookPath])
                child.stdout.pipe(process.stdout)
                child.stderr.pipe(process.stderr)
                child.on('exit', function (code) {
                    fs.unlink(hookPath, respond)
                })
            })
        })
    })
}
<commit_msg>use git_url instead of url for ping events<commit_after>var http = require('http'),
    fs = require('fs'),
    path = require('path'),
    spawn = require('child_process').spawn,
    express = require('express'),
    pod = require('../lib/api'),
    ghURL = require('parse-github-url'),
    app = express()

// late def, wait until pod is ready
var conf

// middlewares
var reloadConf = function (req, res, next) {
    conf = pod.reloadConfig()
    next()
}

var auth = express.basicAuth(function (user, pass) {
    var u = conf.web.username || 'admin',
        p = conf.web.password || 'admin'
    return user === u && pass === p
})

app.configure(function () {
    app.set('views', __dirname + '/views')
    app.set('view engine', 'ejs')
    app.use(express.favicon())
    app.use(reloadConf)
    app.use(app.router)
    app.use(express.static(path.join(__dirname, 'static')))
})

app.get('/', auth, function (req, res) {
    pod.listApps(function (err, list) {
        if (err) return res.end(err)
        res.render('index', {
            apps: list
        })
    })
})

app.get('/json', auth, function (req, res) {
    pod.listApps(function (err, list) {
        if (err) return res.end(err)
        res.json(list)
    })
})

app.post('/hooks/:appid', express.bodyParser(), function (req, res) {
    var appid = req.params.appid,
        payload = JSON.stringify(req.body),
        app = conf.apps[appid]

    try {
        payload = JSON.parse(payload)
    } catch (e) {
        return res.end(e.toString())
    }

    if (req.get('X-GitHub-Event') === 'ping') {
        if (ghURL(payload.repository.git_url).repopath === ghURL(app.remote).repopath) {
            return res.status(200).end()
        } else {
            return res.status(500).end()
        }
    }

    if (app && verify(req, app, payload)) {
        executeHook(appid, app, payload, function () {
            res.end()
        })
    } else {
        res.end()
    }
})

// listen when API is ready
pod.once('ready', function () {
    // load config first
    conf = pod.getConfig()
    // conditional open up jsonp based on config
    if (conf.web.jsonp === true) {
        app.get('/jsonp', function (req, res) {
            pod.listApps(function (err, list) {
                if (err) return res.end(err)
                res.jsonp(list)
            })
        })
    }
    app.listen(process.env.PORT || 19999)
})

// Helpers
function verify(req, app, payload) {
    // not even a remote app
    if (!app.remote) return
    // check repo match

    var repo = payload.repository
    var repoURL

    if (repo.links && /bitbucket\.org/.test(repo.links.html.href)) {
        console.log('\nreceived webhook request from: ' + repo.links.html.href)

        repoURL = repo.links.html.href
    } else {
        console.log('\nreceived webhook request from: ' + repo.url)

        repoURL = repo.url
    }

    if (!repoURL) return

    if (ghURL(repoURL).repopath !== ghURL(app.remote).repopath) {
        console.log('aborted.')
        return
    }

    var commit

    // support bitbucket webhooks payload structure
    if (/bitbucket\.org/.test(repoURL)) {
        commit = payload.push.changes[0].new

        commit.message = commit.target.message
    } else {
        // use gitlab's payload structure if detected
        commit = payload.head_commit ? payload.head_commit :
            payload.commits[payload.commits.length - 1];
    }

    if (!commit) return

    // skip it with [pod skip] message
    console.log('commit message: ' + commit.message)
    if (/\[pod skip\]/.test(commit.message)) {
        console.log('aborted.')
        return
    }
    // check branch match
    var ref = commit.name ? commit.name : payload.ref

    if (!ref) return

    var branch = ref.replace('refs/heads/', ''),
        expected = app.branch || 'master'
    console.log('expected branch: ' + expected + ', got branch: ' + branch)
    if (branch !== expected) {
        console.log('aborted.')
        return
    }
    return true
}

function executeHook(appid, app, payload, cb) {

    // set a response timeout to avoid GitHub webhooks
    // hanging up due to long build times
    var responded = false
    function respond(err) {
        if (!responded) {
            responded = true
            cb(err)
        }
    }
    setTimeout(respond, 3000)

    fs.readFile(path.resolve(__dirname, '../hooks/post-receive'), 'utf-8', function (err, template) {
        if (err) return respond(err)
        var hookPath = conf.root + '/temphook.sh',
            hook = template
                .replace(/\{\{pod_dir\}\}/g, conf.root)
                .replace(/\{\{app\}\}/g, appid)
        if (app.branch) {
            hook = hook.replace('origin/master', 'origin/' + app.branch)
        }
        fs.writeFile(hookPath, hook, function (err) {
            if (err) return respond(err)
            fs.chmod(hookPath, '0777', function (err) {
                if (err) return respond(err)
                console.log('excuting github webhook for ' + appid + '...')
                var child = spawn('bash', [hookPath])
                child.stdout.pipe(process.stdout)
                child.stderr.pipe(process.stderr)
                child.on('exit', function (code) {
                    fs.unlink(hookPath, respond)
                })
            })
        })
    })
}
<|endoftext|>


<commit_before>var assert = require('assert');
var _ = require('underscore');
var Promise = require("bluebird");
var Sdk = require('./../lib/clc-sdk.js');

var sdk = new Sdk();
var compute = sdk.computeServices();

var DataCenter = compute.DataCenter;
var Server = compute.Server;
var Group = compute.Group;

var OsFamily = compute.OsFamily;
var Machine = compute.Machine;

var startsWith = function (str, substr) { return str.indexOf(substr) === 0; };
var contains = function (str, substr) { return str.indexOf(substr) > -1; };
var onlyCompletedServers = function (serverMetadata) {
    return serverMetadata.status !== 'underConstruction';
};

var server1Name = "srv-1";
var server2Name = "srv-2";
var server3Name = "srv-3";

var serverIds = [];

function __createServer(name, dataCenter) {
    return compute
        .servers()
        .create({
            name: name,
            description: name + " description",
            group: {
                dataCenter: dataCenter,
                name: Group.DEFAULT
            },
            template: {
                dataCenter: dataCenter,
                operatingSystem: {
                    family: OsFamily.CENTOS,
                    version: "6",
                    architecture: Machine.Architecture.X86_64
                }
            },
            network: {
                primaryDns: "172.17.1.26",
                secondaryDns: "172.17.1.27"
            },
            machine: {
                cpu: 1,
                memoryGB: 1
            },
            type: Server.STANDARD,
            storageType: Server.StorageType.STANDARD
        })
        .then(function(result) {
            return result.id;
        });
}

function __checkServers(servers) {
    assert.equal(servers.length, 3);

    _.each(servers, function(server) {
        assert(
            contains(server.id, server1Name) ||
            contains(server.id, server2Name) ||
            contains(server.id, server3Name)
        );
    });
}

function __displayResult(result) {
    _.each(result, function(element) {
        console.log("    " + element.id);
    });

    return result;
}

function __deleteServer(serverId) {
    compute.servers().delete({ id : serverId});
}

/* List all servers available for current user */
function __findAllServers() {
    return compute.servers().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_CENTRAL_SALT_LAKE_CITY],
        where: onlyCompletedServers
    })
    .then(function(servers) {
        console.log("All servers:");
        return servers;
    })
    .then(__displayResult)
    .then(__checkServers);
}

/* Find all active servers in all datacenters */
function __findAllActiveServers() {
    return compute.servers().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_CENTRAL_SALT_LAKE_CITY],
        onlyActive: true,
        where: onlyCompletedServers
    })
    .then(function(servers) {
        console.log("Active servers:");
        return servers;
    })
    .then(__displayResult)
    .then(__checkServers);
}

/* Find server within some group in all datacenters */
function __findServersByGroup() {
    return compute.servers().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_CENTRAL_SALT_LAKE_CITY],
        group: {name: Group.DEFAULT},
        where: onlyCompletedServers
    })
    .then(function(servers) {
        console.log("Servers from Default Group (VA1 and WA1):");
        return servers;
    })
    .then(__displayResult)
    .then(__checkServers);
}

/* Find server that contains some value in it�s metadata */
function __findServerByValueInMetadata() {
    return compute.servers().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_CENTRAL_SALT_LAKE_CITY],
        where: function(serverMetadata) {
            return contains(serverMetadata.description, server1Name) && onlyCompletedServers(serverMetadata)
        }
    })
    .then(function(servers) {
        console.log("Server by '" + server1Name + "' value in metadata:");
        return servers;
    })
    .then(__displayResult)
    .then(function(servers) {
        assert.equal(servers.length, 1);
        assert(contains(servers[0].id, server1Name))
    });
}

/* Find groups that contains keyword in description */
function __findGroupByKeywordInDescription() {
    return compute.groups().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_CENTRAL_SALT_LAKE_CITY],
        descriptionContains: "The default"
    })
    .then(function(servers) {
        console.log("Groups that contains 'The default' keyword in description:");
        return servers;
    })
    .then(__displayResult)
    .then(function(groups) {
        assert.equal(groups.length, 2);
    });
}

/* Find templates of specified operating system */
function __listCentOsTemplates() {
    compute
        .templates()
        .find({
            dataCenter: DataCenter.US_EAST_STERLING,
            operatingSystem: {
                family: OsFamily.CENTOS,
                architecture: Machine.Architecture.X86_64
            }
        })
        .then(function (results) {
            assert(results.length > 0);

            var firstTemplate = _.first(results);
            assert(startsWith(firstTemplate.name, 'CENTOS'));

            console.log("Available CentOs templates:");
            _.each(results, function(template) {
                console.log("    " + template.name);
            });
        });
}

function run() {
    Promise.join(
        __createServer(server1Name, DataCenter.US_EAST_STERLING),
        __createServer(server2Name, DataCenter.US_CENTRAL_SALT_LAKE_CITY),
        __createServer(server3Name, DataCenter.US_EAST_STERLING),

        function(serverId1, serverId2, serverId3) {
            serverIds.push(serverId1);
            serverIds.push(serverId2);
            serverIds.push(serverId3);
        }
    )
    .then(__findAllServers)
    .then(__findAllActiveServers)
    .then(__findServersByGroup)
    .then(__findServerByValueInMetadata)
    .then(__listCentOsTemplates)
    .then(__findGroupByKeywordInDescription)
    .then(function() {
        _.each(serverIds, __deleteServer);
    });
}

run();<commit_msg>Fix Search Queries Sample App<commit_after>var assert = require('assert');
var _ = require('underscore');
var Promise = require("bluebird");
var Sdk = require('./../lib/clc-sdk.js');

var sdk = new Sdk();
var compute = sdk.computeServices();

var DataCenter = compute.DataCenter;
var Server = compute.Server;
var Group = compute.Group;

var OsFamily = compute.OsFamily;
var Machine = compute.Machine;

var startsWith = function (str, substr) { return str.indexOf(substr) === 0; };
var contains = function (str, substr) { return str.indexOf(substr) > -1; };
var onlyCompletedServers = function (serverMetadata) {
    return serverMetadata.status !== 'underConstruction';
};

var server1Name = "srv-1";
var server2Name = "srv-2";
var server3Name = "srv-3";

var serverIds = [];

function __createServer(name, dataCenter) {
    return compute
        .servers()
        .create({
            name: name,
            description: name + " description",
            group: {
                dataCenter: dataCenter,
                name: Group.DEFAULT
            },
            template: {
                dataCenter: dataCenter,
                operatingSystem: {
                    family: OsFamily.CENTOS,
                    version: "6",
                    architecture: Machine.Architecture.X86_64
                }
            },
            network: {
                primaryDns: "172.17.1.26",
                secondaryDns: "172.17.1.27"
            },
            machine: {
                cpu: 1,
                memoryGB: 1
            },
            type: Server.STANDARD,
            storageType: Server.StorageType.STANDARD
        })
        .then(function(result) {
            return result.id;
        });
}

function __checkServers(servers) {
    assert.equal(servers.length, 3);

    _.each(servers, function(server) {
        assert(
            contains(server.id, server1Name) ||
            contains(server.id, server2Name) ||
            contains(server.id, server3Name)
        );
    });
}

function __displayResult(result) {
    _.each(result, function(element) {
        console.log("    " + element.id);
    });

    return result;
}

function __deleteServer(serverId) {
    compute.servers().delete({ id : serverId});
}

/* List all servers available for current user */
function __findAllServers() {
    return compute.servers().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_WEST_SANTA_CLARA],
        where: onlyCompletedServers
    })
    .then(function(servers) {
        console.log("All servers:");
        return servers;
    })
    .then(__displayResult)
    .then(__checkServers);
}

/* Find all active servers in all datacenters */
function __findAllActiveServers() {
    return compute.servers().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_WEST_SANTA_CLARA],
        onlyActive: true,
        where: onlyCompletedServers
    })
    .then(function(servers) {
        console.log("Active servers:");
        return servers;
    })
    .then(__displayResult)
    .then(__checkServers);
}

/* Find server within some group in all datacenters */
function __findServersByGroup() {
    return compute.servers().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_WEST_SANTA_CLARA],
        group: {name: Group.DEFAULT},
        where: onlyCompletedServers
    })
    .then(function(servers) {
        console.log("Servers from Default Group (VA1 and WA1):");
        return servers;
    })
    .then(__displayResult)
    .then(__checkServers);
}

/* Find server that contains some value in it�s metadata */
function __findServerByValueInMetadata() {
    return compute.servers().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_WEST_SANTA_CLARA],
        where: function(serverMetadata) {
            return contains(serverMetadata.description, server1Name) && onlyCompletedServers(serverMetadata)
        }
    })
    .then(function(servers) {
        console.log("Server by '" + server1Name + "' value in metadata:");
        return servers;
    })
    .then(__displayResult)
    .then(function(servers) {
        assert.equal(servers.length, 1);
        assert(contains(servers[0].id, server1Name))
    });
}

/* Find groups that contains keyword in description */
function __findGroupByKeywordInDescription() {
    return compute.groups().find({
        dataCenter: [DataCenter.US_EAST_STERLING, DataCenter.US_WEST_SANTA_CLARA],
        descriptionContains: "The default"
    })
    .then(function(servers) {
        console.log("Groups that contains 'The default' keyword in description:");
        return servers;
    })
    .then(__displayResult)
    .then(function(groups) {
        assert.equal(groups.length, 2);
    });
}

/* Find templates of specified operating system */
function __listCentOsTemplates() {
    compute
        .templates()
        .find({
            dataCenter: DataCenter.US_EAST_STERLING,
            operatingSystem: {
                family: OsFamily.CENTOS,
                architecture: Machine.Architecture.X86_64
            }
        })
        .then(function (results) {
            assert(results.length > 0);

            var firstTemplate = _.first(results);
            assert(startsWith(firstTemplate.name, 'CENTOS'));

            console.log("Available CentOs templates:");
            _.each(results, function(template) {
                console.log("    " + template.name);
            });
        });
}

function run() {
    Promise.join(
        __createServer(server1Name, DataCenter.US_EAST_STERLING),
        __createServer(server2Name, DataCenter.US_WEST_SANTA_CLARA),
        __createServer(server3Name, DataCenter.US_EAST_STERLING),

        function(serverId1, serverId2, serverId3) {
            serverIds.push(serverId1);
            serverIds.push(serverId2);
            serverIds.push(serverId3);
        }
    )
    .then(__findAllServers)
    .then(__findAllActiveServers)
    .then(__findServersByGroup)
    .then(__findServerByValueInMetadata)
    .then(__listCentOsTemplates)
    .then(__findGroupByKeywordInDescription)
    .then(function() {
        _.each(serverIds, __deleteServer);
    });
}

run();<|endoftext|>