<commit_before>/*
 @author Zakai Hamilton
 @component AppSessions
 */

screens.app.sessions = function AppSessions(me, { core, ui, widget, react }) {
    const {
        DropDown,
        Tabs,
        Item,
        Bar,
        Swimlane,
        Field,
        Element,
        Direction,
        Language,
        Text,
        List
    } = react;

    const AppToolbar = ({ languageState, sortState, groupState, yearState }) => {
        const languageItems = (me.languages || []).map(language => {
            const name = core.string.title(language.name);
            return (<Item key={language.id} id={language.id}>{name}</Item>);
        });
        const sortItems = (me.sort || []).map(sort => {
            return (<Item key={sort.id} id={sort.id}>{sort.name}</Item>);
        });
        const groupItems = (me.groups || []).map(group => {
            const name = core.string.title(group.name);
            return (<Item key={group.name} id={group.name}>{name}</Item>);
        });
        const yearItems = (me.years || []).map(year => {
            return (<Item key={year} id={year}>{year}</Item>);
        });
        return (
            <Bar>
                <Field label={
                    <>
                        <Text language="eng">Language</Text>
                        <Text language="heb">שפה</Text>
                    </>
                }>
                    <DropDown state={languageState}>
                        {languageItems}
                    </DropDown>
                </Field>
                <Field label={
                    <>
                        <Text language="eng">Sort</Text>
                        <Text language="heb">מיון</Text>
                    </>
                }>
                    <DropDown state={sortState}>
                        {sortItems}
                    </DropDown>
                </Field>
                <Field label={
                    <>
                        <Text language="eng">Group</Text>
                        <Text language="heb">קבוצה</Text>
                    </>
                }>
                    <DropDown state={groupState} multiple={
                        <Item>
                            <Text language="eng">Multiple</Text>
                            <Text language="heb">מספר</Text>
                        </Item>
                    }>
                        <Item id="all" multiple={false}>
                            <Text language="eng">All</Text>
                            <Text language="heb">הכל</Text>
                        </Item>
                        {groupItems}
                    </DropDown>
                </Field>
                <Field label={
                    <>
                        <Text language="eng">Year</Text>
                        <Text language="heb">שנה</Text>
                    </>
                }>
                    <DropDown state={yearState}>
                        <Item id="all" multiple={false}>
                            <Text language="eng">All</Text>
                            <Text language="heb">הכל</Text>
                        </Item>
                        {yearItems}
                    </DropDown>
                </Field>
            </Bar>
        );
    };

    me.imageUrl = function (groupName, sessionName) {
        return "https://screens.sfo2.cdn.digitaloceanspaces.com/" + groupName + "/" + encodeURIComponent(sessionName) + ".png";
    };

    const prepareSessions = (sessions) => {
        var items = [];
        sessions.map(session => {
            let item = items.find(item => item.session === session.session);
            if (!item) {
                item = { extensions: [] };
                items.push(item);
            }
            const { extension, ...map } = session;
            Object.assign(item, { ...item, ...map });
            item.extensions.push(extension);
        });
        items = items.map(item => {
            const tokens = me.sessionTokens(item);
            if (item.extensions.includes("mp4")) {
                item.image = me.imageUrl(item.group, item.session);
            }
            else {
                item.overlay = ui.image.get("mic");
            }
            return { ...item, ...tokens };
        });
        return items;
    };

    const AppHub = ({ groupState, sortState, yearState }) => {
        const [group] = groupState;
        const [sort] = sortState;
        const [year] = yearState;
        react.util.useSubscribe(groupState);
        react.util.useSubscribe(sortState);
        react.util.useSubscribe(yearState);
        let items = me.sessions;
        items = items.filter(item => group[0] === "all" || group.includes(item.group));
        items = items.filter(item => year[0] === "all" || year.includes(item.year));
        items = me.sort.find(item => item.id === sort).sort(items);
        items = items.map(item => (
            <Item key={item.name}>
                <Swimlane label={item.label}>
                    {item.content.map(item => {
                        const title = core.string.title(item.group);
                        const loadSession = () => {
                            core.app.launch("player", item.group, item.session);
                        }
                        return (
                            <Item key={item.session} overlay={item.overlay} image={item.image} onClick={loadSession}>
                                {(group[0] === "all" || group.length > 1) && <Element>{title}</Element>}
                                <Element className="app-sessions-row">
                                    <Element>{item.date}</Element>
                                    <Element>{item.durationText}</Element>
                                </Element>
                                <Element className="app-sessions-label" direction="auto" title={item.name}>{item.name}</Element>
                            </Item>
                        );
                    })}
                </Swimlane>
            </Item>
        ));
        return (<List itemSize={20.625} unit="em">
            {items}
        </List>);
    };

    const Main = () => {
        const yearState = react.util.useState(["all"]);
        const groupState = react.util.useState(["all"]);
        const languageState = react.util.useState("eng");
        const sortState = react.util.useState("date");
        const [language] = languageState;
        const direction = me.languages.find(item => item.id === language).direction;
        const state = {
            languageState,
            groupState,
            sortState,
            yearState
        };
        return (
            <Direction direction={direction}>
                <Language language={language}>
                    <AppToolbar {...state} />
                    <AppHub {...state} />
                </Language>
            </Direction>
        );
    };
    me.languages = [
        {
            id: "eng",
            name: "English",
            direction: "ltr",
            locale: "en-US"
        },
        {
            id: "heb",
            name: "עברית",
            direction: "rtl",
            locale: "he-IL"
        }
    ];
    me.sort = [
        {
            id: "date",
            name: (
                <>
                    <Text language="eng">Date</Text>
                    <Text language="heb">תאריך</Text>
                </>
            ),
            sort: (items) => {
                items = [...items];
                items.sort((a, b) => {
                    return b.date.localeCompare(a.date);
                });
                const swimlanes = {};
                items.map(item => {
                    const unique = item.year + "-" + item.month;
                    let swimlane = swimlanes[unique];
                    if (!swimlane) {
                        swimlane = swimlanes[unique] = { content: [] };
                    }
                    const handler = language => {
                        const date = new Date(item.year, item.month - 1, item.day);
                        const { locale } = me.languages.find(obj => obj.id === language);
                        const month = date.toLocaleString(locale, { month: 'long' });
                        return month + " " + item.year;
                    };
                    swimlane.label = (<Text language={handler} />);
                    item.month + " " + item.year;
                    swimlane.content.push(item);
                });
                return Object.keys(swimlanes).map(unique => swimlanes[unique]);
            }
        },
        {
            id: "name",
            name: (
                <>
                    <Text language="eng">Name</Text>
                    <Text language="heb">שם</Text>
                </>
            ),
            sort: (items) => {
                items = [...items];
                items.sort((a, b) => {
                    return a.name.localeCompare(b.name);
                });
                const swimlanes = {};
                items.map(item => {
                    const unique = item.name[0];
                    let swimlane = swimlanes[unique];
                    if (!swimlane) {
                        swimlane = swimlanes[unique] = { content: [] };
                    }
                    swimlane.label = item.name[0];
                    swimlane.content.push(item);
                });
                return Object.keys(swimlanes).map(unique => swimlanes[unique]);
            }
        },
        {
            id: "duration",
            name: (
                <>
                    <Text language="eng">Duration</Text>
                    <Text language="heb">זמן</Text>
                </>
            ),
            sort: (items) => {
                items = [...items];
                items.sort((a, b) => {
                    return a.duration - b.duration;
                });
                const swimlanes = {};
                items.map(item => {
                    const unique = parseInt(item.duration / 900);
                    let swimlane = swimlanes[unique];
                    if (!swimlane) {
                        swimlane = swimlanes[unique] = { content: [] };
                    }
                    if (!swimlane.label) {
                        if (item.duration) {
                            const time = parseInt(item.duration / 900) * 900;
                            swimlane.label = core.string.formatDuration(time, false, true);
                        }
                        else {
                            swimlane.label = (
                                <>
                                    <Text language="eng">Unknown</Text>
                                    <Text language="heb">לא ידוע</Text>
                                </>
                            );
                        }
                    }
                    swimlane.content.push(item);
                });
                return Object.keys(swimlanes).map(unique => swimlanes[unique]);
            }
        }
    ];
    me.sessionTokens = function (item) {
        let [year, month, day, name = ""] = item.name.split(/(\d{4})-(\d{2})-(\d{2})\s(.+)/g).slice(1);
        const date = [year, month, day].join("-");
        return { year, month, day, date, name: core.path.fileName(name).trim() };
    }
    me.launch = async function () {
        if (core.property.get(me.singleton, "ui.node.parent")) {
            core.property.set(me.singleton, "widget.window.show", true);
            return me.singleton;
        }
        me.singleton = ui.element.create(me.json, "workspace", "self");
    };
    me.ready = function (methods) {
        methods["app.sessions.setGroups"] = ["media.file.groups"];
        methods["app.sessions.setMetadataList"] = ["db.shared.metadata.list", { user: "$userId" }];
    };
    me.setGroups = function (groups) {
        me.groups = groups;
        me.sessions = prepareSessions([].concat.apply([], me.groups.map(group => group.sessions)));
        me.years = Array.from(new Set(me.sessions.map(item => item.year)));
    };
    me.setMetadataList = function (metadataList) {
        me.metadataList = metadataList;
    };
    me.initOptions = async function (object) {
        var window = widget.window.get(object);
        ui.options.load(me, window, {
            groupName: "American"
        });
        core.property.set(window, "app", me);
        core.property.set(window, "name", "");
    };
    me.render = function (object) {
        return (<Main />);
    };
    me.resize = function (object) {

    };
};
<commit_msg>bug fixes<commit_after>/*
 @author Zakai Hamilton
 @component AppSessions
 */

