text:
ace.define("ace/mode/fortran_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var FortranHighlightRules = function() {

    var keywords = (
        "call|case|contains|continue|cycle|do|else|elseif|end|enddo|endif|function|"+
        "if|implicit|in|include|inout|intent|module|none|only|out|print|program|return|"+
        "select|status|stop|subroutine|" +
        "return|then|use|while|write|"+
        "CALL|CASE|CONTAINS|CONTINUE|CYCLE|DO|ELSE|ELSEIF|END|ENDDO|ENDIF|FUNCTION|"+
        "IF|IMPLICIT|IN|INCLUDE|INOUT|INTENT|MODULE|NONE|ONLY|OUT|PRINT|PROGRAM|RETURN|"+
        "SELECT|STATUS|STOP|SUBROUTINE|" +
        "RETURN|THEN|USE|WHILE|WRITE"
    );

    var keywordOperators = (
        "and|or|not|eq|ne|gt|ge|lt|le|" +
        "AND|OR|NOT|EQ|NE|GT|GE|LT|LE"
    );

    var builtinConstants = (
        "true|false|TRUE|FALSE"
    );

    var builtinFunctions = (
        "abs|achar|acos|acosh|adjustl|adjustr|aimag|aint|all|allocate|"+
        "anint|any|asin|asinh|associated|atan|atan2|atanh|"+
        "bessel_j0|bessel_j1|bessel_jn|bessel_y0|bessel_y1|bessel_yn|"+
        "bge|bgt|bit_size|ble|blt|btest|ceiling|char|cmplx|conjg|cos|cosh|"+
        "count|cpu_time|cshift|date_and_time|dble|deallocate|digits|dim|dot_product|dprod|"+
        "dshiftl|dshiftr|dsqrt|eoshift|epsilon|erf|erfc|erfc_scaled|exp|float|floor|"+
        "format|fraction|gamma|input|len|lge|lgt|lle|llt|log|log10|maskl|maskr|matmul|max|maxloc|maxval|"+
        "merge|min|minloc|minval|mod|modulo|nint|not|norm2|null|nullify|pack|parity|popcnt|poppar|"+
        "precision|present|product|radix|random_number|random_seed|range|repeat|reshape|round|"+
        "rrspacing|same_type_as|scale|scan|selected_char_kind|selected_int_kind|selected_real_kind|"+
        "set_exponent|shape|shifta|shiftl|shiftr|sign|sin|sinh|size|sngl|spacing|spread|"+
        "sqrt|sum|system_clock|tan|tanh|tiny|trailz|transfer|transpose|trim|ubound|unpack|verify|" +
        "ABS|ACHAR|ACOS|ACOSH|ADJUSTL|ADJUSTR|AIMAG|AINT|ALL|ALLOCATE|"+
        "ANINT|ANY|ASIN|ASINH|ASSOCIATED|ATAN|ATAN2|ATANH|"+
        "BESSEL_J0|BESSEL_J1|BESSEL_JN|BESSEL_Y0|BESSEL_Y1|BESSEL_YN|"+
        "BGE|BGT|BIT_SIZE|BLE|BLT|BTEST|CEILING|CHAR|CMPLX|CONJG|COS|COSH|"+
        "COUNT|CPU_TIME|CSHIFT|DATE_AND_TIME|DBLE|DEALLOCATE|DIGITS|DIM|DOT_PRODUCT|DPROD|"+
        "DSHIFTL|DSHIFTR|DSQRT|EOSHIFT|EPSILON|ERF|ERFC|ERFC_SCALED|EXP|FLOAT|FLOOR|"+
        "FORMAT|FRACTION|GAMMA|INPUT|LEN|LGE|LGT|LLE|LLT|LOG|LOG10|MASKL|MASKR|MATMUL|MAX|MAXLOC|MAXVAL|"+
        "MERGE|MIN|MINLOC|MINVAL|MOD|MODULO|NINT|NOT|NORM2|NULL|NULLIFY|PACK|PARITY|POPCNT|POPPAR|"+
        "PRECISION|PRESENT|PRODUCT|RADIX|RANDOM_NUMBER|RANDOM_SEED|RANGE|REPEAT|RESHAPE|ROUND|"+
        "RRSPACING|SAME_TYPE_AS|SCALE|SCAN|SELECTED_CHAR_KIND|SELECTED_INT_KIND|SELECTED_REAL_KIND|"+
        "SET_EXPONENT|SHAPE|SHIFTA|SHIFTL|SHIFTR|SIGN|SIN|SINH|SIZE|SNGL|SPACING|SPREAD|"+
        "SQRT|SUM|SYSTEM_CLOCK|TAN|TANH|TINY|TRAILZ|TRANSFER|TRANSPOSE|TRIM|UBOUND|UNPACK|VERIFY"
    );

    var storageType = (
        "logical|character|integer|real|type|" +
        "LOGICAL|CHARACTER|INTEGER|REAL|TYPE"
    );

    var storageModifiers = (
        "allocatable|dimension|intent|parameter|pointer|target|private|public|" +
        "ALLOCATABLE|DIMENSION|INTENT|PARAMETER|POINTER|TARGET|PRIVATE|PUBLIC"
    );

    var keywordMapper = this.createKeywordMapper({
        "invalid.deprecated": "debugger",
        "support.function": builtinFunctions,
        "constant.language": builtinConstants,
        "keyword": keywords,
        "keyword.operator": keywordOperators,
        "storage.type": storageType,
        "storage.modifier" : storageModifiers
    }, "identifier");

    var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?";

    var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))";
    var octInteger = "(?:0[oO]?[0-7]+)";
    var hexInteger = "(?:0[xX][\\dA-Fa-f]+)";
    var binInteger = "(?:0[bB][01]+)";
    var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")";

    var exponent = "(?:[eE][+-]?\\d+)";
    var fraction = "(?:\\.\\d+)";
    var intPart = "(?:\\d+)";
    var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
    var exponentFloat = "(?:(?:" + pointFloat + "|" +  intPart + ")" + exponent + ")";
    var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";

    var stringEscape =  "\\\\(x[0-9A-Fa-f]{2}|[0-7]{3}|[\\\\abfnrtv'\"]|U[0-9A-Fa-f]{8}|u[0-9A-Fa-f]{4})";

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "!.*$"
        }, {
            token : "string",           // multi line """ string start
            regex : strPre + '"{3}',
            next : "qqstring3"
        }, {
            token : "string",           // " string
            regex : strPre + '"(?=.)',
            next : "qqstring"
        }, {
            token : "string",           // multi line ''' string start
            regex : strPre + "'{3}",
            next : "qstring3"
        }, {
            token : "string",           // ' string
            regex : strPre + "'(?=.)",
            next : "qstring"
        }, {
            token : "constant.numeric", // imaginary
            regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b"
        }, {
            token : "constant.numeric", // float
            regex : floatNumber
        }, {
            token : "constant.numeric", // long integer
            regex : integer + "[lL]\\b"
        }, {
            token : "constant.numeric", // integer
            regex : integer + "\\b"
        }, {
            token : "keyword", // pre-compiler directives
            regex : "#\\s*(?:include|import|define|undef|INCLUDE|IMPORT|DEFINE|UNDEF)\\b"
        }, {
            token : "keyword", // special case pre-compiler directive
            regex : "#\\s*(?:endif|ifdef|else|elseif|ifndef|ENDIF|IFDEF|ELSE|ELSEIF|IFNDEF)\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|="
        }, {
            token : "paren.lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\]\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ],
        "qqstring3" : [ {
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string", // multi line """ string end
            regex : '"{3}',
            next : "start"
        }, {
            defaultToken : "string"
        } ],
        "qstring3" : [ {
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string", // multi line """ string end
            regex : '"{3}',
            next : "start"
        }, {
            defaultToken : "string"
        } ],
        "qqstring" : [{
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",
            regex : "\\\\$",
            next  : "qqstring"
        }, {
            token : "string",
            regex : '"|$',
            next  : "start"
        }, {
            defaultToken: "string"
        }],
        "qstring" : [{
            token : "constant.language.escape",
            regex : stringEscape
        }, {
            token : "string",
            regex : "\\\\$",
            next  : "qstring"
        }, {
            token : "string",
            regex : "'|$",
            next  : "start"
        }, {
            defaultToken: "string"
        }]
    };
};

oop.inherits(FortranHighlightRules, TextHighlightRules);

exports.FortranHighlightRules = FortranHighlightRules;
});

ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function(commentRegex) {
    if (commentRegex) {
        this.foldingStartMarker = new RegExp(
            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
        );
        this.foldingStopMarker = new RegExp(
            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
        );
    }
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.foldingStartMarker = /([\{\[\(])[^\}\]\)]*$|^\s*(\/\*)/;
    this.foldingStopMarker = /^[^\[\{\(]*([\}\]\)])|^[\s\*]*(\*\/)/;
    this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
    this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
    this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
    this._getFoldWidgetBase = this.getFoldWidget;
    this.getFoldWidget = function(session, foldStyle, row) {
        var line = session.getLine(row);

        if (this.singleLineBlockCommentRe.test(line)) {
            if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
                return "";
        }

        var fw = this._getFoldWidgetBase(session, foldStyle, row);

        if (!fw && this.startRegionRe.test(line))
            return "start"; // lineCommentRegionStart

        return fw;
    };

    this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
        var line = session.getLine(row);

        if (this.startRegionRe.test(line))
            return this.getCommentRegionBlock(session, line, row);

        var match = line.match(this.foldingStartMarker);
        if (match) {
            var i = match.index;

            if (match[1])
                return this.openingBracketBlock(session, match[1], row, i);

            var range = session.getCommentFoldRange(row, i + match[0].length, 1);

            if (range && !range.isMultiLine()) {
                if (forceMultiline) {
                    range = this.getSectionRange(session, row);
                } else if (foldStyle != "all")
                    range = null;
            }

            return range;
        }

        if (foldStyle === "markbegin")
            return;

        var match = line.match(this.foldingStopMarker);
        if (match) {
            var i = match.index + match[0].length;

            if (match[1])
                return this.closingBracketBlock(session, match[1], row, i);

            return session.getCommentFoldRange(row, i, -1);
        }
    };

    this.getSectionRange = function(session, row) {
        var line = session.getLine(row);
        var startIndent = line.search(/\S/);
        var startRow = row;
        var startColumn = line.length;
        row = row + 1;
        var endRow = row;
        var maxRow = session.getLength();
        while (++row < maxRow) {
            line = session.getLine(row);
            var indent = line.search(/\S/);
            if (indent === -1)
                continue;
            if  (startIndent > indent)
                break;
            var subRange = this.getFoldWidgetRange(session, "all", row);

            if (subRange) {
                if (subRange.start.row <= startRow) {
                    break;
                } else if (subRange.isMultiLine()) {
                    row = subRange.end.row;
                } else if (startIndent == indent) {
                    break;
                }
            }
            endRow = row;
        }

        return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
    };
    this.getCommentRegionBlock = function(session, line, row) {
        var startColumn = line.search(/\s*$/);
        var maxRow = session.getLength();
        var startRow = row;

        var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
        var depth = 1;
        while (++row < maxRow) {
            line = session.getLine(row);
            var m = re.exec(line);
            if (!m) continue;
            if (m[1]) depth--;
            else depth++;

            if (!depth) break;
        }

        var endRow = row;
        if (endRow > startRow) {
            return new Range(startRow, startColumn, endRow, line.length);
        }
    };

}).call(FoldMode.prototype);

});

