<commit_before>// WARNING: This is a generated file.
//          If you edit it you will be sad.
//          Edit src/app.js instead.

var go = {};
go;

go.app = function() {
    var vumigo = require('vumigo_v02');
    var App = vumigo.App;
    var Choice = vumigo.states.Choice;
    var ChoiceState = vumigo.states.ChoiceState;
    var EndState = vumigo.states.EndState;
    var FreeText = vumigo.states.FreeText;
    var JsonApi = vumigo.http.api.JsonApi;
    var PaginatedChoiceState = vumigo.states.PaginatedChoiceState;
    var _ = require("lodash");

    var GoApp = App.extend(function(self) {
        App.call(self, 'states:start');

        self.init = function() {
            self.http = new JsonApi(self.im);
        };

        function capitaliseLocation(string) {
            return string.replace(/\w\S*/g, function(s){
                return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();
            });
        }

        self.states.add('states:start', function(name) {
            return new ChoiceState(name, {
                question: 'Welcome to Wazimap! What would you like to do?',

                choices: [
                    new Choice('states:location', 'Enter a location to query'),
                    new Choice ('states:randomLocation', 'Query a random location'),
                    new Choice('states:end', 'Exit')],

                next: function(choice) {
                   return choice.value;
                }
            });
        });

        self.states.add('states:location', function(name) {
            return new FreeText(name, {
                question: 'Please enter a location on National, Provincial or Ward level to query:',
                next: function(content) {
                    return self
                    .http.get('http://wazimap.co.za/place-search/json/', {
                        params: {q : content}
                    })
                    .then (function(response) {
                        if (response.data.results.length === 0) {
                            return 'states:incorrect_location';
                        } else {
                            return {
                                name: 'states:results',
                                creator_opts: {
                                    locations: response.data.results,
                                    location_input: content
                                }
                            };
                        }
                    });
                }
            });
        });

        self.states.add('states:incorrect_location', function(name) {
            return new ChoiceState(name, {
                question: 'Location not found. Would you like to:',

                choices: [
                    new Choice('states:location', 'Enter a different location'),
                    new Choice('states:start', 'Go to Main Menu'),
                    new Choice('states:end', 'Exit')],

                next: function(choice) {
                    return choice.value;
                }
            });
        });

        self.states.add('states:results', function(name, opts) {
            var location_choices = _.map(opts.locations, function(d) {
                return new Choice(d.full_geoid, d.full_name);
            });

            return new PaginatedChoiceState(name, {
                question: 'Select the location you would like to query:',
                choices: location_choices,
                characters_per_page: 160,
                options_per_page : null,
                more: 'Next',
                back: 'Back',
                next: function(choice) {
                    return {
                        name: 'states:retrieve-location',
                        creator_opts : {
                            full_geoid : choice.value,
                            full_name : choice.label,
                            location_input: opts.location_input
                        }
                    };
                }
            });
        });

        self.states.add('states:retrieve-location', function(name, opts) {
            return self
                .http.get('http://wazimap.co.za/profiles/' + opts.full_geoid + '.json')
                .then(function(response) {
                    opts.data = response.data;
                    return  self.states.create(
                        'states:select-section', opts, opts.location_input);
                });
        });

        self.states.add('states:select-section', function(name, opts) {
            return new ChoiceState(name, {
                question: 'I would like to query:',
                choices: [
                    new Choice('elections', 'Elections'),
                    new Choice('demographics', 'Demographics'),
                    new Choice('households', 'Households'),
                    new Choice('service_delivery', 'Service Delivery'),
                    new Choice('economics', 'Economics'),
                    new Choice('education', 'Education'),
                    new Choice('children', 'Children'),
                    new Choice('child_households', 'Child-headed Households')
                ],
                next: function(choice) {
                    return {
                        name: 'states:display-data',
                        creator_opts : {
                            section_name : choice.label,
                            section_id : choice.value,
                            opts_data : opts.data,
                            location_name : opts.full_name,
                            location_id : opts.full_geoid,
                            location_input: opts.location_input
                        }
                    };
                }
            });
        });

        function sub_section(data, section_id) {
            return sub_section[section_id](data);
        }

        sub_section.elections = function(data) {
            var provincial_parties =_(data.provincial_2014.party_distribution)
              .omit('metadata')
              .sortBy(function(o) { return -o.values.this; })
              .slice(0, 3)
              .value();

            var provincial_party_results = _.map(provincial_parties, function(s) {
                return (" " + s.name + " " + s.values.this + "%").toString();
            });

            var national_parties =_(data.national_2014.party_distribution)
              .omit('metadata')
              .sortBy(function(o) { return -o.values.this; })
              .slice(0, 3)
              .value();

            var national_party_results = _.map(national_parties, function(s) {
                return (" " + s.name + " " + s.values.this + "%").toString();
            });

            return [
                data.provincial_2014.name + ":",
                "Registered voters = " + data.provincial_2014.registered_voters.values.this,
                data.provincial_2014.average_turnout.values.this + "% cast their vote",
                "Results:" + provincial_party_results,
                data.national_2014.name + ":",
                "Registered voters = " + data.national_2014.registered_voters.values.this,
                data.national_2014.average_turnout.values.this + "% cast their vote",
                "Results:" + national_party_results
            ].join("\n");
        };

        sub_section.demographics = function(data) {
            return [
                "Area population: " + data.total_population.values.this,
                "People/square km: " + data.population_density.values.this,
                "RSA Citizens: " + data.citizenship_south_african.values.this + "%",
                "Female (" + data.sex_ratio.Female.values.this + "%) Male (" + data.sex_ratio.Male.values.this + "%)",
                "Black African (" + data.population_group_distribution['Black African'].values.this + "%) Coloured (" + data.population_group_distribution.Coloured.values.this + "%) Indian/Asian (" + data.population_group_distribution['Indian or Asian'].values.this + "%) White (" + data.population_group_distribution.White.values.this + "%)",
                //"Most spoken language: " + data.language_most_spoken.name,
                "Afrikaans (" + data.language_distribution.Afrikaans.values.this + "%) English (" + data.language_distribution.English.values.this + "%) IsiXhosa (" + data.language_distribution.IsiXhosa.values.this + "%) IsiZulu (" + data.language_distribution.IsiZulu.values.this + "%)",
                "Age: <18 (" + data.age_category_distribution['Under 18'].values.this + "%) 18-64 (" + data.age_category_distribution["18 to 64"].values.this + "%) 65+ (" + data.age_category_distribution["65 and over"].values.this + "%)",
                "Born in RSA: " + data.born_in_south_africa.values.this + "%"
            ].join("\n");
        };

        sub_section.households = function(data) {
            return [
                "Informal Dwellings: " + data.informal.values.this + "%",
                "Owned and paid off: " + data.tenure_distribution["Owned and fully paid off"].values.this + "%",
                "Rented: " + data.tenure_distribution.Rented.values.this + "%",
                "Median Annual Income: R" + data.median_annual_income.values.this,
                "Total Households: " + data.total_households.values.this,
                "Head of Household: <18 (" + data.head_of_household.under_18.values.this + "%) Female (" + data.head_of_household.female.values.this + "%)",
                "Own car: " + data.household_goods.Car.values.this + "%"
            ].join("\n");
        };

        sub_section.service_delivery = function(data) {
            return [
                "Flush toilet access: " + data.percentage_flush_toilet_access.values.this + "%",
                "Electricity access: " + data.percentage_electricity_access.values.this + "%",
                "Refuse disposal: " + data.percentage_ref_disp_from_service_provider.values.this + "%"
            ].join("\n");
        };

        sub_section.economics = function(data) {
            return [
                "Median individual income: R" + data.median_individual_income.values.this,
                "Home internet access: " + data.internet_access.values.this + "%",
                "Work in formal sector: " + data.sector_type_distribution["In the formal sector"].values.this + "%",
                "Work in informal sector: " + data.sector_type_distribution["In the informal sector"].values.this + "%",
                "Discouraged work seeker: " + data.employment_status["Discouraged work-seeker"].values.this + "%",
                "Employed: " + data.employment_status.Employed.values.this + "%",
                "Not economically active: " + data.employment_status["Other not economically active"].values.this + "%",
                "Unemployed: " + data.employment_status.Unemployed.values.this + "%"
            ].join("\n");
        };

        sub_section.education = function(data) {
            return [
                "None: " + data.educational_attainment_distribution.None.values.this + "%",
                "Primary: " + data.educational_attainment_distribution.Primary.values.this + "%",
                "Some secondary: " + data.educational_attainment_distribution['Some secondary'].values.this + "%",
                "Grade 12 (Matric): " + data.educational_attainment_distribution['Grade 12 (Matric)'].values.this + "%",
                "Undergrad: " + data.educational_attainment_distribution.Undergrad.values.this + "%",
                "Post-grad: " + data.educational_attainment_distribution['Post-grad'].values.this + "%"
            ].join("\n");
        };

        sub_section.children = function(data) {
            return [
                "Child population: " + data.demographics.total_children.values.this,
                "Children (<18): " + data.demographics.child_adult_distribution['Children (< 18)'].values.this + "%",
                "Female (" + data.demographics.gender_distribution.Female.values.this + "%) Male (" + data.demographics.gender_distribution.Male.values.this + "%)",
                "<14 with no living biological parents: " + data.demographics.percent_no_parent.values.this + "%",
                "Ages 5-17 in school: " + data.school.percent_school_attendance.values.this + "%",
                "Ages 15-17 in labour force: " + data.employment.percent_in_labour_force.values.this + "%",
                "Ave monthly income of employed: R" + data.employment.median_income.values.this
            ].join("\n");
        };

        sub_section.child_households = function(data) {
            return [
                "Total households: " + data.total_households.values.this,
                "In informal dwellings: " + data.informal.values.this + "%",
                "Women as head: " + data.head_of_household.female.values.this + "%",
                "Ave annual household income: R" + data.median_annual_income.values.this
            ].join("\n");
        };

        self.states.add('states:display-data', function(name, opts) {
            var section_data = opts.opts_data[opts.section_id];
            var return_text = sub_section(section_data, opts.section_id);

            return new ChoiceState(name, {
                question: 'You have chosen to query ' + opts.section_name + ' in ' + capitaliseLocation(opts.location_input),

                choices: [
                    new Choice('states:sms', 'SMS details to me'),
                    new Choice('states:select-section', 'Query another section'),
                    new Choice('states:start', 'Main Menu'),
                    new Choice('states:end', 'Exit')],

                next: function(choice) {
                    if (choice.value == 'states:start' || choice.value == 'states:end') {
                        return choice.value;
                    } else if (choice.value == 'states:select-section'){
                        return {
                            name: choice.value,
                            creator_opts: {
                                section_id : opts.section_id,
                                section_data : section_data
                            }
                        };
                    } else if (choice.value == "states:sms") {
                        return {
                            name: choice.value,
                            creator_opts: {
                                location_input: opts.location_input,
                                return_text : return_text,
                                section_name : opts.section_name,
                                location_id : opts.location_id
                            }
                        };
                    }
                }
            });
        });

        self.states.add('states:sms', function(name, opts) {
            return self.im
                .outbound.send_to_user({
                endpoint: 'sms',
                content: [
                    capitaliseLocation(opts.location_input) + " " + opts.section_name + ":",
                    opts.return_text,
                    'Wazimap USSD: *120*8864*1601#',
                    'www.wazimap.co.za'
                ].join('\n'),
            })
            .then(function() {
                return self.states.create(
                    'states:end');
            });
        });

        self.states.add('states:randomLocation', function(name) {
            return new EndState(name, {
                text: 'Random locations coming soon!',
                next: 'states:start'
            });
        });

        self.states.add('states:end', function(name) {
            return new EndState(name, {
                text: 'Thank you for using Wazimap! Find more information on www.wazimap.co.za',
                next: 'states:start'
            });
        });
    });

    return {
        GoApp: GoApp
    };

}();

