<commit_before>/* @flow strict-local */
import type {
  SessionState,
  SessionAction,
  RehydrateAction,
  AccountSwitchAction,
  AppStateAction,
  AppOnlineAction,
  AppRefreshAction,
  InitialFetchCompleteAction,
  InitSafeAreaInsetsAction,
  AppOrientationAction,
  StartEditMessageAction,
  CancelEditMessageAction,
  LoginSuccessAction,
  RealmInitAction,
  DebugFlagToggleAction,
  ToggleOutboxSendingAction,
} from '../types';
import {
  REHYDRATE,
  APP_REFRESH,
  LOGIN_SUCCESS,
  APP_ONLINE,
  ACCOUNT_SWITCH,
  REALM_INIT,
  INIT_SAFE_AREA_INSETS,
  INITIAL_FETCH_COMPLETE,
  APP_ORIENTATION,
  APP_STATE,
  CANCEL_EDIT_MESSAGE,
  START_EDIT_MESSAGE,
  TOGGLE_OUTBOX_SENDING,
  DEBUG_FLAG_TOGGLE,
} from '../actionConstants';
import { getAuth } from '../selectors';

const initialState: SessionState = {
  eventQueueId: -1,
  editMessage: null,
  isOnline: true,
  isActive: true,
  isHydrated: false,
  needsInitialFetch: false,
  orientation: 'PORTRAIT',
  outboxSending: false,
  safeAreaInsets: {
    bottom: 0,
    left: 0,
    right: 0,
    top: 0,
  },
  debug: {
    highlightUnreadMessages: false,
    doNotMarkMessagesAsRead: false,
  },
};

const appRefresh = (
  state: SessionState,
  action: AppRefreshAction | AccountSwitchAction,
): SessionState => ({
  ...state,
  needsInitialFetch: true,
});

const loginSuccess = (state: SessionState, action: LoginSuccessAction): SessionState => ({
  ...state,
  needsInitialFetch: true,
});

const rehydrate = (state: SessionState, action: RehydrateAction): SessionState => {
  const { payload } = action;
  const haveApiKey = !!(payload && payload.accounts && getAuth(payload).apiKey);
  return {
    ...state,
    isHydrated: true,
    // On rehydration, do an initial fetch if we have access to an account
    // (indicated by the presence of an api key). Otherwise, the initial fetch
    // will be initiated on loginSuccess.
    needsInitialFetch: haveApiKey,
  };
};

const realmInit = (state: SessionState, action: RealmInitAction): SessionState => ({
  ...state,
  eventQueueId: action.data.queue_id,
});

const appOnline = (state: SessionState, action: AppOnlineAction): SessionState => ({
  ...state,
  isOnline: action.isOnline,
});

const appState = (state: SessionState, action: AppStateAction): SessionState => ({
  ...state,
  isActive: action.isActive,
});

const initialFetchComplete = (
  state: SessionState,
  action: InitialFetchCompleteAction,
): SessionState => ({
  ...state,
  needsInitialFetch: false,
});

const initSafeAreaInsets = (
  state: SessionState,
  action: InitSafeAreaInsetsAction,
): SessionState => ({
  ...state,
  safeAreaInsets: action.safeAreaInsets,
});

const appOrientation = (state: SessionState, action: AppOrientationAction): SessionState => ({
  ...state,
  orientation: action.orientation,
});

const cancelEditMessage = (state: SessionState, action: CancelEditMessageAction): SessionState => ({
  ...state,
  editMessage: null,
});

const startEditMessage = (state: SessionState, action: StartEditMessageAction): SessionState => ({
  ...state,
  editMessage: {
    id: action.messageId,
    content: action.message,
    topic: action.topic,
  },
});

const toggleOutboxSending = (
  state: SessionState,
  action: ToggleOutboxSendingAction,
): SessionState => ({ ...state, outboxSending: action.sending });

const debugFlagToggle = (state: SessionState, action: DebugFlagToggleAction): SessionState => ({
  ...state,
  debug: {
    ...state.debug,
    [action.key]: action.value,
  },
});

export default (state: SessionState = initialState, action: SessionAction): SessionState => {
  switch (action.type) {
    case APP_REFRESH:
    case ACCOUNT_SWITCH:
      return appRefresh(state, action);

    case LOGIN_SUCCESS:
      return loginSuccess(state, action);

    case REHYDRATE:
      return rehydrate(state, action);

    case REALM_INIT:
      return realmInit(state, action);

    case APP_ONLINE:
      return appOnline(state, action);

    case APP_STATE:
      return appState(state, action);

    case INITIAL_FETCH_COMPLETE:
      return initialFetchComplete(state, action);

    case INIT_SAFE_AREA_INSETS:
      return initSafeAreaInsets(state, action);

    case APP_ORIENTATION:
      return appOrientation(state, action);

    case CANCEL_EDIT_MESSAGE:
      return cancelEditMessage(state, action);

    case START_EDIT_MESSAGE:
      return startEditMessage(state, action);

    case TOGGLE_OUTBOX_SENDING:
      return toggleOutboxSending(state, action);

    case DEBUG_FLAG_TOGGLE:
      return debugFlagToggle(state, action);

    default:
      return state;
  }
};
<commit_msg>sessionReducers: Refactor APP_REFRESH handler to match others.<commit_after>/* @flow strict-local */
import type {
  SessionState,
  SessionAction,
  RehydrateAction,
  AccountSwitchAction,
  AppStateAction,
  AppOnlineAction,
  AppRefreshAction,
  InitialFetchCompleteAction,
  InitSafeAreaInsetsAction,
  AppOrientationAction,
  StartEditMessageAction,
  CancelEditMessageAction,
  LoginSuccessAction,
  RealmInitAction,
  DebugFlagToggleAction,
  ToggleOutboxSendingAction,
} from '../types';
import {
  REHYDRATE,
  APP_REFRESH,
  LOGIN_SUCCESS,
  APP_ONLINE,
  ACCOUNT_SWITCH,
  REALM_INIT,
  INIT_SAFE_AREA_INSETS,
  INITIAL_FETCH_COMPLETE,
  APP_ORIENTATION,
  APP_STATE,
  CANCEL_EDIT_MESSAGE,
  START_EDIT_MESSAGE,
  TOGGLE_OUTBOX_SENDING,
  DEBUG_FLAG_TOGGLE,
} from '../actionConstants';
import { getAuth } from '../selectors';

const initialState: SessionState = {
  eventQueueId: -1,
  editMessage: null,
  isOnline: true,
  isActive: true,
  isHydrated: false,
  needsInitialFetch: false,
  orientation: 'PORTRAIT',
  outboxSending: false,
  safeAreaInsets: {
    bottom: 0,
    left: 0,
    right: 0,
    top: 0,
  },
  debug: {
    highlightUnreadMessages: false,
    doNotMarkMessagesAsRead: false,
  },
};

const loginSuccess = (
  state: SessionState,
  action: AppRefreshAction | LoginSuccessAction | AccountSwitchAction,
): SessionState => ({
  ...state,
  needsInitialFetch: true,
});

const rehydrate = (state: SessionState, action: RehydrateAction): SessionState => {
  const { payload } = action;
  const haveApiKey = !!(payload && payload.accounts && getAuth(payload).apiKey);
  return {
    ...state,
    isHydrated: true,
    // On rehydration, do an initial fetch if we have access to an account
    // (indicated by the presence of an api key). Otherwise, the initial fetch
    // will be initiated on loginSuccess.
    needsInitialFetch: haveApiKey,
  };
};

const realmInit = (state: SessionState, action: RealmInitAction): SessionState => ({
  ...state,
  eventQueueId: action.data.queue_id,
});

const appOnline = (state: SessionState, action: AppOnlineAction): SessionState => ({
  ...state,
  isOnline: action.isOnline,
});

const appState = (state: SessionState, action: AppStateAction): SessionState => ({
  ...state,
  isActive: action.isActive,
});

const initialFetchComplete = (
  state: SessionState,
  action: InitialFetchCompleteAction,
): SessionState => ({
  ...state,
  needsInitialFetch: false,
});

const initSafeAreaInsets = (
  state: SessionState,
  action: InitSafeAreaInsetsAction,
): SessionState => ({
  ...state,
  safeAreaInsets: action.safeAreaInsets,
});

const appOrientation = (state: SessionState, action: AppOrientationAction): SessionState => ({
  ...state,
  orientation: action.orientation,
});

const cancelEditMessage = (state: SessionState, action: CancelEditMessageAction): SessionState => ({
  ...state,
  editMessage: null,
});

const startEditMessage = (state: SessionState, action: StartEditMessageAction): SessionState => ({
  ...state,
  editMessage: {
    id: action.messageId,
    content: action.message,
    topic: action.topic,
  },
});

const toggleOutboxSending = (
  state: SessionState,
  action: ToggleOutboxSendingAction,
): SessionState => ({ ...state, outboxSending: action.sending });

const debugFlagToggle = (state: SessionState, action: DebugFlagToggleAction): SessionState => ({
  ...state,
  debug: {
    ...state.debug,
    [action.key]: action.value,
  },
});

