text:
#include "arg.h"
#include "configuration.h"
#include "generate_action.h"
#include "pull_action.h"
#include "build_action.h"
#include "available_builds.h"
#include "create_action.h"
#include "status_action.h"
#include "correct_branch_action.h"
#include "buildset_printer_action.h"
#include "print_environment_action.h"

#include <vector>
#include <iostream>

#include "../3rdparty/optionparser/src/optionparser.h"

enum optionIndex {
    UNKNOWN,
    HELP,
    SRC_DIR,
    BUILD_DIR,
    INSTALL_DIR,
    BUILDSET,
    BUILDSET_DIR,
    BUILDSET_OUT,
    RESET_SHA,
    BUILD_FROM,
    ONLY_ONE,
    CONTINUE,
    PULL_FIRST,
    CORRECT_BRANCH,
    CLEAN,
    DEEP_CLEAN,
    SKIP_CONFIGURE,
    SKIP_BUILD,
    NO_REGISTER,
    PRINT
};

const option::Descriptor usage[] =
 {
  {UNKNOWN,       0,  "", "",                 Arg::unknown,                 "USAGE: build_shell [options] mode\n\n"
                                                                            "Modes\n"
                                                                            "  generate\t generate a new buildset file\n"
                                                                            "  create\t create a buildset environment\n\n"
                                                                            "  pull\t pulls sources specified in buildsetfile\n"
                                                                            "  build\t builds a buildset file\n\n"
                                                                            "Options:" },
  {HELP,          0, "h" , "help",            option::Arg::None,            "  --help, -h\tPrint usage and exit." },
  {SRC_DIR,       0, "s", "src-dir",          Arg::requiresArg,             "  --src-dir, -s  \tSource dir, where projects are cloned\v"
                                                                            "     and builds read their sources from." },
  {BUILD_DIR,     0, "b", "build-dir",        Arg::requiresArg,             "  --build-dir, -b     \tBuild dir, defaults to source dir. This is\v"
                                                                            "     where the projects will be built."},
  {INSTALL_DIR,   0, "i", "install-dir",      Arg::requiresArg,             "  --install-dir, -i   \tInstall dir, defaults to build dir. This is the directory\v"
                                                                            "     that will be used as prefix for projects."},
  {BUILDSET,      0, "f", "buildset",         Arg::requiresExistingFile,    "  --buildset -f  \tFile used as input for projects"},
  {BUILDSET_DIR,  0, "d", "buildset-dir",     Arg::requiresExistingDir,     "  --buildset-dir -d\tDir used to create build shell configuration"},
  {BUILDSET_OUT,  0, "o", "buildset-out",     Arg::requiresNonExistingFile, "  --buildset-out -o  \tFile used for creating buildset file"},
  {RESET_SHA,     0, "" , "reset-sha",        option::Arg::None,            "  --reset-sha \tIn pull mode reset to sha"},
  {BUILD_FROM,    0, "" , "from",             Arg::requiresArg,             "  --from \tDoesn't perform the build steps for projectes before the mentioned project"},
  {ONLY_ONE,      0, "" , "only-one",         option::Arg::None,            "  --only-one \tOnly build one project"},
  {CONTINUE,      0, "" , "continue",         option::Arg::None,            "  --continue \tDisables only-one"
                                                                            "             \t    This is usefull when using the --from option as the option enables"
                                                                            "             \t    --only-one by default"},
  {PULL_FIRST,    0, "" , "pull-first",       option::Arg::None,            "  --pull-first \tPull/Clone before building"},
  {CORRECT_BRANCH,0, "" , "correct-branch",   option::Arg::None,            "  --correct-branch \tAdjust branch to be the branch specified in the buildset"},
  {CLEAN,         0, "" , "clean",            option::Arg::None,            "  --clean \tRun clean scripts"},
  {DEEP_CLEAN,    0, "" , "deep-clean",       option::Arg::None,            "  --deep-clean\tRemove build directory if differentg from source dir\n"
                                                                            "              \t    and run deep clean script on source. This option discard clean"},
  {SKIP_CONFIGURE,0, "" , "skip-configure",   option::Arg::None,            "  --skip-configure \tSkipping the configure step when running in build mode"},
  {SKIP_BUILD,    0, "" , "skip-build",       option::Arg::None,            "  --skip-build     \tSkipping the build step when running in build mode"},
  {NO_REGISTER,   0, "" , "no-register",      option::Arg::None,            "  --no-register    \tDon't register the build"},
  {PRINT,         0, "" , "print",            option::Arg::None,            "  --print          \tPrint all output"},

  {UNKNOWN, 0,"" ,  ""   ,                    option::Arg::None,            "\nExamples:\n"
                                                                            "  build_shell --src-dir /some/file -f ../some/buildset_file pull\n"},
  {0,0,0,0,0,0}
 };

int main(int argc, char **argv)
{
    argc-=(argc>0); argv+=(argc>0);
    option::Stats  stats(true, usage, argc, argv);
    std::vector<option::Option> options(stats.options_max);
    std::vector<option::Option> buffer(stats.buffer_max);
    option::Parser parser(true, usage, argc, argv, options.data(), buffer.data());

    if (parser.error()) {
        return 1;
    }

    if (options[HELP] || argc == 0) {
        option::printUsage(std::cout, usage);
        return 0;
    }

    Configuration configuration;

    if (parser.nonOptionsCount() == 1) {
        std::string mode = parser.nonOption(0);
        if (mode == "pull") {
            configuration.setMode(Configuration::Pull, mode);
        } else if (mode == "generate") {
            configuration.setMode(Configuration::Generate, mode);
        } else if (mode == "build") {
            configuration.setMode(Configuration::Build, mode);
        } else if (mode == "rebuild") {
            configuration.setMode(Configuration::Rebuild, mode);
        } else if (mode == "available") {
            AvailableBuilds available(configuration);
            available.printAvailable();
            return 0;
        } else if (mode == "build_shell_dev_build") {
#ifdef JSONMOD_PATH
            return 0;
#endif
            return 1;
        } else if (mode == "create") {
            configuration.setMode(Configuration::Create, mode);
        } else if (mode == "status") {
            configuration.setMode(Configuration::Status, mode);
        } else if (mode == "print") {
            configuration.setMode(Configuration::Print, mode);
        } else if (mode == "print_env") {
            configuration.setMode(Configuration::PrintEnv, mode);
        } else if (mode == "correct-branch") {
            configuration.setMode(Configuration::CorrectBranch, mode);
        } else {
            fprintf(stderr, "\nFailed to recognize mode: %s\n\n", mode.c_str());
            return 1;
        }
    } else if (parser.nonOptionsCount() == 2) {
        std::string mode = parser.nonOption(0);
        if ( mode == "get_env_file") {
            AvailableBuilds available(configuration);
            available.printGetEnv(parser.nonOption(1));
            return 0;
        } else {
            fprintf(stderr, "\nFailed to recognize mode\n\n");
            option::printUsage(std::cerr, usage);
            return 1;
        }
    } else {
        fprintf(stderr, "\nFailed to recognize mode\n\n");
        return 1;
    }

    for (int i = 0; i < parser.optionsCount(); ++i)
    {
        option::Option& opt = buffer[i];
        switch (opt.index())
        {
            case HELP:
                // not possible, because handled further above and exits the program
            case SRC_DIR:
                configuration.setSrcDir(opt.arg);
                break;
            case BUILD_DIR:
                configuration.setBuildDir(opt.arg);
                break;
            case INSTALL_DIR:
                configuration.setInstallDir(opt.arg);
                break;
            case BUILDSET:
                configuration.setBuildsetFile(opt.arg);
                break;
            case BUILDSET_DIR:
                configuration.setBuildsetDir(opt.arg);
                break;
            case BUILDSET_OUT:
                configuration.setBuildsetOutFile(opt.arg);
                break;
            case RESET_SHA:
                configuration.setResetToSha(true);
                break;
            case BUILD_FROM:
                configuration.setBuildFromProject(opt.arg);
                break;
            case ONLY_ONE:
                configuration.setOnlyOne(true);
                break;
            case CONTINUE:
                configuration.setOnlyOne(false);
                break;
            case PULL_FIRST:
                configuration.setPullFirst(true);
                break;
            case CLEAN:
                configuration.setClean(true);
                break;
            case DEEP_CLEAN:
                configuration.setDeepClean(true);
                break;
            case SKIP_CONFIGURE:
                configuration.setConfigure(false);
                break;
            case SKIP_BUILD:
                configuration.setBuild(false);
                break;
            case NO_REGISTER:
                configuration.setRegisterBuild(false);
                break;
            case PRINT:
                configuration.setPrint(true);
                break;
            case CORRECT_BRANCH:
                configuration.setCorrectBranch(true);
                break;
            case UNKNOWN:
                fprintf(stderr, "UNKNOWN!");
                // not possible because Arg::Unknown returns ARG_ILLEGAL
                // which aborts the parse with an error
                break;
        }
    }

    configuration.validate();

    Action *action;
    if (!configuration.sane()) {
        option::printUsage(std::cerr,usage);
        return 1;
    } else {
        switch (configuration.mode()) {
            case Configuration::Generate:
                action = new GenerateAction(configuration);
                break;
            case Configuration::Pull:
                action = new PullAction(configuration);
                break;
            case Configuration::Build:
            case Configuration::Rebuild:
                action = new BuildAction(configuration);
                break;
            case Configuration::Create:
                action = new CreateAction(configuration);
                break;
            case Configuration::Status:
                action = new StatusAction(configuration);
                break;
            case Configuration::Print:
                action = new BuildsetPrinterAction(configuration);
                break;
            case Configuration::PrintEnv:
                action = new PrintEnvironmentAction(configuration);
                break;
            case Configuration::CorrectBranch:
                action = new CorrectBranchAction(configuration);
                break;
            default:
                fprintf(stderr, "Mode is invalid %s. Exiting\n", configuration.modeString().c_str());
                exit(1);
                break;
        }
    }

    bool error = action->error();
    if (error) {
        fprintf(stderr, "Failure to initialize action object. Not executing\n");
    } else {
        error = !action->execute();
    }

    if (error) {
        fprintf(stderr, "Execution of mode %s failed\n", configuration.modeString().c_str());
    }

    delete action;

    return error;
}


