text:
import express from 'express';
import http from 'http';
import {
    ChatConnector,
    UniversalBot,
    LuisRecognizer,
    HeroCard,
    CardImage,
    CardAction,
    Message,
    TextFormat,
    EntityRecognizer,
    Prompts,
    ListStyle,
    ResumeReason
} from 'botbuilder';
import uuid from 'uuid';
import emoji from 'node-emoji';

import Spotify from './lib/spotify';

let app = express();

let server = http.Server(app);

const port = process.env.PORT;
server.listen(port, function () {
   console.log('listening to %s', port);
});

// Create chat bot
const connector = new ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD,
    gzipData: true
});

const parseName = function(session, def) {
    if (!session.message.user) return def;
    var name = session.message.user.name.trim().toLowerCase().match(/^[\w]+/i);

    return name === '' ? def : name;
}

const bot = new UniversalBot(connector, function (session) {
    session.send("sorry %s, I didn't understand", parseName(session));
    session.beginDialog('ShowHelp');
});

const getSpotify = function(session, options) {
    var message = null;
    if (session.conversationData.spotifyToken && session.conversationData.spotifyUser) {
        return new Spotify(session.conversationData.spotifyToken, session.conversationData.spotifyUser);
    } else {
        message = 'okay before I do that, do you have a **premium** spotify account?'
        session.replaceDialog('AuthorizeSpotify', { message, options });
    }
}

const createTrackCard = function(session, track) {
    var artist = track.artists && track.artists.length > 0 ? track.artists[0].name : 'not sure who';
    var title = track.name;
    var album = track.album.name;
    var image = track.album.images[1];
    var url = track.external_urls.spotify;

    var date = new Date(null);
    date.setSeconds(track.duration_ms / 1000);
    var mins = date.toISOString().substr(14, 5);

    return new HeroCard(session)
        .title(artist + ' - ' + title)
        .subtitle(mins)
        .text(album)
        .images([ CardImage.create(session, image.url) ])
        .tap(CardAction.openUrl(session, url));
}

const createPlaylistCard = function(session, playlist, images = true) {
    var image = playlist.images[0];
    var url = playlist.external_urls.spotify;

    var card = new HeroCard(session)
        .title(playlist.name)
        .subtitle(playlist.tracks.total + ' tracks')
        .tap(CardAction.openUrl(session, url));

    if (images) {
        card.images([ CardImage.create(session, image.url) ]);
    }

    return card;
}

app.post('/api/messages', connector.listen());

app.get('/', function(req, res) {
    res.send('I\'m a bot... get out!');
});