go.init = function() {
    var vumigo = require('vumigo_v02');
    var InteractionMachine = vumigo.InteractionMachine;
    var GoApp = go.app.GoApp;

    return {
        im: new InteractionMachine(api, new GoApp())
    };
}();
<commit_msg>Line spacing fixed.<commit_after>// WARNING: This is a generated file.
//          If you edit it you will be sad.
//          Edit src/app.js instead.

var go = {};
go;

go.app = function() {
    var vumigo = require('vumigo_v02');
    var App = vumigo.App;
    var Choice = vumigo.states.Choice;
    var ChoiceState = vumigo.states.ChoiceState;
    var EndState = vumigo.states.EndState;
    var FreeText = vumigo.states.FreeText;
    var JsonApi = vumigo.http.api.JsonApi;
    var PaginatedChoiceState = vumigo.states.PaginatedChoiceState;
    var _ = require("lodash");

    var GoApp = App.extend(function(self) {
        App.call(self, 'states:start');

        self.init = function() {
            self.http = new JsonApi(self.im);
        };

        function capitaliseLocation(string) {
            return string.replace(/\w\S*/g, function(s){
                return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();
            });
        }

        self.states.add('states:start', function(name) {
            return new ChoiceState(name, {
                question: 'Welcome to Wazimap! What would you like to do?',

                choices: [
                    new Choice('states:location', 'Enter a location to query'),
                    new Choice ('states:randomLocation', 'Query a random location'),
                    new Choice('states:end', 'Exit')],

                next: function(choice) {
                   return choice.value;
                }
            });
        });

        self.states.add('states:location', function(name) {
            return new FreeText(name, {
                question: 'Please enter a location on National, Provincial or Ward level to query:',
                next: function(content) {
                    return self
                    .http.get('http://wazimap.co.za/place-search/json/', {
                        params: {q : content}
                    })
                    .then (function(response) {
                        if (response.data.results.length === 0) {
                            return 'states:incorrect_location';
                        } else {
                            return {
                                name: 'states:results',
                                creator_opts: {
                                    locations: response.data.results,
                                    location_input: content
                                }
                            };
                        }
                    });
                }
            });
        });

        self.states.add('states:incorrect_location', function(name) {
            return new ChoiceState(name, {
                question: 'Location not found. Would you like to:',

                choices: [
                    new Choice('states:location', 'Enter a different location'),
                    new Choice('states:start', 'Go to Main Menu'),
                    new Choice('states:end', 'Exit')],

                next: function(choice) {
                    return choice.value;
                }
            });
        });

        self.states.add('states:results', function(name, opts) {
            var location_choices = _.map(opts.locations, function(d) {
                return new Choice(d.full_geoid, d.full_name);
            });

            return new PaginatedChoiceState(name, {
                question: 'Select the location you would like to query:',
                choices: location_choices,
                characters_per_page: 160,
                options_per_page : null,
                more: 'Next',
                back: 'Back',
                next: function(choice) {
                    return {
                        name: 'states:retrieve-location',
                        creator_opts : {
                            full_geoid : choice.value,
                            full_name : choice.label,
                            location_input: opts.location_input
                        }
                    };
                }
            });
        });

        self.states.add('states:retrieve-location', function(name, opts) {
            return self
                .http.get('http://wazimap.co.za/profiles/' + opts.full_geoid + '.json')
                .then(function(response) {
                    opts.data = response.data;
                    return  self.states.create(
                        'states:select-section', opts, opts.location_input);
                });
        });

        self.states.add('states:select-section', function(name, opts) {
            return new ChoiceState(name, {
                question: 'I would like to query:',
                choices: [
                    new Choice('elections', 'Elections'),
                    new Choice('demographics', 'Demographics'),
                    new Choice('households', 'Households'),
                    new Choice('service_delivery', 'Service Delivery'),
                    new Choice('economics', 'Economics'),
                    new Choice('education', 'Education'),
                    new Choice('children', 'Children'),
                    new Choice('child_households', 'Child-headed Households')
                ],
                next: function(choice) {
                    return {
                        name: 'states:display-data',
                        creator_opts : {
                            section_name : choice.label,
                            section_id : choice.value,
                            opts_data : opts.data,
                            location_name : opts.full_name,
                            location_id : opts.full_geoid,
                            location_input: opts.location_input
                        }
                    };
                }
            });
        });

        function sub_section(data, section_id) {
            return sub_section[section_id](data);
        }

        sub_section.elections = function(data) {
            var provincial_parties =_(data.provincial_2014.party_distribution)
              .omit('metadata')
              .sortBy(function(o) { return -o.values.this; })
              .slice(0, 3)
              .value();

            var provincial_party_results = _.map(provincial_parties, function(s) {
                return (" " + s.name + " " + s.values.this + "%").toString();
            });

            var national_parties =_(data.national_2014.party_distribution)
              .omit('metadata')
              .sortBy(function(o) { return -o.values.this; })
              .slice(0, 3)
              .value();

            var national_party_results = _.map(national_parties, function(s) {
                return (" " + s.name + " " + s.values.this + "%").toString();
            });

            return [
                data.provincial_2014.name + ":",
                "Registered voters = " + data.provincial_2014.registered_voters.values.this,
                data.provincial_2014.average_turnout.values.this + "% cast their vote",
                "Results:" + provincial_party_results,
                data.national_2014.name + ":",
                "Registered voters = " + data.national_2014.registered_voters.values.this,
                data.national_2014.average_turnout.values.this + "% cast their vote",
                "Results:" + national_party_results
            ].join("\n");
        };

        sub_section.demographics = function(data) {
            return [
                "Area population: " + data.total_population.values.this,
                "People/square km: " + data.population_density.values.this,
                "RSA Citizens: " + data.citizenship_south_african.values.this + "%",
                "Female (" + data.sex_ratio.Female.values.this + "%) Male (" + data.sex_ratio.Male.values.this + "%)",
                "Black African (" + data.population_group_distribution['Black African'].values.this + "%) Coloured (" + data.population_group_distribution.Coloured.values.this + "%) Indian/Asian (" + data.population_group_distribution['Indian or Asian'].values.this + "%) White (" + data.population_group_distribution.White.values.this + "%)",
                //"Most spoken language: " + data.language_most_spoken.name,
                "Afrikaans (" + data.language_distribution.Afrikaans.values.this + "%) English (" + data.language_distribution.English.values.this + "%) IsiXhosa (" + data.language_distribution.IsiXhosa.values.this + "%) IsiZulu (" + data.language_distribution.IsiZulu.values.this + "%)",
                "Age: <18 (" + data.age_category_distribution['Under 18'].values.this + "%) 18-64 (" + data.age_category_distribution["18 to 64"].values.this + "%) 65+ (" + data.age_category_distribution["65 and over"].values.this + "%)",
                "Born in RSA: " + data.born_in_south_africa.values.this + "%"
            ].join("\n");
        };

        sub_section.households = function(data) {
            return [
                "Informal Dwellings: " + data.informal.values.this + "%",
                "Owned and paid off: " + data.tenure_distribution["Owned and fully paid off"].values.this + "%",
                "Rented: " + data.tenure_distribution.Rented.values.this + "%",
                "Median Annual Income: R" + data.median_annual_income.values.this,
                "Total Households: " + data.total_households.values.this,
                "Head of Household: <18 (" + data.head_of_household.under_18.values.this + "%) Female (" + data.head_of_household.female.values.this + "%)",
                "Own car: " + data.household_goods.Car.values.this + "%"
            ].join("\n");
        };

        sub_section.service_delivery = function(data) {
            return [
                "Flush toilet access: " + data.percentage_flush_toilet_access.values.this + "%",
                "Electricity access: " + data.percentage_electricity_access.values.this + "%",
                "Refuse disposal: " + data.percentage_ref_disp_from_service_provider.values.this + "%"
            ].join("\n");
        };

        sub_section.economics = function(data) {
            return [
                "Median individual income: R" + data.median_individual_income.values.this,
                "Home internet access: " + data.internet_access.values.this + "%",
                "Work in formal sector: " + data.sector_type_distribution["In the formal sector"].values.this + "%",
                "Work in informal sector: " + data.sector_type_distribution["In the informal sector"].values.this + "%",
                "Discouraged work seeker: " + data.employment_status["Discouraged work-seeker"].values.this + "%",
                "Employed: " + data.employment_status.Employed.values.this + "%",
                "Not economically active: " + data.employment_status["Other not economically active"].values.this + "%",
                "Unemployed: " + data.employment_status.Unemployed.values.this + "%"
            ].join("\n");
        };

        sub_section.education = function(data) {
            return [
                "None: " + data.educational_attainment_distribution.None.values.this + "%",
                "Primary: " + data.educational_attainment_distribution.Primary.values.this + "%",
                "Some secondary: " + data.educational_attainment_distribution['Some secondary'].values.this + "%",
                "Grade 12 (Matric): " + data.educational_attainment_distribution['Grade 12 (Matric)'].values.this + "%",
                "Undergrad: " + data.educational_attainment_distribution.Undergrad.values.this + "%",
                "Post-grad: " + data.educational_attainment_distribution['Post-grad'].values.this + "%"
            ].join("\n");
        };

        sub_section.children = function(data) {
            return [
                "Child population: " + data.demographics.total_children.values.this,
                "Children (<18): " + data.demographics.child_adult_distribution['Children (< 18)'].values.this + "%",
                "Female (" + data.demographics.gender_distribution.Female.values.this + "%) Male (" + data.demographics.gender_distribution.Male.values.this + "%)",
                "<14 with no living biological parents: " + data.demographics.percent_no_parent.values.this + "%",
                "Ages 5-17 in school: " + data.school.percent_school_attendance.values.this + "%",
                "Ages 15-17 in labour force: " + data.employment.percent_in_labour_force.values.this + "%",
                "Ave monthly income of employed: R" + data.employment.median_income.values.this
            ].join("\n");
        };

        sub_section.child_households = function(data) {
            return [
                "Total households: " + data.total_households.values.this,
                "In informal dwellings: " + data.informal.values.this + "%",
                "Women as head: " + data.head_of_household.female.values.this + "%",
                "Ave annual household income: R" + data.median_annual_income.values.this
            ].join("\n");
        };

        self.states.add('states:display-data', function(name, opts) {
            var section_data = opts.opts_data[opts.section_id];
            var return_text = sub_section(section_data, opts.section_id);

            return new ChoiceState(name, {
                question: 'You have chosen to query ' + opts.section_name + ' in ' + capitaliseLocation(opts.location_input),

                choices: [
                    new Choice('states:sms', 'SMS details to me'),
                    new Choice('states:select-section', 'Query another section'),
                    new Choice('states:start', 'Main Menu'),
                    new Choice('states:end', 'Exit')],

                next: function(choice) {
                    if (choice.value == 'states:start' || choice.value == 'states:end') {
                        return choice.value;
                    } else if (choice.value == 'states:select-section'){
                        return {
                            name: choice.value,
                            creator_opts: {
                                section_id : opts.section_id,
                                section_data : section_data
                            }
                        };
                    } else if (choice.value == "states:sms") {
                        return {
                            name: choice.value,
                            creator_opts: {
                                location_input: opts.location_input,
                                return_text : return_text,
                                section_name : opts.section_name,
                                location_id : opts.location_id
                            }
                        };
                    }
                }
            });
        });

        self.states.add('states:sms', function(name, opts) {
            return self.im
                .outbound.send_to_user({
                endpoint: 'sms',
                content: [
                    capitaliseLocation(opts.location_input) + " " + opts.section_name + ":",
                    opts.return_text,
                    'Wazimap USSD: *120*8864*1601#',
                    'www.wazimap.co.za'
                ].join('\n'),
            })
            .then(function() {
                return self.states.create(
                    'states:end');
            });
        });

        self.states.add('states:randomLocation', function(name) {
            return new EndState(name, {
                text: 'Random locations coming soon!',
                next: 'states:start'
            });
        });

        self.states.add('states:end', function(name) {
            return new EndState(name, {
                text: 'Thank you for using Wazimap! Find more information on www.wazimap.co.za',
                next: 'states:start'
            });
        });
    });

    return {
        GoApp: GoApp
    };
}();