screens.app.sessions = function AppSessions(me, { core, ui, widget, react }) {
    const {
        DropDown,
        Tabs,
        Item,
        Bar,
        Swimlane,
        Field,
        Element,
        Direction,
        Language,
        Text,
        List
    } = react;

    const AppToolbar = ({ languageState, sortState, groupState, yearState }) => {
        const languageItems = (me.languages || []).map(language => {
            const name = core.string.title(language.name);
            return (<Item key={language.id} id={language.id}>{name}</Item>);
        });
        const sortItems = (me.sort || []).map(sort => {
            return (<Item key={sort.id} id={sort.id}>{sort.name}</Item>);
        });
        const groupItems = (me.groups || []).map(group => {
            const name = core.string.title(group.name);
            return (<Item key={group.name} id={group.name}>{name}</Item>);
        });
        const yearItems = (me.years || []).map(year => {
            return (<Item key={year} id={year}>{year}</Item>);
        });
        return (
            <Bar>
                <Field label={
                    <>
                        <Text language="eng">Language</Text>
                        <Text language="heb">שפה</Text>
                    </>
                }>
                    <DropDown state={languageState}>
                        {languageItems}
                    </DropDown>
                </Field>
                <Field label={
                    <>
                        <Text language="eng">Sort</Text>
                        <Text language="heb">מיון</Text>
                    </>
                }>
                    <DropDown state={sortState}>
                        {sortItems}
                    </DropDown>
                </Field>
                <Field label={
                    <>
                        <Text language="eng">Group</Text>
                        <Text language="heb">קבוצה</Text>
                    </>
                }>
                    <DropDown state={groupState} multiple={
                        <Item>
                            <Text language="eng">Multiple</Text>
                            <Text language="heb">מספר</Text>
                        </Item>
                    }>
                        <Item id="all" multiple={false}>
                            <Text language="eng">All</Text>
                            <Text language="heb">הכל</Text>
                        </Item>
                        {groupItems}
                    </DropDown>
                </Field>
                <Field label={
                    <>
                        <Text language="eng">Year</Text>
                        <Text language="heb">שנה</Text>
                    </>
                }>
                    <DropDown state={yearState}>
                        <Item id="all" multiple={false}>
                            <Text language="eng">All</Text>
                            <Text language="heb">הכל</Text>
                        </Item>
                        {yearItems}
                    </DropDown>
                </Field>
            </Bar>
        );
    };

    me.imageUrl = function (groupName, sessionName) {
        return "https://screens.sfo2.cdn.digitaloceanspaces.com/" + groupName + "/" + encodeURIComponent(sessionName) + ".png";
    };

    const prepareSessions = (sessions) => {
        var items = [];
        sessions.map(session => {
            let item = items.find(item => item.session === session.session);
            if (!item) {
                item = { extensions: [] };
                items.push(item);
            }
            const { extension, ...map } = session;
            Object.assign(item, { ...item, ...map });
            item.extensions.push(extension);
        });
        items = items.map(item => {
            const tokens = me.sessionTokens(item);
            if (item.extensions.includes("mp4")) {
                item.image = me.imageUrl(item.group, item.session);
            }
            else {
                item.overlay = ui.image.get("mic");
            }
            return { ...item, ...tokens };
        });
        return items;
    };

    const AppHub = ({ groupState, sortState, yearState }) => {
        const [group] = groupState;
        const [sort] = sortState;
        const [year] = yearState;
        react.util.useSubscribe(groupState);
        react.util.useSubscribe(sortState);
        react.util.useSubscribe(yearState);
        let items = me.sessions;
        items = items.filter(item => group[0] === "all" || group.includes(item.group));
        items = items.filter(item => year[0] === "all" || year.includes(item.year));
        items = me.sort.find(item => item.id === sort).sort(items);
        items = items.map(item => (
            <Item key={item.id}>
                <Swimlane label={item.label}>
                    {item.content.map(item => {
                        const title = core.string.title(item.group);
                        const loadSession = () => {
                            core.app.launch("player", item.group, item.session);
                        }
                        return (
                            <Item key={item.group + item.session} overlay={item.overlay} image={item.image} onClick={loadSession}>
                                <Element className="app-sessions-row">
                                    {(group[0] === "all" || group.length > 1) && <Element key={title}>{title}</Element>}
                                </Element>
                                <Element className="app-sessions-row">
                                    <Element>{item.date}</Element>
                                    <Element>{item.durationText}</Element>
                                </Element>
                                <Element className="app-sessions-label" direction="auto" title={item.name}>{item.name}</Element>
                            </Item>
                        );
                    })}
                </Swimlane>
            </Item>
        ));
        return (<List itemSize={20.625} unit="em">
            {items}
        </List>);
    };

    const Main = () => {
        const yearState = react.util.useState(["all"]);
        const groupState = react.util.useState(["all"]);
        const languageState = react.util.useState("eng");
        const sortState = react.util.useState("date");
        const [language] = languageState;
        const direction = me.languages.find(item => item.id === language).direction;
        const state = {
            languageState,
            groupState,
            sortState,
            yearState
        };
        return (
            <Direction direction={direction}>
                <Language language={language}>
                    <AppToolbar {...state} />
                    <AppHub {...state} />
                </Language>
            </Direction>
        );
    };
    me.languages = [
        {
            id: "eng",
            name: "English",
            direction: "ltr",
            locale: "en-US"
        },
        {
            id: "heb",
            name: "עברית",
            direction: "rtl",
            locale: "he-IL"
        }
    ];
    me.sort = [
        {
            id: "date",
            name: (
                <>
                    <Text language="eng">Date</Text>
                    <Text language="heb">תאריך</Text>
                </>
            ),
            sort: (items) => {
                items = [...items];
                items.sort((a, b) => {
                    return b.date.localeCompare(a.date);
                });
                const swimlanes = {};
                items.map(item => {
                    const unique = item.year + "-" + item.month;
                    let swimlane = swimlanes[unique];
                    if (!swimlane) {
                        swimlane = swimlanes[unique] = { content: [] };
                    }
                    const handler = language => {
                        const date = new Date(item.year, item.month - 1, item.day);
                        const { locale } = me.languages.find(obj => obj.id === language);
                        const month = date.toLocaleString(locale, { month: 'long' });
                        return month + " " + item.year;
                    };
                    swimlane.id = item.month + " " + item.year;
                    swimlane.label = (<Text language={handler} />);
                    swimlane.content.push(item);
                });
                return Object.keys(swimlanes).map(unique => swimlanes[unique]);
            }
        },
        {
            id: "name",
            name: (
                <>
                    <Text language="eng">Name</Text>
                    <Text language="heb">שם</Text>
                </>
            ),
            sort: (items) => {
                items = [...items];
                items.sort((a, b) => {
                    return a.name.localeCompare(b.name);
                });
                const swimlanes = {};
                items.map(item => {
                    const unique = item.name[0];
                    let swimlane = swimlanes[unique];
                    if (!swimlane) {
                        swimlane = swimlanes[unique] = { content: [] };
                    }
                    swimlane.id = item.name[0];
                    swimlane.label = item.name[0];
                    swimlane.content.push(item);
                });
                return Object.keys(swimlanes).map(unique => swimlanes[unique]);
            }
        },
        {
            id: "duration",
            name: (
                <>
                    <Text language="eng">Duration</Text>
                    <Text language="heb">זמן</Text>
                </>
            ),
            sort: (items) => {
                items = [...items];
                items.sort((a, b) => {
                    return a.duration - b.duration;
                });
                const swimlanes = {};
                items.map(item => {
                    const unique = parseInt(item.duration / 900);
                    let swimlane = swimlanes[unique];
                    if (!swimlane) {
                        swimlane = swimlanes[unique] = { content: [] };
                    }
                    if (!swimlane.label) {
                        if (item.duration) {
                            const time = parseInt(item.duration / 900) * 900;
                            swimlane.label = core.string.formatDuration(time, false, true);
                        }
                        else {
                            swimlane.label = (
                                <>
                                    <Text language="eng">Unknown</Text>
                                    <Text language="heb">לא ידוע</Text>
                                </>
                            );
                        }
                    }
                    swimlane.id = unique;
                    swimlane.content.push(item);
                });
                return Object.keys(swimlanes).map(unique => swimlanes[unique]);
            }
        }
    ];
    me.sessionTokens = function (item) {
        let [year, month, day, name = ""] = item.name.split(/(\d{4})-(\d{2})-(\d{2})\s(.+)/g).slice(1);
        const date = [year, month, day].join("-");
        return { year, month, day, date, name: core.path.fileName(name).trim() };
    }
    me.launch = async function () {
        if (core.property.get(me.singleton, "ui.node.parent")) {
            core.property.set(me.singleton, "widget.window.show", true);
            return me.singleton;
        }
        me.singleton = ui.element.create(me.json, "workspace", "self");
    };
    me.ready = function (methods) {
        methods["app.sessions.setGroups"] = ["media.file.groups"];
        methods["app.sessions.setMetadataList"] = ["db.shared.metadata.list", { user: "$userId" }];
    };
    me.setGroups = function (groups) {
        me.groups = groups;
        me.sessions = prepareSessions([].concat.apply([], me.groups.map(group => group.sessions)));
        me.years = Array.from(new Set(me.sessions.map(item => item.year)));
    };
    me.setMetadataList = function (metadataList) {
        me.metadataList = metadataList;
    };
    me.initOptions = async function (object) {
        var window = widget.window.get(object);
        ui.options.load(me, window, {
            groupName: "American"
        });
        core.property.set(window, "app", me);
        core.property.set(window, "name", "");
    };
    me.render = function (object) {
        return (<Main />);
    };
    me.resize = function (object) {

    };
};
<|endoftext|>


<commit_before>// polyfills
import 'babel-polyfill';

// npm modules
import chalk from 'chalk';
import meow from 'meow';
import pick from 'lodash.pick';
import stdin from 'get-stdin';

// local modules
import help from './help';
import lint from './';
import {
	format,
	getConfiguration,
	getPreset,
	getMessages
} from './';

import pkg from '../package';

/**
 * Behavioural rules
 */
const rules = {
	fromStdin: (input, flags) => input.length === 0 &&
		flags.from === null &&
		flags.to === null &&
		!flags.edit
};