text:
export class Rule extends Lint.Rules.AbstractRule {
    public static FAILURE_STRING_PART = "expected a 'break' before ";

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        return this.applyWithWalker(new NoSwitchCaseFallThroughWalker(sourceFile, this.getOptions()));
    }
}

export class NoSwitchCaseFallThroughWalker extends Lint.RuleWalker {
    public visitSwitchStatement(node: ts.SwitchStatement) {
        let isFallingThrough = false;

        // get the position for the first case statement
        const switchClauses = node.caseBlock.clauses;
        switchClauses.forEach((child, i) => {
            const kind = child.kind;
            if (kind === ts.SyntaxKind.CaseClause) {
                const switchClause = <ts.CaseClause> child;
                isFallingThrough = this.fallsThrough(switchClause.statements);
                // no break statements and no statements means the fallthrough is expected.
                // last item doesn't need a break
                if (isFallingThrough && switchClause.statements.length > 0 && ((switchClauses.length - 1) > i)) {
                    if (!this.fallThroughAllowed(switchClauses[i + 1])) {
                        this.addFailure(this.createFailure(child.getEnd(), 1,
                            Rule.FAILURE_STRING_PART + "'case'"));
                    }
                }
            } else {
                // case statement falling through a default
                if (isFallingThrough && !this.fallThroughAllowed(child)) {
                    const failureString = Rule.FAILURE_STRING_PART + "'default'";
                    this.addFailure(this.createFailure(switchClauses[i - 1].getEnd(), 1, failureString));
                }
            }
        });
        super.visitSwitchStatement(node);
    }

    private fallThroughAllowed(nextCaseOrDefaultStatement: ts.Node) {
        const sourceFileText = nextCaseOrDefaultStatement.getSourceFile().text;
        const firstChild = nextCaseOrDefaultStatement.getChildAt(0);
        const commentRanges = ts.getLeadingCommentRanges(sourceFileText, firstChild.getFullStart());
        if (commentRanges != null) {
            for (let commentRange of commentRanges) {
                const commentText = sourceFileText.substring(commentRange.pos, commentRange.end);
                if (commentText === "/* falls through */") {
                    return true;
                }
            }
        }
        return false;
    }