ace.define("ace/mode/fortran",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/fortran_highlight_rules","ace/mode/folding/cstyle","ace/range"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var FortranHighlightRules = require("./fortran_highlight_rules").FortranHighlightRules;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Range = require("../range").Range;

var Mode = function() {
    this.HighlightRules = FortranHighlightRules;
    this.foldingRules = new CStyleFoldMode();
    this.$behaviour = this.$defaultBehaviour;
};
oop.inherits(Mode, TextMode);

(function() {

    this.lineCommentStart = "!";

    this.getNextLineIndent = function(state, line, tab) {
        var indent = this.$getIndent(line);

        var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
        var tokens = tokenizedLine.tokens;

        if (tokens.length && tokens[tokens.length-1].type == "comment") {
            return indent;
        }

        if (state == "start") {
            var match = line.match(/^.*[\{\(\[:]\s*$/);
            if (match) {
                indent += tab;
            }
        }

        return indent;
    };

    var outdents = {
        "return": 1,
        "break": 1,
        "continue": 1,
        "RETURN": 1,
        "BREAK": 1,
        "CONTINUE": 1
    };

    this.checkOutdent = function(state, line, input) {
        if (input !== "\r\n" && input !== "\r" && input !== "\n")
            return false;

        var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens;

        if (!tokens)
            return false;
        do {
            var last = tokens.pop();
        } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/))));

        if (!last)
            return false;

        return (last.type == "keyword" && outdents[last.value]);
    };

    this.autoOutdent = function(state, doc, row) {

        row += 1;
        var indent = this.$getIndent(doc.getLine(row));
        var tab = doc.getTabString();
        if (indent.slice(-tab.length) == tab)
            doc.remove(new Range(row, indent.length-tab.length, row, indent.length));
    };

    this.$id = "ace/mode/fortran";
}).call(Mode.prototype);

exports.Mode = Mode;
});                (function() {
                    ace.require(["ace/mode/fortran"], function(m) {
                        if (typeof module == "object" && typeof exports == "object" && module) {
                            module.exports = m;
                        }
                    });
                })();


text:
//
// Nexus Core - a framework for developing distributed applications
// http://github.com/threerings/nexus/blob/master/LICENSE

package com.threerings.nexus.distrib;

import react.RFuture;
import react.RPromise;

import com.threerings.nexus.io.Streamable;

/**
 * An attribute that contains a Nexus service reference.
 */
public abstract class DService<T extends NexusService> implements DAttribute
{
    /** Used to create service attributes. */
    public interface Factory<T extends NexusService>
    {
        /** Creates a service attribute with the supplied owner. */
        DService<T> createService (NexusObject owner);
    }

    /** An implementation detail used by service dispatchers. */
    public static abstract class Dispatcher<T extends NexusService> extends DService<T> {
        /** Dispatches a service call that came in over the network. */
        public RFuture<?> dispatchCall (short methodId, Object[] args) {
            throw new IllegalArgumentException("Unknown service method [id=" + methodId +
                                               ", obj=" + _owner.getClass().getName() +
                                               ", attrIdx=" + _index + "]");
        }

        protected Dispatcher (NexusObject owner) {
            super(owner);
        }

        /** Used to concisely, and without warning, cast arguments of generic type. */
        @SuppressWarnings("unchecked")
        protected final <C> C cast (Object obj) {
            return (C)obj;
        }
    }

    /** Returns the service encapsulated by this attribute. */
    public abstract T get ();

    /** Returns the class for the service encapsulated by this attribute. */
    public abstract Class<T> getServiceClass ();

    @Override public void readContents (Streamable.Input in) {
        // NOOP
    }

    @Override public void writeContents (Streamable.Output out) {
        // NOOP
    }

    protected DService (NexusObject owner) {
        _owner = owner;
        _index = owner.registerAttr(this);
    }

    /** Used by marshallers to dispatch calls over the network. */
    protected <R> RFuture<R> postCall (short methodId, Object... args) {
        RPromise<R> result = RPromise.create();
        _owner.postCall(_index, methodId, args, result);
        return result;
    }

    /** Used by marshallers to dispatch calls over the network. */
    protected void postVoidCall (short methodId, Object... args) {
        _owner.postCall(_index, methodId, args, null);
    }

    /** The object that owns this attribute. */
    protected final NexusObject _owner;

    /** The index of this attribute in its containing object. */
    protected final short _index;
}

redpajama_set_name: RedPajamaGithub


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Google Chrome EULA</title>
<link rel="stylesheet" type="text/css" href="res://setup.exe/IDR_EULA_CSS.CSS" />

Google Chrome

        Lướt web bằng Google Chrome
 Sử dụng internet nhanh hơn, an toàn hơn và dễ dàng hơn với Google Chrome, trình duyệt web được cài đặt trên máy PC của bạn

  Chấp nhận Điều khoản Dịch vụ của Google Chrome để bắt đầu sử dụng Google Chrome:

  <form method="post" action="" onsubmit="checkAccept(this); return false;">

          <input type="checkbox" name="accept" id="accept" />

          Tuỳ chọn: Giúp cải thiện Google Chrome tốt hơn bằng các tự động gửi cho Google thống kê sử dụng và báo cáo sự cố. Tìm hiểu thêm

      <input type="submit" name="submit" value="Chấp nhận và Chạy"  /> <input onClick="window.returnValue = 2; window.close();" type="button" name="cancel" value="Huỷ"  />

  </form>


text:
from __future__ import unicode_literals
from six.moves import range
from six import int2byte
import unittest, ticket

TICKET_VALUES = (
        b'\x01' * ticket.FULL_LEN,
        b'\xFF' * ticket.FULL_LEN,
        b''.join(int2byte(i) for i in range(ticket.FULL_LEN)),
        )

class TestTicket(unittest.TestCase):
    def setUp(self):
        self.vm = ticket.VendingMachine(b"TestingSecret23")

    def test_encode_decode(self):
        for ticket_value in TICKET_VALUES:
            encoded = ticket.encode(ticket_value)
            decoded = ticket.decode(encoded)
            self.assertEquals(ticket_value, decoded)

    def test_generate_verify(self):
        self.vm.verify(self.vm.generate())

if __name__ == '__main__':
    unittest.main()


text:
package org.apache.olingo.fit.proxy.staticservice.microsoft.test.odata.services.odatawcfservice.types;

// CHECKSTYLE:OFF (Maven checkstyle)

public interface LabourUnionCollectionComposableInvoker
    extends
    org.apache.olingo.ext.proxy.api.StructuredCollectionComposableInvoker<LabourUnionCollection, LabourUnionCollection.Operations> {

  @Override
  LabourUnionCollectionComposableInvoker select(String... select);

  @Override
  LabourUnionCollectionComposableInvoker expand(String... expand);
}


text:
var Users = require('./../models/users');

exports.authenticate = function(req, res, next) {
    if(!req.session.uid)
        res.send("You Must Login!");
    else next();
};

exports.login = function (req, res) {
    var client = req.app.get('dbm').pg,
        data = {
            username: req.body.username,
            passwd: req.body.passwd
        };

    if (!req.body.hasOwnProperty(Users.getColumns.username) ||
        !req.body.hasOwnProperty(Users.getColumns.passwd)) {
        res.statusCode = 400;
        res.send('Error 400: Post syntax incorrect.'); // TODO Implement proper error page
        return;
    }

    Users.getUser(client, data, function(user) {
        req.session.uid = user.id;
        req.session.username = user.username;
        req.session.loggedIn = true;
        res.redirect('/');
    });
};

exports.logout = function (req, res) {
    req.session.destroy( function() {
        // do anything before redirecting...
        res.redirect('/');
    });
}

exports.register = function(req, res) {
    var client = req.app.get('dbm').pg,
        data = {
            username: req.body.username,
            passwd: req.body.passwd
        };

    if (!req.body.hasOwnProperty(Users.getColumns.username) ||
        !req.body.hasOwnProperty(Users.getColumns.passwd)) {
        res.statusCode = 400;
        res.send('Error 400: Post syntax incorrect.'); // TODO Implement proper error page
        return;
    }

    // TODO shouldn't have to call getUser, addNewUser should do the checking
    Users.getUser(client, data, function(user) {
        if (!user.isNullOrUndefined()) {
            res.statusCode = 400;
            res.send('Error 400: Username taken.'); // TODO Check for correct status codes
            return;
        }

    })
};


text:
SVGynths
========

SVG interactive synth icon(s)

Right now, it's only one icon but I plan on adding more.


text:
Татьяна Андреева

Руководитель производства

                    Ходячая энциклопедия гайдлайнов мобильных интерфейсов.

                    Относится к типу дизайнеров, которые с первой попытки делают так, что результат нравится клиенту.

                    Приверженнец простых, но эффективных решений, за что взыскал любовь от программистов.

                    Автор видеокурса «Дизайн мобильных приложений».

Интервью

Публичные выступления

Статьи в блоге


text:
package org.perfcake.pc4idea.api.editor.openapi.ui;

import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.ValidationInfo;
import org.jetbrains.annotations.Nullable;
import org.perfcake.pc4idea.api.editor.editor.component.AbstractEditor;

import javax.swing.*;

/**
 * Created with IntelliJ IDEA.
 * User: Stanislav Kaleta
 * Date: 3.11.2014                     TODO documentation
 */
public class EditorDialog extends DialogWrapper {
    private AbstractEditor centerPanel;

    public EditorDialog(AbstractEditor centerPanel) {
        super(false);
        setTitle(centerPanel.getTitle());
        this.centerPanel = centerPanel;
        this.setResizable(true);
        init();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        return centerPanel;
    }

    @Override
    protected ValidationInfo doValidate(){
        return centerPanel.areInsertedValuesValid();
    }

}


text:
/*	$NetBSD: crypto.c,v 1.1.1.1 2011/04/13 18:14:47 elric Exp $	*/

/*
 * Copyright (c) 2010 Kungliga Tekniska Högskolan
 * (Royal Institute of Technology, Stockholm, Sweden).
 * All rights reserved.
 *
 * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "netlogon.h"

static uint8_t zeros[4];

static void
_netlogon_encode_sequence_number(uint64_t SequenceNumber, uint8_t *p,
                                 int initiatorFlag)
{
    uint32_t LowPart, HighPart;

    LowPart  = (SequenceNumber >> 0 ) & 0xFFFFFFFF;
    HighPart = (SequenceNumber >> 32) & 0xFFFFFFFF;

    _gss_mg_encode_be_uint32(LowPart,  &p[0]);
    _gss_mg_encode_be_uint32(HighPart, &p[4]);

    if (initiatorFlag)
        p[4] |= 0x80;
}

static int
_netlogon_decode_sequence_number(void *ptr, uint64_t *n,
                                 int initiatorFlag)
{
    uint8_t *p = ptr;
    uint32_t LowPart, HighPart;
    int gotInitiatorFlag;

    gotInitiatorFlag = (p[4] & 0x80) != 0;
    if (gotInitiatorFlag != initiatorFlag)
        return -1;

    p[4] &= 0x7F; /* clear initiator bit */

    _gss_mg_decode_be_uint32(&p[0], &LowPart);
    _gss_mg_decode_be_uint32(&p[4], &HighPart);

    *n = (LowPart << 0) | ((uint64_t)HighPart << 32);

    return 0;
}

static inline size_t
_netlogon_checksum_length(NL_AUTH_SIGNATURE *sig)
{
#if 0
    return (sig->SignatureAlgorithm == NL_SIGN_ALG_SHA256) ? 32 : 8;
#else
    /* Owing to a bug in Windows it always uses the old value */
    return 8;
#endif
}

static inline size_t
_netlogon_signature_length(uint16_t alg, int conf_req_flag)
{
    return NL_AUTH_SIGNATURE_COMMON_LENGTH +
        (alg == NL_SIGN_ALG_SHA256 ? 32 : 8) +
        (conf_req_flag ? 8 : 0);
}