const configuration = {
	// flags of string type
	string: ['from', 'to', 'preset', 'extends'],
	// flags of array type
	// flags of bool type
	boolean: ['edit', 'help', 'version', 'quiet', 'color'],
	// flag aliases
	alias: {
		c: 'color',
		e: 'edit',
		f: 'from',
		p: 'preset',
		t: 'to',
		q: 'quiet',
		h: 'help',
		v: 'version',
		x: 'extends'
	},
	description: {
		color: 'toggle formatted output',
		edit: 'read last commit message found in ./git/COMMIT_EDITMSG',
		'extends': 'array of shareable configurations to extend',
		from: 'lower end of the commit range to lint; applies if edit=false',
		preset: 'conventional-changelog-preset to use for commit message parsing',
		to: 'upper end of the commit range to lint; applies if edit=false',
		quiet: 'toggle console output'
	},
	// flag defaults
	default: {
		color: true,
		edit: false,
		from: null,
		preset: 'angular',
		to: null,
		quiet: false
	},
	// fail on unknown
	unknown(arg) {
		throw new Error(`unknown flags: ${arg}`);
	}
};

// Init meow 😸cli
const cli = meow({
	help: `[input] reads from stdin if --edit, --from, --to are omitted\n${help(configuration)}`,
	description: `${pkg.name}@${pkg.version} - ${pkg.description}`
}, configuration);

// Assemble the engine
async function main(options) {
	const {input: raw, flags} = options;
	const fromStdin = rules.fromStdin(raw, flags);

	const input = fromStdin ?
		[await stdin()] :
		await getMessages(
			pick(flags, ['edit', 'from', 'to'])
		);

	return Promise.all(input
		.map(async commit => {
			const fmt = new chalk.constructor({enabled: flags.color});

			const seed = {};
			if (flags.extends) {
				seed.extends = flags.extends.split(',');
			}

			const report = lint(commit, {
				preset: await getPreset(flags.preset),
				configuration: await getConfiguration(
					'conventional-changelog-lint',
					{
						prefix: 'conventional-changelog-lint-config'
					},
					seed
				)
			});

			const formatted = format(report, {
				color: flags.color,
				signs: [' ', '⚠', '✖'],
				colors: ['white', 'yellow', 'red']
			});

			if (!flags.quiet) {
				console.log(`${fmt.grey('⧗')}   input: ${fmt.bold(commit.split('\n')[0])}`);
				console.log(
					formatted
						.join('\n')
				);
			}

			if (report.errors.length > 0) {
				const error = new Error(formatted[formatted.length - 1]);
				error.type = pkg.name;
				throw error;
			}

			console.log('');
		}));
}

// Start the engine
main(cli)
	.catch(error =>
		setTimeout(() => {
			if (error.type === pkg.name) {
				process.exit(1);
			}
			throw error;
		})
	)
<commit_msg>fix: add missing shebang<commit_after>#!/usr/bin/env node
// polyfills
import 'babel-polyfill';

// npm modules
import chalk from 'chalk';
import meow from 'meow';
import pick from 'lodash.pick';
import stdin from 'get-stdin';

// local modules
import help from './help';
import lint from './';
import {
	format,
	getConfiguration,
	getPreset,
	getMessages
} from './';

import pkg from '../package';

/**
 * Behavioural rules
 */
const rules = {
	fromStdin: (input, flags) => input.length === 0 &&
		flags.from === null &&
		flags.to === null &&
		!flags.edit
};

const configuration = {
	// flags of string type
	string: ['from', 'to', 'preset', 'extends'],
	// flags of array type
	// flags of bool type
	boolean: ['edit', 'help', 'version', 'quiet', 'color'],
	// flag aliases
	alias: {
		c: 'color',
		e: 'edit',
		f: 'from',
		p: 'preset',
		t: 'to',
		q: 'quiet',
		h: 'help',
		v: 'version',
		x: 'extends'
	},
	description: {
		color: 'toggle formatted output',
		edit: 'read last commit message found in ./git/COMMIT_EDITMSG',
		'extends': 'array of shareable configurations to extend',
		from: 'lower end of the commit range to lint; applies if edit=false',
		preset: 'conventional-changelog-preset to use for commit message parsing',
		to: 'upper end of the commit range to lint; applies if edit=false',
		quiet: 'toggle console output'
	},
	// flag defaults
	default: {
		color: true,
		edit: false,
		from: null,
		preset: 'angular',
		to: null,
		quiet: false
	},
	// fail on unknown
	unknown(arg) {
		throw new Error(`unknown flags: ${arg}`);
	}
};

// Init meow 😸cli
const cli = meow({
	help: `[input] reads from stdin if --edit, --from, --to are omitted\n${help(configuration)}`,
	description: `${pkg.name}@${pkg.version} - ${pkg.description}`
}, configuration);

// Assemble the engine
async function main(options) {
	const {input: raw, flags} = options;
	const fromStdin = rules.fromStdin(raw, flags);

	const input = fromStdin ?
		[await stdin()] :
		await getMessages(
			pick(flags, ['edit', 'from', 'to'])
		);

	return Promise.all(input
		.map(async commit => {
			const fmt = new chalk.constructor({enabled: flags.color});

			const seed = {};
			if (flags.extends) {
				seed.extends = flags.extends.split(',');
			}

			const report = lint(commit, {
				preset: await getPreset(flags.preset),
				configuration: await getConfiguration(
					'conventional-changelog-lint',
					{
						prefix: 'conventional-changelog-lint-config'
					},
					seed
				)
			});

			const formatted = format(report, {
				color: flags.color,
				signs: [' ', '⚠', '✖'],
				colors: ['white', 'yellow', 'red']
			});

			if (!flags.quiet) {
				console.log(`${fmt.grey('⧗')}   input: ${fmt.bold(commit.split('\n')[0])}`);
				console.log(
					formatted
						.join('\n')
				);
			}

			if (report.errors.length > 0) {
				const error = new Error(formatted[formatted.length - 1]);
				error.type = pkg.name;
				throw error;
			}

			console.log('');
		}));
}

// Start the engine
main(cli)
	.catch(error =>
		setTimeout(() => {
			if (error.type === pkg.name) {
				process.exit(1);
			}
			throw error;
		})
	)
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Product Schema
 */
var ProductSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  title: {
    type: String,
    required: true,
    trim: true
  },
  description: {
    type: String,
    required: true,
    trim: true
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

/**
 * Validations
 */
ProductSchema.path('title').validate(function(title) {
  return !!title;
}, 'Title cannot be blank');

ProductSchema.path('description').validate(function(description) {
  return !!description;
}, 'Description cannot be blank');

/**
 * Statics
 */
ProductSchema.statics.load = function(id, cb) {
  this.findOne({
    _id: id
  }).populate('user', 'name username').exec(cb);
};

mongoose.model('Product', ProductSchema);
<commit_msg>Added tag to product<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Product Schema
 */
var ProductSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  title: {
    type: String,
    required: true,
    trim: true
  },
  description: {
    type: String,
    required: true,
    trim: true
  },
  tag: {
    type: String,
    required: false,
    trim: true
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

/**
 * Validations
 */
ProductSchema.path('title').validate(function(title) {
  return !!title;
}, 'Title cannot be blank');

ProductSchema.path('description').validate(function(description) {
  return !!description;
}, 'Description cannot be blank');

/**
 * Statics
 */
ProductSchema.statics.load = function(id, cb) {
  this.findOne({
    _id: id
  }).populate('user', 'name username').exec(cb);
};

mongoose.model('Product', ProductSchema);
<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";
import cx from "classnames";
import { ButtonCore } from "../Button";
import messages from "../utils/messages.js";

/**
 * Master Dropdown Component
 * Only used for dropdown component
 * Supports required, disabled, custom width, custom error messaging, onclick and onchange functions
 */
class Dropdown extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      "active": false,
      "output": this._getOutput(),
      "value": this._getValue() || '',
      "valid": true,
      "errorMessage": "This field is required",
      "onChange": "",
      "focus": false,
      "zIndex": false
    };
    let isFocus = false;
  }

  _getOutput = () => {
    let count = React.Children.count(this.props.children);
    for(var i = 0; i < count; i++) {
      if(this.props.children[i].props.selected){
        return this.props.children[i].props.children
      }
    }
    if(this.props.defaultText){
      return this.props.defaultText;
    } else {
      return messages.selectOne;
    }
  }

  _getValue = () => {
    let count = React.Children.count(this.props.children);
    for(var i = 0; i < count; i++) {
      if(this.props.children[i].props.selected){
        return this.props.children[i].props.value
      }
    }
  }

  /**
   * closes dropdown click outside of browser window
   */
  _onWindowBlur = () => {
    if (this.state.active === true) {
      this.setState({
        "active": false,
        "zIndex": false
      });
    }
  };

  /**
   *  _clickHandler is used when the dropdown option is selected.
   *
   */
  _clickHandler = (i, event) => {
    if (!this.props.disabled) {
      if (
        typeof this.props.onBeforeChange === "undefined" ||
        this.props.onBeforeChange(this.state.active)
      ) {
        const output = this.props.children[i].props.children;
        const inputValue = this.props.children[i].props.value;
        this.setState({
          "index": i,
          "output": output,
          "active": !this.state.active,
          "value": inputValue,
          "valid": true,
          "zIndex": false
        }, function(){
          this._validationHandler(this.props.errorCallback);
          if (this.props.onChange) {
            this._customOnChangeEvent(event);
          }
          if (this.props.onClick) {
            this._customOnClickEvent(event);
          }
        });

      }
    }
  };

  _customOnChangeEvent = event => {
    /* Pass the event object, and a data object to the click handler.
    The data object contains a boolean for whether the dropdown was
    changed or not, plus all the props passed to the object.  */
    this.props.onChange(event, {
      "active": this.state.valid,
      "props": this.props,
      "value": this.state.value
    });
  };

  _customOnClickEvent = event => {
    /* Pass the event object, and a data object to the click handler.
      The data object contains a boolean for whether the dropdown was
      clicked or not, plus all the props passed to the object.  */

    this.props.onClick(event, {
      "active": this.state.valid,
      "props": this.props,
      "value": this.state.value
    });
  };

  _toggle = (focus, event) => {
    /* Toggles the dropdown from active to inactive state, sets valid to true and zIndex to true.
      Active is used to show/hide options, valid is used to show/hide error messaging related to validation and zIndex sets a class on the component to ensure it has the proper index on the DOM
     */
    let canProceed = true;
    if(focus === "click" && this.isFocus) {
      canProceed = false;
      this.isFocus = false;
    } else if (focus === true) {
      this.isFocus = true;
    }
    if (!this.props.disabled && canProceed) {
      const action = (focus && !this.state.active) ? true : false;
      if(action){
        this.setState({
          "focus": true,
          "active": true,
          "valid": true,
          "zIndex": true
        });
      } else {
        /* When the user exits dropdown the state is change for focus and validation method is called
         */
        this.setState({ "focus": false, "active": false, "zIndex": false });
        this._validationHandler(this.props.errorCallback);
      }

      if (this.props.onClick) {
        this._customOnClickEvent(event);
      }
    }
  };

  _validationHandler = callback => {
    /* Checks that required has been set to true and determines if errorCallback message was passed in a custom error message.
      Also sets state of valid depending on user action
      */
    let validationObject = {
      "valid":
        this.props.required && this.state.value !== "" ||
          !this.props.required,
      "message": this.state.errorMessage
    };
    if(callback){
      validationObject = callback(event, this.state.value);
    }
    this.setState({
      "valid": validationObject.valid,
      "errorMessage": validationObject.message
    });
  };

  _keyDown = event => {
    const indexValid = (typeof this.state.index === "number");
    let newIndex;
    event.preventDefault();
    if (event.key === "ArrowDown") {
      newIndex = (indexValid) ? this.state.index + 1 : 0;
      let count = React.Children.count(this.props.children);
      if(newIndex < count) {
        this.setState({
          index: newIndex
        });
      }
    } else if (event.key === "ArrowUp") {
      newIndex = this.state.index - 1;
      if(newIndex >= 0) {
        this.setState({
          index: newIndex
        });
      }
    } else if (event.key === "Enter") {
      this._clickHandler(this.state.index);
    }
  }

  render() {
    const {
      children,
      className,
      required,
      customLabel,
      buttonWidth,
      disabled
    } = this.props;
    const active = this.state.active;
    const error = !this.state.valid && !disabled ? true : false;
    let zIndex = this.state.zIndex ? true : false;
    const classes = cx({
      "active": active,
      "container": true,
      "zIndex": zIndex
    });

    const buttonClasses = cx({
      "ra_dropdown__dropdown-button": true,
      "ra_dropdown__error": error,
      "ra_dropdown__disabledClass": disabled
    });

    // Builds the option list from the children passed in
    // firstChild, lastChild and selected each have unique styling and those classes are added here
    const bound_children = children.map((child, i) => {
      let count = React.Children.count(this.props.children);
      let childClasses = cx({
        "ra_dropdown__selected": i === this.state.index,
        "ra_dropdown__firstChild": i === 0,
        "ra_dropdown__lastChild": i === count - 1
      });
      let kid =

 { // onMouseDown fires before onBlur. If changed to onClick it will fire after onBlur and not work.
            this._clickHandler(i, e);
          }}
        >
          {child}

      ;
      return kid;
    });

    const dropdownButtonClasses = cx(buttonClasses);

    return (

 {
          this._toggle(true, e);
        }}
        onBlur={(e) => {
          this._toggle(false, e);
        }}
        onKeyDown={e => {
          this._keyDown(e);
        }}
      >
        {customLabel &&

            {customLabel}
            {required &&
              *
            }

        }

 { this._toggle("click", e); }} styleName={"content"}>

            <ButtonCore
              styleName={"buttonClass"}
              className={dropdownButtonClasses}
            >
              {this.state.output}
            </ButtonCore>

          {this.state.active &&
            {bound_children}
          }
          <input type="hidden" value={this.state.value} />

        {error &&

            {this.state.errorMessage}

        }

    );
  }
}