    private fallsThrough(statements: ts.NodeArray<ts.Statement>) {
        return !statements.some((statement) => {
            return statement.kind === ts.SyntaxKind.BreakStatement
                || statement.kind === ts.SyntaxKind.ThrowStatement
                || statement.kind === ts.SyntaxKind.ReturnStatement
                || statement.kind === ts.SyntaxKind.ContinueStatement;
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface ViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

}

- (IBAction)openPhotoBtn:(id)sender {
    //继承了UINavigationViewController
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //图片来源
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    } else {
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }

    imagePicker.delegate = self;
    //是否可编辑,YES在选择照片后会出现一个编辑框
    imagePicker.allowsEditing = YES;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

//ImagePicker Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    NSLog(@"%@",info);
    [picker dismissViewControllerAnimated:YES completion:nil];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
package httpx

import "context"

type headerContextKey string

func (c headerContextKey) String() string {
	return "pkg header " + string(c)
}

func WithHeader(ctx context.Context, headerKey string, headerValue string) context.Context {
	return context.WithValue(ctx, headerContextKey(headerKey).String(), headerValue)
}

func Header(ctx context.Context, headerKey string) string {
	headerValue, _ := ctx.Value(headerContextKey(headerKey).String()).(string)
	return headerValue
}


text:
<?php
/**
 * Invalid lookupd url
 * User: moyo
 * Date: 05/04/2017
 * Time: 10:48 AM
 */

namespace NSQClient\Exception;

class InvalidLookupdException extends \RuntimeException
{

}


text:
import * as https from 'https';
import * as http from 'http';

let proto = require('../../generated_proto/collector_pb.js');

const kMaxDetailedErrorFrequencyMs = 30000;
const kMaxStringLength = 2048;

function truncatedString(s) {
    if (!s || s.length <= kMaxStringLength) {
        return s;
    }
    let half = Math.floor(kMaxStringLength / 2);
    return `${s.substr(0, half)}...${s.substr(-half)}`;
}

function encodeAndTruncate(obj) {
    try {
        return truncatedString(obj.toString('utf8'));
    } catch (exception) {
        return exception;
    }
}

function errorFromResponse(res, buffer) {
    if (buffer && buffer.length) {
        buffer = truncatedString(`${buffer}`.replace(/\s+$/, ''));
    }
    return new Error(`status code=${res.statusCode}, message='${res.statusMessage}', body='${buffer}'`);
}

export default class TransportHTTPProto {
    constructor(logger) {
        this._host = '';
        this._port = 0;
        this._encryption = '';
        this._timeoutMs = 0;

        this._logger = logger;
        this._lastLogMs = 0;
    }

    ensureConnection(opts) {
        this._host       = opts.collector_host;
        this._port       = opts.collector_port;
        this._encryption = opts.collector_encryption;
        this._timeoutMs  = opts.report_timeout_millis;
    }

    _preparePayload(reportRequest, auth, cb) {
        let payload;
        try {
            let reportProto = reportRequest.toProto(auth);
            let binary = reportProto.serializeBinary();
            payload = Buffer.from(binary);
        } catch (exception) {
            // This should never happen. The library should always be constructing
            // valid reports.
            this._error('Could not serialize report!');
            return cb(exception);
        }

        return cb(null, payload);
    }

    report(detached, auth, reportRequest, done) {
        let options = {
            hostname : this._host,
            port     : this._port,
            method   : 'POST',
            path     : '/api/v2/reports',
        };

        let protocol = (this._encryption === 'none') ? http : https;

        this._preparePayload(reportRequest, auth, (payloadErr, payload) => {
            if (payloadErr) {
                this._error('Error serializing payload');
                return done(payloadErr);
            }

            let extraErrorData = [];

            let req = protocol.request(options, (res) => {
                let buffer = [];
                res.on('data', (chunk) => {
                    buffer.push(chunk);
                });
                res.on('end', () => {
                    buffer = Buffer.concat(buffer);
                    let err = null;
                    let resp = null;
                    if (res.statusCode === 400) {
                        this._throttleLog(() => {
                            this._warning('transport status code = 400', {
                                code    : res.statusCode,
                                message : res.statusMessage,
                                body    : buffer,
                                extra   : extraErrorData,
                                report  : encodeAndTruncate(payload),
                            });
                        });
                        err = errorFromResponse(res, buffer);
                    } else if (res.statusCode !== 200) {
                        err = errorFromResponse(res, buffer);
                    } else if (!buffer) {
                        err = new Error('unexpected empty response');
                    } else {
                        try {
                            resp = proto.ReportResponse.deserializeBinary(buffer).toObject();
                        } catch (exception) {
                            err = exception;
                        }
                    }
                    return done(err, resp);
                });
            });
            req.on('socket', (socket, head) => {
                socket.setTimeout(this._timeoutMs);
                socket.on('timeout', () => {
                    // abort() will generate an error, so done() is called as a
                    // result.
                    req.abort();
                    extraErrorData.push(`Request timed out (${this._timeoutMs} ms)`);
                });
            });
            req.on('error', (err) => {
                this._throttleLog(() => {
                    this._warning('HTTP request error', {
                        error  : err,
                        extra  : extraErrorData,
                        report : encodeAndTruncate(reportRequest),
                    });
                });
                done(err, null);
            });

            req.setHeader('Host', this._host);
            req.setHeader('User-Agent', 'LightStep-JavaScript-Node');
            req.setHeader('LightStep-Access-Token', auth.getAccessToken());
            req.setHeader('Accept', 'application/octet-stream');
            req.setHeader('Content-Type', 'application/octet-stream');
            req.setHeader('Content-Length', payload.length);
            if (!detached) {
                req.setHeader('Connection', 'keep-alive');
            }
            req.write(payload);
            req.end();
        });
    }

    _throttleLog(f) {
        let now = Date.now();
        if (now - this._lastLogMs < kMaxDetailedErrorFrequencyMs) {
            return;
        }
        this._lastLogMs = now;
        f();
    }

    _warning(msg, payload) {
        this._logger.warn(msg, payload);
    }

    _error(msg, payload) {
        this._logger.error(msg, payload);
    }
}


text:
function tableStyle(id){
	var Ptr = document.getElementById(id).getElementsByTagName("tr");
	for (i = 1; i < Ptr.length + 1; i++) {
		Ptr[i - 1].className = (i % 2 > 0) ? "t1 ajxaupdate"
				: "t2 ajxaupdate";
	}
	for ( var i = 0; i < Ptr.length; i++) {
		Ptr[i].onmouseover = function() {
			this.tmpClass = this.className;
			this.className = "t3 ajxaupdate";
		};
		Ptr[i].onmouseout = function() {
			this.className = this.tmpClass;
		};
	}
}

function tableStyle2(id){
	var Ptr = document.getElementById(id).getElementsByTagName("tr");
	for (i = 1; i < Ptr.length + 1; i++) {
		Ptr[i - 1].className = (i % 2 > 0) ? "t2 ajxaupdate"
				: "t1 ajxaupdate";
	}
	for ( var i = 0; i < Ptr.length; i++) {
		Ptr[i].onmouseover = function() {
			this.tmpClass = this.className;
			this.className = "t3 ajxaupdate";
		};
		Ptr[i].onmouseout = function() {
			this.className = this.tmpClass;
		};
	}
}

function tableStyleByTrClass(id,cls){
	var Ptr = $("#"+id).find("tr[class='"+cls+"']");
	Ptr.each(function(i){
		Ptr[i].className = (i % 2 > 0) ? "t1 ajxaupdate"
				: "t2 ajxaupdate";
	})
	Ptr.each(function(i){
		Ptr[i].onmouseover = function() {
			if(!$(Ptr[i]).find("input[type=checkbox]").attr("checked")){
				this.tmpClass = this.className;
				this.className = "t3 ajxaupdate";
			}
		};
		Ptr[i].onmouseout = function() {
			if(!$(Ptr[i]).find("input").attr("checked")){
				this.className = this.tmpClass;
			}
		};

		$(Ptr[i]).find("input[type=checkbox]").click(function(){
			if($(this).attr("checked")){
				Ptr[i].tmpClass1 = Ptr[i].tmpClass;
				Ptr[i].className = "t3 ajxaupdate";
			}else if(!$(this).attr("checked")){
				Ptr[i].className = Ptr[i].tmpClass1;
			}
		});
	})
}

function tableStyleByTrTag(id,tag){
	var Ptr = $("#"+id).find("tr");
	Ptr.each(function(i){
		Ptr[i].className = (i % 2 > 0) ? "t1 ajxaupdate" : "t2 ajxaupdate";
	})

	Ptr.each(function(i){
		Ptr[i].onmouseover = function() {
			if(!$(Ptr[i]).find("input[type=checkbox]").attr("checked")){
				this.className = "t3 ajxaupdate";
			}
		};
		Ptr[i].onmouseout = function() {
			if(!$(Ptr[i]).find("input[type=checkbox]").attr("checked")){
				this.className = (i % 2 > 0) ? "t1 ajxaupdate" : "t2 ajxaupdate";
			}
		};

		$(Ptr[i]).find("input[type=checkbox]").click(function(){
			if($(this).attr("checked")){
				Ptr[i].className = "t3 ajxaupdate";
			}else if(!$(this).attr("checked")){
				Ptr[i].className = (i % 2 > 0) ? "t1 ajxaupdate" : "t2 ajxaupdate";
			}
		});
	})
}

//
function selectAllClick(checked, note_name){
	var selectOne = document.getElementsByName("check_one");
	var ptr = document.getElementsByName(note_name);
	for (var i=0; i<selectOne.length; i++){
		selectOne[i].checked = checked;
		ptr[i].className = checked ? "t3 ajxaupdate" :	(i % 2 > 0) ? "t1 ajxaupdate" : "t2 ajxaupdate";
	}
}

//
function selectOneChange(note_name){
	var selectFlagCount = 0;
	$(".select_one[type='checkbox']:checked").each(function(){
		selectFlagCount += 1;
	});
	updateSelectAllCheck(selectFlagCount, true, note_name);
}

//
function updateSelectAllCheck(selectFlagCount, isSelect, note_name){
	var ptr = document.getElementsByName(note_name);
	var changeClass = true;
	if(selectFlagCount == ptr.length){
		if (isSelect){
			$("#select_all").attr("checked", "checked");
			changeClass = false;
		}
		else{
			$("#select_all").removeAttr("checked");
		}
	}else{
		$("#select_all").removeAttr("checked");
	}
	if (changeClass && !isSelect){
		for (var i=0; i<ptr.length; i++){
			ptr[i].className = (i % 2 > 0) ? "t1 ajxaupdate" : "t2 ajxaupdate";
		}
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>nl.uva.vlet</groupId>
    <artifactId>vlet-vfs.lfc</artifactId>
    <version>${vlet.version}</version>
    <name>vfs.lfc (${vlet.version})</name>

    <parent>
        <groupId>nl.uva.vlet</groupId>
        <artifactId>mvnbuild</artifactId>
        <version>1.5.0-dev-2</version>
        <relativePath>../../../mvnbuild/pom.xml</relativePath>
    </parent>

    <build>
        <sourceDirectory>src</sourceDirectory>

        <!--  NOT  <testSourceDirectory>testsrc</testSourceDirectory> -->

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>nl.uva.vlet</groupId>
            <artifactId>vlet-vrs.core</artifactId>
            <version>${vlet.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>nl.uva.vlet</groupId>
            <artifactId>vlet-glite.lfc</artifactId>
            <version>${vlet.version}</version>
        </dependency>
        <dependency>
            <groupId>nl.uva.vlet</groupId>
            <artifactId>vlet-grid.globus</artifactId>
            <version>${vlet.version}</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Text** | **string** | Object text. | [optional]
**Keywords** | [**List<SemanticRolesKeyword>**](SemanticRolesKeyword.md) |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
package org.infinispan.configuration.global;

/**
 * @author Mircea.Markus@jboss.com
 * @since 5.2
 */
public class SiteConfiguration {
   private final String localSite;

   SiteConfiguration(String localSite) {
      this.localSite = localSite;
   }

   /**
    * Returns the name of the local site. Must be a valid name defined in {@link #siteConfigurations()}
    */
   public final String localSite() {
      return localSite;
   }

   @Override
   public boolean equals(Object o) {
      if (this == o) return true;
      if (!(o instanceof SiteConfiguration)) return false;

      SiteConfiguration that = (SiteConfiguration) o;

      if (localSite != null ? !localSite.equals(that.localSite) : that.localSite != null) return false;

      return true;
   }

   @Override
   public int hashCode() {
      return localSite != null ? localSite.hashCode() : 0;
   }

   @Override
   public String toString() {
      return "SiteConfiguration{" +
            "localSite='" + localSite + '\'' +
            '}';
   }
}


text:
package edu.latrobe.blaze.objectives.visual

import edu.latrobe._
import edu.latrobe.blaze._
import edu.latrobe.time._

abstract class XAxisType
  extends Serializable {

  def label
  : String

  def valueFor(optimizer: OptimizerLike)
  : Real

}

object XAxisType {

  case object IterationNo
    extends XAxisType {

    override def label
    : String = "Iteration#"

    override def valueFor(optimizer: OptimizerLike)
    : Real = Real(optimizer.iterationNo)

  }

  case object TimeInSeconds
    extends XAxisType {

    override def label
    : String = "Time (s)"

    override def valueFor(optimizer: OptimizerLike)
    : Real = {
      val now = Timestamp.now()
      TimeSpan(optimizer.beginTime, now).seconds
    }

  }

}


text:
{% extends "layout.html" %}

{% block page_title %}
  Apprenticeships
{% endblock %}

{% block content %}

{% include "includes/phase_banner_beta.html" %}

Back

    Message to alert the user to a problem goes here

    Optional description of the errors and how to correct them

Descriptive link to the question with an error

Access code sent

An acccess code has been sent to pete.kowalczyk@gmail.com

Enter access code

    <form action="/{% include "includes/sprint-link.html" %}/profile">
  <fieldset>
    <legend class="visuallyhidden">Enter code</legend>

              Enter code
              Enter your code here

          <input class="form-control" id="email-code" type="text">

                 <button type="submit" class="button" id="submit-email-code" value="Continue">Continue</button>

</form>

Not received your code?

You can request another access code.

</script>

{% endblock %}


text:
<?php
class PEAR_Installer_Role_Phpf extends PEAR_Installer_Role_Common{}


text:
package com.gbourquet.yaph.client.mvp.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.gbourquet.yaph.client.mvp.presenter.LogoutPresenter;

public class LogoutView extends Composite implements LogoutPresenter.View {

	private static LogoutViewUiBinder uiBinder = GWT.create(LogoutViewUiBinder.class);

	interface LogoutViewUiBinder extends UiBinder<Widget, LogoutView> {
	}

	public LogoutView() {
		initWidget(uiBinder.createAndBindUi(this));
	}
}


text:
package gui;

import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Gui extends Frame {
	Button send, tcpStart, udpStart;
	TextField textField;
	TextArea textArea;
	TextField ipArea, portArea;

	String ip, port;

	public Gui(String title) {
		Frame frame = new Frame(title);
		frame.setLayout(new FlowLayout());
		frame.setBackground(Color.orange);
		frame.setMinimumSize(new Dimension(250, 350));

		send = new Button("Send");
		send.setBackground(Color.pink);
		textField = new TextField(15);
		ipArea = new TextField("ip", 7);
		portArea = new TextField("port", 7);
		tcpStart = new Button("tcp");
		udpStart = new Button("udp");

		send.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				appendNewText(textField.getText().toString());
				textField.setText("");
			}
		});

		udpStart.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

			}
		});
		tcpStart.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {

			}
		});

		textArea = new TextArea(16, 22);
		textArea.setBackground(Color.green);
		textArea.setForeground(Color.BLUE);
		frame.addWindowListener(new W1());

		frame.add(ipArea);
		frame.add(portArea);
		frame.add(tcpStart);
		frame.add(udpStart);

		frame.add(textField);
		frame.add(send);
		frame.add(textArea);

		setFont(new Font("Arial", Font.BOLD, 20));

		frame.setLocation(500, 200);// set the location
		frame.setVisible(true);
		frame.validate();
	}

	private class W1 extends WindowAdapter {
		public void windowClosing(WindowEvent we) {
			System.exit(0);
		}
	}

	public static void main(String args[]) {
		Gui gui = new Gui("TCP-UDP");
	}

	private void appendNewText(String newMessage) {
		StringBuilder sb = new StringBuilder();
		sb.append(textArea.getText().toString());
		sb.append("\n");
		sb.append(newMessage);

		textArea.setText(sb.toString());
	}
}


text:
@interface BMDBaseMessage : NSObject
@property(readonly, atomic)NSString *scheme;
@property(readonly, atomic)NSString *host;
@property(readonly, atomic)NSString *relative;
@property(readonly, atomic)NSString *command;
@property(readonly, atomic)NSDictionary *args;

- (id)initWithHost:(NSString *)host
          relative:(NSString *)relative
           command:(NSString *)command
              args:(NSDictionary *)args;