static inline uint8_t *
_netlogon_confounder(NL_AUTH_SIGNATURE *sig)
{
    size_t cksumlen = _netlogon_checksum_length(sig);

    return &sig->Checksum[cksumlen];
}

static int
_netlogon_encode_NL_AUTH_SIGNATURE(NL_AUTH_SIGNATURE *sig,
                                   uint8_t *p, size_t len)
{
    *p++ = (sig->SignatureAlgorithm >> 0) & 0xFF;
    *p++ = (sig->SignatureAlgorithm >> 8) & 0xFF;
    *p++ = (sig->SealAlgorithm      >> 0) & 0xFF;
    *p++ = (sig->SealAlgorithm      >> 8) & 0xFF;
    *p++ = (sig->Pad                >> 0) & 0xFF;
    *p++ = (sig->Pad                >> 8) & 0xFF;
    *p++ = (sig->Flags              >> 0) & 0xFF;
    *p++ = (sig->Flags              >> 8) & 0xFF;

    if (len > NL_AUTH_SIGNATURE_HEADER_LENGTH) {
        memcpy(p, sig->SequenceNumber, 8);
        p += 8;
    }

    if (len > NL_AUTH_SIGNATURE_COMMON_LENGTH) {
        size_t cksumlen = _netlogon_checksum_length(sig);

        memcpy(p, sig->Checksum, cksumlen);
        p += cksumlen;

        /* Confounder, if present, is immediately after checksum */
        if (sig->SealAlgorithm != NL_SEAL_ALG_NONE) {
            memcpy(p, &sig->Checksum[cksumlen], 8);
        }
    }

    return 0;
}

static int
_netlogon_decode_NL_AUTH_SIGNATURE(const uint8_t *ptr,
                                   size_t len,
                                   NL_AUTH_SIGNATURE *sig)
{
    const uint8_t *p = ptr;
    size_t cksumlen;

    if (len < NL_AUTH_SIGNATURE_COMMON_LENGTH)
        return KRB5_BAD_MSIZE;

    sig->SignatureAlgorithm = (p[0] << 0) | (p[1] << 8);
    sig->SealAlgorithm      = (p[2] << 0) | (p[3] << 8);
    sig->Pad                = (p[4] << 0) | (p[5] << 8);
    sig->Flags              = (p[6] << 0) | (p[7] << 8);
    p += 8;

    memcpy(sig->SequenceNumber, p, 8);
    p += 8;

    /* Validate signature algorithm is known and matches enctype */
    switch (sig->SignatureAlgorithm) {
    case NL_SIGN_ALG_HMAC_MD5:
        cksumlen = NL_AUTH_SIGNATURE_LENGTH;
        break;
    case NL_SIGN_ALG_SHA256:
        cksumlen = NL_AUTH_SHA2_SIGNATURE_LENGTH;
        break;
    default:
        return EINVAL;
        break;
    }

    if (sig->SealAlgorithm == NL_SEAL_ALG_NONE)
        cksumlen -= 8; /* confounder is optional if no sealing */

    if (len < cksumlen)
        return KRB5_BAD_MSIZE;

    /* Copy variable length checksum */
    cksumlen = _netlogon_checksum_length(sig);
    memcpy(sig->Checksum, p, cksumlen);
    p += cksumlen;

    /* Copy confounder in past checksum */
    if (sig->SealAlgorithm != NL_SEAL_ALG_NONE)
        memcpy(&sig->Checksum[cksumlen], p, 8);

    return 0;
}

static void
_netlogon_derive_rc4_hmac_key(uint8_t key[16],
                              uint8_t *salt,
                              size_t saltLength,
                              EVP_CIPHER_CTX *rc4Key,
                              int enc)
{
    uint8_t tmpData[MD5_DIGEST_LENGTH];
    uint8_t derivedKey[MD5_DIGEST_LENGTH];
    unsigned int len = MD5_DIGEST_LENGTH;

    HMAC(EVP_md5(), key, 16, zeros, sizeof(zeros), tmpData, &len);
    HMAC(EVP_md5(), tmpData, MD5_DIGEST_LENGTH,
         salt, saltLength, derivedKey, &len);

    assert(len == MD5_DIGEST_LENGTH);

    EVP_CipherInit_ex(rc4Key, EVP_rc4(), NULL, derivedKey, NULL, enc);

    memset(derivedKey, 0, sizeof(derivedKey));
}

static void
_netlogon_derive_rc4_seal_key(gssnetlogon_ctx ctx,
                              NL_AUTH_SIGNATURE *sig,
                              EVP_CIPHER_CTX *sealkey,
                              int enc)
{
    uint8_t xorKey[16];
    int i;

    for (i = 0; i < sizeof(xorKey); i++) {
        xorKey[i] = ctx->SessionKey[i] ^ 0xF0;
    }

    _netlogon_derive_rc4_hmac_key(xorKey,
        sig->SequenceNumber, sizeof(sig->SequenceNumber), sealkey, enc);

    memset(xorKey, 0, sizeof(xorKey));
}

static void
_netlogon_derive_rc4_seq_key(gssnetlogon_ctx ctx,
                             NL_AUTH_SIGNATURE *sig,
                             EVP_CIPHER_CTX *seqkey,
                             int enc)
{
    _netlogon_derive_rc4_hmac_key(ctx->SessionKey,
        sig->Checksum, sizeof(sig->Checksum), seqkey, enc);
}

static void
_netlogon_derive_aes_seal_key(gssnetlogon_ctx ctx,
                              NL_AUTH_SIGNATURE *sig,
                              EVP_CIPHER_CTX *sealkey,
                              int enc)
{
    uint8_t encryptionKey[16];
    uint8_t ivec[16];
    int i;

    for (i = 0; i < sizeof(encryptionKey); i++) {
        encryptionKey[i] = ctx->SessionKey[i] ^ 0xF0;
    }

    memcpy(&ivec[0], sig->SequenceNumber, 8);
    memcpy(&ivec[8], sig->SequenceNumber, 8);

    EVP_CipherInit_ex(sealkey, EVP_aes_128_cfb8(),
                      NULL, encryptionKey, ivec, enc);

    memset(encryptionKey, 0, sizeof(encryptionKey));
}

static void
_netlogon_derive_aes_seq_key(gssnetlogon_ctx ctx,
                             NL_AUTH_SIGNATURE *sig,
                             EVP_CIPHER_CTX *seqkey,
                             int enc)
{
    uint8_t ivec[16];

    memcpy(&ivec[0], sig->Checksum, 8);
    memcpy(&ivec[8], sig->Checksum, 8);

    EVP_CipherInit_ex(seqkey, EVP_aes_128_cfb8(),
                      NULL, ctx->SessionKey, ivec, enc);
}

static void
_netlogon_seal(gssnetlogon_ctx ctx,
               NL_AUTH_SIGNATURE *sig,
               gss_iov_buffer_desc *iov,
               int iov_count,
               int enc)
{
    EVP_CIPHER_CTX sealkey;
    int i;
    uint8_t *confounder = _netlogon_confounder(sig);

    EVP_CIPHER_CTX_init(&sealkey);

    if (sig->SealAlgorithm == NL_SEAL_ALG_AES128)
        _netlogon_derive_aes_seal_key(ctx, sig, &sealkey, enc);
    else
        _netlogon_derive_rc4_seal_key(ctx, sig, &sealkey, enc);

    EVP_Cipher(&sealkey, confounder, confounder, 8);

    /*
     * For RC4, Windows resets the cipherstate after encrypting
     * the confounder, thus defeating the purpose of the confounder
     */
    if (sig->SealAlgorithm == NL_SEAL_ALG_RC4) {
        EVP_CipherFinal_ex(&sealkey, NULL, &i);
        _netlogon_derive_rc4_seal_key(ctx, sig, &sealkey, enc);
    }

    for (i = 0; i < iov_count; i++) {
        gss_iov_buffer_t iovp = &iov[i];

        switch (GSS_IOV_BUFFER_TYPE(iovp->type)) {
        case GSS_IOV_BUFFER_TYPE_DATA:
        case GSS_IOV_BUFFER_TYPE_PADDING:
            EVP_Cipher(&sealkey, iovp->buffer.value, iovp->buffer.value,
                       iovp->buffer.length);
            break;
        default:
            break;
        }
    }

    EVP_CipherFinal_ex(&sealkey, NULL, &i);
    EVP_CIPHER_CTX_cleanup(&sealkey);
}

static void
_netlogon_seq(gssnetlogon_ctx ctx,
              NL_AUTH_SIGNATURE *sig,
              int enc)
{
    EVP_CIPHER_CTX seqkey;

    EVP_CIPHER_CTX_init(&seqkey);

    if (sig->SignatureAlgorithm == NL_SIGN_ALG_SHA256)
        _netlogon_derive_aes_seq_key(ctx, sig, &seqkey, enc);
    else
        _netlogon_derive_rc4_seq_key(ctx, sig, &seqkey, enc);

    EVP_Cipher(&seqkey, sig->SequenceNumber, sig->SequenceNumber, 8);

    EVP_CIPHER_CTX_cleanup(&seqkey);
}

static void
_netlogon_digest_md5(gssnetlogon_ctx ctx,
                     NL_AUTH_SIGNATURE *sig,
                     gss_iov_buffer_desc *iov,
                     int iov_count,
                     uint8_t *md)
{
    EVP_MD_CTX *md5;
    uint8_t header[NL_AUTH_SIGNATURE_HEADER_LENGTH];
    uint8_t digest[MD5_DIGEST_LENGTH];
    unsigned int md_len = MD5_DIGEST_LENGTH;
    int i;

    _netlogon_encode_NL_AUTH_SIGNATURE(sig, header, sizeof(header));

    md5 = EVP_MD_CTX_create();
    EVP_DigestInit_ex(md5, EVP_md5(), NULL);
    EVP_DigestUpdate(md5, zeros, sizeof(zeros));
    EVP_DigestUpdate(md5, header, sizeof(header));

    if (sig->SealAlgorithm != NL_SEAL_ALG_NONE) {
        EVP_DigestUpdate(md5, sig->Confounder, sizeof(sig->Confounder));
    }

    for (i = 0; i < iov_count; i++) {
        gss_iov_buffer_t iovp = &iov[i];

        switch (GSS_IOV_BUFFER_TYPE(iovp->type)) {
        case GSS_IOV_BUFFER_TYPE_DATA:
        case GSS_IOV_BUFFER_TYPE_PADDING:
        case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
            EVP_DigestUpdate(md5, iovp->buffer.value, iovp->buffer.length);
            break;
        default:
            break;
        }
    }

    EVP_DigestFinal_ex(md5, digest, NULL);
    EVP_MD_CTX_destroy(md5);

    HMAC(EVP_md5(), ctx->SessionKey, sizeof(ctx->SessionKey),
         digest, sizeof(digest), digest, &md_len);
    memcpy(md, digest, 8);
}

