text:
package org.apache.rocketmq.flink.source.reader.deserializer;

import org.apache.rocketmq.flink.source.util.ByteSerializer;
import org.apache.rocketmq.flink.source.util.ByteSerializer.ValueType;
import org.apache.rocketmq.flink.source.util.StringSerializer;

import org.apache.flink.api.common.serialization.DeserializationSchema.InitializationContext;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.descriptors.DescriptorProperties;
import org.apache.flink.table.descriptors.SchemaValidator;
import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.util.Collector;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * The row based implementation of {@link DeserializationSchema} for the deserialization of records.
 */
public class RowDeserializationSchema
        implements DeserializationSchema<List<BytesMessage>, RowData> {

    private static final long serialVersionUID = -1L;
    private static final Logger logger = LoggerFactory.getLogger(RowDeserializationSchema.class);

    private transient TableSchema tableSchema;
    private final DirtyDataStrategy formatErrorStrategy;
    private final DirtyDataStrategy fieldMissingStrategy;
    private final DirtyDataStrategy fieldIncrementStrategy;
    private final String encoding;
    private final String fieldDelimiter;
    private final String lineDelimiter;
    private final boolean columnErrorDebug;
    private final MetadataCollector metadataCollector;
    private final int totalColumnSize;
    private final int dataColumnSize;
    private final ValueType[] fieldTypes;
    private transient DataType[] fieldDataTypes;
    private final Set<String> headerFields;
    private final Map<String, String> properties;
    private final Map<String, Integer> columnIndexMapping;
    private final Map<Integer, Integer> dataIndexMapping;
    private long lastLogExceptionTime;
    private long lastLogHandleFieldTime;

    private static final int DEFAULT_LOG_INTERVAL_MS = 60 * 1000;

    public RowDeserializationSchema(
            TableSchema tableSchema,
            DirtyDataStrategy formatErrorStrategy,
            DirtyDataStrategy fieldMissingStrategy,
            DirtyDataStrategy fieldIncrementStrategy,
            String encoding,
            String fieldDelimiter,
            String lineDelimiter,
            boolean columnErrorDebug,
            boolean hasMetadata,
            MetadataConverter[] metadataConverters,
            List<String> headerFields,
            Map<String, String> properties) {
        this.tableSchema = tableSchema;
        this.formatErrorStrategy = formatErrorStrategy;
        this.fieldMissingStrategy = fieldMissingStrategy;
        this.fieldIncrementStrategy = fieldIncrementStrategy;
        this.columnErrorDebug = columnErrorDebug;
        this.encoding = encoding;
        this.fieldDelimiter = StringEscapeUtils.unescapeJava(fieldDelimiter);
        this.lineDelimiter = StringEscapeUtils.unescapeJava(lineDelimiter);
        this.metadataCollector = new MetadataCollector(hasMetadata, metadataConverters);
        this.headerFields = headerFields == null ? null : new HashSet<>(headerFields);
        this.properties = properties;
        this.totalColumnSize = tableSchema.getFieldNames().length;
        int dataColumnSize = 0;
        this.fieldTypes = new ValueType[totalColumnSize];
        this.columnIndexMapping = new HashMap<>();
        this.dataIndexMapping = new HashMap<>();
        for (int index = 0; index < tableSchema.getFieldNames().length; index++) {
            this.columnIndexMapping.put(tableSchema.getFieldNames()[index], index);
        }
        for (int index = 0; index < totalColumnSize; index++) {
            ValueType type =
                    ByteSerializer.getTypeIndex(tableSchema.getFieldTypes()[index].getTypeClass());
            this.fieldTypes[index] = type;
            if (!isHeaderField(index)) {
                dataIndexMapping.put(dataColumnSize, index);
                dataColumnSize++;
            }
        }
        this.dataColumnSize = dataColumnSize;
    }

    @Override
    public void open(InitializationContext context) {
        DescriptorProperties descriptorProperties = new DescriptorProperties();
        descriptorProperties.putProperties(properties);
        this.tableSchema = SchemaValidator.deriveTableSinkSchema(descriptorProperties);
        this.fieldDataTypes = tableSchema.getFieldDataTypes();
        this.lastLogExceptionTime = System.currentTimeMillis();
        this.lastLogHandleFieldTime = System.currentTimeMillis();
    }

    @Override
    public void deserialize(List<BytesMessage> messages, Collector<RowData> collector) {
        metadataCollector.collector = collector;
        deserialize(messages, metadataCollector);
    }

    private void deserialize(List<BytesMessage> messages, MetadataCollector collector) {
        if (null == messages || messages.size() == 0) {
            return;
        }
        for (BytesMessage message : messages) {
            collector.message = message;
            if (isOnlyHaveVarbinaryDataField()) {
                GenericRowData rowData = new GenericRowData(totalColumnSize);
                int dataIndex = dataIndexMapping.get(0);
                rowData.setField(dataIndex, message.getData());
                for (int index = 0; index < totalColumnSize; index++) {
                    if (index == dataIndex) {
                        continue;
                    }
                    String headerValue = getHeaderValue(message, index);
                    rowData.setField(
                            index,
                            StringSerializer.deserialize(
                                    headerValue,
                                    fieldTypes[index],
                                    fieldDataTypes[index],
                                    new HashSet<>()));
                }
                collector.collect(rowData);
            } else if (isAllHeaderField()) {
                GenericRowData rowData = new GenericRowData(totalColumnSize);
                for (int index = 0; index < totalColumnSize; index++) {
                    String headerValue = getHeaderValue(message, index);
                    rowData.setField(
                            index,
                            StringSerializer.deserialize(
                                    headerValue,
                                    fieldTypes[index],
                                    fieldDataTypes[index],
                                    new HashSet<>()));
                }
                collector.collect(rowData);
            } else {
                if (message.getData() == null) {
                    logger.info("Deserialize empty BytesMessage body, ignore the empty message.");
                    return;
                }
                deserializeBytesMessage(message, collector);
            }
        }
    }

    private boolean isOnlyHaveVarbinaryDataField() {
        if (dataColumnSize == 1 && dataIndexMapping.size() == 1) {
            int index = dataIndexMapping.get(0);
            return isByteArrayType(tableSchema.getFieldNames()[index]);
        }
        return false;
    }

    private boolean isAllHeaderField() {
        return null != headerFields && headerFields.size() == tableSchema.getFieldNames().length;
    }

    private void deserializeBytesMessage(BytesMessage message, Collector<RowData> collector) {
        String body;
        try {
            body = new String(message.getData(), encoding);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String[] lines = StringUtils.split(body, lineDelimiter);
        for (String line : lines) {
            String[] data = StringUtils.splitPreserveAllTokens(line, fieldDelimiter);
            if (dataColumnSize == 1) {
                data = new String[1];
                data[0] = line;
            }
            if (data.length < dataColumnSize) {
                data = handleFieldMissing(data);
            } else if (data.length > dataColumnSize) {
                data = handleFieldIncrement(data);
            }
            if (data == null) {
                continue;
            }
            GenericRowData rowData = new GenericRowData(totalColumnSize);
            boolean skip = false;
            for (int index = 0; index < totalColumnSize; index++) {
                try {
                    String fieldValue = getValue(message, data, line, index);
                    rowData.setField(
                            index,
                            StringSerializer.deserialize(
                                    fieldValue,
                                    fieldTypes[index],
                                    fieldDataTypes[index],
                                    new HashSet<>()));
                } catch (Exception e) {
                    skip = handleException(rowData, index, data, e);
                }
            }
            if (skip) {
                continue;
            }
            collector.collect(rowData);
        }
    }

    private boolean isHeaderField(int index) {
        return headerFields != null && headerFields.contains(tableSchema.getFieldNames()[index]);
    }

    private String getHeaderValue(BytesMessage message, int index) {
        Object object = message.getProperty(tableSchema.getFieldNames()[index]);
        return object == null ? "" : (String) object;
    }

    private String getValue(BytesMessage message, String[] data, String line, int index) {
        String fieldValue = null;
        if (isHeaderField(index)) {
            fieldValue = getHeaderValue(message, index);
        } else {
            if (dataColumnSize == 1) {
                fieldValue = line;
            } else {
                if (index < data.length) {
                    fieldValue = data[index];
                }
            }
        }

        return fieldValue;
    }

    private boolean isByteArrayType(String fieldName) {
        TypeInformation<?> typeInformation =
                tableSchema.getFieldTypes()[columnIndexMapping.get(fieldName)];
        if (typeInformation != null) {
            ValueType valueType = ByteSerializer.getTypeIndex(typeInformation.getTypeClass());
            return valueType == ValueType.V_ByteArray;
        }
        return false;
    }

    private boolean handleException(GenericRowData row, int index, Object[] data, Exception e) {
        boolean skip = false;
        switch (formatErrorStrategy) {
            case SKIP:
                long now = System.currentTimeMillis();
                if (columnErrorDebug || now - lastLogExceptionTime > DEFAULT_LOG_INTERVAL_MS) {
                    logger.warn(
                            "Data format error, field type: "
                                    + fieldTypes[index]
                                    + "field data: "
                                    + data[index]
                                    + ", index: "
                                    + index
                                    + ", data: ["
                                    + StringUtils.join(data, ",")
                                    + "]",
                            e);
                    lastLogExceptionTime = now;
                }
                skip = true;
                break;
            case SKIP_SILENT:
                skip = true;
                break;
            default:
            case CUT:
            case NULL:
            case PAD:
                row.setField(index, null);
                break;
            case EXCEPTION:
                throw new RuntimeException(e);
        }

        return skip;
    }

    private String[] handleFieldMissing(String[] data) {
        switch (fieldMissingStrategy) {
            default:
            case SKIP:
                long now = System.currentTimeMillis();
                if (columnErrorDebug || now - lastLogHandleFieldTime > DEFAULT_LOG_INTERVAL_MS) {
                    logger.warn(
                            "Field missing error, table column number: "
                                    + totalColumnSize
                                    + ", data column number: "
                                    + dataColumnSize
                                    + ", data field number: "
                                    + data.length
                                    + ", data: ["
                                    + StringUtils.join(data, ",")
                                    + "]");
                    lastLogHandleFieldTime = now;
                }
                return null;
            case SKIP_SILENT:
                return null;
            case CUT:
            case NULL:
            case PAD:
                {
                    String[] res = new String[totalColumnSize];
                    for (int i = 0; i < data.length; ++i) {
                        Object dataIndex = dataIndexMapping.get(i);
                        if (dataIndex != null) {
                            res[(int) dataIndex] = data[i];
                        }
                    }
                    return res;
                }
            case EXCEPTION:
                throw new RuntimeException();
        }
    }

    private String[] handleFieldIncrement(String[] data) {
        switch (fieldIncrementStrategy) {
            case SKIP:
                long now = System.currentTimeMillis();
                if (columnErrorDebug || now - lastLogHandleFieldTime > DEFAULT_LOG_INTERVAL_MS) {
                    logger.warn(
                            "Field increment error, table column number: "
                                    + totalColumnSize
                                    + ", data column number: "
                                    + dataColumnSize
                                    + ", data field number: "
                                    + data.length
                                    + ", data: ["
                                    + StringUtils.join(data, ",")
                                    + "]");
                    lastLogHandleFieldTime = now;
                }
                return null;
            case SKIP_SILENT:
                return null;
            default:
            case CUT:
            case NULL:
            case PAD:
                {
                    String[] res = new String[totalColumnSize];
                    for (int i = 0; i < dataColumnSize; ++i) {
                        Object dataIndex = dataIndexMapping.get(i);
                        if (dataIndex != null) {
                            res[(int) dataIndex] = data[i];
                        }
                    }
                    return res;
                }
            case EXCEPTION:
                throw new RuntimeException();
        }
    }

    @Override
    public TypeInformation<RowData> getProducedType() {
        return InternalTypeInfo.of((RowType) tableSchema.toRowDataType().getLogicalType());
    }

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

    /** Source metadata converter interface. */
    public interface MetadataConverter extends Serializable {
        Object read(BytesMessage message);
    }

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

    /** Metadata of RowData collector. */
    public static final class MetadataCollector implements Collector<RowData>, Serializable {

        private static final long serialVersionUID = 1L;

        private final boolean hasMetadata;
        private final MetadataConverter[] metadataConverters;

        public transient BytesMessage message;
        public transient Collector<RowData> collector;

        public MetadataCollector(boolean hasMetadata, MetadataConverter[] metadataConverters) {
            this.hasMetadata = hasMetadata;
            this.metadataConverters = metadataConverters;
        }

        @Override
        public void collect(RowData physicalRow) {
            if (hasMetadata) {
                final int physicalArity = physicalRow.getArity();
                final int metadataArity = metadataConverters.length;
                final GenericRowData producedRow =
                        new GenericRowData(physicalRow.getRowKind(), physicalArity + metadataArity);
                final GenericRowData genericPhysicalRow = (GenericRowData) physicalRow;
                for (int index = 0; index < physicalArity; index++) {
                    producedRow.setField(index, genericPhysicalRow.getField(index));
                }
                for (int index = 0; index < metadataArity; index++) {
                    producedRow.setField(
                            index + physicalArity, metadataConverters[index].read(message));
                }
                collector.collect(producedRow);
            } else {
                collector.collect(physicalRow);
            }
        }

        @Override
        public void close() {
            // nothing to do
        }
    }

    /** Builder of {@link RowDeserializationSchema}. */
    public static class Builder {

        private TableSchema schema;
        private DirtyDataStrategy formatErrorStrategy = DirtyDataStrategy.SKIP;
        private DirtyDataStrategy fieldMissingStrategy = DirtyDataStrategy.SKIP;
        private DirtyDataStrategy fieldIncrementStrategy = DirtyDataStrategy.CUT;
        private String encoding = "UTF-8";
        private String lineDelimiter = "\n";
        private String fieldDelimiter = "\u0001";
        private boolean columnErrorDebug = false;
        private boolean hasMetadata;
        private MetadataConverter[] metadataConverters;
        private List<String> headerFields;
        private Map<String, String> properties;

        public Builder() {}

        public Builder setTableSchema(TableSchema tableSchema) {
            this.schema = tableSchema;
            return this;
        }

        public Builder setFormatErrorStrategy(DirtyDataStrategy formatErrorStrategy) {
            this.formatErrorStrategy = formatErrorStrategy;
            return this;
        }

        public Builder setFieldMissingStrategy(DirtyDataStrategy fieldMissingStrategy) {
            this.fieldMissingStrategy = fieldMissingStrategy;
            return this;
        }

        public Builder setFieldIncrementStrategy(DirtyDataStrategy fieldIncrementStrategy) {
            this.fieldIncrementStrategy = fieldIncrementStrategy;
            return this;
        }

        public Builder setEncoding(String encoding) {
            this.encoding = encoding;
            return this;
        }

        public Builder setFieldDelimiter(String fieldDelimiter) {
            this.fieldDelimiter = fieldDelimiter;
            return this;
        }

        public Builder setLineDelimiter(String lineDelimiter) {
            this.lineDelimiter = lineDelimiter;
            return this;
        }

        public Builder setColumnErrorDebug(boolean columnErrorDebug) {
            this.columnErrorDebug = columnErrorDebug;
            return this;
        }

        public Builder setHasMetadata(boolean hasMetadata) {
            this.hasMetadata = hasMetadata;
            return this;
        }

        public Builder setMetadataConverters(MetadataConverter[] metadataConverters) {
            this.metadataConverters = metadataConverters;
            return this;
        }

        public Builder setHeaderFields(List<String> headerFields) {
            this.headerFields = headerFields;
            return this;
        }

        public Builder setProperties(Map<String, String> properties) {
            this.properties = properties;
            if (null == properties) {
                return this;
            }
            Configuration configuration = new Configuration();
            for (String key : properties.keySet()) {
                configuration.setString(key, properties.get(key));
            }
            String lengthCheck = configuration.get(CollectorOption.LENGTH_CHECK);
            switch (lengthCheck.toUpperCase()) {
                case "SKIP":
                    {
                        this.setFormatErrorStrategy(DirtyDataStrategy.SKIP);
                        this.setFieldMissingStrategy(DirtyDataStrategy.SKIP);
                        this.setFieldIncrementStrategy(DirtyDataStrategy.SKIP);
                    }
                    break;
                case "PAD":
                    {
                        this.setFormatErrorStrategy(DirtyDataStrategy.SKIP);
                        this.setFieldMissingStrategy(DirtyDataStrategy.PAD);
                        this.setFieldIncrementStrategy(DirtyDataStrategy.CUT);
                    }
                    break;
                case "EXCEPTION":
                    {
                        this.setFormatErrorStrategy(DirtyDataStrategy.EXCEPTION);
                        this.setFieldMissingStrategy(DirtyDataStrategy.EXCEPTION);
                        this.setFieldIncrementStrategy(DirtyDataStrategy.EXCEPTION);
                    }
                    break;
                case "SKIP_SILENT":
                    {
                        this.setFormatErrorStrategy(DirtyDataStrategy.SKIP_SILENT);
                        this.setFieldMissingStrategy(DirtyDataStrategy.SKIP_SILENT);
                        this.setFieldIncrementStrategy(DirtyDataStrategy.SKIP_SILENT);
                    }
                    break;
                default:
            }
            this.setEncoding(configuration.getString(CollectorOption.ENCODING));
            this.setFieldDelimiter(configuration.getString(CollectorOption.FIELD_DELIMITER));
            this.setLineDelimiter(configuration.getString(CollectorOption.LINE_DELIMITER));
            this.setColumnErrorDebug(configuration.getBoolean(CollectorOption.COLUMN_ERROR_DEBUG));
            return this;
        }

        public RowDeserializationSchema build() {
            return new RowDeserializationSchema(
                    schema,
                    formatErrorStrategy,
                    fieldMissingStrategy,
                    fieldIncrementStrategy,
                    encoding,
                    fieldDelimiter,
                    lineDelimiter,
                    columnErrorDebug,
                    hasMetadata,
                    metadataConverters,
                    headerFields,
                    properties);
        }
    }

    /** Options for {@link RowDeserializationSchema}. */
    public static class CollectorOption {
        public static final ConfigOption<String> ENCODING =
                ConfigOptions.key("encoding".toLowerCase()).defaultValue("UTF-8");
        public static final ConfigOption<String> FIELD_DELIMITER =
                ConfigOptions.key("fieldDelimiter".toLowerCase()).defaultValue("\u0001");
        public static final ConfigOption<String> LINE_DELIMITER =
                ConfigOptions.key("lineDelimiter".toLowerCase()).defaultValue("\n");
        public static final ConfigOption<Boolean> COLUMN_ERROR_DEBUG =
                ConfigOptions.key("columnErrorDebug".toLowerCase()).defaultValue(true);
        public static final ConfigOption<String> LENGTH_CHECK =
                ConfigOptions.key("lengthCheck".toLowerCase()).defaultValue("NONE");
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<out xmlns:s="http://example.com" xmlns:n="http://ns.test.com">
<n:x>from stylesheet</n:x>
<e xmlns="http://literalURI"><n:a xmlns:n="http://example.com">content</n:a></e></out>


text:
package edu.cmu.sad.microservices.services.web;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;

public class ProductSearchCriteria {
    private String productNumber;

    private String searchText;

    public String getProductNumber() {
        return productNumber;
    }

    public void setProductNumber(String productNumber) {
        this.productNumber = productNumber;
    }

    public String getSearchText() {
        return searchText;
    }

    public void setSearchText(String searchText) {
        this.searchText = searchText;
    }

    public boolean isValid() {
        if (StringUtils.hasText(productNumber))
            return !(StringUtils.hasText(searchText));
        else
            return (StringUtils.hasText(searchText));
    }

    public boolean validate(Errors errors) {
        if (StringUtils.hasText(productNumber)) {
            if (productNumber.length() != 6)
                errors.rejectValue("productNumber", "badFormat",
                        "Product number should be 6 digits");
            else {
                try {
                    Integer.parseInt(productNumber);
                } catch (NumberFormatException e) {
                    errors.rejectValue("productNumber", "badFormat",
                            "Product number should be 6 digits");
                }
            }

            if (StringUtils.hasText(searchText)) {
                errors.rejectValue("searchText", "nonEmpty",
                        "Cannot specify product number and search text");
            }
        } else if (StringUtils.hasText(searchText)) {
            ; // Nothing to do
        } else {
            errors.rejectValue("productNumber", "nonEmpty",
                    "Must specify either an product number or search text");

        }

        return errors.hasErrors();
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return (StringUtils.hasText(productNumber) ? "number: " + productNumber
                : "")
                + (StringUtils.hasText(searchText) ? " text: " + searchText
                : "");
    }
}


text:
classdef BodyMotionData
  % Data structure describing the desired motion of a single body on the
  % robot. The QPLocomotionPlan will call this class's slice() method to get a
  % snapshot of the desired body motion, which will be sent to the controller
  % as part of the QP controller input.
  %
  % The desired body motion is expressed as a piecewise cubic polynomial.
  properties
    ts;  % Times of the breakpoints in the cubic polynomial
    coefs; % Coefficients of the cubic polynomial. The format is [x; y; z; w1; w2; w3] where w(1:3) is the exponential map representation of the orientation.
    body_id; % Body or frame ID to track
    toe_off_allowed; % A flag used by the QPLocomotionPlan to determine whether to engage toe-only support when walking. Set this to False unless you have some reason not to.
    in_floating_base_nullspace; % Whether to explicitly disallow floating base acceleration as a method for accelerating this body in the controller. We set this for the legs so that, for example, if the leg falls behind its plan, the controller doesn't accelerate the pelvis forward to compensate, which can cause a fall.
    control_pose_when_in_contact; % Whether to attempt to control the pose of this body even when it's in contact with the world. This is typically false, but we've set it to true when using the pelvis as a support.
    quat_task_to_world % A rotation transformation, the coefs is specified in the task frame
    translation_task_to_world % translation from task frame to the world frame
    xyz_kp_multiplier % A 3 x 1 vector. The multiplier for the Kp gain on xyz position error of the body, default to [1;1;1]
    xyz_damping_ratio_multiplier % A 3 x 1 vector. The multiplier for the damping ratio on xyz velocity error of the body, default to [1;1;1]
    expmap_kp_multiplier % A positive scalar. The multiplier for the Kp gain on exponential map error of body orientation, default to 1
    expmap_damping_ratio_multiplier % A positive scalar. The multiplier for the damping ratio on exponential map velocity error of body orientation, default to 1
    weight_multiplier % A 6 x 1 vector. The multiplier for twist_dot (angular_aceleration, cartesian_acceleration) weight in the QP controller, default to ones(6,1);
  end

  methods
    function obj = BodyMotionData(body_id, ts)
      obj.ts = ts;
      obj.body_id = body_id;
      obj.toe_off_allowed = false(1, numel(ts));
      obj.in_floating_base_nullspace = false(1, numel(ts));
      obj.control_pose_when_in_contact = false(1, numel(ts));
      obj.coefs = zeros(6, numel(ts), 4);
      obj.quat_task_to_world = [1;0;0;0];
      obj.translation_task_to_world = zeros(3,1);
      obj.xyz_kp_multiplier = [1;1;1];
      obj.xyz_damping_ratio_multiplier = [1;1;1];
      obj.expmap_kp_multiplier = 1;
      obj.expmap_damping_ratio_multiplier = 1;
      obj.weight_multiplier = ones(6,1);
    end

    function t_ind = findTInd(obj, t)
      if t < obj.ts(1)
        t_ind = 1;
      elseif t >= obj.ts(end)
        t_ind = length(obj.ts) - 1;
      else
        t_ind = find(obj.ts <= t, 1, 'last');
      end
    end

    function [x, xd, xdd] = eval(obj, t)
      t_ind = obj.findTInd(t);
      [x, xd, xdd] = obj.evalAtInd(t_ind, t);
    end

    function [x, xd, xdd] = evalAtInd(obj, t_ind, t)
      t_rel = t - obj.ts(t_ind);
      x = obj.coefs(:,t_ind,1)*t_rel^3 + obj.coefs(:,t_ind,2)*t_rel^2 + obj.coefs(:,t_ind,3)*t_rel + obj.coefs(:,t_ind,4);
      xd = 3*obj.coefs(:,t_ind,1)*t_rel^2 + 2*obj.coefs(:,t_ind,2)*t_rel + obj.coefs(:,t_ind,3);
      xdd = 6*obj.coefs(:,t_ind,1)*t_rel + 2*obj.coefs(:,t_ind,2);
    end

    function body_motion_slice = sliceAtTime(obj, t)
      body_motion_slice = obj.slice(obj.findTInd(t));
    end

    function body_motion_slice = slice(obj, t_ind)
      slice_t_inds = min([t_ind, t_ind+1], [length(obj.ts), length(obj.ts)]);
      slice_t_inds = max(slice_t_inds, [1, 1]);
      body_motion_slice = struct('body_id', obj.body_id,...
                                 'ts', obj.ts(slice_t_inds),...
                                 'coefs', obj.coefs(:,t_ind,:),...
                                 'toe_off_allowed', obj.toe_off_allowed(t_ind),...
                                 'in_floating_base_nullspace', obj.in_floating_base_nullspace(t_ind),...
                                 'control_pose_when_in_contact', obj.control_pose_when_in_contact(t_ind),...
                                 'quat_task_to_world',obj.quat_task_to_world,...
                                 'translation_task_to_world',obj.translation_task_to_world,...
                                 'xyz_kp_multiplier',obj.xyz_kp_multiplier,...
                                 'xyz_damping_ratio_multiplier',obj.xyz_damping_ratio_multiplier,...
                                 'expmap_kp_multiplier',obj.expmap_kp_multiplier,...
                                 'expmap_damping_ratio_multiplier',obj.expmap_damping_ratio_multiplier,...
                                 'weight_multiplier',obj.weight_multiplier);
    end

    function pp = getPP(obj)
      pp = mkpp(obj.ts, obj.coefs, size(obj.coefs, 1));
    end

    function obj = extend(obj, new_body_motion_data)
      if obj.ts(end) ~= new_body_motion_data.ts(1)
        error('Drake:BodyMotionData:BadExtend', 'final time of first arg should match initial time of second arg');
      end
      if size(obj.coefs, 1) ~= size(new_body_motion_data.coefs, 1)
        error('Drake:BodyMotionData:BadExtend', 'dimension of coefs should match');
      end
      if obj.body_id ~= new_body_motion_data.body_id
        error('Drake:BodyMotionData:BadExtend', 'body_ids must match');
      end
      if any(obj.quat_task_to_world ~= new_body_motion_data.quat_task_to_world)
        error('Drake:BodyMotionData:BadExtend', 'quat_task_to_world must match');
      end
      if any(obj.translation_task_to_world ~= new_body_motion_data.translation_task_to_world)
        error('Drake:BodyMotionData:BadExtend', 'translation_task_to_world must match');
      end
      if any(obj.xyz_kp_multiplier ~= new_body_motion_data.xyz_kp_multiplier)
        error('Drake:BodyMotionData:BadExtend', 'xyz_kp_multiplier must match');
      end
      if any(obj.xyz_damping_ratio_multiplier ~= new_body_motion_data.xyz_damping_ratio_multiplier)
        error('Drake:BodyMotionData:BadExtend', 'xyz_damping_ratio_multiplier must match');
      end
      if any(obj.expmap_kp_multiplier ~= new_body_motion_data.expmap_kp_multiplier)
        error('Drake:BodyMotionData:BadExtend', 'expmap_kp_multiplier must match');
      end
      if any(obj.expmap_damping_ratio_multiplier ~= new_body_motion_data.expmap_damping_ratio_multiplier)
        error('Drake:BodyMotionData:BadExtend', 'expmap_damping_ratio_multiplier must match');
      end
      if any(obj.weight_multiplier ~= new_body_motion_data.weight_multiplier)
        error('Drake:BodyMotionData:BadExtend', 'weight_multiplier must match');
      end
      nts = numel(obj.ts) - 1;
      obj.ts = [obj.ts(1:nts), new_body_motion_data.ts];
      obj.toe_off_allowed = [obj.toe_off_allowed(1:nts), new_body_motion_data.toe_off_allowed];
      obj.in_floating_base_nullspace = [obj.in_floating_base_nullspace(1:nts), new_body_motion_data.in_floating_base_nullspace];
      obj.control_pose_when_in_contact = [obj.control_pose_when_in_contact(1:nts), new_body_motion_data.control_pose_when_in_contact];
    end
  end

  methods(Static)
    function obj = from_body_poses(body_id, ts, xyz_rpy)
      % Maintained for backwards compatibility, assumed to be xyzrpy
      obj = BodyMotionData.from_body_xyzrpy(body_id, ts, xyz_rpy);
    end

    function obj = from_body_poses_and_velocities(body_id, ts, xyz_rpy, xyz_rpydot)
      % Maintained for backwards compatibility, assumed to be xyzrpy
      quat = zeros(4, size(xyz_rpy, 2));
      quatdot = zeros(4, size(xyz_rpy, 2));
      for j = 1:size(xyz_rpy, 2)
        quat(:,j) = rpy2quat(xyz_rpy(4:6,j));
        angvel = rpydot2angularvel(xyz_rpy(4:6,j), xyz_rpydot(4:6,j));
        M = angularvel2quatdotMatrix(quat(:,j));
        quatdot(:,j) = M * angvel;
      end
      [expmap, expmapdot] = quat2expmapSequence(quat, quatdot);
      xyz_exp = [xyz_rpy(1:3,:); expmap];
      xyz_expdot = [xyz_rpydot(1:3,:); expmapdot];
      obj = BodyMotionData.from_body_xyzexp_and_xyzexpdot(body_id, ts, xyz_exp, xyz_expdot);
    end

    function obj = from_body_xyzrpy(body_id, ts, poses)
      quat = zeros(4, size(poses, 2));
      for j = 1:size(poses, 2)
        quat(:,j) = rpy2quat(poses(4:6,j));
      end
      expmap = quat2expmapSequence(quat, zeros(size(quat)));
      xyz_exp = [poses(1:3,:); expmap];
      obj = BodyMotionData.from_body_xyzexp(body_id, ts, xyz_exp);
    end

    function obj = from_body_xyzquat(body_id, ts, xyz_quat)
      xyz_exp = zeros(6, size(xyz_quat, 2));
      xyz_exp(1:3,:) = xyz_quat(1:3,:);
      expmap = quat2expmapSequence(xyz_quat(4:7,:), zeros(4, size(xyz_quat,2)));
      xyz_exp(4:6,:) = expmap;
      obj = BodyMotionData.from_body_xyzexp(body_id, ts, xyz_exp);
    end

    function obj = from_body_xyzquat_and_xyzquatdot(body_id, ts, xyzquat, xyzquatdot)
      [expmap, expmapdot] = quat2expmapSequence(xyzquat(4:7,:), xyzquatdot(4:7,:));
      xyz_exp = [xyzquat(1:3,:); expmap];
      xyz_expdot = [xyzquatdot(1:3,:); expmapdot];
      obj = BodyMotionData.from_body_xyzexp_and_xyzexpdot(body_id, ts, xyz_exp, xyz_expdot);
    end

    function obj = from_body_xyzexp(body_id, ts, poses_exp)
      % [xyz; exp]
      obj = BodyMotionData(body_id, ts);
      pp = pchip(ts, poses_exp);
      [~, obj.coefs, l, k, d] = unmkpp(pp);
      obj.coefs = reshape(obj.coefs, [d, l, k]);
    end

    function obj = from_body_xyzexp_and_xyzexpdot(body_id, ts, poses_exp, dposes_exp)
      obj = BodyMotionData(body_id, ts);
      pp = pchipDeriv(ts, poses_exp, dposes_exp);
      [~, obj.coefs, l, k, d] = unmkpp(pp);
      obj.coefs = reshape(obj.coefs, [d, l, k]);
    end
  end
end


text:
package org.uberfire.mvp.impl;

import org.junit.Test;
import org.uberfire.mvp.PlaceRequest;

import static org.junit.Assert.*;

public class ConditionalPlaceRequestTest {

    @Test
    public void conditionalTestTruePredicate() {
        DefaultPlaceRequest other = new DefaultPlaceRequest( "other" );
        ConditionalPlaceRequest dora = (ConditionalPlaceRequest) new ConditionalPlaceRequest( "dora" ).when( p -> true )
                .orElse( other );
        assertEquals( dora, dora.resolveConditionalPlaceRequest() );
    }

    @Test
    public void conditionalTestFalsePredicate() {
        DefaultPlaceRequest other = new DefaultPlaceRequest( "other" );
        ConditionalPlaceRequest dora = (ConditionalPlaceRequest) new ConditionalPlaceRequest( "dora" ).when( p -> false )
                .orElse( other );
        assertEquals( other, dora.resolveConditionalPlaceRequest() );
    }

    @Test
    public void incompleteConditionalShouldReturnDefaultPlaceRequest() {
        ConditionalPlaceRequest dora = new ConditionalPlaceRequest( "dora" );
        assertEquals( "dora", dora.resolveConditionalPlaceRequest().getIdentifier() );
    }

    @Test
    public void incompleteConditionalWithNullsShouldReturnDefaultPlaceRequest() {
        ConditionalPlaceRequest dora = (ConditionalPlaceRequest) new ConditionalPlaceRequest( "dora" ).when( null ).orElse( null );
        assertEquals( "dora", dora.resolveConditionalPlaceRequest().getIdentifier() );
    }

    @Test
    public void conditionalTestChainingPredicate() {
        DefaultPlaceRequest my = new DefaultPlaceRequest( "my" );
        ConditionalPlaceRequest bento = (ConditionalPlaceRequest) new ConditionalPlaceRequest( "bento" ).when( p -> false )
                .orElse( my );
        ConditionalPlaceRequest dora = (ConditionalPlaceRequest) new ConditionalPlaceRequest( "dora" ).when( p -> false )
                .orElse( bento );
        assertEquals( my, dora.resolveConditionalPlaceRequest() );
    }

    @Test
    public void conditionalTestChainingPredicateReturningConditional() {
        DefaultPlaceRequest my = new DefaultPlaceRequest( "my" );
        ConditionalPlaceRequest bento = (ConditionalPlaceRequest) new ConditionalPlaceRequest( "bento" ).when( p -> true )
                .orElse( my );
        ConditionalPlaceRequest dora = (ConditionalPlaceRequest) new ConditionalPlaceRequest( "dora" ).when( p -> false )
                .orElse( bento );
        assertEquals( "bento", dora.resolveConditionalPlaceRequest().getIdentifier() );
    }

    @Test
    public void defaultPlaceRequestEqualsToConditionalPlaceRequest() {
        final DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest( "my" );
        final PlaceRequest conditionalPlaceRequest = new ConditionalPlaceRequest( "my" ).when( p -> true ).orElse( new DefaultPlaceRequest( "other" ) );

        equals( defaultPlaceRequest, conditionalPlaceRequest );
    }

    @Test
    public void defaultPlaceRequestNotEqualsToConditionalPlaceRequest() {
        final DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest( "my" );
        final PlaceRequest conditionalPlaceRequest = new ConditionalPlaceRequest( "my" ).when( p -> false ).orElse( new DefaultPlaceRequest( "other" ) );

        notEquals( defaultPlaceRequest, conditionalPlaceRequest );
    }

    @Test
    public void defaultPlaceRequestEqualsToIncompleteConditionalPlaceRequest() {
        final DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest( "my" );
        final PlaceRequest conditionalPlaceRequest = new ConditionalPlaceRequest( "my" );

        equals( defaultPlaceRequest, conditionalPlaceRequest );
    }

    @Test
    public void trueEvaluatedConditionalPlaceRequestEqualsToAnotherTrueEvaluatedConditionalPlaceRequest() {
        final PlaceRequest conditionalPlaceRequest1 = new ConditionalPlaceRequest( "place1" ).when( p -> true ).orElse( new DefaultPlaceRequest( "place2" ) );
        final PlaceRequest conditionalPlaceRequest2 = new ConditionalPlaceRequest( "place1" ).when( p -> true ).orElse( new DefaultPlaceRequest( "place3" ) );

        equals( conditionalPlaceRequest1, conditionalPlaceRequest2 );
    }

    @Test
    public void falseEvaluatedConditionalPlaceRequestEqualsToAnotherFalseEvaluatedConditionalPlaceRequest() {
        final PlaceRequest conditionalPlaceRequest1 = new ConditionalPlaceRequest( "place1" ).when( p -> false ).orElse( new DefaultPlaceRequest( "place2" ) );
        final PlaceRequest conditionalPlaceRequest2 = new ConditionalPlaceRequest( "place3" ).when( p -> false ).orElse( new DefaultPlaceRequest( "place2" ) );

        equals( conditionalPlaceRequest1, conditionalPlaceRequest2 );
    }

    @Test
    public void trueEvaluatedConditionalPlaceRequestEqualsToAnotherFalseEvaluatedConditionalPlaceRequest() {
        final PlaceRequest conditionalPlaceRequest1 = new ConditionalPlaceRequest( "place1" ).when( p -> true ).orElse( new DefaultPlaceRequest( "place2" ) );
        final PlaceRequest conditionalPlaceRequest2 = new ConditionalPlaceRequest( "place3" ).when( p -> false ).orElse( new DefaultPlaceRequest( "place1" ) );

        equals( conditionalPlaceRequest1, conditionalPlaceRequest2 );
    }

    @Test
    public void falseEvaluatedConditionalPlaceRequestEqualsToAnotherTrueEvaluatedConditionalPlaceRequest() {
        final PlaceRequest conditionalPlaceRequest1 = new ConditionalPlaceRequest( "place1" ).when( p -> false ).orElse( new DefaultPlaceRequest( "place2" ) );
        final PlaceRequest conditionalPlaceRequest2 = new ConditionalPlaceRequest( "place2" ).when( p -> true ).orElse( new DefaultPlaceRequest( "place3" ) );

        equals( conditionalPlaceRequest1, conditionalPlaceRequest2 );
    }

    private void equals( final PlaceRequest placeRequest1,
                         final PlaceRequest placeRequest2 ) {
        assertTrue( placeRequest1.equals( placeRequest2 ) );
        assertTrue( placeRequest2.equals( placeRequest1 ) );
        assertEquals( placeRequest1.hashCode(), placeRequest2.hashCode() );
    }

    private void notEquals( final PlaceRequest placeRequest1,
                            final PlaceRequest placeRequest2 ) {
        assertFalse( placeRequest1.equals( placeRequest2 ) );
        assertFalse( placeRequest2.equals( placeRequest1 ) );
        assertNotEquals( placeRequest1.hashCode(), placeRequest2.hashCode() );
    }
}


text:
package org.apache.usergrid.cassandra;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** @author Mathieu Carbou (mathieu.carbou@gmail.com) */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface Concurrent {
    int threads() default 5;
}


text:
module load fsl

echo "Getting seed sizes for combined eddy corrected..."
cd /scratch/projects/UT/poldracklab/poldrack/selftracking/MRI/stanford_diffusion/combined_eddy_corrected/
ls seed_masks/* > foo
cat foo | sed 's/^/fslstats /' | sed 's/$/ -V/' | bash > tmp
cat tmp | cut -d" " -f1 > seedsizes
rm tmp

#echo "Getting seed sizes for skyra..."
#cd /scratch/PI/russpold/data/MYCONNECTOME/skyra_data/
#ls seed_masks/* > foo
#cat foo | sed 's/^/fslstats /' | sed 's/$/ -V/' | bash > tmp
#cat tmp | cut -d" " -f1 > seedsizes
rm tmp


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateTempScoreboardTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('temp_scoreboard', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('center_id')->unsigned();
            $table->string('routing_key', 150);
            $table->timestamps();
            $table->dateTime('expires_at')->nullable();
            $table->integer('value');
            $table->unique(['center_id', 'routing_key']);
        });

        Schema::create('temp_scoreboard_log', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('center_id')->unsigned();
            $table->integer('quarter_id')->unsigned()->nullable();
            $table->integer('stats_report_id')->unsigned()->nullable();
            $table->string('game', 50)->nullable();
            $table->string('type', 50)->nullable();
            $table->integer('value');
            $table->timestamps();
            $table->index(['center_id', 'quarter_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('temp_scoreboard_log');
        Schema::dropIfExists('temp_scoreboard');
    }
}


text:
module Dyalikeblags
  class Image < ActiveRecord::Base

  	before_destroy :delete_image_file
  	validates :file_name, :name,  uniqueness: true

  	@@public_root = "public"
  	@@public_directory = "images"
  	@@full_path = 	@@public_root + "/" + @@public_directory

  	def self.upload(image_file)
  			#upload image
		    file_name = image_file.original_filename

		    if !Image.exists?(file_name)
			    path = File.join( @@full_path , file_name)
			    File.open(path, "wb") { |f| f.write(image_file.read) }
			  end
		end

  	def delete_image_file
  		if Image.exists?(self.file_name)
  			File.delete(full_path)
  		end
  	end

  	def link_path
			"/" + @@public_directory + "/" + self.file_name
		end

		def full_path
  		@@full_path + "/" + self.file_name
  	end

  	#class methods
		def self.exists?(file_name)
			 File.file?(@@full_path + "/" + file_name)
		end

		def self.public_directory
			@@public_directory
		end

  end
end


text:
static float conditionContrast(float contrast);

@interface CCEffectContrast ()
@property (nonatomic, strong) NSNumber *conditionedContrast;
@end

@interface CCEffectContrastImpl : CCEffectImpl
@property (nonatomic, weak) CCEffectContrast *interface;
@end

@implementation CCEffectContrastImpl

-(id)initWithInterface:(CCEffectContrast *)interface
{
    CCEffectUniform* uniformContrast = [CCEffectUniform uniform:@"float" name:@"u_contrast" value:[NSNumber numberWithFloat:1.0f]];

    NSArray *fragFunctions = [CCEffectContrastImpl buildFragmentFunctions];
    NSArray *renderPasses = [CCEffectContrastImpl buildRenderPassesWithInterface:interface];

    if((self = [super initWithRenderPasses:renderPasses fragmentFunctions:fragFunctions vertexFunctions:nil fragmentUniforms:@[uniformContrast] vertexUniforms:nil varyings:nil]))
    {
        self.interface = interface;
        self.debugName = @"CCEffectContrastImpl";
    }
    return self;
}

+ (NSArray *)buildFragmentFunctions
{
    CCEffectFunctionInput *input = [[CCEffectFunctionInput alloc] initWithType:@"vec4" name:@"inputValue" initialSnippet:CCEffectDefaultInitialInputSnippet snippet:CCEffectDefaultInputSnippet];

    NSString* effectBody = CC_GLSL(
                                   vec3 offset = vec3(0.5) * inputValue.a;
                                   return vec4(((inputValue.rgb - offset) * vec3(u_contrast) + offset), inputValue.a);
                                   );

    CCEffectFunction* fragmentFunction = [[CCEffectFunction alloc] initWithName:@"contrastEffect" body:effectBody inputs:@[input] returnType:@"vec4"];
    return @[fragmentFunction];
}

+ (NSArray *)buildRenderPassesWithInterface:(CCEffectContrast *)interface
{
    __weak CCEffectContrast *weakInterface = interface;

    CCEffectRenderPass *pass0 = [[CCEffectRenderPass alloc] init];
    pass0.debugLabel = @"CCEffectContrast pass 0";
    pass0.beginBlocks = @[[[CCEffectRenderPassBeginBlockContext alloc] initWithBlock:^(CCEffectRenderPass *pass, CCEffectRenderPassInputs *passInputs){

        passInputs.shaderUniforms[CCShaderUniformMainTexture] = passInputs.previousPassTexture;
        passInputs.shaderUniforms[CCShaderUniformPreviousPassTexture] = passInputs.previousPassTexture;
        passInputs.shaderUniforms[CCShaderUniformTexCoord1Center] = [NSValue valueWithGLKVector2:passInputs.texCoord1Center];
        passInputs.shaderUniforms[CCShaderUniformTexCoord1Extents] = [NSValue valueWithGLKVector2:passInputs.texCoord1Extents];

        passInputs.shaderUniforms[passInputs.uniformTranslationTable[@"u_contrast"]] = weakInterface.conditionedContrast;
    }]];

    return @[pass0];
}

@end

@implementation CCEffectContrast

-(id)init
{
    return [self initWithContrast:0.0f];
}

-(id)initWithContrast:(float)contrast
{
    if((self = [super init]))
    {
        _contrast = contrast;
        _conditionedContrast = [NSNumber numberWithFloat:conditionContrast(contrast)];

        self.effectImpl = [[CCEffectContrastImpl alloc] initWithInterface:self];
        self.debugName = @"CCEffectContrast";
    }
    return self;
}

+(instancetype)effectWithContrast:(float)contrast
{
    return [[self alloc] initWithContrast:contrast];
}

-(void)setContrast:(float)contrast
{
    _contrast = contrast;
    _conditionedContrast = [NSNumber numberWithFloat:conditionContrast(contrast)];
}

@end

float conditionContrast(float contrast)
{
    NSCAssert((contrast >= -1.0) && (contrast <= 1.0), @"Supplied contrast out of range [-1..1].");

    // Yes, this value is somewhat magical. It was arrived at experimentally by comparing
    // our results at min and max contrast (-1 and 1 respectively) with the results from
    // various image editing applications at their own min and max contrast values.
    static const float kContrastBase = 4.0f;

    float clampedExp = clampf(contrast, -1.0f, 1.0f);
    return powf(kContrastBase, clampedExp);
}


text:
SELECT * FROM (
  SELECT MAX(A01) AS A01, MAX(A02) AS A02, MAX(A11) AS A11, MAX(B08) AS B08, MAX(B17) AS B17, COUNT(*) AS totalAllelesTyped, Id
  FROM
  (
    SELECT
    CASE WHEN ShortName = 'A01' THEN Status ELSE NULL END AS A01,
    CASE WHEN ShortName = 'A02' THEN Status ELSE NULL END AS A02,
    CASE WHEN ShortName = 'A11' THEN Status ELSE NULL END AS A11,
    CASE WHEN ShortName = 'B08' THEN Status ELSE NULL END AS B08,
    CASE WHEN ShortName = 'B17' THEN Status ELSE NULL END AS B17,
    Id
    FROM study.MHC_SSP_Summary
  )
  X GROUP BY Id
) Y
WHERE totalAllelesTyped > 0


text:
package org.springframework.boot.actuate.endpoint.jmx;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.boot.actuate.endpoint.LoggersEndpoint;
import org.springframework.boot.logging.logback.LogbackLoggingSystem;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.jmx.export.MBeanExporter;
import org.springframework.jmx.support.ObjectNameManager;
import org.springframework.util.ObjectUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage;

/**
 * Tests for {@link EndpointMBeanExporter}
 *
 * @author Christian Dupuis
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 */
public class EndpointMBeanExporterTests {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	GenericApplicationContext context = null;

	@After
	public void close() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@Test
	public void testRegistrationOfOneEndpoint() throws Exception {
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class));
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(TestEndpoint.class));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		MBeanInfo mbeanInfo = mbeanExporter.getServer()
				.getMBeanInfo(getObjectName("endpoint1", this.context));
		assertThat(mbeanInfo).isNotNull();
		assertThat(mbeanInfo.getOperations().length).isEqualTo(3);
		assertThat(mbeanInfo.getAttributes().length).isEqualTo(3);
	}

	@Test
	public void testSkipRegistrationOfDisabledEndpoint() throws Exception {
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class));
		MutablePropertyValues mpv = new MutablePropertyValues();
		mpv.add("enabled", Boolean.FALSE);
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(TestEndpoint.class, null, mpv));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		assertThat(mbeanExporter.getServer()
				.isRegistered(getObjectName("endpoint1", this.context))).isFalse();
	}

	@Test
	public void testRegistrationOfEnabledEndpoint() throws Exception {
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class));
		MutablePropertyValues mpv = new MutablePropertyValues();
		mpv.add("enabled", Boolean.TRUE);
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(TestEndpoint.class, null, mpv));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		assertThat(mbeanExporter.getServer()
				.isRegistered(getObjectName("endpoint1", this.context))).isTrue();
	}

	@Test
	public void testRegistrationTwoEndpoints() throws Exception {
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class));
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(TestEndpoint.class));
		this.context.registerBeanDefinition("endpoint2",
				new RootBeanDefinition(TestEndpoint2.class));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		assertThat(mbeanExporter.getServer()
				.getMBeanInfo(getObjectName("endpoint1", this.context))).isNotNull();
		assertThat(mbeanExporter.getServer()
				.getMBeanInfo(getObjectName("endpoint2", this.context))).isNotNull();
	}

	@Test
	public void testRegistrationWithDifferentDomain() throws Exception {
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class, null,
						new MutablePropertyValues(
								Collections.singletonMap("domain", "test-domain"))));
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(TestEndpoint.class));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		assertThat(mbeanExporter.getServer().getMBeanInfo(
				getObjectName("test-domain", "endpoint1", false, this.context)))
						.isNotNull();
	}

	@Test
	public void testRegistrationWithDifferentDomainAndIdentity() throws Exception {
		Map<String, Object> properties = new HashMap<String, Object>();
		properties.put("domain", "test-domain");
		properties.put("ensureUniqueRuntimeObjectNames", true);
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class, null,
						new MutablePropertyValues(properties)));
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(TestEndpoint.class));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		assertThat(mbeanExporter.getServer().getMBeanInfo(
				getObjectName("test-domain", "endpoint1", true, this.context)))
						.isNotNull();
	}

	@Test
	public void testRegistrationWithDifferentDomainAndIdentityAndStaticNames()
			throws Exception {
		Map<String, Object> properties = new HashMap<String, Object>();
		properties.put("domain", "test-domain");
		properties.put("ensureUniqueRuntimeObjectNames", true);
		Properties staticNames = new Properties();
		staticNames.put("key1", "value1");
		staticNames.put("key2", "value2");
		properties.put("objectNameStaticProperties", staticNames);
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class, null,
						new MutablePropertyValues(properties)));
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(TestEndpoint.class));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		assertThat(mbeanExporter.getServer().getMBeanInfo(ObjectNameManager.getInstance(
				getObjectName("test-domain", "endpoint1", true, this.context).toString()
						+ ",key1=value1,key2=value2"))).isNotNull();
	}

	@Test
	public void testRegistrationWithParentContext() throws Exception {
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class));
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(TestEndpoint.class));
		GenericApplicationContext parent = new GenericApplicationContext();
		this.context.setParent(parent);
		parent.refresh();
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		assertThat(mbeanExporter.getServer()
				.getMBeanInfo(getObjectName("endpoint1", this.context))).isNotNull();
		parent.close();
	}

	@Test
	public void jsonMapConversionWithDefaultObjectMapper() throws Exception {
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class));
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(JsonMapConversionEndpoint.class));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		Object response = mbeanExporter.getServer().invoke(
				getObjectName("endpoint1", this.context), "getData", new Object[0],
				new String[0]);
		assertThat(response).isInstanceOf(Map.class);
		assertThat(((Map<?, ?>) response).get("date")).isInstanceOf(Long.class);
	}

	@Test
	public void jsonMapConversionWithCustomObjectMapper() throws Exception {
		this.context = new GenericApplicationContext();
		ConstructorArgumentValues constructorArgs = new ConstructorArgumentValues();
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
		constructorArgs.addIndexedArgumentValue(0, objectMapper);
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class, constructorArgs,
						null));
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(JsonMapConversionEndpoint.class));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		Object response = mbeanExporter.getServer().invoke(
				getObjectName("endpoint1", this.context), "getData", new Object[0],
				new String[0]);
		assertThat(response).isInstanceOf(Map.class);
		assertThat(((Map<?, ?>) response).get("date")).isInstanceOf(String.class);
	}

	@Test
	public void jsonListConversion() throws Exception {
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class));
		this.context.registerBeanDefinition("endpoint1",
				new RootBeanDefinition(JsonListConversionEndpoint.class));
		this.context.refresh();
		MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
		Object response = mbeanExporter.getServer().invoke(
				getObjectName("endpoint1", this.context), "getData", new Object[0],
				new String[0]);
		assertThat(response).isInstanceOf(List.class);
		assertThat(((List<?>) response).get(0)).isInstanceOf(Long.class);
	}

	@Test
	public void loggerEndpointLowerCaseLogLevel() throws Exception {
		MBeanExporter mbeanExporter = registerLoggersEndpoint();
		Object response = mbeanExporter.getServer().invoke(
				getObjectName("loggersEndpoint", this.context), "setLogLevel",
				new Object[] { "com.example", "trace" },
				new String[] { String.class.getName(), String.class.getName() });
		assertThat(response).isNull();
	}

	@Test
	public void loggerEndpointUnknownLogLevel() throws Exception {
		MBeanExporter mbeanExporter = registerLoggersEndpoint();
		this.thrown.expect(MBeanException.class);
		this.thrown.expectCause(hasMessage(containsString("No enum constant")));
		this.thrown.expectCause(hasMessage(containsString("LogLevel.INVALID")));
		mbeanExporter.getServer().invoke(getObjectName("loggersEndpoint", this.context),
				"setLogLevel", new Object[] { "com.example", "invalid" },
				new String[] { String.class.getName(), String.class.getName() });
	}

	private MBeanExporter registerLoggersEndpoint() {
		this.context = new GenericApplicationContext();
		this.context.registerBeanDefinition("endpointMbeanExporter",
				new RootBeanDefinition(EndpointMBeanExporter.class));
		RootBeanDefinition bd = new RootBeanDefinition(LoggersEndpoint.class);
		ConstructorArgumentValues values = new ConstructorArgumentValues();
		values.addIndexedArgumentValue(0,
				new LogbackLoggingSystem(getClass().getClassLoader()));
		bd.setConstructorArgumentValues(values);
		this.context.registerBeanDefinition("loggersEndpoint", bd);
		this.context.refresh();
		return this.context.getBean(EndpointMBeanExporter.class);
	}

	private ObjectName getObjectName(String beanKey, GenericApplicationContext context)
			throws MalformedObjectNameException {
		return getObjectName("org.springframework.boot", beanKey, false, context);
	}

	private ObjectName getObjectName(String domain, String beanKey,
			boolean includeIdentity, ApplicationContext applicationContext)
					throws MalformedObjectNameException {
		if (includeIdentity) {
			return ObjectNameManager.getInstance(String.format(
					"%s:type=Endpoint,name=%s,identity=%s", domain, beanKey, ObjectUtils
							.getIdentityHexString(applicationContext.getBean(beanKey))));
		}
		return ObjectNameManager
				.getInstance(String.format("%s:type=Endpoint,name=%s", domain, beanKey));
	}

	public static class TestEndpoint extends AbstractEndpoint<String> {

		public TestEndpoint() {
			super("test");
		}

		@Override
		public String invoke() {
			return "hello world";
		}

	}

	public static class TestEndpoint2 extends TestEndpoint {

	}

	public static class JsonMapConversionEndpoint
			extends AbstractEndpoint<Map<String, Object>> {

		public JsonMapConversionEndpoint() {
			super("json_map_conversion");
		}

		@Override
		public Map<String, Object> invoke() {
			Map<String, Object> result = new LinkedHashMap<String, Object>();
			result.put("date", new Date());
			return result;
		}

	}

	public static class JsonListConversionEndpoint
			extends AbstractEndpoint<List<Object>> {

		public JsonListConversionEndpoint() {
			super("json_list_conversion");
		}

		@Override
		public List<Object> invoke() {
			return Arrays.<Object>asList(new Date());
		}

	}

}