app.get('/spotify/authorized', function(req, res) {
    if (req.query.code && req.query.state) {
        var state = JSON.parse(Buffer.from(req.query.state, 'base64'));

        res.send('
thanks, just close this window <3
');
        bot.beginDialog(state.address, 'SpotifyAuthorized', {
            authCode: req.query.code,
            dialog: state.dialog,
            dialogArgs: state.args
        });

    } else {
        res.status(500);
        res.send('
cannot authorize bot :(
');
    }
});

// install mention middleware. fixes #2530 and #2419
bot.use({
    receive: (e, session, next) => {
        const mention = '@' + e.address.bot.name;
        if (e.type === 'message') {
            if (e.text.includes(mention)) {
                e.text = e.text.replace(mention, '').trim();
            }
        }

        next();
    }
});

// Enable Conversation Data persistence
bot.set('persistConversationData', true);

const recognizer = new LuisRecognizer(process.env.LOUIS_MODEL);
bot.recognizer(recognizer);

const playTrack = async function(session, spotify, track) {
    session.send('now playing. enjoy ' + emoji.get('musical_note'));
    session.sendTyping();

    var playback = null;

    if (session.conversationData.spotifyDevice) {
        try {
            playback = await spotify.play(track.uri, session.conversationData.spotifyDevice.id, session.conversationData.spotifyPlaylist.uri);
        } catch (err) {
            session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
            console.log(err);
        }

        if (playback) {
            var card = createTrackCard(session, track);
            var msg = new Message(session)
                .textFormat(TextFormat.markdown)
                .attachments([ card ]);
            session.send(msg);
        } else {
            session.send('can\'t play on current device. :(\n\ntry to say "devices" to select one :)');
        }
    } else {
        session.send('device not set. say "show devices" to get started.');
    }
}

const playPlaylist = async function(session, spotify, playlist) {
    session.send('playing **%s** %s', playlist.name, emoji.get('musical_note'));
    session.sendTyping();

    var playback = null;

    if (session.conversationData.spotifyDevice) {
        try {
            playback = await spotify.play(null, session.conversationData.spotifyDevice.id, playlist.uri);
            session.conversationData.spotifyPlaylist = playlist;
        } catch (err) {
            session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
            console.log(err);
        }

        if (playback) {
            var card = createPlaylistCard(session, playlist);
            var msg = new Message(session)
                .textFormat(TextFormat.markdown)
                .attachments([ card ]);
            session.send(msg);
        } else {
            session.send('can\'t play on current device. :(\n\ntry to say "devices" to select one');
        }
    } else {
        session.send('device not set. type "show devices" to get started.');
    }
}

const queueTrack = async function(session, spotify, query, message = true) {
    session.send('looking for **%s**...', query);
    session.sendTyping();

    try {
        var tracks = await spotify.search(query);

        if (tracks) {
            var track = tracks[0];

            var playback = await spotify.addTrackToPlaylist(track.uri, session.conversationData.spotifyBotPlaylist.id);
            if (message) {
                session.send('**%s** by **%s** added to **bot queue** (y)', track.name, track.artists[0].name);
                if (session.conversationData.spotifyBotPlaylist.id !== session.conversationData.spotifyPlaylist.id) {
                    session.send('you\'re not under **bot queue**, type "browse" to select it ;)');
                }
            }

            return tracks;
        } else {
            session.endDialog('no music found, sorry.');
            return;
        }

    } catch (err) {
        session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
        console.log(err);
    }
}

const playTrackNumber = async function(session, spotify, number) {
    session.sendTyping();
    var data = await spotify.getPlaylistTracks(session.conversationData.spotifyPlaylist.owner.id, session.conversationData.spotifyPlaylist.id);
    if (data && data.length > 0) {
        var track = data[Math.max(1, number) - 1];
        if (track) {
            await playTrack(session, spotify, track);
        } else {
            session.send('track **#%s** not in queue. try to type "show queue" to get a list of tracks :)', number);
        }
    } else {
        session.send('track number not found :(');
    }
}

const playTrackQuery = async function(session, spotify, query, message = true) {
    session.send('looking for **%s**...', query);
    session.sendTyping();

    try {
        var tracks = await spotify.search(query);

        if (tracks) {
            var track = tracks[0];

            var playback = null;
            if (session.conversationData.spotifyDevice) {
                await spotify.addTrackToPlaylist(track.uri, session.conversationData.spotifyBotPlaylist.id);
                playback = await spotify.play(track.uri, session.conversationData.spotifyDevice.id, session.conversationData.spotifyBotPlaylist.uri);

                if (playback) {
                    if (session.conversationData.spotifyPlaylist.id !== session.conversationData.spotifyBotPlaylist.id) {
                        session.send('now playing on **bot\'s queue** ' + emoji.get('musical_note'));
                        session.conversationData.spotifyPlaylist = session.conversationData.spotifyBotPlaylist;
                    }
                    if (message) {
                        var card = createTrackCard(session, track);
                        var msg = new Message(session)
                            .textFormat(TextFormat.markdown)
                            .attachments([ card ]);
                        session.send(msg);
                    }

                    return tracks;
                } else {
                    session.send('can\'t play on current device. :(\n\ntry to say "devices" to select one');
                }
            } else {
                session.send('device not set. type "show devices" to get started.');
            }
        } else {
            session.endDialog('no music found, sorry.');
            return;
        }
    } catch (err) {
        session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
        console.log(err);
    }
}

bot.on('conversationUpdate', function (message) {
   // Check for group conversations
    if (message.address.conversation.isGroup) {
        // Send a hello message when bot is added
        if (message.membersAdded) {
            message.membersAdded.forEach(function (identity) {
                if (identity.id === message.address.bot.id) {
                    var reply = new Message()
                        .address(message.address)
                        .text("hello everyone!");
                    bot.send(reply);
                    bot.beginDialog(message.address, 'ShowHelp');
                }
            });
        }

        // Send a goodbye message when bot is removed
        if (message.membersRemoved) {
            message.membersRemoved.forEach(function (identity) {
                if (identity.id === message.address.bot.id) {
                    var reply = new Message()
                        .address(message.address)
                        .text("k bye");
                    bot.send(reply);
                }
            });
        }
    }
});

bot.on('contactRelationUpdate', function (message) {
    if (message.action === 'add') {
        var reply = new Message()
                .address(message.address)
                .text("hello %s...", parseName({ message }));
        bot.send(reply);
        bot.beginDialog(message.address, 'ShowHelp');
    } else {
        bot.beginDialog(message.address, 'DeleteUserData', { message: 'k bye' });
    }
});

bot.on('deleteUserData', function (message) {
    bot.beginDialog(message.address, 'DeleteUserData', { message: 'got it' });
});

bot.dialog('Greeting', [
    function(session, args) {
        var greeting =  EntityRecognizer.findEntity(args.intent.entities, 'greeting');

        var msg = new Message(session)
            .text([
                'hi %s',
                "what's up?",
                'yes?',
                'hello %s',
                'what can I do for you %s?',
                'you again %s?',
                'what do you want today %s?',
                'what is it that you want %s?',
                'what do you want?',
                'yoh',
                'hey %s',
                'hey'
            ], parseName(session));

        session.send(msg);
        Prompts.confirm(session, 'do you need help?')
    },
    function(session, results) {
        if (results.response) {
            session.send([
                'got it',
                'okay',
                'no problem',
                'sure'
            ]);

            session.beginDialog('ShowHelp');
        } else {
            session.endDialog([
                'kool',
                '(y)',
                ':)',
                'yep',
                'ok',
                'k',
                'got it'
            ]);
        }
    }
]).triggerAction({
    matches: 'Greeting'
});

bot.dialog('Compliment', function(session, args) {
    session.endDialog([
        'no problem %s!',
        '(y)',
        'okay %s',
        'sure %s',
        'anytime ;)'
    ], parseName(session));

}).triggerAction({
    matches: /^(?:\@[\w-_]+\s+)?(?:thanks|thank you)/i
});

bot.dialog('PlayerControl', function(session, args) {
    if (!args) return session.endDialog('use common playback words like "play", "pause", etc.');

    for (var i in Spotify.playbackCommands) {
        var command = Spotify.playbackCommands[i];

        var commandEntity = EntityRecognizer.findEntity(args.intent.entities, 'player_command::' + command);
        if (commandEntity) {
            var number = EntityRecognizer.findEntity(args.intent.entities, 'builtin.number');
            var time = EntityRecognizer.findEntity(args.intent.entities, 'builtin.datetime.time');
            var switchOn = EntityRecognizer.findEntity(args.intent.entities, 'switch::on');
            var switchOff = EntityRecognizer.findEntity(args.intent.entities, 'switch::off');

            return session.beginDialog('ApplyPlayerCommand', {
                number: number && number.entity,
                time: time && time.entity,
                switchOn,
                switchOff,
                command
            });
        }
    }

}).triggerAction({
    matches: 'PlayerControl'
});

bot.dialog('ApplyPlayerCommand', async function(session, args) {
    session.sendTyping();

    var spotify = getSpotify(session, {
        resumeDialog: 'ApplyPlayerCommand',
        dialogArgs: {
            ...args
        }
    });

    if (spotify) {
        try {
            if (session.conversationData.spotifyDevice) {
                var result = await spotify.playback(args, session.conversationData.spotifyDevice.id, (message) => {
                    session.send('%s', message);
                });

                if (!result) {
                    session.send('cannot connect to device. try to say "devices" to select one :)');
                }

                session.endDialogWithResult({ response: result })
            } else {
                session.send('can\'t play on current device. :(\n\ntry to say "devices" to select one');
                session.endDialogWithResult();
            }
        } catch (err) {
            session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
            console.log(err);
        }
    }
});

bot.dialog('PlaylistControl', function(session, args) {
    if (!args) return session.endDialog('use command playlist words like "browse", "show", "clear", etc.');

    var create = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::create');
    var show = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::show');
    var browse = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::browse');
    var playlistquery = EntityRecognizer.findEntity(args.intent.entities, 'playlistquery');

    var clear = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::clear');
    var add = EntityRecognizer.findEntity(args.intent.entities, 'playlist_command::add');

    var songtitle =  EntityRecognizer.findEntity(args.intent.entities, 'songtitle');
    var songartist = EntityRecognizer.findEntity(args.intent.entities, 'songartist');

    if (show) {
        if (/top|featured/i.test(session.message.text)) {
            session.send('you meant to **browse** playlist right? :)');
            session.beginDialog('BrowsePlaylists', { playlistquery: playlistquery && playlistquery.entity });
        } else {
            session.beginDialog('ShowPlaylistQueue');
        }
    } else if (clear) {
        session.beginDialog('ClearPlaylist');
    } else if (browse) {
        session.beginDialog('BrowsePlaylists', { playlistquery: playlistquery && playlistquery.entity });
    } else if (add || songtitle) {
        if (songtitle) {
            var trackQuery = songtitle.entity + (songartist ? ' artist:' + songartist.entity : '');
            session.beginDialog('AddMusic', {
                trackQuery
            });
        }
    } else {
        if (/playlist|queue/i.test(session.message.text)) {
            session.send('you meant to show queue right? :)');
            session.beginDialog('ShowPlaylistQueue');
        } else {
            session.endDialog('not sure what you mean there.');
        }
    }

}).triggerAction({
    matches: 'PlaylistControl'
}).cancelAction('cancelPlaylistControl', 'k', { matches: /^(?:\@[\w-_]+\s+)?(?:cancel|nvm|nevermind)/i });

const browseTypes = {
    '1. My Playlists' : 'user-playlists',
    '2. Featured' : 'featured-playlists',
    '3. Genres & Moods' : 'categories',
    '4. Charts' : 'charts',
    '5. Search' : 'search'
};

bot.dialog('BrowsePlaylists', [
    function(session, args, next) {
        if (args) {
            if (args.playlistquery) {
                next({
                    response: {
                        entity: Object.keys(browseTypes)[4],
                        searchQuery: args.playlistquery
                    }
                });

                return;
            } else if (args.selectedType) {
                next({
                    response: {
                        entity: args.selectedType
                    }
                });

                return;
            }
        }

        Prompts.choice(session, 'pick one...', browseTypes, { listStyle: ListStyle['button'] });
    },
    async function (session, results, next) {
        if (results.response) {
            session.sendTyping();

            session.dialogData.selectedType = results.response.entity;
            var type = browseTypes[results.response.entity];

            if (type === 'categories') {
                var spotify = getSpotify(session, {
                    resumeDialog: 'BrowsePlaylists',
                    dialogArgs: {
                        selectedType: results.response.entity
                    }
                });

                if (spotify) {
                    var categoriesData = await spotify.getBrowseCategories();
                    if (categoriesData) {
                        var categories = {};

                        categoriesData.forEach((category) => {
                            categories[category.name] = category.id;
                        });

                        session.dialogData.categories = categories;
                        Prompts.choice(session, 'select your genre/mood...', categories, { listStyle: ListStyle['auto'] });
                    }
                }

            } else if (type === 'search') {
                if (results.response.searchQuery) {
                    session.send('searching for **%s**', results.response.searchQuery)
                    next({ response: results.response.searchQuery })
                } else {
                    Prompts.text(session, 'so what are you looking for?');
                }
            } else {
                next();
            }
        }
    },
    async function(session, results, next) {
        if (session.dialogData.selectedType) {
            var spotify = getSpotify(session, {
                resumeDialog: 'BrowsePlaylists',
                dialogArgs: {
                    selectedType: session.dialogData.selectedType
                }
            });

            if (spotify) {
                var type = browseTypes[session.dialogData.selectedType];
                try {
                    var options = {};
                    if (type === 'categories') {
                        if (results.response.entity) {
                            options.categoryId = session.dialogData.categories[results.response.entity];
                            options.shouldSearch = false; // should search for playlists
                        } else {
                            session.send('you must choose your mood :(');
                            return session.endDialogWithResult({
                                resumed: ResumeReason.notCompleted
                            });
                        }
                    } else if (type === 'search') {
                        if (results.response) {
                            options.query = results.response;
                        } else {
                            session.send('you must be looking for something. try again later :)');
                            return session.endDialogWithResult({
                                resumed: ResumeReason.notCompleted
                            });
                        }
                    }

                    session.sendTyping();
                    var data = await spotify.browsePlaylists(type, options);

                    if (data && data.length > 0) {
                        var playlists = {};

                        data.forEach((playlist) => {
                            playlists[playlist.name] = playlist;
                        });

                        session.dialogData.playlists = playlists;
                        Prompts.choice(session, 'here\'s what I got. type the number or "cancel" ;)', playlists, { listStyle: ListStyle['auto'] });
                    } else {
                        session.send('nothing :(');
                        session.endDialogWithResult();
                    }
                } catch (err) {
                    session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                    console.log(err);
                }
            }
        }
    },
    async function(session, results) {
        if (results.response) {
            if (results.response.entity && session.dialogData.playlists[results.response.entity]) {
                var playlist = session.dialogData.playlists[results.response.entity];
                var spotify = getSpotify(session);
                if (spotify) {
                    try {
                        await playPlaylist(session, spotify, playlist);
                    } catch (err) {
                        session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                        console.log(err);
                    }
                }
            }
        }
    }
]).cancelAction('cancelBrowsePlaylists', 'k', { matches: /^(?:\@[\w-_]+\s+)?(?:cancel|nvm|nevermind)/i });

bot.dialog('ShowPlaylistQueue', [
    async function(session, args, next) {
        session.sendTyping();

        var spotify = getSpotify(session, {
            resumeDialog: 'ShowPlaylistQueue'
        });

        if (spotify) {
            try {
                var currentTrack = await spotify.getCurrentTrack();
                var data = await spotify.getPlaylistTracks(session.conversationData.spotifyPlaylist.owner.id, session.conversationData.spotifyPlaylist.id);
                if (data && data.length > 0) {
                    var tracks = {};
                    data.forEach((track) => {
                        var text = currentTrack && currentTrack.id === track.id ?
                            '**' + track.artists[0].name + ' - ' + track.name + '** ' + emoji.get('musical_note') :
                            track.artists[0].name + ' - ' + track.name;

                        tracks[text] = track;
                    });

                    session.dialogData.tracks = tracks;
                    var card = createPlaylistCard(session, session.conversationData.spotifyPlaylist, false);
                    var msg = new Message(session)
                        .textFormat(TextFormat.markdown)
                        .attachments([ card ]);

                    session.send(msg);
                    Prompts.choice(session, 'pick one or type "cancel" ;)', tracks, { listStyle: ListStyle['auto'] });
                } else {
                    session.send('no tracks found in current playlist :(\n\nmaybe it\'s private. tsk.');
                    session.endDialogWithResult();
                }
            } catch (err) {
                session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                console.log(err);
            }
        }
    },
    async function(session, results, next) {
        if (results.response && results.response.entity) {
            var spotify = getSpotify(session, {
                resumeDialog: 'ShowPlaylistQueue'
            });

            if (spotify) {
                try {
                    var track = session.dialogData.tracks[results.response.entity];
                    await playTrack(session, spotify, track);
                    session.endDialogWithResult();
                } catch (err) {
                    session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                    console.log(err);
                }
            }
        }
    }
]).cancelAction('cancelShowPlaylistQueue', 'k', { matches: /^(?:\@[\w-_]+\s+)?(?:cancel|nvm|nevermind)/i });

bot.dialog('ClearPlaylist', [
    function(session, args) {
        Prompts.confirm(session, 'are you sure you want to clear our **bot queue**?');
    },
    async function(session, results) {
        session.sendTyping();

        var spotify = getSpotify(session, { resumeDialog: 'ClearPlaylist' });
        if (spotify) {
            if (results.response) {
                try {
                    var result = await spotify.clearPlaylist(session.conversationData.spotifyBotPlaylist.id);
                    if (result) {
                        session.send('done (y)');
                    } else {
                        session.send('can\'t :(');
                    }
                    session.endDialogWithResult();
                } catch (err) {
                    session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                    console.log(err);
                }
            } else {
                session.send('I thought so ;)');
                session.endDialogWithResult({
                    resumed: ResumeReason.canceled
                });
            }
        }
    }
]);

bot.dialog('SongQuery', async function(session, args) {
    session.sendTyping();

    var spotify = getSpotify(session, { resumeDialog: 'SongQuery' });
    if (spotify) {
        try {
            const track = await spotify.getCurrentTrack();

            if (track) {
                session.send('here you go');
                var card = createTrackCard(session, track);
                var msg = new Message(session)
                    .textFormat(TextFormat.markdown)
                    .attachments([ card ]);
                session.send(msg);
            } else {
                session.send('nothing. try to say "play shape of you" ;)');
            }
        } catch (err) {
            session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
            console.log(err);
        }
    }
}).triggerAction({
    matches: 'SongQuery'
});

bot.dialog('ShowHelp', [
    function(session, args) {
        if (!session.conversationData.spotifyUser) {
            session.send('setup spotify by saying "init"');
        }

        if (!session.conversationData.spotifyDevice) {
            session.send('setup your device by saying "devices"');
        }

        var helps = [
            'browse',
            'play/queue shape of you',
            'play, pause, next, previous, etc.',
            'search for "top hits"',
            'show queue',
            'quit'
        ];
        session.send('command me by saying...\n\n- ' + helps.join('\n- '));
        Prompts.confirm(session, 'do you want more?');
    },
    function(session, results) {
        if (results.response) {
            var moreHelps = [
                'clear queue',
                'play track 5',
                'set volume 80%',
                'seek 2:00',
                'set repeat',
                'set shuffle',
                'what\'s playing?',
                'help'
            ];

            session.send('here\'s more I can do...\n\n- ' + moreHelps.join('\n- '));
            session.endDialogWithResult();
        } else {
            session.send([
                'I thought so ;)',
                'got it (y)',
                '(y)',
                ';)',
                'kool'
            ]);

            session.endDialogWithResult({
                resumed: ResumeReason.notCompleted
            });
        }
    }
]).triggerAction({
    matches: 'ShowHelp'
});

bot.dialog('PlayMusic', [
    async function(session, args, next) {
        if (!args) return session.endDialog();

        var trackQuery = null;
        var trackNumber = null;
        var playCommand = null;

        if (args.playTrackQuery) {
            trackQuery = args.playTrackQuery;
        } else if (args.playTrackNumber) {
            trackNumber = args.playTrackNumber;
        } else if (args.playCommand) {
            playCommand = args.playCommand;
        } else {
            if (args.intent) {
                var songtitle =  EntityRecognizer.findEntity(args.intent.entities, 'songtitle');
                var songartist = EntityRecognizer.findEntity(args.intent.entities, 'songartist');
                var play = EntityRecognizer.findEntity(args.intent.entities, 'player_command::play');
                var number = EntityRecognizer.findEntity(args.intent.entities, 'builtin.number');

                if (songtitle) {
                    trackQuery = songtitle.entity + (songartist ? ' artist:' + songartist.entity : '');
                } else if (play) {
                    playCommand = true;
                    trackNumber = number && number.entity;
                }
            }
        }

        var spotify = getSpotify(session, {
            resumeDialog: 'PlayMusic',
            dialogArgs: {
                playTrackQuery: trackQuery,
                playTrackNumber: trackNumber,
                playCommand: playCommand
            }
        });

        if (spotify) {
            try {
                if (trackQuery) {
                    const tracks = await playTrackQuery(session, spotify, trackQuery);
                    if (tracks && tracks.length > 1) {
                        var artists = [];

                        tracks.forEach((track) => {
                            var artist = track.artists[0];
                            var query = artist.name + ' - ' + track.name;

                            if (artists.indexOf(query) === -1) {
                                artists.push(query);
                            }
                        });

                        Prompts.choice(session, 'found other versions too...', artists, { listStyle: ListStyle['button'] });
                    }

                    session.endDialog();
                } else {

                    if (play) {
                        if (trackNumber) {
                            await playTrackNumber(session, spotify, parseInt(trackNumber));
                        } else {

                            var query = session.message.text.replace(play.entity, '').trim();
                            if (query !== '') {
                                session.dialogData.trackQuery = query;
                                Prompts.confirm(session, 'are you looking for "' + query + '"?');
                            } else {
                                session.beginDialog('ApplyPlayerCommand', { command: 'play' });
                            }
                        }
                    } else {
                        session.endDialog();
                    }
                }

            } catch (err) {
                session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                console.log(err);
            }
        }

    },
    function(session, results) {
        if (results.response) {
            session.beginDialog('PlayMusic', { playTrackQuery: session.dialogData.trackQuery });
        }
    }
]).triggerAction({
    matches: 'PlayMusic'
});

bot.dialog('AddMusic', [
    async function(session, args) {
        if (!args) return session.endDialogWithResult();

        var trackQuery = args.trackQuery;

        if (trackQuery) {
            var spotify = getSpotify(session, {
                resumeDialog: 'AddMusic',
                dialogArgs: { queueTrack: trackQuery }
            });

            if (spotify) {
                try {
                    var tracks = await queueTrack(session, spotify, trackQuery);
                    if (tracks && tracks.length > 1) {
                        var artists = [];

                        tracks.forEach((track) => {
                            var artist = track.artists[0];
                            var query = artist.name + ' - ' + track.name;

                            if (artists.indexOf(query) === -1) {
                                artists.push(query);
                            }
                        });

                        Prompts.choice(session, 'you might want to check some of these...', artists, { listStyle: ListStyle['auto'] });
                    } else {
                        session.endDialogWithResult();
                    }
                } catch (err) {
                    session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                    console.log(err);
                }
            }
        } else {
            session.endDialogWithResult();
        }
    },
    async function(session, results) {
        if (results.response) {
            if (results.response.entity) {
                var spotify = getSpotify(session);
                if (spotify) {
                    try {
                        await queueTrack(session, spotify, results.response.entity);
                        session.send('(y)');
                    } catch (err) {
                        session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                        console.log(err);
                    }

                    session.endDialogWithResult();
                }
            } else {
                session.endDialogWithResult();
            }
        }
    }
]);

bot.dialog('SpotifySetDevice', [
    async function(session, args, next) {
        session.sendTyping();

        var spotify = getSpotify(session, {
            resumeDialog: 'SpotifySetDevice',
            dialogArgs: { playTrackQuery: args && args.playTrackQuery }
        });

        if (spotify) {
            var devices = {};

            try {
                var devicesData = await spotify.getDevices();

                if (devicesData && devicesData.length > 0) {
                    devicesData.forEach((device) => {
                        devices[device.type + ' - ' + device.name] = device;
                    });

                    session.dialogData.devices = devices;
                    session.dialogData.playTrackQuery = args && args.playTrackQuery;

                    if (devicesData.length > 1) {
                        Prompts.choice(session, "which of these devices you want me use?", devices, { listStyle: ListStyle['button'] });
                    } else {
                        var defaultDevice = devicesData[0].type + ' - ' + devicesData[0].name;
                        session.send('playing on device **%s**', defaultDevice);
                        next({ response: { entity: defaultDevice } })
                    }
                } else {
                    session.send('no devices found. **open spotify** and try again :)');
                    session.endDialogWithResult({
                        resumed: ResumeReason.notCompleted
                    });
                }
            } catch (err) {
                session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                console.log(err);
            }
        }
    },
    async function(session, results) {
        session.sendTyping();

        if (results.response) {
            if (results.response.entity) {
                var device = session.dialogData.devices[results.response.entity];
                session.conversationData.spotifyDevice = device;
                session.send('(y)');

                var spotify = getSpotify(session, {
                    resumeDialog: 'SpotifySetDevice',
                    dialogArgs: { playTrackQuery: session.dialogData.playTrackQuery }
                });

                if (spotify) {
                    try {
                        await spotify.setDevice(device.id);
                        if (session.dialogData.playTrackQuery) {
                            await playTrackQuery(session, spotify, session.dialogData.playTrackQuery);
                        }
                    } catch (err) {
                        session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                        console.log(err);
                    }
                }

                session.endDialogWithResult();
            } else {
                session.send('no problem - going to use active device then ;)');
                session.endDialogWithResult();
            }
        }
    }
]).triggerAction({
    matches: /^(?:\@[\w-_]+\s+)?(?:show devices|list devices|devices|setup devices|setup device)/i
}).cancelAction('cancelSpotifySetDevice', 'k', { matches: /^(?:\@[\w-_]+\s+)?(?:cancel|nvm|nevermind)/i });;

bot.dialog('CreatePlaylist', [
    function(session, args, next) {
        if (args && args.name) {
            next({ response: args.name });
        } else {
            session.send('creating your playlist...');
            Prompts.text(session, 'what\'s the name?');
        }
    },
    async function(session, results) {
        session.sendTyping();

        var spotify = getSpotify(session, {
            resumeDialog: 'CreatePlaylist',
            dialogArgs: results.response
        });

        if (spotify) {
            if (results.response) {
                try {
                    var playlist = await spotify.createPlaylist(results.response);
                    if (playlist) {
                        session.send('playlist **%s** created (y)', results.response);
                        session.conversationData.spotifyBotPlaylist = playlist;
                        if (!session.conversationData.spotifyPlaylist) {
                            session.conversationData.spotifyPlaylist = playlist;
                        }

                        session.endDialogWithResult({
                            response: { playlist }
                        });
                    } else {
                        session.send('cannot create playlist :(');
                        session.endDialogWithResult({
                            resumed: ResumeReason.notCompleted
                        });
                    }
                } catch (err) {
                    session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
                    console.log(err);
                }
            }
        }
    }
]);

bot.dialog('SpotifyAuthorized', [
    async function(session, args, next) {
        session.sendTyping();

        try {
            // authorize spotify
            var tokenData = await Spotify.initToken(args.authCode);
            var data = await new Spotify(tokenData).init();

            if (data && tokenData) {
                session.send('thanks! just a moment...');

                session.conversationData.args = args;
                session.conversationData.spotifyUser = data.userData;
                session.conversationData.spotifyToken = tokenData;

                if (!data.playlist) {
                    session.beginDialog('CreatePlaylist', { name: process.env.SPOTIFY_QUEUE_PLAYLIST_NAME });
                } else {
                    session.conversationData.spotifyPlaylist = data.playlist;
                    session.conversationData.spotifyBotPlaylist = data.playlist;
                    next();
                }

            } else {
                session.send('something went wrong ;(... restarting over.');
                session.replaceDialog('AuthorizeSpotify');
            }
        } catch (err) {
            session.send('opps... bot make bobo ' + emoji.get('face_with_head_bandage'));
            console.log(err);
        }
    },
    function(session, results) {
        session.beginDialog('SpotifySetDevice');
    },
    async function(session, results) {
        var args = session.conversationData.args;
        if (args && args.dialog) {
            session.send('all set! now where were we...');
            session.beginDialog(args.dialog, args && args.dialogArgs);
        } else {
            session.endDialog('all set!');
        }
    }
]);

bot.dialog('AuthorizeSpotify', [
    function(session, args) {
        session.dialogData.resumeDialog = args.options && args.options.resumeDialog;
        session.dialogData.dialogArgs = args.options && args.options.dialogArgs;
        Prompts.confirm(session, args.message ? args.message : 'do you want me to use your spotify account to play music?');
    },
    function(session, results) {
        if (results.response) {
            var state = Buffer.from(JSON.stringify({
                address: session.message.address,
                dialog: session.dialogData.resumeDialog,
                args: session.dialogData.dialogArgs
            })).toString('base64');

            session.send('good. click below to authorize me...');
            var msg = new Message(session)
                .attachments([
                    new HeroCard(session)
                        .title("accounts.spotify.com")
                        .subtitle("Authorize bot to play music, search and do some cool stuff.")
                        .tap(CardAction.openUrl(session, 'https://accounts.spotify.com/authorize?client_id=933adf0420af4eecb7d70cc8c7687d70&response_type=code&redirect_uri='+encodeURIComponent(process.env.SPOTIFY_REDIRECT_URI)+'&scope=user-read-playback-state+user-modify-playback-state+playlist-read-private+playlist-modify-public+user-library-read+user-read-private+user-read-email+user-follow-modify+playlist-read-collaborative+playlist-modify-private+user-library-modify+user-read-birthdate+user-follow-read+user-top-read&state=' + encodeURIComponent(state)))
                ]);

            session.endDialog(msg);

        } else {
            session.endDialog('k nvm');
        }
    }
]).triggerAction({
    matches: /^(?:\@[\w-_]+\s+)?(?:turn on|setup|init|start|load|reset)/i
}).cancelAction('cancelAuthorizeSpotify', 'k', { matches: /^(?:\@[\w-_]+\s+)?(?:cancel|nvm|nevermind)/i });

bot.dialog('DeleteUserData', function(session, args) {
    session.conversationData = {};
    session.userData = {};

    session.endDialog(args.message ? args.message : [
        'all clear! ;)',
        'cleared',
        'shutting down... (y)',
        'done!',
        'bye',
        'k bye'
    ]);
}).triggerAction({
    matches: /^(?:\@[\w-_]+\s+)?(?:terminate|exit|shutdown|turn off|quit|leave)/i
});


text:
<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Authenticated Controller
 *
 * Provides a base class for all controllers that must check user login status.
 *
 * @package  Bonfire\Core\Controllers\Authenticated_Controller
 * @category Controllers
 * @author   Bonfire Dev Team
 * @link     http://cibonfire.com/docs
 *
 */
class Authenticated_Controller extends Base_Controller
{

    protected $require_authentication = true;

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

    /**
     * Class constructor setup login restriction and load various libraries
     *
     * @return void
     */
    public function __construct()
    {
        $this->autoload['helpers'][]   = 'form';
        $this->autoload['libraries'][] = 'Template';
        $this->autoload['libraries'][] = 'Assets';
        $this->autoload['libraries'][] = 'form_validation';

        parent::__construct();

        $this->form_validation->CI =& $this;
        $this->form_validation->set_error_delimiters('', '');
    }
}

redpajama_set_name: RedPajamaGithub


text:
// JavaScript Olympics

// I paired Jovanka Nikolovski on this challenge.

// This challenge took me [#] hours.

// Warm Up

// Bulk Up
var athletes = [
  {name: "Sarah Hughes", event: "Ladies' Singles"},
  {name: "Michael Phelps", event: "Swimming"}
]

function winner(athletes) {
  for(var i = 0; i < athletes.length; i++) {
    athletes[i].win = function() {
      console.log(this.name + " won the " + this.event + " event.");
    }
  }
};

winner(athletes);
athletes[0].win();

// Jumble your words

function reverseWords(words) {
 console.log(words.split("").reverse().join(""));
};

var words = "!sdrow ruoy elbmuJ"
reverseWords(words)

// 2,4,6,8

function evenNumbers(numbers) {
  var evenArray = [];
  for(var i = 0; i < numbers.length; i++) {
    if(numbers[i] % 2 === 0){
      evenArray.push(numbers[i]);
    }
  }
  return console.log(evenArray);
}

var numbers = [1,2,3,4,5,6,7,8,9,10];

evenNumbers(numbers);

// "We built this city"

function Athlete(name, age, sport, quote) {
    this.name = name;
    this.age = age;
    this.sport = sport;
    this.quote = quote;
};

var michaelPhelps = new Athlete("Michael Phelps", 29, "swimming", "It's medicinal I swear!")
console.log(michaelPhelps.constructor === Athlete)
console.log(michaelPhelps.name + " " + michaelPhelps.sport + " " + michaelPhelps.quote)

// Reflection

/*
  What JavaScript knowledge did you solidify in this challenge?
  This challenge really helped me solidify my knowledge in writing a function in JavaScript and iterating over an array.

  What are constructor functions?
  Constructor functions contain related variables or blocks of code that can be called in later code. They're useful for situations in which there are repetitive sections of code.

  How are constructors different from Ruby classes (in your research)?
  The constructor is the class definition in JavaScript, but in Ruby the constructor is one of the functions in the class.
*/


text:
package org.pentaho.di.core.logging;

/**
 * This enumeration describes the logging status in a logging table for transformations and jobs.
 *
 * @author matt
 *
 */
public enum LogStatus {

  START( "start" ), END( "end" ), STOP( "stop" ), ERROR( "error" ), RUNNING( "running" ), PAUSED( "paused" );

  private String status;

  private LogStatus( String status ) {
    this.status = status;
  }

  public String getStatus() {
    return status;
  }

  @Override
  public String toString() {
    return status;
  }

  public boolean equals( LogStatus logStatus ) {
    return status.equalsIgnoreCase( logStatus.status );
  }

  /**
   * Find the LogStatus based on the string description of the status.
   *
   * @param status
   *          the status string to search for
   * @return the LogStatus or null if none is found
   */
  public static LogStatus findStatus( String status ) {
    for ( LogStatus logStatus : values() ) {
      if ( logStatus.status.equalsIgnoreCase( status ) ) {
        return logStatus;
      }
    }
    return null;
  }
}


text:
"""Tests for tensorflow.ops.tf.scatter."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf

def _AsType(v, vtype):
    return v.astype(vtype) if isinstance(v, np.ndarray) else vtype(v)

def _NumpyAdd(ref, indices, updates):
    # Since numpy advanced assignment does not support repeated indices,
    # we run a simple loop to perform scatter_add.
    for i, indx in np.ndenumerate(indices):
        ref[indx] += updates[i]

def _NumpySub(ref, indices, updates):
    for i, indx in np.ndenumerate(indices):
        ref[indx] -= updates[i]

class ScatterTest(tf.test.TestCase):
    def _VariableRankTest(self, np_scatter, tf_scatter, vtype, itype, use_gpu,
                          repeat_indices=False):
        np.random.seed(8)
        with self.test_session(use_gpu=use_gpu):
            for indices_shape in (), (2,), (3, 7), (3, 4, 7):
                for extra_shape in (), (5,), (5, 9):
                    # Generate random indices with no duplicates for easy numpy comparison
                    size = np.prod(indices_shape, dtype=itype)
                    first_dim = 3 * size
                    indices = np.arange(first_dim)
                    np.random.shuffle(indices)
                    indices = indices[:size]
                    if size > 1 and repeat_indices:
                        # Add some random repeats.
                        indices = indices[:size // 2]
                        for _ in range(size - size // 2):
                            # Randomly append some repeats.
                            indices = np.append(indices, indices[np.random.randint(size // 2)])
                        np.random.shuffle(indices)
                    indices = indices.reshape(indices_shape)
                    updates = _AsType(np.random.randn(*(indices_shape + extra_shape)),
                                      vtype)
                    old = _AsType(np.random.randn(*((first_dim,) + extra_shape)), vtype)

                    # Scatter via numpy
                    new = old.copy()
                    np_scatter(new, indices, updates)
                    # Scatter via tensorflow
                    ref = tf.Variable(old)
                    ref.initializer.run()
                    tf_scatter(ref, indices, updates).eval()
                    # Compare
                    self.assertAllClose(ref.eval(), new)

    def _VariableRankTests(self, np_scatter, tf_scatter):
        for vtype in (np.float32, np.float64):
            for itype in (np.int32, np.int64):
                for use_gpu in (False, True):
                    self._VariableRankTest(np_scatter, tf_scatter, vtype, itype, use_gpu)

    def testVariableRankUpdate(self):
        def update(ref, indices, updates):
            ref[indices] = updates

        self._VariableRankTests(update, tf.scatter_update)

    def testVariableRankAdd(self):
        self._VariableRankTests(_NumpyAdd, tf.scatter_add)

    def testVariableRankSub(self):
        self._VariableRankTests(_NumpySub, tf.scatter_sub)

    def _ScatterRepeatIndicesTest(self, np_scatter, tf_scatter):
        for vtype in (np.float32, np.float64):
            for itype in (np.int32, np.int64):
                for use_gpu in (False, True):
                    self._VariableRankTest(np_scatter, tf_scatter, vtype, itype, use_gpu,
                                           repeat_indices=True)

    def testScatterRepeatIndices(self):
        """This tests scatter_add using indices that repeat."""
        self._ScatterRepeatIndicesTest(_NumpyAdd, tf.scatter_add)
        self._ScatterRepeatIndicesTest(_NumpySub, tf.scatter_sub)

    def testBooleanScatterUpdate(self):
        with self.test_session(use_gpu=False) as session:
            var = tf.Variable([True, False])
            update0 = tf.scatter_update(var, 1, True)
            update1 = tf.scatter_update(var, tf.constant(0, dtype=tf.int64), False)
            var.initializer.run()

            session.run([update0, update1])

            self.assertAllEqual([False, True], var.eval())

    def testScatterOutOfRangeCpu(self):
        for op in (tf.scatter_add, tf.scatter_sub, tf.scatter_update):
            params = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32)
            updates = np.array([-3, -4, -5]).astype(np.float32)
            with self.test_session(use_gpu=False):
                ref = tf.Variable(params)
                ref.initializer.run()

                # Indices all in range, no problem.
                indices = np.array([2, 0, 5])
                op(ref, indices, updates).eval()

                # Test some out of range errors.
                indices = np.array([-1, 0, 5])
                with self.assertRaisesOpError('indices is out of range'):
                    op(ref, indices, updates).eval()

                indices = np.array([2, 0, 6])
                with self.assertRaisesOpError('indices is out of range'):
                    op(ref, indices, updates).eval()

    # TODO(fpmc): Re-enable this test when gpu_pip test actually runs on a GPU.
    def _disabledTestScatterOutOfRangeGpu(self):
        if not tf.test.IsBuiltWithCuda():
            return
        for op in (tf.scatter_add, tf.scatter_sub, tf.scatter_update):
            params = np.array([1, 2, 3, 4, 5, 6]).astype(np.float32)
            updates = np.array([-3, -4, -5]).astype(np.float32)
            # With GPU, the code ignores indices that are out of range.
            # We don't test the implementation; just test there's no failures.
            with self.test_session(force_gpu=True):
                ref = tf.Variable(params)
                ref.initializer.run()

                # Indices all in range, no problem.
                indices = np.array([2, 0, 5])
                op(ref, indices, updates).eval()

                # Indicies out of range should not fail.
                indices = np.array([-1, 0, 5])
                op(ref, indices, updates).eval()
                indices = np.array([2, 0, 6])
                op(ref, indices, updates).eval()

if __name__ == "__main__":
    tf.test.main()


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     Dieser Code wurde von einem Tool generiert.
//     Laufzeitversion:4.0.30319.42000
//
//     Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
//     der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Microsoft.WindowsAPICodePack.ShellExtensions.Resources {
    using System;

    /// <summary>
    ///   Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
    /// </summary>
    // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
    // -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
    // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
    // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class LocalizedMessages {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal LocalizedMessages() {
        }

        /// <summary>
        ///   Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("EnhanceForm.Microsoft.WindowsAPICodePack.ShellExtensions.Resources.LocalizedMessa" +
                            "ges", typeof(LocalizedMessages).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
        ///   Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Control has not yet been assigned. Methods requiring it cannot be called. ähnelt.
        /// </summary>
        internal static string PreviewHandlerControlNotInitialized {
            get {
                return ResourceManager.GetString("PreviewHandlerControlNotInitialized", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die {0} must implement one or more of IPreviewFromStream, IPreviewFromShellObject or IPreviewFromFile. ähnelt.
        /// </summary>
        internal static string PreviewHandlerInterfaceNotImplemented {
            get {
                return ResourceManager.GetString("PreviewHandlerInterfaceNotImplemented", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die PreviewHandler '{0}' must have exactly one PreviewHandler attribute. ähnelt.
        /// </summary>
        internal static string PreviewHandlerInvalidAttributes {
            get {
                return ResourceManager.GetString("PreviewHandlerInvalidAttributes", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Unable to call interface {0} because it is not supported on this object. ähnelt.
        /// </summary>
        internal static string PreviewHandlerUnsupportedInterfaceCalled {
            get {
                return ResourceManager.GetString("PreviewHandlerUnsupportedInterfaceCalled", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die The sum of offset and count must be less than or equal to the size of the buffer. ähnelt.
        /// </summary>
        internal static string StorageStreamBufferOverflow {
            get {
                return ResourceManager.GetString("StorageStreamBufferOverflow", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Count must be greater than or equal to zero. ähnelt.
        /// </summary>
        internal static string StorageStreamCountLessThanZero {
            get {
                return ResourceManager.GetString("StorageStreamCountLessThanZero", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die The stream was initialized as read-only. ähnelt.
        /// </summary>
        internal static string StorageStreamIsReadonly {
            get {
                return ResourceManager.GetString("StorageStreamIsReadonly", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Offset must be greater than or equal to zero. ähnelt.
        /// </summary>
        internal static string StorageStreamOffsetLessThanZero {
            get {
                return ResourceManager.GetString("StorageStreamOffsetLessThanZero", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die {0} does not implement IThumbnailFromStream and so requires DisableProcessIsolation set to true. ähnelt.
        /// </summary>
        internal static string ThumbnailProviderDisabledProcessIsolation {
            get {
                return ResourceManager.GetString("ThumbnailProviderDisabledProcessIsolation", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die {0} must implement one or more of IThumbnailFromStream, IThumbnailFromShellObject or IThumbnailFromFile. ähnelt.
        /// </summary>
        internal static string ThumbnailProviderInterfaceNotImplemented {
            get {
                return ResourceManager.GetString("ThumbnailProviderInterfaceNotImplemented", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Cannot retrieve handle because proxy window has not been created. ähnelt.
        /// </summary>
        internal static string WpfPreviewHandlerNoHandle {
            get {
                return ResourceManager.GetString("WpfPreviewHandlerNoHandle", resourceCulture);
            }
        }
    }
}


text:
use std::fmt;

use header;
use http::{self, Body};
use status::StatusCode;
use version;

/// The Response sent to a client after receiving a Request in a Service.
///
/// The default `StatusCode` for a `Response` is `200 OK`.
pub struct Response<B = Body> {
    head: http::MessageHead<StatusCode>,
    body: Option<B>,
}

impl<B> Response<B> {
    /// Create a new Response.
    #[inline]
    pub fn new() -> Response<B> {
        Response::default()
    }

    /// The headers of this response.
    #[inline]
    pub fn headers(&self) -> &header::Headers { &self.head.headers }

    /// The status of this response.
    #[inline]
    pub fn status(&self) -> StatusCode {
        self.head.subject
    }

    /// The HTTP version of this response.
    #[inline]
    pub fn version(&self) -> version::HttpVersion { self.head.version }

    /// Get a mutable reference to the Headers.
    #[inline]
    pub fn headers_mut(&mut self) -> &mut header::Headers { &mut self.head.headers }

    /// Set the `StatusCode` for this response.
    #[inline]
    pub fn set_status(&mut self, status: StatusCode) {
        self.head.subject = status;
    }

    /// Set the body.
    #[inline]
    pub fn set_body<T: Into<B>>(&mut self, body: T) {
        self.body = Some(body.into());
    }

    /// Set the status and move the Response.
    ///
    /// Useful for the "builder-style" pattern.
    #[inline]
    pub fn with_status(mut self, status: StatusCode) -> Self {
        self.set_status(status);
        self
    }

    /// Set a header and move the Response.
    ///
    /// Useful for the "builder-style" pattern.
    #[inline]
    pub fn with_header<H: header::Header>(mut self, header: H) -> Self {
        self.head.headers.set(header);
        self
    }

    /// Set the headers and move the Response.
    ///
    /// Useful for the "builder-style" pattern.
    #[inline]
    pub fn with_headers(mut self, headers: header::Headers) -> Self {
        self.head.headers = headers;
        self
    }

    /// Set the body and move the Response.
    ///
    /// Useful for the "builder-style" pattern.
    #[inline]
    pub fn with_body<T: Into<B>>(mut self, body: T) -> Self {
        self.set_body(body);
        self
    }
}

impl<B> Default for Response<B> {
    fn default() -> Response<B> {
        Response {
            head: Default::default(),
            body: None,
        }
    }
}

impl<B> fmt::Debug for Response<B> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Response")
            .field("status", &self.head.subject)
            .field("version", &self.head.version)
            .field("headers", &self.head.headers)
            .finish()
    }
}

pub fn split<B>(res: Response<B>) -> (http::MessageHead<StatusCode>, Option<B>) {
    (res.head, res.body)
}


text:
module CelluloidBenchmark
  module Visitors
    module HTTPMethods
      def get(uri, parameters = [], referer = nil, headers = {})
        page = browser.get(uri, parameters, referer, headers)
        log_response page
        page
      end

      def post(uri, query = {}, headers = {})
        page = browser.post(uri, query, headers)
        log_response page
        page
      end

      def put(uri, entity, headers = {})
        page = browser.put(uri, entity, headers)
        log_response page
        page
      end

      def get_json(uri, headers = {})
        get uri, [], nil, headers.merge("Accept" => "application/json, text/javascript, */*; q=0.01")
      end

      def post_json(uri, query, headers = {})
        post(
          uri,
          MultiJson.dump(query),
          { "Content-Type" => "application/json", "Accept" => "application/json, text/javascript, */*; q=0.01" }.merge(headers)
        )
      end

      def put_json(uri, query, headers = {})
        put(
          uri,
          MultiJson.dump(query),
          { "Content-Type" => "application/json", "Accept" => "application/json, text/javascript, */*; q=0.01" }.merge(headers)
        )
      end
    end
  end
end


text:
@interface ANDetailViewController ()

@end

@implementation ANDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL *webURL = self.webURL;

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:webURL];

    [self.webView loadRequest:urlRequest];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
@interface YDInstructionsCell ()
@property (nonatomic, strong) UILabel *title;
@property (nonatomic, strong) UILabel *desc;
@end

@implementation YDInstructionsCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self.contentView.backgroundColor = YDGlobalBg;
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        self.title = [[UILabel alloc] init];
        self.title.font = [UIFont systemFontOfSize:12];
        [self.contentView addSubview:_title];

        self.title.frame = CGRectMake(5, 5, SCREEN_WIDTH - 10, 20);
//        self.title.backgroundColor = [UIColor redColor];

        self.desc = [[UILabel alloc] init];
        [self.contentView addSubview:_desc];
        self.desc.numberOfLines = 0;
        self.desc.font = [UIFont systemFontOfSize:12];

        self.desc.frame = CGRectMake(5, 25, SCREEN_WIDTH - 10, 20);
//        self.desc.backgroundColor = [UIColor greenColor];
    }
    return self;
}

- (void)cellsetModelInfo:(NSString *)info index:(NSIndexPath *)index {

    NSArray *title = @[@"【药品名称】",@"【成份】",@"【性状】",@"【适应症】",@"【规格】",@"【用法用量】",@"【不良反应】",@"【禁忌】",@"【注意事项】",@"【妊娠与哺乳期用药】",@"【儿童用药】",@"【老人用药】",@"【药物相互作用】",@"【药理作用】",@"【贮藏】",@"【有效期】",@"【批准文号】",@"【执行标准】",@"【说明书修订日期】",@"【生产企业】"];

    if (info.length == 0) {
        self.title.text = @"";
    } else {
        self.title.text = title[index.row];
    }
    self.desc.text = info;

    //计算介绍label的高度
    CGRect bounds=[self.desc.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 10, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:12] forKey:NSFontAttributeName] context:nil];

    self.desc.numberOfLines = 0;

    self.desc.font=[UIFont systemFontOfSize:12];

    self.desc.frame = CGRectMake(10, 25, SCREEN_WIDTH - 10, bounds.size.height + 5);
}

+ (CGFloat)heightForCell:(NSString *)info
{
    CGRect bounds=[info boundingRectWithSize:CGSizeMake(SCREEN_WIDTH / 1.2, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13] forKey:NSFontAttributeName] context:nil];

    return 5 + 20 + bounds.size.height + 8;
}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
import { RenderingTestCase, moduleFor, strip, runTask } from 'internal-test-helpers';

import { set } from '@ember/-internals/metal';

import { Component } from '../../utils/helpers';

moduleFor(
  'Helpers test: {{array}}',
  class extends RenderingTestCase {
    ['@test returns an array']() {
      this.render(strip`
      {{#with (array "Sergio") as |people|}}
        {{#each people as |personName|}}
          {{personName}}
        {{/each}}
      {{/with}}`);

      this.assertText('Sergio');

      this.assertStableRerender();
    }

    ['@test can have more than one value']() {
      this.render(strip`
      {{#with (array "Sergio" "Robert") as |people|}}
        {{#each people as |personName|}}
          {{personName}},
        {{/each}}
      {{/with}}`);

      this.assertText('Sergio,Robert,');

      this.assertStableRerender();
    }

    ['@test binds values when variables are used']() {
      this.render(
        strip`{{#with (array personOne) as |people|}}
              {{#each people as |personName|}}
                {{personName}}
              {{/each}}
            {{/with}}`,
        {
          personOne: 'Tom',
        }
      );

      this.assertText('Tom');

      this.assertStableRerender();

      runTask(() => set(this.context, 'personOne', 'Yehuda'));
      this.assertText('Yehuda');

      runTask(() => set(this.context, 'personOne', 'Tom'));
      this.assertText('Tom');
    }

    ['@test binds multiple values when variables are used']() {
      this.render(
        strip`{{#with (array personOne personTwo) as |people|}}
              {{#each people as |personName|}}
                {{personName}},
              {{/each}}
            {{/with}}`,
        {
          personOne: 'Tom',
          personTwo: 'Yehuda',
        }
      );

      this.assertText('Tom,Yehuda,');

      this.assertStableRerender();

      runTask(() => set(this.context, 'personOne', 'Sergio'));

      this.assertText('Sergio,Yehuda,');

      runTask(() => set(this.context, 'personTwo', 'Tom'));

      this.assertText('Sergio,Tom,');

      runTask(() => {
        set(this.context, 'personOne', 'Tom');
        set(this.context, 'personTwo', 'Yehuda');
      });

      this.assertText('Tom,Yehuda,');
    }

    ['@test array helpers can be nested']() {
      this.render(
        strip`{{#with (array (array personOne personTwo)) as |listOfPeople|}}
              {{#each listOfPeople as |people|}}
                List:
                {{#each people as |personName|}}
                  {{personName}},
                {{/each}}
              {{/each}}
            {{/with}}`,
        {
          personOne: 'Tom',
          personTwo: 'Yehuda',
        }
      );

      this.assertText('List:Tom,Yehuda,');

      this.assertStableRerender();

      runTask(() => set(this.context, 'personOne', 'Chad'));

      this.assertText('List:Chad,Yehuda,');

      runTask(() => set(this.context, 'personTwo', 'Balint'));

      this.assertText('List:Chad,Balint,');

      runTask(() => {
        set(this.context, 'personOne', 'Tom');
        set(this.context, 'personTwo', 'Yehuda');
      });

      this.assertText('List:Tom,Yehuda,');
    }

    ['@test should yield hash of an array of internal properties']() {
      let fooBarInstance;
      let FooBarComponent = Component.extend({
        init() {
          this._super();
          fooBarInstance = this;
          this.model = { personOne: 'Chad' };
        },
      });

      this.registerComponent('foo-bar', {
        ComponentClass: FooBarComponent,
        template: `{{yield (hash people=(array this.model.personOne))}}`,
      });

      this.render(strip`
      {{#foo-bar as |values|}}
        {{#each values.people as |personName|}}
          {{personName}}
        {{/each}}
      {{/foo-bar}}`);

      this.assertText('Chad');

      this.assertStableRerender();

      runTask(() => set(fooBarInstance, 'model.personOne', 'Godfrey'));

      this.assertText('Godfrey');

      runTask(() => set(fooBarInstance, 'model', { personOne: 'Chad' }));

      this.assertText('Chad');

      runTask(() => set(fooBarInstance, 'model.personOne', 'Godfrey'));

      this.assertText('Godfrey');
    }

    ['@test should yield hash of an array of internal and external properties']() {
      let fooBarInstance;
      let FooBarComponent = Component.extend({
        init() {
          this._super();
          fooBarInstance = this;
          this.model = { personOne: 'Chad' };
        },
      });

      this.registerComponent('foo-bar', {
        ComponentClass: FooBarComponent,
        template: `{{yield (hash people=(array this.model.personOne personTwo))}}`,
      });

      this.render(
        strip`
        {{#foo-bar personTwo=this.model.personTwo as |values|}}
          {{#each values.people as |personName|}}
            {{personName}},
          {{/each}}
        {{/foo-bar}}`,
        {
          model: { personTwo: 'Tom' },
        }
      );

      this.assertText('Chad,Tom,');

      this.assertStableRerender();

      runTask(() => {
        set(fooBarInstance, 'model.personOne', 'Godfrey');
        set(this.context, 'model.personTwo', 'Yehuda');
      });

      this.assertText('Godfrey,Yehuda,');

      runTask(() => {
        set(fooBarInstance, 'model', { personOne: 'Chad' });
        set(this.context, 'model', { personTwo: 'Tom' });
      });

      this.assertText('Chad,Tom,');
    }

    ['@test should render when passing as argument to a component invocation']() {
      let FooBarComponent = Component.extend({});

      this.registerComponent('foo-bar', {
        ComponentClass: FooBarComponent,
        template: strip`
        {{#each people as |personName|}}
          {{personName}},
        {{/each}}`,
      });

      this.render(strip`{{foo-bar people=(array "Tom" personTwo)}}`, { personTwo: 'Chad' });

      this.assertText('Tom,Chad,');

      this.assertStableRerender();

      runTask(() => set(this.context, 'personTwo', 'Godfrey'));

      this.assertText('Tom,Godfrey,');

      runTask(() => set(this.context, 'personTwo', 'Chad'));

      this.assertText('Tom,Chad,');
    }

    ['@test should return an entirely new array when any argument change']() {
      let fooBarInstance;
      let FooBarComponent = Component.extend({
        init() {
          this._super();
          fooBarInstance = this;
        },
      });

      this.registerComponent('foo-bar', {
        ComponentClass: FooBarComponent,
        template: strip`
        {{#each people as |personName|}}
          {{personName}},
        {{/each}}`,
      });

      this.render(strip`{{foo-bar people=(array "Tom" personTwo)}}`, { personTwo: 'Chad' });

      let firstArray = fooBarInstance.people;

      runTask(() => set(this.context, 'personTwo', 'Godfrey'));

      this.assert.ok(
        firstArray !== fooBarInstance.people,
        'should have created an entirely new array'
      );
    }

    ['@test capture array values in JS to assert deep equal']() {
      let captured;

      this.registerHelper('capture', function([array]) {
        captured = array;
        return 'captured';
      });

      this.render(`{{capture (array 'Tom' personTwo)}}`, { personTwo: 'Godfrey' });

      this.assert.deepEqual(captured, ['Tom', 'Godfrey']);

      runTask(() => set(this.context, 'personTwo', 'Robert'));

      this.assert.deepEqual(captured, ['Tom', 'Robert']);

      runTask(() => set(this.context, 'personTwo', 'Godfrey'));

      this.assert.deepEqual(captured, ['Tom', 'Godfrey']);
    }
  }
);


text:
ARG CILIUM_BUILDER_IMAGE=docker.io/cilium/cilium-builder-dev:618b6b93c98b3075048861a512fa93525ef3f1f1
ARG CILIUM_RUNTIME_IMAGE=docker.io/cilium/cilium-runtime-dev:329a090f697c3be3725d55925eef944a87df4582

FROM --platform=linux/amd64 ${CILIUM_BUILDER_IMAGE} as builder

ARG NOSTRIP
ARG LOCKDEBUG
ARG RACE

RUN --mount=type=bind,readwrite,target=/go/src/github.com/cilium/cilium --mount=target=/root/.cache,type=cache --mount=target=/go/pkg/mod,type=cache \
  make build-container install-container \
    NOSTRIP=$NOSTRIP LOCKDEBUG=$LOCKDEBUG RACE=$RACE PKG_BUILD=1 SKIP_DOCS=true DESTDIR=/out/linux/amd64

RUN --mount=type=bind,readwrite,target=/go/src/github.com/cilium/cilium --mount=target=/root/.cache,type=cache --mount=target=/go/pkg/mod,type=cache \
  env GOARCH=arm64 CC=aarch64-linux-gnu-gcc \
    make build-container install-container \
      NOSTRIP=$NOSTRIP LOCKDEBUG=$LOCKDEBUG RACE=$RACE PKG_BUILD=1 SKIP_DOCS=true DESTDIR=/out/linux/arm64 \
      HOST_CC=aarch64-linux-gnu-gcc HOST_STRIP=aarch64-linux-gnu-strip

RUN --mount=type=bind,readwrite,target=/go/src/github.com/cilium/cilium \
  cd /go/src/github.com/cilium/cilium/plugins/cilium-cni \
    && cp cni-install.sh cni-uninstall.sh /out/linux/amd64 \
    && cp cni-install.sh cni-uninstall.sh /out/linux/arm64

RUN --mount=type=bind,readwrite,target=/go/src/github.com/cilium/cilium \
  cd /go/src/github.com/cilium/cilium/contrib/packaging/docker \
    && cp init-container.sh /out/linux/amd64 \
    && cp init-container.sh /out/linux/arm64

FROM ${CILIUM_RUNTIME_IMAGE}
ARG TARGETPLATFORM
LABEL maintainer="maintainer@cilium.io"

COPY --from=builder /out/${TARGETPLATFORM} /

WORKDIR /home/cilium

RUN groupadd -f cilium \
    && echo ". /etc/profile.d/bash_completion.sh" >> /etc/bash.bashrc

CMD ["/usr/bin/cilium"]


text:
namespace franka_gazebo {

/// Can be used to check controllers in franka_gazebo. It also can distinguish
/// between gripper and arm controllers.
class ControllerVerifier {
 public:
  /// Creates a ControllerVerifier object to check controllers for franka_gazebo
  /// @param joints map of joint names and joints including gripper joints
  /// @param arm_id prefix of the joints
  ControllerVerifier(const std::map<std::string, std::shared_ptr<franka_gazebo::Joint>>& joints,
                     const std::string& arm_id);

  /// checks if a set of joint_names only contains the joints that are used for the arm
  bool areArmJoints(const std::set<std::string>& resources) const;

  /// checks if a controller can be used in the franka_hw gazebo plugin
  bool isValidController(const hardware_interface::ControllerInfo& controller) const;

  /// checks if a set of joint_names only contains the joints that are used for the gripper
  bool areFingerJoints(const std::set<std::string>& resources) const;

  /// checks if a controller wants to use the finger joints with the effort interface
  bool isClaimingGripperController(const hardware_interface::ControllerInfo& info) const;

  /// checks if a controller that uses the joints of the arm (not gripper joints) claims a position,
  /// velocity or effort interface.
  bool isClaimingArmController(const hardware_interface::ControllerInfo& info) const;

  /// returns the control method of a hardware interface
  static boost::optional<ControlMethod> determineControlMethod(
      const std::string& hardware_interface);

 private:
  std::vector<std::string> joint_names_;
  std::string arm_id_;

  static bool hasControlMethodAndValidSize(const hardware_interface::InterfaceResources& resource);
};
}  // namespace franka_gazebo


text:
<?php

namespace Admin\EinstitutAdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Candidat
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Admin\EinstitutAdminBundle\Entity\CandidatRepository")
 */
class Candidat
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

        /**
     * @ORM\OneToMany(targetEntity="Admin\EinstitutAdminBundle\Entity\Dossier",mappedBy="Candidat")
     */
    private $dossiers;

    /**
    *@ORM\OneToOne(targetEntity="Admin\EinstitutAdminBundle\Entity\User")
    *@ORM\JoinColumn(nullable=false)
    */
    private $utilisateur;

    /**
     * @var string
     *
     * @ORM\Column(name="niveau", type="string", length=255)
     */
    private $niveau;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->dossiers = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add dossiers
     *
     * @param \Admin\EinstitutAdminBundle\Entity\Dossier $dossiers
     * @return Candidat
     */
    public function addDossier(\Admin\EinstitutAdminBundle\Entity\Dossier $dossiers)
    {
        $this->dossiers[] = $dossiers;

        return $this;
    }

    /**
     * Remove dossiers
     *
     * @param \Admin\EinstitutAdminBundle\Entity\Dossier $dossiers
     */
    public function removeDossier(\Admin\EinstitutAdminBundle\Entity\Dossier $dossiers)
    {
        $this->dossiers->removeElement($dossiers);
    }

    /**
     * Get dossiers
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getDossiers()
    {
        return $this->dossiers;
    }

    /**
     * Set utilisateur
     *
     * @param \Admin\EinstitutAdminBundle\Entity\User $utilisateur
     * @return Candidat
     */
    public function setUtilisateur(\Admin\EinstitutAdminBundle\Entity\User $utilisateur)
    {
        $this->utilisateur = $utilisateur;

        return $this;
    }

    /**
     * Get utilisateur
     *
     * @return \Admin\EinstitutAdminBundle\Entity\User
     */
    public function getUtilisateur()
    {
        return $this->utilisateur;
    }

    /**
     * Set niveau
     *
     * @param string $niveau
     * @return Candidat
     */
    public function setNiveau($niveau)
    {
        $this->niveau = $niveau;

        return $this;
    }

    /**
     * Get niveau
     *
     * @return string
     */
    public function getNiveau()
    {
        return $this->niveau;
    }
}