go.init = function() {
    var vumigo = require('vumigo_v02');
    var InteractionMachine = vumigo.InteractionMachine;
    var GoApp = go.app.GoApp;

    return {
        im: new InteractionMachine(api, new GoApp())
    };
}();
<|endoftext|>


<commit_before>// WARNING: This is a generated file.
//          If you edit it you will be sad.
//          Edit src/app.js instead.

var go = {};
go;

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.rht = {
    // Registration of Head Teacher States

    state_rht_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_rht_exit';
                } else {
                    return 'state_rht_exit';
                }
            }
        });
    },

    state_rht_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_rht_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.rdo = {
    // Registration of Head Teacher States

    state_rdo_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_rdo_exit';
                } else {
                    return 'state_rdo_exit';
                }
            }
        });
    },

    state_rdo_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_rdo_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.cm = {
    // Registration of Head Teacher States

    state_cm_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_cm_exit';
                } else {
                    return 'state_cm_exit';
                }
            }
        });
    },

    state_cm_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_cm_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.lp = {
    // LearnerPerformance States

    state_lp_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_lp_next';
                } else {
                    return 'state_lp_exit';
                }
            }
        });
    },

    state_lp_next: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('to_tp', 'Switch to TeacherPerformance'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'to_tp') {
                    return 'state_tp_start'; // Switch to TP
                } else {
                    return 'state_lp_exit';
                }
            }
        });
    },

    state_lp_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_lp_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.tp = {
    // TeacherPerformance States

    state_tp_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_tp_next';
                } else {
                    return 'state_tp_exit';
                }
            }
        });
    },

    state_tp_next: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('again', 'Back to beginning'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'again') {
                    return 'state_tp_start';
                } else {
                    return 'state_tp_exit';
                }
            }
        });
    },

    state_tp_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_tp_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.sp = {
    // LearnerPerformance States

    state_sp_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_sp_next';
                } else {
                    return 'state_sp_exit';
                }
            }
        });
    },

    state_sp_next: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('to_tp', 'Switch to TeacherPerformance'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'to_tp') {
                    return 'state_tp_start'; // Switch to TP
                } else {
                    return 'state_sp_exit';
                }
            }
        });
    },

    state_sp_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_sp_start'
        });
    }

};