- (id)initWithURL:(NSURL*)url;

- (NSURL *)generateURL;
@end


text:
using Sitecore.Data.Items;
using Sitecore.Links;
using System.Text;

namespace Revolver.Core.Commands
{
  [Command("links")]
  public class Links : BaseCommand
  {
    private readonly int[] DISPLAY_COLUMN_WIDTHS = new int[] { 11, 8, 20, 10 };
    private const string VALID_LABEL = "yes";
    private const string INVALID_LABEL = "no";
    private const string INCOMING_LABEL = "in";
    private const string OUTGOING_LABEL = "out";
    private const string UNKNOWN_LABEL = "<unknown>";

    [FlagParameter("i")]
    [Description("Show incoming links (referrers).")]
    [Optional]
    public bool ShowIncomingLinks { get; set; }

    [FlagParameter("o")]
    [Description("Show outgoing links (references).")]
    [Optional]
    public bool ShowOutgoingLinks { get; set; }

    [FlagParameter("b")]
    [Description("Show invalid links.")]
    [Optional]
    public bool ShowBadLinks { get; set; }

    [FlagParameter("id")]
    [Description("Output links as an id list.")]
    [Optional]
    public bool OutputIds { get; set; }

    [NamedParameter("f", "field")]
    [Description("The source field the link must originate from.")]
    [Optional]
    public string OriginFieldName { get; set; }

    [NumberedParameter(0, "path")]
    [Description("The path of the item to list the links for.")]
    [Optional]
    public string Path { get; set; }

    public override CommandResult Run()
    {
      var showAll = !ShowBadLinks && !ShowIncomingLinks && !ShowOutgoingLinks;

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var linkDb = Sitecore.Configuration.Factory.GetLinkDatabase();
        if (linkDb == null)
          return new CommandResult(CommandStatus.Failure, "Failed to find the link database");

        var output = new StringBuilder();

        if (!OutputIds)
        {
          Formatter.PrintTable(new[] { "Direction", "Valid", "Field", "Link" }, DISPLAY_COLUMN_WIDTHS, output);
          Formatter.PrintTable(new[] { "---------", "-----", "-----", "----" }, DISPLAY_COLUMN_WIDTHS, output);
          Formatter.PrintLine(string.Empty, output);
        }

        if (ShowIncomingLinks || showAll)
          ProcessIncomingLinks(linkDb.GetReferrers(Context.CurrentItem), output);

        if (ShowOutgoingLinks || showAll)
          ProcessOutgoingLinks(linkDb.GetReferences(Context.CurrentItem), output);

        if (ShowIncomingLinks || showAll)
          ProcessBadLinks(linkDb.GetBrokenLinks(Context.CurrentDatabase), output);

        return new CommandResult(CommandStatus.Success, output.ToString());
      }
    }

    private void ProcessIncomingLinks(ItemLink[] links, StringBuilder output)
    {
      var currentItem = Context.CurrentItem;
      for (int i = 0; i < links.Length; i++)
      {
        if (links[i].TargetItemID == currentItem.ID)
        {
          var fieldItem = Context.CurrentDatabase.GetItem(links[i].SourceFieldID);
          var sourceItem = links[i].GetSourceItem();
          if (sourceItem != null)
          {
            if (string.IsNullOrEmpty(OriginFieldName) || (fieldItem != null && fieldItem.Key == OriginFieldName.ToLower()))
            {
              if (OutputIds)
              {
                if (output.Length > 0)
                  output.Append("|");

                output.Append(sourceItem.ID.ToString());
              }
              else
              {
                if (fieldItem != null)
                  Formatter.PrintTable(new[] { INCOMING_LABEL, VALID_LABEL, fieldItem.Name, sourceItem.Paths.FullPath }, DISPLAY_COLUMN_WIDTHS, output);
                else
                  Formatter.PrintTable(new[] { INCOMING_LABEL, VALID_LABEL, UNKNOWN_LABEL, sourceItem.Paths.FullPath }, DISPLAY_COLUMN_WIDTHS, output);
              }
            }
          }
          else if (!OutputIds)
            Formatter.PrintTable(new string[] { INCOMING_LABEL, INVALID_LABEL, UNKNOWN_LABEL, UNKNOWN_LABEL }, DISPLAY_COLUMN_WIDTHS, output);
        }
      }
    }

    private void ProcessOutgoingLinks(ItemLink[] links, StringBuilder output)
    {
      var currentItem = Context.CurrentItem;
      for (int i = 0; i < links.Length; i++)
      {
        if (links[i].SourceItemID == currentItem.ID)
        {
          var fieldItem = Context.CurrentDatabase.GetItem(links[i].SourceFieldID);
          var targetItem = links[i].GetTargetItem();
          if (targetItem != null)
          {
            if (string.IsNullOrEmpty(OriginFieldName) || (fieldItem != null && fieldItem.Key == OriginFieldName.ToLower()))
            {
              if (OutputIds)
              {
                if (output.Length > 0)
                  output.Append("|");

                output.Append(targetItem.ID.ToString());
              }
              else
              {
                if (fieldItem != null)
                  Formatter.PrintTable(new string[] { OUTGOING_LABEL, VALID_LABEL, fieldItem.Name, targetItem.Paths.FullPath }, DISPLAY_COLUMN_WIDTHS, output);
                else
                  Formatter.PrintTable(new string[] { OUTGOING_LABEL, VALID_LABEL, UNKNOWN_LABEL, targetItem.Paths.FullPath }, DISPLAY_COLUMN_WIDTHS, output);
              }
            }
          }
          else if (!OutputIds)
            Formatter.PrintTable(new string[] { OUTGOING_LABEL, INVALID_LABEL, UNKNOWN_LABEL, UNKNOWN_LABEL }, DISPLAY_COLUMN_WIDTHS, output);
        }
      }
    }

    private void ProcessBadLinks(ItemLink[] links, StringBuilder output)
    {
      var currentItem = Context.CurrentItem;
      for (int i = 0; i < links.Length; i++)
      {
        if (links[i].SourceItemID == currentItem.ID)
        {
          Item sourceFieldItem = Context.CurrentDatabase.GetItem(links[i].SourceFieldID);
          if (string.IsNullOrEmpty(OriginFieldName) || (sourceFieldItem != null && sourceFieldItem.Key == OriginFieldName.ToLower()))
          {
            if (OutputIds)
            {
              if (output.Length > 0)
                output.Append("|");

              output.Append(links[i].TargetItemID.ToString());
            }
            else
            {
              var fieldItem = Context.CurrentDatabase.GetItem(links[i].SourceFieldID);
              if (fieldItem != null)
                Formatter.PrintTable(new string[] { OUTGOING_LABEL, INVALID_LABEL, fieldItem.Name, links[i].TargetPath }, DISPLAY_COLUMN_WIDTHS, output);
              else
                Formatter.PrintTable(new string[] { OUTGOING_LABEL, INVALID_LABEL, UNKNOWN_LABEL, links[i].TargetPath }, DISPLAY_COLUMN_WIDTHS, output);
            }
          }
        }
      }
    }

    public override string Description()
    {
      return "List referrers and references from the link database";
    }

    public override void Help(HelpDetails details)
    {
      details.AddExample("-o ..\a");
      details.AddExample("-i -o ..\a");
      details.AddExample("-b");
      details.AddExample("-o -id");
      details.AddExample("-i -f __source");
    }
  }
}


text:
namespace dialog::editor
{
	// This class is only invoked by RestrictEditor. RestrictEditor always passes an alloc parent.
	// So all memory detached from this class is owned by a parent and must not be freed manually
	static std::wstring COMMENTCLASS = L"ResCommentEditor"; // STRING_OK
	class ResCommentEditor : public CEditor
	{
	public:
		ResCommentEditor(
			_In_ CWnd* pParentWnd,
			_In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects,
			_In_ const _SRestriction* lpRes,
			_In_ LPVOID lpAllocParent);

		_Check_return_ LPSRestriction DetachModifiedSRestriction() noexcept;
		_Check_return_ LPSPropValue DetachModifiedSPropValue() noexcept;
		_Check_return_ ULONG GetSPropValueCount() const noexcept;
		_Check_return_ bool DoListEdit(ULONG ulListNum, int iItem, _In_ sortlistdata::sortListData* lpData) override;

	private:
		void OnEditAction1() override;
		BOOL OnInitDialog() override;
		void InitListFromPropArray(ULONG ulListNum, ULONG cProps, _In_count_(cProps) const _SPropValue* lpProps) const;
		_Check_return_ const _SRestriction* GetSourceRes() const noexcept;
		void OnOK() override;

		LPVOID m_lpAllocParent;
		const _SRestriction* m_lpSourceRes;

		LPSRestriction m_lpNewCommentRes;
		LPSPropValue m_lpNewCommentProp;
		ULONG m_ulNewCommentProp{};
		std::shared_ptr<cache::CMapiObjects> m_lpMapiObjects{};
	};
} // namespace dialog::editor


text:
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset
from django import forms

from campaign.models.user import Squadron

class SquadronForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # If you pass FormHelper constructor a form instance
        # It builds a default layout with all its fields
        self.helper = FormHelper()
        self.helper.form_id = 'add_squadron'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-8'

        # You can dynamically adjust your layout
        self.helper.layout = Layout(
            Fieldset(
                'Create New Squadron',
                'name',
                'invite_only',
            )
        )

        self.helper.layout.append(
            FormActions(
                Submit('save', 'save')
            ),
        )

    class Meta:
        model = Squadron
        fields = (
            'name',
            'invite_only',
        )


text:
var CommandBotName, Icommand;

Icommand = require('../icommand.js');