Dropdown.propTypes = {
  /**
   * Text for dropdown label
   * @examples 'Some Label'
   */
  "customLabel": PropTypes.string,

  /* Boolean value taht tells the dropdown whether to
    be open or not.*/
  "active": PropTypes.bool,

  /* Boolean value that tells the dropdown whether the value is valid and controls error message is returns false.*/
  "valid": PropTypes.bool,

  /**
   * If included, dropdown is disabled
   * @examples <Dropdown disabled />, <Dropdown disabled={true} />
   */
  "disabled": PropTypes.bool,

  /**
   * Allows user to pass a callback for click events.
   */
  "onClick": PropTypes.func,

  /**
   * Allows user to pass a function to be executed when the dropdown state is changed.
   */
  "onChange": PropTypes.func,

  /**
   * If included, dropdown will return and error onBlur or onChange if not checked.
   */
  "required": PropTypes.bool,

  /**
   * Allows the user to pass a function for custom validation. Should return either true or false.
   */
  "errorCallback": PropTypes.func,

  /* . */
  "clickEvent": PropTypes.func,

  /**
   * Allows the user to pass a function for custom validation. Should return either true or false.
   */
  "errorCallback": PropTypes.func,

  /* The children elements to be wrapped by the dropdown menu. */
  "children": PropTypes.node.isRequired,

  /* Pass CSS styles to className to set them on the dropdown component. */
  "className": PropTypes.string,

  /* Default text to show in collapsed dropdown on initial render */
  "defaultText": PropTypes.string,

  /* Allows user to ask for user feedback before changing the selected value of the Dropdown. */
  "onBeforeChange": PropTypes.func,

  /* Allows user to set custom width of dropdown */
  "buttonWidth": PropTypes.string
};

Dropdown.defaultProps = {
  "className": "",
  "buttonWidth": "160",
  "required": false,
  "disabled": false
};

export default Dropdown;
<commit_msg>Change to ul from span, pass back value then event, finanally persist events.<commit_after>import React from "react";
import PropTypes from "prop-types";
import cx from "classnames";
import { ButtonCore } from "../Button";
import messages from "../utils/messages.js";

/**
 * Master Dropdown Component
 * Only used for dropdown component
 * Supports required, disabled, custom width, custom error messaging, onclick and onchange functions
 */
class Dropdown extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      "active": false,
      "output": this._getOutput(),
      "value": this._getValue() || '',
      "valid": true,
      "errorMessage": "This field is required",
      "onChange": "",
      "focus": false,
      "zIndex": false
    };
    let isFocus = false;
  }

  _getOutput = () => {
    let count = React.Children.count(this.props.children);
    for(var i = 0; i < count; i++) {
      if(this.props.children[i].props.selected){
        return this.props.children[i].props.children
      }
    }
    if(this.props.defaultText){
      return this.props.defaultText;
    } else {
      return messages.selectOne;
    }
  }

  _getValue = () => {
    let count = React.Children.count(this.props.children);
    for(var i = 0; i < count; i++) {
      if(this.props.children[i].props.selected){
        return this.props.children[i].props.value
      }
    }
  }

  /**
   * closes dropdown click outside of browser window
   */
  _onWindowBlur = () => {
    if (this.state.active === true) {
      this.setState({
        "active": false,
        "zIndex": false
      });
    }
  };

  /**
   *  _clickHandler is used when the dropdown option is selected.
   *
   */
  _clickHandler = (i, event) => {
    event.persist();
    if (!this.props.disabled) {
      if (
        typeof this.props.onBeforeChange === "undefined" ||
        this.props.onBeforeChange(this.state.active)
      ) {
        const output = this.props.children[i].props.children;
        const inputValue = this.props.children[i].props.value;
        this.setState({
          "index": i,
          "output": output,
          "active": !this.state.active,
          "value": inputValue,
          "valid": true,
          "zIndex": false
        }, function(){
          this._validationHandler(this.props.errorCallback);
          if (this.props.onChange) {
            this._customOnChangeEvent(event);
          }
          if (this.props.onClick) {
            this._customOnClickEvent(event);
          }
        });

      }
    }
  };

  _customOnChangeEvent = event => {
    /* Pass the event object, and a data object to the click handler.
    The data object contains a boolean for whether the dropdown was
    changed or not, plus all the props passed to the object.  */
    event.persist();
    this.props.onChange(event.target.innerText, event);
  };

  _customOnClickEvent = event => {
    /* Pass the event object, and a data object to the click handler.
      The data object contains a boolean for whether the dropdown was
      clicked or not, plus all the props passed to the object.  */
    event.persist();
    this.props.onClick(event.target.innerText, event);
  };

  _toggle = (focus, event) => {
    /* Toggles the dropdown from active to inactive state, sets valid to true and zIndex to true.
      Active is used to show/hide options, valid is used to show/hide error messaging related to validation and zIndex sets a class on the component to ensure it has the proper index on the DOM
     */
    let canProceed = true;
    if(focus === "click" && this.isFocus) {
      canProceed = false;
      this.isFocus = false;
    } else if (focus === true) {
      this.isFocus = true;
    }
    if (!this.props.disabled && canProceed) {
      const action = (focus && !this.state.active) ? true : false;
      if(action){
        this.setState({
          "focus": true,
          "active": true,
          "valid": true,
          "zIndex": true
        });
      } else {
        /* When the user exits dropdown the state is change for focus and validation method is called
         */
        this.setState({ "focus": false, "active": false, "zIndex": false });
        this._validationHandler(this.props.errorCallback);
      }

      if (this.props.onClick) {
        this._customOnClickEvent(event);
      }
    }
  };

  _validationHandler = callback => {
    /* Checks that required has been set to true and determines if errorCallback message was passed in a custom error message.
      Also sets state of valid depending on user action
      */
    let validationObject = {
      "valid":
        this.props.required && this.state.value !== "" ||
          !this.props.required,
      "message": this.state.errorMessage
    };
    if(callback){
      validationObject = callback(event, this.state.value);
    }
    this.setState({
      "valid": validationObject.valid,
      "errorMessage": validationObject.message
    });
  };

  _keyDown = event => {
    const indexValid = (typeof this.state.index === "number");
    let newIndex;
    event.preventDefault();
    if (event.key === "ArrowDown") {
      newIndex = (indexValid) ? this.state.index + 1 : 0;
      let count = React.Children.count(this.props.children);
      if(newIndex < count) {
        this.setState({
          index: newIndex
        });
      }
    } else if (event.key === "ArrowUp") {
      newIndex = this.state.index - 1;
      if(newIndex >= 0) {
        this.setState({
          index: newIndex
        });
      }
    } else if (event.key === "Enter") {
      this._clickHandler(this.state.index);
    }
  }

  render() {
    const {
      children,
      className,
      required,
      customLabel,
      buttonWidth,
      disabled
    } = this.props;
    const active = this.state.active;
    const error = !this.state.valid && !disabled ? true : false;
    let zIndex = this.state.zIndex ? true : false;
    const classes = cx({
      "active": active,
      "container": true,
      "zIndex": zIndex
    });

    const buttonClasses = cx({
      "ra_dropdown__dropdown-button": true,
      "ra_dropdown__error": error,
      "ra_dropdown__disabledClass": disabled
    });

    // Builds the option list from the children passed in
    // firstChild, lastChild and selected each have unique styling and those classes are added here
    const bound_children = children.map((child, i) => {
      let count = React.Children.count(this.props.children);
      let childClasses = cx({
        "ra_dropdown__selected": i === this.state.index,
        "ra_dropdown__firstChild": i === 0,
        "ra_dropdown__lastChild": i === count - 1
      });
      let kid =

 { // onMouseDown fires before onBlur. If changed to onClick it will fire after onBlur and not work.
            this._clickHandler(i, e);
          }}
        >
          {child}

      ;
      return kid;
    });

    const dropdownButtonClasses = cx(buttonClasses);

    return (

 {
          this._toggle(true, e);
        }}
        onBlur={(e) => {
          this._toggle(false, e);
        }}
        onKeyDown={e => {
          this._keyDown(e);
        }}
      >
        {customLabel &&

            {customLabel}
            {required &&
              *
            }

        }

 { this._toggle("click", e); }} styleName={"content"}>

            <ButtonCore
              styleName={"buttonClass"}
              className={dropdownButtonClasses}
            >
              {this.state.output}
            </ButtonCore>

          {this.state.active &&

{bound_children}

          }
          <input type="hidden" value={this.state.value} />

        {error &&

            {this.state.errorMessage}

        }

    );
  }
}