go.app = function() {
    var vumigo = require('vumigo_v02');
    var App = vumigo.App;

    var GoApp = App.extend(function(self) {
        App.call(self, 'state_lp_start');

        // REGISTER HEAD TEACHER STATES
        // ----------------------------

        self.states.add('state_rht_start', function(name) {
            return go.rht.state_rht_start(name);
        });

        self.states.add('state_rht_exit', function(name) {
            return go.rht.state_rht_exit(name);
        });

        // REGISTER DISTRICT OFFICIAL STATES
        // ---------------------------------

        self.states.add('state_rdo_start', function(name) {
            return go.rdo.state_rdo_start(name);
        });

        self.states.add('state_rdo_exit', function(name) {
            return go.rdo.state_rdo_exit(name);
        });

        // CHANGE MANAGEMENT STATES
        // ------------------------

        self.states.add('state_cm_start', function(name) {
            return go.cm.state_cm_start(name);
        });

        self.states.add('state_cm_exit', function(name) {
            return go.cm.state_cm_exit(name);
        });

        // LEARNER PERFORMANCE STATES
        // --------------------------

        self.states.add('state_lp_start', function(name) {
            return go.lp.state_lp_start(name);
        });

        self.states.add('state_lp_next', function(name) {
            return go.lp.state_lp_next(name);
        });

        self.states.add('state_lp_exit', function(name) {
            return go.lp.state_lp_exit(name);
        });

        // TEACHER PERFORMANCE STATES
        // --------------------------

        self.states.add('state_tp_start', function(name) {
            return go.tp.state_tp_start(name);
        });

        self.states.add('state_tp_next', function(name) {
            return go.tp.state_tp_next(name);
        });

        self.states.add('state_tp_exit', function(name) {
            return go.tp.state_tp_exit(name);
        });

        // SCHOOL PERFORMANCE STATES
        // --------------------------

        self.states.add('state_sp_start', function(name) {
            return go.sp.state_sp_start(name);
        });

        self.states.add('state_sp_next', function(name) {
            return go.sp.state_sp_next(name);
        });

        self.states.add('state_sp_exit', function(name) {
            return go.sp.state_sp_exit(name);
        });

    });

    return {
        GoApp: GoApp
    };
}();

go.init = function() {
    var vumigo = require('vumigo_v02');
    var InteractionMachine = vumigo.InteractionMachine;
    var GoApp = go.app.GoApp;

    return {
        im: new InteractionMachine(api, new GoApp())
    };
}();
<commit_msg>trailing compiled app<commit_after>// WARNING: This is a generated file.
//          If you edit it you will be sad.
//          Edit src/app.js instead.

var go = {};
go;

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.rht = {
    // Registration of Head Teacher States

    state_rht_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_rht_exit';
                } else {
                    return 'state_rht_exit';
                }
            }
        });
    },

    state_rht_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_rht_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.rdo = {
    // Registration of Head Teacher States

    state_rdo_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_rdo_exit';
                } else {
                    return 'state_rdo_exit';
                }
            }
        });
    },

    state_rdo_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_rdo_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.cm = {
    // Registration of Change Management States

    state_cm_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_cm_exit';
                } else {
                    return 'state_cm_exit';
                }
            }
        });
    },

    state_cm_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_cm_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.lp = {
    // LearnerPerformance States

    state_lp_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_lp_next';
                } else {
                    return 'state_lp_exit';
                }
            }
        });
    },

    state_lp_next: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('to_tp', 'Switch to TeacherPerformance'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'to_tp') {
                    return 'state_tp_start'; // Switch to TP
                } else {
                    return 'state_lp_exit';
                }
            }
        });
    },

    state_lp_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_lp_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.tp = {
    // TeacherPerformance States

    state_tp_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_tp_next';
                } else {
                    return 'state_tp_exit';
                }
            }
        });
    },

    state_tp_next: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('again', 'Back to beginning'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'again') {
                    return 'state_tp_start';
                } else {
                    return 'state_tp_exit';
                }
            }
        });
    },

    state_tp_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_tp_start'
        });
    }

};

var vumigo = require('vumigo_v02');
var ChoiceState = vumigo.states.ChoiceState;
var EndState = vumigo.states.EndState;
var Choice = vumigo.states.Choice;

go.sp = {
    // LearnerPerformance States

    state_sp_start: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('next', 'Go to next state'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'next') {
                    return 'state_sp_next';
                } else {
                    return 'state_sp_exit';
                }
            }
        });
    },

    state_sp_next: function(name) {
        return new ChoiceState(name, {
            question: 'Hi there! What do you want to do?',

            choices: [
                new Choice('to_tp', 'Switch to TeacherPerformance'),
                new Choice('exit', 'Exit')],

            next: function(choice) {
                if(choice.value === 'to_tp') {
                    return 'state_tp_start'; // Switch to TP
                } else {
                    return 'state_sp_exit';
                }
            }
        });
    },

    state_sp_exit: function(name) {
        return new EndState(name, {
            text: 'Thanks, cheers!',
            next: 'state_sp_start'
        });
    }

};