CommandBotName = class CommandBotName extends Icommand {
  constructor() {
    super();
  }

  handle(sender, text, args, storage, textRouter, commandManager) {
    if (args.length > 1) {
      return false;
    }
    commandManager.send(sender, textRouter, commandManager.toDisplayName(textRouter.getSelfName()));
    return true;
  }

  help(commandPrefix) {
    //console.log "add method to override this!"
    return ["make this bot to say his name, Usage:", `${commandPrefix}`];
  }

  hasPermission(sender, text, args, storage, textRouter, commandManager, fromBinding) {
    return true;
  }

};

module.exports = CommandBotName;


text:
dfst-git-commit-hooks
=====================

DITA for Small Teams-specific commit hook scripts for use with git to support

To use the hooks:

1. Copy or symlink the common/ directory into the .git/hooks directory in your repository
2. Copy or symlink the files in the client-side/ directory into the .git/hooks directory.

After this your .git/hooks directory should look like this:

~~~~
applypatch-msg.sample
commit-msg.sample
common/
post-checkout
post-commit
post-merge
post-update.sample
pre-applypatch.sample
pre-commit.sample
pre-push.sample
pre-rebase.sample
prepare-commit-msg.sample
update.sample
~~~

The hooks rely on the basexclient command, so you must have at least that command in your PATH.


text:
/**
 * \file
 * \brief Event mutex implementation
 *
 * This code implements an event-driven mutex which supports lock acquisition
 * events.
 */

/*
 * Copyright (c) 2010, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
 */

#include <barrelfish/barrelfish.h>
#include <barrelfish/event_mutex.h>
#include <threads.h>

/// Initialise a new event mutex
void event_mutex_init(struct event_mutex *em, struct waitset *waitset)
{
    thread_mutex_init(&em->tmutex);
    event_queue_init(&em->equeue, waitset, EVENT_QUEUE_ONESHOT);
    em->tqueue = NULL;
    em->locked = false;
}

/**
 * \brief Enqueue a lock acquisition request for the mutex
 *
 * \param em Event mutex
 * \param qn Storage for queue node. allocated by caller, live until continuation runs
 * \param lockcont Continuation for lock acquisition
 *
 * \returns true iff the lock was acquired and the continuation run, false if enqueued
 */
bool event_mutex_enqueue_lock(struct event_mutex *em,
                              struct event_queue_node *qn,
                              struct event_closure lockcont)
{
    thread_mutex_lock(&em->tmutex);

    if (!em->locked) {
        // got the lock! we're the first in, so we can just run our event
        em->locked = true;
        thread_mutex_unlock(&em->tmutex);
        lockcont.handler(lockcont.arg);
        return true;
    } else {
        // failed, enqueue our event
        event_queue_add(&em->equeue, qn, lockcont);
        thread_mutex_unlock(&em->tmutex);
        return false;
    }
}

/**
 * \brief Acquire the mutex, blocking the calling thread until done
 *
 * \param em Event mutex
 */
void event_mutex_threaded_lock(struct event_mutex *em)
{
    thread_mutex_lock(&em->tmutex);

    if (!em->locked) {
        // got the lock! we're done...
        em->locked = true;
        thread_mutex_unlock(&em->tmutex);
    } else {
        // add ourselves to the thread queue and block
        // XXX: TODO: the mutex unlock and block on the queue must be atomic
        assert(!"this is broken without thread_block_and_release_mutex()");
        thread_mutex_unlock(&em->tmutex);
        void *wakeup_reason = thread_block(&em->tqueue);

        assert(wakeup_reason == em);
        assert(em->locked);
    }
}

/**
 * \brief Unlock the mutex, which must be held by the caller
 *
 * \note This always prefers releasing a thread rather than triggering the next
 * event, so threaded code can starve event-driven code in a program that mixes
 * the two models.
 */
void event_mutex_unlock(struct event_mutex *em)
{
    errval_t err;

    thread_mutex_lock(&em->tmutex);
    assert(em->locked);

    // is there a thread waiting? if so unblock it
    if (em->tqueue != NULL) {
        thread_unblock_one(&em->tqueue, em);
        thread_mutex_unlock(&em->tmutex);
        return;
    }

    // fire the next event if there is one, handing over the lock
    err = event_queue_trigger(&em->equeue);
    if (err_is_ok(err)) {
        // new event is now triggered: keep lock held
    } else {
        assert(err_no(err) == LIB_ERR_EVENT_QUEUE_EMPTY);
        // nothing else in the queue: release lock
        em->locked = false;
    }

    thread_mutex_unlock(&em->tmutex);
}


text:
var assert = require('assert-plus');
var jdiff = require('json-diff');

function AssertDiff() {
  assert.ok.apply(assert.ok, arguments);
}

AssertDiff.options = {strict: false};

Object.keys(assert).forEach(function(k) {
  AssertDiff[k] = function() {
    assert[k].apply(assert[k], arguments);
  };
});

AssertDiff.deepStrictEqual = function deepStrictEqual() {
  try {
    assert.deepStrictEqual.apply(assert.deepStrictEqual, arguments);
  } catch (e) {
    throw new assert.AssertionError({
      message: addDiffToMessage(e.message, jdiff.diffString(e.expected, e.actual)),
      stackStartFunction: assert.AssertionError
    })
  }
};

AssertDiff.deepEqual = function deepEqual() {
  try {
    assert.deepEqual.apply(assert.deepEqual, arguments);
  } catch (e) {
    throw new assert.AssertionError({
      message: addDiffToMessage(e.message, jdiff.diffString(e.expected, e.actual)),
      stackStartFunction: assert.AssertionError
    })
  }
  if (AssertDiff.options.strict && jdiff.diff(arguments[0], arguments[1])) {
    throw new assert.AssertionError({
      message: addDiffToMessage(arguments[2], jdiff.diffString(arguments[0], arguments[1])),
      stackStartFunction: assert.AssertionError
    })
  }
};

function addDiffToMessage(message, diff) {
  var msg = message ? message : '';
  var resetCliColorAttributes = '\u001b[m';

  return msg + resetCliColorAttributes + '\n' + diff;
}

AssertDiff.deepEqualOrig = assert.deepEqual;

module.exports = AssertDiff;


text:
print("Project15: Blynk accelerometer from phone")

vw_cb = function(cmd)
    pin = tonumber(cmd[2])  -- ALL vpin "vw" messages arrive here. What vpin is this packet?
    if pin == 13 then   -- v13 = accel
        xx=tonumber(cmd[3])
        yy=tonumber(cmd[4])
        zz=tonumber(cmd[5])
        print("pitch", axl.pitch(yy,zz), "roll", axl.roll(xx,zz))
    end
    if pin == 14 then  -- v14 = light
        ll = cmd[3]
        print("light level", ll)
    end
end

dofile("{token}.lua")
dofile ( 'lib-BLYNK.lua' )
b=blynk.new (token, function(b) b:on("vw", vw_cb) end ):connect()

dofile("lib-ACCEL.lua") -- provides the pitch/roll maths

-- at phone, accelerometer vpin 13, 1 sec
-- also (incidentlally) a light sensor on V14, 1/sec


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2005 The Apache Software Foundation

    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.
-->

<!-- $Rev$ $Date$ -->
<project>
    <pomVersion>3</pomVersion>
    <groupId>geronimo</groupId>
    <id>geronimo-assembly-plugin</id>
    <name>Geronimo :: Maven Assembly Plugin</name>
    <description>A plugin used to assemble a distribution of Geronimo</description>
    <currentVersion>1.0.8</currentVersion>

    <dependencies>
        <dependency>
            <groupId>geronimo</groupId>
            <artifactId>geronimo-kernel</artifactId>
            <version>1.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>geronimo</groupId>
            <artifactId>geronimo-system</artifactId>
            <version>1.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>src/java</sourceDirectory>

        <resources>
            <resource>
                <directory></directory>
                <includes>
                    <include>plugin.jelly</include>
                    <include>plugin.properties</include>
                    <include>project.xml</include>
                    <include>NOTICE.txt</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>


text:
package com.simit.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.simit.database.Article;

import java.lang.reflect.Type;

/**
 * Created by liuchun on 2015/12/6.
 */
public class ParserUtils {
    private static final String TAG = "ParserUtils";

    /**
     * 解析Splash的图片
     * @param json
     * @return
     */
    public static String parseSplashImgUrl(String json){
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        SplashImgUrl jsonLoadUrl = gson.fromJson(json, SplashImgUrl.class);
        String loadUrl = jsonLoadUrl.getData();

        return loadUrl;
    }

    public static UpdateApkUrl parseUpdateApkUrl(String json){
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        return gson.fromJson(json, UpdateApkUrl.class);
    }

    /**
     *
     * @param json
     * @return
     */
    public static Article[] parseArticles(String json){
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Article.class, new ArticleDeserializer());
        builder.registerTypeAdapter(ArticleWrapper.class, new ArticleWrapperDeserializer());
        Gson gson = builder.create();

        ArticleWrapper jsonArticle = gson.fromJson(json, ArticleWrapper.class);
        Article[] articles = jsonArticle.getData();