Dropdown.propTypes = {
  /**
   * Text for dropdown label
   * @examples 'Some Label'
   */
  "customLabel": PropTypes.string,

  /* Boolean value taht tells the dropdown whether to
    be open or not.*/
  "active": PropTypes.bool,

  /* Boolean value that tells the dropdown whether the value is valid and controls error message is returns false.*/
  "valid": PropTypes.bool,

  /**
   * If included, dropdown is disabled
   * @examples <Dropdown disabled />, <Dropdown disabled={true} />
   */
  "disabled": PropTypes.bool,

  /**
   * Allows user to pass a callback for click events.
   */
  "onClick": PropTypes.func,

  /**
   * Allows user to pass a function to be executed when the dropdown state is changed.
   */
  "onChange": PropTypes.func,

  /**
   * If included, dropdown will return and error onBlur or onChange if not checked.
   */
  "required": PropTypes.bool,

  /**
   * Allows the user to pass a function for custom validation. Should return either true or false.
   */
  "errorCallback": PropTypes.func,

  /* . */
  "clickEvent": PropTypes.func,

  /**
   * Allows the user to pass a function for custom validation. Should return either true or false.
   */
  "errorCallback": PropTypes.func,

  /* The children elements to be wrapped by the dropdown menu. */
  "children": PropTypes.node.isRequired,

  /* Pass CSS styles to className to set them on the dropdown component. */
  "className": PropTypes.string,

  /* Default text to show in collapsed dropdown on initial render */
  "defaultText": PropTypes.string,

  /* Allows user to ask for user feedback before changing the selected value of the Dropdown. */
  "onBeforeChange": PropTypes.func,

  /* Allows user to set custom width of dropdown */
  "buttonWidth": PropTypes.string
};

Dropdown.defaultProps = {
  "className": "",
  "buttonWidth": "160",
  "required": false,
  "disabled": false
};

export default Dropdown;
<|endoftext|>


<commit_before>import Rx from 'rxjs/Rx';

import {
  createMessage,
} from '../kernel/messaging';

import {
  focusCellEditor,
} from '../actions'

import {
  COMM_OPEN,
  COMM_MESSAGE,
  COMM_ERROR,
  NEW_KERNEL,
} from '../constants';

import * as uuid from 'uuid';

/**
 * creates a comm open message
 * @param  {string} comm_id       uuid
 * @param  {string} target_name   comm handler
 * @param  {any} data             up to the target handler
 * @param  {string} target_module [Optional] used to select a module that is responsible for handling the target_name
 * @return {jmp.Message}          Message ready to send on the shell channel
 */
export function createCommOpenMessage(comm_id, target_name, data = {}, target_module) {
  const msg = createMessage('comm_open', { content: { comm_id, target_name, data } });
  if (target_module) {
    msg.content.target_module = target_module;
  }
  return msg;
}

/**
 * creates a comm message for sending to a kernel
 * @param  {string}     comm_id    unique identifier for the comm
 * @param  {Object}     data       any data to send for the comm
 * @param  {Uint8Array} buffers    arbitrary binary data to send on the comm
 * @return {jmp.Message}           jupyter message for comm_msg
 */
export function createCommMessage(comm_id, data = {}, buffers = new Uint8Array()) {
  return createMessage('comm_msg', { content: { comm_id, data }, buffers });
}

/**
 * creates a comm close message for sending to a kernel
 * @param  {Object} parent_header    header from a parent jupyter message
 * @param  {string}     comm_id      unique identifier for the comm
 * @param  {Object}     data         any data to send for the comm
 * @return {jmp.Message}             jupyter message for comm_msg
 */
export function createCommCloseMessage(parent_header, comm_id, data = {}) {
  return createMessage('comm_close', { content: { comm_id, data }, parent_header });
}

/**
 * creates a comm error action
 * @param  {error} error any type of error to pass on
 * @return {Object}       Flux standard error action
 */
export const createCommErrorAction = error =>
  Rx.Observable.of({
    type: COMM_ERROR,
    payload: error,
    error: true,
  });

/**
 * Action creator for comm_open messages
 * @param  {jmp.Message} a comm_open message
 * @return {Object}      COMM_OPEN action
 */
export function commOpenAction(message) {
  console.log('commOpenAction');
  // invariant: expects a comm_open message
  return {
    type: COMM_OPEN,
    data: message.content.data,
    metadata: message.content.metadata,
    comm_id: message.content.comm_id,
    target_name: message.content.target_name,
    target_module: message.content.target_module,
    // Pass through the buffers
    buffers: message.blob || message.buffers,
    // NOTE: Naming inconsistent between jupyter notebook and jmp
    //       see https://github.com/n-riesco/jmp/issues/14
    //       We just expect either one
  };
}

/**
 * Action creator for comm_msg messages
 * @param  {jmp.Message} a comm_msg
 * @return {Object}      COMM_MESSAGE action
 */
export function commMessageAction(message) {
  console.log('commMessageAction');
  return {
    type: COMM_MESSAGE,
    comm_id: message.content.comm_id,
    data: message.content.data,
    // Pass through the buffers
    buffers: message.blob || message.buffers,
    // NOTE: Naming inconsistent between jupyter notebook and jmp
    //       see https://github.com/n-riesco/jmp/issues/14
    //       We just expect either one
  };
}

/**
 * creates all comm related actions given a new kernel action
 * @param  {Object} newKernelAction a NEW_KERNEL action
 * @return {ActionsObservable}          all actions resulting from comm messages on this kernel
 */
export function commActionObservable(newKernelAction) {
  const commOpenAction$ = newKernelAction.channels.iopub
    .ofMessageType(['comm_open'])
    .map(commOpenAction);

  const commMessageAction$ = newKernelAction.channels.iopub
    .ofMessageType(['comm_msg'])
    .map(commMessageAction);

  return Rx.Observable.merge(
    commOpenAction$,
    commMessageAction$
  ).retry();
}

/**
 * An epic that emits comm actions from the backend kernel
 * @param  {ActionsObservable} action$ Action Observable from redux-observable
 * @param  {redux.Store} store   the redux store
 * @return {ActionsObservable}         Comm actions
 */
export const commListenEpic = action$ =>
  action$.ofType(NEW_KERNEL)
    // We have a new channel
    .switchMap(commActionObservable);

export function importFileEpic(action$, store) {
  console.log('importFileEpic');
  return action$.ofType('CONVERT_FILE')
    // .map((action) => Rx.Observable.timer(0, 500).do(() => { console.log('timer'); }))
    // .mergeAll()
    // .filter(() => false);
    // .do((action) => { console.log('x'); })
    // .filter(() => false);
    .map((action) => {
      const state = store.getState();
      const channels = state.app.channels;
      if (!channels || !channels.iopub || !channels.shell) {
        throw new Error('kernel not connected');
      }

      console.log('importFileEpic map');
      const identity = uuid.v4();
      const commOpen = createCommOpenMessage(identity, 'import_file_comm', {some_data: 'abc'});
      const childMessages = channels.iopub.childOf(commOpen);
      console.log('commOpen');
      channels.shell.next(commOpen);
      console.log('after send commOpen');
      // return childMessages.do(() => { console.log('child msg'); });
      return Rx.Observable.timer(0, 500).do(() => { console.log('le timer'); });
      // return Rx.Observable.empty();
    })
    .mergeAll()
    .filter(() => false);
}
<commit_msg>print child msg<commit_after>import Rx from 'rxjs/Rx';

import {
  createMessage,
} from '../kernel/messaging';

import {
  focusCellEditor,
} from '../actions'

import {
  COMM_OPEN,
  COMM_MESSAGE,
  COMM_ERROR,
  NEW_KERNEL,
} from '../constants';

import * as uuid from 'uuid';

/**
 * creates a comm open message
 * @param  {string} comm_id       uuid
 * @param  {string} target_name   comm handler
 * @param  {any} data             up to the target handler
 * @param  {string} target_module [Optional] used to select a module that is responsible for handling the target_name
 * @return {jmp.Message}          Message ready to send on the shell channel
 */
export function createCommOpenMessage(comm_id, target_name, data = {}, target_module) {
  const msg = createMessage('comm_open', { content: { comm_id, target_name, data } });
  if (target_module) {
    msg.content.target_module = target_module;
  }
  return msg;
}