go.app = function() {
    var vumigo = require('vumigo_v02');
    var App = vumigo.App;

    var GoApp = App.extend(function(self) {
        App.call(self, 'state_lp_start');

        // REGISTER HEAD TEACHER STATES
        // ----------------------------

        self.states.add('state_rht_start', function(name) {
            return go.rht.state_rht_start(name);
        });

        self.states.add('state_rht_exit', function(name) {
            return go.rht.state_rht_exit(name);
        });

        // REGISTER DISTRICT OFFICIAL STATES
        // ---------------------------------

        self.states.add('state_rdo_start', function(name) {
            return go.rdo.state_rdo_start(name);
        });

        self.states.add('state_rdo_exit', function(name) {
            return go.rdo.state_rdo_exit(name);
        });

        // CHANGE MANAGEMENT STATES
        // ------------------------

        self.states.add('state_cm_start', function(name) {
            return go.cm.state_cm_start(name);
        });

        self.states.add('state_cm_exit', function(name) {
            return go.cm.state_cm_exit(name);
        });

        // LEARNER PERFORMANCE STATES
        // --------------------------

        self.states.add('state_lp_start', function(name) {
            return go.lp.state_lp_start(name);
        });

        self.states.add('state_lp_next', function(name) {
            return go.lp.state_lp_next(name);
        });

        self.states.add('state_lp_exit', function(name) {
            return go.lp.state_lp_exit(name);
        });

        // TEACHER PERFORMANCE STATES
        // --------------------------

        self.states.add('state_tp_start', function(name) {
            return go.tp.state_tp_start(name);
        });

        self.states.add('state_tp_next', function(name) {
            return go.tp.state_tp_next(name);
        });

        self.states.add('state_tp_exit', function(name) {
            return go.tp.state_tp_exit(name);
        });

        // SCHOOL PERFORMANCE STATES
        // --------------------------

        self.states.add('state_sp_start', function(name) {
            return go.sp.state_sp_start(name);
        });

        self.states.add('state_sp_next', function(name) {
            return go.sp.state_sp_next(name);
        });

        self.states.add('state_sp_exit', function(name) {
            return go.sp.state_sp_exit(name);
        });

    });

    return {
        GoApp: GoApp
    };
}();

go.init = function() {
    var vumigo = require('vumigo_v02');
    var InteractionMachine = vumigo.InteractionMachine;
    var GoApp = go.app.GoApp;

    return {
        im: new InteractionMachine(api, new GoApp())
    };
}();
<|endoftext|>


<commit_before>// @flow weak

import { now as timeNow } from 'd3-timer';
import tween from './tween';
import schedule from './schedule';
import { newId, easeCubicInOut } from './helpers';

const preset = {
  time: null,
  delay: 0,
  duration: 250,
  ease: easeCubicInOut,
};

export default function transition(config) {
  const transitions = { ...config };

  const events = transitions.events || {};
  delete transitions.events;

  const timing = transitions.timing || {};
  delete transitions.timing;

  Object.keys(transitions).forEach((refName) => {
    const tweens = [];

    Object.keys(transitions[refName]).forEach((attr) => {
      const val = transitions[refName][attr];
      const ref = this[refName];

      if (!ref) {
        const name = this.constructor.name || 'Component';
        throw new Error(`No ref "${refName}" found on ${name}`);
      }

      if (Array.isArray(val)) {
        if (val.length === 1) {
          tweens.push(tween.call(this[refName], attr, val[0]));
        } else {
          this[refName].setAttribute(attr, val[0]);
          tweens.push(tween.call(this[refName], attr, val[1]));
        }
      } else {
        this[refName].setAttribute(attr, val);
      }
    });

    const timingConfig = { ...preset, ...timing, time: timeNow() };
    schedule(this, refName, newId(), timingConfig, tweens, events);
  });
}
<commit_msg>assure existing transitions are stopped on ref<commit_after>// @flow weak

import { now as timeNow } from 'd3-timer';
import tween from './tween';
import schedule from './schedule';
import { newId, easeCubicInOut } from './helpers';

const preset = {
  time: null,
  delay: 0,
  duration: 250,
  ease: easeCubicInOut,
};

export default function transition(config) {
  const transitions = { ...config };

  const events = transitions.events || {};
  delete transitions.events;

  const timing = transitions.timing || {};
  delete transitions.timing;

  Object.keys(transitions).forEach((refName) => {
    const tweens = [];

    Object.keys(transitions[refName]).forEach((attr) => {
      const val = transitions[refName][attr];
      const ref = this[refName];

      if (!ref) {
        const name = this.constructor.name || 'Component';
        throw new Error(`No ref "${refName}" found on ${name}`);
      }

      if (Array.isArray(val)) {
        if (val.length === 1) {
          tweens.push(tween.call(this[refName], attr, val[0]));
        } else {
          this[refName].setAttribute(attr, val[0]);
          tweens.push(tween.call(this[refName], attr, val[1]));
        }
      } else {
        this[refName].setAttribute(attr, val);
        // This assures any existing transitions are killed
        tweens.push(tween.call(this[refName], attr, val));
      }
    });

    const timingConfig = { ...preset, ...timing, time: timeNow() };
    schedule(this, refName, newId(), timingConfig, tweens, events);
  });
}
<|endoftext|>


<commit_before>'use strict'
/**
 *          .·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.
 *          .·' H O M E S C R E E N S F O R A L L'·.  by leandro713
 *          .·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.
 *
 * Tilescreen
 * (c)  [ leandro@leandro.org, sergio.cero@gmail.com ]
 * GPL v3 license
 *
 * @author      leandro713 <leandro@leandro.org>
 * @copyright   leandro713 - 2016
 * @link        https://github.com/novia713/tilescreen
 * @license     http://www.gnu.org/licenses/gpl-3.0.en.html
 * @version     1.4.22
 * @date        20160131
 *
 * @see         https://github.com/mozilla-b2g/gaia/tree/88c8d6b7c6ab65505c4a221b61c91804bbabf891/apps/homescreen
 * @thanks      to @CodingFree for his tireless support and benevolent friendship
 * @todo
 *      - order icons by use [done]
 *      - show tile with date data
 *      - show wifi network name and telephony provider name
 *      - show weather
 *      - show missed calls
 *      - default icon if not found
 *
 */

requirejs.config({
    appDir: ".",
    baseUrl: "js",
    paths: {
        'ramdajs': ['ramda.min'],
        'uitls': "utils",
        'tilejs' : "tileJs",
        'fxos_icons': "../bower_components/fxos-icons/fxos-icons"

    },
    shim: {
        'ramdajs': {  exports: 'R' },
        'utils'  : {  exports: 'U' },
        'tilejs' : {  exports: 'Tile' }
    }
});

