text:
'''
Command line parser for fashion project.

Created on 2016-04-29 Copyright (c) 2016 Bradford Dillman
'''

import argparse
import json
import logging
import shutil
import sys
import zipfile

from pathlib import Path

from munch import Munch, munchify

from fashion.portfolio import FASHION_HOME, Portfolio, findPortfolio
from fashion.runway import Runway
from fashion.schema import SchemaRepository
from fashion.util import cd

# Tru means query_yes_no never prompts and always returns yes.
alwaysYes = False

# Current portfolio determined from working directory, if any found.
portfolio = None

def query_yes_no(question, default="yes"):
    '''
    Ask a yes/no question via input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    '''
    valid = {"yes": True, "y": True, "ye": True,
             "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        if alwaysYes:
            sys.stdout.write("y\n")
            return True
        choice = input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "
                             "(or 'y' or 'n').\n")

def setup(args):
    '''
    Set up access to the portfolio.
    :param args: arguments from argparse.
    '''
    global portfolio
    portfolio = findPortfolio(Path(args.project))
    if portfolio is None:
        return False
    argsObj = munchify(vars(args))
    del argsObj["func"]
    argsObj.project = argsObj.project.as_posix()
    portfolio.db.setSingleton('fashion.prime.args', argsObj)
    pf = munchify(portfolio.properties)
    pf.projectPath = portfolio.projectPath.as_posix()
    pf.mirrorPath = portfolio.mirrorPath.as_posix()
    portfolio.db.setSingleton('fashion.prime.portfolio', pf)
    return True

def home(args):
    '''Show FASHION_HOME directory.'''
    print("FASHION_HOME={0}".format(FASHION_HOME))

    global portfolio
    if not setup(args):
        return
    print("project home={0}".format(str(portfolio.projectPath)))

def init(args):
    '''Initialize a new fashion project.'''
    global portfolio
    portfolio = Portfolio(args.project)
    if portfolio.exists():
        print("project already exists")
    else:
        portfolio.create()

def kill(args):
    '''Delete a fashion project.'''
    global portfolio
    portfolio = Portfolio(args.project)
    if portfolio.exists():
        if query_yes_no("Are you sure you want to delete the fashion project", "no"):
            portfolio.delete()
    else:
        print("project doesn't exist")

def clean(args):
    '''Build the output.'''
    global portfolio
    if not setup(args):
        return
    portfolio.db.db.purge_tables()

def build(args):
    '''Build the output.'''
    global portfolio
    if not setup(args):
        return
    print("building...")
    with cd(portfolio.projectPath):
        r = portfolio.getRunway()
        r.plan()
        r.execute()

def createXform(args):
    global portfolio
    if not setup(args):
        return
    tp = portfolio.warehouse.getDefaultsTemplatePath()
    seg = portfolio.defaultSegment()
    seg.createXform(args.name, tp)

def deleteXform(args):
    global portfolio
    if not setup(args):
        return
    tp = portfolio.warehouse.getDefaultsTemplatePath()
    seg = portfolio.defaultSegment()
    seg.deleteXform(args.name)

def createTemplate(args):
    global portfolio
    if not setup(args):
        return
    filename = portfolio.normalizeFilename(args.name)
    with cd(portfolio.projectPath):
        tp = portfolio.warehouse.getDefaultsTemplatePath()
        seg = portfolio.defaultSegment()
        seg.createTemplate(filename, tp)

def deleteTemplate(args):
    global portfolio
    if not setup(args):
        return
    filename = portfolio.normalizeFilename(args.name)
    with cd(portfolio.projectPath):
        seg = portfolio.defaultSegment()
        seg.deleteTemplate(filename)

def guessSchema(args):
    global portfolio
    if not setup(args):
        return
    portfolio.warehouse.loadSegments()
    schemaDefs = portfolio.warehouse.getSchemaDefintions()
    if args.kind in schemaDefs:
        if not query_yes_no("Are you sure you want to overwrite the schema?", "no"):
            return
    portfolio.warehouse.guessSchema(portfolio.db, args.kind)

def listKinds(args):
    global portfolio
    if not setup(args):
        return
    for t in sorted(portfolio.db.kinds()):
        count = len(portfolio.db.table(t).all())
        print("{0} ({1})".format(t, count))

def dump(args):
    global portfolio
    if not setup(args):
        return
    print(json.dumps(portfolio.db.table(args.kind).get(doc_id=args.id), indent=4))

def dumpAll(args):
    global portfolio
    if not setup(args):
        return
    print(json.dumps(portfolio.db.table(args.kind).all(), indent=4))

def segmentList(args):
    global portfolio
    if not setup(args):
        return
    segNames = portfolio.warehouse.listSegments()
    if portfolio.warehouse.fallback is not None:
        segNames.extend(portfolio.warehouse.fallback.listSegments())
    if len(segNames) == 0:
        print("No segments found.")
        return
    for sn in segNames:
        seg = portfolio.warehouse.loadSegment(sn)
        print("{0} v{1} - {2}".format(seg.properties.name,
                                      seg.properties.version, seg.absDirname))

def segmentNew(args):
    global portfolio
    if not setup(args):
        return
    seg = portfolio.warehouse.loadSegment(args.segname)
    if seg is not None:
        if query_yes_no("Are you sure you want to overwrite the segment?", "no"):
            portfolio.warehouse.deleteSegment(seg)
        else:
            return
    portfolio.warehouse.newSegment(args.segname)

def segmentDelete(args):
    global portfolio
    if not setup(args):
        return
    seg = portfolio.warehouse.loadSegment(args.segname)
    if seg is not None:
        if query_yes_no("Are you sure you want to delete the segment?", "no"):
            portfolio.warehouse.deleteSegment(seg)

def segmentExport(args):
    global portfolio
    if not setup(args):
        return
    seg = portfolio.warehouse.loadSegment(args.segname)
    if seg is None:
        print("Segment not found: {0}".format(args.segname))
        return
    print("exporting segment {0}".format(args.segname))
    portfolio.warehouse.exportSegment(args.segname)

def segmentImport(args):
    global portfolio
    if not setup(args):
        return
    filepath = Path(args.filename)
    if not filepath.exists():
        print("{0} not found.".format(args.filename))
        return
    segname = filepath.name.split("_v")[0]
    version = filepath.name.split("_v")[1].split(".zip")[0]
    seg = portfolio.warehouse.loadSegment(segname)
    if seg is not None:
        if query_yes_no("Are you sure you want to overwrite the segment?", "no"):
            portfolio.warehouse.deleteSegment(seg)
        else:
            return
    print("importing segment {0} v{1}".format(segname, version))
    portfolio.warehouse.importSegment(args.filename)

def segmentDefault(args):
    global portfolio
    if not setup(args):
        return
    portfolio.setDefaultSegment(args.name)

def nab(args):
    '''Create a template and xform from a file.'''
    global portfolio
    if not setup(args):
        return
    filename = portfolio.normalizeFilename(args.filename)
    with cd(portfolio.projectPath):
        if not filename.exists():
            print("{0} not found.".format(filename))
            return
        tp = portfolio.warehouse.getDefaultsTemplatePath()
        seg = portfolio.defaultSegment()
        xformName = filename.stem
        model = {
            "template": filename.as_posix(),
            "targetFile": filename.as_posix()
        }
        tplFile = "defaultNabXformTemplate.py"
        if seg.templateExists(filename):
            if query_yes_no("Are you sure you want to overwrite the template?", "no"):
                seg.deleteTemplate(filename)
            else:
                return

        if seg.xformExists(xformName):
            if query_yes_no("Are you sure you want to overwrite the xform?", "no"):
                seg.deleteXform(str(filename))
            else:
                return
        seg.createTemplate(filename)
        seg.createXform(xformName, tp, templateFile=tplFile, model=model)

def main():
    '''Parse command from command line args, then delegate.'''
    parser = argparse.ArgumentParser(prog='fashion')
    parser.add_argument('-p', '--project',   help='project directory', nargs=1)
    parser.add_argument('-y', '--alwaysYes',
                        help="answer 'y' to all prompts", action='store_true')
    parser.add_argument('-v', '--verbose',
                        help="verbose output", action='store_true')
    parser.add_argument('-d', '--debug',
                        help="debug logging", action='store_true')
    parser.add_argument('--version', action='version',
                        version='%(prog)s 2.0 beta')

    subparsers = parser.add_subparsers(dest='command',
                                       title='commands',
                                       description='valid commands',
                                       help='command help')

    homeParser = subparsers.add_parser(
        'home', help='show FASHION_HOME directory')
    homeParser.set_defaults(func=home)

    initParser = subparsers.add_parser(
        'init', help='initialize a new fashion project in current directory')
    initParser.set_defaults(func=init)

    killParser = subparsers.add_parser(
        'kill', help='delete all fashion contents from project directory')
    killParser.set_defaults(func=kill)

    listKindsP = subparsers.add_parser(
        'list_kinds', help='list all known model kinds')
    listKindsP.set_defaults(func=listKinds)

    cleanP = subparsers.add_parser(
        'clean', help='clean tables from database')
    cleanP.set_defaults(func=clean)

    buildParser = subparsers.add_parser(
        'build', help='build the plan of xforms and generate output')
    buildParser.add_argument('-f', '--force',
                             help="force overwrite of generated files", action='store_true')
    buildParser.set_defaults(func=build)

    createParser = subparsers.add_parser(
        'create', help='create a default xform, schema, model, etc.')
    createSubParser = createParser.add_subparsers(dest='createCommand',
                                                  title='create subcommands',
                                                  description='valid create subcommands',
                                                  help='create subcommand help')

    createXformParser = createSubParser.add_parser(
        'xform', help='create a new xform')
    createXformParser.add_argument('name', help='xform name')
    createXformParser.set_defaults(func=createXform)

    createTemplateParser = createSubParser.add_parser(
        'template', help='create a new template')
    createTemplateParser.add_argument('name', help='xform name')
    createTemplateParser.set_defaults(func=createTemplate)

    deleteParser = subparsers.add_parser(
        'delete', help='delete an xform, schema, model, etc.')
    deleteSubParser = deleteParser.add_subparsers(dest='deleteCommand',
                                                  title='delete subcommands',
                                                  description='valid delete subcommands',
                                                  help='delete subcommand help')

    deleteXformParser = deleteSubParser.add_parser(
        'xform', help='delete an xform')
    deleteXformParser.add_argument('name', help='xform name')
    deleteXformParser.set_defaults(func=deleteXform)

    deleteTemplateParser = deleteSubParser.add_parser(
        'template', help='delete a template')
    deleteTemplateParser.add_argument('name', help='template name')
    deleteTemplateParser.set_defaults(func=deleteTemplate)

    guessSchemaParser = subparsers.add_parser(
        'guess_schema', help='create a default schema for a model kind')
    guessSchemaParser.add_argument('kind', help='kind of model for schema')
    guessSchemaParser.set_defaults(func=guessSchema)

    nabParser = subparsers.add_parser(
        'nab', help='create template and xform from existing file')
    nabParser.add_argument('filename', help='file to nab')
    nabParser.set_defaults(func=nab)

    dumpParser = subparsers.add_parser(
        'dump', help='print model contents')
    dumpParser.add_argument('kind', help='kind of model')
    dumpParser.add_argument('id', help='id of model')
    dumpParser.set_defaults(func=dump)

    dumpAllParser = subparsers.add_parser(
        'dump_all', help='print model contents')
    dumpAllParser.add_argument('kind', help='kind of model')
    dumpAllParser.set_defaults(func=dumpAll)

    segmentParser = subparsers.add_parser(
        'segment', help='list, import, export, update segments')
    segmentSubParser = segmentParser.add_subparsers(dest='segmentCommand',
                                                    title='segment subcommands',
                                                    description='valid segment subcommands',
                                                    help='segment subcommand help')

    segmentListParser = segmentSubParser.add_parser(
        'list', help='list segments')
    segmentListParser.set_defaults(func=segmentList)
    segmentExportParser = segmentSubParser.add_parser(
        'export', help='export a segment')
    segmentExportParser.add_argument(
        'segname', help='name of segment to export')
    segmentExportParser.set_defaults(func=segmentExport)
    segmentImportParser = segmentSubParser.add_parser(
        'import', help='import a segment')
    segmentImportParser.add_argument(
        'filename', help='filename of segment to import')
    segmentImportParser.set_defaults(func=segmentImport)
    segmentNewParser = segmentSubParser.add_parser(
        'new', help='create a new segment')
    segmentNewParser.add_argument(
        'segname', help='name of new segment')
    segmentNewParser.set_defaults(func=segmentNew)
    segmentDeleteParser = segmentSubParser.add_parser(
        'delete', help='create a new segment')
    segmentDeleteParser.add_argument(
        'segname', help='name of segment to delete')
    segmentDeleteParser.set_defaults(func=segmentDelete)
    segmentDefaultP = segmentSubParser.add_parser(
        'default', help='set the default segment')
    segmentDefaultP.add_argument(
        'segname', help='name of default segment')
    segmentDefaultP.set_defaults(func=segmentDefault)

    result = parser.parse_args(sys.argv[1:])
    if result.project == None:
        result.project = Path.cwd()

    global alwaysYes
    if result.alwaysYes:
        alwaysYes = result.alwaysYes

    if result.debug:
        logging.basicConfig(level=logging.DEBUG)

    logging.debug(result)

    result.func(result)

    global portfolio
    if portfolio is not None:
        portfolio.db.close()

