text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.binghamton.jhelp.ast</title>
<meta name="date" content="2021-03-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.binghamton.jhelp.ast

Interface Summary

Interface
Description

ASTVisitor

Interface for visiting AST nodes

Visitable

An interface to represent objects able to be visited by a visitor

Class Summary

Class
Description

AbstractBodyDeclaration

An abstract class representing a non-constructible (abstract) body
 declaration.

AccessExpression

A class representing a Java symbol access expression
 e.g.

Annotation

A class representing the use of Java annotation
 e.g.

AnnotationDeclaration

A class representing a Java annotation type declaration
 e.g.

ArrayAccessExpression

A class representing a Java array access
 e.g.

ArrayConstruction

A class representing the construction of a new array
 e.g.

ArrayInitializer

A class representing a Java array initializer
 e.g.

ArrayTypeExpression

A class denoting an array type
 e.g.

AssertStatement

A class representing a Java assert statement
 e.g.

AssignmentExpression

A class representing a Java assignment expression
 e.g.

ASTNode

Base class representing a node in the AST

BinaryExpression

A class representing a Java binary expression
 e.g.

Block

Class representing a scope-delimiting block,
 e.g.

BodyDeclaration

An abstract class representing a body declaration.

BodyLevelVisitor

The body level Visitor for visiting the member declarations contained within
 body declarations

CallExpression

A class representing a Java method call, including explicit constructor calls
 e.g.

CaseBlock

A class representing a Java case block of a Java switch statement
 e.g.

CastExpression

A class representing a Java cast expression
 e.g.

CatchBlock

A class representing a Java catch block
 e.g.

ClassDeclaration

A class representing a Java class declaration

ClassLiteralExpression

A class representing a Java class literal
 e.g.

CodeLevelVisitor

The code (lowest) level Visitor for visiting each line of code contained
 within all declarations.

CompilationUnit

A class representing a Java compilation unit (file)

ConcreteBodyDeclaration

An abstract class representing a concrete body declaration.

Declaration

Abstract base class for all Java declarations
 e.g.

DeclarationLevelVisitor

The top level Visitor for visiting top-level declarations and adding them to
 the symbol table

Dimension

Class representing a dimension
 e.g.

DimensionExpression

Class representing a dimension expression
 e.g.

EmptyStatement

A class to represent an empty statement in Java
 e.g.

EmptyVisitor

Base class for visiting AST nodes

EnumConstant

A class representing a constant in a Java enum
 e.g.

EnumDeclaration

A class representing enum declarations

Expression

Base class representing a Java syntactic expression

FileLevelVisitor

The file (highest) level Visitor for visiting packages, imports, and
 symbol names.

ForEachStatement

A class representing a Java for-each statement
 e.g.

ForStatement

A class representing a Java for statement
 e.g.

IfElseStatement