require(['ramdajs', 'utils', 'tilejs', 'fxos_icons'], ( R, U, Tile ) => {

    //CONFIG
    var only_big       = 0;
    var b_transparency = 0; /* 1 = semi-transparent background colors  VS 0 = solid background colors */
    //CONFIG

/*
    const apps_2_exclude = [
        "Downloads", "EmergencyCall", "System", "Legacy", "Ringtones",
        "Legacy Home Screen", "Wallpaper", "Default Theme", "Purchased Media",
        "Built-in Keyboard", "Bluetooth Manager", "Communications",
        "PDF Viewer", "Network Alerts", "WAP Push manager", "Default Home Screen" ];
*/
    const HIDDEN_ROLES = [ 'system', 'input', 'homescreen', 'theme', 'addon', 'langpack' ];

    var parent = document.getElementById('apps');
    var iconMap = new WeakMap();
    var usage = [];
    var smalls = [];
    var i = 0;
    var storage = null;
    var date = new Date();
    var width_1_col = 0;
    var width_2_col = 0;
    var width_4_col = 0;

    /**
     * Prints set up message
     */
     var print_msg = () => {
        var txt_msg  = "

Please, set this homescreen your default homescreen in Settings / Homescreens / Change Homescreens. This homescreen won't work if you don't do so

";
            txt_msg += "

Ve a Configuración / Homescreens y haz este homescreen tu homescreen por defecto. Si no lo haces, este homescreen no funciona!

";
            parent.innerHTML = txt_msg;
     };

     var hour_tile = function() {
        var oldtile = document.getElementById("hour_tile");
        if ( oldtile )
            parent.removeChild( oldtile );

        var tile       = document.createElement('div');
        tile.className = 'tile';
        tile.innerHTML = "";

        var battery = navigator.battery;
        if (battery) {
            var batterylevel = Math.round(battery.level * 100) + "%";
            var batterylevel_10 = Math.round(battery.level * 10) + "%";
            if (batterylevel_10 > 10) batterylevel_10 = 10;
            tile.innerHTML += " " + batterylevel + "";
        }

        tile.id        = 'hour_tile';
        tile.innerHTML += "
"+ U.get_worded_day( U.get_numeric_day( date )) + " " + date.getDate() + "
";
        tile.style     = "background-color:orange;";

        //TODO: refactor all this in aux
        function success(pos) {
              /*
               * show here info weather based on geoloc data
               * http://api.yr.no/weatherapi/locationforecast/1.9/documentation#schema
               * http://api.yr.no/weatherapi/weathericon/1.1/documentation
               * -------------------------------------------
               */
                var weather_info =
                        U.ajax("http://api.yr.no/weatherapi/locationforecast/1.9/?lat="+ pos.coords.latitude +";lon=" + pos.coords.longitude);
                document.getElementById("hour_tile").innerHTML +=
                            // TODO: css this, please
                                ""
                              + ""
                              + "";

        };

        function error(err) {
          console.warn('ERROR (' + err.code + '): ' + err.message);
        };

        navigator.geolocation.getCurrentPosition(success, error, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 });

        parent.insertBefore(tile, parent.children[1]);
        Tile( tile );
     };

    /**
     * Renders the icon to the container.
     */
    var render = icon => {

            // guards
            if (!icon.manifest.icons) return;
            if ( R.contains ( icon.manifest.role, HIDDEN_ROLES ))  return;
            //end guards

            if ( U.is_small( i, R, smalls ) > -1 ) {
                var icon_image = navigator.mozApps.mgmt.getIcon(icon, 32);
            }else{
                var icon_image = navigator.mozApps.mgmt.getIcon(icon, 60);
            }

            icon_image.then ( img => {

                var name = icon.manifest.name; if (name == "Communications")

                // Callscreen icon
                /* @FIXME: no funciona bien :(
                 * this app is different, so this icon needs a custom launch url
                 * @todo: refactor this in an outer named function
                 * icon: http://www.iconarchive.com/show/firefox-os-icons-by-vcferreira/dialer-icon.html
                 *
                 *
                 * CAUTION: callscreen is an standalone app from 1 feb 2016
                 */

                // TODO: delete me
                if (name == "Communications") {

                }

                // end callscreen
                var wordname = name.split(" ");
                var firstchar = name.charAt(0);

                /* tile generation*/
                var tile = document.createElement('div');
                tile.className = 'tile';

                    /* tile icon */
                    var tile_ic = document.createElement('div');
                    tile_ic.className = 'tile_ic';
                    tile_ic.style.background = 'transparent url(' + window.URL.createObjectURL( img ) + ') no-repeat';

                    // Callscreen icon [ doing things like this is cheese ]
                    if (name == "Communications") { //should be Callscreen
                        tile_ic.style.background = 'transparent url(/img/dialer-icon.png) no-repeat';
                    }

                    tile_ic.setAttribute('rel', wordname[0]);
                    tile_ic.id = wordname[0];

                    tile.appendChild(tile_ic);

                    /* tile background */
                    // FIXME: esto funciona, pero en algun momento después se sobreescribe .... porque el fondo no se hace transparente al poner b_transparency = 1
                    var tile_bg = document.createElement('div');
                    tile_bg.className = 'tile_bg';

                    if (b_transparency != 1) {
                        tile_bg.style.backgroundColor = U.get_color(name);
                    }else
                        tile_bg.style.backgroundColor = 'rgba(0,0,0,0.5)';

                    tile.appendChild(tile_bg);

                document.getElementById('apps').appendChild(tile);

                /* we associate the tile_ic to the firefox OS icon, because the tile_ic is who get the 'click' event, not the tile container */
                iconMap.set(tile_ic, icon);

                /* end tile generation*/

                // array for storing it in JSON for using records
                var item = { "label": wordname[0], "index": i, "order": 0 };
                storage = localStorage.getItem("storage");

                if ( !storage ) {
                    storage = [];
                    storage[i] = item;
                    localStorage.setItem( "storage", JSON.stringify( storage ));
                } else  {
                    var data = JSON.parse(storage);
                    data[i] =  item;
                    localStorage.setItem( "storage", JSON.stringify( data ));
                }

                ++i;

                if ( U.is_small( i, R, smalls ) > -1 )  {
                    tile.classList.add("small");
                }

                Tile( tile );

            });

            if (typeof icon_image == undefined) return;
    }

    /* fires up the painting */
    var start = () => {

        i = 0;

        if (b_transparency == 1){
            U.add_style('#apps { background-color: transparent; background-color: rgba(0,0,0,0.1); }');
        }else{
            U.add_style('#apps { background-color: #000;}');
        }

        if (only_big != 1)
            smalls = [ 2, 3 ,4 ,5, 7, 8 ,9 ,10, 15, 16, 17, 18 ];

            /**
             * Fetch all apps and render them.
             */
            var myApps = new Promise((resolve, reject) => {
                    var request = navigator.mozApps.mgmt.getAll();

                    request.onsuccess = (e) => {

                      hour_tile();

                      // hic sunt render leones
                      R.forEach( render, request.result );

                    };

                    request.onerror = (e) => {
                      console.error('Error calling getAll: ' + request.error.name);
                      resolve();
                    };
            });

            myApps.then(
                v => {

                }, v => {
                    print_msg();
                }
            );

            U.add_initial_styles( window, width_1_col, width_2_col, width_4_col );

    } //end start

    window.addEventListener('devicelight', ev => { console.log(ev.target);
        //console.log(ev.value);
    });

    window.addEventListener('click', ev => {

        var this_tile = ev.originalTarget;

        if ( typeof storage == "string" ) storage = JSON.parse( storage );
        var i = iconMap.get( ev.target );

        if (i) {

            var rel       = this_tile.getAttribute('rel');
            var index     =  R.filter( R.propEq("label", rel ), storage )[0].index;

            // we add 1 to value of that icon in localStorage ...
            storage[index].order +=1;
            localStorage.setItem( "storage", JSON.stringify( storage ));

            // transpose storage value to DOM elements
            this_tile.dataset.order = storage[index].order;

            i.launch();
            U.print_dock( R, iconMap );
        }

        // options
        if (this_tile.id == "worded" || this_tile.id == "hour_tile") {
           U.show_options(b_transparency, only_big);
        }

        // TODO:  make me a switch, please
        if (this_tile.id == "hide_trans") {
            b_transparency = 0;
            start();
        }

        if (this_tile.id == "set_trans") {
            b_transparency = 1;
            start();
        }

        if (this_tile.id == "only_big") {
            only_big = 1;
            R.forEach(removeSmall, document.getElementsByClassName("tile"));
            R.forEach(addSmall, document.getElementsByClassName("in-dock"));
            start();
        }

        if (this_tile.id == "show_small") {
            only_big = 0;
            start();
        }

        // end options

    }); //end window event 'click', document.getElementsByClassName('tile'));

    var removeSmall = function (el) {
        el.classList.remove("small")
    }

    var addSmall = function (el) {
        el.classList.add("small")
    }

    // 3, 2, 1 ...
    start();

});
<commit_msg>fixed Callscreen icon. TODO: contacts app<commit_after>'use strict'
/**
 *          .·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.
 *          .·' H O M E S C R E E N S F O R A L L'·.  by leandro713
 *          .·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.
 *
 * Tilescreen
 * (c)  [ leandro@leandro.org, sergio.cero@gmail.com ]
 * GPL v3 license
 *
 * @author      leandro713 <leandro@leandro.org>
 * @copyright   leandro713 - 2016
 * @link        https://github.com/novia713/tilescreen
 * @license     http://www.gnu.org/licenses/gpl-3.0.en.html
 * @version     1.4.22
 * @date        20160131
 *
 * @see         https://github.com/mozilla-b2g/gaia/tree/88c8d6b7c6ab65505c4a221b61c91804bbabf891/apps/homescreen
 * @thanks      to @CodingFree for his tireless support and benevolent friendship
 * @todo
 *      - order icons by use [done]
 *      - show tile with date data
 *      - show wifi network name and telephony provider name
 *      - show weather
 *      - show missed calls
 *      - default icon if not found
 *
 */