/**
 * creates a comm message for sending to a kernel
 * @param  {string}     comm_id    unique identifier for the comm
 * @param  {Object}     data       any data to send for the comm
 * @param  {Uint8Array} buffers    arbitrary binary data to send on the comm
 * @return {jmp.Message}           jupyter message for comm_msg
 */
export function createCommMessage(comm_id, data = {}, buffers = new Uint8Array()) {
  return createMessage('comm_msg', { content: { comm_id, data }, buffers });
}

/**
 * creates a comm close message for sending to a kernel
 * @param  {Object} parent_header    header from a parent jupyter message
 * @param  {string}     comm_id      unique identifier for the comm
 * @param  {Object}     data         any data to send for the comm
 * @return {jmp.Message}             jupyter message for comm_msg
 */
export function createCommCloseMessage(parent_header, comm_id, data = {}) {
  return createMessage('comm_close', { content: { comm_id, data }, parent_header });
}

/**
 * creates a comm error action
 * @param  {error} error any type of error to pass on
 * @return {Object}       Flux standard error action
 */
export const createCommErrorAction = error =>
  Rx.Observable.of({
    type: COMM_ERROR,
    payload: error,
    error: true,
  });

/**
 * Action creator for comm_open messages
 * @param  {jmp.Message} a comm_open message
 * @return {Object}      COMM_OPEN action
 */
export function commOpenAction(message) {
  console.log('commOpenAction');
  // invariant: expects a comm_open message
  return {
    type: COMM_OPEN,
    data: message.content.data,
    metadata: message.content.metadata,
    comm_id: message.content.comm_id,
    target_name: message.content.target_name,
    target_module: message.content.target_module,
    // Pass through the buffers
    buffers: message.blob || message.buffers,
    // NOTE: Naming inconsistent between jupyter notebook and jmp
    //       see https://github.com/n-riesco/jmp/issues/14
    //       We just expect either one
  };
}

/**
 * Action creator for comm_msg messages
 * @param  {jmp.Message} a comm_msg
 * @return {Object}      COMM_MESSAGE action
 */
export function commMessageAction(message) {
  console.log('commMessageAction');
  return {
    type: COMM_MESSAGE,
    comm_id: message.content.comm_id,
    data: message.content.data,
    // Pass through the buffers
    buffers: message.blob || message.buffers,
    // NOTE: Naming inconsistent between jupyter notebook and jmp
    //       see https://github.com/n-riesco/jmp/issues/14
    //       We just expect either one
  };
}

/**
 * creates all comm related actions given a new kernel action
 * @param  {Object} newKernelAction a NEW_KERNEL action
 * @return {ActionsObservable}          all actions resulting from comm messages on this kernel
 */
export function commActionObservable(newKernelAction) {
  const commOpenAction$ = newKernelAction.channels.iopub
    .ofMessageType(['comm_open'])
    .map(commOpenAction);

  const commMessageAction$ = newKernelAction.channels.iopub
    .ofMessageType(['comm_msg'])
    .map(commMessageAction);

  return Rx.Observable.merge(
    commOpenAction$,
    commMessageAction$
  ).retry();
}

/**
 * An epic that emits comm actions from the backend kernel
 * @param  {ActionsObservable} action$ Action Observable from redux-observable
 * @param  {redux.Store} store   the redux store
 * @return {ActionsObservable}         Comm actions
 */
export const commListenEpic = action$ =>
  action$.ofType(NEW_KERNEL)
    // We have a new channel
    .switchMap(commActionObservable);

export function importFileEpic(action$, store) {
  console.log('importFileEpic');
  return action$.ofType('CONVERT_FILE')
    // .map((action) => Rx.Observable.timer(0, 500).do(() => { console.log('timer'); }))
    // .mergeAll()
    // .filter(() => false);
    // .do((action) => { console.log('x'); })
    // .filter(() => false);
    .map((action) => {
      const state = store.getState();
      const channels = state.app.channels;
      if (!channels || !channels.iopub || !channels.shell) {
        throw new Error('kernel not connected');
      }

      console.log('importFileEpic map');
      const identity = uuid.v4();
      const commOpen = createCommOpenMessage(identity, 'import_file_comm', {some_data: 'abc'});
      const childMessages = channels.iopub.childOf(commOpen);
      console.log('commOpen');
      channels.shell.next(commOpen);
      console.log('after send commOpen');
      return childMessages.do(() => { console.log('child msg'); });
      // return Rx.Observable.timer(0, 500).do(() => { console.log('le timer'); });
      // return Rx.Observable.empty();
    })
    .mergeAll()
    .filter(() => false);
}
<|endoftext|>


<commit_before>/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author ikerr / http://verold.com
 */

THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {

	THREE.Mesh.call( this, geometry, material );

	this.type = 'SkinnedMesh';

	this.bindMode = "attached";
	this.bindMatrix = new THREE.Matrix4();
	this.bindMatrixInverse = new THREE.Matrix4();

	// init bones

	// TODO: remove bone creation as there is no reason (other than
	// convenience) for THREE.SkinnedMesh to do this.

	var bones = [];

	if ( this.geometry && this.geometry.bones !== undefined ) {

		var bone, gbone;

		for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {

			gbone = this.geometry.bones[ b ];

			bone = new THREE.Bone( this );
			bones.push( bone );

			bone.name = gbone.name;
			bone.position.fromArray( gbone.pos );
			bone.quaternion.fromArray( gbone.rotq );
			if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );

		}

		for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {

			gbone = this.geometry.bones[ b ];

			if ( gbone.parent !== - 1 && gbone.parent !== null ) {

				bones[ gbone.parent ].add( bones[ b ] );

			} else {

				this.add( bones[ b ] );

			}

		}

	}

	this.normalizeSkinWeights();

	this.updateMatrixWorld( true );
	this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );

};

THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;

THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {

	this.skeleton = skeleton;

	if ( bindMatrix === undefined ) {

		this.updateMatrixWorld( true );

		this.skeleton.calculateInverses();

		bindMatrix = this.matrixWorld;

	}

	this.bindMatrix.copy( bindMatrix );
	this.bindMatrixInverse.getInverse( bindMatrix );

};

THREE.SkinnedMesh.prototype.pose = function () {

	this.skeleton.pose();

};

THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {

	if ( this.geometry instanceof THREE.Geometry ) {

		for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {

			var sw = this.geometry.skinWeights[ i ];

			var scale = 1.0 / sw.lengthManhattan();

			if ( scale !== Infinity ) {

				sw.multiplyScalar( scale );

			} else {

				sw.set( 1, 0, 0, 0 ); // do something reasonable

			}

		}

	} else if ( this.geometry instanceof THREE.BufferGeometry ) {

		var vec = new THREE.Vector4();

		var skinWeight = this.geometry.attributes.skinWeight;

		for ( var i = 0; i < skinWeight.count; i ++ ) {

			vec.x = skinWeight.getX( i );
			vec.y = skinWeight.getY( i );
			vec.z = skinWeight.getZ( i );
			vec.w = skinWeight.getW( i );

			var scale = 1.0 / vec.lengthManhattan();

			if ( scale !== Infinity ) {

				vec.multiplyScalar( scale );

			} else {

				vec.set( 1, 0, 0, 0 ); // do something reasonable

			}

			skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );

		}

	}

};

THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {

	THREE.Mesh.prototype.updateMatrixWorld.call( this, true );

	if ( this.bindMode === "attached" ) {

		this.bindMatrixInverse.getInverse( this.matrixWorld );

	} else if ( this.bindMode === "detached" ) {

		this.bindMatrixInverse.getInverse( this.bindMatrix );

	} else {

		console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );

	}

};

THREE.SkinnedMesh.prototype.clone = function() {

	return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this );

};
<commit_msg>SkinnedMesh: Safer parent check. Fixes #8636.<commit_after>/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author ikerr / http://verold.com
 */

THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {

	THREE.Mesh.call( this, geometry, material );

	this.type = 'SkinnedMesh';

	this.bindMode = "attached";
	this.bindMatrix = new THREE.Matrix4();
	this.bindMatrixInverse = new THREE.Matrix4();

	// init bones

	// TODO: remove bone creation as there is no reason (other than
	// convenience) for THREE.SkinnedMesh to do this.

	var bones = [];

	if ( this.geometry && this.geometry.bones !== undefined ) {

		var bone, gbone;

		for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {

			gbone = this.geometry.bones[ b ];

			bone = new THREE.Bone( this );
			bones.push( bone );

			bone.name = gbone.name;
			bone.position.fromArray( gbone.pos );
			bone.quaternion.fromArray( gbone.rotq );
			if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );

		}

		for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {

			gbone = this.geometry.bones[ b ];

			if ( gbone.parent !== - 1 && gbone.parent !== null &&
					bones[ gbone.parent ] !== undefined ) {

				bones[ gbone.parent ].add( bones[ b ] );

			} else {

				this.add( bones[ b ] );

			}

		}

	}

	this.normalizeSkinWeights();

	this.updateMatrixWorld( true );
	this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );

};

THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;

THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {

	this.skeleton = skeleton;

	if ( bindMatrix === undefined ) {

		this.updateMatrixWorld( true );

		this.skeleton.calculateInverses();

		bindMatrix = this.matrixWorld;

	}

	this.bindMatrix.copy( bindMatrix );
	this.bindMatrixInverse.getInverse( bindMatrix );

};

THREE.SkinnedMesh.prototype.pose = function () {

	this.skeleton.pose();

};

THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {

	if ( this.geometry instanceof THREE.Geometry ) {

		for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {

			var sw = this.geometry.skinWeights[ i ];

			var scale = 1.0 / sw.lengthManhattan();

			if ( scale !== Infinity ) {

				sw.multiplyScalar( scale );

			} else {

				sw.set( 1, 0, 0, 0 ); // do something reasonable

			}

		}

	} else if ( this.geometry instanceof THREE.BufferGeometry ) {

		var vec = new THREE.Vector4();

		var skinWeight = this.geometry.attributes.skinWeight;

		for ( var i = 0; i < skinWeight.count; i ++ ) {

			vec.x = skinWeight.getX( i );
			vec.y = skinWeight.getY( i );
			vec.z = skinWeight.getZ( i );
			vec.w = skinWeight.getW( i );

			var scale = 1.0 / vec.lengthManhattan();

			if ( scale !== Infinity ) {

				vec.multiplyScalar( scale );

			} else {

				vec.set( 1, 0, 0, 0 ); // do something reasonable

			}

			skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );

		}

	}

};

THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {

	THREE.Mesh.prototype.updateMatrixWorld.call( this, true );

	if ( this.bindMode === "attached" ) {

		this.bindMatrixInverse.getInverse( this.matrixWorld );

	} else if ( this.bindMode === "detached" ) {

		this.bindMatrixInverse.getInverse( this.bindMatrix );

	} else {

		console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );

	}

};

THREE.SkinnedMesh.prototype.clone = function() {

	return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this );

};
<|endoftext|>


<commit_before>'use strict';

let gulp = require('gulp');
let del = require('del');
let imagemin = require('gulp-imagemin');

gulp.task('images:watch', function() {
  gulp.watch('./src/images/**/*.{png,jpg,jpeg,gif,svg}', ['images']);
});

gulp.task('images', function() {
  del('./public/images/**/*.{png,jpg,jpeg,gif,svg}', {dot: true});

  return gulp.src('./src/images/**/*.{png,jpg,jpeg,gif,svg}')
    .pipe(imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeViewBox: false}],
    }))
    .pipe(gulp.dest('./public/images'));
});
<commit_msg>Adds higher level of png optimisation<commit_after>'use strict';

let gulp = require('gulp');
let del = require('del');
let imagemin = require('gulp-imagemin');

gulp.task('images:watch', function() {
  gulp.watch('./src/images/**/*.{png,jpg,jpeg,gif,svg}', ['images']);
});

gulp.task('images', function() {
  del('./public/images/**/*.{png,jpg,jpeg,gif,svg}', {dot: true});

  return gulp.src('./src/images/**/*.{png,jpg,jpeg,gif,svg}')
    .pipe(imagemin({
      optimizationLevel: 7,
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeViewBox: false}],
    }))
    .pipe(gulp.dest('./public/images'));
});
<|endoftext|>


<commit_before>'use strict';

const gulp   = require('gulp');
const path   = require('path');
const ms     = require('merge-stream');
const config = require('../config.js');
const $      = require('../load.js');

/**
 * スプライトの生成
 */

gulp.task('sprite', () => {
	return gulp.src(config.path.sprite.src)
		.pipe($.flatmap((stream, file) => {
			if (!file.isDirectory()) { return stream; }

			const dirname       = file.path.split(path.sep).pop();
			const relative_path = path.relative(config.path.style.dest, config.path.image.dest);
			const is_retina     = /2x$/.test(dirname);
			const options    = {
				cssTemplate        : 'gulp/templates/spritesmith.handlebars',
				cssSpritesheetName : dirname,
				imgName            : `${dirname}.png`,
				cssName            : `_${dirname}.scss`,
				imgPath            : `${relative_path}/${dirname}.png`,
				algorithm          : 'binary-tree',
				padding            : 6,
				cssOpts            : {
					scale  : is_retina ? .5 : 1
				}
			};

			const data = gulp.src(`${file.path}/*.png`)
				.pipe($.plumber({errorHandler: $.notify.onError('<%= error.message %>')}))
				.pipe($.spritesmith(options));
			const image = data.img.pipe(gulp.dest(config.path.sprite.dest.image));
			const style = data.css.pipe(gulp.dest(config.path.sprite.dest.style));

			return ms(image, style);
		}));
});
<commit_msg>JSのbraceのあとにセミコロンはつけない<commit_after>'use strict';

const gulp   = require('gulp');
const path   = require('path');
const ms     = require('merge-stream');
const config = require('../config.js');
const $      = require('../load.js');

/**
 * スプライトの生成
 */

gulp.task('sprite', () => {
	return gulp.src(config.path.sprite.src)
		.pipe($.flatmap((stream, file) => {
			if (!file.isDirectory()) { return stream; }

			const dirname       = file.path.split(path.sep).pop();
			const relative_path = path.relative(config.path.style.dest, config.path.image.dest);
			const is_retina     = /2x$/.test(dirname);
			const options    = {
				cssTemplate        : 'gulp/templates/spritesmith.handlebars',
				cssSpritesheetName : dirname,
				imgName            : `${dirname}.png`,
				cssName            : `_${dirname}.scss`,
				imgPath            : `${relative_path}/${dirname}.png`,
				algorithm          : 'binary-tree',
				padding            : 6,
				cssOpts            : {
					scale  : is_retina ? .5 : 1
				}
			}

			const data = gulp.src(`${file.path}/*.png`)
				.pipe($.plumber({errorHandler: $.notify.onError('<%= error.message %>')}))
				.pipe($.spritesmith(options));
			const image = data.img.pipe(gulp.dest(config.path.sprite.dest.image));
			const style = data.css.pipe(gulp.dest(config.path.sprite.dest.style));

			return ms(image, style);
		}));
});
<|endoftext|>


<commit_before>'use strict';

var config = require('../../.project/.config'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),
    path = require('path'),
    del = require('del'),
    rename = require('gulp-rename'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    autoprefixer = require('gulp-autoprefixer'),
    cssGlob = require('gulp-css-globbing'),
    cssNano = require('gulp-cssnano'),
    //strip = require('gulp-strip-css-comments'),
    sassdoc = require('sassdoc'),
    watch = require('gulp-watch'),
    notify = require('gulp-notify');

module.exports = function() {

    // paths
    var srcGlob = [
            config.srcPath + '/styles.scss',
            config.srcCssPath + '/**/*.scss'
        ],
        dest = config.destCssPath,
        docs = config.destDocsPathCss;

    gulp.add('styles:build', function(done) {

        // cleanup
        del.sync([dest + '*[.css,.css.map', dest + '/themes/*[.css,.css.map'], { force: true });

        // build
        gulp.src(srcGlob)
            .pipe(plumber(function(error) {
                gutil.log(error.message);
                notify().write(error.message);
                this.emit('end');
            }))
            .pipe(sourcemaps.init())
            .pipe(cssGlob({ extensions: ['.scss'], ignoreFolders: ['.', './scss'] }))
            .pipe(sass({
                outputStyle: 'expanded',
                defaultEncoding: 'utf-8',
                unixNewlines: false,
                cacheLocation: config.srcPath + '.sass-cache/',
                precision: 4,
                compass: false,
                includePaths: ['node_modules'],
                errLogToConsole: true,
                stopOnError: false
            }).on('error', function(err) {
                notify({ title: 'SASS compile issue' }).write('line ' + err.line + ', col ' + err.column + ': ' + err.messageOriginal);
                //notify(err.messageOriginal);
                this.emit('end');
            }))
            .pipe(autoprefixer({ browsers: ['> 5%', 'IE 11', 'last 3 version'], cascade: false }))
            .pipe(cssNano({ zindex: false }))
            //.pipe(strip({ preserve: false }))
            .pipe(rename({ suffix: '.min' }))
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest(dest));

        done();
    });

    gulp.add('styles:watch', function() {
        watch(config.srcPath + '/**/*.scss', {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styles:build', 'server:reload']);
        });
    });

    gulp.add('styles:docs', function(done) {
        gulp.src(config.srcPath + '/**/*.scss')
            .pipe(sassdoc({
                package: './package.json',
                dest: docs
            }))
            .resume();
        done();
    });
};
<commit_msg>Fixed stylesheet cleanup on build<commit_after>'use strict';

var config = require('../../.project/.config'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),
    path = require('path'),
    del = require('del'),
    rename = require('gulp-rename'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    autoprefixer = require('gulp-autoprefixer'),
    cssGlob = require('gulp-css-globbing'),
    cssNano = require('gulp-cssnano'),
    //strip = require('gulp-strip-css-comments'),
    sassdoc = require('sassdoc'),
    watch = require('gulp-watch'),
    notify = require('gulp-notify');

module.exports = function() {

    // paths
    var srcGlob = [
            config.srcPath + '/styles.scss',
            config.srcCssPath + '/**/*.scss'
        ],
        dest = config.destCssPath,
        docs = config.destDocsPathCss;

    gulp.add('styles:build', function(done) {

        // cleanup
        del.sync([dest + '*[.css,.css.map]', dest + '/themes/*[.css,.css.map]'], { force: true });

        // build
        gulp.src(srcGlob)
            .pipe(plumber(function(error) {
                gutil.log(error.message);
                notify().write(error.message);
                this.emit('end');
            }))
            .pipe(sourcemaps.init())
            .pipe(cssGlob({ extensions: ['.scss'], ignoreFolders: ['.', './scss'] }))
            .pipe(sass({
                outputStyle: 'expanded',
                defaultEncoding: 'utf-8',
                unixNewlines: false,
                cacheLocation: config.srcPath + '.sass-cache/',
                precision: 4,
                compass: false,
                includePaths: ['node_modules'],
                errLogToConsole: true,
                stopOnError: false
            }).on('error', function(err) {
                notify({ title: 'SASS compile issue' }).write('line ' + err.line + ', col ' + err.column + ': ' + err.messageOriginal);
                //notify(err.messageOriginal);
                this.emit('end');
            }))
            .pipe(autoprefixer({ browsers: ['> 5%', 'IE 11', 'last 3 version'], cascade: false }))
            .pipe(cssNano({ zindex: false }))
            //.pipe(strip({ preserve: false }))
            .pipe(rename({ suffix: '.min' }))
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest(dest));

        done();
    });

    gulp.add('styles:watch', function() {
        watch(config.srcPath + '/**/*.scss', {
            read: false
        }, function(file) {
            gutil.log('>>> ' + path.relative(file.base, file.path) + ' (' + file.event + ').');
            gulp.start(['styles:build', 'server:reload']);
        });
    });

    gulp.add('styles:docs', function(done) {
        gulp.src(config.srcPath + '/**/*.scss')
            .pipe(sassdoc({
                package: './package.json',
                dest: docs
            }))
            .resume();
        done();
    });
};
<|endoftext|>


<commit_before>module.exports = function(app) {
  return new Handler(app);
};

var Handler = function(app) {
  this.app = app;
};