export default (state: SessionState = initialState, action: SessionAction): SessionState => {
  switch (action.type) {
    case APP_REFRESH:
    case ACCOUNT_SWITCH:
    case LOGIN_SUCCESS:
      return loginSuccess(state, action);

    case REHYDRATE:
      return rehydrate(state, action);

    case REALM_INIT:
      return realmInit(state, action);

    case APP_ONLINE:
      return appOnline(state, action);

    case APP_STATE:
      return appState(state, action);

    case INITIAL_FETCH_COMPLETE:
      return initialFetchComplete(state, action);

    case INIT_SAFE_AREA_INSETS:
      return initSafeAreaInsets(state, action);

    case APP_ORIENTATION:
      return appOrientation(state, action);

    case CANCEL_EDIT_MESSAGE:
      return cancelEditMessage(state, action);

    case START_EDIT_MESSAGE:
      return startEditMessage(state, action);

    case TOGGLE_OUTBOX_SENDING:
      return toggleOutboxSending(state, action);

    case DEBUG_FLAG_TOGGLE:
      return debugFlagToggle(state, action);

    default:
      return state;
  }
};
<|endoftext|>


<commit_before>TaskModel = Backbone.Model.extend({
    urlRoot: 'http://localhost:8000/api/tasks'
});

module.exports = Marionette.ItemView.extend({
    template: require('../../../../templates/tasks/tasks.dust'),
    helpers: function (cb) {
        var tasklist = new TaskModel();
        var helpers = {};
        tasklist.fetch({
            success: function (tasks) {
                var taskList = _.toArray(tasks.attributes);
                //_.forEach(taskList, function (task) {
                //    task.owner = getOwnerName(task.owner);
                //});
                helpers = {
                    tasks: taskList,
                    getUserName: function (chunk, context, bodies, params) {
                        var user = new UserModel({id: params.id});
                        return chunk.map(function (chunk) {
                            user.fetch({
                                success: function (user) {
                                    var username = user.get('username');
                                    return chunk.write(username + " (" + params.id + ")").end();

                                },
                                failure: function () {
                                    return chunk.write('ERROR');
                                }
                            })
                        })
                    },
                    isOwner: function (chunk, context, bodies, params) {

                        var userID = Session.get('id');
                        console.log(userID);
                        console.log(params.id);
                       return userID === params.id;

                    }

                };
                var userlist = new UserModel();

                userlist.fetch({
                    success: function (users) {
                        var list = [];
                        _.forEach(users.attributes, function (user) {
                            list.push(user.username);
                        });
                        helpers.users = list;
                        helpers.filteredUsers = function (chunk, context, bodies, params) {
                            return _.difference(this.users, params.members);
                        };
                        cb(null, helpers);

                    }
                }).fail(function (error) {
                    setNotify('danger', error.status + ' ' + error.statusText);
                    cb(error, null);
                });

            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });
    },
    /**
     * @returns {Object}
     */
    events: function () {
        return {
            'click .add-task': 'onAddTask',
            'click .delete-task': 'remTask',
            'click .complete': 'markCompleted',
            'click .taskMembersSubmit': 'collapseTaskMembers',
            'click .memberInputSubmit': 'collapseMemberInput',
            'click .memberRemove': 'removeMember'
        };
    }
    ,

    /**
     *
     * @chainable
     * @returns {Backbone.View}
     */

    render: function () {
        var self = this;
        this.helpers(function (err, helpers) {
            self.template(helpers, function (error, html) {
                if (error) {
                    console.log(error);
                }
                else {
                    self.$el.html(html);
                }
            });
        });

    }
    ,

    onAddTask: function (e) {
        e.preventDefault();

        var formData = $('.task-form').serializeArray();
        var taskDetails = {};
        var self = this;
        var task = new TaskModel();

        _.forEach(formData, function forEveryFormData(val) {
            taskDetails[val.name] = val.value;
        });

        //taskDetails.id = taskDetails.title;

        task.save(taskDetails, {
            success: function (task) {
                console.log('Success');
                self.render();
            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });

        return false;
    }
    ,
    remTask: function (e) {
        e.preventDefault();

        var entry = e.currentTarget.value;
        console.log(entry);
        var task = new TaskModel({
            id: entry
        });

        task.destroy({
            success: function () {
                $('#tr-' + entry).remove();

            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });

        return false;

    }
    ,
    markCompleted: function (e) {
        var completed = e.currentTarget.checked;
        var entry = e.currentTarget.name;
        var task = new TaskModel({
            id: entry
        });
        var self = this;
        task.fetch({
            success: function (task) {
                task.save({completed: completed}, {
                    success: function () {
                        self.render();
                        $('#tr-' + entry).blur();
                        return true;
                    }
                }).fail(function (error) {
                    self.render();
                    setNotify('danger', error.status + ' ' + error.statusText);
                });
            }
        });

    }
    ,

    collapseMemberInput: function (e) {
        e.preventDefault();
        var self = this;
        var id = e.currentTarget.value;
        var task = new TaskModel({
            id: id
        });
        var newMemberUsername = $('#select-' + id).val();

        task.fetch({
            success: function (task) {
                var members = task.get('members') || [];

                members.push(newMemberUsername);

                task.save({members: _.uniq(members)}, {
                    success: function () {
                        var thisRow = $(e.target).parents('.row.memberInput');
                        thisRow.collapse('toggle');
                        thisRow.siblings('.row.taskMembers').collapse('show');
                        self.render();
                    }
                }).fail(function (error) {
                    var thisRow = $(e.target).parents('.row.memberInput');
                    thisRow.collapse('toggle');
                    thisRow.siblings('.row.taskMembers').collapse('show');
                    setNotify('danger', error.status + ' ' + error.statusText);
                });
            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });

    }
    ,

    collapseTaskMembers: function (e) {
        e.preventDefault();
        var thisRow = $(e.target).parents('.row.taskMembers');
        thisRow.collapse('toggle');
        thisRow.siblings('.row.memberInput').collapse('show');
    }
    ,

    removeMember: function (e) {
        e.preventDefault();
        var self = this;
        var id = e.currentTarget.parentNode.id;
        var member = e.currentTarget.value;
        var taskToUpdate = new TaskModel({
            id: id
        });

        taskToUpdate.fetch({
            success: function (task) {
                var members = task.get('members') || [];

                taskToUpdate.save({members: _.without(members, member)}, {
                    success: function () {
                        self.render();
                    }
                }).fail(function (error) {
                    setNotify('danger', error.status + ' ' + error.statusText);
                });
            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });
    }
})
;
<commit_msg>fix(thing): remove log<commit_after>TaskModel = Backbone.Model.extend({
    urlRoot: 'http://localhost:8000/api/tasks'
});

module.exports = Marionette.ItemView.extend({
    template: require('../../../../templates/tasks/tasks.dust'),
    helpers: function (cb) {
        var tasklist = new TaskModel();
        var helpers = {};
        tasklist.fetch({
            success: function (tasks) {
                var taskList = _.toArray(tasks.attributes);
                //_.forEach(taskList, function (task) {
                //    task.owner = getOwnerName(task.owner);
                //});
                helpers = {
                    tasks: taskList,
                    getUserName: function (chunk, context, bodies, params) {
                        var user = new UserModel({id: params.id});
                        return chunk.map(function (chunk) {
                            user.fetch({
                                success: function (user) {
                                    var username = user.get('username');
                                    return chunk.write(username + " (" + params.id + ")").end();

                                },
                                failure: function () {
                                    return chunk.write('ERROR');
                                }
                            })
                        })
                    },
                    isOwner: function (chunk, context, bodies, params) {

                        var userID = Session.get('id');
                        return userID === params.id;

                    }

                };
                var userlist = new UserModel();

                userlist.fetch({
                    success: function (users) {
                        var list = [];
                        _.forEach(users.attributes, function (user) {
                            list.push(user.username);
                        });
                        helpers.users = list;
                        helpers.filteredUsers = function (chunk, context, bodies, params) {
                            return _.difference(this.users, params.members);
                        };
                        cb(null, helpers);

                    }
                }).fail(function (error) {
                    setNotify('danger', error.status + ' ' + error.statusText);
                    cb(error, null);
                });

            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });
    },
    /**
     * @returns {Object}
     */
    events: function () {
        return {
            'click .add-task': 'onAddTask',
            'click .delete-task': 'remTask',
            'click .complete': 'markCompleted',
            'click .taskMembersSubmit': 'collapseTaskMembers',
            'click .memberInputSubmit': 'collapseMemberInput',
            'click .memberRemove': 'removeMember'
        };
    }
    ,

    /**
     *
     * @chainable
     * @returns {Backbone.View}
     */

    render: function () {
        var self = this;
        this.helpers(function (err, helpers) {
            self.template(helpers, function (error, html) {
                if (error) {
                    console.log(error);
                }
                else {
                    self.$el.html(html);
                }
            });
        });

    }
    ,

    onAddTask: function (e) {
        e.preventDefault();

        var formData = $('.task-form').serializeArray();
        var taskDetails = {};
        var self = this;
        var task = new TaskModel();

        _.forEach(formData, function forEveryFormData(val) {
            taskDetails[val.name] = val.value;
        });

        //taskDetails.id = taskDetails.title;

        task.save(taskDetails, {
            success: function (task) {
                console.log('Success');
                self.render();
            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });

        return false;
    }
    ,
    remTask: function (e) {
        e.preventDefault();

        var entry = e.currentTarget.value;
        console.log(entry);
        var task = new TaskModel({
            id: entry
        });

        task.destroy({
            success: function () {
                $('#tr-' + entry).remove();

            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });

        return false;

    }
    ,
    markCompleted: function (e) {
        var completed = e.currentTarget.checked;
        var entry = e.currentTarget.name;
        var task = new TaskModel({
            id: entry
        });
        var self = this;
        task.fetch({
            success: function (task) {
                task.save({completed: completed}, {
                    success: function () {
                        self.render();
                        $('#tr-' + entry).blur();
                        return true;
                    }
                }).fail(function (error) {
                    self.render();
                    setNotify('danger', error.status + ' ' + error.statusText);
                });
            }
        });

    }
    ,

    collapseMemberInput: function (e) {
        e.preventDefault();
        var self = this;
        var id = e.currentTarget.value;
        var task = new TaskModel({
            id: id
        });
        var newMemberUsername = $('#select-' + id).val();

        task.fetch({
            success: function (task) {
                var members = task.get('members') || [];

                members.push(newMemberUsername);

                task.save({members: _.uniq(members)}, {
                    success: function () {
                        var thisRow = $(e.target).parents('.row.memberInput');
                        thisRow.collapse('toggle');
                        thisRow.siblings('.row.taskMembers').collapse('show');
                        self.render();
                    }
                }).fail(function (error) {
                    var thisRow = $(e.target).parents('.row.memberInput');
                    thisRow.collapse('toggle');
                    thisRow.siblings('.row.taskMembers').collapse('show');
                    setNotify('danger', error.status + ' ' + error.statusText);
                });
            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });

    }
    ,

    collapseTaskMembers: function (e) {
        e.preventDefault();
        var thisRow = $(e.target).parents('.row.taskMembers');
        thisRow.collapse('toggle');
        thisRow.siblings('.row.memberInput').collapse('show');
    }
    ,

    removeMember: function (e) {
        e.preventDefault();
        var self = this;
        var id = e.currentTarget.parentNode.id;
        var member = e.currentTarget.value;
        var taskToUpdate = new TaskModel({
            id: id
        });

        taskToUpdate.fetch({
            success: function (task) {
                var members = task.get('members') || [];

                taskToUpdate.save({members: _.without(members, member)}, {
                    success: function () {
                        self.render();
                    }
                }).fail(function (error) {
                    setNotify('danger', error.status + ' ' + error.statusText);
                });
            }
        }).fail(function (error) {
            setNotify('danger', error.status + ' ' + error.statusText);
        });
    }
})
;
<|endoftext|>


<commit_before>import express from "express"
import {assoc, map} from "ramda"
import favicon from "serve-favicon"
import path from "path"
import winston from "winston"

import handleRender from "./render"
import {addNormalizedDescription} from "../search"
import {fetchParameters, fetchVariables, fetchSwagger} from "../webservices"
import config from "../config"

winston.configure(config.winstonConfig);

function startServer(state) {
  const server = express()
  server.use(favicon(path.resolve(__dirname, "../assets/favicon.ico")))
  server.use(express.static(path.resolve(__dirname, "../../public")))

  server.use(handleRender(state))

  // Generic server errors (e.g. not caught by components)
  server.use((err, req, res, next) => {
    winston.error(req.method + " " + req.url, {error: err})
    if (server.get("env") === "production") {
      res.status(500).send(
        "
"
        + "Something unexpected happened, sorry. The error has been logged.\n"
        + "Details : " + new Date().toISOString() + ", " + err.stack
        + "
"
      )
    } else {
      next(err)
    }
  })

  const host = process.env.HOST || "localhost"
  const port = process.env.PORT || 2030
  server.listen(port, host, () => {
    console.log(`Server listening at http://${host}:${port}/`)
  })
}

console.log("Fetching variables and parameters on Web API...")
Promise.all([fetchParameters(), fetchVariables(), fetchSwagger()])
  .then(([parametersResponse, variablesResponse, swaggerResponse]) => {
    console.log("Starting server...")
    const normalizedParameters = map(
      assoc('itemType', 'parameter'),
      addNormalizedDescription(parametersResponse.data)
    )
    const normalizedVariables = map(
      assoc('itemType', 'variable'),
      addNormalizedDescription(variablesResponse.data),
    )
    const state = {
      countryPackageName: variablesResponse['country-package'],
      countryPackageVersion: variablesResponse['country-package-version'],
      parameters: normalizedParameters,
      variables: normalizedVariables,
      swaggerSpec: swaggerResponse.data,
    }
    startServer(state)
  }, error => {
    console.log('error:', error)
  })
  .catch((error) => {
    console.log('Top-level error:', error)
  })
<commit_msg>Improve error page<commit_after>import express from "express"
import {assoc, map} from "ramda"
import favicon from "serve-favicon"
import path from "path"
import winston from "winston"

import handleRender from "./render"
import {addNormalizedDescription} from "../search"
import {fetchParameters, fetchVariables, fetchSwagger} from "../webservices"
import config from "../config"

winston.configure(config.winstonConfig);

function startServer(state) {
  const server = express()
  server.use(favicon(path.resolve(__dirname, "../assets/favicon.ico")))
  server.use(express.static(path.resolve(__dirname, "../../public")))

  server.use(handleRender(state))

  // Generic server errors (e.g. not caught by components)
  server.use((err, req, res, next) => {
    winston.error(req.method + " " + req.url, {error: err})
    if (server.get("env") === "production") {
      res.status(500).send(
        '
Error: ' + err.message + '
'
        + '
This error has been logged at ' + new Date().toISOString() + '.
'
        + '
If this happens often, please open an issue.
'
        + '
Technical details
'
        + '
' + err.stack + '
'
      )
    } else {
      next(err)
    }
  })

  const host = process.env.HOST || "localhost"
  const port = process.env.PORT || 2030
  server.listen(port, host, () => {
    console.log(`Server listening at http://${host}:${port}/`)
  })
}

console.log("Fetching variables and parameters on Web API...")
Promise.all([fetchParameters(), fetchVariables(), fetchSwagger()])
  .then(([parametersResponse, variablesResponse, swaggerResponse]) => {
    console.log("Starting server...")
    const normalizedParameters = map(
      assoc('itemType', 'parameter'),
      addNormalizedDescription(parametersResponse.data)
    )
    const normalizedVariables = map(
      assoc('itemType', 'variable'),
      addNormalizedDescription(variablesResponse.data),
    )
    const state = {
      countryPackageName: variablesResponse['country-package'],
      countryPackageVersion: variablesResponse['country-package-version'],
      parameters: normalizedParameters,
      variables: normalizedVariables,
      swaggerSpec: swaggerResponse.data,
    }
    startServer(state)
  }, error => {
    console.log('error:', error)
  })
  .catch((error) => {
    console.log('Top-level error:', error)
  })
<|endoftext|>


<commit_before>function Spotlight(){
	//store core cache
	this.album = {
					linksList : [], //array of links
					numberImage : 0 // current image count
					};
	this.init();

}

Spotlight.prototype.init = function() {
	this.init = false;
	this.run();
};

Spotlight.prototype.run = function() {
	var self = this

	$('body').on('click', 'a[data-spotLight]', function(event) { //event click on data-spotLight value

    	if(self.init == false){
			self.buildAlbum($(event.currentTarget));// attribute from the event.currentTarget

    	}else{
    		for(var i = 0; i < self.album.linksList.length; i++){
   				//console.log("event : "+$(event.currentTarget)[0]);
   				//console.log("linkList : "+self.album.linksList[i].link);
    			if (self.album.linksList[i].link === $(event.currentTarget).attr('href')){
    				self.album.numberImage = i
    				console.log("first : "+self.album.numberImage);
    			}
			}

			$('#spotlight').fadeIn('slow');
			self.showImage(self.album.numberImage);
			self.sizeContainer();
    	}
    	return false;
    });
};

Spotlight.prototype.buildAlbum = function($link){
	var self = this

	// method push album in the array with object data
	function addToAlbum($link){
		self.album.linksList.push({ // push in the ablum.linksList array
        link : $link.attr('href'),
    	});
	};

	var $links, //cache linksList
	dataSpotLightValue = $link.attr('data-spotLight');//get attribute from data-spotLight

	//loop storing
	if (dataSpotLightValue) { // == dataSpotLightValue return true
		$links = $($link.prop('tagName') + '[data-spotLight="' + dataSpotLightValue + '"]');// assign to links
		//console.log($links)
		//loop for storing data on linksList
		for (var i = 0; i < $links.length; i++) {
        	addToAlbum($($links[i]));

	    	if ($links[i] === $link[0]) {
	        	this.album.numberImage = i;
	      	}
	    }
	}
	this.cacheDiv();
	this.update();
	this.init = true;
};

Spotlight.prototype.cacheDiv = function(){

	this.next = ''
	this.prev = ''
	this.close = ''

	this.rightButton = '
'+this.next+'
'
	this.leftButton = '
'+this.prev+'
'
	this.closeButton = '
'+this.close+'
'
	this.image = ''

	this.container = '
'+this.rightButton+this.image+this.leftButton+this.closeButton+'
';
	this.spotlight = '
'+this.container+'
';

};

Spotlight.prototype.update = function(){

	$(this.spotlight).appendTo($('body'));
	this.nav();
	this.end(); //close button method "jquery"

};

Spotlight.prototype.nav = function(){
	var	self = this;

	this.showImage(this.album.numberImage);

	$('body').on('click', 'div[id = rightButton],div[id = leftButton]', function(event){
		var id = ($(event.currentTarget)).attr('id')
		navlogic(id);
	});

	function navlogic(id){

		if (id == 'rightButton'){
			if(self.album.numberImage >= self.album.linksList.length -1){
				self.album.numberImage = 0;
				console.log("numberImage : "+self.album.numberImage+" album : "+self.album.linksList.length);
			}else{
				self.album.numberImage++;
				console.log("numberImage : "+self.album.numberImage+" album : "+self.album.linksList.length);
			}
		}

		else if (id == 'leftButton'){
			if(self.album.numberImage -1 < 0){
				self.album.numberImage = self.album.linksList.length -1;
				console.log("numberImage : "+self.album.numberImage+" album : "+self.album.linksList.length);
			}else{
				self.album.numberImage--;
				console.log("numberImage : "+self.album.numberImage+" album : "+self.album.linksList.length);
			}
		}
		return self.showImage(self.album.numberImage);
	};
};

Spotlight.prototype.sizeContainer = function() {
    var $spotlight = $('#spotlight');
    $spotlight.width($(document).width());
    $spotlight.height($(document).height());
};

Spotlight.prototype.showImage = function(numberImage) {
    var $image = $('#show');
    var preloader = new Image();
   	var self = this;

   	var windowWidth = $(window).width(),
   		windowHeight  = $(window).height();

    preloader.onload = function(){
    	var $preloader;
		$('#show').attr('src',self.album.linksList[numberImage].link);
		$preloader = $(preloader)
	 	$image.width(preloader.width * 0.7);
     	$image.height(preloader.height * 0.7);

	}

 	preloader.src = this.album.linksList[numberImage].link;
 	console.log("second : "+numberImage)
 	this.sizeContainer();
};

Spotlight.prototype.end = function(){
	var $spotlight = $('#spotlight')

	$('#closeButton').click(function(){
    	$spotlight.fadeOut('slow');
	});
};

$(document).ready(function(){
new Spotlight();

});<commit_msg>fix, call method, i need to change it<commit_after>function Spotlight(){
	//store core cache
	this.album = {
					linksList : [], //array of links
					numberImage : 0 // current image count
					};
	this.init();

}

Spotlight.prototype.init = function() {
	this.init = false;
	this.run();
};

Spotlight.prototype.run = function() {
	var self = this

	$('body').on('click', 'a[data-spotLight]', function(event) { //event click on data-spotLight value

    	if(self.init == false){
			self.buildAlbum($(event.currentTarget));// attribute from the event.currentTarget

    	}else{
    		for(var i = 0; i < self.album.linksList.length; i++){
   				//console.log("event : "+$(event.currentTarget)[0]);
   				//console.log("linkList : "+self.album.linksList[i].link);
    			if (self.album.linksList[i].link === $(event.currentTarget).attr('href')){
    				self.album.numberImage = i
    				console.log("first : "+self.album.numberImage);
    			}
			}

			$('#spotlight').fadeIn('slow');
			self.showImage(self.album.numberImage);
			self.sizeContainer();
    	}
    	return false;
    });
};

Spotlight.prototype.buildAlbum = function($link){
	var self = this

	// method push album in the array with object data
	function addToAlbum($link){
		self.album.linksList.push({ // push in the ablum.linksList array
        link : $link.attr('href'),
    	});
	};

	var $links, //cache linksList
	dataSpotLightValue = $link.attr('data-spotLight');//get attribute from data-spotLight

	//loop storing
	if (dataSpotLightValue) { // == dataSpotLightValue return true
		$links = $($link.prop('tagName') + '[data-spotLight="' + dataSpotLightValue + '"]');// assign to links
		//console.log($links)
		//loop for storing data on linksList
		for (var i = 0; i < $links.length; i++) {
        	addToAlbum($($links[i]));

	    	if ($links[i] === $link[0]) {
	        	this.album.numberImage = i;
	      	}
	    }
	}
	this.cacheDiv();
	this.update();
	this.init = true;
};

Spotlight.prototype.cacheDiv = function(){

	this.next = ''
	this.prev = ''
	this.close = ''

	this.rightButton = '
'+this.next+'
'
	this.leftButton = '
'+this.prev+'
'
	this.closeButton = '
'+this.close+'
'
	this.image = ''

	this.container = '
'+this.rightButton+this.image+this.leftButton+this.closeButton+'
';
	this.spotlight = '
'+this.container+'
';

};

Spotlight.prototype.update = function(){

	$(this.spotlight).appendTo($('body'));
	this.nav();
	this.end(); //close button method "jquery"

};

Spotlight.prototype.nav = function(){
	var	self = this;

	this.showImage(this.album.numberImage);

	$('body').on('click', 'div[id = rightButton],div[id = leftButton]', function(event){
		var id = ($(event.currentTarget)).attr('id')
		navlogic(id);
	});

	function navlogic(id){

		if (id == 'rightButton'){
			if(self.album.numberImage >= self.album.linksList.length -1){
				self.album.numberImage = 0;
				console.log("numberImage : "+self.album.numberImage+" album : "+self.album.linksList.length);
			}else{
				self.album.numberImage++;
				console.log("numberImage : "+self.album.numberImage+" album : "+self.album.linksList.length);
			}
		}

		else if (id == 'leftButton'){
			if(self.album.numberImage -1 < 0){
				self.album.numberImage = self.album.linksList.length -1;
				console.log("numberImage : "+self.album.numberImage+" album : "+self.album.linksList.length);
			}else{
				self.album.numberImage--;
				console.log("numberImage : "+self.album.numberImage+" album : "+self.album.linksList.length);
			}
		}
		return self.showImage(self.album.numberImage);
	};
};

Spotlight.prototype.sizeContainer = function() {
    var $spotlight = $('#spotlight');
    $spotlight.width($(document).width());
    $spotlight.height($(document).height());
};

Spotlight.prototype.showImage = function(numberImage) {
    var $image = $('#show');
    var preloader = new Image();
   	var self = this;

   	var windowWidth = $(window).width(),
   		windowHeight  = $(window).height();

    preloader.onload = function(){
    	var $preloader;
		$('#show').attr('src',self.album.linksList[numberImage].link);
		$preloader = $(preloader)
	 	$image.width(preloader.width * 0.7);
     	$image.height(preloader.height * 0.7);

	}

 	preloader.src = this.album.linksList[numberImage].link;
 	console.log("second : "+numberImage)
 	this.sizeContainer();
};

Spotlight.prototype.end = function(){
	var $spotlight = $('#spotlight')

	$('#closeButton').click(function(){
    	$spotlight.fadeOut('slow');
    	//$('#spotlight').remove();
	});
};

$('body').on('click', 'a[data-spotLight]', function(event) { // change call method
new Spotlight();

return false;
});<|endoftext|>


<commit_before>var droonga = require('express-droonga'),
    fs      = require('fs'),
    yaml    = require('js-yaml'),
    path    = require('path');

var baseDir = path.resolve(process.env.DROONGA_BASE_DIR || ".");

var engineConfigs = {};

function setBaseDir(baseDir) {
  var configs = {};

  var configFile = path.resolve(baseDir, "droonga-http-server.yaml");
  if (fs.existsSync(configFile)) {
    configs = yaml.safeLoad(fs.readFileSync(configFile, 'utf8'));
    if (!('daemon' in configs))
      configs.daemon = true;
  }

  var engineConfigFile = path.resolve(baseDir, "droonga-engine.yaml");
  if (fs.existsSync(engineConfigFile)) {
    engineConfigs = yaml.safeLoad(fs.readFileSync(engineConfigFile, 'utf8'));
  }

  configs.baseDir = baseDir;
  configs = defineDefaultConfigs(configs);
  configs.setBaseDir = setBaseDir;
  return configs;
}

function define(slot, path, value) {
  var keys = path.split('.');
  keys.some(function(key, index) {
    if (index == keys.length - 1) {
      if (!(key in slot))
        slot[key] = value;
    } else {
      if (!(key in slot))
        slot[key] = {};
      slot = slot[key];
    }
  });
}

function defineDefaultConfigs(configs) {
define(engineConfigs, 'host', '127.0.0.1');
define(engineConfigs, 'port', 10031);
define(engineConfigs, 'tag',  'droonga');

define(configs, 'port',               10041);
define(configs, 'cache_size',         100);
define(configs, 'enable_trust_proxy', false);
define(configs, 'plugins', [
  droonga.API_REST,
  droonga.API_GROONGA,
  droonga.API_DROONGA
]);
define(configs, 'environment', process.env.NODE_ENV || 'development');

if (configs.daemon) {
  define(configs, 'pid_file',        'droonga-http-server.pid');
  define(configs, 'access_log_file', 'droonga-http-server.access.log');
  define(configs, 'system_log_file', 'droonga-http-server.system.log');
} else {
  define(configs, 'daemon',          false);
  define(configs, 'access_log_file', '-');
  define(configs, 'system_log_file', '-');
}

define(configs, 'engine.host',            engineConfigs.host);
define(configs, 'engine.port',            engineConfigs.port);
define(configs, 'engine.tag',             engineConfigs.tag);
define(configs, 'engine.default_dataset', 'Default');
// We can use the host name of the droogna-engine as the receiver host
// of the http server, because this computer works as a droonga-engine
// node and it is guaranteed that this computer can be accessed with
// the host name.
define(configs, 'engine.receiver_host',   engineConfigs.host);

return configs;
}

module.exports = setBaseDir(baseDir);
<commit_msg>Load droonga-engine.yaml for the service<commit_after>var droonga = require('express-droonga'),
    fs      = require('fs'),
    yaml    = require('js-yaml'),
    path    = require('path');

var baseDir = path.resolve(process.env.DROONGA_BASE_DIR || ".");

var engineConfigs = {};
var engineServiceUserName = 'droonga-engine';
var engineServiceBaseDir  = '/home/' + engineServiceUserName + '/droonga';

function setBaseDir(baseDir) {
  var configs = {};

  var configFile = path.resolve(baseDir, "droonga-http-server.yaml");
  if (fs.existsSync(configFile)) {
    configs = yaml.safeLoad(fs.readFileSync(configFile, 'utf8'));
    if (!('daemon' in configs))
      configs.daemon = true;
  }

  var engineServiceConfigFile = path.resolve(engineServiceBaseDir, "droonga-engine.yaml");
  if (fs.existsSync(engineServiceConfigFile)) {
    engineConfigs = yaml.safeLoad(fs.readFileSync(engineServiceConfigFile, 'utf8'));
  }
  else {
    var engineConfigFile = path.resolve(baseDir, "droonga-engine.yaml");
    if (fs.existsSync(engineConfigFile)) {
      engineConfigs = yaml.safeLoad(fs.readFileSync(engineConfigFile, 'utf8'));
    }
  }

  configs.baseDir = baseDir;
  configs = defineDefaultConfigs(configs);
  configs.setBaseDir = setBaseDir;
  return configs;
}

function define(slot, path, value) {
  var keys = path.split('.');
  keys.some(function(key, index) {
    if (index == keys.length - 1) {
      if (!(key in slot))
        slot[key] = value;
    } else {
      if (!(key in slot))
        slot[key] = {};
      slot = slot[key];
    }
  });
}

function defineDefaultConfigs(configs) {
define(engineConfigs, 'host', '127.0.0.1');
define(engineConfigs, 'port', 10031);
define(engineConfigs, 'tag',  'droonga');

define(configs, 'port',               10041);
define(configs, 'cache_size',         100);
define(configs, 'enable_trust_proxy', false);
define(configs, 'plugins', [
  droonga.API_REST,
  droonga.API_GROONGA,
  droonga.API_DROONGA
]);
define(configs, 'environment', process.env.NODE_ENV || 'development');

if (configs.daemon) {
  define(configs, 'pid_file',        'droonga-http-server.pid');
  define(configs, 'access_log_file', 'droonga-http-server.access.log');
  define(configs, 'system_log_file', 'droonga-http-server.system.log');
} else {
  define(configs, 'daemon',          false);
  define(configs, 'access_log_file', '-');
  define(configs, 'system_log_file', '-');
}

define(configs, 'engine.host',            engineConfigs.host);
define(configs, 'engine.port',            engineConfigs.port);
define(configs, 'engine.tag',             engineConfigs.tag);
define(configs, 'engine.default_dataset', 'Default');
// We can use the host name of the droogna-engine as the receiver host
// of the http server, because this computer works as a droonga-engine
// node and it is guaranteed that this computer can be accessed with
// the host name.
define(configs, 'engine.receiver_host',   engineConfigs.host);

return configs;
}

module.exports = setBaseDir(baseDir);
<|endoftext|>


<commit_before>/*jshint node: true, evil: true */
/*global require, exports */
'use strict';

var path = require('path');
var fs = require('fs');
var extend = require('util')._extend;
var stylus = require('stylus');
var mkpath = require('mkpath');

function readOptions(content) {
    var firstLine = content.substr(0, content.indexOf('\n')),
        match = /^\s*\/\/\s*(.+)/.exec(firstLine),
        options = {};

    if (!match) {
        return options;
    }

    match[1].split(',').forEach(function (item) {
        var key, value, i = item.indexOf(':');

        if (i < 0) {
            return;
        }

        key = item.substr(0, i).trim();
        value = item.substr(i + 1).trim();
        if (value.match(/^(true|false|undefined|null|[0-9]+)$/)) {
            value = eval(value);
        }
        options[key] = value;
    });
    return options;
}

// makes a file in a path where directories may or may not have existed before
function mkfile(filepath, content, callback) {
    mkpath(path.dirname(filepath), function (err) {
        if (err) {
            return callback ? callback(err) : undefined;
        }
        fs.writeFile(filepath, content, callback);
    });
}

// compile the given less file
function compile(stylusFile, callback) {
    fs.readFile(stylusFile, 'utf8', function (err, buffer) {
        if (err) {
            return callback(err);
        }

        var content = buffer.toString(),
            stylusPath = path.dirname(stylusFile),
            cssFilename,
            cssFile,
            defaults = {
                compress: false,
                sourcemap: false,
                prefix: '',
                paths: [stylusPath]
            },
            options = extend(defaults, readOptions(content)),
            style = stylus(content, options);

        // main is set: compile the referenced file instead
        if (options.main) {
            stylusFile = path.resolve(stylusPath, options.main);
            return compile(stylusFile, callback);
        }

        // out is null or false: do not compile
        if (options.out === null || options.out === false) {
            return callback();
        }

        // out is set: output to the given file name
        if (options.out) {
            cssFilename = options.out;
            if (path.extname(cssFilename) === '') {
                cssFilename += '.css';
            }
            delete options.out;
        } else {
            cssFilename = path.basename(stylusFile);
            cssFilename = cssFilename.substr(0, cssFilename.length - path.extname(cssFilename).length) + '.css';
        }

        cssFile = path.resolve(stylusPath, cssFilename);

        style.render(function (err, css) {
            if (err) {
                return callback(err);
            }

            mkfile(cssFile, css, function (err) {
                if (err) {
                    return callback(err);
                }
            });

            // write sourcemap
            if (options.sourcemap) {
                mkfile(cssFile + '.map', JSON.stringify(style.sourcemap), function (err) {
                    if (err) {
                        return callback(err);
                    }
                });
            }

            callback();
        });
    });
}

// set up service for brackets
function init(DomainManager) {
    if (!DomainManager.hasDomain('StylusCompiler')) {
        DomainManager.registerDomain('StylusCompiler', { major: 1, minor: 0 });
    }
    DomainManager.registerCommand(
        'StylusCompiler', // domain name
        'compile', // command name
        compile, // command handler function
        true, // this command is asynchronous
        'Compiles a stylus file',
        [{
            name: 'stylusFile',
            type: 'String',
            description: 'stylus filename'
        }, {
            name: 'callback',
            type: 'Function',
            description: 'callback function'
        }],
        null
    );
}

exports.init = init;<commit_msg>sourcemap fix<commit_after>/*jshint node: true, evil: true */
/*global require, exports */
'use strict';

var path = require('path');
var fs = require('fs');
var extend = require('util')._extend;
var stylus = require('stylus');
var mkpath = require('mkpath');

function readOptions(content) {
    var firstLine = content.substr(0, content.indexOf('\n')),
        match = /^\s*\/\/\s*(.+)/.exec(firstLine),
        options = {};

    if (!match) {
        return options;
    }

    match[1].split(',').forEach(function (item) {
        var key, value, i = item.indexOf(':');

        if (i < 0) {
            return;
        }

        key = item.substr(0, i).trim();
        value = item.substr(i + 1).trim();
        if (value.match(/^(true|false|undefined|null|[0-9]+)$/)) {
            value = eval(value);
        }
        options[key] = value;
    });
    return options;
}

// makes a file in a path where directories may or may not have existed before
function mkfile(filepath, content, callback) {
    mkpath(path.dirname(filepath), function (err) {
        if (err) {
            return callback ? callback(err) : undefined;
        }
        fs.writeFile(filepath, content, callback);
    });
}

// compile the given stylus file
function compile(stylusFile, callback) {
    fs.readFile(stylusFile, 'utf8', function (err, buffer) {
        if (err) {
            return callback(err);
        }

        var content = buffer.toString(),
            stylusPath = path.dirname(stylusFile),
            cssFilename,
            cssFile,
            defaults = {
                compress: false,
                sourcemap: false,
                prefix: '',
                paths: [stylusPath]
            },
            options = extend(defaults, readOptions(content));

        // main is set: compile the referenced file instead
        if (options.main) {
            stylusFile = path.resolve(stylusPath, options.main);
            return compile(stylusFile, callback);
        }

        // out is null or false: do not compile
        if (options.out === null || options.out === false) {
            return callback();
        }

        // out is set: output to the given file name
        if (options.out) {
            cssFilename = options.out;
            if (path.extname(cssFilename) === '') {
                cssFilename += '.css';
            }
            delete options.out;
        } else {
            cssFilename = path.basename(stylusFile);
            cssFilename = cssFilename.substr(0, cssFilename.length - path.extname(cssFilename).length) + '.css';
        }

        cssFile = path.resolve(stylusPath, cssFilename);

        options.filename = cssFilename;
        var style = stylus(content, options);

        style.render(function (err, css) {
            if (err) {
                return callback(err);
            }

            mkfile(cssFile, css, function (err) {
                if (err) {
                    return callback(err);
                }
            });

            // write sourcemap
            if (options.sourcemap) {
                mkfile(cssFile + '.map', JSON.stringify(style.sourcemap), function (err) {
                    if (err) {
                        return callback(err);
                    }
                });
            }

            callback();
        });
    });
}

// set up service for brackets
function init(DomainManager) {
    if (!DomainManager.hasDomain('StylusCompiler')) {
        DomainManager.registerDomain('StylusCompiler', { major: 1, minor: 0 });
    }
    DomainManager.registerCommand(
        'StylusCompiler', // domain name
        'compile', // command name
        compile, // command handler function
        true, // this command is asynchronous
        'Compiles a stylus file',
        [{
            name: 'stylusFile',
            type: 'String',
            description: 'stylus filename'
        }, {
            name: 'callback',
            type: 'Function',
            description: 'callback function'
        }],
        null
    );
}

exports.init = init;
<|endoftext|>


<commit_before>const handlebars = require('handlebars');
const fs = require('fs');
const { promisify } = require('util');
const Hoek = require('hoek');
const bookshelf = require('../../lib/bookshelf');

module.exports = () => ({
  async fetchTemplate(clientId, page) {
    Hoek.assert(clientId, new Error('clientId is required in ThemeService::fetchTemplate'));

    const client = await bookshelf.model('client')
      .where({client_id: clientId})
      .fetch({ withRelated: ['theme.templates.layout'] });

    // scenario 1, client has null theme
    if (!client.get('theme_id')) return false;

    // scenario 2, client has theme but null template
    const template = client.related('theme').related('templates').find(template => template.get('name') === page);
    return template || false;
  },

  async getThemedTemplate(clientId, page, context) {
    Hoek.assert(clientId, new Error('clientId is required in ThemeService::getThemedTemplate'));
    const template = await this.fetchTemplate(clientId, page);
    if (!template) return false;

    const renderedTemplate = await template.render(page, context);
    // const serializedTemplate = template.serialize();

    // serializedTemplate.rendered_code = renderedTemplate;
    // return serializedTemplate;

    return {
      template,
      renderedTemplate,
    }
  },

  async renderThemedTemplate(clientId, page, context) {
    Hoek.assert(clientId, new Error('clientId is required in ThemeService::renderThemedTemplate'));

    const template = await this.fetchTemplate(clientId, page);
    if (!template) return false;

    const renderedTemplate = await template.render(page, context);
    return renderedTemplate;
  }
});

module.exports['@singleton'] = true;
module.exports['@require'] = [];
<commit_msg>Fix template query<commit_after>const Hoek = require('hoek');
const bookshelf = require('../../lib/bookshelf');

module.exports = () => ({
  async fetchTemplate(clientId, page) {
    Hoek.assert(clientId, new Error('clientId is required in ThemeService::fetchTemplate'));

    const client = await bookshelf.model('client')
      .where({client_id: clientId})
      .fetch();

    // scenario 1, client has null theme
    if (!client.get('theme_id')) return false;

    // scenario 2, client has theme but null template
    const template = await bookshelf.model('template').where({
      theme_id: client.get('theme_id'),
      name: page,
    }).fetch({withRelated: ['layout']});

    return template || false;
  },

  async getThemedTemplate(clientId, page, context) {
    Hoek.assert(clientId, new Error('clientId is required in ThemeService::getThemedTemplate'));
    const template = await this.fetchTemplate(clientId, page);
    if (!template) return false;

    const renderedTemplate = await template.render(page, context);

    return {
      template,
      renderedTemplate,
    };
  },

  async renderThemedTemplate(clientId, page, context) {
    Hoek.assert(clientId, new Error('clientId is required in ThemeService::renderThemedTemplate'));

    const template = await this.fetchTemplate(clientId, page);
    if (!template) return false;

    const renderedTemplate = await template.render(page, context);
    return renderedTemplate;
  }
});

module.exports['@singleton'] = true;
module.exports['@require'] = [];
<|endoftext|>


<commit_before>window.loadContributors = () => {
    $('.file-header').each((_, header) => {
        $(header).find('.file-actions a.btn:contains("View")').each((_, anchor) => {
            $.get($(anchor).attr('href')).done(function (data) {
                var contributors = $(data).find('.commit-tease-contributors');
                $(contributors).css({'margin-top': '0px', 'border-top': 'none'});
                $(contributors).find('.contributors-toggle').contents()[0].textContent = 'File has ';
                var bar = $('

').append($(contributors)[0]);
                $(bar).css('padding-top', '0px');
                $(header).after($(bar));
            });
        });
    });
}
<commit_msg>Prevent doube loading of contributor listing<commit_after>window.loadContributors = () => {
    $('.file-header').each((_, header) => {
        if (!$(header).next().hasClass("contributor-bar")) {
            $(header).find('.file-actions a.btn:contains("View")').each((_, anchor) => {
                $.get($(anchor).attr('href')).done(function (data) {
                    var contributors = $(data).find('.commit-tease-contributors');
                    $(contributors).css({'margin-top': '0px', 'border-top': 'none'});
                    $(contributors).find('.contributors-toggle').contents()[0].textContent = 'File has ';
                    var bar = $('

').append($(contributors)[0]);
                    $(bar).css('padding-top', '0px');
                    $(header).after($(bar));
                });
            });
        }
    });
}
<|endoftext|>


<commit_before>import express from 'express';
import session from 'express-session';
import bodyParser from 'body-parser';
import config from '../src/config';
import * as actions from './actions/index';
import {mapUrl} from './utils/common.js';
import PrettyError from 'pretty-error';
import http from 'http';
import SocketIo from 'socket.io';
import DB from './lib/db-interface.js';
import sitemap from './lib/sitemap.js';
const MongoStore = require('connect-mongo')(session);
import {logger} from './lib/logger';
var cors = require('cors');

var mongoModel = require('./lib/model.js')
var mongoConnection = mongoModel.initMongoDb()

const pretty = new PrettyError();
const app = express();

const server = new http.Server(app);

const io = new SocketIo(server);

app.use(bodyParser.json());

var corsOptions = { credentials : false}
app.use(cors(corsOptions));

app.use((req, res) => {
  logger.info("get request :", req.url)

  const splittedUrlPath = req.url.split('?')[0].split('/').slice(1);

  const {action, params} = mapUrl(actions, splittedUrlPath);

  if (action) {
    action(req, params, io)
      .then((result) => {
        if (result instanceof Function) {
          result(res);
        } else {
          res.json(result);
        }
      }, (reason) => {
        if (reason && reason.redirect) {
          res.redirect(reason.redirect);
        } else {
          logger.error('API ERROR:', pretty.render(reason));
          res.status(reason.status || 500).json(reason);
        }
      });
  } else {
    res.status(404).end('NOT FOUND');
  }
});

const bufferSize = 100;
const messageBuffer = new Array(bufferSize);
let messageIndex = 0;

if (config.apiPort) {
  const runnable = app.listen(config.apiPort, (err) => {
    if (err) {
      logger.error(err);
    }
    logger.info('----\n==> 🌎  API is running on port %s', config.apiPort);
    logger.info('==> 💻  Send requests to http://%s:%s', config.apiHost, config.apiPort);
  });
  app.set('socketio', io);
  app.set('server', runnable);
  io.on('connection', (socket) => {

    console.log('a new customer connect to server')
    socket.emit('greet', {msg: `'Hello World!' from server`});

    socket.on('sendHelp', function(ev,data){
      socket.emit("sendHelpAsker" + data.asker, data)
    })

    socket.on('sendUpdate', function(ev,data){
      socket.emit('updateHelper' + data.helper, data)
    })
  });
  io.listen(runnable);
} else {
  logger.error('==>     ERROR: No PORT environment variable has been specified');
}
<commit_msg>update socket io<commit_after>import express from 'express';
import session from 'express-session';
import bodyParser from 'body-parser';
import config from '../src/config';
import * as actions from './actions/index';
import {mapUrl} from './utils/common.js';
import PrettyError from 'pretty-error';
import http from 'http';
import SocketIo from 'socket.io';
import DB from './lib/db-interface.js';
import sitemap from './lib/sitemap.js';
const MongoStore = require('connect-mongo')(session);
import {logger} from './lib/logger';
var cors = require('cors');

var mongoModel = require('./lib/model.js')
var mongoConnection = mongoModel.initMongoDb()

const pretty = new PrettyError();
const app = express();

const server = new http.Server(app);

const io = new SocketIo(server);

app.use(bodyParser.json());

var corsOptions = { credentials : false}
app.use(cors(corsOptions));

app.use((req, res) => {
  logger.info("get request :", req.url)

  const splittedUrlPath = req.url.split('?')[0].split('/').slice(1);

  const {action, params} = mapUrl(actions, splittedUrlPath);

  if (action) {
    action(req, params, io)
      .then((result) => {
        if (result instanceof Function) {
          result(res);
        } else {
          res.json(result);
        }
      }, (reason) => {
        if (reason && reason.redirect) {
          res.redirect(reason.redirect);
        } else {
          logger.error('API ERROR:', pretty.render(reason));
          res.status(reason.status || 500).json(reason);
        }
      });
  } else {
    res.status(404).end('NOT FOUND');
  }
});

const bufferSize = 100;
const messageBuffer = new Array(bufferSize);
let messageIndex = 0;

if (config.apiPort) {
  const runnable = app.listen(config.apiPort, (err) => {
    if (err) {
      logger.error(err);
    }
    logger.info('----\n==> 🌎  API is running on port %s', config.apiPort);
    logger.info('==> 💻  Send requests to http://%s:%s', config.apiHost, config.apiPort);
  });
  app.set('socketio', io);
  app.set('server', runnable);
  io.on('connection', (socket) => {

    console.log('a new customer connect to server')
    io.emit('greet', {msg: `'Hello World!' from server`});

    socket.on('sendHelp', function(data){
      logger.debug('sendHelp data is' , data)
      io.emit("sendHelpAsker" + data.asker, data)
    })

    socket.on('sendUpdate', function(data){
      logger.debug('sendUpdate data is' , data)
      io.emit('updateHelper' + data.helper, data)
    })
  });
  io.listen(runnable);
} else {
  logger.error('==>     ERROR: No PORT environment variable has been specified');
}
<|endoftext|>


<commit_before>import list from "./list";

export default function(circles) {
  return encloseN(list(circles), []);
}

function encloses(a, b) {
  var dr, dx, dy;
  return (dr = a.r - b.r) >= 0 && dr * dr + 1e-6 > (dx = b.x - a.x) * dx + (dy = b.y - a.y) * dy;
}

// Returns the smallest circle that contains circles L and intersects circles B.
function encloseN(L, B) {
  var circle,
      l0 = null,
      l1 = L.head,
      l2,
      p1;

  switch (B.length) {
    case 1: circle = enclose1(B[0]); break;
    case 2: circle = enclose2(B[0], B[1]); break;
    case 3: circle = enclose3(B[0], B[1], B[2]); break;
  }

  while (l1) {
    p1 = l1._, l2 = l1.next;
    if (!circle || !encloses(circle, p1)) {

      // Temporarily truncate L before l1.
      if (l0) L.tail = l0, l0.next = null;
      else L.head = L.tail = null;

      B.push(p1);
      circle = encloseN(L, B); // Note: reorders L!
      B.pop();

      // Move l1 to the front of L and reconnect the truncated list L.
      if (L.head) l1.next = L.head, L.head = l1;
      else l1.next = null, L.head = L.tail = l1;
      l0 = L.tail, l0.next = l2;

    } else {
      l0 = l1;
    }
    l1 = l2;
  }

  L.tail = l0;
  return circle;
}

function enclose1(a) {
  return {
    x: a.x,
    y: a.y,
    r: a.r
  };
}

function enclose2(a, b) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1,
      l = Math.sqrt(x21 * x21 + y21 * y21);
  return {
    x: (x1 + x2 + x21 / l * r21) / 2,
    y: (y1 + y2 + y21 / l * r21) / 2,
    r: (l + r1 + r2) / 2
  };
}

function enclose3(a, b, c) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x3 = c.x, y3 = c.y, r3 = c.r,
      a2 = 2 * (x1 - x2),
      b2 = 2 * (y1 - y2),
      c2 = 2 * (r2 - r1),
      d2 = x1 * x1 + y1 * y1 - r1 * r1 - x2 * x2 - y2 * y2 + r2 * r2,
      a3 = 2 * (x1 - x3),
      b3 = 2 * (y1 - y3),
      c3 = 2 * (r3 - r1),
      d3 = x1 * x1 + y1 * y1 - r1 * r1 - x3 * x3 - y3 * y3 + r3 * r3,
      ab = a3 * b2 - a2 * b3,
      xa = (b2 * d3 - b3 * d2) / ab - x1,
      xb = (b3 * c2 - b2 * c3) / ab,
      ya = (a3 * d2 - a2 * d3) / ab - y1,
      yb = (a2 * c3 - a3 * c2) / ab,
      A = xb * xb + yb * yb - 1,
      B = 2 * (xa * xb + ya * yb + r1),
      C = xa * xa + ya * ya - r1 * r1,
      r = (-B - Math.sqrt(B * B - 4 * A * C)) / (2 * A);
  return {
    x: xa + xb * r + x1,
    y: ya + yb * r + y1,
    r: r
  };
}
<commit_msg>Fix quadratic solution when A = 0.<commit_after>import list from "./list";

export default function(circles) {
  return encloseN(list(circles), []);
}

function encloses(a, b) {
  var dr, dx, dy;
  return (dr = a.r - b.r) >= 0 && dr * dr + 1e-6 > (dx = b.x - a.x) * dx + (dy = b.y - a.y) * dy;
}

// Returns the smallest circle that contains circles L and intersects circles B.
function encloseN(L, B) {
  var circle,
      l0 = null,
      l1 = L.head,
      l2,
      p1;

  switch (B.length) {
    case 1: circle = enclose1(B[0]); break;
    case 2: circle = enclose2(B[0], B[1]); break;
    case 3: circle = enclose3(B[0], B[1], B[2]); break;
  }

  while (l1) {
    p1 = l1._, l2 = l1.next;
    if (!circle || !encloses(circle, p1)) {

      // Temporarily truncate L before l1.
      if (l0) L.tail = l0, l0.next = null;
      else L.head = L.tail = null;

      B.push(p1);
      circle = encloseN(L, B); // Note: reorders L!
      B.pop();

      // Move l1 to the front of L and reconnect the truncated list L.
      if (L.head) l1.next = L.head, L.head = l1;
      else l1.next = null, L.head = L.tail = l1;
      l0 = L.tail, l0.next = l2;

    } else {
      l0 = l1;
    }
    l1 = l2;
  }

  L.tail = l0;
  return circle;
}

function enclose1(a) {
  return {
    x: a.x,
    y: a.y,
    r: a.r
  };
}

function enclose2(a, b) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1,
      l = Math.sqrt(x21 * x21 + y21 * y21);
  return {
    x: (x1 + x2 + x21 / l * r21) / 2,
    y: (y1 + y2 + y21 / l * r21) / 2,
    r: (l + r1 + r2) / 2
  };
}

function enclose3(a, b, c) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x3 = c.x, y3 = c.y, r3 = c.r,
      a2 = 2 * (x1 - x2),
      b2 = 2 * (y1 - y2),
      c2 = 2 * (r2 - r1),
      d2 = x1 * x1 + y1 * y1 - r1 * r1 - x2 * x2 - y2 * y2 + r2 * r2,
      a3 = 2 * (x1 - x3),
      b3 = 2 * (y1 - y3),
      c3 = 2 * (r3 - r1),
      d3 = x1 * x1 + y1 * y1 - r1 * r1 - x3 * x3 - y3 * y3 + r3 * r3,
      ab = a3 * b2 - a2 * b3,
      xa = (b2 * d3 - b3 * d2) / ab - x1,
      xb = (b3 * c2 - b2 * c3) / ab,
      ya = (a3 * d2 - a2 * d3) / ab - y1,
      yb = (a2 * c3 - a3 * c2) / ab,
      A = xb * xb + yb * yb - 1,
      B = 2 * (xa * xb + ya * yb + r1),
      C = xa * xa + ya * ya - r1 * r1,
      r = A ? (-B - Math.sqrt(B * B - 4 * A * C)) / (2 * A) : (-C / B);
  return {
    x: xa + xb * r + x1,
    y: ya + yb * r + y1,
    r: r
  };
}
<|endoftext|>


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

	var user = module.parent.require('./user'),
		meta = module.parent.require('./meta'),
		db = module.parent.require('../src/database'),
		passport = module.parent.require('passport'),
  		passportTwitter = require('passport-twitter').Strategy,
  		fs = module.parent.require('fs'),
  		path = module.parent.require('path'),
  		nconf = module.parent.require('nconf');

	var constants = Object.freeze({
		'name': "Twitter",
		'admin': {
			'route': '/plugins/sso-twitter',
			'icon': 'fa-twitter-square'
		}
	});

	var Twitter = {};

	Twitter.init = function(app, middleware, controllers) {
		function render(req, res, next) {
			res.render('admin/plugins/sso-twitter', {});
		}

		console.log('adding twitter routes!');
		app.get('/admin/plugins/sso-twitter', middleware.admin.buildHeader, render);
		app.get('/api/admin/plugins/sso-twitter', render);
	};

	Twitter.getStrategy = function(strategies, callback) {
		if (meta.config['social:twitter:key'] && meta.config['social:twitter:secret']) {
			passport.use(new passportTwitter({
				consumerKey: meta.config['social:twitter:key'],
				consumerSecret: meta.config['social:twitter:secret'],
				callbackURL: nconf.get('url') + '/auth/twitter/callback'
			}, function(token, tokenSecret, profile, done) {
				Twitter.login(profile.id, profile.username, profile.photos, function(err, user) {
					if (err) {
						return done(err);
					}
					done(null, user);
				});
			}));

			strategies.push({
				name: 'twitter',
				url: '/auth/twitter',
				callbackURL: '/auth/twitter/callback',
				icon: 'twitter',
				scope: ''
			});
		}

		callback(null, strategies);
	};

	Twitter.login = function(twid, handle, photos, callback) {
		Twitter.getUidByTwitterId(twid, function(err, uid) {
			if(err) {
				return callback(err);
			}

			if (uid !== null) {
				// Existing User
				callback(null, {
					uid: uid
				});
			} else {
				// New User
				user.create({username: handle}, function(err, uid) {
					if(err) {
						return callback(err);
					}

					// Save twitter-specific information to the user
					user.setUserField(uid, 'twid', twid);
					db.setObjectField('twid:uid', twid, uid);

					// Save their photo, if present
					if (photos && photos.length > 0) {
						var photoUrl = photos[0].value;
						photoUrl = path.dirname(photoUrl) + '/' + path.basename(photoUrl, path.extname(photoUrl)).slice(0, -6) + 'bigger' + path.extname(photoUrl);
						user.setUserField(uid, 'uploadedpicture', photoUrl);
						user.setUserField(uid, 'picture', photoUrl);
					}

					callback(null, {
						uid: uid
					});
				});
			}
		});
	};

	Twitter.getUidByTwitterId = function(twid, callback) {
		db.getObjectField('twid:uid', twid, function(err, uid) {
			if (err) {
				return callback(err);
			}
			callback(null, uid);
		});
	};

	Twitter.addMenuItem = function(custom_header) {
		custom_header.authentication.push({
			"route": constants.admin.route,
			"icon": constants.admin.icon,
			"name": constants.name
		});

		callback(null, custom_header);
	}

	// Twitter.addAdminRoute = function(custom_routes, callback) {
	// 	fs.readFile(path.resolve(__dirname, './static/admin.tpl'), function (err, template) {
	// 		custom_routes.routes.push({
	// 			"route": constants.admin.route,
	// 			"method": "get",
	// 			"options": function(req, res, callback) {
	// 				callback({
	// 					req: req,
	// 					res: res,
	// 					route: constants.admin.route,
	// 					name: constants.name,
	// 					content: template
	// 				});
	// 			}
	// 		});

	// 		callback(null, custom_routes);
	// 	});
	// };

	module.exports = Twitter;
}(module));
<commit_msg>fixed missing cb<commit_after>(function(module) {
	"use strict";

	var user = module.parent.require('./user'),
		meta = module.parent.require('./meta'),
		db = module.parent.require('../src/database'),
		passport = module.parent.require('passport'),
  		passportTwitter = require('passport-twitter').Strategy,
  		fs = module.parent.require('fs'),
  		path = module.parent.require('path'),
  		nconf = module.parent.require('nconf');

	var constants = Object.freeze({
		'name': "Twitter",
		'admin': {
			'route': '/plugins/sso-twitter',
			'icon': 'fa-twitter-square'
		}
	});

	var Twitter = {};

	Twitter.init = function(app, middleware, controllers) {
		function render(req, res, next) {
			res.render('admin/plugins/sso-twitter', {});
		}

		console.log('adding twitter routes!');
		app.get('/admin/plugins/sso-twitter', middleware.admin.buildHeader, render);
		app.get('/api/admin/plugins/sso-twitter', render);
	};

	Twitter.getStrategy = function(strategies, callback) {
		if (meta.config['social:twitter:key'] && meta.config['social:twitter:secret']) {
			passport.use(new passportTwitter({
				consumerKey: meta.config['social:twitter:key'],
				consumerSecret: meta.config['social:twitter:secret'],
				callbackURL: nconf.get('url') + '/auth/twitter/callback'
			}, function(token, tokenSecret, profile, done) {
				Twitter.login(profile.id, profile.username, profile.photos, function(err, user) {
					if (err) {
						return done(err);
					}
					done(null, user);
				});
			}));

			strategies.push({
				name: 'twitter',
				url: '/auth/twitter',
				callbackURL: '/auth/twitter/callback',
				icon: 'twitter',
				scope: ''
			});
		}

		callback(null, strategies);
	};

	Twitter.login = function(twid, handle, photos, callback) {
		Twitter.getUidByTwitterId(twid, function(err, uid) {
			if(err) {
				return callback(err);
			}

			if (uid !== null) {
				// Existing User
				callback(null, {
					uid: uid
				});
			} else {
				// New User
				user.create({username: handle}, function(err, uid) {
					if(err) {
						return callback(err);
					}

					// Save twitter-specific information to the user
					user.setUserField(uid, 'twid', twid);
					db.setObjectField('twid:uid', twid, uid);

					// Save their photo, if present
					if (photos && photos.length > 0) {
						var photoUrl = photos[0].value;
						photoUrl = path.dirname(photoUrl) + '/' + path.basename(photoUrl, path.extname(photoUrl)).slice(0, -6) + 'bigger' + path.extname(photoUrl);
						user.setUserField(uid, 'uploadedpicture', photoUrl);
						user.setUserField(uid, 'picture', photoUrl);
					}

					callback(null, {
						uid: uid
					});
				});
			}
		});
	};

	Twitter.getUidByTwitterId = function(twid, callback) {
		db.getObjectField('twid:uid', twid, function(err, uid) {
			if (err) {
				return callback(err);
			}
			callback(null, uid);
		});
	};

	Twitter.addMenuItem = function(custom_header, callback) {
		custom_header.authentication.push({
			"route": constants.admin.route,
			"icon": constants.admin.icon,
			"name": constants.name
		});

		callback(null, custom_header);
	}

	// Twitter.addAdminRoute = function(custom_routes, callback) {
	// 	fs.readFile(path.resolve(__dirname, './static/admin.tpl'), function (err, template) {
	// 		custom_routes.routes.push({
	// 			"route": constants.admin.route,
	// 			"method": "get",
	// 			"options": function(req, res, callback) {
	// 				callback({
	// 					req: req,
	// 					res: res,
	// 					route: constants.admin.route,
	// 					name: constants.name,
	// 					content: template
	// 				});
	// 			}
	// 		});

	// 		callback(null, custom_routes);
	// 	});
	// };

	module.exports = Twitter;
}(module));
<|endoftext|>


<commit_before>$(document).ready(function() {

	$(document).delegate('.treeexpand', 'click', function () {
		$(this).attr('src', '/img/tree/dhxmenu_loader.gif');
		var isLoaded = $(this).attr('data-loaded');
		if (isLoaded == "1") {
			$(this).siblings('ul').css('display', 'list-item');
		} else {
			var geographyId = $(this).attr('data-geographyid');
			loadTree(geographyId, $(this).parent());
			$(this).attr('data-loaded', '1');
		}
		$(this).removeClass('treeexpand');
		$(this).addClass('treecollapse');
		$(this).attr('src', '/img/tree/minus.gif');
	});

	$(document).delegate('.treecollapse', 'click', function () {
		$(this).siblings('ul').css('display', 'none');
		$(this).addClass('treeexpand');
		$(this).removeClass('treecollapse');
		$(this).attr('src', '/img/tree/plus.gif');
	});

	function getTree(el)
	{
		var id = $(el).attr('data-widgetid');
		var input = $('#' + id);
		var value = jQuery.parseJSON($(input).val());

		return value.tree;
	}

	function loadTree(geographyId, liParent)
	{
		var widgetId = $(liParent).parent().attr('data-widgetid');
		url = '/api/geography/children/' + geographyId;
		$.ajax({
			url: url,
			success: function (data) {
				var ul ='
';
				for (i=0; i<data.length; i++) {
					var name = data[i].geography;
					var childId = data[i].geographyid;
					var hasChildren = data[i].haschildren;

					var expandTag = '';

					var attrs = 'data-widgetid="' + widgetId + '" style="cursor:pointer" data-geographyid="' + childId + '" ';

					if (hasChildren == "1") {
						expandTag = '';
					} else {
						expandTag = '';
					}

					attrs =
			            'data-haschildren="' + hasChildren + '" ' +
			            'data-loaded="0" ' +
			            'data-state="2" ' +
			            'data-widgetid="' + widgetId + '" ' +
			            'style="cursor:pointer" ' +
			            'class="treeitemselect" ' +
			            'data-geographyid="' + childId + '"';

					var checkTag = ' ';
					ul +=
						 '
' +
						 expandTag +
						 checkTag +
						 name +
						 '
';
				}
				ul += '
';
				$(liParent).append(ul);
			}
		});
	}
});

<commit_msg>Add spinner widget<commit_after>$(document).ready(function() {

	$(document).delegate('.treeexpand', 'click', function () {
		$(this).attr('src', '/img/tree/dhxmenu_loader.gif');
		var isLoaded = $(this).attr('data-loaded');
		if (isLoaded == "1") {
			$(this).siblings('ul').css('display', 'list-item');
			$(this).attr('src', '/img/tree/minus.gif');
		} else {
			var geographyId = $(this).attr('data-geographyid');
			loadTree(geographyId, $(this));
			$(this).attr('data-loaded', '1');
		}
		$(this).removeClass('treeexpand');
		$(this).addClass('treecollapse');
	});

	$(document).delegate('.treecollapse', 'click', function () {
		$(this).siblings('ul').css('display', 'none');
		$(this).addClass('treeexpand');
		$(this).removeClass('treecollapse');
		$(this).attr('src', '/img/tree/plus.gif');
	});

	function getTree(el)
	{
		var id = $(el).attr('data-widgetid');
		var input = $('#' + id);
		var value = jQuery.parseJSON($(input).val());

		return value.tree;
	}

	function loadTree(geographyId, imageClicked)
	{
		liParent = $(imageClicked).parent();

		var widgetId = $(liParent).parent().attr('data-widgetid');
		url = '/api/geography/children/' + geographyId;
		$.ajax({
			url: url,
			success: function (data) {
				var ul ='
';
				for (i=0; i<data.length; i++) {
					var name = data[i].geography;
					var childId = data[i].geographyid;
					var hasChildren = data[i].haschildren;

					var expandTag = '';

					var attrs = 'data-widgetid="' + widgetId + '" style="cursor:pointer" data-geographyid="' + childId + '" ';

					if (hasChildren == "1") {
						expandTag = '';
					} else {
						expandTag = '';
					}

					attrs =
			            'data-haschildren="' + hasChildren + '" ' +
			            'data-loaded="0" ' +
			            'data-state="2" ' +
			            'data-widgetid="' + widgetId + '" ' +
			            'style="cursor:pointer" ' +
			            'class="treeitemselect" ' +
			            'data-geographyid="' + childId + '"';

					var checkTag = ' ';
					ul +=
						 '
' +
						 expandTag +
						 checkTag +
						 name +
						 '
';
				}
				ul += '
';
				$(liParent).append(ul);
				$(imageClicked).attr('src', '/img/tree/minus.gif');
			}
		});
	}
});

<|endoftext|>