requirejs.config({
    appDir: ".",
    baseUrl: "js",
    paths: {
        'ramdajs': ['ramda.min'],
        'uitls': "utils",
        'tilejs' : "tileJs",
        'fxos_icons': "../bower_components/fxos-icons/fxos-icons"

    },
    shim: {
        'ramdajs': {  exports: 'R' },
        'utils'  : {  exports: 'U' },
        'tilejs' : {  exports: 'Tile' }
    }
});

require(['ramdajs', 'utils', 'tilejs', 'fxos_icons'], ( R, U, Tile ) => {

    //CONFIG
    var only_big       = 0;
    var b_transparency = 0; /* 1 = semi-transparent background colors  VS 0 = solid background colors */
    //CONFIG

/*
    const apps_2_exclude = [
        "Downloads", "EmergencyCall", "System", "Legacy", "Ringtones",
        "Legacy Home Screen", "Wallpaper", "Default Theme", "Purchased Media",
        "Built-in Keyboard", "Bluetooth Manager", "Communications",
        "PDF Viewer", "Network Alerts", "WAP Push manager", "Default Home Screen" ];
*/
    const HIDDEN_ROLES = [ 'system', 'input', 'homescreen', 'theme', 'addon', 'langpack' ];

    var parent = document.getElementById('apps');
    var iconMap = new WeakMap();
    var usage = [];
    var smalls = [];
    var i = 0;
    var storage = null;
    var date = new Date();
    var width_1_col = 0;
    var width_2_col = 0;
    var width_4_col = 0;

    /**
     * Prints set up message
     */
     var print_msg = () => {
        var txt_msg  = "

Please, set this homescreen your default homescreen in Settings / Homescreens / Change Homescreens. This homescreen won't work if you don't do so

";
            txt_msg += "

Ve a Configuración / Homescreens y haz este homescreen tu homescreen por defecto. Si no lo haces, este homescreen no funciona!

";
            parent.innerHTML = txt_msg;
     };

     var hour_tile = function() {
        var oldtile = document.getElementById("hour_tile");
        if ( oldtile )
            parent.removeChild( oldtile );

        var tile       = document.createElement('div');
        tile.className = 'tile';
        tile.innerHTML = "";

        var battery = navigator.battery;
        if (battery) {
            var batterylevel = Math.round(battery.level * 100) + "%";
            var batterylevel_10 = Math.round(battery.level * 10) + "%";
            if (batterylevel_10 > 10) batterylevel_10 = 10;
            tile.innerHTML += " " + batterylevel + "";
        }

        tile.id        = 'hour_tile';
        tile.innerHTML += "
"+ U.get_worded_day( U.get_numeric_day( date )) + " " + date.getDate() + "
";
        tile.style     = "background-color:orange;";

        //TODO: refactor all this in aux
        function success(pos) {
              /*
               * show here info weather based on geoloc data
               * http://api.yr.no/weatherapi/locationforecast/1.9/documentation#schema
               * http://api.yr.no/weatherapi/weathericon/1.1/documentation
               * -------------------------------------------
               */
                var weather_info =
                        U.ajax("http://api.yr.no/weatherapi/locationforecast/1.9/?lat="+ pos.coords.latitude +";lon=" + pos.coords.longitude);
                document.getElementById("hour_tile").innerHTML +=
                            // TODO: css this, please
                                ""
                              + ""
                              + "";

        };

        function error(err) {
          console.warn('ERROR (' + err.code + '): ' + err.message);
        };

        navigator.geolocation.getCurrentPosition(success, error, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 });

        parent.insertBefore(tile, parent.children[1]);
        Tile( tile );
     };

    /**
     * Renders the icon to the container.
     */
    var render = icon => {

            // guards
            if (!icon.manifest.icons) return;
            if ( R.contains ( icon.manifest.role, HIDDEN_ROLES ))  return;
            //end guards

            if ( U.is_small( i, R, smalls ) > -1 ) {
                var icon_image = navigator.mozApps.mgmt.getIcon(icon, 32);
            }else{
                var icon_image = navigator.mozApps.mgmt.getIcon(icon, 60);
            }

            icon_image.then ( img => {

                var name = icon.manifest.name; if (name == "Communications")

                // Callscreen icon
                /* @FIXME: no funciona bien :(
                 * this app is different, so this icon needs a custom launch url
                 * @todo: refactor this in an outer named function
                 * icon: http://www.iconarchive.com/show/firefox-os-icons-by-vcferreira/dialer-icon.html
                 *
                 *
                 * CAUTION: callscreen is an standalone app from 1 feb 2016
                 * TODO: Communication apps includes Contacts, which is not handle by now
                 */

                // TODO: delete me
                if (name == "Communications") {

                }

                // end callscreen
                var wordname = name.split(" ");
                var firstchar = name.charAt(0);

                /* tile generation*/
                var tile = document.createElement('div');
                tile.className = 'tile';

                    /* tile icon */
                    var tile_ic = document.createElement('div');
                    tile_ic.className = 'tile_ic';
                    tile_ic.style.background = 'transparent url(' + window.URL.createObjectURL( img ) + ') no-repeat';

                    // Callscreen icon [ doing things like this is cheese ]
                    if (name == "Communications") { //should be Callscreen
                        tile_ic.style.background = 'transparent url(/img/dialer-icon.png) no-repeat';
                    }

                    tile_ic.setAttribute('rel', wordname[0]);
                    tile_ic.id = wordname[0];

                    tile.appendChild(tile_ic);

                    /* tile background */
                    // FIXME: esto funciona, pero en algun momento después se sobreescribe .... porque el fondo no se hace transparente al poner b_transparency = 1
                    var tile_bg = document.createElement('div');
                    tile_bg.className = 'tile_bg';

                    if (b_transparency != 1) {
                        tile_bg.style.backgroundColor = U.get_color(name);
                    }else
                        tile_bg.style.backgroundColor = 'rgba(0,0,0,0.5)';

                    tile.appendChild(tile_bg);

                document.getElementById('apps').appendChild(tile);

                /* we associate the tile_ic to the firefox OS icon, because the tile_ic is who get the 'click' event, not the tile container */
                iconMap.set(tile_ic, icon);

                /* end tile generation*/

                // array for storing it in JSON for using records
                var item = { "label": wordname[0], "index": i, "order": 0 };
                storage = localStorage.getItem("storage");

                if ( !storage ) {
                    storage = [];
                    storage[i] = item;
                    localStorage.setItem( "storage", JSON.stringify( storage ));
                } else  {
                    var data = JSON.parse(storage);
                    data[i] =  item;
                    localStorage.setItem( "storage", JSON.stringify( data ));
                }

                ++i;

                if ( U.is_small( i, R, smalls ) > -1 )  {
                    tile.classList.add("small");
                }

                Tile( tile );

            });

            if (typeof icon_image == undefined) return;
    }

    /* fires up the painting */
    var start = () => {

        i = 0;

        if (b_transparency == 1){
            U.add_style('#apps { background-color: transparent; background-color: rgba(0,0,0,0.1); }');
        }else{
            U.add_style('#apps { background-color: #000;}');
        }

        if (only_big != 1)
            smalls = [ 2, 3 ,4 ,5, 7, 8 ,9 ,10, 15, 16, 17, 18 ];

            /**
             * Fetch all apps and render them.
             */
            var myApps = new Promise((resolve, reject) => {
                    var request = navigator.mozApps.mgmt.getAll();

                    request.onsuccess = (e) => {

                      hour_tile();

                      // hic sunt render leones
                      R.forEach( render, request.result );

                    };

                    request.onerror = (e) => {
                      console.error('Error calling getAll: ' + request.error.name);
                      resolve();
                    };
            });

            myApps.then(
                v => {

                }, v => {
                    print_msg();
                }
            );

            U.add_initial_styles( window, width_1_col, width_2_col, width_4_col );

    } //end start

    window.addEventListener('devicelight', ev => { console.log(ev.target);
        //console.log(ev.value);
    });

    window.addEventListener('click', ev => {

        var this_tile = ev.originalTarget;

        if ( typeof storage == "string" ) storage = JSON.parse( storage );
        var i = iconMap.get( ev.target );

        if (i) {

            var rel       = this_tile.getAttribute('rel');
            var index     =  R.filter( R.propEq("label", rel ), storage )[0].index;

            // we add 1 to value of that icon in localStorage ...
            storage[index].order +=1;
            localStorage.setItem( "storage", JSON.stringify( storage ));

            // transpose storage value to DOM elements
            this_tile.dataset.order = storage[index].order;

            // Callscreen, so dirty :S
            var entry = null;
            if (i.manifest.name == "Communications")
                entry = "dialer";
            //TODO; handle launch contacts

            i.launch(entry);
            U.print_dock( R, iconMap );
        }

        // options
        if (this_tile.id == "worded" || this_tile.id == "hour_tile") {
           U.show_options(b_transparency, only_big);
        }

        // TODO:  make me a switch, please
        if (this_tile.id == "hide_trans") {
            b_transparency = 0;
            start();
        }

        if (this_tile.id == "set_trans") {
            b_transparency = 1;
            start();
        }

        if (this_tile.id == "only_big") {
            only_big = 1;
            R.forEach(removeSmall, document.getElementsByClassName("tile"));
            R.forEach(addSmall, document.getElementsByClassName("in-dock"));
            start();
        }

        if (this_tile.id == "show_small") {
            only_big = 0;
            start();
        }

        // end options

    }); //end window event 'click', document.getElementsByClassName('tile'));

    var removeSmall = function (el) {
        el.classList.remove("small")
    }

    var addSmall = function (el) {
        el.classList.add("small")
    }

    // 3, 2, 1 ...
    start();

});
<|endoftext|>