A class representing a Java if/else statement
 {@code if (True) { ...

ImportStatement

A class representing a Java import statement
 e.g.

InstantiationExpression

A class representing an instantion (constructor call) with possible anonymous
 inner class.

InterfaceDeclaration

A class representing the declaration of a Java interface

JumpStatement

A class representing a Java jump statement.

LabelStatement

A class representing a Java label statement
 e.g.

LambdaExpression

A class representing a Java lambda expression
 e.g.

LiteralExpression

A class representing a Java literal
 e.g.

LocalClassDeclaration

A class representing the declaration of a local class
 e.g.

LocalVariableStatement

A class representing a statement declaring local variables
 e.g.

MethodDeclaration

A class representing the declaration of a Java method

MethodReferenceExpression

A class representing a Java8 method reference
 e.g.

NameExpression

A class representing Java identifiers over several categories.

NilBlock

A class representing an absent block.

NilExpression

A class representing an absent expression

NonNullVisitor

A testing class to ensure AST is built without any null values

PackageStatement

A class representing a Java package statement
 e.g.

ParamExpression

A class representing a parameterized type expression
 e.g.

PrintVisitor

Visits and prints each AST node

QualifiableExpression

A class representing Expression that may be qualified in the future by a
 qualifying Expression.

ReturnStatement

A class representing a Java return statement
 e.g.

Statement

Base class representing a Java syntactic statement

SwitchStatement

A class representing a Java switch statement
 e.g.

SynchronizedBlock

A class representing a Java synchronized block
 e.g.

TernaryExpression

A class representing a Java ternary expression
 e.g.

ThrowStatement

A class representing a Java throws statement
 e.g.

TryCatchBlock

A class representing a Java try/catch/finally block
 e.g.

TypeArgument

A class representing a Java type argument
 e.g.

TypeParameter

A class representing a Java type parameter
 e.g.

UnaryExpression

A class representing a Java unary expression
 e.g.

VariableDeclaration

A class representing a Java variable declaration

WhileStatement

A class representing a Java (do) while statement
 e.g.

Enum Summary

Enum
Description

BinaryOperator

Enum representing valid binary operators
 e.g.

BodyDeclaration.Kind

An enum enumerating the kinds of BodyDeclarations

NameExpression.Kind

An enum enumerating the kinds of NameExpressions

UnaryOperator

Enum representing valid unary operators
 e.g.

Visitable.Order

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _getIterator2 = require('babel-runtime/core-js/get-iterator');

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _Particle = require('./Particle');

var _Particle2 = _interopRequireDefault(_Particle);

var _Library = require('./Library');

var _Library2 = _interopRequireDefault(_Library);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Client = function () {
	function Client(_ref) {
		var auth = _ref.auth,
		    _ref$api = _ref.api,
		    api = _ref$api === undefined ? new _Particle2.default() : _ref$api;
		(0, _classCallCheck3.default)(this, Client);

		(0, _assign2.default)(this, { auth: auth, api: api });
	}

	(0, _createClass3.default)(Client, [{
		key: 'ready',
		value: function ready() {
			return Boolean(this.auth);
		}

		/**
   * Get firmware library objects
   * @param  {Object} query The query parameters for libraries. See Particle.listLibraries
   * @return {Promise}
   */

	}, {
		key: 'libraries',
		value: function libraries() {
			var _this = this;

			var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

			return this.api.listLibraries((0, _assign2.default)({}, query, { auth: this.auth })).then(function (payload) {
				var libraries = payload.body.data || [];
				return libraries.map(function (l) {
					return new _Library2.default(_this, l);
				});
			});
		}

		/**
   * Get one firmware library object
   * @param  {String} name Name of the library to fetch
   * @param  {Object} query The query parameters for libraries. See Particle.getLibrary
   * @return {Promise}
   */

	}, {
		key: 'library',
		value: function library(name) {
			var _this2 = this;

			var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

			return this.api.getLibrary((0, _assign2.default)({}, query, { name: name, auth: this.auth })).then(function (payload) {
				var library = payload.body.data || {};
				return new _Library2.default(_this2, library);
			});
		}

		/**
   * Get list of library versions
   * @param  {String} name Name of the library to fetch
   * @param  {Object} query The query parameters for versions. See Particle.getLibraryVersions
   * @return {Promise}
   */

	}, {
		key: 'libraryVersions',
		value: function libraryVersions(name) {
			var _this3 = this;

			var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

			return this.api.getLibraryVersions((0, _assign2.default)({}, query, { name: name, auth: this.auth })).then(function (payload) {
				var libraries = payload.body.data || [];
				return libraries.map(function (l) {
					return new _Library2.default(_this3, l);
				});
			});
		}

		/**
   * Contribute a new library version
   * @param  {Buffer} archive The compressed archive with the library source
   * @return {Promise}
   */

	}, {
		key: 'contributeLibrary',
		value: function contributeLibrary(archive) {
			var _this4 = this;

			return this.api.contributeLibrary({ archive: archive, auth: this.auth }).then(function (payload) {
				var library = payload.body.data || {};
				return new _Library2.default(_this4, library);
			}, function (error) {
				_this4._throwError(error);
			});
		}

		/**
   * Make the the most recent private library version public
   * @param  {string} name The name of the library to publish
   * @return {Promise} To publish the library
   */

	}, {
		key: 'publishLibrary',
		value: function publishLibrary(name) {
			var _this5 = this;

			return this.api.publishLibrary({ name: name, auth: this.auth }).then(function (payload) {
				var library = payload.body.data || {};
				return new _Library2.default(_this5, library);
			}, function (error) {
				_this5._throwError(error);
			});
		}

		/**
   * Delete an entire published library
   * @param  {String} $0.name Name of the library to delete
   * @param  {String} $0.force Key to force deleting a public library
   * @return {Promise}
   */

	}, {
		key: 'deleteLibrary',
		value: function deleteLibrary(_ref2) {
			var _this6 = this;

			var name = _ref2.name,
			    version = _ref2.version,
			    force = _ref2.force;

			return this.api.deleteLibrary({ name: name, force: force, auth: this.auth }).then(function (payload) {
				return true;
			}, function (error) {
				_this6._throwError(error);
			});
		}
	}, {
		key: '_throwError',
		value: function _throwError(error) {
			if (error.body && error.body.errors) {
				var errorMessages = error.body.errors.map(function (e) {
					return e.message;
				}).join('\n');
				throw new Error(errorMessages);
			}
			throw error;
		}
	}, {
		key: 'downloadFile',
		value: function downloadFile(url) {
			return this.api.downloadFile({ url: url });
		}

		/**
   * @param {Object} files Object containing files to be compiled
   * @param {Number} platformId Platform id number of the device you are compiling for
   * @param {String} targetVersion System firmware version to compile against
   * @return {Promise}
   * @deprecated Will be removed in 6.5
   */

	}, {
		key: 'compileCode',
		value: function compileCode(files, platformId, targetVersion) {
			return this.api.compileCode({ files: files, platformId: platformId, targetVersion: targetVersion, auth: this.auth });
		}

		/**
   * @param {String} $0.deviceId Device ID or Name
   * @param {Boolean} $0.signal   Signal on or off
   * @return {Promise}
   * @deprecated Will be removed in 6.5
   */

	}, {
		key: 'signalDevice',
		value: function signalDevice(_ref3) {
			var signal = _ref3.signal,
			    deviceId = _ref3.deviceId;

			return this.api.signalDevice({ signal: signal, deviceId: deviceId, auth: this.auth });
		}

		/**
   * @return {Promise}
   * @deprecated Will be removed in 6.5
   */

	}, {
		key: 'listDevices',
		value: function listDevices() {
			return this.api.listDevices({ auth: this.auth });
		}

		/**
   * @return {Promise}
   * @deprecated Will be removed in 6.5
   */

	}, {
		key: 'listBuildTargets',
		value: function listBuildTargets() {
			return this.api.listBuildTargets({ onlyFeatured: true, auth: this.auth }).then(function (payload) {
				var targets = [];
				var _iteratorNormalCompletion = true;
				var _didIteratorError = false;
				var _iteratorError = undefined;

				try {
					for (var _iterator = (0, _getIterator3.default)(payload.body.targets), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
						var target = _step.value;
						var _iteratorNormalCompletion2 = true;
						var _didIteratorError2 = false;
						var _iteratorError2 = undefined;

						try {
							for (var _iterator2 = (0, _getIterator3.default)(target.platforms), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
								var platform = _step2.value;

								targets.push({
									version: target.version,
									platform: platform,
									prerelease: target.prereleases.indexOf(platform) > -1,
									firmware_vendor: target.firmware_vendor
								});
							}
						} catch (err) {
							_didIteratorError2 = true;
							_iteratorError2 = err;
						} finally {
							try {
								if (!_iteratorNormalCompletion2 && _iterator2.return) {
									_iterator2.return();
								}
							} finally {
								if (_didIteratorError2) {
									throw _iteratorError2;
								}
							}
						}
					}
				} catch (err) {
					_didIteratorError = true;
					_iteratorError = err;
				} finally {
					try {
						if (!_iteratorNormalCompletion && _iterator.return) {
							_iterator.return();
						}
					} finally {
						if (_didIteratorError) {
							throw _iteratorError;
						}
					}
				}

				return targets;
			}, function (error) {});
		}
	}, {
		key: 'trackingIdentity',
		value: function trackingIdentity() {
			var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
			    _ref4$full = _ref4.full,
			    full = _ref4$full === undefined ? false : _ref4$full,
			    context = _ref4.context;

			return this.api.trackingIdentity({ full: full, context: context, auth: this.auth }).then(function (payload) {
				return payload.body;
			});
		}
	}]);
	return Client;
}();

exports.default = Client;
module.exports = exports['default'];
//# sourceMappingURL=Client.js.map

redpajama_set_name: RedPajamaGithub


text:
const div = document.createElement('div');
export const shadowDomV1 = !!div.attachShadow; // eslint-disable-line import/prefer-default-export


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import controller.MobilePartnerController;
import db_pojo.MessageDefine;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.swing.table.AbstractTableModel;
import jpa_controllers.MessageDefineJpaController;

/**
 *
 * @author Shanaka P
 */
public class PredefinesTableModel extends AbstractTableModel {

    List<MessageDefine> modelData = new ArrayList<>();
    String colNames[] = {"Id", "Type", "Notifiying Color"};
    Class<?> colClasses[] = {Integer.class, String.class, Integer.class};
    private static PredefinesTableModel singletonForm = new PredefinesTableModel();

    private PredefinesTableModel() {
        modelData.addAll(getAllPredefines());
    }

    public void addAllData() {
        modelData.clear();
        modelData.addAll(getAllPredefines());
    }

    @Override
    public int getRowCount() {
        return modelData.size();
    }

    @Override
    public int getColumnCount() {
        return colNames.length;
    }

    @Override
    public String getColumnName(int column) {
        return colNames[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return colClasses[columnIndex];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if (columnIndex == 0) {
            return modelData.get(rowIndex).getId();
        }
        if (columnIndex == 1) {
            return modelData.get(rowIndex).getTypeName();
        }
        if (columnIndex == 2) {
            return Integer.parseInt(modelData.get(rowIndex).getDescription());
        }

        return null;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        if (columnIndex == 0) {
            modelData.get(rowIndex).setId((Integer) aValue);
        }
        if (columnIndex == 1) {
            modelData.get(rowIndex).setTypeName((String) aValue);
        }
        if (columnIndex == 2) {
            modelData.get(rowIndex).setDescription((String) aValue);
        }

        fireTableCellUpdated(rowIndex, columnIndex);
    }

    public static PredefinesTableModel getInstance() {
        return singletonForm;
    }

    @Override
    public void fireTableDataChanged() {
        super.fireTableDataChanged();
    }

    private Collection<? extends MessageDefine> getAllPredefines() {
        try {
            EntityManagerFactory emf = MobilePartnerController.getInstance().getEntityManagerFactory();
            MessageDefineJpaController defineController = new MessageDefineJpaController(emf);

            return defineController.findMessageDefineEntities();
        } catch (Exception ex) {
            Logger.getLogger(PredefinesTableModel.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

    }

}


text:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Common;
using SharpCompress.Common.Rar;
using SharpCompress.Common.Rar.Headers;
using SharpCompress.Compressor.Rar;

namespace SharpCompress.Archive.Rar
{
    public class RarArchiveEntry : RarEntry, IArchiveEntry
    {
        private readonly ICollection<RarFilePart> parts;
        private readonly RarArchive archive;

        internal RarArchiveEntry(RarArchive archive, IEnumerable<RarFilePart> parts)
        {
            this.parts = parts.ToList<RarFilePart>();

            this.archive = archive;
        }

        public override CompressionType CompressionType
        {
            get { return CompressionType.Rar; }
        }

        public IArchive Archive
        {
            get
            {
                return archive;
            }
        }

        internal override IEnumerable<FilePart> Parts
        {
            get { return parts.Cast<FilePart>(); }
        }

        internal override FileHeader FileHeader
        {
            get { return parts.First().FileHeader; }
        }

        public override long Crc
        {
            get
            {
                CheckIncomplete();
                return parts.Select(fp => fp.FileHeader)
                    .Single(fh => !fileFlags_HasFlag(fh.FileFlags,FileFlags.SPLIT_AFTER)).FileCRC;
            }
        }

        private bool fileFlags_HasFlag(FileFlags fileFlags1, FileFlags fileFlags2) {
           return (fileFlags1&fileFlags2)==fileFlags2;
        }

        public override long Size
        {
            get
            {
                CheckIncomplete();
                return parts.First().FileHeader.UncompressedSize;
            }
        }

        public override long CompressedSize
        {
            get
            {
                CheckIncomplete();
                return parts.Aggregate(0L, (total, fp) => { return total + fp.FileHeader.CompressedSize; });
            }
        }

        public Stream OpenEntryStream()
        {
            return new RarStream(archive.Unpack, FileHeader,
                                 new MultiVolumeReadOnlyStream(Parts.Cast<RarFilePart>(), archive));
        }

        public bool IsComplete
        {
            get { return parts.Select(fp => fp.FileHeader).Any(fh => !fileFlags_HasFlag(fh.FileFlags,FileFlags.SPLIT_AFTER)); }
        }

        private void CheckIncomplete()
        {
            if (!IsComplete)
            {
                throw new IncompleteArchiveException("ArchiveEntry is incomplete and cannot perform this operation.");
            }
        }
    }
}


text:
(function () {
    'use strict';

    process.env.NODE_ENV = 'test';

    var chai = require("chai"),
        should = chai.should(),
        expect = chai.expect,
        supertest = require("supertest-as-promised"),
        baseUrl = 'http://localhost:3000',
        request = supertest.agent(baseUrl),
        mongoose  = require('mongoose'),
        databaseConfig = require('../lib/configs/database.config'),
        applicationConfig = require('../lib/configs/application.config'),
        Promise = require("bluebird"),
        HTTPStatus = require('http-status'),
        async = require('async'),
        dbUrl = "mongodb://" + databaseConfig.test.username + ":" + databaseConfig.test.password + "@" + databaseConfig.test.host + ":" + databaseConfig.test.port + "/" + databaseConfig.test.dbName;

    var loginUrl = '/api/login/';
    var imagePathUrl = ['/home/lakhe/Desktop/nodebeats/images/mountain_nepal.png', '/home/lakhe/Desktop/nodebeats/images/homepage.png'];
    var loginObj = {
        username : applicationConfig.user.defaultUsername,
        password : applicationConfig.user.defaultPassword
    };
    var documentPathUrl = ['/home/lakhe/Desktop/nodebeats/documents/proposal_example.pdf', '/home/lakhe/Desktop/nodebeats/documents/googleanalytics-jsonconfig.json'];
    var apiFileDeleteUrl = '/api/deletefile';

    beforeEach(function (done) {
        function clearDB() {
            for (var i in mongoose.connection.collections) {
                if (mongoose.connection.collections.hasOwnProperty(i)) {
                    mongoose.connection.collections[i].remove();
                }
            }
            return done();
        }

        function reconnect() {
            mongoose.connect(dbUrl, function (err) {
                if (err) {
                    throw err;
                }
                return clearDB();
            });
        }

        function checkState() {
            switch (mongoose.connection.readyState) {
                case 0:
                    reconnect();
                    break;
                case 1:
                    clearDB();
                    break;
                default:
                    process.nextTick(checkState);
            }
        }
        checkState();
    });

    describe('User login', function () {
        it('should return authentication token along with logged in user object', function (done) {
            request
                .post(loginUrl)
                .set('Accept', 'application/x-www-form-urlencoded')
                .send(loginObj)
                .expect('Content-Type', /json/)
                .then(function (response) {
                    expect(response.statusCode).to.equal(HTTPStatus.OK);
                    expect(response.body).to.have.property("success");
                    expect(response.body.success).to.equal(true);
                    expect(response.body).to.have.property("token");
                    expect(response.body.message).to.not.equal("");
                    expect(response.body).to.have.property("userInfo");
                    expect(response.body.userInfo).to.be.an('object');
                    expect(response.body.userInfo).to.have.property("userRole");
                    expect(response.body.userInfo.userRole).to.equal('superadmin');

                    var accessToken = response.body.token;

                    require('./integrationtests/cloudinary.setting.integration.test')(expect, request, accessToken);
                    require('./integrationtests/email.service.configure.integration.test')(expect, request, accessToken);
                    require('./integrationtests/email.template.integration.test')(expect, request, accessToken);
                    require('./integrationtests/role.management.integration.test')(expect, request, accessToken);
                    require('./integrationtests/apiAccess.management.integration.test')(expect, request, accessToken);
                    require('./integrationtests/html.module.integration.test')(expect, request, accessToken);
                    require('./integrationtests/google.maps.integration.test')(expect, request, accessToken);
                    require('./integrationtests/comment.setting.integration.test')(expect, request, accessToken);
                    require('./integrationtests/google.analytics.integration.test')(expect, request, documentPathUrl, apiFileDeleteUrl, accessToken);
                    require('./integrationtests/organization.info.integration.test')(expect, request, imagePathUrl, accessToken);
                    require('./integrationtests/contact.integration.test')(expect, request, accessToken);
                    require('./integrationtests/event.integration.test')(expect, request, imagePathUrl, apiFileDeleteUrl, accessToken);
                    require('./integrationtests/image.slider.integration.test')(expect, request, imagePathUrl, accessToken);
                    require('./integrationtests/news.integration.test')(expect, request, imagePathUrl, accessToken);
                    require('./integrationtests/image.gallery.integration.test')(expect, request, imagePathUrl, accessToken);
                    require('./integrationtests/testimonial.integration.test')(expect, request, imagePathUrl, accessToken);
                    require('./integrationtests/team.management.integration.test')(expect, request, imagePathUrl, accessToken);
                    require('./integrationtests/blog.integration.test')(expect, request, imagePathUrl, documentPathUrl, accessToken);
                    require('./integrationtests/user.integration.test')(expect, request, imagePathUrl, accessToken);
                    require('./integrationtests/partner.integration.test')(expect, request, imagePathUrl, accessToken);
                    require('./integrationtests/two.factor.authentication.integration.test')(expect, request, accessToken);
                    require('./integrationtests/error.log.integration.test')(expect, request, accessToken);
                    require('./integrationtests/login.integration.test')(expect, request, loginObj, loginUrl, accessToken);
                    require('./integrationtests/authorization.token.integration.test')(expect, request, loginObj, loginUrl);
                    done();
                });
        });
    });

    afterEach(function (done) {
        mongoose.disconnect();
        return done();
    });

    after(function (done) {
        mongoose.connect(dbUrl, function(){
            mongoose.connection.db.dropDatabase(function(){
                done();
            });
        });
    });

})();


text:
package com.datamountaineer.streamreactor.connect.hbase.config

import java.util

import com.datamountaineer.streamreactor.connect.config.base.traits._
import org.apache.kafka.common.config.ConfigDef
import org.apache.kafka.common.config.ConfigDef.{Importance, Type}

object HBaseConfig {
  val config: ConfigDef = new ConfigDef()
    .define(HBaseConfigConstants.COLUMN_FAMILY, Type.STRING, Importance.HIGH, HBaseConfigConstants.COLUMN_FAMILY_DOC,
      "Connection", 1, ConfigDef.Width.MEDIUM, HBaseConfigConstants.COLUMN_FAMILY)
    .define(HBaseConfigConstants.KCQL_QUERY, Type.STRING, Importance.HIGH, HBaseConfigConstants.KCQL_QUERY,
      "Connection", 2, ConfigDef.Width.MEDIUM, HBaseConfigConstants.KCQL_QUERY)
    .define(HBaseConfigConstants.ERROR_POLICY, Type.STRING, HBaseConfigConstants.ERROR_POLICY_DEFAULT, Importance.HIGH, HBaseConfigConstants.ERROR_POLICY_DOC,
      "Connection", 3, ConfigDef.Width.MEDIUM, HBaseConfigConstants.ERROR_POLICY)
    .define(HBaseConfigConstants.ERROR_RETRY_INTERVAL, Type.INT, HBaseConfigConstants.ERROR_RETRY_INTERVAL_DEFAULT, Importance.MEDIUM, HBaseConfigConstants.ERROR_RETRY_INTERVAL_DOC,
      "Connection", 4, ConfigDef.Width.MEDIUM, HBaseConfigConstants.ERROR_RETRY_INTERVAL)
    .define(HBaseConfigConstants.NBR_OF_RETRIES, Type.INT, HBaseConfigConstants.NBR_OF_RETIRES_DEFAULT, Importance.MEDIUM, HBaseConfigConstants.NBR_OF_RETRIES_DOC,
      "Connection", 5, ConfigDef.Width.MEDIUM, HBaseConfigConstants.NBR_OF_RETRIES)
    .define(HBaseConfigConstants.PROGRESS_COUNTER_ENABLED, Type.BOOLEAN, HBaseConfigConstants.PROGRESS_COUNTER_ENABLED_DEFAULT,
      Importance.MEDIUM, HBaseConfigConstants.PROGRESS_COUNTER_ENABLED_DOC,
      "Metrics", 1, ConfigDef.Width.MEDIUM, HBaseConfigConstants.PROGRESS_COUNTER_ENABLED_DISPLAY)
}

/**
  *
HbaseSinkConfig

  *
  * Holds config, extends AbstractConfig.
  **/
case class HBaseConfig(props: util.Map[String, String])
  extends BaseConfig(HBaseConfigConstants.CONNECTOR_PREFIX, HBaseConfig.config, props)
    with KcqlSettings
    with ErrorPolicySettings
    with NumberRetriesSettings


text:
<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
        <meta name="keywords" content="" />
        <meta name="description" content="运行后台进程有很多好处,但是坑也很多" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title> Android后台单进程保活处理实践  </title>
        <link rel="stylesheet" href="http://localhost:4000/css/default.css" type="text/css" />
        <link rel="stylesheet" href="http://localhost:4000/css/small.css" type="text/css" media="(max-width: 720px)"/>
        <link rel="stylesheet" href="http://localhost:4000/css/syntax.css" type="text/css" />
        <link rel="shortcut icon" href="http://localhost:4000/favicon.ico" type="image/x-icon" />

        首页
        分类
        维基
        链接
        关于

SITEMAP订阅

 Android后台单进程保活处理实践

0x00、如何实现一个后台进程

自定义的 Service,实现相应的业务逻辑

在 Manifest 文件中配置 Service 组件,需配置 process 属性,然后指定 intent-filter 和 priority 属性,如下示例:

<service
	android:name="com.stfl.SSClientService"
	android:process=":ssclient">
			<intent-filter android:priority="1000">
		<action android:name="io.telebox.ssclient.service" />
	</intent-filter>
</service>

priority 属性值越大,优先级越高。

0x01、如何重启进程

重写 Service 的 OnDestroy 方法。主要逻辑是监听到 Service 被杀掉后,发送一个 Broadcast 通知,重新启动 Service 进程。根据不同的业务逻辑,可以选择是否调用 killProcess 方法,彻底清理所有进程资源。可参考如下:

	@Override
	public void onDestroy() {
        super.onDestroy();
        logger.info("SSClient is stop!");
        // 根据业务需要决定是否调用killProcess,这里我是推荐调用此方法,清理资源。
        Process.killProcess(Process.myPid());
        // 服务关掉通知
        Intent intent = new Intent(SSClientReceiver.ACTION_DISCONNECTED);
        intent.setComponent(new ComponentName(getPackageName(), SSClientReceiver.class.getName()));
        sendBroadcast(intent);
	}

需要注意的是,需要设置 component 否则在8.0手机会出现 Background execution not allowed的错误。

0x02、实现监听进程通知

继承 BroadcastReceiver 并实现 onReceive()方法。实现参考:

	@Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action == null) {
            action = "";
        }
        switch (action) {
            case ACTION_START:
                Log.d("SSClient", "start by receiver.");
                SSClientService.startSService(context);
                break;
            case ACTION_DISCONNECTED:
                Log.d("SSClient", "disconnected,restart by receiver.");
                SSClientService.startSService(context);
                onSSClientDisconnected();
                break;
            case ACTION_CONNECTED:
                onSSClientConnected();
                break;
        }
    }

在接收到ACTION_START或ACTION_DISCONNECTED时,就调用启动Service的方法。

在 Manifest 文件中配置 Broadcast ,示例参考:

	<receiver
		android:name="com.stfl.SSClientReceiver"
		android:enabled="true">
		<intent-filter>
			<action android:name="io.telebox.ssclient.start" />
		</intent-filter>
	</receiver>

0x03、需要注意的问题

配置Service优先级priority属性,尽量提高Service的优先级

Android 8.0手机发送通知时会出现 Background execution not allowed的错误,intent要设置component。

Intent intent = new Intent("receiver-action-string");
intent.setComponent(new ComponentName(getPackageName(),"receiver-class-name"));
sendBroadcast(intent);

Android 8.0后台服务启动时出现java.lang.IllegalStateException: Not allowed to start service Intent错误。

// 1.启动Service的方法中修改为
Intent service = new Intent(SSClientService.ACTION);
service.setPackage(context.getPackageName());
// kill:java.lang.IllegalStateException: Not allowed to start service Intent
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
	context.startForegroundService(service);
} else {
    context.startService(service);
}
// 2.在Service类中调用startForeground方法
public void onCreate() {
	super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    	startForeground(Integer.MAX_VALUE, new Notification());
       	//这个id不要和应用内的其他同志id一样,不行就写 int.maxValue()
      	//context.startForeground(SERVICE_ID, builder.getNotification());
    }
}

Android 8.1出现android.app.RemoteServiceException: Bad notification for startForeground

修改startForeground方法。

	@TargetApi(Build.VERSION_CODES.O)
    private void startForeground() {
        int nid = 1010;
        String channelId = createNotificationChannel();

        Notification.Builder builder = new Notification.Builder(this, channelId);
        Notification notification = builder.setOngoing(false)
                .setSmallIcon(R.mipmap.ic_small_logo)
                .setPriority(Notification.PRIORITY_MIN)

                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(nid, notification);
    }

    @TargetApi(Build.VERSION_CODES.O)
    private String createNotificationChannel() {
        String channelId = "my_service";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        service.createNotificationChannel(chan);
        return channelId;
    }

Published on Sep 21, 2018 in categories

                上一篇
                搭建Telegram代理服务

                下一篇
                Android NDK开发CMakeLists文件配置解析

        <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">

Powered by Jekyll and Theme by solid


text:
(function (angular) {
    'use strict';

    //// JavaScript Code ////
    function commandRunningCtrl($scope,$interval,$log,$routeParams,CodeineService,Constants,ApplicationFocusService) {
        /*jshint validthis:true */
        var vm  = this;
        vm.projectName = $routeParams.project_name;
        vm.limit = 10;

        CodeineService.getRunningCommands().success(function(data) {
            vm.history = data;
        });
        var maxUpdatesNotInFocus = 100;
        var intervalTriggered = 0;

        var intervalHandler = $interval(function() {
            if (!ApplicationFocusService.isInFocus() && intervalTriggered > maxUpdatesNotInFocus) {
                return;
            }
            intervalTriggered++;
            $.ajax( {
                type: 'GET',
                url: Constants.CODEINE_WEB_SERVER + '/api/commands-status',
                success: function(response) {
                    if  ((vm.history.length !== response.length) || (angular.toJson(vm.history) !== angular.toJson(response))) {
                        $scope.$apply(function() {
                            vm.history = response;
                        });
                    }
                },
                error:  function(err) {
                    $log.error('commandRunningCtrl: ' + err);
                },
                dataType: 'json'
            });
        },5000,0,false);

        $scope.$on('$destroy', function() {
            $interval.cancel(intervalHandler);
        });
    }

    //// Angular Code ////
    angular.module('codeine').controller('commandRunningCtrl', commandRunningCtrl);

})(angular);


text:
.DEFAULT_GOAL := help

export GO111MODULE := off
export PATH := $(CURDIR)/.go-packages/bin:$(PATH)

# This is a magic code to output help message at default
# see https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
.PHONY:help
help:
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'

.PHONY:dev
dev: ## Build dev binary
	@bash -c $(CURDIR)/build/scripts/dev.sh

.PHONY:dist
dist: ## Build dist binaries
	@bash -c $(CURDIR)/build/scripts/dist.sh

.PHONY:packaging
packaging: ## Create packages (now support RPM only)
	@bash -c $(CURDIR)/build/scripts/packaging.sh

.PHONY:clean
clean: ## Clean the built binaries.
	@bash -c $(CURDIR)/build/scripts/clean.sh

.PHONY:fmt
fmt:
	go fmt $$(go list ./... | grep -v vendor)

.PHONY:test
test: ## Run all tests
	go test -cover $$(go list ./... | grep -v vendor)

.PHONY:testv
testv: ## Run all tests with verbose outputing.
	go test -v -cover $$(go list ./... | grep -v vendor)

.PHONY: installtools
installtools: ## Install dev tools
	GOPATH=$(CURDIR)/.go-packages && \
      go get -u github.com/golang/dep/cmd/dep && \
      go get -u github.com/mitchellh/gox && \
      go get -u github.com/axw/gocov/gocov && \
      go get -u gopkg.in/matm/v1/gocov-html

.PHONY:deps
deps: ## Install dependences.
	PATH=$(CURDIR)/.go-packages/bin:${PATH} && dep ensure

.PHONY:resetdeps
resetdeps: ## reset dependences.
	rm -rf Gopkg.*
	rm -rf vendor
	dep init
	dep ensure


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Photobooth - Oxford, Hong-Kong, Reunion Island</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">

    <link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="vendor/simple-line-icons/css/simple-line-icons.css">
    <link rel="stylesheet" href="vendor/device-mockups/device-mockups.min.css">

    <link href="css/new-age.min.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Photo Booth

                        Book now!

                        Features

                        Contact

+44 (0) 7554 938537

Looking to incorporate a photo booth into your event? Look no further!

                            Book it with us!

Book your photobooth with us!

We are based in Oxfordshire and ready to please you!

                                                <form class="inline" role="form">
                                                    Phone number
                                                    <input type="phone" class="form-control transparent" placeholder="Landline, mobile? We don't mind!">
                                                  <button type="submit" class="btn btn-outline btn-xl page-scroll">Request a call</button>
                                                </form>

What do we provide? Unlimited fun!

Check out what we can do for you!

Share

with us, you can share the fun on the social media!

Flexible

We can add  image, video, animation, or anything else in the screen!

The best gift you can do!

Let your friends go back home with souvenirs!

Open memories

Your friends/customers will have memories left at home!

Stop waiting.
Enjoy!

                Book your slot!

We  new friends!

© 2016 Start Photobooth. All Rights Reserved.


text:
#ifndef BASE_WIN_WIN_UTIL_H_
#define BASE_WIN_WIN_UTIL_H_

#include "base/basictypes.h"
#include "base/base_export.h"
#include <string>

namespace base {
namespace win {

BASE_EXPORT std::string ErrCodeToMessage(uint32 err_code);
}  // namespace win
}  // namespace base

#endif  // BASE_WIN_WIN_UTIL_H_


text:
<?php
/**
 * Test the handler filter
 *
 * @author Aaron Saray
 */

namespace AaronSaray\PHProblemLogger\Tests;

use AaronSaray\PHProblemLogger\HandlerFilter;

/**
 * Class HandlerFilterTest
 * @package AaronSaray\PHProblemLogger\Tests\Unit
 */
class HandlerFilterTest extends \PHPUnit_Framework_TestCase
{
    public function testAllFilter()
    {
        $filter = HandlerFilter::all();
        $this->assertTrue(is_callable($filter));
        $this->assertEquals(['item'], $filter(['item']));
    }

    public function testNoneFilter()
    {
        $filter = HandlerFilter::none();
        $this->assertTrue(is_callable($filter));
        $this->assertNull($filter(['item']));
    }
}


text:
<?php
namespace App\Models;

use App\Models\Model;
use Config\Services;

class AdminRoleAccessModel extends Model{

    protected $table = 'admin_role_access';

    protected $primaryKey = false;

    protected $returnType = 'array';

    protected $allowedFields = ['role_id', 'auth'];

    protected $useTimestamps = false;

    public function __construct(&$db = null, $config = null, $validation = null){

        parent::__construct($db, $config, $validation);

    }

}


text:
/**
 *    Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior
 *    University
 *
 *    Licensed under the Apache License, Version 2.0 (the "License"); you may
 *    not use this file except in compliance with the License. You may obtain
 *    a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *    License for the specific language governing permissions and limitations
 *    under the License.
 **/

package org.openflow.protocol;

import java.util.LinkedList;
import java.util.List;

import org.jboss.netty.buffer.ChannelBuffer;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.factory.OFActionFactory;
import org.openflow.protocol.factory.OFActionFactoryAware;
import org.openflow.util.U16;

import edu.princeton.cs.policy.adv.PolicyCompositionUtil;

/**
 * Represents an ofp_flow_mod message
 *
 * @author David Erickson (daviderickson@cs.stanford.edu)
 *
 */
public class OFFlowMod extends OFMessage implements OFActionFactoryAware,
        Cloneable {
    public static int MINIMUM_LENGTH = 72;

    public static final short OFPFC_ADD = 0; /* New flow. */
    public static final short OFPFC_MODIFY = 1; /* Modify all matching flows. */
    public static final short OFPFC_MODIFY_STRICT = 2; /*
                                                        * Modify entry strictly
                                                        * matching wildcards
                                                        */
    public static final short OFPFC_DELETE = 3; /* Delete all matching flows. */
    public static final short OFPFC_DELETE_STRICT = 4; /*
                                                        * Strictly match
                                                        * wildcards and
                                                        * priority.
                                                        */

    // Open Flow Flow Mod Flags. Use "or" operation to set multiple flags
    public static final short OFPFF_SEND_FLOW_REM = 0x1; // 1 << 0
    public static final short OFPFF_CHECK_OVERLAP = 0x2; // 1 << 1
    public static final short OFPFF_EMERG = 0x4; // 1 << 2

    protected OFActionFactory actionFactory;
    protected OFMatch match;
    protected long cookie;
    protected short command;
    protected short idleTimeout;
    protected short hardTimeout;
    protected short priority;
    protected int bufferId;
    protected short outPort;
    protected short flags;
    protected List<OFAction> actions;

    protected OFMatch actApplyMatch;

    public OFFlowMod() {
        super();
        this.outPort = OFPort.OFPP_NONE.getValue();
        this.type = OFType.FLOW_MOD;
        this.length = U16.t(OFFlowMod.MINIMUM_LENGTH);
        this.actApplyMatch = null;
    }

    /**
     * Get buffer_id
     *
     * @return
     */
    public int getBufferId() {
        return this.bufferId;
    }

    /**
     * Set buffer_id
     *
     * @param bufferId
     */
    public OFFlowMod setBufferId(final int bufferId) {
        this.bufferId = bufferId;
        return this;
    }

    /**
     * Get cookie
     *
     * @return
     */
    public long getCookie() {
        return this.cookie;
    }

    /**
     * Set cookie
     *
     * @param cookie
     */
    public OFFlowMod setCookie(final long cookie) {
        this.cookie = cookie;
        return this;
    }

    /**
     * Get command
     *
     * @return
     */
    public short getCommand() {
        return this.command;
    }

    /**
     * Set command
     *
     * @param command
     */
    public OFFlowMod setCommand(final short command) {
        this.command = command;
        return this;
    }

    /**
     * Get flags
     *
     * @return
     */
    public short getFlags() {
        return this.flags;
    }

    /**
     * Set flags
     *
     * @param flags
     */
    public OFFlowMod setFlags(final short flags) {
        this.flags = flags;
        return this;
    }

    /**
     * Get hard_timeout
     *
     * @return
     */
    public short getHardTimeout() {
        return this.hardTimeout;
    }

    /**
     * Set hard_timeout
     *
     * @param hardTimeout
     */
    public OFFlowMod setHardTimeout(final short hardTimeout) {
        this.hardTimeout = hardTimeout;
        return this;
    }

    /**
     * Get idle_timeout
     *
     * @return
     */
    public short getIdleTimeout() {
        return this.idleTimeout;
    }

    /**
     * Set idle_timeout
     *
     * @param idleTimeout
     */
    public OFFlowMod setIdleTimeout(final short idleTimeout) {
        this.idleTimeout = idleTimeout;
        return this;
    }

    /**
     * Gets a copy of the OFMatch object for this FlowMod, changes to this
     * object do not modify the FlowMod
     *
     * @return
     */
    public OFMatch getMatch() {
        return this.match;
    }

    public OFMatch getActApplyMatch() {
    	if (this.actApplyMatch == null) {
    		this.actApplyMatch = PolicyCompositionUtil.actApplyMatch(this.match, this.actions);
    	}
    	return this.actApplyMatch;
    }

    /**
     * Set match
     *
     * @param match
     */
    public OFFlowMod setMatch(final OFMatch match) {
        this.match = match;
        return this;
    }

    /**
     * Get out_port
     *
     * @return
     */
    public short getOutPort() {
        return this.outPort;
    }

    /**
     * Set out_port
     *
     * @param outPort
     */
    public OFFlowMod setOutPort(final short outPort) {
        this.outPort = outPort;
        return this;
    }

    /**
     * Set out_port
     *
     * @param port
     */
    public OFFlowMod setOutPort(final OFPort port) {
        this.outPort = port.getValue();
        return this;
    }

    /**
     * Get priority
     *
     * @return
     */
    public short getPriority() {
        return this.priority;
    }

    /**
     * Set priority
     *
     * @param priority
     */
    public OFFlowMod setPriority(final short priority) {
        this.priority = priority;
        return this;
    }

    /**
     * Returns read-only copies of the actions contained in this Flow Mod
     *
     * @return a list of ordered OFAction objects
     */
    public List<OFAction> getActions() {
        return this.actions;
    }

    /**
     * Sets the list of actions this Flow Mod contains
     *
     * @param actions
     *            a list of ordered OFAction objects
     */
    public OFFlowMod setActions(final List<OFAction> actions) {
        this.actions = actions;
        return this;
    }

    @Override
    public void readFrom(final ChannelBuffer data) {
        super.readFrom(data);
        if (this.match == null) {
            this.match = new OFMatch();
        }
        this.match.readFrom(data);
        this.cookie = data.readLong();
        this.command = data.readShort();
        this.idleTimeout = data.readShort();
        this.hardTimeout = data.readShort();
        this.priority = data.readShort();
        this.bufferId = data.readInt();
        this.outPort = data.readShort();
        this.flags = data.readShort();
        if (this.actionFactory == null) {
            throw new RuntimeException("OFActionFactory not set");
        }
        this.actions = this.actionFactory.parseActions(data, this.getLengthU()
                - OFFlowMod.MINIMUM_LENGTH);
    }

    @Override
    public void writeTo(final ChannelBuffer data) {
        super.writeTo(data);
        this.match.writeTo(data);
        data.writeLong(this.cookie);
        data.writeShort(this.command);
        data.writeShort(this.idleTimeout);
        data.writeShort(this.hardTimeout);
        data.writeShort(this.priority);
        data.writeInt(this.bufferId);
        data.writeShort(this.outPort);
        data.writeShort(this.flags);
        if (this.actions != null) {
            for (final OFAction action : this.actions) {
                action.writeTo(data);
            }
        }
    }

    @Override
    public void setActionFactory(final OFActionFactory actionFactory) {
        this.actionFactory = actionFactory;
    }

    @Override
    public int hashCode() {
        final int prime = 227;
        int result = super.hashCode();
        result = prime * result
                + (this.actions == null ? 0 : this.actions.hashCode());
        result = prime * result + this.bufferId;
        result = prime * result + this.command;
        result = prime * result + (int) (this.cookie ^ this.cookie >>> 32);
        result = prime * result + this.flags;
        result = prime * result + this.hardTimeout;
        result = prime * result + this.idleTimeout;
        result = prime * result
                + (this.match == null ? 0 : this.match.hashCode());
        result = prime * result + this.outPort;
        result = prime * result + this.priority;
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (!super.equals(obj)) {
            return false;
        }
        if (!(obj instanceof OFFlowMod)) {
            return false;
        }
        final OFFlowMod other = (OFFlowMod) obj;
        if (this.actions == null) {
            if (other.actions != null) {
                return false;
            }
        } else if (!this.actions.equals(other.actions)) {
            return false;
        }
        if (this.bufferId != other.bufferId) {
            return false;
        }
        if (this.command != other.command) {
            return false;
        }
        if (this.cookie != other.cookie) {
            return false;
        }
        if (this.flags != other.flags) {
            return false;
        }
        if (this.hardTimeout != other.hardTimeout) {
            return false;
        }
        if (this.idleTimeout != other.idleTimeout) {
            return false;
        }
        if (this.match == null) {
            if (other.match != null) {
                return false;
            }
        } else if (!this.match.equals(other.match)) {
            return false;
        }
        if (this.outPort != other.outPort) {
            return false;
        }
        if (this.priority != other.priority) {
            return false;
        }
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#clone()
     */
    @Override
    public OFFlowMod clone() throws CloneNotSupportedException {
        final OFMatch neoMatch = this.match.clone();
        final OFFlowMod flowMod = (OFFlowMod) super.clone();
        flowMod.setMatch(neoMatch);
        final List<OFAction> neoActions = new LinkedList<OFAction>();
        for (final OFAction action : this.actions) {
            neoActions.add(action.clone());
        }
        flowMod.setActions(neoActions);
        return flowMod;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        /*return "OFFlowMod [actionFactory=" + this.actionFactory + ", actions="
                + this.actions + ", bufferId=" + this.bufferId + ", command="
                + this.command + ", cookie=" + Long.toHexString(this.cookie)
                + ", flags=" + this.flags + ", hardTimeout=" + this.hardTimeout
                + ", idleTimeout=" + this.idleTimeout + ", match=" + this.match
                + ", outPort=" + this.outPort + ", priority=" + this.priority
                + ", length=" + this.length + ", type=" + this.type
                + ", version=" + this.version + ", xid=" + this.xid + "]";*/
    	return "priority=" + this.priority + ", match=" + this.match + ", actions=" + this.actions;
    }
}


text:
import os
import binascii
import urllib2
import json

def make_random_id():
    bits = os.urandom(8)
    return binascii.hexlify(bits)

class CommonEqualityMixin(object):

    def __eq__(self, other):
        return (isinstance(other, self.__class__)
            and self.__dict__ == other.__dict__)

    def __ne__(self, other):
        return not self.__eq__(other)

class HTTPInterface(object): # TODO test it

    def poll(self, url):
        try:
            return json.loads(urllib2.urlopen(url).read())
        except ValueError:
            return [] # bad data
        except urllib2.URLError:
            return [] # connection issues

    def post(self, url, content):
        data = json.dumps(content)
        return urllib2.urlopen(url, data).read() == 'Success'


text:
package blockcutter

import (
	"bytes"
	"testing"

	"github.com/hyperledger/fabric/orderer/common/filter"
	mocksharedconfig "github.com/hyperledger/fabric/orderer/mocks/sharedconfig"
	cb "github.com/hyperledger/fabric/protos/common"
	ab "github.com/hyperledger/fabric/protos/orderer"
	logging "github.com/op/go-logging"
)

func init() {
	logging.SetLevel(logging.DEBUG, "")
}

type isolatedCommitter struct{}

func (ic isolatedCommitter) Isolated() bool { return true }

func (ic isolatedCommitter) Commit() {}

type mockIsolatedFilter struct{}

func (mif *mockIsolatedFilter) Apply(msg *cb.Envelope) (filter.Action, filter.Committer) {
	if bytes.Equal(msg.Payload, isolatedTx.Payload) {
		return filter.Accept, isolatedCommitter{}
	}
	return filter.Forward, nil
}

type mockRejectFilter struct{}

func (mrf mockRejectFilter) Apply(message *cb.Envelope) (filter.Action, filter.Committer) {
	if bytes.Equal(message.Payload, badTx.Payload) {
		return filter.Reject, nil
	}
	return filter.Forward, nil
}

type mockAcceptFilter struct{}

func (mrf mockAcceptFilter) Apply(message *cb.Envelope) (filter.Action, filter.Committer) {
	if bytes.Equal(message.Payload, goodTx.Payload) {
		return filter.Accept, filter.NoopCommitter
	}
	return filter.Forward, nil
}

func getFilters() *filter.RuleSet {
	return filter.NewRuleSet([]filter.Rule{
		&mockIsolatedFilter{},
		&mockRejectFilter{},
		&mockAcceptFilter{},
	})
}

var badTx = &cb.Envelope{Payload: []byte("BAD")}
var goodTx = &cb.Envelope{Payload: []byte("GOOD")}
var goodTxLarge = &cb.Envelope{Payload: []byte("GOOD"), Signature: make([]byte, 1000)}
var isolatedTx = &cb.Envelope{Payload: []byte("ISOLATED")}
var unmatchedTx = &cb.Envelope{Payload: []byte("UNMATCHED")}

func TestNormalBatch(t *testing.T) {
	filters := getFilters()
	maxMessageCount := uint32(2)
	absoluteMaxBytes := uint32(1000)
	preferredMaxBytes := uint32(100)
	r := NewReceiverImpl(&mocksharedconfig.Manager{BatchSizeVal: &ab.BatchSize{MaxMessageCount: maxMessageCount, AbsoluteMaxBytes: absoluteMaxBytes, PreferredMaxBytes: preferredMaxBytes}}, filters)

	batches, committers, ok := r.Ordered(goodTx)

	if batches != nil || committers != nil {
		t.Fatalf("Should not have created batch")
	}

	if !ok {
		t.Fatalf("Should have enqueued message into batch")
	}

	batches, committers, ok = r.Ordered(goodTx)

	if batches == nil || committers == nil {
		t.Fatalf("Should have created batch")
	}

	if !ok {
		t.Fatalf("Should have enqueued second message into batch")
	}

}

func TestBadMessageInBatch(t *testing.T) {
	filters := getFilters()
	maxMessageCount := uint32(2)
	absoluteMaxBytes := uint32(1000)
	preferredMaxBytes := uint32(100)
	r := NewReceiverImpl(&mocksharedconfig.Manager{BatchSizeVal: &ab.BatchSize{MaxMessageCount: maxMessageCount, AbsoluteMaxBytes: absoluteMaxBytes, PreferredMaxBytes: preferredMaxBytes}}, filters)

	batches, committers, ok := r.Ordered(badTx)

	if batches != nil || committers != nil {
		t.Fatalf("Should not have created batch")
	}

	if ok {
		t.Fatalf("Should not have enqueued bad message into batch")
	}

	batches, committers, ok = r.Ordered(goodTx)

	if batches != nil || committers != nil {
		t.Fatalf("Should not have created batch")
	}

	if !ok {
		t.Fatalf("Should have enqueued good message into batch")
	}

	batches, committers, ok = r.Ordered(badTx)

	if batches != nil || committers != nil {
		t.Fatalf("Should not have created batch")
	}

	if ok {
		t.Fatalf("Should not have enqueued second bad message into batch")
	}
}

func TestUnmatchedMessageInBatch(t *testing.T) {
	filters := getFilters()
	maxMessageCount := uint32(2)
	absoluteMaxBytes := uint32(1000)
	preferredMaxBytes := uint32(100)
	r := NewReceiverImpl(&mocksharedconfig.Manager{BatchSizeVal: &ab.BatchSize{MaxMessageCount: maxMessageCount, AbsoluteMaxBytes: absoluteMaxBytes, PreferredMaxBytes: preferredMaxBytes}}, filters)

	batches, committers, ok := r.Ordered(unmatchedTx)

	if batches != nil || committers != nil {
		t.Fatalf("Should not have created batch")
	}

	if ok {
		t.Fatalf("Should not have enqueued unmatched message into batch")
	}

	batches, committers, ok = r.Ordered(goodTx)

	if batches != nil || committers != nil {
		t.Fatalf("Should not have created batch")
	}

	if !ok {
		t.Fatalf("Should have enqueued good message into batch")
	}

	batches, committers, ok = r.Ordered(unmatchedTx)

	if batches != nil || committers != nil {
		t.Fatalf("Should not have created batch from unmatched message")
	}

	if ok {
		t.Fatalf("Should not have enqueued second bad message into batch")
	}
}

func TestIsolatedEmptyBatch(t *testing.T) {
	filters := getFilters()
	maxMessageCount := uint32(2)
	absoluteMaxBytes := uint32(1000)
	preferredMaxBytes := uint32(100)
	r := NewReceiverImpl(&mocksharedconfig.Manager{BatchSizeVal: &ab.BatchSize{MaxMessageCount: maxMessageCount, AbsoluteMaxBytes: absoluteMaxBytes, PreferredMaxBytes: preferredMaxBytes}}, filters)

	batches, committers, ok := r.Ordered(isolatedTx)

	if !ok {
		t.Fatalf("Should have enqueued isolated message")
	}

	if len(batches) != 1 || len(committers) != 1 {
		t.Fatalf("Should created new batch, got %d and %d", len(batches), len(committers))
	}

	if len(batches[0]) != 1 || len(committers[0]) != 1 {
		t.Fatalf("Should have had one isolatedTx in the second batch got %d and %d", len(batches[1]), len(committers[0]))
	}

	if !bytes.Equal(batches[0][0].Payload, isolatedTx.Payload) {
		t.Fatalf("Should have had the isolated tx in the first batch")
	}
}

func TestIsolatedPartialBatch(t *testing.T) {
	filters := getFilters()
	maxMessageCount := uint32(2)
	absoluteMaxBytes := uint32(1000)
	preferredMaxBytes := uint32(100)
	r := NewReceiverImpl(&mocksharedconfig.Manager{BatchSizeVal: &ab.BatchSize{MaxMessageCount: maxMessageCount, AbsoluteMaxBytes: absoluteMaxBytes, PreferredMaxBytes: preferredMaxBytes}}, filters)

	batches, committers, ok := r.Ordered(goodTx)

	if batches != nil || committers != nil {
		t.Fatalf("Should not have created batch")
	}

	if !ok {
		t.Fatalf("Should have enqueued good message into batch")
	}

	batches, committers, ok = r.Ordered(isolatedTx)

	if !ok {
		t.Fatalf("Should have enqueued isolated message")
	}

	if len(batches) != 2 || len(committers) != 2 {
		t.Fatalf("Should have created two batches, got %d and %d", len(batches), len(committers))
	}

	if len(batches[0]) != 1 || len(committers[0]) != 1 {
		t.Fatalf("Should have had one normal tx in the first batch got %d and %d committers", len(batches[0]), len(committers[0]))
	}

	if !bytes.Equal(batches[0][0].Payload, goodTx.Payload) {
		t.Fatalf("Should have had the normal tx in the first batch")
	}

	if len(batches[1]) != 1 || len(committers[1]) != 1 {
		t.Fatalf("Should have had one isolated tx in the second batch got %d and %d committers", len(batches[1]), len(committers[1]))
	}

	if !bytes.Equal(batches[1][0].Payload, isolatedTx.Payload) {
		t.Fatalf("Should have had the isolated tx in the second batch")
	}
}

func TestBatchSizePreferredMaxBytesOverflow(t *testing.T) {
	filters := getFilters()

	goodTxBytes := messageSizeBytes(goodTx)

	// set preferred max bytes such that 10 goodTx will not fit
	preferredMaxBytes := goodTxBytes*10 - 1

	// set message count > 9
	maxMessageCount := uint32(20)

	r := NewReceiverImpl(&mocksharedconfig.Manager{BatchSizeVal: &ab.BatchSize{MaxMessageCount: maxMessageCount, AbsoluteMaxBytes: preferredMaxBytes * 2, PreferredMaxBytes: preferredMaxBytes}}, filters)

	// enqueue 9 messages
	for i := 0; i < 9; i++ {
		batches, committers, ok := r.Ordered(goodTx)
		if batches != nil || committers != nil {
			t.Fatalf("Should not have created batch")
		}
		if !ok {
			t.Fatalf("Should have enqueued message into batch")
		}
	}

	// next message should create batch
	batches, committers, ok := r.Ordered(goodTx)

	if batches == nil || committers == nil {
		t.Fatalf("Should have created batch")
	}

	if len(batches) != 1 || len(committers) != 1 {
		t.Fatalf("Should have created one batch, got %d and %d", len(batches), len(committers))
	}

	if len(batches[0]) != 9 || len(committers[0]) != 9 {
		t.Fatalf("Should have had nine normal tx in the batch got %d and %d committers", len(batches[0]), len(committers[0]))
	}
	if !ok {
		t.Fatalf("Should have enqueued the tenth message into batch")
	}

	// force a batch cut
	messageBatch, committerBatch := r.Cut()

	if messageBatch == nil || committerBatch == nil {
		t.Fatalf("Should have created batch")
	}

	if len(messageBatch) != 1 || len(committerBatch) != 1 {
		t.Fatalf("Should have had one tx in the batch, got %d and %d", len(batches), len(committers))
	}

}

func TestBatchSizePreferredMaxBytesOverflowNoPending(t *testing.T) {
	filters := getFilters()

	goodTxLargeBytes := messageSizeBytes(goodTxLarge)

	// set preferred max bytes such that 1 goodTxLarge will not fit
	preferredMaxBytes := goodTxLargeBytes - 1

	// set message count > 1
	maxMessageCount := uint32(20)

	r := NewReceiverImpl(&mocksharedconfig.Manager{BatchSizeVal: &ab.BatchSize{MaxMessageCount: maxMessageCount, AbsoluteMaxBytes: preferredMaxBytes * 3, PreferredMaxBytes: preferredMaxBytes}}, filters)

	// submit large message
	batches, committers, ok := r.Ordered(goodTxLarge)

	if batches == nil || committers == nil {
		t.Fatalf("Should have created batch")
	}

	if len(batches) != 1 || len(committers) != 1 {
		t.Fatalf("Should have created one batch, got %d and %d", len(batches), len(committers))
	}

	if len(batches[0]) != 1 || len(committers[0]) != 1 {
		t.Fatalf("Should have had one normal tx in the batch got %d and %d committers", len(batches[0]), len(committers[0]))
	}
	if !ok {
		t.Fatalf("Should have enqueued the message into batch")
	}

}


text:
@implementation UIView (ZYExtension)

-(void)setCenterX:(CGFloat)centerX
{
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}

-(CGFloat)centerX
{
    return self.center.x;
}

-(void)setCenterY:(CGFloat)centerY
{
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}

-(CGFloat)centerY
{
    return self.center.y;
}

-(void)setSize:(CGSize)size
{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

-(CGSize)size
{
    return self.frame.size;
}

-(void)setWidth:(CGFloat)width
{
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

-(void)setHeight:(CGFloat)height
{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

-(void)setX:(CGFloat)x
{
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

-(void)setY:(CGFloat)y
{
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

-(CGFloat)width
{
    return self.frame.size.width;
}

-(CGFloat)height
{
    return self.frame.size.height;
}

-(CGFloat)x
{
    return self.frame.origin.x;
}

-(CGFloat)y
{
    return self.frame.origin.y;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)right {
    return self.frame.origin.x + self.frame.size.width;
}

- (void)setRight:(CGFloat)right {
    CGRect frame = self.frame;
    frame.origin.x = right - frame.size.width;
    self.frame = frame;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}

- (void)setBottom:(CGFloat)bottom {
    CGRect frame = self.frame;
    frame.origin.y = bottom - frame.size.height;
    self.frame = frame;
}

- (void)removeAllSubViews {
    for (UIView *subView in self.subviews) {
        [subView removeFromSuperview];
    }
}

@end


text:
#ifndef INCLUDE_path_h__
#define INCLUDE_path_h__

#include "common.h"
#include "buffer.h"
#include "vector.h"

/**
 * Path manipulation utils
 *
 * These are path utilities that munge paths without actually
 * looking at the real filesystem.
 */

/*
 * The dirname() function shall take a pointer to a character string
 * that contains a pathname, and return a pointer to a string that is a
 * pathname of the parent directory of that file. Trailing '/' characters
 * in the path are not counted as part of the path.
 *
 * If path does not contain a '/', then dirname() shall return a pointer to
 * the string ".". If path is a null pointer or points to an empty string,
 * dirname() shall return a pointer to the string "." .
 *
 * The `git_path_dirname` implementation is thread safe. The returned
 * string must be manually free'd.
 *
 * The `git_path_dirname_r` implementation writes the dirname to a `git_buf`
 * if the buffer pointer is not NULL.
 * It returns an error code < 0 if there is an allocation error, otherwise
 * the length of the dirname (which will be > 0).
 */
extern char *git_path_dirname(const char *path);
extern int git_path_dirname_r(git_buf *buffer, const char *path);

/*
 * This function returns the basename of the file, which is the last
 * part of its full name given by fname, with the drive letter and
 * leading directories stripped off. For example, the basename of
 * c:/foo/bar/file.ext is file.ext, and the basename of a:foo is foo.
 *
 * Trailing slashes and backslashes are significant: the basename of
 * c:/foo/bar/ is an empty string after the rightmost slash.
 *
 * The `git_path_basename` implementation is thread safe. The returned
 * string must be manually free'd.
 *
 * The `git_path_basename_r` implementation writes the basename to a `git_buf`.
 * It returns an error code < 0 if there is an allocation error, otherwise
 * the length of the basename (which will be >= 0).
 */
extern char *git_path_basename(const char *path);
extern int git_path_basename_r(git_buf *buffer, const char *path);

/* Return the offset of the start of the basename.  Unlike the other
 * basename functions, this returns 0 if the path is empty.
 */
extern size_t git_path_basename_offset(git_buf *buffer);

extern const char *git_path_topdir(const char *path);

/**
 * Find offset to root of path if path has one.
 *
 * This will return a number >= 0 which is the offset to the start of the
 * path, if the path is rooted (i.e. "/rooted/path" returns 0 and
 * "c:/windows/rooted/path" returns 2).  If the path is not rooted, this
 * returns < 0.
 */
extern int git_path_root(const char *path);

/**
 * Ensure path has a trailing '/'.
 */
extern int git_path_to_dir(git_buf *path);

/**
 * Ensure string has a trailing '/' if there is space for it.
 */
extern void git_path_string_to_dir(char* path, size_t size);

/**
 * Taken from git.git; returns nonzero if the given path is "." or "..".
 */
GIT_INLINE(int) git_path_is_dot_or_dotdot(const char *name)
{
	return (name[0] == '.' &&
			  (name[1] == '\0' ||
				(name[1] == '.' && name[2] == '\0')));
}

#ifdef GIT_WIN32
GIT_INLINE(int) git_path_is_dot_or_dotdotW(const wchar_t *name)
{
	return (name[0] == L'.' &&
			  (name[1] == L'\0' ||
				(name[1] == L'.' && name[2] == L'\0')));
}

/**
 * Convert backslashes in path to forward slashes.
 */
GIT_INLINE(void) git_path_mkposix(char *path)
{
	while (*path) {
		if (*path == '\\')
			*path = '/';

		path++;
	}
}
#else
#	define git_path_mkposix(p) /* blank */
#endif

extern int git__percent_decode(git_buf *decoded_out, const char *input);

/**
 * Extract path from file:// URL.
 */
extern int git_path_fromurl(git_buf *local_path_out, const char *file_url);

/**
 * Path filesystem utils
 *
 * These are path utilities that actually access the filesystem.
 */

/**
 * Check if a file exists and can be accessed.
 * @return true or false
 */
extern bool git_path_exists(const char *path);

/**
 * Check if the given path points to a directory.
 * @return true or false
 */
extern bool git_path_isdir(const char *path);

/**
 * Check if the given path points to a regular file.
 * @return true or false
 */
extern bool git_path_isfile(const char *path);

/**
 * Check if the given path is a directory, and is empty.
 */
extern bool git_path_is_empty_dir(const char *path);

/**
 * Stat a file and/or link and set error if needed.
 */
extern int git_path_lstat(const char *path, struct stat *st);

/**
 * Check if the parent directory contains the item.
 *
 * @param dir Directory to check.
 * @param item Item that might be in the directory.
 * @return 0 if item exists in directory, <0 otherwise.
 */
extern bool git_path_contains(git_buf *dir, const char *item);

/**
 * Check if the given path contains the given subdirectory.
 *
 * @param parent Directory path that might contain subdir
 * @param subdir Subdirectory name to look for in parent
 * @param append_if_exists If true, then subdir will be appended to the parent path if it does exist
 * @return true if subdirectory exists, false otherwise.
 */
extern bool git_path_contains_dir(git_buf *parent, const char *subdir);

/**
 * Check if the given path contains the given file.
 *
 * @param dir Directory path that might contain file
 * @param file File name to look for in parent
 * @param append_if_exists If true, then file will be appended to the path if it does exist
 * @return true if file exists, false otherwise.
 */
extern bool git_path_contains_file(git_buf *dir, const char *file);

/**
 * Prepend base to unrooted path or just copy path over.
 *
 * This will optionally return the index into the path where the "root"
 * is, either the end of the base directory prefix or the path root.
 */
extern int git_path_join_unrooted(
	git_buf *path_out, const char *path, const char *base, ssize_t *root_at);

/**
 * Clean up path, prepending base if it is not already rooted.
 */
extern int git_path_prettify(git_buf *path_out, const char *path, const char *base);

/**
 * Clean up path, prepending base if it is not already rooted and
 * appending a slash.
 */
extern int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base);

/**
 * Get a directory from a path.
 *
 * If path is a directory, this acts like `git_path_prettify_dir`
 * (cleaning up path and appending a '/').  If path is a normal file,
 * this prettifies it, then removed the filename a la dirname and
 * appends the trailing '/'.  If the path does not exist, it is
 * treated like a regular filename.
 */
extern int git_path_find_dir(git_buf *dir, const char *path, const char *base);

/**
 * Resolve relative references within a path.
 *
 * This eliminates "./" and "../" relative references inside a path,
 * as well as condensing multiple slashes into single ones.  It will
 * not touch the path before the "ceiling" length.
 *
 * Additionally, this will recognize an "c:/" drive prefix or a "xyz://" URL
 * prefix and not touch that part of the path.
 */
extern int git_path_resolve_relative(git_buf *path, size_t ceiling);

/**
 * Apply a relative path to base path.
 *
 * Note that the base path could be a filename or a URL and this
 * should still work.  The relative path is walked segment by segment
 * with three rules: series of slashes will be condensed to a single
 * slash, "." will be eaten with no change, and ".." will remove a
 * segment from the base path.
 */
extern int git_path_apply_relative(git_buf *target, const char *relpath);

/**
 * Walk each directory entry, except '.' and '..', calling fn(state).
 *
 * @param pathbuf buffer the function reads the initial directory
 * 		path from, and updates with each successive entry's name.
 * @param fn function to invoke with each entry. The first arg is
 *		the input state and the second arg is pathbuf. The function
 *		may modify the pathbuf, but only by appending new text.
 * @param state to pass to fn as the first arg.
 * @return 0 on success, GIT_EUSER on non-zero callback, or error code
 */
extern int git_path_direach(
	git_buf *pathbuf,
	int (*fn)(void *, git_buf *),
	void *state);

/**
 * Sort function to order two paths
 */
extern int git_path_cmp(
	const char *name1, size_t len1, int isdir1,
	const char *name2, size_t len2, int isdir2,
	int (*compare)(const char *, const char *, size_t));

/**
 * Invoke callback up path directory by directory until the ceiling is
 * reached (inclusive of a final call at the root_path).
 *
 * Returning anything other than 0 from the callback function
 * will stop the iteration and propogate the error to the caller.
 *
 * @param pathbuf Buffer the function reads the directory from and
 *		and updates with each successive name.
 * @param ceiling Prefix of path at which to stop walking up.  If NULL,
 *      this will walk all the way up to the root.  If not a prefix of
 *      pathbuf, the callback will be invoked a single time on the
 *      original input path.
 * @param fn Function to invoke on each path.  The first arg is the
 *		input satte and the second arg is the pathbuf.  The function
 *		should not modify the pathbuf.
 * @param state Passed to fn as the first ath.
 */
extern int git_path_walk_up(
	git_buf *pathbuf,
	const char *ceiling,
	int (*fn)(void *state, git_buf *),
	void *state);

/**
 * Load all directory entries (except '.' and '..') into a vector.
 *
 * For cases where `git_path_direach()` is not appropriate, this
 * allows you to load the filenames in a directory into a vector
 * of strings. That vector can then be sorted, iterated, or whatever.
 * Remember to free alloc of the allocated strings when you are done.
 *
 * @param path The directory to read from.
 * @param prefix_len When inserting entries, the trailing part of path
 * 		will be prefixed after this length.  I.e. given path "/a/b" and
 * 		prefix_len 3, the entries will look like "b/e1", "b/e2", etc.
 * @param alloc_extra Extra bytes to add to each string allocation in
 * 		case you want to append anything funny.
 * @param contents Vector to fill with directory entry names.
 */
extern int git_path_dirload(
	const char *path,
	size_t prefix_len,
	size_t alloc_extra,
	git_vector *contents);

typedef struct {
	struct stat st;
	size_t      path_len;
	char        path[GIT_FLEX_ARRAY];
} git_path_with_stat;

extern int git_path_with_stat_cmp(const void *a, const void *b);
extern int git_path_with_stat_cmp_icase(const void *a, const void *b);

/**
 * Load all directory entries along with stat info into a vector.
 *
 * This adds four things on top of plain `git_path_dirload`:
 *
 * 1. Each entry in the vector is a `git_path_with_stat` struct that
 *    contains both the path and the stat info
 * 2. The entries will be sorted alphabetically
 * 3. Entries that are directories will be suffixed with a '/'
 * 4. Optionally, you can be a start and end prefix and only elements
 *    after the start and before the end (inclusively) will be stat'ed.
 *
 * @param path The directory to read from
 * @param prefix_len The trailing part of path to prefix to entry paths
 * @param ignore_case How to sort and compare paths with start/end limits
 * @param start_stat As optimization, only stat values after this prefix
 * @param end_stat As optimization, only stat values before this prefix
 * @param contents Vector to fill with git_path_with_stat structures
 */
extern int git_path_dirload_with_stat(
	const char *path,
	size_t prefix_len,
	bool ignore_case,
	const char *start_stat,
	const char *end_stat,
	git_vector *contents);

#endif


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>jss-camel-case</title>
  <link rel="stylesheet" href="../node_modules/qunitjs/qunit/qunit.css">


text:
package collections.ship.factory;

import java.io.Serializable;

/**
 * Weight represents a weight amount and unit of measure.
 *
 * <p> In this sample, Weight is embedded in part data values which are stored
 * as Java serialized objects; therefore Weight must be Serializable. </p>
 *
 * @author Mark Hayes
 */
public class Weight implements Serializable {

    public final static String GRAMS = "grams";
    public final static String OUNCES = "ounces";

    private double amount;
    private String units;

    public Weight(double amount, String units) {

        this.amount = amount;
        this.units = units;
    }

    public final double getAmount() {

        return amount;
    }

    public final String getUnits() {

        return units;
    }

    public String toString() {

        return "[" + amount + ' ' + units + ']';
    }
}


text:
package gobcy

import (
	"encoding/hex"
	"errors"
	"strconv"

	"github.com/btcsuite/btcd/btcec"
)

//GetUnTX returns an array of the latest unconfirmed TXs.
func (api *API) GetUnTX() (txs []TX, err error) {
	u, err := api.buildURL("/txs", nil)
	if err != nil {
		return
	}
	err = getResponse(u, &txs)
	return
}

//GetTX returns a TX represented by the passed hash. Takes
//an optionally-nil URL parameter map.
func (api *API) GetTX(hash string, params map[string]string) (tx TX, err error) {
	u, err := api.buildURL("/txs/"+hash, params)
	if err != nil {
		return
	}
	err = getResponse(u, &tx)
	return
}

//GetTXConf returns a TXConf containing a float [0,1] that
//represents BlockCypher's confidence that an unconfirmed transaction
//won't be successfully double-spent against. If the confidence is 1,
//the transaction has already been confirmed.
func (api *API) GetTXConf(hash string) (conf TXConf, err error) {
	u, err := api.buildURL("/txs/"+hash+"/confidence", nil)
	if err != nil {
		return
	}
	err = getResponse(u, &conf)
	return
}

//TempNewTX creates a simple template transaction, suitable for
//use in NewTX. Takes an input/output address and amount.
func TempNewTX(inAddr string, outAddr string, amount int) (trans TX) {
	trans.Inputs = make([]TXInput, 1)
	trans.Outputs = make([]TXOutput, 1)
	trans.Inputs[0].Addresses = make([]string, 1)
	trans.Outputs[0].Addresses = make([]string, 1)
	trans.Inputs[0].Addresses[0] = inAddr
	trans.Outputs[0].Addresses[0] = outAddr
	trans.Outputs[0].Value = amount
	return
}

//TempMultiTX creates a skeleton multisig transaction,
//suitable for use in NewTX. If outAddr == "", then the
//returned TX will be a skeleton to fund a multisig address.
//If inAddr == "", then the returned TX will be a skeleton to
//send from a multisig address (/series of public keys).
//n represents the number of valid signatures required, and m
//is derived from the number of pubkeys.
func TempMultiTX(inAddr string, outAddr string, amount int, n int, pubkeys []string) (trans TX, err error) {
	m := len(pubkeys)
	if inAddr != "" && outAddr != "" {
		err = errors.New("TempMultiTX: Can't have both inAddr and outAddr != \"\"")
		return
	}
	if n > m {
		err = errors.New("TempMultiTX: n cannot be greater than the number of pubkeys")
		return
	}
	scripttype := "multisig-" + strconv.Itoa(n) + "-of-" + strconv.Itoa(m)
	trans.Inputs = make([]TXInput, 1)
	trans.Outputs = make([]TXOutput, 1)
	if inAddr != "" {
		trans.Inputs[0].Addresses = make([]string, 1)
		trans.Inputs[0].Addresses[0] = inAddr
		trans.Outputs[0].Addresses = pubkeys
		trans.Outputs[0].ScriptType = scripttype
	} else if outAddr != "" {
		trans.Inputs[0].Addresses = pubkeys
		trans.Inputs[0].ScriptType = scripttype
		trans.Outputs[0].Addresses = make([]string, 1)
		trans.Outputs[0].Addresses[0] = outAddr
	}
	trans.Outputs[0].Value = amount
	return
}

//NewTX takes a partially formed TX and returns a TXSkel
//with the data that needs to be signed. Can use TempNewTX
//or TempMultiTX to streamline input transaction, or customize
//transaction as described in the BlockCypher docs:
//http://dev.blockcypher.com/#customizing-transaction-requests
//If verify is true, will include "ToSignTX," which can be used
//to locally verify the "ToSign" data is valid.
func (api *API) NewTX(trans TX, verify bool) (skel TXSkel, err error) {
	u, err := api.buildURL("/txs/new",
		map[string]string{"includeToSignTx": strconv.FormatBool(verify)})
	if err != nil {
		return
	}
	err = postResponse(u, &trans, &skel)
	return
}

//Sign takes a hex-encoded string slice of private
//keys and uses them to sign the ToSign data in a
//TXSkel, generating the proper Signatures and PubKeys
//array, both hex-encoded. This is meant as a helper
//function, and leverages btcd's btcec library.
func (skel *TXSkel) Sign(priv []string) (err error) {
	//num of private keys must match len(ToSign)
	//Often this might mean repeating private keys
	if len(priv) != len(skel.ToSign) {
		err = errors.New("*TXSkel.Sign error: number of private keys != length of ToSign array")
		return
	}
	//Loop through keys, append sigs/public key
	for i, k := range priv {
		privDat, err := hex.DecodeString(k)
		tosign, err := hex.DecodeString(skel.ToSign[i])
		if err != nil {
			return err
		}
		privkey, pubkey := btcec.PrivKeyFromBytes(btcec.S256(), privDat)
		sig, err := privkey.Sign(tosign)
		if err != nil {
			return err
		}
		skel.Signatures = append(skel.Signatures, hex.EncodeToString(sig.Serialize()))
		skel.PubKeys = append(skel.PubKeys, hex.EncodeToString(pubkey.SerializeCompressed()))
	}
	return
}

//SendTX takes a TXSkel, returns the completed
//transaction and sends it across the Coin/Chain
//network. TXSkel requires a fully formed TX, Signatures,
//and PubKeys. PubKeys should not be included in the
//special case of multi-sig addresses.
func (api *API) SendTX(skel TXSkel) (trans TXSkel, err error) {
	u, err := api.buildURL("/txs/send", nil)
	if err != nil {
		return
	}
	err = postResponse(u, &skel, &trans)
	return
}

//PushTX takes a hex-encoded transaction string
//and pushes it directly to the Coin/Chain network.
func (api *API) PushTX(hex string) (trans TXSkel, err error) {
	u, err := api.buildURL("/txs/push", nil)
	if err != nil {
		return
	}
	err = postResponse(u, &map[string]string{"tx": hex}, &trans)
	return
}

//DecodeTX takes a hex-encoded transaction string
//and decodes it into a TX object, without sending
//it along to the Coin/Chain network.
func (api *API) DecodeTX(hex string) (trans TXSkel, err error) {
	u, err := api.buildURL("/txs/decode", nil)
	if err != nil {
		return
	}
	err = postResponse(u, &map[string]string{"tx": hex}, &trans)
	return
}


text:
module.exports = (Hyper, { React }) => {
  const decorate = require('hyper/decorate');
  const Component = require('hyper/component');
  const HyperToolbar = require('../components/toolbar');

  return class extends Component {
    constructor (props) {
      super(props);
    }

    render() {
      const toolbar = React.createElement(decorate(HyperToolbar, 'HyperToolbar'), this.props.toolbar);
      const children = Array.from(this.props.customChildren || []).concat(toolbar);

      return React.createElement(Hyper, Object.assign({}, this.props, {
        customChildren: children
      }));
    }
  }
};


text:
require 'mixlib/cli'
require 'spanx/logger'

class Spanx::CLI::Report < Spanx::CLI

  banner 'Usage: spanx report [ -b | -t ] [options]'
  description 'Report on tracked and/or blocked IPs'

  option :blocked,
         :short => '-b',
         :long => '--blocked',
         :description => 'Show all currently blocked IPs',
         :required => false

  option :tracked,
         :short => '-t',
         :long => '--tracked',
         :description => 'Show all IPs seen within the tracked period',
         :required => false

  option :summary,
         :short => '-s',
         :long => '--summary',
         :description => 'Only show summary',
         :required => false

  option :config_file,
         :short => '-c CONFIG',
         :long => '--config CONFIG',
         :description => 'Path to config file (YML)',
         :required => true

  option :debug,
         :short => '-g',
         :long => '--debug',
         :description => 'Log to STDOUT status of execution and some time metrics',
         :boolean => true,
         :required => false,
         :default => false

  option :help,
         :short => '-h',
         :long => '--help',
         :description => 'Show this message',
         :on => :tail,
         :boolean => true,
         :show_options => true,
         :exit => 0

  def run(argv = ARGV)
    generate_config(argv)
    out = ''
    if config[:blocked]
      ips = Spanx::IPChecker.rate_limited_identifiers
      out << report_ips('Blocked', ips)
    end
    if config[:tracked]
      ips = Spanx::IPChecker.tracked_identifiers
      out << report_ips('Tracked', ips)
    end
    if config[:summary] or (config[:blocked].nil? && config[:tracked].nil?)
      out << "  Total tracked IPS: #{Spanx::IPChecker.tracked_identifiers.size}\n"
      out << "  Total blocked IPS: #{Spanx::IPChecker.rate_limited_identifiers.size}\n"
      out << "___________________\n\n"
      out << "Keeping history for: #{config[:collector][:history] / 3600 }hrs\n"
      out << "    Time resolution: #{config[:collector][:resolution] / 60 }min\n"
    end
    puts out
    out
  end

  private
  def report_ips name, ips = []
    ips.empty? ? "No #{name.downcase} IPs were found.\n" : "#{name} IPs:\n" + ips.join("\n") + "\n"
  end
end


text:
layout: post
title:  "Syncronize Android and iTunes"
date:   2015-03-28 11:50:00
categories: martin
tags: [itunes, android]
permalink: blog/:title
---
  * Install Google Play Music on Android
    * [Google Play Music in Play store][androidapp]
  * Install Google Music Manager on desktop
    * [Music Manager][desktopapp]
  * Open Music Manager on desktop
    * select the "Upload" tab
    * select "Automatically upload songs added to iTunes"

As of this writing you can upload up to 50.000 songs. Using the Play Music app on your Android you might want to keep the songs on the device instead of streaming them. Therefor click the download button on the album of song you want.

[androidapp]: https://play.google.com/store/apps/details?id=com.google.android.music&hl=en
[desktopapp]: https://play.google.com/music/listen?u=0#/manager


text:
package org.nlp4l.lucene

import java.nio.file.FileSystems
import org.apache.lucene.index.IndexWriter
import org.apache.lucene.index.IndexWriterConfig
import org.apache.lucene.store.Directory
import org.apache.lucene.store.FSDirectory

/**
 * Factory for [[IWriter]] instances
 */
object IWriter {
  /**
   * Create a new IWriter instance with given index path and [[Schema]].
   * @param index the path for index directory
   * @param schema the schema
   * @return a new IWriter instance
   */
  def apply(index: String, schema: Schema) = new IWriter(index, schema)
}

/**
 * Class representing schema aware index writer. This holds a Lucene IndexWriter internally.
 *
 * @constructor Create a new IWriter instance with given index path and schema.
 *
 * @param index the index path string
 * @param schema the schema
 */
class IWriter(index: String, schema: Schema) {

  val config : IndexWriterConfig = new IndexWriterConfig(schema.perFieldAnalyzer)
  val directory : Directory = FSDirectory.open(FileSystems.getDefault.getPath(index))
  val writer : IndexWriter = new IndexWriter(directory, config)

  /**
   * Add a document to the index.
   * @param document the document to add
   */
  def write(document: Document): Unit = {
    writer.addDocument(document.luceneDocument(schema))
  }

  /**
   * Delete all documents in the index.
   */
  def deleteAll(): Unit = {
    writer.deleteAll()
  }

  /**
    * Force merge the index.
    */
  def forceMerge( maxNumSegments: Int): Unit = {
    writer.forceMerge(maxNumSegments)
  }

  /**
   * Close the index.
   */
  def close(): Unit = {
    writer.close
    directory.close
  }
}


text:
<?php

namespace Kovalevych\MappingConverter\Generator;

use Kovalevych\MappingConverter\Field\Document\SimpleField;
use Kovalevych\MappingConverter\Field\Document\ReferenceOneField;
use Kovalevych\MappingConverter\Field\Document\ReferenceManyField;

class DoctrineDocumentGenerator
{
    /**
     * @param  string        $name
     * @param  array|string  $fieldData
     * @return \Kovalevych\MappingConverter\Field\SimpleField
     */
    public function createSimpleField($name, $fieldData)
    {
        if (is_array($fieldData)) {
            if (array_key_exists('type', $fieldData)) {
                $field = new SimpleField();
                $field
                    ->setType($fieldData['type'])
                    ->setName($name)
                ;
                if (array_key_exists('default', $fieldData)) {
                    $field->setDefault($fieldData['default']);
                }

                return $field;
            }
        }

        switch ($fieldData) {
            case 'string':
            case 'integer':
            case 'raw':
            case 'boolean':
            case 'date':
            case 'float':
                $field = new SimpleField();
                $field->setType($fieldData);
                break;
            default:
                throw new \RuntimeException(sprintf('Type %s is not supported', $fieldData));
                break;
        }
        $field->setName($name);

        return $field;
    }

    /**
     * @param  string $name
     * @param  array  $fieldData
     * @param  string $fromNamespace
     * @param  string $toNamespace
     * @return Kovalevych\MandangoToDoctrineConverter\Field\ReferenceOneField
     */
    public function createReferenceOneField($name, array $fieldData, $fromNamespace = null, $toNamespace = null)
    {
        $field = new ReferenceOneField();
        $field->setType('ReferenceOne');

        return $field
            ->setName($name)
            ->setReferencedClass($fieldData['class'], $fromNamespace, $toNamespace)
        ;
    }

    /**
     * @param  string $name
     * @param  array  $fieldData
     * @param  string $fromNamespace
     * @param  string $toNamespace
     * @return Kovalevych\MandangoToDoctrineConverter\Field\ReferenceManyField
     */
    public function createReferenceManyField($name, array $fieldData, $fromNamespace = null, $toNamespace = null)
    {
        $field = new ReferenceManyField();
        $field->setType('ReferenceMany');

        return $field
            ->setName($name)
            ->setReferencedClass($fieldData['class'], $fromNamespace, $toNamespace)
        ;
    }
}


text:
FOUNDATION_EXPORT double FideliusVersionNumber;
FOUNDATION_EXPORT const unsigned char FideliusVersionString[];


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

using SF.Sys.Annotations;
using SF.Sys.Entities.Annotations;
using System.ComponentModel.DataAnnotations;

namespace SF.Common.FrontEndContents.Friendly
{
	public class TextItem : LinkItemBase
    {
		/// <summary>
		/// 文字1
		/// </summary>
		[Required]
        [Layout(1)]
        public string Text1 { get; set; }

		/// <summary>
		/// 文字2
		/// </summary>
		[Layout(2)]
        public string Text2 { get; set; }

    }
}


text:
package io.agrest.unit;

import io.agrest.ResourceEntity;
import io.agrest.meta.AgEntity;
import io.agrest.meta.DefaultAgAttribute;
import io.agrest.meta.AgPersistentAttribute;
import io.agrest.meta.cayenne.CayenneEntityCompiler;
import io.agrest.meta.compiler.AgEntityCompiler;
import io.agrest.meta.compiler.PojoEntityCompiler;
import io.agrest.meta.parser.IResourceParser;
import io.agrest.meta.parser.ResourceParser;
import io.agrest.runtime.cayenne.ICayennePersister;
import io.agrest.runtime.meta.BaseUrlProvider;
import io.agrest.runtime.meta.IMetadataService;
import io.agrest.runtime.meta.IResourceMetadataService;
import io.agrest.runtime.meta.MetadataService;
import io.agrest.runtime.meta.ResourceMetadataService;
import io.agrest.runtime.parser.converter.DefaultJsonValueConverterFactoryProvider;
import io.agrest.runtime.parser.converter.IJsonValueConverterFactory;
import io.agrest.runtime.processor.select.SelectContext;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.configuration.server.DataSourceFactory;
import org.apache.cayenne.configuration.server.ServerRuntime;
import org.apache.cayenne.di.Module;
import org.apache.cayenne.exp.Property;
import org.apache.cayenne.exp.parser.ASTPath;
import org.apache.cayenne.map.ObjEntity;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * A superclass of Cayenne-aware test cases that do not need to access the DB,
 * but need to work with EntityResolver and higher levels of the stack.
 */
public class TestWithCayenneMapping {

	protected static ServerRuntime runtime;

	@BeforeClass
	public static void setUpClass() {
		Module module = binder -> {
            DataSourceFactory dsf = mock(DataSourceFactory.class);
            binder.bind(DataSourceFactory.class).toInstance(dsf);
        };
		runtime = ServerRuntime
				.builder()
				.addConfig("cayenne-agrest-tests.xml")
				.addModule(module)
				.build();
	}

	@AfterClass
	public static void tearDownClass() {
		runtime.shutdown();
		runtime = null;
	}

	protected ICayennePersister mockCayennePersister;
	protected IMetadataService metadataService;
	protected IResourceMetadataService resourceMetadataService;
	protected IResourceParser resourceParser;
	protected IJsonValueConverterFactory converterFactory;

	@Before
	public void initAgDataMap() {

		ObjectContext sharedContext = runtime.newContext();

		this.mockCayennePersister = mock(ICayennePersister.class);
		when(mockCayennePersister.entityResolver()).thenReturn(runtime.getChannel().getEntityResolver());
		when(mockCayennePersister.sharedContext()).thenReturn(sharedContext);
		when(mockCayennePersister.newContext()).thenReturn(runtime.newContext());

		this.converterFactory = new DefaultJsonValueConverterFactoryProvider(Collections.emptyMap()).get();
		this.metadataService = createMetadataService();
		this.resourceParser = new ResourceParser(metadataService);
		this.resourceMetadataService = createResourceMetadataService();
	}

	protected IMetadataService createMetadataService() {

		List<AgEntityCompiler> compilers = new ArrayList<>();
		compilers.add(new CayenneEntityCompiler(mockCayennePersister, Collections.emptyMap(), converterFactory));
		compilers.add(new PojoEntityCompiler(Collections.emptyMap()));

		return new MetadataService(compilers, mockCayennePersister);
	}

	protected IResourceMetadataService createResourceMetadataService() {
		return new ResourceMetadataService(resourceParser, BaseUrlProvider.forUrl(Optional.empty()));
	}

	protected <T> SelectContext<T> prepareContext(MultivaluedMap<String, String> params, Class<T> type) {
		SelectContext<T> context = new SelectContext<>(type);

		UriInfo uriInfo = mock(UriInfo.class);
		when(uriInfo.getQueryParameters()).thenReturn(params);

		context.setUriInfo(uriInfo);
		return context;
	}

	protected <T> AgEntity<T> getAgEntity(Class<T> type) {
		return metadataService.getAgEntity(type);
	}

	protected ObjEntity getEntity(Class<?> type) {
		return runtime.getChannel().getEntityResolver().getObjEntity(type);
	}

	protected <T> ResourceEntity<T> getResourceEntity(Class<T> type) {
		return new ResourceEntity<>(getAgEntity(type));
	}

	protected <T> void appendAttribute(ResourceEntity<?> entity, Property<T> property, Class<T> type) {
		appendAttribute(entity, property.getName(), type);
	}

	protected void appendAttribute(ResourceEntity<?> entity, String name, Class<?> type) {
		entity.getAttributes().put(name, new DefaultAgAttribute(name, type));
	}

	protected <T> void appendPersistenceAttribute(ResourceEntity<?> entity, Property<T> property, Class<T> javaType,
			int jdbcType) {
		appendPersistenceAttribute(entity, property.getName(), javaType, jdbcType);
	}

	protected void appendPersistenceAttribute(ResourceEntity<?> entity, String name, Class<?> javaType, int jdbcType) {
		entity.getAttributes().put(name,
				new TestAgPersistentAttribute(name, javaType, jdbcType));
	}

	private class TestAgPersistentAttribute extends DefaultAgAttribute implements AgPersistentAttribute {
		private int jdbcType;

		public TestAgPersistentAttribute(String name, Class<?> javaType, int jdbcType) {
			super(name, javaType);
			this.jdbcType = jdbcType;
		}

		@Override
		public int getJdbcType() {
			return jdbcType;
		}

		@Override
		public String getColumnName() {
			return getName();
		}

		@Override
		public boolean isMandatory() {
			return false;
		}

		@Override
		public ASTPath getPathExp() {
			return null;
		}
	}
}