#
# Main entry point
#
if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
@interface PAYFormErrorMessage ()

@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *message;
@property (nonatomic, assign) PAYFormErrorMessageBlock titleBlock;
@property (nonatomic, assign) PAYFormErrorMessageBlock messageBlock;

@end

@implementation PAYFormErrorMessage

+ (instancetype)errorMessageWithTitle:(NSString *)title message:(NSString *)message {
    if (!title && !message) {
        return nil;
    }
    PAYFormErrorMessage *errorMessage = [PAYFormErrorMessage new];
    errorMessage.title = title;
    errorMessage.message = message;
    return errorMessage;
}

+ (instancetype)errorMessageWithError:(NSError *)error {
    return [self errorMessageWithTitle:error.title message:error.message];
}

+ (instancetype)errorMessageWithTitleBlock:(PAYFormErrorMessageBlock)titleBlock messageBlock:(PAYFormErrorMessageBlock)messageBlock {
    PAYFormErrorMessage *errorMessage = [PAYFormErrorMessage new];
    errorMessage.titleBlock = titleBlock;
    errorMessage.messageBlock = messageBlock;
    return errorMessage;
}

- (NSString *)titleForField:(id<PAYValidatableFormCell>)field {
    if (self.titleBlock) {
        self.title = self.titleBlock(field);
    }
    if (field && [self.title rangeOfString:@"%@"].location != NSNotFound) {
        return [NSString stringWithFormat:self.title, field.name];
    }
    return self.title;
}

- (NSString *)messageForField:(id<PAYValidatableFormCell>)field {
    if (self.messageBlock) {
        self.message = self.messageBlock(field);
    }
    if (field && [self.message rangeOfString:@"%@"].location != NSNotFound) {
        return [NSString stringWithFormat:self.message, field.name];
    }
    return self.message;
}

@end


text:
<?php

namespace Blog\GeneralBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $name = "Hamdi";
        return $this->render('BlogGeneralBundle:Default:index.html.twig', array('name' => $name));
    }
}


text:
package net.java.html.leaflet.event;

/**
 *
 * @author Andreas Grimmer
 */
public final class ErrorEvent extends Event {

    private final String message;
    private final int code;

    public ErrorEvent(final Object src, final String type, final String message,
            final int code) {
        super(src, type);
        this.message = message;
        this.code = code;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @return the code
     */
    public int getCode() {
        return code;
    }

    public static enum Type {

        LOCATIONERROR;

        @Override
        public String toString() {
            return super.toString().toLowerCase();
        }
    }
}


text:
package test_lab;

/**
 * Router forwarding table info.
 */
public class Path {

    /** length */
    private int length;
    /** path(split with space) */
    private String path;

    public Path(String path, int length) {
        this.length = length;
        this.path = path;
    }

    public int getLength() {
        return length;
    }

    public String getPath() {
        return path;
    }

    @Override
    public String toString() {
        return "path: " + path + " length: " + length;
    }
}


text:
#!/usr/bin/env node

'use strict';

const loadCoverage = require('../lib/loadCoverage');
const remap = require('../lib/remap');
const writeReport = require('../lib/writeReport');
const MemoryStore = require('istanbul/lib/store/memory');
const Collector = require('istanbul/lib/collector');

/**
 * Helper function that reads from standard in and resolves a Promise with the
 * data or rejects with any errors.
 * @return {Promise} A promsie that is resolved with the data from standard in
 *                   or rejected with any errors.
 */
function readStdIn() {
	/* istanbul ignore next: too challenging to test for reading from stdin */
	return new Promise((resolve, reject) => {
		const stdin = process.stdin;
		let buffer = '';

		stdin.setEncoding('utf8');

		stdin.on('data', (data) => {
			buffer += data;
		});

		stdin.on('error', (e) => {
			reject(e);
		});

		stdin.on('end', () => {
			resolve(buffer);
		});

		try {
			stdin.resume();
		} catch (e) {
			reject(e);
		}
	});
}

/**
 * The main wrapper to provide a CLI interface to remap-istanbul
 * @param  {Array}   argv An array of arguments passed the process
 * @return {Promise}      A promise that resolves when the remapping is complete
 *                        or rejects if there is an error.
 */
function main(argv) {
	/* jshint maxcomplexity:13 */

	/**
	 * Helper function that processes the arguments
	 * @return {String} The next valid argument
	 */
	function getArg() {
		let arg = argv.shift();
		if (arg && arg.indexOf('--') === 0) {
			arg = arg.split('=');
			if (arg.length > 1) {
				argv.unshift(arg.slice(1).join('='));
			}
			arg = arg[0];
		} else if (arg && arg[0] === '-') {
			/* istanbul ignore if */
			if (arg.length > 2) {
				argv = arg.substring(1).split('')
					.map((ch) => '-' + ch)
					.concat(argv);
				arg = argv.shift();
			}
		}

		return arg;
	}

	let arg;
	const inputFiles = [];
	let output;
	let reportType;
	let basePath;
	let exclude;
	for (arg = getArg(); arg; arg = getArg()) {
		switch (arg) {
			case '-i':
			case '--input':
				inputFiles.push(argv.shift());
				break;
			case '-o':
			case '--output':
				output = argv.shift();
				break;
			case '-b':
			case '--basePath':
				basePath = argv.shift();
				break;
			case '-t':
			case '--type':
				reportType = argv.shift();
				break;
			case '-e':
			case '--exclude':
				exclude = argv.shift();
				if (exclude.indexOf(',') !== -1) {
					exclude = new RegExp(exclude.replace(/,/g, '|'));
				}
				break;
			default:
				throw new SyntaxError(`Unrecognised argument: "${arg}".`);
		}
	}

	return new Promise((resolve, reject) => {
		const coverage = inputFiles.length ? loadCoverage(inputFiles) :
			/* istanbul ignore next */
			readStdIn().then((data) => {
				try {
					data = JSON.parse(data);
					const collector = new Collector();
					collector.add(data);
					return collector.getFinalCoverage();
				} catch (err) {
					console.error(err.stack);
					throw err;
				}
			}, reject);

		resolve(coverage);
	}).then((coverage) => {
		let sources = new MemoryStore();
		const collector = remap(coverage, {
			sources,
			basePath: basePath || undefined,
			exclude: exclude || undefined,
		});
		if (!Object.keys(sources.map).length) {
			sources = undefined;
		}
		const reportOptions = {};
		if (output) {
			return writeReport(collector, reportType || 'json', reportOptions, output, sources);
		}
		if (reportType && (reportType === 'lcovonly' || reportType === 'text-lcov')) {
			return writeReport(collector, 'text-lcov', reportOptions);
		}
		process.stdout.write(JSON.stringify(collector.getFinalCoverage()) + '\n');
		return null;
	});
}

/* istanbul ignore if: we use the module interface in testing */
if (!module.parent) {
	process.title = 'remap-istanbul';
	/* first two arguments are meaningless to the process */
	main(process.argv.slice(2))
		.then(
			(code) => process.exit(code || 0),
			(err) => {
				console.log(err.stack);
				process.exit(1);
			});
} else {
	module.exports = main;
}


text:
<?php

namespace Tests\Magium\MagentoEE114\Navigation;

use Magium\Magento\AbstractMagentoTestCase;
use Magium\Magento\Navigators\Store\Switcher;

class StoreSwitcherNavigationTest extends \Tests\Magium\Magento\Navigation\StoreSwitcherNavigationTest
{

    public function setUp()
    {
        parent::setUp();
        $this->switchThemeConfiguration('Magium\Magento\Themes\MagentoEE114\ThemeConfiguration');
    }
}


text:
require 'spec_helper'
require File.join(PROJECT_ROOT, 'build_tools/compiler/asset_compiler.rb')
require File.join(PROJECT_ROOT, 'build_tools/packager/ejs_packager.rb')

describe Packager::EJSPackager do
  let(:generated_directory_path) {File.join(PROJECT_ROOT, "pkg/ejs_govuk_template-#{GovukTemplate::VERSION}")}
  let(:generated_template_path) {File.join(generated_directory_path, "views/layouts/govuk_template.html")}
  let(:generated_package_json_path) {File.join(generated_directory_path, "package.json")}
  subject {described_class.new}

  after do
    FileUtils.rm_rf(generated_directory_path)
  end

  context "functional" do
    describe "build" do

      let(:example_package_json) {ERB.new(File.read(File.join(SPEC_ROOT, 'support/examples/package_ejs.json'))).result(binding)}
      it "should output the correct template" do
        subject.build

        generated_template = File.read(generated_template_path)
        expect(generated_template).to match(%r[href="<%= govukTemplateAssetPath %>stylesheets/govuk-template\.css\?#{Regexp.escape(GovukTemplate::VERSION)}"])

        expect(File.read(generated_package_json_path)).to eql(example_package_json)
      end