<commit_before>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

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

module.exports = class bcex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bcex',
            'name': 'bcex',
            'countries': [ 'CA' ],
            'rateLimit': 500,
            'version': '1',
            'has': {
                'fetchBalance': true,
                'fetchMarkets': true,
                'createOrder': true,
                'cancelOrder': true,
                'fetchTicker': true,
                'fetchTickers': false,
                'fetchOrder': true,
                'fetchOrders': true,
                'fetchOpenOrders': true,
            },
            'urls': {
                'logo': 'https://www.bcex.top/images/bcex_logo0.png',
                'api': 'https://www.bcex.top',
                'www': 'https://www.bcex.ca',
                'doc': 'https://www.bcex.ca/api_market/market/',
                'fees': 'http://bcex.udesk.cn/hc/articles/57085',
            },
            'api': {
                'public': {
                    'get': [
                        'Api_Market/getPriceList'
                    ],
                },
                'private': {
                    'post': [
                        'Api_User/userBalance',
                        'Api_Order/coinTrust',
                        'Api_Order/cancel',
                        'Api_Order/ticker',
                        'Api_Order/orderList',
                        'Api_Order/tradeList',
                    ],
                },
            },
            'fees': {
            },
        });
    }

    async fetchMarkets () {
        let response = await this.publicGetApiMarketGetPriceList ();
        let result = [];
        let keys = Object.keys(response);
        for (let i = 0; i < keys.length; i++) {
            var currentMarketId = keys[i];
            var currentMarkets = response[currentMarketId];
            for (let j = 0; j < currentMarkets.length; j++) {
                var market = currentMarkets[j];
                let baseId = market.coin_from;
                let quoteId = market.coin_to;
                let base = this.commonCurrencyCode(baseId);
                let quote = this.commonCurrencyCode(quoteId);
                let id = base + "2" + quote;
                let symbol = base + '/' + quote;
                let active = true;
                result.push({
                    'id': id,
                    'symbol': symbol,
                    'base': base,
                    'quote': quote,
                    'baseId': baseId,
                    'quoteId': quoteId,
                    'active': active,
                    'info': market
                    });
            }
        }
        return result;
    }

    async fetchBalance (params = {}) {
        return 0;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        return 0;
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        return 0;
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        return 0;
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        return 0;
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        return 0;
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return 0;
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let request = '/' + this.implodeParams(path, params);
        let query = this.omit(params, this.extractParams(path));
        if (method === 'GET') {
            if (Object.keys(query).length)
                request += '?' + this.urlencode(query);
        }
        let url = this.urls['api'] + request;
        if (api === 'private') {
            this.checkRequiredCredentials();
            let timestamp = this.milliseconds().toString();
            let payload = '';
            if (method !== 'GET') {
                if (Object.keys(query).length) {
                    body = this.json(query);
                    payload = body;
                }
            }
            let what = timestamp + method + request + payload;
            let signature = this.hmac(this.encode(what), this.encode(this.secret), 'sha256');
            headers = {
                'CRYPTON-APIKEY': this.apiKey,
                'CRYPTON-SIGNATURE': signature,
                'CRYPTON-TIMESTAMP': timestamp,
                'Content-Type': 'application/json',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<commit_msg>Correct sign() method for BCEX<commit_after>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

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

module.exports = class bcex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bcex',
            'name': 'bcex',
            'countries': [ 'CA' ],
            'rateLimit': 500,
            'version': '1',
            'has': {
                'fetchBalance': true,
                'fetchMarkets': true,
                'createOrder': true,
                'cancelOrder': true,
                'fetchTicker': true,
                'fetchTickers': false,
                'fetchOrder': true,
                'fetchOrders': true,
                'fetchOpenOrders': true,
            },
            'urls': {
                'logo': 'https://www.bcex.top/images/bcex_logo0.png',
                'api': 'https://www.bcex.top',
                'www': 'https://www.bcex.ca',
                'doc': 'https://www.bcex.ca/api_market/market/',
                'fees': 'http://bcex.udesk.cn/hc/articles/57085',
            },
            'api': {
                'public': {
                    'get': [
                        'Api_Market/getPriceList'
                    ],
                },
                'private': {
                    'post': [
                        'Api_User/userBalance',
                        'Api_Order/coinTrust',
                        'Api_Order/cancel',
                        'Api_Order/ticker',
                        'Api_Order/orderList',
                        'Api_Order/tradeList',
                    ],
                },
            },
            'fees': {
            },
        });
    }

    async fetchMarkets () {
        let response = await this.publicGetApiMarketGetPriceList ();
        let result = [];
        let keys = Object.keys(response);
        for (let i = 0; i < keys.length; i++) {
            var currentMarketId = keys[i];
            var currentMarkets = response[currentMarketId];
            for (let j = 0; j < currentMarkets.length; j++) {
                var market = currentMarkets[j];
                let baseId = market.coin_from;
                let quoteId = market.coin_to;
                let base = this.commonCurrencyCode(baseId);
                let quote = this.commonCurrencyCode(quoteId);
                let id = base + "2" + quote;
                let symbol = base + '/' + quote;
                let active = true;
                result.push({
                    'id': id,
                    'symbol': symbol,
                    'base': base,
                    'quote': quote,
                    'baseId': baseId,
                    'quoteId': quoteId,
                    'active': active,
                    'info': market
                    });
            }
        }
        return result;
    }

    async fetchBalance (params = {}) {
        return 0;
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        return 0;
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        return 0;
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        return 0;
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        return 0;
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        return 0;
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return 0;
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let request = '/' + this.implodeParams(path, params);
        let query = this.omit(params, this.extractParams(path));
        if (method === 'GET') {
            if (Object.keys(query).length)
                request += '?' + this.urlencode(query);
        }
        let url = this.urls['api'] + request;
        if (api === 'private') {
            this.checkRequiredCredentials();
            if (method !== 'GET') {
                if (Object.keys(query).length) {
                    let messageParts = []
                    let paramsKeys = Object.keys(params).sort();
                    for (let i = 0; i < paramsKeys.length; i++) {
                        let paramKey = paramsKeys[i];
                        let param = params[paramKey];
                        messageParts.push(this.encode(paramKey) + '=' + encodeURIComponent(param));
                    }
                    body = messageParts.join ('&');
                    let message = body + "&secret_key=" + this.secret;
                    let signedMessage = this.hash(message);
                    body = body + "&sign=" + signedMessage;
                    params['sign'] = signedMessage;
                    headers = {}
                    headers['Content-Type'] = 'application/x-www-form-urlencoded';
                }
            }
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<|endoftext|>