        return articles;
    }

    /**
     * Article反序列化规则
     */
    public static class ArticleDeserializer implements JsonDeserializer<Article> {

        @Override
        public Article deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            final JsonObject jsonObject = json.getAsJsonObject();

            final Article article = new Article();

            String title = jsonObject.get("title").getAsString();
            String link = jsonObject.get("link").getAsString();
            String author = "";
            String pubDate = "";
            if(!title.equals("AD")){
                // not advertisement
                author = jsonObject.get("author").getAsString();
                pubDate = jsonObject.get("pubDate").getAsString();
            }
            String description = jsonObject.get("description").getAsString();
            description = description.trim();
            String imgurl = "";
            if(jsonObject.get("imgurl") != null){
                imgurl = jsonObject.get("imgurl").getAsString();
            }

            // update article information
            article.setTitle(title);
            article.setLink(link);
            article.setAuthor(author);
            article.setPubDate(pubDate);
            article.setDescription(description);
            article.setImgUrl(imgurl);

            return article;
        }
    }

    /**
     * ArticleWrapper反序列化规则
     */
    public static class ArticleWrapperDeserializer implements JsonDeserializer<ArticleWrapper> {

        @Override
        public ArticleWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            final JsonObject jsonObject = json.getAsJsonObject();

            final ArticleWrapper wrapper = new ArticleWrapper();

            String msg = jsonObject.get("msg").getAsString();
            int error = jsonObject.get("error").getAsInt();

            wrapper.setMsg(msg);
            wrapper.setError(error);
            if(msg.equals("no data") || error != 0){
                //返回了错误的article信息
                wrapper.setData(new Article[0]);
            }else {
                //正常的信息
                JsonElement jsonElement = jsonObject.get("data");
                Article[] data = context.deserialize(jsonElement, Article[].class);
                wrapper.setData(data);
            }

            return wrapper;
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/>
    </parent>
    <groupId>dev.nincodedo</groupId>
    <artifactId>ninbot</artifactId>
    <version>3.9.7</version>
    <name>Ninbot</name>
    <description>Discord bot for OCW Discord using JDA</description>
    <url>https://github.com/Nincodedo/Ninbot</url>
    <licenses>
        <license>
            <name>MIT License</name>
            <url>https://www.mit.edu/~amini/LICENSE.md</url>
        </license>
    </licenses>
    <developers>
        <developer>
            <id>nincodedo</id>
            <name>Nincodedo</name>
            <email>nincodedo@gmail.com</email>
        </developer>
    </developers>
    <scm>
        <connection>scm:git:https://github.com/Nincodedo/Ninbot.git</connection>
        <developerConnection>scm:git:ssh://github.com:Nincodedo/Ninbot.git</developerConnection>
        <url>https://github.com/Nincodedo/Ninbot</url>
    </scm>
    <properties>
        <JDA.version>5.0.0-alpha.22</JDA.version>
        <annotations.version>23.0.0</annotations.version>
        <archunit.version>1.0.0</archunit.version>
        <assertj-core.version>3.23.1</assertj-core.version>
        <commons-io.version>2.11.0</commons-io.version>
        <commons-lang.version>2.6</commons-lang.version>
        <commons-text.version>1.10.0</commons-text.version>
        <dice.version>2.2.1</dice.version>
        <discord-webhooks.version>0.8.2</discord-webhooks.version>
        <imgscalr-lib.version>4.2</imgscalr-lib.version>
        <jackson-databind.version>2.14.0-rc2</jackson-databind.version>
        <jacoco-maven-plugin.version>0.8.8</jacoco-maven-plugin.version>
        <jsr305.version>3.0.2</jsr305.version>
        <log4j.version>2.19.0</log4j.version>
        <lombok.version>1.18.24</lombok.version>
        <maven-failsafe-plugin.version>2.22.2</maven-failsafe-plugin.version>
        <maven-release-plugin.version>2.5.3</maven-release-plugin.version>
        <maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
        <pitest-maven.version>1.9.8</pitest-maven.version>
        <sap-conversational-ai-java-api.version>0.0.4</sap-conversational-ai-java-api.version>
        <sonar.coverage.jacoco.xmlReportPaths>target/site/jacoco/jacoco.xml,target/site/jacoco-it/jacoco.xml
        </sonar.coverage.jacoco.xmlReportPaths>
        <sortpom-maven-plugin.version>3.2.0</sortpom-maven-plugin.version>
        <spring-cloud-starter-openfeign.version>3.1.4</spring-cloud-starter-openfeign.version>
        <syllable-counter.version>4.1.0</syllable-counter.version>
        <testcontainers.version>1.17.5</testcontainers.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>club.minnced</groupId>
            <artifactId>discord-webhooks</artifactId>
            <version>${discord-webhooks.version}</version>
        </dependency>
        <dependency>
            <groupId>com.bernardomg.tabletop</groupId>
            <artifactId>dice</artifactId>
            <version>${dice.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-slf4j-impl</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.ibm.icu</groupId>
                    <artifactId>icu4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson-databind.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>${jsr305.version}</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>
        <dependency>
            <groupId>com.tngtech.archunit</groupId>
            <artifactId>archunit</artifactId>
            <version>${archunit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons-io.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>${commons-lang.version}</version>
        </dependency>
        <dependency>
            <groupId>eu.crydee</groupId>
            <artifactId>syllable-counter</artifactId>
            <version>${syllable-counter.version}</version>
        </dependency>
        <dependency>
            <groupId>net.dv8tion</groupId>
            <artifactId>JDA</artifactId>
            <version>${JDA.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>club.minnced</groupId>
                    <artifactId>opus-java</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>${commons-text.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>${assertj-core.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.imgscalr</groupId>
            <artifactId>imgscalr-lib</artifactId>
            <version>${imgscalr-lib.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>${annotations.version}</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>${spring-cloud-starter-openfeign.version}</version>
        </dependency>
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>${testcontainers.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>mysql</artifactId>
            <version>${testcontainers.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>testcontainers</artifactId>
            <version>${testcontainers.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>dv8tion</id>
            <name>m2-dv8tion</name>
            <url>https://m2.dv8tion.net/releases</url>
        </repository>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
        <repository>
            <id>sonatype</id>
            <name>sonatype-snapshots</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        </repository>
    </repositories>
    <build>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>com.github.ekryd.sortpom</groupId>
                    <artifactId>sortpom-maven-plugin</artifactId>
                    <version>${sortpom-maven-plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-release-plugin</artifactId>
                    <version>${maven-release-plugin.version}</version>
                    <configuration>
                        <tagNameFormat>@{project.version}</tagNameFormat>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>com.github.ekryd.sortpom</groupId>
                <artifactId>sortpom-maven-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <createBackupFile>false</createBackupFile>
                    <expandEmptyElements>false</expandEmptyElements>
                    <keepBlankLines>false</keepBlankLines>
                    <predefinedSortOrder>default_1_0_0</predefinedSortOrder>
                    <predefinedSortOrder>recommended_2008_06</predefinedSortOrder>
                    <sortDependencies>groupId,artifactId</sortDependencies>
                    <sortPlugins>groupId,artifactId</sortPlugins>
                    <sortProperties>true</sortProperties>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <compilerArgs>--enable-preview</compilerArgs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <excludes>
                        <exclude>**/*IT</exclude>
                    </excludes>
                    <argLine>@{argLine} --enable-preview</argLine>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>${jacoco-maven-plugin.version}</version>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>default-report</id>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <phase>prepare-package</phase>
                    </execution>
                    <execution>
                        <id>prepare-agent-it</id>
                        <goals>
                            <goal>prepare-agent-integration</goal>
                        </goals>
                        <configuration>
                            <destFile>${project.build.directory}/jacoco-it.exec</destFile>
                        </configuration>
                    </execution>
                    <execution>
                        <id>report-it</id>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <phase>post-integration-test</phase>
                        <configuration>
                            <dataFile>${project.build.directory}/jacoco-it.exec</dataFile>
                            <outputDirectory>${project.reporting.outputDirectory}/jacoco-it</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.pitest</groupId>
                <artifactId>pitest-maven</artifactId>
                <version>${pitest-maven.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>org.pitest</groupId>
                        <artifactId>pitest-junit5-plugin</artifactId>
                        <version>1.1.0</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>dev.nincodedo.ninbot.NinbotRunner</mainClass>
                    <layout>ZIP</layout>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <profiles>
        <profile>
            <id>git-commit</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>pl.project13.maven</groupId>
                        <artifactId>git-commit-id-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>integration</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <version>${maven-failsafe-plugin.version}</version>
                        <configuration>
                            <includes>
                                <include>**/*IT</include>
                            </includes>
                            <argLine>--enable-preview</argLine>
                        </configuration>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>integration-test</goal>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>${maven-surefire-plugin.version}</version>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>test</goal>
                                </goals>
                                <phase>integration-test</phase>
                                <configuration>
                                    <includes>
                                        <include>**/*IT</include>
                                    </includes>
                                    <argLine>@{argLine} --enable-preview</argLine>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
@interface CKBasicAuthUrlUtilitiesTests ()

@property (nonatomic) CKBasicAuthUrlUtilities *utilitiesHttpScheme;
@property (nonatomic) CKBasicAuthUrlUtilities *utilitiesHttpsScheme;
@property (nonatomic) id mockUrl;
@property (nonatomic) id mockString;
@property (nonatomic) id mockData;

@end

@implementation CKBasicAuthUrlUtilitiesTests

- (void)setUp
{
    [super setUp];

    self.mockUrl = [OCMockObject niceMockForClass:NSURL.class];
    self.mockString = [OCMockObject niceMockForClass:NSString.class];
    self.mockData = [OCMockObject niceMockForClass:NSData.class];

    self.utilitiesHttpScheme = CKBasicAuthUrlUtilities.new;
    self.utilitiesHttpScheme.schemeType = CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttp;

    self.utilitiesHttpsScheme = CKBasicAuthUrlUtilities.new;
}

#pragma mark - CKBasicAuthUrlUtilitiesDefaultSchemeType tests

- (void)testBasicAuthUrlUtilitiesDefaultSchemeTypes
{
    XCTAssertTrue(CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttps == 0);
    XCTAssertTrue(CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttp == 1);
}

- (void)testBasicAuthUrlUtilitiesDefaultSchemeHttpsOnInit
{
    XCTAssertTrue(CKBasicAuthUrlUtilities.new.schemeType == CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttps);
    XCTAssertTrue(self.utilitiesHttpsScheme.schemeType == CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttps);
    XCTAssertTrue(self.utilitiesHttpScheme.schemeType == CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttp);
}

- (void)testSchemeTranslation
{
    XCTAssertEqualObjects(self.utilitiesHttpsScheme.scheme, @"https");
    XCTAssertEqualObjects(self.utilitiesHttpScheme.scheme, @"http");
}

#pragma mark - NSURL encode tests

- (void)testUrlWithUtf8EncodingForString
{
    NSString *nonEncodedString = @"http://www.google.com/?q=whoami?";
    NSString *encodedString = @"http://www.google.com/?q=whoami%3F";

    NSURL *expectedUrl = [NSURL URLWithString:nonEncodedString];

    [[[self.mockString expect] andReturn:encodedString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[[self.mockUrl expect] andReturn:expectedUrl] URLWithString:encodedString];

    NSURL *actualUrl = [self.utilitiesHttpScheme urlWithUtf8EncodingForString:self.mockString];

    [self.mockString verify];
    [self.mockUrl verify];

    XCTAssertEqual(actualUrl, expectedUrl);
}

- (void)testUrlWithUtf8EncodingForStringReturnsNilIfInputStringIsNil
{
    NSURL *actualUrl = [self.utilitiesHttpScheme urlWithUtf8EncodingForString:nil];

    XCTAssertTrue(actualUrl == nil);
}

- (void)testUrlWithUtf8EncodingForStringWithoutScheme
{
    NSString *urlWithoutScheme = @"www.google.com";

    NSURL *expectedUrlForHttpScheme = [NSURL URLWithString:@"http://www.google.com"];
    NSURL *expectedUrlForHttpsScheme = [NSURL URLWithString:@"https://www.google.com"];

    NSURL *actualUrlForHttpScheme = [self.utilitiesHttpScheme urlWithUtf8EncodingForString:urlWithoutScheme];
    NSURL *actualUrlForHttpsScheme = [self.utilitiesHttpsScheme urlWithUtf8EncodingForString:urlWithoutScheme];

    XCTAssertEqualObjects(actualUrlForHttpScheme, expectedUrlForHttpScheme);
    XCTAssertEqualObjects(actualUrlForHttpsScheme, expectedUrlForHttpsScheme);
}

#pragma mark - NSURL Update User/Password Tests

- (void)testUrlWithUpdatedUsername
{
    [self verifyUrlWithUpdatedUsernameWithSchemeType:CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttp];
    [self verifyUrlWithUpdatedUsernameWithSchemeType:CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttps];
}

- (void)testUrlWithUpdatedPassword
{
    [self verifyUrlWithUpdatedPasswordWithSchemeType:CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttp];
    [self verifyUrlWithUpdatedPasswordWithSchemeType:CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttps];
}

- (void)testUrlWithUpdatedUsernameAndPassword
{
    [self verifyUrlWithUpdatedUsernameAndPasswordWithSchemeType:CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttp];
    [self verifyUrlWithUpdatedUsernameAndPasswordWithSchemeType:CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttps];
}

- (void)verifyUrlWithUpdatedUsernameWithSchemeType:(CKBasicAuthUrlUtilitiesDefaultSchemeType)schemeType
{
    CKBasicAuthUrlUtilities *utils = (schemeType == CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttps) ? self.utilitiesHttpsScheme : self.utilitiesHttpScheme;
    NSURL *expectedUrl = NSURL.new;

    [[[self.mockUrl expect] andReturn:expectedUrl] urlWithUpdatedUsername:self.mockString withScheme:utils.scheme];

    NSURL *actualUrl = [utils urlWithUpdatedUsername:self.mockString forUrl:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertEqual(actualUrl, expectedUrl);
}

- (void)verifyUrlWithUpdatedPasswordWithSchemeType:(CKBasicAuthUrlUtilitiesDefaultSchemeType)schemeType
{
    CKBasicAuthUrlUtilities *utils = (schemeType == CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttps) ? self.utilitiesHttpsScheme : self.utilitiesHttpScheme;
    NSURL *expectedUrl = NSURL.new;

    [[[self.mockUrl expect] andReturn:expectedUrl] urlWithUpdatedPassword:self.mockString withScheme:utils.scheme];

    NSURL *actualUrl = [utils urlWithUpdatedPassword:self.mockString forUrl:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertEqual(actualUrl, expectedUrl);
}

- (void)verifyUrlWithUpdatedUsernameAndPasswordWithSchemeType:(CKBasicAuthUrlUtilitiesDefaultSchemeType)schemeType
{
    id mockUsernameString = self.mockString;
    id mockPasswordString = [OCMockObject niceMockForClass:NSString.class];

    CKBasicAuthUrlUtilities *utils = (schemeType == CKBasicAuthUrlUtilitiesDefaultSchemeTypeHttps) ? self.utilitiesHttpsScheme : self.utilitiesHttpScheme;
    NSURL *expectedUrl = NSURL.new;

    [[[self.mockUrl expect] andReturn:expectedUrl] urlWithUpdatedUsername:mockUsernameString andPassword:mockPasswordString withScheme:utils.scheme];

    NSURL *actualUrl = [utils urlWithUpdatedUsername:mockUsernameString andPassword:mockPasswordString forUrl:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertEqual(actualUrl, expectedUrl);
}

- (void)testUrlWithUpdatedUsernameAndPasswordWithNilUrl
{
    NSURL *actual = [self.utilitiesHttpsScheme urlWithUpdatedUsername:@"user" andPassword:@"pass" forUrl:nil];

    XCTAssertTrue(actual == nil);
}

#pragma mark - NSURL Tests

- (void)testAbsoluteStringWithoutAuthenticationForUrlWithAuth
{
    NSURL *url = [NSURL URLWithString:@"http://user:pass@www.google.com"];
    NSString *expected = @"http://www.google.com";

    NSString *actual = [self.utilitiesHttpScheme absoluteStringWithoutAuthenticationForUrl:url];

    XCTAssertEqualObjects(expected, actual);
}

- (void)testAbsoluteStringWithoutAuthenticationForUrlWithoutAuth
{
    NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
    NSString *expected = @"http://www.google.com";

    NSString *actual = [self.utilitiesHttpScheme absoluteStringWithoutAuthenticationForUrl:url];

    XCTAssertEqualObjects(expected, actual);
}

- (void)testAbsoluteStringObfuscatedPasswordWithAuth
{
    NSURL *url = [NSURL URLWithString:@"http://user:pass@www.google.com"];
    NSString *expected = @"http://user:****@www.google.com";

    NSString *actual = [self.utilitiesHttpScheme absoluteStringObfuscatedPassword:url];

    XCTAssertEqualObjects(expected, actual);
}

- (void)testAbsoluteStringObfuscatedPasswordWithoutAuth
{
    NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
    NSString *expected = @"http://www.google.com";

    NSString *actual = [self.utilitiesHttpScheme absoluteStringObfuscatedPassword:url];

    XCTAssertEqualObjects(expected, actual);
}

- (void)testAbsoluteStringObfuscatedPasswordWithNilUrl
{
    NSString *actual = [self.utilitiesHttpScheme absoluteStringObfuscatedPassword:nil];

    XCTAssertTrue(actual == nil);
}

- (void)testUrlWithoutAuthenticationFromUrl
{
    NSURL *expectedUrl = NSURL.new;

    [[[self.mockUrl expect] andReturn:expectedUrl] urlWithoutAuthentication];

    NSURL *actualUrl = [self.utilitiesHttpsScheme urlWithoutAuthenticationFromUrl:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertEqual(actualUrl, expectedUrl);
}

- (void)testUrlWithoutAuthenticationFromUrlWithNilUrl
{
    NSURL *actualUrl = [self.utilitiesHttpsScheme urlWithoutAuthenticationFromUrl:nil];

    XCTAssertTrue(actualUrl == nil);
}

#pragma mark BOOL methods

- (void)testUrlHasSchemeReturnsTrue
{
    BOOL returnValue = YES;

    [[[self.mockUrl expect] andReturnValue:OCMOCK_VALUE(returnValue)] hasHttpOrHttpsScheme];

    BOOL result = [self.utilitiesHttpScheme urlHasHttpOrHttpsScheme:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertTrue(result);
}

- (void)testUrlHasSchemeReturnsFalse
{
    BOOL returnValue = NO;

    [[[self.mockUrl expect] andReturnValue:OCMOCK_VALUE(returnValue)] hasHttpOrHttpsScheme];

    BOOL result = [self.utilitiesHttpScheme urlHasHttpOrHttpsScheme:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertFalse(result);
}

- (void)testUrlHasSchemeReturnsFalseForNilUrl
{
    BOOL result = [self.utilitiesHttpScheme urlHasHttpOrHttpsScheme:nil];

    XCTAssertFalse(result);
}

- (void)testUrlHasAuthenticationReturnsTrue
{
    BOOL returnValue = YES;

    [[[self.mockUrl expect] andReturnValue:OCMOCK_VALUE(returnValue)] hasAuthentication];

    BOOL result = [self.utilitiesHttpScheme urlHasAuthentication:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertTrue(result);
}

- (void)testUrlHasAuthenticationReturnsFalse
{
    BOOL returnValue = NO;

    [[[self.mockUrl expect] andReturnValue:OCMOCK_VALUE(returnValue)] hasAuthentication];

    BOOL result = [self.utilitiesHttpScheme urlHasAuthentication:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertFalse(result);
}

- (void)testUrlHasAuthenticationReturnsFalseIfNil
{
    BOOL result = [self.utilitiesHttpScheme urlHasAuthentication:nil];

    XCTAssertFalse(result);
}

- (void)testAuthenticationStringWithEncodingForUrl
{
    NSString *expected = @"user:pass";

    [[[self.mockUrl expect] andReturn:expected] basicAuthenticationStringWithEncoding];

    NSString *actual = [self.utilitiesHttpScheme basicAuthenticationStringWithEncodingForUrl:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertEqualObjects(actual, expected);
}

- (void)testAuthenticationStringWithoutEncodingForUrl
{
    NSString *expected = @"user:pass";

    [[[self.mockUrl expect] andReturn:expected] basicAuthenticationStringWithoutEncoding];

    NSString *actual = [self.utilitiesHttpScheme basicAuthenticationStringWithoutEncodingForUrl:self.mockUrl];

    [self.mockUrl verify];

    XCTAssertEqualObjects(actual, expected);
}

- (void)testAuthenticationStringWithoutEncodingForNilUrl
{
    NSString *actual = [self.utilitiesHttpScheme basicAuthenticationStringWithoutEncodingForUrl:nil];

    XCTAssertTrue(actual == nil);
}

- (void)testUrlSafeString
{
    NSString *expectedString = @"ABC";
    [[[self.mockString expect] andReturn:expectedString] urlSafeString];

    NSString *actualString = [self.utilitiesHttpScheme urlSafeStringFromString:self.mockString];

    [self.mockString verify];

    XCTAssertEqualObjects(actualString, expectedString);
}

- (void)testUrlSafeStringReturnsNilWithNilArgument
{
    [[self.mockString reject] urlSafeString];

    NSString *returnedString = [self.utilitiesHttpScheme urlSafeStringFromString:nil];

    [self.mockString verify];

    XCTAssertNil(returnedString);
}

- (void)testDoesStringContainIllegalUrlCharactersReturnsTrue
{
    BOOL expectedReturnBool = YES;
    [[[self.mockString expect] andReturnValue:OCMOCK_VALUE(expectedReturnBool)] doesStringContainIllegalUrlCharacters];

    BOOL conntainsIllegalCharacters = [self.utilitiesHttpScheme doesStringContainIllegalUrlCharacters:self.mockString];

    [self.mockString verify];

    XCTAssertTrue(conntainsIllegalCharacters);
}

- (void)testDoesStringContainIllegalUrlCharactersReturnsFalse
{
    BOOL expectedReturnBool = NO;
    [[[self.mockString expect] andReturnValue:OCMOCK_VALUE(expectedReturnBool)] doesStringContainIllegalUrlCharacters];

    BOOL conntainsIllegalCharacters = [self.utilitiesHttpScheme doesStringContainIllegalUrlCharacters:self.mockString];

    [self.mockString verify];

    XCTAssertFalse(conntainsIllegalCharacters);
}

- (void)testDoesStringContainIllegalUrlCharactersWithNilArgument
{
    [[self.mockString reject] doesStringContainIllegalUrlCharacters];

    BOOL conntainsIllegalCharacters = [self.utilitiesHttpScheme doesStringContainIllegalUrlCharacters:nil];

    [self.mockString verify];

    XCTAssertFalse(conntainsIllegalCharacters);
}

#pragma mark - NSURLRequest

- (void)testUrlRequestReturnsInitializedRequesstWithoutAuthHeaderIfUrlDoesNotProvideUsernameOrPassword
{
    NSURL *expected = [NSURL URLWithString:@"http://www.yahoo.com"];

    NSMutableURLRequest *actual = [self.utilitiesHttpScheme urlRequestWithPreemptiveBasicAuthenticationWithUrl:expected];

    id value = [actual.allHTTPHeaderFields objectForKey:@"Authorization"];

    XCTAssertTrue((value == nil));
    XCTAssertEqualObjects(actual.URL, expected);
}

- (void)testUrlRequestReturnsNilRequesstWithoutNilUrl
{
    NSMutableURLRequest *actual = [self.utilitiesHttpScheme urlRequestWithPreemptiveBasicAuthenticationWithUrl:nil];

    XCTAssertTrue(actual == nil);
}

#pragma mark - NSData-Base64 methods

- (void)testDataFromBase64String
{
    NSString *inputString = @"TEST";
    NSData *expected = [NSData new];

    id partialMockUtils = [OCMockObject partialMockForObject:self.utilitiesHttpScheme];
    [[[partialMockUtils expect] andReturn:expected] dataFromBase64String:inputString];

    NSData *actual = [self.utilitiesHttpScheme dataFromBase64String:inputString];

    [partialMockUtils verify];

    XCTAssertEqualObjects(actual, expected);
}

- (void)testDataFromBase64StringWithNil
{
    NSData *actual = [self.utilitiesHttpScheme dataFromBase64String:nil];

    XCTAssertTrue(actual == nil);
}

- (void)testBase64EncodedStringForNilData
{
    NSString *actual = [self.utilitiesHttpScheme base64EncodedStringForData:nil];

    XCTAssertTrue(actual == nil);
}

@end


text:
import { Route } from '../router';
import { teas } from '../teaDetails/data';

export const Effect = (update) => (state) => {
  if (
    state.route.page === Route.Tea ||
    state.route.page === Route.TeaDetails
  ) {
    setTimeout(() => {
      update({ teas });
    }, 1000);
  }
};


text:
namespace nodejs_db {
class EventEmitter : public node::ObjectWrap {
    public:
        static void Init();

    protected:
#if !NODE_VERSION_AT_LEAST(0, 5, 0)
        static v8::Persistent<v8::String> syEmit;
#endif

        EventEmitter();
        bool Emit(const char* event, int argc,  v8::Handle<v8::Value> argv[]);
};
}

#endif  // __EVENTS_H_INCLUDED__


text:
from __future__ import unicode_literals
from django.db.models import Max
from django.utils.translation import ugettext_lazy as _
from cms.models import Page
from cms.admin.placeholderadmin import PlaceholderAdminMixin, FrontendEditableAdminMixin
from parler.admin import TranslatableAdmin
from polymorphic.admin import PolymorphicChildModelAdmin
from myshop.models.shopmodels import Product
from myshop.admin.image import ProductImageInline

class CommodityAdmin(TranslatableAdmin, FrontendEditableAdminMixin, PlaceholderAdminMixin, PolymorphicChildModelAdmin):
    base_model = Product
    fieldsets = (
        (None, {
            'fields': ('identifier', ('unit_price', 'cost', 'active',),)
        }),
        (_("Translatable Fields"), {
            'fields': ('name', 'slug', 'description',)
        }),
        (_("Properties"), {
            'fields': ('cms_pages',),
        })
    )
    filter_horizontal = ('cms_pages',)
    inlines = (ProductImageInline,)

    def get_prepopulated_fields(self, request, obj=None):
        return {'slug': ('name',)}

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == 'cms_pages':
            # restrict many-to-many field for cms_pages to TextilePanelsApp only
            limit_choices_to = {'publisher_is_draft': False, 'application_urls': 'CommodityListApp'}
            kwargs['queryset'] = Page.objects.filter(**limit_choices_to)
        return super(CommodityAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

    def save_model(self, request, obj, form, change):
        if not change:
            # since SortableAdminMixin is missing on this class, ordering has to be computed by hand
            max_order = self.base_model.objects.aggregate(max_order=Max('order'))['max_order']
            obj.order = max_order + 1 if max_order else 1
        obj.legacy_fixed = True
        super(CommodityAdmin, self).save_model(request, obj, form, change)


text:
package org.springframework.boot.jta.narayana;

import javax.transaction.TransactionManager;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;

/**
 * {@link BeanFactoryPostProcessor} to automatically setup correct beans ordering.
 *
 * @author Gytis Trikleris
 * @since 1.4.0
 */
public class NarayanaBeanFactoryPostProcessor
		implements BeanFactoryPostProcessor, Ordered {

	private static final String[] NO_BEANS = {};

	private static final int ORDER = Ordered.LOWEST_PRECEDENCE;

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
			throws BeansException {
		String[] transactionManagers = beanFactory
				.getBeanNamesForType(TransactionManager.class, true, false);
		String[] recoveryManagers = beanFactory
				.getBeanNamesForType(NarayanaRecoveryManagerBean.class, true, false);
		addBeanDependencies(beanFactory, transactionManagers, "javax.sql.DataSource");
		addBeanDependencies(beanFactory, recoveryManagers, "javax.sql.DataSource");
		addBeanDependencies(beanFactory, transactionManagers,
				"javax.jms.ConnectionFactory");
		addBeanDependencies(beanFactory, recoveryManagers, "javax.jms.ConnectionFactory");
	}

	private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory,
			String[] beanNames, String dependencyType) {
		for (String beanName : beanNames) {
			addBeanDependencies(beanFactory, beanName, dependencyType);
		}
	}

	private void addBeanDependencies(ConfigurableListableBeanFactory beanFactory,
			String beanName, String dependencyType) {
		for (String dependentBeanName : getBeanNamesForType(beanFactory,
				dependencyType)) {
			beanFactory.registerDependentBean(beanName, dependentBeanName);
		}
	}

	private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory,
			String type) {
		try {
			return beanFactory.getBeanNamesForType(Class.forName(type), true, false);
		}
		catch (ClassNotFoundException | NoClassDefFoundError ex) {
			// Ignore
		}
		return NO_BEANS;
	}

	@Override
	public int getOrder() {
		return ORDER;
	}

}


text:
package jetbrains.buildServer.nuget.agent.commands.impl;

import jetbrains.buildServer.nuget.agent.parameters.PackageSource;
import jetbrains.buildServer.util.FileUtil;
import jetbrains.buildServer.util.XmlUtil;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.util.Collection;

/**
 * Created 04.01.13 19:33
 *
 * @author Eugene Petrenko (eugene.petrenko@jetbrains.com)
 */
public class NuGetSourcesWriter {
  public void writeNuGetSources(@NotNull final File file,
                                @NotNull final Collection<PackageSource> sources) throws IOException {
    final Element root = new Element("sources");
    for (PackageSource source : sources) {
      final Element sourceElement = new Element("source");
      sourceElement.setAttribute("source", source.getSource());

      final String username = source.getUsername();
      if (username != null) sourceElement.setAttribute("username", username);

      final String password = source.getPassword();
      if (password != null) sourceElement.setAttribute("password", password);

      root.addContent((Content)sourceElement);
    }

    final OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
    try {
      XmlUtil.saveDocument(new Document(root), os);
    } finally {
      FileUtil.close(os);
    }

  }
}