static void
_netlogon_digest_sha256(gssnetlogon_ctx ctx,
                        NL_AUTH_SIGNATURE *sig,
                        gss_iov_buffer_desc *iov,
                        int iov_count,
                        uint8_t *md)
{
    HMAC_CTX hmac;
    uint8_t header[NL_AUTH_SIGNATURE_HEADER_LENGTH];
    uint8_t digest[SHA256_DIGEST_LENGTH];
    unsigned int md_len = SHA256_DIGEST_LENGTH;
    int i;

    /* Encode first 8 bytes of signature into header */
    _netlogon_encode_NL_AUTH_SIGNATURE(sig, header, sizeof(header));

    HMAC_CTX_init(&hmac);
    HMAC_Init_ex(&hmac, ctx->SessionKey, sizeof(ctx->SessionKey),
                 EVP_sha256(), NULL);
    HMAC_Update(&hmac, header, sizeof(header));

    if (sig->SealAlgorithm != NL_SEAL_ALG_NONE) {
        /*
         * If the checksum length bug is ever fixed, then be sure to
         * update this code to point to &sig->Checksum[32] as that is
         * where the confounder is supposed to be.
         */
        HMAC_Update(&hmac, sig->Confounder, 8);
    }

    for (i = 0; i < iov_count; i++) {
        gss_iov_buffer_t iovp = &iov[i];

        switch (GSS_IOV_BUFFER_TYPE(iovp->type)) {
        case GSS_IOV_BUFFER_TYPE_DATA:
        case GSS_IOV_BUFFER_TYPE_PADDING:
        case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
            HMAC_Update(&hmac, iovp->buffer.value, iovp->buffer.length);
            break;
        default:
            break;
        }
    }

    HMAC_Final(&hmac, digest, &md_len);
    HMAC_CTX_cleanup(&hmac);
    memcpy(md, digest, 8);
}

static void
_netlogon_digest(gssnetlogon_ctx ctx,
                 NL_AUTH_SIGNATURE *sig,
                 gss_iov_buffer_desc *iov,
                 int iov_count,
                 uint8_t *md)
{
    if (sig->SignatureAlgorithm == NL_SIGN_ALG_SHA256)
        _netlogon_digest_sha256(ctx, sig, iov, iov_count, md);
    else
        _netlogon_digest_md5(ctx, sig, iov, iov_count, md);
}

OM_uint32
_netlogon_wrap_iov(OM_uint32 * minor_status,
                   gss_ctx_id_t  context_handle,
                   int conf_req_flag,
                   gss_qop_t qop_req,
                   int *conf_state,
                   gss_iov_buffer_desc *iov,
                   int iov_count)
{
    OM_uint32 ret;
    gss_iov_buffer_t header;
    NL_AUTH_SIGNATURE_U sigbuf = { { 0 } };
    NL_AUTH_SIGNATURE *sig = NL_AUTH_SIGNATURE_P(&sigbuf);
    gssnetlogon_ctx ctx = (gssnetlogon_ctx)context_handle;
    size_t size;
    uint8_t *seqdata;

    if (ctx->State != NL_AUTH_ESTABLISHED) {
        *minor_status = EINVAL;
        return GSS_S_FAILURE;
    }

    header = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
    if (header == NULL) {
        *minor_status = EINVAL;
        return GSS_S_FAILURE;
    }

    size = _netlogon_signature_length(ctx->SignatureAlgorithm, conf_req_flag);

    if (GSS_IOV_BUFFER_FLAGS(header->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE) {
        ret = _gss_mg_allocate_buffer(minor_status, header, size);
        if (GSS_ERROR(ret))
            return ret;
    } else if (header->buffer.length < size) {
        *minor_status = KRB5_BAD_MSIZE;
        return GSS_S_FAILURE;
    } else {
        header->buffer.length = size;
    }

    memset(header->buffer.value, 0, header->buffer.length);

    sig->SignatureAlgorithm = ctx->SignatureAlgorithm;
    sig->SealAlgorithm = conf_req_flag ? ctx->SealAlgorithm : NL_SEAL_ALG_NONE;

    if (conf_req_flag)
        krb5_generate_random_block(_netlogon_confounder(sig), 8);

    sig->Pad = 0xFFFF;              /* [MS-NRPC] 3.3.4.2.1.3 */
    sig->Flags = 0;                 /* [MS-NRPC] 3.3.4.2.1.4 */
    HEIMDAL_MUTEX_lock(&ctx->Mutex);
    _netlogon_encode_sequence_number(ctx->SequenceNumber, sig->SequenceNumber,
                                     ctx->LocallyInitiated);
    ctx->SequenceNumber++;
    HEIMDAL_MUTEX_unlock(&ctx->Mutex);

    /* [MS-NRPC] 3.3.4.2.1.7: sign header, optional confounder and data  */
    _netlogon_digest(ctx, sig, iov, iov_count, sig->Checksum);

    /* [MS-NRPC] 3.3.4.2.1.8: optionally encrypt confounder and data */
    if (conf_req_flag)
        _netlogon_seal(ctx, sig, iov, iov_count, 1);

    /* [MS-NRPC] 3.3.4.2.1.9: encrypt sequence number */
    _netlogon_seq(ctx, sig, 1);

    _netlogon_encode_NL_AUTH_SIGNATURE(sig, header->buffer.value,
                                       header->buffer.length);

    if (conf_state != NULL)
        *conf_state = conf_req_flag;

    *minor_status = 0;
    return GSS_S_COMPLETE;
}

OM_uint32
_netlogon_unwrap_iov(OM_uint32 *minor_status,
                     gss_ctx_id_t context_handle,
                     int *conf_state,
                     gss_qop_t *qop_state,
                     gss_iov_buffer_desc *iov,
                     int iov_count)
{
    OM_uint32 ret;
    gss_iov_buffer_t header;
    NL_AUTH_SIGNATURE_U sigbuf;
    NL_AUTH_SIGNATURE *sig = NL_AUTH_SIGNATURE_P(&sigbuf);
    gssnetlogon_ctx ctx = (gssnetlogon_ctx)context_handle;
    uint8_t checksum[SHA256_DIGEST_LENGTH];
    uint64_t SequenceNumber;

    if (ctx->State != NL_AUTH_ESTABLISHED) {
        *minor_status = EINVAL;
        return GSS_S_FAILURE;
    }

    header = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
    if (header == NULL) {
        *minor_status = EINVAL;
        return GSS_S_FAILURE;
    }

    ret = _netlogon_decode_NL_AUTH_SIGNATURE(header->buffer.value,
                                             header->buffer.length,
                                             sig);
    if (ret != 0) {
        *minor_status = ret;
        return GSS_S_DEFECTIVE_TOKEN;
    }

    /* [MS-NRPC] 3.3.4.2.2.1: verify signature algorithm selection */
    if (sig->SignatureAlgorithm != ctx->SignatureAlgorithm)
        return GSS_S_BAD_SIG;

    /* [MS-NRPC] 3.3.4.2.2.2: verify encryption algorithm selection */
    if (sig->SealAlgorithm != NL_SEAL_ALG_NONE &&
        sig->SealAlgorithm != ctx->SealAlgorithm)
        return GSS_S_DEFECTIVE_TOKEN;

    /* [MS-NRPC] 3.3.4.2.2.3: verify Pad bytes */
    if (sig->Pad != 0xFFFF)
        return GSS_S_DEFECTIVE_TOKEN;

    /* [MS-NRPC] 3.3.4.2.2.5: decrypt sequence number */
    _netlogon_seq(ctx, sig, 0);

    /* [MS-NRPC] 3.3.4.2.2.6: decode sequence number */
    if (_netlogon_decode_sequence_number(sig->SequenceNumber, &SequenceNumber,
                                         !ctx->LocallyInitiated) != 0)
        return GSS_S_UNSEQ_TOKEN;

    /* [MS-NRPC] 3.3.4.2.2.9: decrypt confounder and data */
    if (sig->SealAlgorithm != NL_SEAL_ALG_NONE)
        _netlogon_seal(ctx, sig, iov, iov_count, 0);

    /* [MS-NRPC] 3.3.4.2.2.10: verify signature */
    _netlogon_digest(ctx, sig, iov, iov_count, checksum);
    if (memcmp(sig->Checksum, checksum, _netlogon_checksum_length(sig)) != 0)
        return GSS_S_BAD_SIG;

    HEIMDAL_MUTEX_lock(&ctx->Mutex);
    if (SequenceNumber != ctx->SequenceNumber) {
        /* [MS-NRPC] 3.3.4.2.2.7: check sequence number */
        ret = GSS_S_UNSEQ_TOKEN;
    } else {
        /* [MS-NRPC] 3.3.4.2.2.8: increment sequence number */
        ctx->SequenceNumber++;
        ret = GSS_S_COMPLETE;
    }
    HEIMDAL_MUTEX_unlock(&ctx->Mutex);

    if (conf_state != NULL)
        *conf_state = (sig->SealAlgorithm != NL_SEAL_ALG_NONE);
    if (qop_state != NULL)
        *qop_state = GSS_C_QOP_DEFAULT;

    *minor_status = 0;
    return ret;
}

OM_uint32
_netlogon_wrap_iov_length(OM_uint32 * minor_status,
        	          gss_ctx_id_t context_handle,
        	          int conf_req_flag,
        	          gss_qop_t qop_req,
        	          int *conf_state,
        	          gss_iov_buffer_desc *iov,
        	          int iov_count)
{
    OM_uint32 ret;
    gss_iov_buffer_t iovp;
    gssnetlogon_ctx ctx = (gssnetlogon_ctx)context_handle;
    size_t len;

    iovp = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
    if (iovp == NULL) {
        *minor_status = EINVAL;
        return GSS_S_FAILURE;
    }

    len = NL_AUTH_SIGNATURE_COMMON_LENGTH;
    if (ctx->SignatureAlgorithm == NL_SIGN_ALG_SHA256)
        len += 32;  /* SHA2 checksum size */
    else
        len += 8;   /* HMAC checksum size */
    if (conf_req_flag)
        len += 8;   /* counfounder */

    iovp->buffer.length = len;

    iovp = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDING);
    if (iovp != NULL)
        iovp->buffer.length = 0;

    iovp = _gss_mg_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILER);
    if (iovp != NULL)
        iovp->buffer.length = 0;

    if (conf_state != NULL)
        *conf_state = conf_req_flag;

    *minor_status = 0;
    return GSS_S_COMPLETE;
}

OM_uint32 _netlogon_get_mic
           (OM_uint32 * minor_status,
            const gss_ctx_id_t context_handle,
            gss_qop_t qop_req,
            const gss_buffer_t message_buffer,
            gss_buffer_t message_token
           )
{
    gss_iov_buffer_desc iov[2];
    OM_uint32 ret;

    iov[0].type = GSS_IOV_BUFFER_TYPE_DATA;
    iov[0].buffer = *message_buffer;
    iov[1].type = GSS_IOV_BUFFER_TYPE_HEADER | GSS_IOV_BUFFER_FLAG_ALLOCATE;
    iov[1].buffer.length = 0;
    iov[1].buffer.value = NULL;

    ret = _netlogon_wrap_iov(minor_status, context_handle, 0,
                             qop_req, NULL, iov, 2);
    if (ret == GSS_S_COMPLETE)
        *message_token = iov[1].buffer;

    return ret;
}

OM_uint32
_netlogon_verify_mic
           (OM_uint32 * minor_status,
            const gss_ctx_id_t context_handle,
            const gss_buffer_t message_buffer,
            const gss_buffer_t token_buffer,
            gss_qop_t * qop_state
            )
{
    gss_iov_buffer_desc iov[2];

    iov[0].type = GSS_IOV_BUFFER_TYPE_DATA;
    iov[0].buffer = *message_buffer;
    iov[1].type = GSS_IOV_BUFFER_TYPE_HEADER;
    iov[1].buffer = *token_buffer;

    return _netlogon_unwrap_iov(minor_status, context_handle,
                                NULL, qop_state, iov, 2);
}

OM_uint32
_netlogon_wrap_size_limit (
            OM_uint32 * minor_status,
            const gss_ctx_id_t context_handle,
            int conf_req_flag,
            gss_qop_t qop_req,
            OM_uint32 req_output_size,
            OM_uint32 *max_input_size
           )
{
    gss_iov_buffer_desc iov[1];
    OM_uint32 ret;

    iov[0].type = GSS_IOV_BUFFER_TYPE_HEADER;
    iov[0].buffer.length = 0;

    ret = _netlogon_wrap_iov_length(minor_status, context_handle,
                                    conf_req_flag, qop_req, NULL,
                                    iov, sizeof(iov)/sizeof(iov[0]));
    if (GSS_ERROR(ret))
        return ret;

    if (req_output_size < iov[0].buffer.length)
        *max_input_size = 0;
    else
        *max_input_size = req_output_size - iov[0].buffer.length;

    return GSS_S_COMPLETE;
}