    end
  end

end


text:
define(
    ['helper/dom', 'helper/ajax'],
    function(dom, ajaxHelper){
        var ready = false,
            $doc = dom.getDocument(),
            $window = dom.getWindow(),
            eastPanes = ['#help', '#stat', '#rateHelp'];

        function init(){
            dom.get('#helpToggler').click(function() {
                toggle(eastPanes, 0);
            });
            dom.get('#statToggler').click(function() {
                toggle(eastPanes, 1);
            });
            dom.get('#gui').delegate('.rateHelp', 'click', function(event) {
                event.preventDefault();

                toggle(eastPanes, 2);
            });
            dom.get('#feedback, #south .deutschodoro-link a').click(newWindow);

            dom.get('#rateHelp').html(
                [
                    '
Help for rating words:
',
                    '
1. apple, mother, to sit, red
',
                    '
2. post office, cuisine, to use, tall
',
                    '
3. friendship, judge, to require, scary
',
                    '
4. corkscrew, chimneysweep, to pray, impressive
',
                    '
5. exhaust pipe, coroner, to depict, coarse
',
                    '
6. pelmet, mortgage, to to oblige, scruffy
',
                    '
7. pre-highschool level terminology, secondary synonyms
',
                    '
8. highschool level terminology, rare words
',
                    '
9. university level words
'
                ].join('')
            );

            ready = true;
        }

        function isReady() {
            return ready;
        }

        function displayGame(html) {
            if (isReady()) {
                dom.getCached('#center').empty().append(html);
            }
        }

        function addRaters(hash) {
            if (isReady()) {
                dom.getCached('#center').append(getRaters(hash));
            }
        }

        function getRaters(hash) {
            var raters;

            raters = $(getRatersHtml());

            setupRaters(raters, hash);

            return raters;
        }

        function getRatersHtml() {
            var html;

            html = [
                '
',
                '
What level this word belongs to? (Help)
',
                '
',
                '
<button class="alert">1</button>
',
                '
<button class="alert">2</button>
',
                '
<button class="alert">3</button>
',
                '
<button class="alert">4</button>
',
                '
<button class="alert">5</button>
',
                '
<button class="alert">6</button>
',
                '
<button class="alert">7</button>
',
                '
<button class="alert">8</button>
',
                '
<button class="alert">9</button>
',
                '
',
                '
'
            ];

            return html.join('');
        }

        function setupRaters(raters, hash) {
            $('button', raters).click(function(e){
                var $this = $(this), ul, p, div;

                e.preventDefault();

                ajaxHelper.vote(hash, $this.text());

                ul  = $this.closest('ul');
                p   = ul.prev();
                div = ul.parent();

                ul.fadeOut();
                p.text('Thank you!');
                setTimeout(function(){
                    div.fadeOut('normal', function(){ div.remove(); });
                }, 2000);
            });
        }

        function newWindow(e){
            var url = dom.get(this).attr('href');

            e.preventDefault();

            dom.getWindow(true).open(url, 'deutschodoro-help');
        }

        function displayHelp(gameHelp, words) {
            var html = [], east;
            if (isReady()) {
                html.push('
Help
');
                html.push(getGameHelpHtml(gameHelp));
                html.push(getDictionaryHelpHtml(words));

                east = dom.getCached('#help').empty().append(html.join(''));
                dom.get('a', east).click(newWindow);
            }
        }

        function getGameHelpHtml(gameHelp) {
            var html = [];

            if (gameHelp) {
                html.push('
Game help
');
                html.push('
' + gameHelp + '
');

                return '
' +  html.join('') + '
';
            }

            return '';
        }

        function getDictionaryHelpHtml(words) {
            var i, html = [], german;

            if (words.length) {
                for (i = 0; i < words.length; i++) {
                    german = words[i].german;
                    html.push('
Word #' + (i+1) + '
');
                    html.push('
');
                    html.push('
' + getWikiLink(german) + '
');
                    html.push('
' + getLeoLink(german) + '
');
                    html.push('
' + getThefreedictionaryLink(german) + '
');
                    html.push('
' + getDudenLink(german) + '
');
                    html.push('
' + getCanooLink(german) + '
');
                    html.push('
');
                }

                return '
' +  html.join('') + '
';
            }

            return '';
        }

        function getWikiLink(german) {
            return 'wiktionary.org';
        }

        function getLeoLink(german) {
            return [
                '',
                'leo.org',
                ''
            ].join('');
        }

        function getThefreedictionaryLink(german) {
            return 'thefreedictionary.com';
        }

        function getDudenLink(german) {
            return 'duden.de';
        }

        function getCanooLink(german) {
            return [
                '',
                'canoo.net',
                ''
            ].join('');
        }

        function displayPage(html) {
            dom.getCached('#center').empty().append(html);
        }

        function toggle(selectors, toggleIndex) {
            var i;

            if (dom.getCached(selectors[toggleIndex]).is(':visible')) {
                dom.getCached(selectors[toggleIndex]).hide();
            } else {
                for (i = 0; i < selectors.length; i++) {
                    dom.getCached(selectors[i]).hide();
                }

                dom.getCached(selectors[toggleIndex]).show();
            }
        }

        function resize(){
            var width;

            width = Math.min(300, Math.floor($doc.width()/4));

            dom.getCached('.ui-layout-eas').width(width);
        }

        function updateStats(stats) {
            var html = [], totalScore = 0, totalCount = 0, percentage;

            html.push('
');

            html.push('
');
            html.push('
hit rate	count
');
            html.push('
');

            html.push('
');
            if (isReady()) {
                _.each(stats, function(value, index){
                    percentage = (index * 10);
                    percentage = percentage==100 ? percentage : (percentage + ' - ' + (percentage + 10))
                    html.push('
' + percentage + '%	' + value + '
');
                    totalScore += (value * 10 * index);
                    totalCount += value;
                });
            }
            html.push('
');

            if (totalCount) {
                percentage = Math.floor(totalScore / totalCount * 100) / 100;
                html.push('
');
                html.push('
' + percentage + '%	' + totalCount + '
');
                html.push('
');
            }

            html.push('
');

            dom.getCached('#stat').html(html.join(''));
        }

        function showErrorReportBtn() {
            var errorReportBtn;

            errorReportBtn = dom.get('<button class="alert" id="report" href="">Report</button>')
                .attr('href', 'https://groups.google.com/forum/#!forum/deutschodoro')
                .click(newWindow);

            errorReportBtn.insertAfter('#submit');
        }

        $doc.ready(function(){
            init();
            $window.resize();
        });

        $window.resize(resize);

        return {
            isReady: isReady,
            displayGame: displayGame,
            addRaters: addRaters,
            displayHelp: displayHelp,
            displayPage: displayPage,
            showErrorReportBtn: showErrorReportBtn,
            updateStats: updateStats
        }
    }
);


text:
package edu.american.student.stonewall.display.html;

import static org.junit.Assert.assertEquals;

import java.net.MalformedURLException;
import java.util.UUID;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import edu.american.student.stonewall.display.html.component.HTMLButton;
import edu.american.student.stonewall.display.html.framework.ValidationException;
import edu.american.student.stonewall.display.html.text.HTMLPlainText;
import edu.american.student.stonewall.display.html.util.ButtonType;
import edu.american.student.stonewall.display.html.util.EncodingType;
import edu.american.student.stonewall.display.html.util.Target;
import edu.american.student.stonewall.util.ResourceFinder;
import edu.american.student.stonewall.util.ResourceType;

public class HTMLButtonTest
{

	@BeforeClass
	public static void setUpBeforeClass() throws Exception
	{
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception
	{
	}

	@Before
	public void setUp() throws Exception
	{
	}

	@After
	public void tearDown() throws Exception
	{
	}

	@Test
	public void fullTest() throws MalformedURLException, ValidationException
	{
		HTMLButton button = new HTMLButton(UUID.randomUUID().toString(),new HTMLPlainText(UUID.randomUUID().toString(),"Click me!"),ButtonType.SUBMITABLE)
			.setAutoFocus(true)
			.setDisabled(false)
			.setFormAction(new ResourceFinder("https://raw.github.com/headjs/headjs/v0.99/dist/head.min.js",ResourceType.EXTERNAL))
			.setFormEncodingType(EncodingType.PLAIN_TEXT)
			.setFormNoValidate(false)
			.setFormTarget(Target.NEW_WINDOW)
			.setName("myButton")
			.setInitialValue("5");
		String expected = "<button formaction=\"https://raw.github.com/headjs/headjs/v0.99/dist/head.min.js\"  name=\"myButton\"  value=\"5\"  formenctype=\"text/plain\"  formtarget=\"_blank\"  type=\"submit\"  autofocus>Click me!</button>";
		//assertEquals(expected,button.makeElement());
	}
}


text:
package com.tehasdf.discord.codec

import java.math.BigInteger
import java.time.{Instant, ZoneId, ZonedDateTime}

import com.tehasdf.discord.model._
import com.tehasdf.discord.messages._
import spray.json._

object DiscordProtocol extends DefaultJsonProtocol {
  implicit def wsMsgF[A: JsonFormat] = jsonFormat2(WsClientMessage.apply[A])

  implicit val loginF = jsonFormat3(Login)
  implicit object PingFormat extends JsonFormat[Ping] {
    override def read(json: JsValue): Ping = Ping(json.convertTo[Long])
    override def write(obj: Ping): JsValue = JsNumber(obj.ts)
  }

  implicit object InstantFormat extends JsonFormat[Instant] {
    override def read(json: JsValue): Instant = {
      ZonedDateTime.parse(json.convertTo[String]).toInstant
    }

    override def write(obj: Instant): JsValue = JsString(ZonedDateTime.ofInstant(obj, ZoneId.of("UTC")).toString)
  }

  implicit object BigIntegerFormat extends JsonFormat[BigInteger] {
    override def read(json: JsValue): BigInteger = new BigInteger(json.convertTo[String])

    override def write(obj: BigInteger): JsValue = JsString(obj.toString)
  }

  implicit object GuildFormat extends JsonFormat[Guild] {
    override def read(json: JsValue): Guild = {
      val obj = json.asJsObject
      Guild(afkChannelId = obj.fields("afk_channel_id").convertTo[Option[Long]],
        afkTimeout = obj.fields("afk_timeout").convertTo[Long],
        channels = obj.fields("channels").convertTo[Seq[Channel]],
        icon = obj.fields("icon").convertTo[String],
        id = obj.fields("id").convertTo[BigInteger],
        joinedAt = obj.fields("joined_at").convertTo[Instant],
        large = obj.fields("large").convertTo[Boolean],
        members = obj.fields("members").convertTo[Seq[Membership]],
        name = obj.fields("name").convertTo[String],
        ownerId = obj.fields("owner_id").convertTo[BigInteger],
        presences = obj.fields("presences").convertTo[Seq[Presence]],
        region = obj.fields("region").convertTo[String],
        roles = obj.fields("roles").convertTo[Seq[Role]])
    }

    override def write(obj: Guild): JsValue = {
      JsObject(
        "afk_channel_id" -> obj.afkChannelId.toJson,
        "afk_timeout" -> obj.afkTimeout.toJson,
        "channels" -> obj.channels.toJson,
        "icon" -> obj.icon.toJson,
        "id" -> obj.id.toJson,
        "joined_at" -> obj.joinedAt.toJson,
        "large" -> obj.large.toJson,
        "members" -> obj.members.toJson,
        "name" -> obj.name.toJson,
        "owner_id" -> obj.ownerId.toJson,
        "presences" -> obj.presences.toJson,
        "region" -> obj.region.toJson,
        "roles" -> obj.roles.toJson
      )
    }
  }

  implicit object PresenceFormat extends JsonFormat[Presence] {
    override def read(json: JsValue): Presence = {
      val obj = json.asJsObject
      Presence(
        gameId = obj.fields("game_id").convertTo[Option[Long]],
        status = obj.fields("status").convertTo[String],
        user = obj.fields("user").convertTo[Id].id
      )
    }

    override def write(obj: Presence): JsValue = {
      JsObject(
        "game_id" -> obj.gameId.toJson,
        "status" -> obj.status.toJson,
        "user" -> Id(obj.user).toJson
      )
    }
  }

  implicit val serverMsgF = jsonFormat(ServerMsg, "t", "s", "op", "d")

  implicit val selfF = jsonFormat6(Self)
  implicit val userF = jsonFormat4(User)
  implicit val idF = jsonFormat1(Id)
  implicit val membershipF = jsonFormat(Membership, "deaf", "joined_at", "mute", "roles", "user")
  implicit val roleF = jsonFormat7(Role)
  implicit val permissionF = jsonFormat(Permission, "allow", "deny", "id", "type")
  implicit val channelF = jsonFormat(Channel, "id", "last_message_id", "name", "permission_overwrites", "position", "topic", "type")

  implicit val readyF = jsonFormat7(ReadyPayload)
  implicit val presenceUpdateF = jsonFormat(PresenceUpdatePayload, "user", "status", "roles", "guild_id", "game_id")
  implicit val messageCreateF = jsonFormat(MessageCreatePayload, "tts", "timestamp", "nonce", "mentions", "mention_everyone", "id", "embeds", "edited_timestamp", "content", "channel_id", "author", "attachments")

  implicit val guildMemberAddF = jsonFormat(GuildMemberAddPayload, "user", "roles", "joined_at", "guild_id")
  implicit val loginInfoF = jsonFormat2(LoginInfo)
  implicit val msgF = jsonFormat4(Msg)
}


text:
<?php

require_once("Mail.php");
require_once("Mail/mime.php");

define("EMAIL_ON",true);

function reservation_confirmation_email($reservation_id)
{
	global $db;

	// use reservation_id to lookup email address and reservation info
	$reservations = load_reservation_details($reservation_id);
	foreach($reservations as $reservation)
		break;

	$user = get_user_by_id($reservation->user_id);

	$rooms = load_rooms(null,array('id'=>$reservation->room_id));
	foreach($rooms as $room)
		break;

	$from = NOTICE_EMAIL_ADDRESS;
	$reply_to = NOTICE_EMAIL_ADDRESS;
	$recipient = $user->email;

	$subject = "PSU Library - Study Room Reservation Confirmation";

	// check to see if there is an override template for this room or room group
	if(file_exists("http://".$_SERVER["HTTP_HOST"].WEB_ROOT."email_templates/rooms/$room->room_id/reservation_confirmation.txt"))
		$template = file_get_contents("http://".$_SERVER["HTTP_HOST"].WEB_ROOT."email_templates/rooms/$room->room_id/reservation_confirmation.txt");
	else if(file_exists("http://".$_SERVER["HTTP_HOST"].WEB_ROOT."email_templates/room_groups/$room->room_group_id/reservation_confirmation.txt"))
		$template = file_get_contents("http://".$_SERVER["HTTP_HOST"].WEB_ROOT."email_templates/room_groups/$room->room_group_id/reservation_confirmation.txt");
	else
		$template = file_get_contents("http://".$_SERVER["HTTP_HOST"].WEB_ROOT."email_templates/reservation_confirmation.txt");

	$body = set_template_tokens($template,$reservation,$user,$room);

	$result = send_email($reservation->id,"Reservation Confirmation",$from,$reply_to,$recipient,$subject,$body);

	return($result);
}

function reservation_cancellation_email($db,$reservation_id)
{
	// use reservation_id to lookup email address and reservation info
	$reservations = load_reservation_details($reservation_id);
	foreach($reservations as $reservation)
		break;

	$user = get_user_by_id($reservation->user_id);

	$rooms = load_rooms(null,array('id'=>$reservation->room_id));
	foreach($rooms as $room)
		break;

	$from = NOTICE_EMAIL_ADDRESS;
	$reply_to = NOTICE_EMAIL_ADDRESS;
	$recipient = $user->email;

	$subject = "PSU Library - Study Room Reservation Cancellation";
	$template = set_template_tokens(file_get_contents("http://".$_SERVER["HTTP_HOST"].WEB_ROOT."email_templates/reservation_cancellation.txt"),$reservation,$user,$room);

	$result = send_email($reservation->id,"Reservation Cancellation",$from,$reply_to,$recipient,$subject,$template);

	return($result);
}

function overdue_email($db,$reservation_id)
{
	// use reservation_id to lookup email address and reservation info
	$reservations = load_reservation_details($reservation_id);
	foreach($reservations as $reservation)
		break;

	$user = get_user_by_id($reservation->user_id);

	$rooms = load_rooms(null,array('id'=>$reservation->room_id));
	foreach($rooms as $room)
		break;

	$from = NOTICE_EMAIL_ADDRESS;
	$reply_to = NOTICE_EMAIL_ADDRESS;
	$recipient = $user->email;

	$subject = "PSU Library - Study Room Overdue Notice";
	$template = set_template_tokens(file_get_contents("http://".$_SERVER["HTTP_HOST"].WEB_ROOT."email_templates/overdue.txt"),$reservation,$user,$room);

	$result = send_email($reservation->id,"Overdue Notice",$from,$reply_to,$recipient,$subject,$template);

	return($result);
}

function lost_key_email($db,$reservation_id)
{
	// use reservation_id to lookup email address and reservation info
	$reservations = load_reservation_details($reservation_id);
	foreach($reservations as $reservation)
		break;

	$user = get_user_by_id($reservation->user_id);

	$rooms = load_rooms(null,array('id'=>$reservation->room_id));
	foreach($rooms as $room)
		break;

	$from = NOTICE_EMAIL_ADDRESS;
	$reply_to = NOTICE_EMAIL_ADDRESS;
	$recipient = $user->email;

	$subject = "PSU Library - Study Room Overdue FINAL Notice";
	$template = set_template_tokens(file_get_contents("http://".$_SERVER["HTTP_HOST"].WEB_ROOT."email_templates/lost_key.txt"),$reservation,$user,$room);

	$result = send_email($reservation->id,"Lost Key",$from,$reply_to,$recipient,$subject,$template);

	return($result);
}

function set_template_tokens($template,$reservation,$user=null,$room=null)
{
	$template = str_replace("{reservation_calendar_url}","http://".$_SERVER["HTTP_HOST"].WEB_ROOT,$template);
	$template = str_replace("{room_id}",$reservation->id,$template);
	$template = str_replace("{room_number}",$room->room_number,$template);
	$template = str_replace("{patrons_first_name}",$user->first_name,$template);
	$template = str_replace("{patrons_last_name}",$user->last_name,$template);
	$template = str_replace("{reservation_id}",$reservation->id,$template);
	$template = str_replace("{reservation_date}",date('m/d/Y',strtotime($reservation->date)),$template);
	$template = str_replace("{reservation_start_time}",date('g:ia',strtotime($reservation->sched_start_time)),$template);
	$template = str_replace("{reservation_end_time}",date('g:ia',strtotime($reservation->sched_end_time)),$template);
	if(strcmp($reservation->cancellation_reason,''))
		$template = str_replace("{cancellation_reason}","Cancellation Reason: ".$reservation->cancellation_reason,$template);
	$template = str_replace("\n","<br>",$template);

	return($template);
}

function send_email($reservation_id,$type,$from,$reply_to,$recipient,$subject,$message,$html_message="")
{
	global $db;

	if(!strcmp(trim($recipient),''))
	{
		$recipient = "mflakus@pdx.edu";
		$subject = $subject;
	}

	$headers = array('To'=>$recipient,'From'=> $from,'Return-Path'=> $reply_to,'Subject'=> $subject);

	$html_body = $message;
	$body = strip_tags(nl2br($html_body));

	$mime = new Mail_mime(PHP_EOL);
	$mime->setTXTBody($body);
	$mime->setHTMLBody($html_body);
	$body = $mime->get();
	$headers = $mime->headers($headers);

	// TODO: add config.php setting for selecting and configuring mail settings

	// smtp parameters
	$params['host'] = SMTP_HOST;

	// Create the mail object using the Mail::factory method
	$mail =& Mail::factory('smtp', $params);
	if(EMAIL_ON)
		$mail->send($recipient, $headers,  $body);

	// TODO: check for error when sending email

	// Log email sent to patron
	$fields = array('reservation_id','type','recipient','subject','body','date_added');
	$values = array($reservation_id,$type,$recipient,$subject,$message,date("Y-m-d H:i:s"));
	$db->insert("email_log",$fields,$values);

	return(true);

}

?>


text:
layout: post
uuid: dda5bccc-dc11-4f24-b8ba-9087b1680678
title: moving-from-amazon-ec2-to-s3
name: moving-from-amazon-ec2-to-s3
created_at: 2011-10-03
updated_at: 2011-10-03
categories: unfinished
published: false
---

Since the site is now using Jekyll, a static site generator, it is possible to host it on S3.

Previously the site was hosted on EC2. Because micro spot instance


text:
module HashiCorp

    module VagrantVMwarefusion

        module Action

            class SnapshotDelete

                def initialize(app, env)
                    @app = app
                end

                def call(env)

                    env[:ui].info(I18n.t("vagrant_snap.actions.vm.snapshot_delete.deleting",
                        :snapshot => env[:snap_name]),
                    )

                    env[:result] = env[:machine].provider.driver.snapshot_delete(env[:snap_name])

                    @app.call(env)

                end

            end

        end

    end

end


text:
Ping Pong is a sample JavaScript application for demonstrating basic proficiency in JavaScript, jQuery, Git, Markdown, HTML, Bootstrap, CSS, and BDD.

A user enters a number and is shown a range of numbers from 1 to the number entered with the following exceptions:

* Numbers divisible by 3 are replaced with "ping"
* Numbers divisible by 5 are replaced with "pong"
* Numbers divisible by 15 are replaced with "pingpong"

## Demo
View on [GitHub Pages](https://jeffreyruder.github.io/ping-pong-app/).

## Installation
Install Ping Pong by cloning this repository:
```
https://github.com/JeffreyRuder/PingPongApp.git
```
## License
MIT License. Copyright 2015 Jeffrey Ruder.


text:
<?php
use yii\helpers\Html;
use yii\helpers\Url;
/* @var $this CompanyController */
/* @var $model Company */

$this->title=Yii::$app->name . ' - Update Service';
$this->params['breadcrumbs'][]= ['label'=>'Services', 'url'=>['index']];
$this->params['breadcrumbs'][]= 'Update';
?>

<?php echo Html::a('Список услуг', Url::toRoute('index'),['class'=>'btn-lg btn btn-primary']) ?>

Update Service <?php echo $model->id; ?>

<?php echo $this->context->renderPartial('_form', ['model'=>$model]); ?>


text:
<?php

declare(strict_types=1);

Route::domain('{subdomain}.'.domain())->group(function () {
    Route::name('managerarea.')
         ->middleware(['web', 'nohttpcache'])
         ->namespace('Cortex\Auth\Http\Controllers\Managerarea')
         ->prefix(config('cortex.foundation.route.locale_prefix') ? '{locale}/'.config('cortex.foundation.route.prefix.managerarea') : config('cortex.foundation.route.prefix.managerarea'))->group(function () {

        // Login Routes
             Route::get('login')->name('login')->uses('AuthenticationController@form');
             Route::post('login')->name('login.process')->uses('AuthenticationController@login');
             Route::post('logout')->name('logout')->uses('AuthenticationController@logout');

             // Reauthentication Routes
             Route::name('reauthentication.')->prefix('reauthentication')->group(function () {
                 // Reauthentication Password Routes
                 Route::post('password')->name('password.process')->uses('ReauthenticationController@processPassword');

                 // Reauthentication Twofactor Routes
                 Route::post('twofactor')->name('twofactor.process')->uses('ReauthenticationController@processTwofactor');
             });

             // Password Reset Routes
             Route::get('passwordreset')->name('passwordreset')->uses('RedirectionController@passwordreset');
             Route::name('passwordreset.')->prefix('passwordreset')->group(function () {
                 Route::get('request')->name('request')->uses('PasswordResetController@request');
                 Route::post('send')->name('send')->uses('PasswordResetController@send');
                 Route::get('reset')->name('reset')->uses('PasswordResetController@reset');
                 Route::post('process')->name('process')->uses('PasswordResetController@process');
             });

             // Verification Routes
             Route::get('verification')->name('verification')->uses('RedirectionController@verification');
             Route::name('verification.')->prefix('verification')->group(function () {
                 // Phone Verification Routes
                 Route::name('phone.')->prefix('phone')->group(function () {
                     Route::get('request')->name('request')->uses('PhoneVerificationController@request');
                     Route::post('send')->name('send')->uses('PhoneVerificationController@send');
                     Route::get('verify')->name('verify')->uses('PhoneVerificationController@verify');
                     Route::post('process')->name('process')->uses('PhoneVerificationController@process');
                 });

                 // Email Verification Routes
                 Route::name('email.')->prefix('email')->group(function () {
                     Route::get('request')->name('request')->uses('EmailVerificationController@request');
                     Route::post('send')->name('send')->uses('EmailVerificationController@send');
                     Route::get('verify')->name('verify')->uses('EmailVerificationController@verify');
                 });
             });

             Route::middleware(['can:access-managerarea'])->group(function () {

                 // Account Settings Route Alias
                 Route::get('account')->name('account')->uses('AccountSettingsController@index');

                 // User Account Routes
                 Route::name('account.')->prefix('account')->group(function () {
                     // Account Settings Routes
                     Route::get('settings')->name('settings')->uses('AccountSettingsController@edit');
                     Route::post('settings')->name('settings.update')->uses('AccountSettingsController@update');

                     // Account Media Routes
                     Route::delete('{member}/media/{media}')->name('media.destroy')->uses('AccountMediaController@destroy');

                     // Account Password Routes
                     Route::get('password')->name('password')->uses('AccountPasswordController@edit');
                     Route::post('password')->name('password.update')->uses('AccountPasswordController@update');

                     // Account Attributes Routes
                     Route::get('attributes')->name('attributes')->uses('AccountAttributesController@edit');
                     Route::post('attributes')->name('attributes.update')->uses('AccountAttributesController@update');

                     // Account Sessions Routes
                     Route::get('sessions')->name('sessions')->uses('AccountSessionsController@index');
                     Route::delete('sessions')->name('sessions.flush')->uses('AccountSessionsController@flush');
                     Route::delete('sessions/{session?}')->name('sessions.destroy')->uses('AccountSessionsController@destroy');

                     // Account TwoFactor Routes
                     Route::get('twofactor')->name('twofactor')->uses('AccountTwoFactorController@index');
                     Route::name('twofactor.')->prefix('twofactor')->group(function () {

                         // Account TwoFactor TOTP Routes
                         Route::name('totp.')->prefix('totp')->group(function () {
                             Route::get('enable')->name('enable')->uses('AccountTwoFactorController@enableTotp');
                             Route::post('update')->name('update')->uses('AccountTwoFactorController@updateTotp');
                             Route::post('disable')->name('disable')->uses('AccountTwoFactorController@disableTotp');
                             Route::post('backup')->name('backup')->uses('AccountTwoFactorController@backupTotp');
                         });

                         // Account TwoFactor Phone Routes
                         Route::name('phone.')->prefix('phone')->group(function () {
                             Route::post('enable')->name('enable')->uses('AccountTwoFactorController@enablePhone');
                             Route::post('disable')->name('disable')->uses('AccountTwoFactorController@disablePhone');
                         });
                     });
                 });

                 // Social Authentication Routes
                 Route::redirect('auth', 'login');
                 Route::get('auth/{provider}')->name('auth.social')->uses('SocialAuthenticationController@redirectToProvider');
                 Route::get('auth/{provider}/callback')->name('auth.social.callback')->uses('SocialAuthenticationController@handleProviderCallback');

                 // Roles Routes
                 Route::name('roles.')->prefix('roles')->group(function () {
                     Route::get('/')->name('index')->uses('RolesController@index');
                     Route::get('import')->name('import')->uses('RolesController@import');
                     Route::post('import')->name('stash')->uses('RolesController@stash');
                     Route::post('hoard')->name('hoard')->uses('RolesController@hoard');
                     Route::get('import/logs')->name('import.logs')->uses('RolesController@importLogs');
                     Route::get('create')->name('create')->uses('RolesController@create');
                     Route::post('create')->name('store')->uses('RolesController@store');
                     Route::get('{role}')->name('show')->uses('RolesController@show');
                     Route::get('{role}/edit')->name('edit')->uses('RolesController@edit');
                     Route::put('{role}/edit')->name('update')->uses('RolesController@update');
                     Route::get('{role}/logs')->name('logs')->uses('RolesController@logs');
                     Route::delete('{role}')->name('destroy')->uses('RolesController@destroy');
                 });

                 // Members Routes
                 Route::name('members.')->prefix('members')->group(function () {
                     Route::get('/')->name('index')->uses('MembersController@index');
                     Route::get('import')->name('import')->uses('MembersController@import');
                     Route::post('import')->name('stash')->uses('MembersController@stash');
                     Route::post('hoard')->name('hoard')->uses('MembersController@hoard');
                     Route::get('import/logs')->name('import.logs')->uses('MembersController@importLogs');
                     Route::get('create')->name('create')->uses('MembersController@form');
                     Route::post('create')->name('store')->uses('MembersController@store');
                     Route::get('{member}')->name('show')->uses('MembersController@show');
                     Route::get('{member}/edit')->name('edit')->uses('MembersController@form');
                     Route::put('{member}/edit')->name('update')->uses('MembersController@update');
                     Route::get('{member}/logs')->name('logs')->uses('MembersController@logs');
                     Route::get('{member}/activities')->name('activities')->uses('MembersController@activities');
                     Route::get('{member}/attributes')->name('attributes')->uses('MembersController@attributes');
                     Route::put('{member}/attributes')->name('attributes.update')->uses('MembersController@updateAttributes');
                     Route::delete('{member}')->name('destroy')->uses('MembersController@destroy');
                     Route::delete('{member}/media/{media}')->name('media.destroy')->uses('MembersMediaController@destroy');
                 });

                 // Managers Routes
                 Route::name('managers.')->prefix('managers')->group(function () {
                     Route::get('/')->name('index')->uses('ManagersController@index');
                     Route::get('import')->name('import')->uses('ManagersController@import');
                     Route::post('import')->name('stash')->uses('ManagersController@stash');
                     Route::post('hoard')->name('hoard')->uses('ManagersController@hoard');
                     Route::get('import/logs')->name('import.logs')->uses('ManagersController@importLogs');
                     Route::get('create')->name('create')->uses('ManagersController@create');
                     Route::post('create')->name('store')->uses('ManagersController@store');
                     Route::get('{manager}')->name('show')->uses('ManagersController@show');
                     Route::get('{manager}/edit')->name('edit')->uses('ManagersController@edit');
                     Route::put('{manager}/edit')->name('update')->uses('ManagersController@update');
                     Route::get('{manager}/logs')->name('logs')->uses('ManagersController@logs');
                     Route::get('{manager}/activities')->name('activities')->uses('ManagersController@activities');
                     Route::get('{manager}/attributes')->name('attributes')->uses('ManagersController@attributes');
                     Route::put('{manager}/attributes')->name('attributes.update')->uses('ManagersController@updateAttributes');
                     Route::delete('{manager}')->name('destroy')->uses('ManagersController@destroy');
                     Route::delete('{manager}/media/{media}')->name('media.destroy')->uses('ManagersMediaController@destroy');
                 });
             });
         });
});


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Vatica rynchocarpa P.S.Ashton

### Remarks
null


text:
import com.neulevel.epp.core.*;
import com.neulevel.epp.core.command.*;
import com.neulevel.epp.core.response.*;

import org.w3c.dom.*;

/**
 * The EppLogoutTest class tests functions of
 * EppCommandLogout commands.
 *
 * @author Ning Zhang ning.zhang@neustar.com
 * @version $Revision: 1.1 $ $Date: 2005/12/06 20:11:35 $
 */
public class EppLogoutTest
{
	public static void main( String argv[] )
	{
		EppCommandLogout logout = new EppCommandLogout();
		System.out.println(logout);

		logout.setClientTransactionId("ABC-DEF-12345");
		System.out.println(logout);

		EppParser parser = new EppParser(logout.toString());

		if( parser.hasError() )
		{
			System.out.println(parser.getResult());
			System.exit(1);
		}

		Node epp = parser.getRootNode();
		EppCommand cmd = (EppCommand) EppCommand.fromXML(epp);
		if( cmd == null )
		{
			System.out.println("Error in fromXML");
			System.exit(1);
		}
		System.out.println(cmd);
	}
}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2012-2013 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include "config.h"

#include "mock-unit-test.h"
#include "testutil.h"
#include <map>

/*
 * Helper functions
 */
extern "C" {
    static void kvoErrorHandler(lcb_t instance,
                                lcb_error_t err, const char *msg)
    {
        KVOperation::handleInstanceError(instance, err, msg);
    }

    static void storeKvoCallback(lcb_t, const void *cookie,
                                 lcb_storage_t operation,
                                 lcb_error_t error,
                                 const lcb_store_resp_t *resp)
    {

        KVOperation *kvo = (KVOperation *)cookie;
        kvo->cbCommon(error);
        kvo->result.assignKC(resp, error);
        ASSERT_EQ(LCB_SET, operation);
    }

    static void getKvoCallback(lcb_t, const void *cookie,
                               lcb_error_t error,
                               const lcb_get_resp_t *resp)
    {
        KVOperation *kvo = (KVOperation *)cookie;
        kvo->cbCommon(error);
        kvo->result.assign(resp, error);
    }

    static void removeKvoCallback(lcb_t, const void *cookie,
                                  lcb_error_t error,
                                  const lcb_remove_resp_t *resp)
    {
        KVOperation *kvo = (KVOperation *)cookie;
        kvo->cbCommon(error);
        kvo->result.assignKC(resp, error);
    }
}

void KVOperation::handleInstanceError(lcb_t instance, lcb_error_t err,
                                      const char *)
{
    KVOperation *kvo = reinterpret_cast<KVOperation *>(
            const_cast<void*>(lcb_get_cookie(instance)));
    kvo->assertOk(err);
    kvo->globalErrors.insert(err);
}

void KVOperation::enter(lcb_t instance)
{
    callbacks.err = lcb_set_error_callback(instance, kvoErrorHandler);
    callbacks.get = lcb_set_get_callback(instance, getKvoCallback);
    callbacks.rm = lcb_set_remove_callback(instance, removeKvoCallback);
    callbacks.store = lcb_set_store_callback(instance, storeKvoCallback);
    oldCookie = lcb_get_cookie(instance);
    lcb_set_cookie(instance, this);
}

void KVOperation::leave(lcb_t instance)
{
    lcb_set_error_callback(instance, callbacks.err);
    lcb_set_get_callback(instance, callbacks.get);
    lcb_set_remove_callback(instance, callbacks.rm);
    lcb_set_store_callback(instance, callbacks.store);
    lcb_set_cookie(instance, oldCookie);
}

void KVOperation::assertOk(lcb_error_t err)
{
    if (allowableErrors.empty()) {
        ASSERT_EQ(LCB_SUCCESS, err);
        return;
    }
    ASSERT_TRUE(allowableErrors.find(err) != allowableErrors.end());
}

void KVOperation::store(lcb_t instance)
{
    lcb_store_cmd_t cmd(LCB_SET,
                        request->key.data(), request->key.length(),
                        request->val.data(), request->val.length(),
                        request->flags,
                        request->exp,
                        request->cas,
                        request->datatype);
    lcb_store_cmd_t *cmds[] = { &cmd };

    enter(instance);
    EXPECT_EQ(LCB_SUCCESS, lcb_store(instance, this, 1, cmds));
    EXPECT_EQ(LCB_SUCCESS, lcb_wait(instance));
    leave(instance);

    ASSERT_EQ(1, callCount);

}

void KVOperation::remove(lcb_t instance)
{
    lcb_remove_cmd_t cmd(request->key.data(), request->key.length(),
                         request->cas);
    lcb_remove_cmd_t *cmds[] = { &cmd };

    enter(instance);
    EXPECT_EQ(LCB_SUCCESS, lcb_remove(instance, this, 1, cmds));
    EXPECT_EQ(LCB_SUCCESS, lcb_wait(instance));
    leave(instance);

    ASSERT_EQ(1, callCount);

}

void KVOperation::get(lcb_t instance)
{
    lcb_get_cmd_t cmd(request->key.data(), request->key.length(), request->exp);
    lcb_get_cmd_t *cmds[] = { &cmd };

    enter(instance);
    EXPECT_EQ(LCB_SUCCESS, lcb_get(instance, this, 1, cmds));
    EXPECT_EQ(LCB_SUCCESS, lcb_wait(instance));
    leave(instance);

    ASSERT_EQ(1, callCount);
}

void storeKey(lcb_t instance, const std::string &key, const std::string &value)
{
    Item req = Item(key, value);
    KVOperation kvo = KVOperation(&req);
    kvo.store(instance);
}

void removeKey(lcb_t instance, const std::string &key)
{
    Item req = Item();
    req.key = key;
    KVOperation kvo = KVOperation(&req);
    kvo.allowableErrors.insert(LCB_SUCCESS);
    kvo.allowableErrors.insert(LCB_KEY_ENOENT);
    kvo.remove(instance);
}

void getKey(lcb_t instance, const std::string &key, Item &item)
{
    Item req = Item();
    req.key = key;
    KVOperation kvo = KVOperation(&req);
    kvo.result.cas = 0xdeadbeef;

    kvo.get(instance);
    ASSERT_NE(0xdeadbeef, kvo.result.cas);
    item = kvo.result;
}

void genDistKeys(VBUCKET_CONFIG_HANDLE vbc, std::vector<std::string> &out)
{
    char buf[1024] = { '\0' };
    int servers_max = vbucket_config_get_num_servers(vbc);
    std::map<int, bool> found_servers;
    EXPECT_TRUE(servers_max > 0);

    for (int cur_num = 0; found_servers.size() != servers_max; cur_num++) {
        int ksize = sprintf(buf, "VBKEY_%d", cur_num);
        int vbid;
        int srvix;
        vbucket_map(vbc, buf, ksize, &vbid, &srvix);

        if (!found_servers[srvix]) {
            out.push_back(std::string(buf));
            found_servers[srvix] = true;
        }
    }

    EXPECT_EQ(servers_max, out.size());
}

void genStoreCommands(const std::vector<std::string> &keys,
                      std::vector<lcb_store_cmd_t> &cmds,
                      std::vector<lcb_store_cmd_t*> &cmdpp)
{
    for (unsigned int ii = 0; ii < keys.size(); ii++) {
        lcb_store_cmd_t cmd;
        memset(&cmd, 0, sizeof(cmd));
        cmd.v.v0.key = keys[ii].c_str();
        cmd.v.v0.nkey = keys[ii].size();
        cmd.v.v0.bytes = cmd.v.v0.key;
        cmd.v.v0.nbytes = cmd.v.v0.nkey;
        cmd.v.v0.operation = LCB_SET;
        cmds.push_back(cmd);
    }

    for (unsigned int ii = 0; ii < keys.size(); ii++) {
        cmdpp.push_back(&cmds[ii]);
    }
}

/**
 * Dump the item object to a stream
 * @param out where to dump the object to
 * @param item the item to print
 * @return the stream
 */
std::ostream &operator<< (std::ostream &out, const Item &item)
{
    using namespace std;
    out << "Key: " << item.key << endl;
    if (item.val.length()) {
        out <<  "Value: " << item.val << endl;
    }

    out << ios::hex << "CAS: 0x" << item.cas << endl
        << "Flags: 0x" << item.flags << endl;

    if (item.err != LCB_SUCCESS) {
        out << "Error: " << item.err << endl;
    }

    return out;
}


text:
#include "Platform.h"
#include "Utils.h"

#include <windows.h>

char *className = "OpenGL";

std::string windowName;
int winX = 0, winY = 0;
int winWidth = 300, winHeight = 300;

HDC hDC;
HGLRC hGLRC;
HPALETTE hPalette;

extern int main(int argc, char *argv[]);

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw)
  {
  main(0, 0);
  }

//-----------------------------------------------------------------------------
// Initialize the platform

int PlatformInit()
{
  UTI_Log("Platform Init\n");
  return 0;
}

//-----------------------------------------------------------------------------
// Quit the platform

int PlatformQuit()
{
  UTI_Log("Platform Quit\n");
  return 0;
}

int PlatformPollEvent(Event * event)
  {

  return 0;
  }

void
setupPixelFormat(HDC hDC)
	{
	PIXELFORMATDESCRIPTOR pfd = {
		sizeof(PIXELFORMATDESCRIPTOR),  /* size */
		1,                              /* version */
		PFD_SUPPORT_OPENGL |
		PFD_DRAW_TO_WINDOW |
		PFD_DOUBLEBUFFER,               /* support double-buffering */
		PFD_TYPE_RGBA,                  /* color type */
		16,                             /* prefered color depth */
		0, 0, 0, 0, 0, 0,               /* color bits (ignored) */
		0,                              /* no alpha buffer */
		0,                              /* alpha bits (ignored) */
		0,                              /* no accumulation buffer */
		0, 0, 0, 0,                     /* accum bits (ignored) */
		16,                             /* depth buffer */
		0,                              /* no stencil buffer */
		0,                              /* no auxiliary buffers */
		PFD_MAIN_PLANE,                 /* main layer */
		0,                              /* reserved */
		0, 0, 0,                        /* no layer, visible, damage masks */
		};
	int pixelFormat;

	pixelFormat = ChoosePixelFormat(hDC, &pfd);
	if (pixelFormat == 0)
		{
		MessageBox(WindowFromDC(hDC), "ChoosePixelFormat failed.", "Error",
			   MB_ICONERROR | MB_OK);
		exit(1);
		}

	if (SetPixelFormat(hDC, pixelFormat, &pfd) != TRUE)
		{
		MessageBox(WindowFromDC(hDC), "SetPixelFormat failed.", "Error",
			   MB_ICONERROR | MB_OK);
		exit(1);
		}
	}

void
setupPalette(HDC hDC)
	{
	int pixelFormat = GetPixelFormat(hDC);
	PIXELFORMATDESCRIPTOR pfd;
	LOGPALETTE* pPal;
	int paletteSize;

	DescribePixelFormat(hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);

	if (pfd.dwFlags & PFD_NEED_PALETTE)
		{
		paletteSize = 1 << pfd.cColorBits;
		}
	else
		{
		return;
		}

	pPal = (LOGPALETTE*)
		malloc(sizeof(LOGPALETTE) + paletteSize * sizeof(PALETTEENTRY));
	pPal->palVersion = 0x300;
	pPal->palNumEntries = paletteSize;

	/* build a simple RGB color palette */
		{
		int redMask = (1 << pfd.cRedBits) - 1;
		int greenMask = (1 << pfd.cGreenBits) - 1;
		int blueMask = (1 << pfd.cBlueBits) - 1;
		int i;

		for (i = 0; i<paletteSize; ++i)
			{
			pPal->palPalEntry[i].peRed =
				(((i >> pfd.cRedShift) & redMask) * 255) / redMask;
			pPal->palPalEntry[i].peGreen =
				(((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask;
			pPal->palPalEntry[i].peBlue =
				(((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask;
			pPal->palPalEntry[i].peFlags = 0;
			}
		}

		hPalette = CreatePalette(pPal);
		free(pPal);

		if (hPalette)
			{
			SelectPalette(hDC, hPalette, FALSE);
			RealizePalette(hDC);
			}
	}

LRESULT APIENTRY
WndProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
	{
	switch (message)
		{
			case WM_CREATE:
				/* initialize OpenGL rendering */
				hDC = GetDC(hWnd);
				setupPixelFormat(hDC);
				setupPalette(hDC);
				hGLRC = wglCreateContext(hDC);
				wglMakeCurrent(hDC, hGLRC);

				return 0;
			case WM_DESTROY:
				/* finish OpenGL rendering */
				if (hGLRC)
					{
					wglMakeCurrent(NULL, NULL);
					wglDeleteContext(hGLRC);
					}
				if (hPalette)
					{
					DeleteObject(hPalette);
					}
				ReleaseDC(hWnd, hDC);
				PostQuitMessage(0);
				return 0;
			case WM_SIZE:
				/* track window size changes */
				if (hGLRC)
					{
					winWidth = (int)LOWORD(lParam);
					winHeight = (int)HIWORD(lParam);
					return 0;
					}
			case WM_PALETTECHANGED:
				/* realize palette if this is *not* the current window */
				if (hGLRC && hPalette && (HWND)wParam != hWnd)
					{
					UnrealizeObject(hPalette);
					SelectPalette(hDC, hPalette, FALSE);
					RealizePalette(hDC);

					break;
					}
				break;
			case WM_QUERYNEWPALETTE:
				/* realize palette if this is the current window */
				if (hGLRC && hPalette)
					{
					UnrealizeObject(hPalette);
					SelectPalette(hDC, hPalette, FALSE);
					RealizePalette(hDC);

					return TRUE;
					}
				break;
			case WM_PAINT:
					{
					PAINTSTRUCT ps;
					BeginPaint(hWnd, &ps);
					if (hGLRC)
						{

						}
					EndPaint(hWnd, &ps);
					return 0;
					}
					break;
			case WM_CHAR:
				/* handle keyboard input */
				switch ((int)wParam)
					{
						case VK_ESCAPE:
							DestroyWindow(hWnd);
							return 0;
						default:
							break;
					}
				break;
			default:
				break;
		}
	return DefWindowProc(hWnd, message, wParam, lParam);
	}

void PlatformDelay(int ms)
  {
  Sleep(ms);
  }
//-----------------------------------------------------------------------------
// Create the main window

int PlatformCreateWindow(int sizeX, int sizeY, std::string title)
{
    WNDCLASS wndClass;
    HWND hWnd;

    winWidth = sizeX;
    winHeight = sizeY;
    windowName = title;

    /* register window class */
    wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wndClass.lpfnWndProc = WndProc;
    wndClass.cbClsExtra = 0;
    wndClass.cbWndExtra = 0;
    wndClass.hInstance = GetModuleHandle(NULL);
    wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    wndClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
    wndClass.lpszMenuName = NULL;
    wndClass.lpszClassName = className;
    RegisterClass(&wndClass);

    /* create window */
    hWnd = CreateWindow(
        className, windowName.c_str(),
        WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
        winX, winY, winWidth, winHeight,
	NULL, NULL, GetModuleHandle(NULL), NULL);

    /* display window */
    ShowWindow(hWnd, SW_SHOW);
    UpdateWindow(hWnd);

    return 0;
}


text:
using System;
using System.ComponentModel.Composition;
using GitHub.Api;
using GitHub.Services;
using GitHub.VisualStudio.Base;
using GitHub.VisualStudio.Helpers;
using Microsoft.TeamFoundation.Controls;
using GitHub.UI;
using GitHub.VisualStudio.UI;

namespace GitHub.VisualStudio.TeamExplorer.Home
{
    [TeamExplorerNavigationItem(GraphsNavigationItemId, NavigationItemPriority.Graphs)]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class GraphsNavigationItem : TeamExplorerNavigationItemBase
    {
        public const string GraphsNavigationItemId = "5245767A-B657-4F8E-BFEE-F04159F1DDA5";

        readonly Lazy<IVisualStudioBrowser> browser;

        [ImportingConstructor]
        public GraphsNavigationItem(IGitHubServiceProvider serviceProvider,
            ISimpleApiClientFactory apiFactory,
            Lazy<IVisualStudioBrowser> browser,
            ITeamExplorerServiceHolder holder)
            : base(serviceProvider, apiFactory, holder, Octicon.graph)
        {
            this.browser = browser;
            Text = Resources.GraphsNavigationItemText;
            ArgbColor = Colors.LightBlueNavigationItem.ToInt32();
        }

        public override void Execute()
        {
            OpenInBrowser(browser, "graphs");
            base.Execute();
        }
    }
}


text:
let init = document.querySelector('#init');

init.addEventListener('click', function() {
    calculator.init();
    Object.keys(calculator).forEach(function(key) {
        console.log(key + ' ' + calculator[key]);
    })
});

let calculator = {
    'buffer' : [''],
    'config' : {
        'sign' : false,
        "next" : 'add'
    },
    'init' : function() {
        let content = document.querySelector('div');
        content.appendChild(calculator.drawTable());
        let table = content.childNodes[0];
        table.appendChild(calculator.drawRow());
        table.appendChild(calculator.drawRow('', 0, '*', '='));
        table.appendChild(calculator.drawRow(7, 8, 9, '/'));
        table.appendChild(calculator.drawRow(4, 5, 6, '-'));
        table.appendChild(calculator.drawRow(1, 2, 3, '+'));
    },
    'drawTable' : function() {
        return document.createElement('table')
    },
    'drawRow' : function(first, second, third, forth) {
        let tr = document.createElement('tr');
        tr.appendChild(calculator.drawCell(first));
        tr.appendChild(calculator.drawCell(second));
        tr.appendChild(calculator.drawCell(third));
        tr.appendChild(calculator.drawCell(forth));
        return tr;
    },
    'drawCell' : function(value) {
        let td = document.createElement('td');
        td.textContent = value;
        if(value !== '') {
            td.addEventListener('click', function() {
                calculator.operation(value);
            });
        }
        return td;
    },
    'operation' : function(key) {
        if(key !== '+' && key !== '-' && key !== '*' && key !== '/' && key !== '=') {
            if(calculator.config.sign === true) {
                calculator.buffer.push(key.toString());
                calculator.config.sign = false;
            }
            else {
                let tmp = calculator.buffer.pop();
                calculator.buffer.push(tmp + key.toString());
            }
        }
        else {
            if(key !== '=') {
                calculator.buffer.push(key);
                calculator.config.sign = true;
            }
            else {
                calculator.result();
            }
        }
    },
    'result' : function() {
        let result = 0;
        for(let item of calculator.buffer) {
            console.log(item);
            if(item === "+") {
                calculator.config.next = 'add';
            }
            else if(item === '-') {
                calculator.config.next = 'sub';
            }
            else if(item === '/') {
                calculator.config.next = 'div';
            }
            else if(item === '*') {
                calculator.config.next = 'mult';
            }
            else {
                // operation calcul
                if(calculator.config.next === 'add') {
                    result = parseInt(result) + parseInt(item);
                }
                else if(calculator.config.next === 'sub') {
                    result = parseInt(result) - parseInt(item);
                }
                else if(calculator.config.next === 'div') {
                    result = parseInt(result) / parseInt(item);
                }
                else if(calculator.config.next === 'mult') {
                    result = parseInt(result) * parseInt(item);
                }
            }
        }
        alert(result);
    }
}


text:
layout: paper
year: 1993
title: Implementing Fudgets with Standard Widget Sets
publisher: Springer London
pages: 222--235
month: July
location: Ayr, Scotland
isbn: 978-1-4471-3236-3
editor: John T. O'Donnell, Kevin Hammond
doi: 10.1007/978-1-4471-3236-3_18
day: 5-7
booktitle: Proceedings of the 1993 Glasgow Workshop on Functional Programming
author: Alastair Reid, Satnam Singh
ar_shortname: GFPW 93
ar_file: GFPW_93
affiliation: University of Glasgow
address: London
abstract: |

    Carlsson and Hallgren describe the implementation of a set of
    "functional widgets" (Fudgets): components for programming graphical
    user interfaces under the X window system using the non-strict
    functional programming language Haskell.
    We describe an alternative implementation based on existing
    widget sets (currently Openlook and Motif).
    Our purpose is twofold: to show that the Fudgets approach can be
    applied to existing widget sets; and to discuss problems experienced
    with Fudgets during an industrial case study.
ENTRYTYPE: inbook
ID: Reid1993
bibtex: |
    @inbook{Reid1993
        , abstract = {
    Carlsson and Hallgren describe the implementation of a set of
    "functional widgets" (Fudgets): components for programming graphical
    user interfaces under the X window system using the non-strict
    functional programming language Haskell.
    We describe an alternative implementation based on existing
    widget sets (currently Openlook and Motif).
    Our purpose is twofold: to show that the Fudgets approach can be
    applied to existing widget sets; and to discuss problems experienced
    with Fudgets during an industrial case study.
    }
        , address = {London}
        , affiliation = {University of Glasgow}
        , ar_file = {GFPW_93}
        , ar_shortname = {GFPW 93}
        , author = {Alastair Reid and Satnam Singh}
        , booktitle = {Proceedings of the 1993 Glasgow Workshop on Functional Programming}
        , day = {5-7}
        , doi = {10.1007/978-1-4471-3236-3\_18}
        , editor = {John T. O'Donnell and Kevin Hammond}
        , isbn = {978-1-4471-3236-3}
        , location = {Ayr, Scotland}
        , month = {July}
        , pages = {222--235}
        , publisher = {Springer London}
        , title = {{I}mplementing {F}udgets with {S}tandard {W}idget {S}ets}
        , year = {1993}
    }
---


text:
import {Injectable} from '@angular/core';
import {BaseCrudService} from "./base-crud.service";
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import {User} from "./users.service";
import {List} from "./list";
import {Challenge} from './challenge.service';
import {AuthService} from '../auth/auth.service';

@Injectable()
export class LadderService extends BaseCrudService<Ladder> {

  url = '/api/ladder';

  challengeAbove : number = 2;
  challengeBelow : number = 2;

  constructor(public http: HttpClient, private authService : AuthService) {
    super(http);
  }

  getLadderUsers(id: number): Observable<LadderUser[]> {
    return this.http.get<List<LadderUser>>(`${this.url}/${id}/members`)
      .map(list=>{
      let loggedInUser = this.authService.getCurrentUser();
      let loggedInUserPosition = list.data.find(item => item.userId === loggedInUser.id).position;
      list.data.map(user => {
        if (user.challenger && user.challenger.challengedId === loggedInUser.id) {
          user.isChallenger = true;
        } else if (user.challenged && user.challenged.challengerId === loggedInUser.id) {
          user.isChallenged = true;
        } else if (user.position < loggedInUserPosition && user.position >= loggedInUserPosition - this.challengeAbove
          || user.position > loggedInUserPosition && user.position <= loggedInUserPosition + this.challengeBelow) {
          user.canChallenge = true;
        }

        return user;
      });
      return list.data;
    })

  }
}

export interface Ladder {
  id: number;
  name: string;
  created: Date;
}

export interface LadderUser extends User {
  position: number;
  isChallenger: boolean;
  isChallenged: boolean;
  canChallenge: boolean;
  userId: number;
  challenged: Challenge;
  challenger: Challenge;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of Tense in UD_Afrikaans</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Afrikaans: Features: Tense

This feature is universal.
It occurs with 2 different values: Past, Pres.

7591 tokens (15%) have a non-empty value of Tense.
1030 types (17%) occur at least once with a non-empty value of Tense.
797 lemmas (15%) occur at least once with a non-empty value of Tense.
The feature is used with 2 part-of-speech tags: <tt>VERB</tt> (4317; 9% instances), <tt>AUX</tt> (3274; 7% instances).

VERB

4317 <tt>VERB</tt> tokens (100% of all VERB tokens) have a non-empty value of Tense.

The most frequent other feature values with which VERB and Tense co-occurred: <tt>Subcat</tt><tt>=Tran</tt> (3568; 83%), <tt>VerbForm</tt><tt>=Fin,Inf</tt> (3424; 79%).

VERB tokens may have the following values of Tense:

Past (893; 21% of non-empty Tense): gemaak gedoen gestel uitgereik geneem geregistreer ingedien ingevul gebaseer ingevoer

Pres (3424; 79% of non-empty Tense): doen maak gebruik het verbeter verseker stel betaal verskaf werk

Paradigm doen	<tt>Pres</tt>	<tt>Past</tt>

<tt><tt>Subcat</tt><tt>=Intr</tt>|<tt>VerbForm</tt><tt>=Fin,Inf</tt></tt>	doen

<tt><tt>Subcat</tt><tt>=Tran</tt>|<tt>VerbForm</tt><tt>=Fin,Inf</tt></tt>	doen

<tt><tt>Subcat</tt><tt>=Tran</tt>|<tt>VerbForm</tt><tt>=Part</tt></tt>		gedoen

AUX

3274 <tt>AUX</tt> tokens (100% of all AUX tokens) have a non-empty value of Tense.

The most frequent other feature values with which AUX and Tense co-occurred: <tt>VerbForm</tt><tt>=Fin,Inf</tt> (2899; 89%).

AUX tokens may have the following values of Tense:

Past (375; 11% of non-empty Tense): is was moes sou kon geword geraak geblyk gelyk gewees

Pres (2899; 89% of non-empty Tense): word is sal het moet kan wees wil mag behoort

Paradigm is	<tt>Pres</tt>	<tt>Past</tt>

<tt><tt>VerbForm</tt><tt>=Fin,Inf</tt>|<tt>VerbType</tt><tt>=Cop</tt></tt>	is

<tt><tt>VerbForm</tt><tt>=Fin</tt>|<tt>VerbType</tt><tt>=Cop</tt></tt>		was

<tt><tt>VerbForm</tt><tt>=Fin</tt>|<tt>VerbType</tt><tt>=Pas</tt></tt>		is

Relations with Agreement in Tense

The 10 most frequent relations where parent and child node agree in Tense:
<tt>VERB –[<tt>aux</tt>]–> AUX</tt> (1007; 68%),
<tt>VERB –[<tt>obl</tt>]–> VERB</tt> (362; 79%),
<tt>VERB –[<tt>conj</tt>]–> VERB</tt> (237; 75%),
<tt>VERB –[<tt>ccomp</tt>]–> VERB</tt> (119; 72%),
<tt>AUX –[<tt>aux</tt>]–> AUX</tt> (95; 86%),
<tt>VERB –[<tt>xcomp</tt>]–> VERB</tt> (64; 98%),
<tt>VERB –[<tt>cop</tt>]–> AUX</tt> (31; 82%),
<tt>AUX –[<tt>ccomp</tt>]–> VERB</tt> (26; 81%),
<tt>AUX –[<tt>conj</tt>]–> VERB</tt> (23; 72%),
<tt>VERB –[<tt>xcomp</tt>]–> AUX</tt> (20; 100%).

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
require 'qiniu'

# 构建鉴权对象
Qiniu.establish_connection! access_key: 'Access_Key',
                            secret_key: 'Secret_Key'

# 你要测试的list的空间名
bucket = 'xxxx'

# 调用list接口,参数可以参考 http://developer.qiniu.com/code/v6/api/kodo-api/rs/list.html#list-specification
code, result, response_headers, s, d = Qiniu::Storage.list(Qiniu::Storage::ListPolicy.new(
    bucket,   # bucket
    100,      # limit
    'photo/', # prefix
    ''        # delimiter
))

# 打印出返回的状态码和信息
puts code
puts result
puts response_headers


text:
require "mongoid/relations/accessors"
require "mongoid/relations/cascading"
require "mongoid/relations/cyclic"
require "mongoid/relations/proxy"
require "mongoid/relations/bindings"
require "mongoid/relations/builders"
require "mongoid/relations/many"
require "mongoid/relations/one"
require "mongoid/relations/polymorphic"
require "mongoid/relations/embedded/in"
require "mongoid/relations/embedded/many"
require "mongoid/relations/embedded/one"
require "mongoid/relations/referenced/in"
require "mongoid/relations/referenced/many"
require "mongoid/relations/referenced/many_to_many"
require "mongoid/relations/referenced/one"
require "mongoid/relations/reflections"
require "mongoid/relations/metadata"
require "mongoid/relations/macros"

module Mongoid # :nodoc:

  # All classes and modules under the relations namespace handle the
  # functionality that has to do with embedded and referenced (relational)
  # associations.
  module Relations
    extend ActiveSupport::Concern
    include Accessors
    include Cascading
    include Cyclic
    include Builders
    include Macros
    include Polymorphic
    include Reflections

    included do
      attr_accessor :metadata
    end

    # Determine if the document itself is embedded in another document via the
    # proper channels. (If it has a parent document.)
    #
    # @example Is the document embedded?
    #   address.embedded?
    #
    # @return [ true, false ] True if the document has a parent document.
    #
    # @since 2.0.0.rc.1
    def embedded?
      _parent.present?
    end

    # Determine if the document is part of an embeds_many relation.
    #
    # @example Is the document in an embeds many?
    #   address.embedded_many?
    #
    # @return [ true, false ] True if in an embeds many.
    #
    # @since 2.0.0.rc.1
    def embedded_many?
      metadata && metadata.macro == :embeds_many
    end

    # Determine if the document is part of an embeds_one relation.
    #
    # @example Is the document in an embeds one?
    #   address.embedded_one?
    #
    # @return [ true, false ] True if in an embeds one.
    #
    # @since 2.0.0.rc.1
    def embedded_one?
      metadata && metadata.macro == :embeds_one
    end

    # Determine if the document is part of an references_many relation.
    #
    # @example Is the document in a references many?
    #   post.referenced_many?
    #
    # @return [ true, false ] True if in a references many.
    #
    # @since 2.0.0.rc.1
    def referenced_many?
      metadata && metadata.macro == :references_many
    end

    # Determine if the document is part of an references_one relation.
    #
    # @example Is the document in a references one?
    #   address.referenced_one?
    #
    # @return [ true, false ] True if in a references one.
    #
    # @since 2.0.0.rc.1
    def referenced_one?
      metadata && metadata.macro == :references_one
    end
  end
end


text:
@interface ChatMessage () {
@protected

    NSData *_internalData;
    NSData *_bodyData;
    NSData *_jsonLenData;
    NSData *_jsonData;

    NSMutableDictionary *_chatHeader;
    NSMutableDictionary *_chatBody;
}
@end
@implementation ChatMessage
//RES
- (instancetype)initWithResponseCode:(ChatResponseCode)code{
    self = [super init];
    if (self) {
        _messageType = ChatMessageTypeResponse;
        self.responseCode = code;
    }
    return self;
}
//REQ
- (instancetype)init{
    if (self = [super init]) {
        _messageType = ChatMessageTypeRequest;
        _chatHeader = [NSMutableDictionary dictionary];
        _chatBody = [NSMutableDictionary dictionary];
    }
    return self;
}
//RES
- (instancetype)initWithData:(NSData *)data{
    self = [super init];
    if (self) {
        _messageType = ChatMessageTypeUnkown;
        _internalData = data;
        if ([data length]) {
            [self parseData];
        }
    }
    return self;
}

- (void)addHeader:(id)value forKey:(id)key{
    if ([key isEqualToString:ChatMessageBodyKey]) {
        return;
    }
    if (key) {
        _chatHeader[key] = value;
    }
}
- (id)headerForKey:(id)key{
    return _chatHeader[key];
}

- (void)addBody:(id)value forKey:(id)key{
    if (key) {
        _chatBody[key] = value;
    }
}
- (id)bodyForKey:(id)key{
    return _chatBody[key];
}

- (void)setBodyData:(NSData *)data{
    _bodyData = data;
}
- (NSData *)bodyData{
    return _bodyData;
}

- (void)setResponseCode:(ChatResponseCode)responseCode{
    _responseCode = responseCode;
    [self addHeader:@(responseCode) forKey:ChatResponseCodeKey];
}
- (void)setMethod:(NSString *)method{
    [_chatHeader setObject:method forKey:ChatRequestMethodKey];
}

- (NSString *)method{
    return [_chatHeader objectForKey:ChatRequestMethodKey];
}

- (NSData *)toMessage{
    NSInteger jsonDataLength = 2;
    NSError *error = nil;
    _chatHeader[ChatMessageTypeKey] = [self __chatMessageTypeWithKey:_messageType];
    if (_chatBody.allValues.count) {//addBodyIntoIt
        _chatHeader[ChatMessageBodyKey] = _chatBody;
    }
    _jsonData = [CSJsonUntil toJsonWithObject:_chatHeader error:&error];
    if (error) {
        NSLog(@"Fail with - toMessage func, error = %@", error.localizedDescription);
        return nil;
    }

    NSInteger jsonLen = [_jsonData length];
    _jsonLenData = [NSData dataWithBytes:&jsonLen length:jsonDataLength];
    NSMutableData *retVal = [NSMutableData data];
    //jsonlen
    [retVal appendData:_jsonLenData];
    //json
    [retVal appendData:_jsonData];
    //body
    if ([self bodyData]) {
        [retVal appendData:[self bodyData]];
    }
    return retVal;
}

- (BOOL)parseData{
    NSInteger jsonDataLength = 2;
    _jsonLenData = [_internalData subdataWithRange:(NSRange){0, jsonDataLength}];
    NSInteger jsonLen = *((NSInteger *)_jsonLenData.bytes);

    //json
    _jsonData = [_internalData subdataWithRange:(NSRange){jsonDataLength, jsonLen}];
    NSInteger bodyLen = _internalData.length - (jsonLen + jsonDataLength);
    //body
    if (bodyLen > 0) {
        [self setBodyData:[_internalData subdataWithRange:(NSRange){(jsonLen + jsonDataLength), bodyLen}]];
    }
    NSError *error = nil;
    id object = [CSJsonUntil jsonWithData:_jsonData error:&error];
    if (error) {
        NSLog(@"Fail with - parseData func, error = %@", error.localizedDescription);
        return NO;
    }
    if ([object isKindOfClass:[NSDictionary class]]) {
        _chatHeader = object;
        _chatBody = _chatHeader[ChatMessageBodyKey];
        _messageType = [self __typeWithChatMessageTypeKey:[self chatMessageType]];
        _responseCode = [_chatHeader[ChatResponseCodeKey] unsignedIntegerValue];
        return YES;
    }
    NSLog(@"Fail with - parseData func, is not a NSDictionary class");
    return NO;
}

- (NSString *)chatMessageType{
    return _chatHeader[ChatMessageTypeKey];
}

- (NSString *)description{
    return _chatHeader.description;
}

- (ChatMessageType)__typeWithChatMessageTypeKey:(NSString *)key{
    if ([key isEqualToString:ChatRequestMessage]) {
        return ChatMessageTypeRequest;
    }else if ([key isEqualToString:ChatResponseMessage]){
        return ChatMessageTypeResponse;
    }
    return ChatMessageTypeUnkown;
}
- (NSString *)__chatMessageTypeWithKey:(ChatMessageType)type{
    switch (type) {
        case ChatMessageTypeRequest: return ChatRequestMessage;
        case ChatMessageTypeResponse: return ChatResponseMessage;
        default: break;
    }
    return ChatUnkownMessage;
}
@end


text:
class Profile < ApplicationRecord
  belongs_to :user
end


text:
/**
 * Given a List of words,
 * return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
 *
 * Example 1:
 *  Input: ["Hello", "Alaska", "Dad", "Peace"]
 *  Output: ["Alaska", "Dad"]
 *
 * Note:
 *  You may use one character in the keyboard more than once.
 *  You may assume the input string will only contain letters of alphabet.
 */

/**
 * @param {string[]} words
 * @return {string[]}
 */
var findWords = function(words) {
    var len = words.length;

    if(len === 0) return [];

    var line1 = 'qwertyuiop';
    var line2 = 'asdfghjkl';
    var line3 = 'zxcvbnm';

    var ret = [];

    words.forEach(function (word) {
        if( check(word) ) {
            ret.push(word);
        }
    });

    function check(word) {
        word = word.toLowerCase();

        var oldLine = 0;
        var newLine = 0;

        for(var i=0; i<word.length; i++) {
            var char = word.charAt(i);

            if( line1.indexOf(char) > -1 ) { newLine = 1; }
            else if( line2.indexOf(char) > -1 ) { newLine = 2; }
            else if( line3.indexOf(char) > -1 ) { newLine = 3; }

            if( oldLine === 0 ) {
                oldLine = newLine;
            }else{
                if( oldLine != newLine ) {
                    return false;
                }
            }
        }

        return true;
    }

    return ret;
};


text:
class Never : public TriggerCondition {

public:

    bool isTriggered(AbstractTree &tree);

};
#endif //NEVER_H


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0022_add_error_fields'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='layer',
            name='thumb_large',
        ),
        migrations.RemoveField(
            model_name='layer',
            name='thumb_small',
        ),
        migrations.RemoveField(
            model_name='layerimage',
            name='thumb_large',
        ),
        migrations.RemoveField(
            model_name='layerimage',
            name='thumb_small',
        ),
        migrations.AddField(
            model_name='layer',
            name='thumb_large_key',
            field=models.CharField(default='', help_text='400x150 pixels', max_length=255, blank=True),
        ),
        migrations.AddField(
            model_name='layer',
            name='thumb_small_key',
            field=models.CharField(default='', help_text='80x80 pixels', max_length=255, blank=True),
        ),
        migrations.AddField(
            model_name='layerimage',
            name='thumb_large_key',
            field=models.CharField(default='', help_text='300x300 pixels', max_length=255, blank=True),
        ),
        migrations.AddField(
            model_name='layerimage',
            name='thumb_small_key',
            field=models.CharField(default='', help_text='80x80 pixels', max_length=255, blank=True),
        ),
        migrations.AlterField(
            model_name='layer',
            name='status',
            field=models.CharField(default='created', help_text='Processing workflow status of the layer', max_length=12, blank=True, choices=[('created', 'Created'), ('uploaded', 'Uploaded'), ('validated', 'Validated'), ('thumbnailed', 'Thumbnailed'), ('processing', 'Processing'), ('failed', 'Failed'), ('completed', 'Completed')]),
        ),
        migrations.AlterField(
            model_name='layerimage',
            name='status',
            field=models.CharField(default='created', help_text='Image processing workflow status of the image', max_length=12, blank=True, choices=[('created', 'Created'), ('uploaded', 'Uploaded'), ('valid', 'Valid'), ('invalid', 'Invalid'), ('thumbnailed', 'Thumbnailed')]),
        ),
    ]


text:
require 'rubygems'
require 'bundler'

require 'simplecov'
SimpleCov.start do
  add_filter '/spec/'
end

Bundler.require(:default, :development, :test)

require 'protobuf/rspec'
require 'support/helpers'

$LOAD_PATH << ::File.expand_path('../support/protobuf', __FILE__)
require 'support/protobuf'
require 'support/models'

RSpec.configure do |config|
  config.include Protobuf::RSpec::Helpers

  # Turn deprecation warnings into errors with full backtrace.
  config.raise_errors_for_deprecations!

  # Verifies the existance of any stubbed methods, replaces better_receive and better_stub
  # https://www.relishapp.com/rspec/rspec-mocks/v/3-1/docs/verifying-doubles/partial-doubles
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end