/**
 * New client entry.
 *
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next stemp callback
 * @return {Void}
 */
Handler.prototype.entry = function(msg, session, next) {
  next(null, {code: 200, msg: 'game server is ok.'});
};

/**
 * Publish route for mqtt connector.
 *
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next stemp callback
 * @return {Void}
 */
Handler.prototype.publish = function(msg, session, next) {
	var result = {
		topic: 'publish',
		payload: JSON.stringify({code: 200, msg: 'publish message is ok.'})
	};
  next(null, result);
};

/**
 * Subscribe route for mqtt connector.
 *
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next stemp callback
 * @return {Void}
 */
Handler.prototype.subscribe = function(msg, session, next) {
	var result = {
		topic: 'subscribe',
		payload: JSON.stringify({code: 200, msg: 'subscribe message is ok.'})
	};
  next(null, result);
};<commit_msg>Fix typos in the entryHandler.js of the template<commit_after>module.exports = function(app) {
  return new Handler(app);
};

var Handler = function(app) {
  this.app = app;
};

/**
 * New client entry.
 *
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next step callback
 * @return {Void}
 */
Handler.prototype.entry = function(msg, session, next) {
  next(null, {code: 200, msg: 'game server is ok.'});
};

/**
 * Publish route for mqtt connector.
 *
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next step callback
 * @return {Void}
 */
Handler.prototype.publish = function(msg, session, next) {
	var result = {
		topic: 'publish',
		payload: JSON.stringify({code: 200, msg: 'publish message is ok.'})
	};
  next(null, result);
};

/**
 * Subscribe route for mqtt connector.
 *
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next step callback
 * @return {Void}
 */
Handler.prototype.subscribe = function(msg, session, next) {
	var result = {
		topic: 'subscribe',
		payload: JSON.stringify({code: 200, msg: 'subscribe message is ok.'})
	};
  next(null, result);
};
<|endoftext|>


<commit_before>/*
  gulpfile.js
  ===========
  Rather than manage one giant configuration file responsible
  for creating multiple tasks, each task has been broken out into
  its own file in gulpfile.js/tasks. Any files in that directory get
  automatically required below.

  To add a new task, simply add a new task file that directory.
  gulpfile.js/tasks/default.js specifies the default set of tasks to run
  when you run `gulp`.
*/

const requireDir = require('require-dir')
const gutil = require('gulp-util')

gutil.env['version'] = 'v3'

// Require all tasks in gulpfile.js/tasks
requireDir('./tasks', { recurse: false })
<commit_msg>Removal of V3 flag reference<commit_after>/*
  gulpfile.js
  ===========
  Rather than manage one giant configuration file responsible
  for creating multiple tasks, each task has been broken out into
  its own file in gulpfile.js/tasks. Any files in that directory get
  automatically required below.

  To add a new task, simply add a new task file that directory.
  gulpfile.js/tasks/default.js specifies the default set of tasks to run
  when you run `gulp`.
*/

const requireDir = require('require-dir')

// Require all tasks in gulpfile.js/tasks
requireDir('./tasks', { recurse: false })
<|endoftext|>


<commit_before>const gulp = require("gulp");
const gutil = require("gulp-util");
const Promise = require("bluebird");

const { options } = require("./config");
const { checkOutputFile, fs, newer, spawn, stampPath,
        touchAsync } = require("./util");

// This task also needs to check the hash of the latest commit because typedoc
// generates links to source based on the latest commit in effect when it is
// run. So if a commit happened between the time the doc was generated last, and
// now, we need to regenerate the docs.
gulp.task("typedoc", ["generate-ts", "stamp-dir", "lint"],
          Promise.coroutine(function *task() {
            const sources = ["lib/**/*.ts"];
            const stamp = stampPath("typedoc");
            const hashPath = "./build/typedoc.hash.txt";

            const [savedHash, [currentHash]] = yield Promise.all(
              [fs.readFileAsync(hashPath)
               .then(hash => hash.toString())
               .catch(() => undefined),
               checkOutputFile("git", ["rev-parse", "--short", "HEAD"]),
              ]);

            if ((currentHash === savedHash) && !(yield newer(sources, stamp))) {
              gutil.log("No change, skipping typedoc.");
              return;
            }

            const tsoptions = [
              "--out", "./build/api",
              "--name", "wed",
              "--tsconfig", "./lib/tsconfig.json",
              "--exclude", "**/lib/tests/**/*",
              "--listInvalidSymbolLinks",
            ];

            if (!options.doc_private) {
              tsoptions.push("--excludePrivate");
            }

            yield spawn("./node_modules/.bin/typedoc", tsoptions,
                        { stdio: "inherit" });

            yield Promise.all([fs.writeFileAsync(hashPath, currentHash),
                               touchAsync(stamp)]);
          }));
<commit_msg>Force including private entities in typedoc-generated doc.<commit_after>const gulp = require("gulp");
const gutil = require("gulp-util");
const Promise = require("bluebird");

const { options } = require("./config");
const { checkOutputFile, fs, newer, spawn, stampPath,
        touchAsync } = require("./util");

// This task also needs to check the hash of the latest commit because typedoc
// generates links to source based on the latest commit in effect when it is
// run. So if a commit happened between the time the doc was generated last, and
// now, we need to regenerate the docs.
gulp.task("typedoc", ["generate-ts", "stamp-dir", "lint"],
          Promise.coroutine(function *task() {
            const sources = ["lib/**/*.ts"];
            const stamp = stampPath("typedoc");
            const hashPath = "./build/typedoc.hash.txt";

            const [savedHash, [currentHash]] = yield Promise.all(
              [fs.readFileAsync(hashPath)
               .then(hash => hash.toString())
               .catch(() => undefined),
               checkOutputFile("git", ["rev-parse", "--short", "HEAD"]),
              ]);

            if ((currentHash === savedHash) && !(yield newer(sources, stamp))) {
              gutil.log("No change, skipping typedoc.");
              return;
            }

            const tsoptions = [
              "--out", "./build/api",
              "--name", "wed",
              "--tsconfig", "./lib/tsconfig.json",
              "--exclude", "**/lib/tests/**/*",
              "--listInvalidSymbolLinks",
            ];

            // For now we require that private entities be included in the
            // documentation due to an issue in typedoc whereby public object
            // properties defined in a private constructor won't be included in
            // the documentation.
            // eslint-disable-next-line no-constant-condition
            if (false && !options.doc_private) {
              tsoptions.push("--excludePrivate");
            }

            yield spawn("./node_modules/.bin/typedoc", tsoptions,
                        { stdio: "inherit" });

            yield Promise.all([fs.writeFileAsync(hashPath, currentHash),
                               touchAsync(stamp)]);
          }));
<|endoftext|>


<commit_before>'use strict';
(() => {
  const debounce = (func, wait, immediate) => {
    let timeout;
    return () => {
      const context = this;
      const args = arguments;

      const later = () => {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };

      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) { func.apply(context, args); }
    };
  };

  module.exports = (gulp, plugins, config) => {
    return () => {
      gulp.watch(['./rocketbelt/**/*.scss', './templates/scss/**/*.scss'], ['styles']);
      gulp.watch(['./templates/**/*.pug'], ['views']);
      gulp.watch(['./rocketbelt/**/*.js'], ['copy-js', 'uglify']);
      gulp.watch(config.buildPath + '/**/*.html')
        .on('change', plugins.browserSync.reload);
      gulp.watch(config.buildPath + '/**/*.js')
        .on('change', plugins.browserSync.reload);

      global.isWatching = true;

      return true;
    }
  };
})();
<commit_msg>Watch task not re-symlinking template indexes<commit_after>'use strict';
(() => {
  const debounce = (func, wait, immediate) => {
    let timeout;
    return () => {
      const context = this;
      const args = arguments;

      const later = () => {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };

      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) { func.apply(context, args); }
    };
  };

  module.exports = (gulp, plugins, config) => {
    return () => {
      gulp.watch(['./rocketbelt/**/*.scss', './templates/scss/**/*.scss'], ['styles']);
      gulp.watch(['./templates/**/*.pug'], ['views', 'link-templates']);
      gulp.watch(['./rocketbelt/**/*.js'], ['copy-js', 'uglify']);
      gulp.watch(config.buildPath + '/**/*.html')
        .on('change', plugins.browserSync.reload);
      gulp.watch(config.buildPath + '/**/*.js')
        .on('change', plugins.browserSync.reload);

      global.isWatching = true;

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


<commit_before>/**图片压缩
 * 开发*/

var gulp = require('gulp'),

    imagemin = require('gulp-imagemin'),//图片压缩

    pngquant = require('imagemin-pngquant'),//png压缩

    cache = require('gulp-cache');//缓存

function devImg() {

    gulp.src('src/icon/*.{png,jpg}')

        .pipe(cache(imagemin({

            progressive: true,

            use: [pngquant()]

        })))

        .pipe(gulp.dest('build/icon'));

    gulp.src("src/fonts/*.*")

        .pipe(gulp.dest('build/fonts'))

}

module.exports = devImg;<commit_msg>修改图片配置文件<commit_after>/**图片压缩
 * 开发*/

var gulp = require('gulp'),

    imagemin = require('gulp-imagemin'),//图片压缩

    pngquant = require('imagemin-pngquant'),//png压缩

    cache = require('gulp-cache');//缓存

function devImg() {

    gulp.src('src/icon/*.{png,jpg}')

        .pipe(cache(imagemin({

            progressive: true,

            use: [pngquant()]

        })))

        .pipe(gulp.dest('build/icon'));

    gulp.src('src/images/**/*.{png,jpg}')

        .pipe(cache(imagemin({

            progressive: true,

            use: [pngquant()]

        })))

        .pipe(gulp.dest('build/images'));

    gulp.src("src/fonts/*.*")

        .pipe(gulp.dest('build/fonts'))

}

module.exports = devImg;<|endoftext|>


<commit_before>// import the paths
//
const paths = require('./paths.json');

module.exports = (gulp) =>
    gulp.watch(paths.lint, ['lint']);
<commit_msg>updated path<commit_after>// import the paths
//
const paths = require('../paths.json');

module.exports = (gulp) =>
    gulp.watch(paths.lint, ['lint']);
<|endoftext|>