text:
module Magick
  Magick4J = Java::magick4j
  RMagick4J = Java::rmagick4j

  QuantumDepth = 8
  QuantumRange = 2**QuantumDepth-1
  QuantumScale = 1.0/QuantumRange.to_f

  # Geometries
  JGeometry        = Magick4J::Geometry

  JGeometries = [
                  JGeometry,
                  Magick4J::PercentGeometry,
                  Magick4J::AspectGeometry,
                  Magick4J::LessGeometry,
                  Magick4J::GreaterGeometry,
                  Magick4J::AreaGeometry
                ]
end


text:
#pragma once

#include <Carna/base/noncopyable.h>
#include <Carna/VolumeRenderings/VolumeVisualizationCameraController.h>
#include <QTimer>
#include <QTime>

// ----------------------------------------------------------------------------------
// VolumeViewCameraController
// ----------------------------------------------------------------------------------

class VolumeViewCameraController : public Carna::VolumeRenderings::VolumeVisualizationCameraController
{

    Q_OBJECT

    NON_COPYABLE

public:

    explicit VolumeViewCameraController( Carna::VolumeRenderings::VolumeVisualization& view, QObject* parent = nullptr );

    virtual void event( Carna::base::Visualization& sourceModule, QEvent* event ) override;

    int getStepsPerSecond() const;

    bool hasAutoRotate() const;

    double getSecondsPerRotation() const;

public slots:

    void setStepsPerSecond( int );

    void setAutoRotate( bool );

    void setSecondsPerRotation( double );

private slots:

    void doRotationStep();

    void startAutoRotate();

    void stopAutoRotate();

private:

    QTimer autoRotationTimer;

    QTime frameTimer;

    int stepsPerSecond;

    bool autoRotate;

    double secondsPerRotation;

}; // VolumeViewCameraController


text:
package main

import (
	"flag"
	"log"
	"os"
	"runtime"
	"runtime/pprof"
)

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

func main() {
	numCPU := runtime.NumCPU()
	runtime.GOMAXPROCS(numCPU)
	flag.Parse()

	// profile
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	app, err := newApp()
	checkError(err)
	defer app.Dispose()

	if args := flag.Args(); len(args) > 0 {
		fileName := args[0]
		app.OpenDoc(fileName)
	}

	checkError(app.Run())
}


text:
title: "24 Days of Hackage: HLint"
---