text:
HDFS for Go
===========

[![GoDoc](https://godoc.org/github.com/colinmarc/hdfs/web?status.svg)](https://godoc.org/github.com/colinmarc/hdfs) [![build](https://travis-ci.org/colinmarc/hdfs.svg?branch=master)](https://travis-ci.org/colinmarc/hdfs)

This is a native golang client for hdfs. It connects directly to the namenode using
the protocol buffers API.

It tries to be idiomatic by aping the stdlib `os` package, where possible, and
implements the interfaces from it, including `os.FileInfo` and `os.PathError`.

Here's what it looks like in action:

```go
client, _ := hdfs.New("namenode:8020")

file, _ := client.Open("/mobydick.txt")

buf := make([]byte, 59)
file.ReadAt(buf, 48847)

fmt.Println(string(buf))
// => Abominable are the tumblers into which he pours his poison.
```

For complete documentation, check out the [Godoc][1].

The `hdfs` Binary
-----------------

Along with the library, this repo contains a commandline client for HDFS. Like
the library, its primary aim is to be idiomatic, by enabling your favorite unix
verbs:

    $ hdfs --help
    Usage: hdfs COMMAND
    The flags available are a subset of the POSIX ones, but should behave similarly.

    Valid commands:
      ls [-lah] [FILE]...
      rm [-rf] FILE...
      mv [-fT] SOURCE... DEST
      mkdir [-p] FILE...
      touch [-amc] FILE...
      chmod [-R] OCTAL-MODE FILE...
      chown [-R] OWNER[:GROUP] FILE...
      cat SOURCE...
      head [-n LINES | -c BYTES] SOURCE...
      tail [-n LINES | -c BYTES] SOURCE...
      du [-sh] FILE...
      checksum FILE...
      get SOURCE [DEST]
      getmerge SOURCE DEST
      put SOURCE DEST

Since it doesn't have to wait for the JVM to start up, it's also a lot faster
`hadoop -fs`:

    $ time hadoop fs -ls / > /dev/null

    real  0m2.218s
    user  0m2.500s
    sys 0m0.376s

    $ time hdfs ls / > /dev/null

    real  0m0.015s
    user  0m0.004s
    sys 0m0.004s

Best of all, it comes with bash tab completion for paths!

Installing the commandline client
---------------------------------

Grab a tarball from the [releases page](https://github.com/colinmarc/hdfs/releases)
and unzip it wherever you like.

To configure the client, make sure one or both of these environment variables
point to your Hadoop configuration (`core-site.xml` and `hdfs-site.xml`). On
systems with Hadoop installed, they should already be set.

    $ export HADOOP_HOME="/etc/hadoop"
    $ export HADOOP_CONF_DIR="/etc/hadoop/conf"

To install tab completion globally on linux, copy or link the `bash_completion`
file which comes with the tarball into the right place:

    $ ln -sT bash_completion /etc/bash_completion.d/gohdfs

By default on non-kerberized clusters, the HDFS user is set to the
currently-logged-in user. You can override this with another environment
variable:

    $ export HADOOP_USER_NAME=username

Using the commandline client with Kerberos authentication
---------------------------------------------------------

Like `hadoop fs`, the commandline client expects a `ccache` file in the default
location: `/tmp/krb5cc_<uid>`. That means it should 'just work' to use `kinit`:

    $ kinit bob@EXAMPLE.com
    $ hdfs ls /

If that doesn't work, try setting the `KRB5CCNAME` environment variable to
wherever you have the `ccache` saved.

Compatibility
-------------

This library uses "Version 9" of the HDFS protocol, which means it should work
with hadoop distributions based on 2.2.x and above. The tests run against CDH
5.x and HDP 2.x.

Acknowledgements
----------------

This library is heavily indebted to [snakebite][3].

[1]: https://godoc.org/github.com/colinmarc/hdfs
[2]: https://golang.org/doc/install
[3]: https://github.com/spotify/snakebite


text:
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * appProdUrlMatcher
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appProdUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        // project_homepage
        if (0 === strpos($pathinfo, '/hello') && preg_match('#^/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'project_homepage')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::indexAction',));
        }

        if (0 === strpos($pathinfo, '/projet')) {
            // project_list
            if ($pathinfo === '/projets') {
                return array (  '_controller' => 'projectBundle\\Controller\\DefaultController::listProjectAction',  '_route' => 'project_list',);
            }

            if (0 === strpos($pathinfo, '/projet/intervenant')) {
                // Projet_inter
                if (0 === strpos($pathinfo, '/projet/intervenant/idprojet') && preg_match('#^/projet/intervenant/idprojet\\=(?P<idprojet>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'Projet_inter')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::ProjetinterAction',));
                }

                if (0 === strpos($pathinfo, '/projet/intervenant/ajouter/interc')) {
                    // Projet_interCl
                    if (0 === strpos($pathinfo, '/projet/intervenant/ajouter/intercl/idprojet') && preg_match('#^/projet/intervenant/ajouter/intercl/idprojet\\=(?P<idprojet>[^/]++)$#s', $pathinfo, $matches)) {
                        return $this->mergeDefaults(array_replace($matches, array('_route' => 'Projet_interCl')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::ProjetinterClAction',));
                    }

                    // Projet_interCap
                    if (0 === strpos($pathinfo, '/projet/intervenant/ajouter/intercap/idprojet') && preg_match('#^/projet/intervenant/ajouter/intercap/idprojet\\=(?P<idprojet>[^/]++)$#s', $pathinfo, $matches)) {
                        return $this->mergeDefaults(array_replace($matches, array('_route' => 'Projet_interCap')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::ProjetinterCapAction',));
                    }

                }

            }

            if (0 === strpos($pathinfo, '/projet/besoin')) {
                // Besoin_list
                if (0 === strpos($pathinfo, '/projet/besoin/projet') && preg_match('#^/projet/besoin/projet\\=(?P<idprojet>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'Besoin_list')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::listBesoinAction',));
                }

                // Besoin_add
                if (0 === strpos($pathinfo, '/projet/besoin/ajouter/projet') && preg_match('#^/projet/besoin/ajouter/projet\\=(?P<idprojet>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'Besoin_add')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::addBesoinAction',));
                }

                if (0 === strpos($pathinfo, '/projet/besoin/version')) {
                    // Vbesoin_add
                    if (0 === strpos($pathinfo, '/projet/besoin/version/ajouter/projet') && preg_match('#^/projet/besoin/version/ajouter/projet\\=(?P<idprojet>[^/]++)/b\\=(?P<idbesoin>[^/]++)$#s', $pathinfo, $matches)) {
                        return $this->mergeDefaults(array_replace($matches, array('_route' => 'Vbesoin_add')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::addVersionBesoinAction',));
                    }

                    // Doc_add
                    if (0 === strpos($pathinfo, '/projet/besoin/version/doc/projet') && preg_match('#^/projet/besoin/version/doc/projet\\=(?P<idprojet>[^/]++)/vBesoin\\=(?P<vBesoin>[^/]++)$#s', $pathinfo, $matches)) {
                        return $this->mergeDefaults(array_replace($matches, array('_route' => 'Doc_add')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::uploadAction',));
                    }

                }

            }

            if (0 === strpos($pathinfo, '/projet/exigence')) {
                // Exigence_add
                if (0 === strpos($pathinfo, '/projet/exigence/ajouter/projet') && preg_match('#^/projet/exigence/ajouter/projet\\=(?P<idprojet>[^/]++)/vBesoin\\=(?P<vBesoin>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'Exigence_add')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::addExigenceAction',));
                }

                // Exigence_list
                if (0 === strpos($pathinfo, '/projet/exigence/projet') && preg_match('#^/projet/exigence/projet\\=(?P<idprojet>[^/]++)/vBesoin\\=(?P<vBesoin>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'Exigence_list')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::listExigenceAction',));
                }

            }

            if (0 === strpos($pathinfo, '/projet/a')) {
                // projet_add
                if ($pathinfo === '/projet/ajouter') {
                    return array (  '_controller' => 'projectBundle\\Controller\\DefaultController::addProjectAction',  '_route' => 'projet_add',);
                }

                // projet_archive
                if ($pathinfo === '/projet/archiver') {
                    return array (  '_controller' => 'projectBundle\\Controller\\DefaultController::achiverProjetAction',  '_route' => 'projet_archive',);
                }

            }

            // VExigence_add
            if (0 === strpos($pathinfo, '/projet/exigence/version/ajouter/projet') && preg_match('#^/projet/exigence/version/ajouter/projet\\=(?P<idprojet>[^/]++)/vBesoin\\=(?P<vBesoin>[^/]++)/idExig\\=(?P<idExig>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'VExigence_add')), array (  '_controller' => 'projectBundle\\Controller\\DefaultController::addVexigenceAction',));
            }

            if (0 === strpos($pathinfo, '/projet/client')) {
                // Client_add
                if ($pathinfo === '/projet/client/ajouter') {
                    return array (  '_controller' => 'projectBundle\\Controller\\DefaultController::addClientAction',  '_route' => 'Client_add',);
                }

                // Client_list
                if (rtrim($pathinfo, '/') === '/projet/client') {
                    if (substr($pathinfo, -1) !== '/') {
                        return $this->redirect($pathinfo.'/', 'Client_list');
                    }

                    return array (  '_controller' => 'projectBundle\\Controller\\DefaultController::listClientAction',  '_route' => 'Client_list',);
                }

            }

        }

        // profile_homepage
        if ($pathinfo === '/dashbord') {
            return array (  '_controller' => 'profileBundle\\Controller\\DefaultController::indexAction',  '_route' => 'profile_homepage',);
        }

        // profile_voir
        if ($pathinfo === '/profile') {
            return array (  '_controller' => 'profileBundle\\Controller\\DefaultController::indexAction',  '_route' => 'profile_voir',);
        }

        if (0 === strpos($pathinfo, '/log')) {
            if (0 === strpos($pathinfo, '/login')) {
                // user_login
                if ($pathinfo === '/login') {
                    return array (  '_controller' => 'userBundle\\Controller\\UserController::loginAction',  '_route' => 'user_login',);
                }

                // user_login_check
                if ($pathinfo === '/login_check') {
                    return array('_route' => 'user_login_check');
                }

            }

            // user_logout
            if ($pathinfo === '/logout') {
                return array (  '_controller' => 'userBundle\\Controller\\UserController::logoutAction',  '_route' => 'user_logout',);
            }

        }

        if (0 === strpos($pathinfo, '/dashboard')) {
            // user_dashboard
            if ($pathinfo === '/dashboard') {
                return array (  '_controller' => 'userBundle\\Controller\\UserController::dashboardAction',  '_route' => 'user_dashboard',);
            }

            // user_table
            if ($pathinfo === '/dashboard/table') {
                return array (  '_controller' => 'userBundle\\Controller\\UserController::tableAction',  '_route' => 'user_table',);
            }

        }

        if (0 === strpos($pathinfo, '/utilisateur')) {
            // user_gestion
            if ($pathinfo === '/utilisateur') {
                return array (  '_controller' => 'userBundle\\Controller\\UserController::listAction',  '_route' => 'user_gestion',);
            }

            // user_add
            if ($pathinfo === '/utilisateur/ajouter') {
                return array (  '_controller' => 'userBundle\\Controller\\UserController::addAction',  '_route' => 'user_add',);
            }

        }

        // homepage
        if ($pathinfo === '/app/example') {
            return array (  '_controller' => 'AppBundle\\Controller\\DefaultController::indexAction',  '_route' => 'homepage',);
        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}


text:
var rows = $('tbody:eq(0) tr');

// PO123456789BR
var regExp = /[a-zA-Z]{2}\d{9}[a-zA-Z]{2}/;

rows.each(function() {
	$this = $(this)

	var codeCol = $this.find("td:eq(0)");

	var validateCol = $this.find("td:eq(1)");

	if(validateCol.length > 0) {

		var rast = regExp.exec($this.html());

                flag = String(rast).slice(-2).toLowerCase();

                $(`<span class="flag-icon flag-icon-` + flag + `" style="vertical-align: initial;"></span>`).prependTo(codeCol);

		$(`<form style="display:inline" method="POST" target="_blank" action="https://www2.correios.com.br/sistemas/rastreamento/resultado_semcontent.cfm">
		<input type="hidden" name="Objetos" value="` + rast + `">
		<input class="icone-categoria" style="width:20px;margin-bottom:-5px" type="image" value=" " src=` + chrome.extension.getURL("img/correios_icon.jpg") + `>
		</form>`).prependTo(codeCol);
	}
});


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public string PrimarySiteCollectionAdmin { get; set; }
```

### Property Value
Type: System.String

## See also
- [SiteCollection](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.SiteCollection.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201705.md)


text:
module TxtDB
  module SQL
    module Create

      class CreateDatabase

        def set_parameters(params)
          set_parameters_tests = at_least_one_parameter?(params) && no_more_than_one_parameter?(params)
          if (set_parameters_tests) then
            @database_name = params.shift
          end
          set_parameters_tests
        end

        def execute
          TxtDB::FileSystem::create_database(@database_name)
        end

        private

        def at_least_one_parameter?(params)
          params.count > 0
        end

        def no_more_than_one_parameter?(params)
          params.count < 2
        end

      end

    end
  end
end


text:
package com.taobao.meta.test;

import org.junit.Assert;

import org.junit.Test;

import com.taobao.metamorphosis.exception.InvalidConsumerConfigException;

/**
 * meta¼¯³É²âÊÔ_groupΪ¿Õ
 *
 * @author gongyangyu(gongyangyu@taobao.com)
 *
 */

public class BlankGroupTest extends BaseMetaTest {

	private final String topic = "meta-test";

	@Test
	public void sendConsume() throws Exception {
		createProducer();
		// ÐèÒª·¢²¼topic
		producer.publish(this.topic);
		try {
			// ¶©ÔÄÕßδָ¶¨·Ö×é
			createConsumer2();
			Assert.fail();

			// ·¢ËÍÏûÏ¢
			final int count = 5;
			sendMessage(count, "hello", this.topic);

			// ¶©ÔĽÓÊÕÏûÏ¢²¢ÑéÖ¤Êý¾ÝÕýÈ·
			subscribe(this.topic, 1024 * 1024, count);

		} catch (Exception e) {
			Assert.assertTrue(e instanceof InvalidConsumerConfigException);
			System.out.println("fuck");
			Assert.assertTrue(e.getMessage().indexOf("Blank group") != -1);
		} finally {
			producer.shutdown();
			if (null != consumer) {
				consumer.shutdown();
			}
		}

	}

}


text:
#ifndef __MONO_PERFCOUNTERS_H__
#define __MONO_PERFCOUNTERS_H__

#include <glib.h>
#include <metadata/object.h>
#include <utils/mono-compiler.h>

typedef struct _MonoCounterSample MonoCounterSample;

void* mono_perfcounter_get_impl (MonoString* category, MonoString* counter, MonoString* instance,
		MonoString* machine, int *type, MonoBoolean *custom) MONO_INTERNAL;

MonoBoolean mono_perfcounter_get_sample (void *impl, MonoBoolean only_value, MonoCounterSample *sample) MONO_INTERNAL;

gint64 mono_perfcounter_update_value    (void *impl, MonoBoolean do_incr, gint64 value) MONO_INTERNAL;
void   mono_perfcounter_free_data       (void *impl) MONO_INTERNAL;

/* Category icalls */
MonoBoolean mono_perfcounter_category_del    (MonoString *name) MONO_INTERNAL;
MonoString* mono_perfcounter_category_help   (MonoString *category, MonoString *machine) MONO_INTERNAL;
MonoBoolean mono_perfcounter_category_exists (MonoString *counter, MonoString *category, MonoString *machine) MONO_INTERNAL;
MonoBoolean mono_perfcounter_create          (MonoString *category, MonoString *help, int type, MonoArray *items) MONO_INTERNAL;
int         mono_perfcounter_instance_exists (MonoString *instance, MonoString *category, MonoString *machine) MONO_INTERNAL;
MonoArray*  mono_perfcounter_category_names  (MonoString *machine) MONO_INTERNAL;
MonoArray*  mono_perfcounter_counter_names   (MonoString *category, MonoString *machine) MONO_INTERNAL;
MonoArray*  mono_perfcounter_instance_names  (MonoString *category, MonoString *machine) MONO_INTERNAL;

#endif /* __MONO_PERFCOUNTERS_H__ */


text:
module Sparsacus
  # Runtime configuration options that will be
  # included alongside Document definitions
  #
  # @example Configure Sparsacus
  #   Sparsacus.configure do |config|
  #     config.test_mode = true
  #   end
  #
  # @attr [Boolean] test_mode True if Sparsacus is in test mode, otherwise false.
  #
  # @see Sparsacus.configure
  class Configuration
    class << self
      def defaults
        @default ||= {
          test_mode: false
        }
      end
    end

    attr_accessor :test_mode

    def initialize
      self.class.defaults.each_pair { |k, v| send("#{k}=", v) }
    end
  end
end


text:
package com.jakewharton.disklrucache;

import com.esotericsoftware.kryo.KryoException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.ProtocolException;

public class JournalApiTest {

    private CacheMap<String> cache;
    private InMemoryFileSystem fileSystem;
    private Journal<String> journal;

    @Before
    public void setUp() throws Exception {
        cache = new CacheMap<>();
        fileSystem = new InMemoryFileSystem();
        journal = new Journal<>(cache, fileSystem);
        journal.initJournal();
    }

    @Test
    public void testEmptyJournal() throws Exception {
        journal.close();

        Assert.assertEquals("Wrong file count in the FS", 1, fileSystem.count());

        long length = fileSystem.get(Journal.JOURNAL_FILE_NAME).length();

        new Journal<>(cache, fileSystem).close();

        Assert.assertEquals("Wrong file count in the FS", 1, fileSystem.count());

        long length2 = fileSystem.get(Journal.JOURNAL_FILE_NAME).length();
        Assert.assertEquals("File changed after reopening", length, length2);
    }

    @Test
    public void testReCreateEmptyJournal() throws Exception {
        journal.createEmptyJournal();
        testPut();
    }

    @Test
    public void testPut() throws Exception {
        for (int i = 0; i < 10; i++) {
            journal.put("k" + i, "m" + i, false);
        }

        journal.put("k3", "m32", true);
        journal.put("k4", "m4", true);

        journal.close();

        new Journal<>(cache, fileSystem).initJournal();

        String[][] expected = {
                {"k0", "m0"},
                {"k1", "m1"},
                {"k2", "m2"},
                {"k5", "m5"},
                {"k6", "m6"},
                {"k7", "m7"},
                {"k8", "m8"},
                {"k9", "m9"},
                {"k3", "m32"},
                {"k4", "m4"},
        };

        cache.assertEquals(expected);
    }

    @Test
    public void testCompactJournal() throws Exception {
        cache.map.put("k", "m");
        journal.put("k", "m", false);

        cache.map.put("a", "m1");
        journal.put("a", "m1", false);

        cache.map.put("b", "m2");
        journal.put("b", "m2", false);

        for (int i = 0; i < Journal.MAX_REDUNDANT_OPERATION_COUNT; i++) {
            cache.map.put("k", "m");
            journal.put("k", "m", true);
        }
        Assert.assertEquals("There should be exactly " + Journal.MAX_REDUNDANT_OPERATION_COUNT +
                " redundant operations", Journal.MAX_REDUNDANT_OPERATION_COUNT, journal.getRedundantOperations());

        journal.put("k", "m", true);

        Assert.assertEquals("There shouldn't be any redundant operations", 0, journal.getRedundantOperations());

        journal.close();

        journal = new Journal<>(cache, fileSystem);
        Assert.assertEquals("There shouldn't be any redundant operations", 0, journal.getRedundantOperations());

        String[][] expected = {
                {"a", "m1"},
                {"b", "m2"},
                {"k", "m"},
        };
        cache.assertEquals(expected);
    }

    @Test
    public void testAccess() throws Exception {
        for (int i = 0; i < 10; i++) {
            journal.put("k" + i, "m" + i, false);
        }

        journal.access("k0", true);
        journal.access("k1", false);

        String[][] expected = {
                {"k2", "m2"},
                {"k3", "m3"},
                {"k4", "m4"},
                {"k5", "m5"},
                {"k6", "m6"},
                {"k7", "m7"},
                {"k8", "m8"},
                {"k9", "m9"},
                {"k0", "m0"},
                {"k1", "m1"},
        };

        journal.close();

        new Journal<>(cache, fileSystem).initJournal();

        cache.assertEquals(expected);
    }

    @Test
    public void testRemove() throws Exception {
        for (int i = 0; i < 10; i++) {
            journal.put("k" + i, "m" + i, false);
        }

        journal.remove("k5");
        journal.remove("k0");
        journal.remove("k9");

        String[][] expected = {
                {"k1", "m1"},
                {"k2", "m2"},
                {"k3", "m3"},
                {"k4", "m4"},
                {"k6", "m6"},
                {"k7", "m7"},
                {"k8", "m8"},
        };

        journal.close();

        new Journal<>(cache, fileSystem).initJournal();

        cache.assertEquals(expected);
    }

    @Test(expected = IOException.class)
    public void testThrowCause() throws Exception {
        KryoException e = new KryoException(new RuntimeException());
        Journal.throwIOException(e);
    }

    @Test(expected = ProtocolException.class)
    public void testThrowCause2() throws Exception {
        KryoException e = new KryoException(new ProtocolException());
        Journal.throwIOException(e);
    }
}


text:
---
uid: SolidEdgePart.PartDocument.IsGeometricVersionDirty
summary: Retrieves whether the geometric version number of the assembly document is dirty or not.
remarks:
---


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

    angular
        .module('app.document')
        .factory('MathFuncList', MathFuncList);

    MathFuncList.$inject = [];

    function MathFuncList() {
        return new MathFuncListServiceObject();
    }

    function MathFuncListServiceObject() {
        this.createMathFuncList = function() {
            return new MathFuncListObject();
        }
    }

    function MathFuncListObject() {

        // public
        this.getAll = getCopyOfMathFuncList;
        this.add = addMathFunc;
        this.remove = removeMathFunc;
        this.removeAll = removeAllMathFunc;
        this.isEmpty = isEmpty;

        //private

        this.mathFuncList = [];
        var nextId = 0;

        function getCopyOfMathFuncList() {
            return this.mathFuncList.slice();
        }

        function addMathFunc(mathFunc) {
            var id = getNextId();
            this.mathFuncList.push({id: id, func: mathFunc, status: true});
            return id;
        }

        function removeMathFunc(id) {
            var index = findFirstIndex(this.mathFuncList, function(item) {
                return item.id == id;
            });

            if (index == -1) {
                throw 'Internal error: no such mathFunc id: ' + id;
            }

            this.mathFuncList.splice(index, 1);
        }

        function removeAllMathFunc() {
            this.mathFuncList.length = 0;
        }

        function isEmpty() {
            return this.mathFuncList.length == 0;
        }

        function getNextId() {
            return nextId++;
        }

        function findFirstIndex(array, func) {
            for (var i = 0; i < array.length; i++) {
                if (func(array[i])) {
                    return i;
                }
            }
            return -1;
        }

    }

})();


text:
class Minitest::Test
  def setup
    DatabaseRewinder.clean_all
  end

  def teardown
    DatabaseRewinder.clean
  end
end


text:
layout: post
title: "Serving coffee in an espresso ..."
---
Serving coffee in an espresso cup doesn't make it espresso.


text:
/* globals Accounts, Tracker, ReactiveVar, FlowRouter, Accounts, HTTP, facebookConnectPlugin */

const _unstoreLoginToken = Accounts._unstoreLoginToken;
Accounts._unstoreLoginToken = function() {
	RocketChat.iframeLogin.tryLogin();
	_unstoreLoginToken.apply(Accounts, arguments);
};

class IframeLogin {
	constructor () {
		this.enabled = false;
		this.reactiveIframeUrl = new ReactiveVar();
		this.reactiveEnabled = new ReactiveVar();
		this.iframeUrl = undefined;
		this.apiUrl = undefined;
		this.apiMethod = undefined;

		Tracker.autorun((c) => {
			this.enabled = RocketChat.settings.get('Accounts_iframe_enabled');
			this.reactiveEnabled.set(this.enabled);

			this.iframeUrl = RocketChat.settings.get('Accounts_iframe_url');
			this.apiUrl = RocketChat.settings.get('Accounts_Iframe_api_url');
			this.apiMethod = RocketChat.settings.get('Accounts_Iframe_api_method');

			if (this.enabled === false) {
				return c.stop();
			}

			if (this.enabled === true && this.iframeUrl && this.apiUrl && this.apiMethod && FlowRouter.subsReady('userData', 'activeUsers')) {
				c.stop();
				if (!Accounts._storedLoginToken()) {
					this.tryLogin(() => {});
				}
			}
		});
	}

	tryLogin (callback) {
		if (!this.enabled) {
			return;
		}

		if (!this.iframeUrl || !this.apiUrl || !this.apiMethod) {
			return;
		}

		console.log('tryLogin');
		const options = {
			beforeSend: (xhr) => {
				xhr.withCredentials = true;
			}
		};

		let iframeUrl = this.iframeUrl;
		let separator = '?';
		if (iframeUrl.indexOf('?') > -1) {
			separator = '&';
		}

		if (window.cordova) {
			iframeUrl += separator + 'client=cordova';
		} else if (navigator.userAgent.indexOf('Electron') > -1) {
			iframeUrl += separator + 'client=electron';
		}

		HTTP.call(this.apiMethod, this.apiUrl, options, (error, result) => {
			console.log(error, result);
			if (result && result.data && result.data.token) {
				// TODO get from api
				result.data.token = 'yaMadZ1RMBdMzs6kGycKybrHVptoDl7nokxtorz1me0';
				this.loginWithToken(result.data.token, (error, result) => {
					if (error) {
						this.reactiveIframeUrl.set(iframeUrl);
					} else {
						this.reactiveIframeUrl.set();
					}
					callback(error, result);
				});
			} else {
				this.reactiveIframeUrl.set(iframeUrl);
				callback(error, result);
			}
		});
	}

	loginWithToken (token, callback) {
		if (!this.enabled) {
			return;
		}

		console.log('loginWithToken');
		Accounts.callLoginMethod({
			methodArguments: [{
				iframe: true,
				token: token
			}],
			userCallback: (err) => {
				if (err) {
					callback(err);
				}
			}
		});
	}
}

RocketChat.iframeLogin = new IframeLogin();

window.addEventListener('message', (e) => {
	if (! _.isObject(e.data)) {
		return;
	}

	console.log(e);

	switch (e.data.event) {
		case 'try-iframe-login':
			RocketChat.iframeLogin.tryLogin((error) => {
				if (error) {
					e.source.postMessage({
						event: 'login-error',
						response: error.message
					}, e.origin);
				}
			});
			break;

		case 'loggin-with-token':
			RocketChat.iframeLogin.loginWithToken(e.data.token, (error) => {
				if (error) {
					e.source.postMessage({
						event: 'login-error',
						response: error.message
					}, e.origin);
				}
			});
			break;

		case 'call-facebook-login':
			const fbLoginSuccess = (response) => {
				e.source.postMessage({
					event: 'facebook-login-success',
					response: response
				}, e.origin);
			};

			const fbLoginError = (error, response) => {
				e.source.postMessage({
					event: 'facebook-login-error',
					error: error,
					response: response
				}, e.origin);
			};

			if (typeof facebookConnectPlugin === 'undefined') {
				return fbLoginError('no-native-plugin');
			}

			facebookConnectPlugin.getLoginStatus((response) => {
				if (response.status === 'connected') {
					return fbLoginSuccess(response);
				}

				facebookConnectPlugin.login(e.data.permissions, fbLoginSuccess, (error) => {
					return fbLoginError('login-error', error);
				});
			}, (error) => {
				return fbLoginError('get-status-error', error);
			});
			break;
		}
});


text:
// (C) Copyright 2015 Moodle Pty Ltd.
//
// 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.

import { Injectable } from '@angular/core';
import { Params } from '@angular/router';
import { CoreContentLinksHandlerBase } from '@features/contentlinks/classes/base-handler';
import { CoreContentLinksAction } from '@features/contentlinks/services/contentlinks-delegate';
import { CoreNavigator } from '@services/navigator';
import { makeSingleton } from '@singletons';
import { AddonBlog } from '../blog';

/**
 * Handler to treat links to blog page.
 */
@Injectable({ providedIn: 'root' })
export class AddonBlogIndexLinkHandlerService extends CoreContentLinksHandlerBase {

    name = 'AddonBlogIndexLinkHandler';
    featureName = 'CoreUserDelegate_AddonBlog:blogs';
    pattern = /\/blog\/index\.php/;

    /**
     * @inheritdoc
     */
    getActions(siteIds: string[], url: string, params: Record<string, string>): CoreContentLinksAction[] {
        const pageParams: Params = {};

        params.userid ? pageParams['userId'] = parseInt(params.userid, 10) : null;
        params.modid ? pageParams['cmId'] = parseInt(params.modid, 10) : null;
        params.courseid ? pageParams['courseId'] = parseInt(params.courseid, 10) : null;
        params.entryid ? pageParams['entryId'] = parseInt(params.entryid, 10) : null;
        params.groupid ? pageParams['groupId'] = parseInt(params.groupid, 10) : null;
        params.tagid ? pageParams['tagId'] = parseInt(params.tagid, 10) : null;

        return [{
            action: (siteId: string): void => {
                CoreNavigator.navigateToSitePath('/blog', { params: pageParams, siteId });
            },
        }];
    }

    /**
     * @inheritdoc
     */
    isEnabled(siteId: string): Promise<boolean> {
        return AddonBlog.isPluginEnabled(siteId);
    }

}
export const AddonBlogIndexLinkHandler = makeSingleton(AddonBlogIndexLinkHandlerService);