In my [first post](/posts/2012-12-01-24-days-of-hackage.html) I mentioned
that Cabal is capable of building executables, but so far we've only looked at
libraries. [Hackage](http://hackage.haskell.org) also contains a plethora of
tools for the working Haskell programmer, and today we will look at HLint.

[HLint](http://community.haskell.org/~ndm/hlint/), created by
[Neil Mitchell](http://community.haskell.org/~ndm/), is a tool that takes
Haskell `.hs` files as input, and analyses them to produce hints on better ways
to write code - be that more performent, more succinct or more
idiomatic. Because of this, HLint is frequently suggested to beginners - but it's
still a tool I frequently use! Though maybe I'm really still just a beginner...

It would be a rather long article if I were to enumerate all of the hints HLint
can give you; instead I will concentrate on a few that have helped further my
Haskell knowledge.

To the beginner, Haskell seems full of operators and combinators, and has a
somewhat alien way of calling functions. This threw me for a while - "how on
earth am I meant to remember the precedance for function application?!" and "why
can't I drop the brackets here?" were amongst the questions I found myself
asking. HLint helped clear a lot of this confusion for me: instead, I started
liberally using parentheses and let HLint guide me to write more idiomatic
Haskell. For example, we could start with the following code.

```haskell
[(10 + 20), 9] == (map (\x -> x * 3) [10, 3])
```

HLint, after a few passes, reduces this code to:

```haskell
[10 + 20, 9] == map (* 3) [10, 3]
```

Which is certainly much cleaner! By repeating this exercise, it all started to
click a litle bit more.

HLint is also aware of common programming patterns too, which has been another
way to strengthen my knowledge, especially in developing intuition for how all
the pieces fit together. All the various monad combinators seemed a little
mythical to me at first, and I would often write code such as:

```haskell
getLine >>= return . map toUpper
```

But this can be simplified by the `liftM` combinator:

```haskell
liftM (map toUpper) getLine
```

Why not indeed - thanks HLint!

## Writing your own hints

HLint also allows you to extend it with your own hints - a feature that I think
can be over looked, but is nonetheless very useful, and likely essential for
large team who wish to write consistent code. I personally tend to prefer the
use of infix `fmap` via `<$>` - so ideally I'd like `fmap x foo` to produce a
hint to change it to `x <$> foo`.

```
warn = fmap f x ==> f <$> x
```

And now if we try:

```haskell
fmap (map toUpper) getLine
```

HLint rightfully suggests:

```
Warning: Use <$>
Found:
  fmap (map toUpper) getLine
Why not:
  map toUpper <$> getLine

```

Simple! HLint features literally
[hundreds](http://community.haskell.org/~ndm/darcs/hlint/data/Default.hs) of
hints out the box, which are already enough to get going with. If your
participating in [24 Pull Requests](http://24pullrequests.com) this year, HLint
can be a great way to make pull requests on code that is otherwise too difficult
for you - after all, which maintainer doesn't want pretty, consistent code?


text:
<!DOCTYPE HTML>

<base href="">

<title>模板页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="">
<meta http-equiv="description" content="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link rel="stylesheet" type="text/css" href="css/allStyle.css">

这是中文


text:
'use strict';

var HashCodeGenerator = require('./generator');

/**
 * An abstract implementation of {@link HashCodeGenerator} that is intended for implementations that wish to support
 * value types that contain a collection of other values. This is achieved by requesting the elements contained within
 * the value as an array from the implementation and then generates hash codes for each element to compute the hash code
 * for the value.
 *
 * Implementations must implement the {@link CollectionHashCodeGenerator#getElements} and
 * {@link HashCodeGenerator#supports} methods.
 *
 * @protected
 * @constructor
 * @extends HashCodeGenerator
 */
var CollectionHashCodeGenerator = HashCodeGenerator.extend({

  /**
   * @inheritdoc
   * @override
   * @memberof CollectionHashCodeGenerator#
   */
  generate: function generate(context) {
    var elements = this.getElements(context);

    return elements.reduce(function(hash, element) {
      return ((31 * hash) + context.hashCode(element)) | 0;
    }, 1);
  },

  /**
   * Returns the elements contained within the value of the specified context.
   *
   * @param {HashCodeContext} context - the {@link HashCodeContext} containing the value whose children elements are to
   * be returned
   * @return {Array} The elements contained within the value of context.
   * @protected
   * @abstract
   * @memberof CollectionHashCodeGenerator#
   */
  getElements: /* istanbul ignore next */ function getElements(context) {}

});

module.exports = CollectionHashCodeGenerator;


text:
package org.apache.camel.reifier.validator;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.ExchangePattern;
import org.apache.camel.model.validator.EndpointValidatorDefinition;
import org.apache.camel.model.validator.ValidatorDefinition;
import org.apache.camel.processor.SendProcessor;
import org.apache.camel.processor.validator.ProcessorValidator;
import org.apache.camel.spi.Validator;

public class EndpointValidatorReifier extends ValidatorReifier<EndpointValidatorDefinition> {

    public EndpointValidatorReifier(CamelContext camelContext, ValidatorDefinition definition) {
        super(camelContext, (EndpointValidatorDefinition) definition);
    }

    @Override
    protected Validator doCreateValidator() {
        Endpoint endpoint = definition.getUri() != null
                ? camelContext.getEndpoint(definition.getUri()) : lookupByNameAndType(definition.getRef(), Endpoint.class);
        SendProcessor processor = new SendProcessor(endpoint, ExchangePattern.InOut);
        return new ProcessorValidator(camelContext).setProcessor(processor).setType(definition.getType());
    }

}


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

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Three Forks springsnail factsheet on ARKive - Pyrgulopsis trivialis</title>
        <link rel="canonical" href="http://www.arkive.org/three-forks-springsnail/pyrgulopsis-trivialis/" />
		<link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" />
		<link rel="icon" href="/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Three Forks springsnail (Pyrgulopsis trivialis)

Kingdom	Animalia

Phylum	Mollusca

Class	Gastropoda

Order	Littorinimorpha

Family	Hydrobiidae

Genus	Pyrgulopsis (1)

The Three Forks springsnail is classified as Critically Endangered (CR) on the IUCN Red List (1).

Information on the Three Forks springsnail (Pyrgulopsis trivialis) is currently being researched and written and will appear here shortly.

This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact:
arkive@wildscreen.org.uk

IUCN Red List (March, 2013)
http://www.iucnredlist.org


text:
@ECHO OFF
ECHO Copying files to your code snippets directory...

xcopy /s "..\src" "%USERPROFILE%\Documents\Visual Studio 2013\Code Snippets"

ECHO Done!
PAUSE


text:
package com.github.takezoe.xlsbeans;

import com.github.takezoe.xlsbeans.annotation.Column;
import com.github.takezoe.xlsbeans.annotation.MapColumns;

import java.util.Map;

public class LanguageIDE {

  private String name;
  private Map<String, String> attributes;

  public Map<String, String> getAttributes() {
    return attributes;
  }

  @MapColumns(previousColumnName = "Name")
  public void setAttributes(Map<String, String> attributes) {
    this.attributes = attributes;
  }

  public String getName() {
    return name;
  }

  @Column(columnName = "Name")
  public void setName(String name) {
    this.name = name;
  }

}


text:
package org.dryomys.exceptions;

import org.dryomys.util.NumericUtils;

/**
 *
 * @author Gabriele Falace
 *
 */
public class ExceptionFactory {

    private ExceptionFactory() {
    }

    /**
     * Creates an UnsupportedNumberTypeException based on the first object that
     * is of an unsupported type, given an array of objects.
     *
     * @param numbers
     *            an array of Number in which at least one is not of a supported
     *            type
     * @return an UnsupportedNumberTypeException referring to the first object
     *         of an unsupported type
     */
    public static final UnsupportedTypeException createUnsupportedNumberType(Number... numbers) {
        UnsupportedTypeException unte = new UnsupportedTypeException(
                "Unsupported type, not related to a particular number");
        for (Number o : numbers) {
            if (o != null && !NumericUtils.isProper(o)) {
                unte = new UnsupportedTypeException(o);
                break;
            }
        }
        return unte;
    }

}


text: Production Manager


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Diagnostics.CodeAnalysis;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    [SuppressMessage("Performance", "CA1067", Justification = "Equality not actually implemented")]
    internal readonly struct BinaryOperatorAnalysisResult
    {
        public readonly Conversion LeftConversion;
        public readonly Conversion RightConversion;
        public readonly BinaryOperatorSignature Signature;
        public readonly OperatorAnalysisResultKind Kind;

        private BinaryOperatorAnalysisResult(OperatorAnalysisResultKind kind, BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion)
        {
            this.Kind = kind;
            this.Signature = signature;
            this.LeftConversion = leftConversion;
            this.RightConversion = rightConversion;
        }

        public bool IsValid
        {
            get { return this.Kind == OperatorAnalysisResultKind.Applicable; }
        }

        public bool HasValue
        {
            get { return this.Kind != OperatorAnalysisResultKind.Undefined; }
        }

        public override bool Equals(object obj)
        {
            // implement if needed
            throw ExceptionUtilities.Unreachable();
        }

        public override int GetHashCode()
        {
            // implement if needed
            throw ExceptionUtilities.Unreachable();
        }

        public static BinaryOperatorAnalysisResult Applicable(BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion)
        {
            return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Applicable, signature, leftConversion, rightConversion);
        }

        public static BinaryOperatorAnalysisResult Inapplicable(BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion)
        {
            return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Inapplicable, signature, leftConversion, rightConversion);
        }

        public BinaryOperatorAnalysisResult Worse()
        {
            return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Worse, this.Signature, this.LeftConversion, this.RightConversion);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_focused="false" android:state_pressed="true"
	android:drawable="@drawable/btndown_menucolor"/>
	<item android:drawable="@drawable/btn_menucolor"/>
</selector>


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea alocizoides Leight.

### Remarks
null


text:
/*global define:false */

// The omelette module
define(["eggs", "bacon", "eat"], function (eggs, bacon, eat) {
  "use strict";

  return {
    isOmelette: true,
    isMocked: false,

    getEggs: function () { return eggs; },
    getBacon: function () { return bacon; },
    eat: eat
  };
});


text:
layout: post
title: "Backups with rsync and zfs"
categories:
  - bits
---

As I [mentioned before][uncloud] I'm running my own backup on a server that is
running in my apartment. I didn't really talk a lot about how this works,
other than it is running on a HP Microserver with an encrypted ZFS RAID. So I
wanted to also quickly jot down how the backup works. This is only set up for
a single user right now because I'm the only one using it.

For me a backup has two important parts:

- Have data in a different location
- Be able to restore data from the past

The time sensitivity of those two properties are pretty different for me. For
example I have chosen for myself that I'm happy with only being able to
restore deleted data from the last day. So if I create something and delete it
5 hours later, I'm ok with not being able to recover it. On the other hand I'm
very aware of the fact that my mailserver can disappear at any given time:

that moment when you want to make dinner and your mailserver disappears
— Daniel Schauenberg (@mrtazz) December 14, 2013

This is why I want to copy data to a remote location as often as possible
(which for me means about every 15 minutes). And my setup is heavily based
around those ideas. The core of the backup system is ZFS and a separate file
system for each machine I want to backup. In order to have the ability to go
back in time I use [zfs snapshots][snapshots]. Every night the following
script runs on my backup server and creates a snapshot for the day:

```bash
#!/bin/sh
# simple script to snapshot locations on a ZFS backup pool

timestamp=`date +%Y-%m-%d-%H:%M:%S`
for volume in $(ls /backup); do
  echo "Creating snapshot for ${volume} at date ${timestamp}"
  /sbin/zfs snapshot backup/${volume}@${timestamp}
done
```

And to make sure that I really do have snapshots I have this simple nagios
script to tell me if the snapshotting worked last night.

```bash
#!/bin/sh

# nagios script to check age of backup snapshots

YESTERDAY=`date -v-1d +%Y-%m-%d`
EXITCODE=0

for backup in $(ls /backup); do
  zfs list -t snapshot | grep ${backup} | grep -q ${YESTERDAY}
  if [ $? != 0 ]; then
    echo "Snapshot of ${backup} missing for ${YESTERDAY}."
    EXITCODE=2
  fi
done

if [ ${EXITCODE} == 0 ]; then
  echo "All backup volumes were snapshotted on ${YESTERDAY}."
fi

exit ${EXITCODE}

```

And this check (which runs on all my servers because I have zpools everywhere)
to tell me about the disk health of the backup zpool:

```bash
#!/bin/sh

# check for zpool health
ZPOOL=`which zpool`
EXITSTATUS=0
IFS=$'\n'

for line in $(${ZPOOL} list -o name,health | grep -v NAME | grep -v ONLINE)
do
  echo $line
  EXITSTATUS=2
done

if [ $EXITSTATUS == 0 ]; then
  echo "All pools are healthy."
fi

exit $EXITSTATUS
```

With this setup in place I can simply copy files into the file system that
belongs to that machine and it will get snapshotted every night. And what's an
awesome tool to copy data? That's right, [rsync][rsync].

My backup script runs once every 15 minutes and looks like this:

```bash
#!/bin/sh
#
# Backup script to pull in changes from remote hosts
#
for backup in $(ls /backup); do
  grep -q ${backup} ~/.backupexcludes
  if [ $? != 0 ]; then
    /usr/local/bin/rsync -e 'ssh -o BatchMode=yes -o ConnectTimeout=10' \
--archive --delete --timeout=5 ${backup}:. /backup/${backup}/
  fi
done
```

This allows me to have machines that I used to backup but are no longer online
in an excludes list. That way rsync (and ssh) doesn't hang or error for
something that doesn't need to be backed up anymore anyways. And in case a
machine is unavailable or disappears the timeout settings in that script make
sure it just gets skipped and retried on the next run.

I'm pretty happy with the setup, my backup server pulls in data from all my
servers on the internet and stores it (forever?). It is chef'd for the most
part (though there is always more to automate) and is pretty simple in my
opinion. The backup situation for my laptop is not ideal yet, as I manually
back it up by running rsync. I want to set the backup server up to also serve
some of the backup filesystems as Timemachine targets, so I can just use
Timemachine on my laptop and have it automatically run the backups.

But in the meantime I can add a new backup with this one weird trick:

```bash
zfs create /backup/newhost && chown -R mrtazz:mrtazz /backup/newhost
```

[uncloud]: http://www.unwiredcouch.com/2013/10/30/uncloud-your-life.html
[snapshots]: http://docs.oracle.com/cd/E19253-01/819-5461/gbcya/index.html
[rsync]: http://rsync.samba.org


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S15.9.5.4_A2_T1;
 * @section: 15.9.5.4;
 * @assertion: The "length" property of the "toTimeString" is 0;
 * @description: The "length" property of the "toTimeString" is 0;
 */

if(Date.prototype.toTimeString.hasOwnProperty("length") !== true){
  $ERROR('#1: The toTimeString has a "length" property');
}

if(Date.prototype.toTimeString.length !== 0){
  $ERROR('#2: The "length" property of the toTimeString is 0');
}


text:
<title>RTMPGW(8): </title>

RTMPGW(8)RTMPGW(8)

RTMPDump v2.2e2010-05-02RTMPGW(8)

NAME

rtmpgw − RTMP streaming media gateway

SYNOPSIS

rtmpgw
[−r url]
[−n hostname]
[−c port]
[−l protocol]
[−S host:port]
[−a app]
[−t tcUrl]
[−p pageUrl]
[−s swfUrl]
[−f flashVer]
[−u auth]
[−C conndata]
[−y playpath]
[−v]
[−d subscription]
[−e]
[−k skip]
[−A start]
[−B stop]
[−b buffer]
[−m timeout]
[−T key]
[−w swfHash]
[−x swfSize]
[−W swfUrl]
[−X swfAge]
[−D address]
[−g port]
[−q]
[−V]
[−z]

rtmpgw −h

DESCRIPTION

rtmpgw
is a server for streaming media content from RTMP out to HTTP.

rtmpgw
listens for HTTP requests that specify RTMP stream parameters and
then returns the RTMP data in the HTTP response. The only valid
HTTP request is "GET /" but additional options can be provided
in URL-encoded fashion. Options specified on the command line will
be used as defaults, which can be overridden by options in the HTTP
request.

OPTIONS

Network Parameters

These options define how to connect to the media server.

−−rtmp		−r url

URL of the server and media content.

−−host		−n hostname

Overrides the hostname in the RTMP URL.

−−port		−c port

Overrides the port number in the RTMP URL.

−−protocol	−l number

Overrides the protocol in the RTMP URL.

  0 = rtmp
  1 = rtmpt
  2 = rtmpe
  3 = rtmpte
  4 = rtmps
  5 = rtmpts

−−socks		−S host:port

Use the specified SOCKS4 proxy.

Connection Parameters

These options define the content of the RTMP Connect request packet.
If correct values are not provided, the media server will reject the
connection attempt.

−−app		−a app

Name of application to connect to on the RTMP server. Overrides
the app in the RTMP URL. Sometimes the rtmpdump URL parser cannot
determine the app name automatically, so it must be given explicitly
using this option.

−−tcUrl		−t url

URL of the target stream. Defaults to rtmp[e]://host[:port]/app/playpath.

−−pageUrl		−p url

URL of the web page in which the media was embedded. By default no
value will be sent.

−−swfUrl		−s url

URL of the SWF player for the media. By default no value will be sent.

−−flashVer	−f version

Version of the Flash plugin used to run the SWF player. The
default is "LNX 10,0,32,18".

−−auth		−u string

An authentication string to be appended to the Connect message. Using
this option will append a Boolean TRUE and then the specified string.
This option is only used by some particular servers and is
deprecated. The more general
−−conn
option should be used instead.

−−conn		−C type:data

Append arbitrary AMF data to the Connect message. The type
must be B for Boolean, N for number, S for string, O for object, or Z
for null. For Booleans the data must be either 0 or 1 for FALSE or TRUE,
respectively. Likewise for Objects the data must be 0 or 1 to end or
begin an object, respectively. Data items in subobjects may be named, by
prefixing the type with 'N' and specifying the name before the value, e.g.
NB:myFlag:1. This option may be used multiple times to construct arbitrary
AMF sequences. E.g.

  −C B:1 −C S:authMe −C O:1 −C NN:code:1.23 −C NS:flag:ok −C O:0

Session Parameters

These options take effect after the Connect request has succeeded.

−−playpath	−y path

Overrides the playpath parsed from the RTMP URL. Sometimes the
rtmpdump URL parser cannot determine the correct playpath
automatically, so it must be given explicitly using this option.

−−live −v

Specify that the media is a live stream. No resuming or seeking in
live streams is possible.

−−subscribe	−d stream

Name of live stream to subscribe to. Defaults to
playpath.

−−start		−A num

Start at
num
seconds into the stream. Not valid for live streams.

−−stop		−B num

Stop at
num
seconds into the stream.

−−buffer		−b num

Set buffer time to
num
milliseconds. The default is 20000.

−−timeout		−m num

Timeout the session after
num
seconds without receiving any data from the server. The default is 120.

Security Parameters

These options handle additional authentication requests from the server.

−−token		−T key

Key for SecureToken response, used if the server requires SecureToken
authentication.

−−swfhash		−w hexstring

SHA256 hash of the decompressed SWF file. This option may be needed if
the server uses SWF Verification, but see the
−−swfVfy
option below. The hash is 32 bytes, and must be
given in hexadecimal. The
−−swfsize
option must always be used with this option.

−−swfsize		−x num

Size of the decompressed SWF file. This option may be needed if the
server uses SWF Verification, but see the
−−swfVfy
option below. The
−−swfhash
option must always be used with this option.

−−swfVfy		−W url

URL of the SWF player for this media. This option replaces all three
of the
−−swfUrl,
−−swfhash,
and
−−swfsize
options. When this option is used, the SWF player is retrieved from the
specified URL and the hash and size are computed automatically. Also
the information is cached in a
.swfinfo
file in the user's home directory, so that it doesn't need to be retrieved
and recalculated every time rtmpdump is run. The .swfinfo file records
the URL, the time it was fetched, the modification timestamp of the SWF
file, its size, and its hash. By default, the cached info will be used
for 30 days before re-checking.

−−swfAge		−X days

Specify how many days to use the cached SWF info before re-checking. Use
0 to always check the SWF URL. Note that if the check shows that the
SWF file has the same modification timestamp as before, it will not be
retrieved again.

Miscellaneous

−−device		−D address

Listener IP address. The default is 0.0.0.0, i.e., any IP address.

−−sport		−g port

Listener port. The default is 80.

−−quiet −q

Suppress all command output.

−−verbose −V

Verbose command output.

−−debug −z

Debug level output. Extremely verbose, including hex dumps of all packet data.

−−help −h

Print a summary of command options.

EXAMPLES

The HTTP request

	GET /?r=rtmp:%2f%2fserver%2fmyapp&y=somefile HTTP/1.0

is equivalent to the
rtrmpdump(1)
invocation

	rtmpdump −r rtmp://server/myapp −y somefile

Note that only the shortform (single letter) options are supported.

ENVIRONMENT

HOME

The value of
$HOME
is used as the location for the
.swfinfo
file.

FILES

$HOME/.swfinfo

Cache of SWF Verification information

SEE ALSO

rtmpdump(1)

AUTHORS

Andrej Stepanchuk, Howard Chu, The Flvstreamer Team

<http://rtmpdump.mplayerhq.hu>


text:
'use strict';

const { createController } = require('../index');
const Sequelize = require('sequelize');
const supertest = require('supertest');
const assert = require('assert');
const db = require('./db');

describe('createChildren()', () => {
	before(async () => {
		await db.sequelize.sync({ force: true })
		await db.author.bulkCreate([
			{ id: 1, name: 'Bud' },
			{ id: 2, name: 'Frank' }
		]);
		await db.post.bulkCreate([
			{ id: 1, authorId: 1, title: 'One Title' },
			{ id: 2, authorId: 1, title: 'Two Titles' },
			{ id: 3, authorId: 2, title: 'Three Titles' }
		]);
	});

	describe('GET /<parent>/<id>/<child>', () => {
		it('should list posts by author', async () => {
			const app = require('express')();
			app.use('/authors', createController(db.author, {
				createChildren: true
			}));
			app.use(() => done(new Error()));
			const request = supertest(app);
			const response = await request.get('/authors/1/posts');
			assert.equal(response.statusCode, 200);
			assert.equal(response.body.posts.length, 2);
			assert.deepEqual(response.body.posts.map((x) => x.authorId), [1,1]);
		});
	});

	describe('GET /<parent>/<id>/<child>/<id>', () => {
		it('should return requested child', async () => {
			const app = require('express')();
			app.use('/authors', createController(db.author, {
				createChildren: true
			}));
			const request = supertest(app);
			const response = await request.get('/authors/1/posts/2');
			assert.equal(response.statusCode, 200);
			assert.equal(response.body.post.id, 2);
			assert.equal(response.body.post.authorId, 1);
		});

		it('should not return requested child from other parent', async () => {
			const app = require('express')();
			app.use('/authors', createController(db.author, {
				createChildren: true
			}));
			const request = supertest(app);
			const response = await request.get('/authors/2/posts/2');
			assert.equal(response.statusCode, 404);
		});
	});

	describe('POST /<parent>/<id>/<child>', () => {
		it('should create a child under parent', async () => {
			const app = require('express')();
			app.use('/authors', createController(db.author, {
				createChildren: true
			}));
			const request = supertest(app);
			const response = await request.post('/authors/1/posts')
				.set('Content-Type', 'application/json')
				.send({
					post: {
						title: 'Random Post',
						description: 'Test'
					}
				});
			assert.equal(response.statusCode, 201);
			assert.equal(response.body.post.authorId, 1);
			assert.equal(response.body.post.description, 'Test');
			assert.notEqual(response.body.post.id, 1);
		});

		it('should not allow setting record primary key', async () => {
			const app = require('express')();
			app.use('/authors', createController(db.author, {
				createChildren: true
			}));
			const request = supertest(app);
			const response = await request.post('/authors/1/posts')
				.set('Content-Type', 'application/json')
				.send({
					post: {
						id: 1,
						title: 'Random Post',
						description: 'Test'
					}
				});
			assert.equal(response.statusCode, 422);
		});
	});

	describe('PUT /<parent>/<id>/<child>/<id>', () => {
		it('should update the post', async () => {
			const app = require('express')();
			app.use('/authors', createController(db.author, {
				createChildren: true
			}));
			const request = supertest(app);
			const response = await request.put('/authors/1/posts/1')
				.set('Content-Type', 'application/json')
				.send({
					post: {
						title: 'Updated Title'
					}
				})
			assert.equal(response.statusCode, 200);
			assert.equal(response.body.post.title, 'Updated Title');
		});

		it('should not allow editing under different parent', async () => {
			const app = require('express')();
			app.use('/authors', createController(db.author, {
				createChildren: true
			}));
			const request = supertest(app);
			const response = await request.put('/authors/2/posts/1')
				.set('Content-Type', 'application/json')
				.send({
					post: {
						title: 'Updated Title'
					}
				})
			assert.equal(response.statusCode, 404);
		});
	});

	describe('DELETE /<parent>/<id>/<child>/<id>', () => {
		it('should delete the post', async () => {
			const app = require('express')();
			app.use('/authors', createController(db.author, {
				createChildren: true
			}));
			const request = supertest(app);
			const response = await request.delete('/authors/1/posts/1');
			assert.equal(response.statusCode, 200);
			assert.equal(response.body.status, 'ok');
		});

		it('should not allow delete under different parent', async () => {
			const app = require('express')();
			app.use('/authors', createController(db.author, {
				createChildren: true
			}));
			const request = supertest(app);
			const response = await request.delete('/authors/2/posts/1');
			assert.equal(response.statusCode, 404);
		});
	});
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using PayPal;
using PayPal.Api.Payments;

namespace FreeFoodUs.Models
{
    public class PayPalFacade
    {
        public static Tuple<string, string, PaypalTransaction> Pay(decimal value, string forWhat, string okUrl, string failUrl)
        {
            var tokenCredential = new OAuthTokenCredential("AWJSwhCGxY2l-VceOlwTqTc2AJilK0AaJqSIOQQACAwj-KdfGG2gOMeH8s4U",
                "EKq-ehBlniQi5j5OBk-o81JbK4H2j51XlYK8bJfXQ52f2Wh4FVVoLx5HNH5y");
            var accessToken = tokenCredential.GetAccessToken();
            Payment createdPayment = new Payment
             {
                 intent = "sale",
                 transactions =
                     new List<Transaction>
                    {
                        new Transaction
                        {
                            amount = new Amount
                            {
                                total = value.ToString("0.00"),
                                currency = "GBP"
                            },
                            description = forWhat
                        }
                    },
                 redirect_urls = new RedirectUrls
                 {
                     cancel_url = failUrl,
                     return_url = okUrl
                 },
                 payer = new Payer
                 {
                     payment_method = "paypal"
                 }

             }.Create(accessToken);
            var url = createdPayment.links.First(l => l.rel == "approval_url").href;
            var token = new Uri(url).ParseQueryString()["token"];
            return Tuple.Create(url, token, new PaypalTransaction { Price = value, Description = forWhat });
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single" >
        <item
            android:id="@+id/item_add_city"
            android:checked="false"
            android:icon="@drawable/ic_add_circle_outline_white_36dp"
            android:title="@string/add_city" />
        <item
            android:id="@+id/item_manage_city"
            android:checked="false"
            android:icon="@drawable/ic_location_city_white_36dp"
            android:title="@string/manage_city" />
        <item
            android:id="@+id/item_settings"
            android:checked="false"
            android:icon="@drawable/ic_settings_white_36dp"
            android:title="@string/settings" />
        <item
            android:id="@+id/item_share"
            android:checked="false"
            android:icon="@drawable/ic_share_white_36dp"
            android:title="@string/share"/>
    </group>
</menu>


text:
{% extends 'WebProfilerBundle:Profiler:layout.twig.html' %}

{% block head %}
    <link href="{{ asset('bundles/framework/css/exception.css') }}" rel="stylesheet" type="text/css" media="screen" />
{% endblock %}

{% block menu %}
{% if collector.hasexception %}
    1
{% endif %}

Exception
{% endblock %}

{% block panel %}

Exception

    {% if not collector.hasexception %}
        No exception was thrown and uncaught during the request.
    {% else %}
        {% render 'WebProfilerBundle:Exception:show' with { 'exception': collector.exception, 'format': 'html' } %}
    {% endif %}
{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;

namespace MIMWebClient
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapHttpRoute(
                name: "API Default",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
);

            routes.MapRoute(
                name: "Room",
                url: "{controller}/{action}/{region}/{area}/{areaId}",
                defaults: new { controller = "Home", action = "Index", region = UrlParameter.Optional, area = UrlParameter.Optional, areaId = UrlParameter.Optional }
            );

            routes.MapRoute(
                  "Default",
                 "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                new[] { "MIMWebClient.Controllers" }
            );
        }
    }
}


text:
package org.jwat.archive.common;

import java.io.IOException;
import java.util.Arrays;

import org.jwat.common.ByteCountingPushBackInputStream;
import org.jwat.common.Scheme;

/**
 * Unified archive reader factory base.
 *
 * @author nicl
 */
public class ReaderFactoryAbstract {

    /** GZip header magic number. */
    protected static final int GZIP_MAGIC = 0x8b1f;

    /** An ARC version block starts with this string. */
    protected static final String ARC_MAGIC_HEADER = "filedesc:";

    /**
     * A WARC header block starts with this string including trailing version
     * information.
     * */
    protected static final String WARC_MAGIC_HEADER = "WARC/";

    /**
     * Private constructor to enforce factory methods.
     */
    protected ReaderFactoryAbstract() {
    }

    /**
     * Check head of PushBackInputStream for a GZip magic number.
     * The state of the PushBackInputStream is the same after the
     * call as before the call.
     * @param pbin PushBackInputStream with GZip entries
     * @return boolean indicating presence of a GZip magic number
     * @throws IOException if an i/o error occurs while examining head of stream
     */
    public static boolean isGzipped(ByteCountingPushBackInputStream pbin) throws IOException {
        if (pbin == null) {
            throw new IllegalArgumentException("'pbin'is null!");
        }
        byte[] magicBytes = new byte[2];
        int magicNumber = 0xdeadbeef;
        // Look for the leading 2 magic bytes in front of every valid GZip entry.
        int read = pbin.readFully(magicBytes);
        if (read == 2) {
            magicNumber = ((magicBytes[1] & 255) << 8) | (magicBytes[0] & 255);
        }
        if (read > 0) {
            pbin.unread(magicBytes, 0, read);
        }
        return (magicNumber == GZIP_MAGIC);
    }

    /**
     * Check head of PushBackInputStream for an ARC file identifier.
     * The identifier for ARC files is "filedesc:" in the beginning.
     * @param pbin PushBackInputStream with an ARC version block
     * @return boolean indicating presence of an ARC file identifier
     * @throws IOException if an i/o error occurs while examining head of stream
     */
    public static boolean isArcFile(ByteCountingPushBackInputStream pbin) throws IOException {
        byte[] streamBytes = new byte[ARC_MAGIC_HEADER.length()];
        byte[] arcBytes = ARC_MAGIC_HEADER.getBytes();
        // Look for an ARC file identifier in the beginning of the stream.
        pbin.peek(streamBytes);
        return (Arrays.equals(arcBytes, streamBytes));
    }

    /**
     * Check head of PushBackInputStream for an ARC record identifier.
     * The identifier for ARC files is "filedesc:" in the beginning.
     * @param pbin PushBackInputStream with an ARC version block
     * @return boolean indicating presence of an ARC file identifier
     * @throws IOException if an i/o error occurs while examining head of stream
     */
    public static boolean isArcRecord(ByteCountingPushBackInputStream pbin) throws IOException {
        byte[] streamBytes = new byte[32];
        // Look for a valid scheme in the beginning of the stream.
        pbin.peek(streamBytes);
        return Scheme.startsWithScheme(streamBytes);
    }

    /**
     * Check head of PushBackInputStream for a WARC file identifier.
     * The identifier for WARC files is "WARC/" in the beginning.
     * @param pbin PushBackInputStream with WARC records
     * @return boolean indicating presence of a WARC file identifier
     * @throws IOException if an i/o error occurs while examining head of stream
     */
    public static boolean isWarcFile(ByteCountingPushBackInputStream pbin) throws IOException {
        return isWarcRecord(pbin);
    }

    /**
     * Check head of PushBackInputStream for a WARC record identifier.
     * The identifier for WARC records is "WARC/" in the beginning.
     * @param pbin PushBackInputStream with WARC records
     * @return boolean indicating presence of a WARC magic number
     * @throws IOException if an i/o error occurs while examining head of stream
     */
    public static boolean isWarcRecord(ByteCountingPushBackInputStream pbin) throws IOException {
        byte[] streamBytes = new byte[WARC_MAGIC_HEADER.length()];
        byte[] warcBytes = WARC_MAGIC_HEADER.getBytes();
        // Look for the leading magic bytes in front of every valid WARC record.
        pbin.peek(streamBytes);
        return (Arrays.equals(warcBytes, streamBytes));
    }

}


text:
package rest;

import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import tm.FestiAndesMaster;
import vos.Ciudad;
import vos.ListaCiudad;

@Path("ciudades")
public class FestiAndesCiudadServices {

	@Context
	private ServletContext context;

	private String getPath() {
		return context.getRealPath("WEB-INF/ConnectionData");
	}

	private String doErrorMessage(Exception e){
		return "{ \"ERROR\": \""+ e.getMessage() + "\"}" ;
	}

	// --------------------------------------------------------------------------------------------------------------------------------------
	// getCiudades --------------------------------------------------------------------------------------------------------------------------
	// --------------------------------------------------------------------------------------------------------------------------------------
	@GET
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getCiudades() {
		FestiAndesMaster tm = new FestiAndesMaster(getPath());
		ListaCiudad ciudades;
		try {
			ciudades = tm.darCiudades();
		}
		catch (Exception e) {
			return Response.status(500).entity(doErrorMessage(e)).build();
		}
		return Response.status(200).entity(ciudades).build();
	}

	// --------------------------------------------------------------------------------------------------------------------------------------
	// getCiudadName ------------------------------------------------------------------------------------------------------------------------
	// --------------------------------------------------------------------------------------------------------------------------------------
	@GET
	@Path("/ciudades/{name}")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getCiudadName(@javax.ws.rs.PathParam("name") String name) {
		FestiAndesMaster tm = new FestiAndesMaster(getPath());
		ListaCiudad ciudades;
		try {
			if (name == null || name.length() == 0) throw new Exception("Nombre del actor no valido");
			ciudades = tm.buscarCiudadPorNombre(name);
		}
		catch (Exception e) {
			return Response.status(500).entity(doErrorMessage(e)).build();
		}
		return Response.status(200).entity(ciudades).build();
	}

	// --------------------------------------------------------------------------------------------------------------------------------------
	// addCiudad ----------------------------------------------------------------------------------------------------------------------------
	// --------------------------------------------------------------------------------------------------------------------------------------
	@POST
	@Path("/ciudad")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response addCiudad(Ciudad ciudad) {
		FestiAndesMaster tm = new FestiAndesMaster(getPath());
		try {
			tm.addCiudad(ciudad);
		}
		catch (Exception e) {
			return Response.status(500).entity(doErrorMessage(e)).build();
		}
		return Response.status(200).entity(ciudad).build();
	}

	// --------------------------------------------------------------------------------------------------------------------------------------
	// updateCiudad -------------------------------------------------------------------------------------------------------------------------
	// --------------------------------------------------------------------------------------------------------------------------------------
	@PUT
	@Path("/ciudad")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateCiudad(Ciudad ciudad) {
		FestiAndesMaster tm = new FestiAndesMaster(getPath());
		try {
			tm.updateCiudad(ciudad);
		}
		catch (Exception e) {
			return Response.status(500).entity(doErrorMessage(e)).build();
		}
		return Response.status(200).entity(ciudad).build();
	}

	// --------------------------------------------------------------------------------------------------------------------------------------
	// deleteCiudad -------------------------------------------------------------------------------------------------------------------------
	// --------------------------------------------------------------------------------------------------------------------------------------
    @DELETE
	@Path("/ciudad")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response deleteCiudad(Ciudad ciudad) {
		FestiAndesMaster tm = new FestiAndesMaster(getPath());
		try {
			tm.deleteCiudad(ciudad);
		}
		catch (Exception e) {
			return Response.status(500).entity(doErrorMessage(e)).build();
		}
		return Response.status(200).entity(ciudad).build();
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KickBrain
{
	/// <summary>
	/// This class takes care of maintaining a list of all signal generators and trigger generators (sources)
	/// that are available. It has methods to query, add, reorder and remove sources
	/// </summary>
	public class SourceManager
	{
		// All IInputs
		public List<IInput> InputChannels;

		// All ISignalChannels
		List<ISignalChannel> SignalChannels;

		// All ITriggerChannels
		List<IEventChannel> EventChannels;

		// All OutputPorts
		List<OutputPort> OutputPorts;

		public SourceManager()
		{
			InputChannels = new List<IInput>();
			SignalChannels = new List<ISignalChannel>();
			EventChannels = new List<IEventChannel>();
			OutputPorts = new List<OutputPort>();
		}

		// ------------ Input Channels ------------

		public void AddInputChannel(IInput input)
		{
			if (InputChannels.Contains(input))
				return;

			InputChannels.Add(input);
		}

		public void RemoveInputChannel(int index)
		{
			if(InputChannels.Count > index)
				InputChannels.RemoveAt(index);
		}

		// ------------ Signal Channels ------------

		public void AddSignalChannel(ISignalChannel channel)
		{
			if (SignalChannels.Contains(channel))
				return;

			SignalChannels.Add(channel);
		}

		public List<ISignalChannel> GetSignalChannels()
		{
			// returns a shallow copy
			return SignalChannels.Select(x => x).ToList();
		}

		public bool SetChannelName(ISignalChannel channel, string name)
		{
			if (channel.ChannelName == name)
				return true;

			var channels = Brain.KB.Sources.GetSignalChannels();
			bool contains = channels.Any(x => x.ChannelName == name);
			if (contains)
			{
				Brain.KB.ShowError("There is already a channel with the name " + name + ".\nNames must be unique, please select another one.");
				return false;
			}
			else
			{
				channel.ChannelName = name;
				return true;
			}
		}

		/// <summary>
		/// Get all signals of all channels
		/// </summary>
		/// <returns></returns>
		public List<Signal> GetAllSignals()
		{
			var output = new List<Signal>();
			foreach(var channel in SignalChannels)
			{
				foreach(var signal in channel.Signals)
				{
					output.Add(signal);
				}
			}

			return output;
		}

		public void SetSignalChannelIndex(ISignalChannel channel, int newIndex)
		{
			if (!SignalChannels.Contains(channel))
				Brain.KB.ShowError("This channel is not registered in the Channel Manager!");
		}

		public int GetSignalChannelIndex(ISignalChannel channel)
		{
			if (channel == null)
				return 99999;
			if (!SignalChannels.Contains(channel))
				return 99999;
			else
				return SignalChannels.IndexOf(channel);
		}

		// ------------ Triggers ------------

		public void AddTriggerChannel(IEventChannel trigger)
		{
			if (EventChannels.Contains(trigger))
				return;

			EventChannels.Add(trigger);
		}

		public List<IEventChannel> GetTriggerChannels()
		{
			// returns a shallow copy
			return EventChannels.Select(x => x).ToList();
		}

		/// <summary>
		/// Get all signals of all channels
		/// </summary>
		/// <returns></returns>
		public List<Event> GetAllEvents()
		{
			var output = new List<Event>();
			foreach (var channel in EventChannels)
			{
				foreach (var signal in channel.Events)
				{
					output.Add(signal);
				}
			}

			return output;
		}

		/// <summary>
		/// Detaches the specified delegate from any and all events registered with this source manager
		/// </summary>
		/// <param name="dele"></param>
		public void DetachAllEvents(Action<object> dele)
		{
			GetAllEvents().ForEach(x => x.Remove(dele));
		}

		// ------------------- Output Ports ------------------

		public void AddOutputPort(OutputPort port)
		{
			if (OutputPorts.Contains(port))
				return;

			OutputPorts.Add(port);
		}

		public List<OutputPort> GetOutputPorts()
		{
			// returns a shallow copy
			return OutputPorts.Select(x => x).ToList();
		}

		public void RemoveOutputPort(OutputPort port)
		{
			if (!OutputPorts.Contains(port))
				return;

			OutputPorts.Remove(port);
			port.Dispose();
		}

	}
}


text:
#import "AutoScalingResponse.h"

#import "AutoScalingLimitExceededException.h"
#import "AutoScalingAlreadyExistsException.h"

/**
 * Create Launch Configuration
 */
@interface AutoScalingCreateLaunchConfigurationResponse:AutoScalingResponse
{
}

@end


text:
package com.boxupp.db.beans;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "sync_folder")
public class SyncFoldersBean {
	public static final String MACHINE_ID_FIELD_NAME = "machineID";

	@DatabaseField(canBeNull = false, generatedId= true, useGetSet = true)
	private Integer syncFolderID;

	@DatabaseField(foreign = true,foreignAutoRefresh=true, maxForeignAutoRefreshLevel=1, columnName = MACHINE_ID_FIELD_NAME)
	MachineConfigurationBean machineConfig;

	@DatabaseField(useGetSet = true)
	private String hostFolder;

	@DatabaseField(useGetSet = true)
	private String vmFolder;

	public Integer getSyncFolderID() {
		return syncFolderID;
	}
	public void setSyncFolderID(Integer syncFolderID) {
		this.syncFolderID = syncFolderID;
	}
	public String getHostFolder() {
		return hostFolder;
	}
	public void setHostFolder(String hostFolder) {
		this.hostFolder = hostFolder;
	}
	public String getVmFolder() {
		return vmFolder;
	}
	public void setVmFolder(String vmFolder) {
		this.vmFolder = vmFolder;
	}
	public MachineConfigurationBean getMachineConfig() {
		return machineConfig;
	}
	public void setMachineConfig(MachineConfigurationBean machineConfig) {
		this.machineConfig = machineConfig;
	}

}


text:
<?php

namespace Aisel\FixtureBundle\DataFixtures\ORM;

use Aisel\FixtureBundle\Model\XMLFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

/**
 * Cart fixtures
 * @author Ivan Proskuryakov <volgodark@gmail.com>
 */
class LoadCartData extends XMLFixture implements OrderedFixtureInterface
{

    protected $fixturesName = array('global/aisel_cart.xml');

    /**
     * Cart manager
     * @return \Aisel\CartBundle\Manager\CartManager
     */
    protected function getCartManager()
    {
        return $this->container->get('aisel.cart.manager');
    }

    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        foreach ($this->fixtureFiles as $file) {
            if (file_exists($file)) {
                $contents = file_get_contents($file);
                $XML = simplexml_load_string($contents);

                foreach ($XML->database->table as $table) {
                    $user = $this->getReference('user_' . $table->column[1]);
                    $product = $this->getReference('product_' . $table->column[3]);
                    $cartItem = $this->getCartManager()->addProductToCart(
                        $user,
                        $product->getId(),
                        (int) $table->column[2]
                    );
                    $this->addReference('cart_' . $table->column[0], $cartItem);
                }
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 400;
    }
}