text:
package org.apache.rocketmq.connect.runtime.connectorwrapper;

import com.alibaba.fastjson.JSON;
import io.openmessaging.KeyValue;
import io.openmessaging.connector.api.PositionStorageReader;
import io.openmessaging.connector.api.common.QueueMetaData;
import io.openmessaging.connector.api.data.Converter;
import io.openmessaging.connector.api.data.DataEntryBuilder;
import io.openmessaging.connector.api.data.EntryType;
import io.openmessaging.connector.api.data.Field;
import io.openmessaging.connector.api.data.Schema;
import io.openmessaging.connector.api.data.SinkDataEntry;
import io.openmessaging.connector.api.data.SourceDataEntry;
import io.openmessaging.connector.api.sink.SinkTask;
import io.openmessaging.connector.api.sink.SinkTaskContext;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.consumer.PullResult;
import org.apache.rocketmq.client.consumer.PullStatus;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.connect.runtime.common.ConnectKeyValue;
import org.apache.rocketmq.connect.runtime.common.LoggerName;
import org.apache.rocketmq.connect.runtime.config.RuntimeConfigDefine;
import org.apache.rocketmq.connect.runtime.converter.JsonConverter;
import org.apache.rocketmq.connect.runtime.converter.RocketMQConverter;
import org.apache.rocketmq.connect.runtime.service.PositionManagementService;
import org.apache.rocketmq.connect.runtime.store.PositionStorageReaderImpl;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A wrapper of {@link SinkTask} for runtime.
 */
public class WorkerSinkTask implements WorkerTask {

    private static final Logger log = LoggerFactory.getLogger(LoggerName.ROCKETMQ_RUNTIME);

    /**
     * The configuration key that provides the list of topicNames that are inputs for this SinkTask.
     */
    public static final String QUEUENAMES_CONFIG = "topicNames";

    /**
     * Connector name of current task.
     */
    private String connectorName;

    /**
     * The implements of the sink task.
     */
    private SinkTask sinkTask;

    /**
     * The configs of current sink task.
     */
    private ConnectKeyValue taskConfig;

    /**
     * Atomic state variable
     */
    private AtomicReference<WorkerTaskState> state;

    /**
     * Stop retry limit
     */

    /**
     * A RocketMQ consumer to pull message from MQ.
     */
    private final DefaultMQPullConsumer consumer;

    private final PositionManagementService offsetManagementService;

    /**
     *
     */
    private final PositionStorageReader offsetStorageReader;

    /**
     * A converter to parse sink data entry to object.
     */
    private Converter recordConverter;

    private final ConcurrentHashMap<MessageQueue, Long> messageQueuesOffsetMap;

    private final ConcurrentHashMap<MessageQueue, QueueState> messageQueuesStateMap;

    private static final Integer TIMEOUT = 3 * 1000;

    private static final Integer MAX_MESSAGE_NUM = 32;

    private static final String COMMA = ",";

    public static final String OFFSET_COMMIT_TIMEOUT_MS_CONFIG = "offset.flush.timeout.ms";

    private long nextCommitTime = 0;

    public WorkerSinkTask(String connectorName,
        SinkTask sinkTask,
        ConnectKeyValue taskConfig,
        PositionManagementService offsetManagementService,
        Converter recordConverter,
        DefaultMQPullConsumer consumer) {
        this.connectorName = connectorName;
        this.sinkTask = sinkTask;
        this.taskConfig = taskConfig;
        this.consumer = consumer;
        this.offsetManagementService = offsetManagementService;
        this.offsetStorageReader = new PositionStorageReaderImpl(offsetManagementService);
        this.recordConverter = recordConverter;
        this.messageQueuesOffsetMap = new ConcurrentHashMap<>(256);
        this.messageQueuesStateMap = new ConcurrentHashMap<>(256);
        this.state = new AtomicReference<>(WorkerTaskState.NEW);
    }

    /**
     * Start a sink task, and receive data entry from MQ cyclically.
     */
    @Override
    public void run() {
        try {
            consumer.start();
            log.info("Sink task consumer start.");
            state.compareAndSet(WorkerTaskState.NEW, WorkerTaskState.PENDING);
            sinkTask.initialize(new SinkTaskContext() {
                @Override
                public void resetOffset(QueueMetaData queueMetaData, Long offset) {
                    String shardingKey = queueMetaData.getShardingKey();
                    String queueName = queueMetaData.getQueueName();
                    if (StringUtils.isNotEmpty(shardingKey) && StringUtils.isNotEmpty(queueName)) {
                        String[] s = shardingKey.split(COMMA);
                        if (s.length == 2 && StringUtils.isNotEmpty(s[0]) && StringUtils.isNotEmpty(s[1])) {
                            String brokerName = s[0];
                            Integer queueId = Integer.valueOf(s[1]);
                            MessageQueue messageQueue = new MessageQueue(queueName, brokerName, queueId);
                            messageQueuesOffsetMap.put(messageQueue, offset);
                            offsetManagementService.putPosition(convertToByteBufferKey(messageQueue), convertToByteBufferValue(offset));
                            return;
                        }
                    }
                    log.warn("Missing parameters, queueMetaData {}", queueMetaData);
                }

                @Override
                public void resetOffset(Map<QueueMetaData, Long> offsets) {
                    for (Map.Entry<QueueMetaData, Long> entry : offsets.entrySet()) {
                        String shardingKey = entry.getKey().getShardingKey();
                        String queueName = entry.getKey().getQueueName();
                        if (StringUtils.isNotEmpty(shardingKey) && StringUtils.isNotEmpty(queueName)) {
                            String[] s = shardingKey.split(COMMA);
                            if (s.length == 2 && StringUtils.isNotEmpty(s[0]) && StringUtils.isNotEmpty(s[1])) {
                                String brokerName = s[0];
                                Integer queueId = Integer.valueOf(s[1]);
                                MessageQueue messageQueue = new MessageQueue(queueName, brokerName, queueId);
                                messageQueuesOffsetMap.put(messageQueue, entry.getValue());
                                offsetManagementService.putPosition(convertToByteBufferKey(messageQueue), convertToByteBufferValue(entry.getValue()));
                                continue;
                            }
                        }
                        log.warn("Missing parameters, queueMetaData {}", entry.getKey());
                    }
                }

                @Override
                public void pause(List<QueueMetaData> queueMetaDatas) {
                    if (null != queueMetaDatas && queueMetaDatas.size() > 0) {
                        for (QueueMetaData queueMetaData : queueMetaDatas) {
                            String shardingKey = queueMetaData.getShardingKey();
                            String queueName = queueMetaData.getQueueName();
                            if (StringUtils.isNotEmpty(shardingKey) && StringUtils.isNotEmpty(queueName)) {
                                String[] s = shardingKey.split(COMMA);
                                if (s.length == 2 && StringUtils.isNotEmpty(s[0]) && StringUtils.isNotEmpty(s[1])) {
                                    String brokerName = s[0];
                                    Integer queueId = Integer.valueOf(s[1]);
                                    MessageQueue messageQueue = new MessageQueue(queueName, brokerName, queueId);
                                    messageQueuesStateMap.put(messageQueue, QueueState.PAUSE);
                                    continue;
                                }
                            }
                            log.warn("Missing parameters, queueMetaData {}", queueMetaData);
                        }
                    }
                }

                @Override
                public void resume(List<QueueMetaData> queueMetaDatas) {
                    if (null != queueMetaDatas && queueMetaDatas.size() > 0) {
                        for (QueueMetaData queueMetaData : queueMetaDatas) {
                            String shardingKey = queueMetaData.getShardingKey();
                            String queueName = queueMetaData.getQueueName();
                            if (StringUtils.isNotEmpty(shardingKey) && StringUtils.isNotEmpty(queueName)) {
                                String[] s = shardingKey.split(COMMA);
                                if (s.length == 2 && StringUtils.isNotEmpty(s[0]) && StringUtils.isNotEmpty(s[1])) {
                                    String brokerName = s[0];
                                    Integer queueId = Integer.valueOf(s[1]);
                                    MessageQueue messageQueue = new MessageQueue(queueName, brokerName, queueId);
                                    messageQueuesStateMap.remove(messageQueue);
                                    continue;
                                }
                            }
                            log.warn("Missing parameters, queueMetaData {}", queueMetaData);
                        }
                    }
                }

                @Override
                public KeyValue configs() {
                    return taskConfig;
                }
            });

            String topicNamesStr = taskConfig.getString(QUEUENAMES_CONFIG);

            if (!StringUtils.isEmpty(topicNamesStr)) {
                String[] topicNames = topicNamesStr.split(COMMA);
                for (String topicName : topicNames) {
                    final Set<MessageQueue> messageQueues = consumer.fetchSubscribeMessageQueues(topicName);
                    for (MessageQueue messageQueue : messageQueues) {
                        final long offset = consumer.searchOffset(messageQueue, TIMEOUT);
                        messageQueuesOffsetMap.put(messageQueue, offset);
                    }
                    messageQueues.addAll(messageQueues);
                }
                log.debug("{} Initializing and starting task for topicNames {}", this, topicNames);
            } else {
                log.error("Lack of sink comsume topicNames config");
                state.set(WorkerTaskState.ERROR);
                return;
            }

            for (Map.Entry<MessageQueue, Long> entry : messageQueuesOffsetMap.entrySet()) {
                MessageQueue messageQueue = entry.getKey();
                ByteBuffer byteBuffer = offsetStorageReader.getPosition(convertToByteBufferKey(messageQueue));
                if (null != byteBuffer) {
                    messageQueuesOffsetMap.put(messageQueue, convertToOffset(byteBuffer));
                }
            }

            sinkTask.start(taskConfig);
            // we assume executed here means we are safe
            log.info("Sink task start, config:{}", JSON.toJSONString(taskConfig));
            state.compareAndSet(WorkerTaskState.PENDING, WorkerTaskState.RUNNING);

            while (WorkerTaskState.RUNNING == state.get()) {
                // this method can block up to 3 minutes long
                pullMessageFromQueues();
            }

            sinkTask.stop();
            state.compareAndSet(WorkerTaskState.STOPPING, WorkerTaskState.STOPPED);
            log.info("Sink task stop, config:{}", JSON.toJSONString(taskConfig));

        } catch (Exception e) {
            log.error("Run task failed.", e);
            state.set(WorkerTaskState.ERROR);
        } finally {
            if (consumer != null) {
                consumer.shutdown();
                log.info("Sink task consumer shutdown.");
            }
        }
    }

    private void pullMessageFromQueues() throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
        long startTimeStamp = System.currentTimeMillis();
        log.info("START pullMessageFromQueues, time started : {}", startTimeStamp);
        for (Map.Entry<MessageQueue, Long> entry : messageQueuesOffsetMap.entrySet()) {
            if (messageQueuesStateMap.containsKey(entry.getKey())) {
                continue;
            }
            log.info("START pullBlockIfNotFound, time started : {}", System.currentTimeMillis());

            if (WorkerTaskState.RUNNING != state.get()) {
                break;
            }
            final PullResult pullResult = consumer.pullBlockIfNotFound(entry.getKey(), "*", entry.getValue(), MAX_MESSAGE_NUM);
            long currentTime = System.currentTimeMillis();

            log.info("INSIDE pullMessageFromQueues, time elapsed : {}", currentTime - startTimeStamp);
            if (pullResult.getPullStatus().equals(PullStatus.FOUND)) {
                final List<MessageExt> messages = pullResult.getMsgFoundList();
                receiveMessages(messages);
                messageQueuesOffsetMap.put(entry.getKey(), pullResult.getNextBeginOffset());
                offsetManagementService.putPosition(convertToByteBufferKey(entry.getKey()), convertToByteBufferValue(pullResult.getNextBeginOffset()));
                preCommit();
            }
        }
    }

    private void preCommit() {
        long commitInterval = taskConfig.getLong(OFFSET_COMMIT_TIMEOUT_MS_CONFIG, 1000);
        if (nextCommitTime <= 0) {
            long now = System.currentTimeMillis();
            nextCommitTime = now + commitInterval;
        }
        if (nextCommitTime < System.currentTimeMillis()) {
            Map<QueueMetaData, Long> queueMetaDataLongMap = new HashMap<>(512);
            if (messageQueuesOffsetMap.size() > 0) {
                for (Map.Entry<MessageQueue, Long> messageQueueLongEntry : messageQueuesOffsetMap.entrySet()) {
                    QueueMetaData queueMetaData = new QueueMetaData();
                    queueMetaData.setQueueName(messageQueueLongEntry.getKey().getTopic());
                    queueMetaData.setShardingKey(messageQueueLongEntry.getKey().getBrokerName() + COMMA + messageQueueLongEntry.getKey().getQueueId());
                    queueMetaDataLongMap.put(queueMetaData, messageQueueLongEntry.getValue());
                }
            }
            sinkTask.preCommit(queueMetaDataLongMap);
            nextCommitTime = 0;
        }
    }

    private void removePauseQueueMessage(MessageQueue messageQueue, List<MessageExt> messages) {
        if (null != messageQueuesStateMap.get(messageQueue)) {
            final Iterator<MessageExt> iterator = messages.iterator();
            while (iterator.hasNext()) {
                final MessageExt message = iterator.next();
                String msgId = message.getMsgId();
                log.info("BrokerName {}, topicName {}, queueId {} is pause, Discard the message {}", messageQueue.getBrokerName(), messageQueue.getTopic(), message.getQueueId(), msgId);
                iterator.remove();
            }
        }
    }

    @Override
    public void stop() {
        state.compareAndSet(WorkerTaskState.RUNNING, WorkerTaskState.STOPPING);
    }

    @Override
    public void cleanup() {
        if (state.compareAndSet(WorkerTaskState.STOPPED, WorkerTaskState.TERMINATED) ||
            state.compareAndSet(WorkerTaskState.ERROR, WorkerTaskState.TERMINATED))
            consumer.shutdown();
        else {
            log.error("[BUG] cleaning a task but it's not in STOPPED or ERROR state");
        }
    }

    /**
     * receive message from MQ.
     *
     * @param messages
     */
    private void receiveMessages(List<MessageExt> messages) {
        List<SinkDataEntry> sinkDataEntries = new ArrayList<>(32);
        for (MessageExt message : messages) {
            SinkDataEntry sinkDataEntry = convertToSinkDataEntry(message);
            sinkDataEntries.add(sinkDataEntry);
            String msgId = message.getMsgId();
            log.info("Received one message success : msgId {}", msgId);
        }
        sinkTask.put(sinkDataEntries);
    }

    private SinkDataEntry convertToSinkDataEntry(MessageExt message) {
        Map<String, String> properties = message.getProperties();
        String queueName;
        EntryType entryType;
        Schema schema;
        Long timestamp;
        Object[] datas = new Object[1];
        if (null == recordConverter || recordConverter instanceof RocketMQConverter) {
            queueName = properties.get(RuntimeConfigDefine.CONNECT_TOPICNAME);
            String connectEntryType = properties.get(RuntimeConfigDefine.CONNECT_ENTRYTYPE);
            entryType = StringUtils.isNotEmpty(connectEntryType) ? EntryType.valueOf(connectEntryType) : null;
            String connectTimestamp = properties.get(RuntimeConfigDefine.CONNECT_TIMESTAMP);
            timestamp = StringUtils.isNotEmpty(connectTimestamp) ? Long.valueOf(connectTimestamp) : null;
            String connectSchema = properties.get(RuntimeConfigDefine.CONNECT_SCHEMA);
            schema = StringUtils.isNotEmpty(connectSchema) ? JSON.parseObject(connectSchema, Schema.class) : null;
            datas = new Object[1];
            datas[0] = new String(message.getBody());
        } else {
            final byte[] messageBody = message.getBody();
            final SourceDataEntry sourceDataEntry = JSON.parseObject(new String(messageBody), SourceDataEntry.class);
            final Object[] payload = sourceDataEntry.getPayload();
            final byte[] decodeBytes = Base64.getDecoder().decode((String) payload[0]);
            Object recodeObject;
            if (recordConverter instanceof JsonConverter) {
                JsonConverter jsonConverter = (JsonConverter) recordConverter;
                jsonConverter.setClazz(Object[].class);
                recodeObject = recordConverter.byteToObject(decodeBytes);
                datas = (Object[]) recodeObject;
            }
            schema = sourceDataEntry.getSchema();
            entryType = sourceDataEntry.getEntryType();
            queueName = sourceDataEntry.getQueueName();
            timestamp = sourceDataEntry.getTimestamp();
        }
        DataEntryBuilder dataEntryBuilder = new DataEntryBuilder(schema);
        dataEntryBuilder.entryType(entryType);
        dataEntryBuilder.queue(queueName);
        dataEntryBuilder.timestamp(timestamp);
        SinkDataEntry sinkDataEntry = dataEntryBuilder.buildSinkDataEntry(message.getQueueOffset());
        List<Field> fields = schema.getFields();
        if (null != fields && !fields.isEmpty()) {
            for (Field field : fields) {
                dataEntryBuilder.putFiled(field.getName(), datas[field.getIndex()]);
            }
        }
        return sinkDataEntry;
    }

    @Override
    public String getConnectorName() {
        return connectorName;
    }

    @Override
    public WorkerTaskState getState() {
        return state.get();
    }

    @Override
    public ConnectKeyValue getTaskConfig() {
        return taskConfig;
    }

    /**
     * Further we cant try to log what caused the error
     */
    @Override
    public void timeout() {
        this.state.set(WorkerTaskState.ERROR);
    }
    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();
        sb.append("connectorName:" + connectorName)
            .append("\nConfigs:" + JSON.toJSONString(taskConfig))
            .append("\nState:" + state.get().toString());
        return sb.toString();
    }

    @Override
    public Object getJsonObject() {
        HashMap obj = new HashMap<String, Object>();
        obj.put("connectorName", connectorName);
        obj.put("configs", JSON.toJSONString(taskConfig));
        obj.put("state", state.get().toString());
        return obj;
    }

    private enum QueueState {
        PAUSE
    }

    private ByteBuffer convertToByteBufferKey(MessageQueue messageQueue) {
        return ByteBuffer.wrap((messageQueue.getTopic() + COMMA + messageQueue.getBrokerName() + COMMA + messageQueue.getQueueId()).getBytes());
    }

    private MessageQueue convertToMessageQueue(ByteBuffer byteBuffer) {
        byte[] array = byteBuffer.array();
        String s = String.valueOf(array);
        String[] split = s.split(COMMA);
        return new MessageQueue(split[0], split[1], Integer.valueOf(split[2]));
    }

    private ByteBuffer convertToByteBufferValue(Long offset) {
        return ByteBuffer.wrap(String.valueOf(offset).getBytes());
    }

    private Long convertToOffset(ByteBuffer byteBuffer) {
        return Long.valueOf(new String(byteBuffer.array()));
    }
}


text:
package org.apache.causeway.extensions.fullcalendar.wkt.fullcalendar.res;

import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.apache.wicket.util.string.Strings;

import org.apache.causeway.extensions.fullcalendar.wkt.fullcalendar.CalendarConfig;

import lombok.Getter;
import lombok.experimental.Accessors;

public class FullCalendarIntegrationJsReference
extends JavaScriptResourceReference {

    private static final long serialVersionUID = 1L;

    @Getter(lazy = true) @Accessors(fluent = true)
    private static final FullCalendarIntegrationJsReference instance =
        new FullCalendarIntegrationJsReference();

    private FullCalendarIntegrationJsReference() {
        super(FullCalendarIntegrationJsReference.class, "fullcalendar-integration.js");
    }

    /**
     * @return this resource reference singleton instance as header item
     */
    public static HeaderItem asHeaderItem() {
        return JavaScriptHeaderItem.forReference(instance());
    }

    public static OnDomReadyHeaderItem domReadyScript(
            final String markupId,
            final CalendarConfig calendarConfig) {
        return OnDomReadyHeaderItem.forScript(
                calendarResponseScript(
                markupId,
                calendarConfig.toJson()));
    }

    public static String calendarResponseScript(
            final String markupId,
            final String... args) {
        return String.format("$('#%s').fullCalendarExt(%s);",
                markupId,
                Strings.join(",", args));
    }

}

redpajama_set_name: RedPajamaGithub


text:
module Azure::EventGrid::V2018_01_01
  module Models
    #
    # Ingest fragment dropped event data.
    #
    class MediaLiveEventIncomingDataChunkDroppedEventData

      include MsRestAzure

      # @return [String] Gets the timestamp of the data chunk dropped.
      attr_accessor :timestamp

      # @return [String] Gets the type of the track (Audio / Video).
      attr_accessor :track_type

      # @return [Integer] Gets the bitrate of the track.
      attr_accessor :bitrate

      # @return [String] Gets the timescale of the Timestamp.
      attr_accessor :timescale

      # @return [String] Gets the result code for fragment drop operation.
      attr_accessor :result_code

      # @return [String] Gets the name of the track for which fragment is
      # dropped.
      attr_accessor :track_name

      #
      # Mapper for MediaLiveEventIncomingDataChunkDroppedEventData class as
      # Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'MediaLiveEventIncomingDataChunkDroppedEventData',
          type: {
            name: 'Composite',
            class_name: 'MediaLiveEventIncomingDataChunkDroppedEventData',
            model_properties: {
              timestamp: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'timestamp',
                type: {
                  name: 'String'
                }
              },
              track_type: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'trackType',
                type: {
                  name: 'String'
                }
              },
              bitrate: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'bitrate',
                type: {
                  name: 'Number'
                }
              },
              timescale: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'timescale',
                type: {
                  name: 'String'
                }
              },
              result_code: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'resultCode',
                type: {
                  name: 'String'
                }
              },
              track_name: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'trackName',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?php
/**
 * Created by PhpStorm.
 * User: kenny
 * Date: 12/19/16
 * Time: 10:23 AM
 */

namespace PayU\Test\Api;

use PayU\Api\Phone;

class PhoneTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Gets Object Instance with Json data filled in
     * @return Phone
     */
    public static function getObject()
    {
        return new Phone(self::getJson());
    }

    /**
     * Gets Json String of Object Address
     * @return string
     */
    public static function getJson()
    {
        return '{"countryCode":"TestSample","nationalNumber":"TestSample","extension":"TestSample"}';
    }

    /**
     * Tests for Serialization and Deserialization Issues
     * @return Phone
     */
    public function testSerializationDeserialization()
    {
        $obj = new Phone(self::getJson());
        $this->assertNotNull($obj);
        $this->assertNotNull($obj->getCountryCode());
        $this->assertNotNull($obj->getNationalNumber());
        $this->assertNotNull($obj->getExtension());
        $this->assertEquals(self::getJson(), $obj->toJson());
        return $obj;
    }

    /**
     * @depends testSerializationDeserialization
     * @param Phone $obj
     */
    public function testGetters($obj)
    {
        $this->assertEquals($obj->getCountryCode(), "TestSample");
        $this->assertEquals($obj->getNationalNumber(), "TestSample");
        $this->assertEquals($obj->getExtension(), "TestSample");
    }
}


text:
package org.dasein.attributes.types;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

import org.dasein.attributes.DataType;
import org.dasein.attributes.DataTypeFactory;
import org.dasein.attributes.InvalidAttributeException;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.Translator;

/**
 *
Extends the Date concept to the time as well.

 *
 *
Accepts times formatted as yyyy-MM-dd'T'HH:mm:ss like 2011-02-24T21:30:22

 */
public class TimeFactory extends DataTypeFactory<Date> {
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 3257571607120356115L;

    static public final String TYPE_NAME = "time";

    public Translator<String> getDisplayName() {
        return new Translator<String>(Locale.US, TYPE_NAME);
    }

    public String getStringValue(Object ob) {
        if( ob instanceof Date ) {
            return String.valueOf(((Date)ob).getTime());
        }
        return super.getStringValue(ob);
    }

    public String getTypeName() {
        return TYPE_NAME;
    }

    public DataType<Date> getType(boolean ml, boolean mv, boolean req, String... typeArgs) {
        return getType(null, null, ml, mv, req, typeArgs);
    }

    public DataType<Date> getType(String grp, Number idx, boolean ml, boolean mv, boolean req, String... typeArgs) {
        String sfmt = null;
        String efmt = null;
        Date start, end;

        if( typeArgs == null || typeArgs.length < 1 ) {
            start = null;
            end = null;
        }
        else if( typeArgs.length == 1 && (typeArgs[0] == null || typeArgs[0].length() < 1) ) {
            start = null;
            end = null;
        }
        else {
            try {
                sfmt = typeArgs[0];
                if( sfmt == null || sfmt.equals(":") || sfmt.equals("") || sfmt.equals("null") ) {
                    sfmt = null;
                    start = null;
                }
                else {
                    start = new Date(Long.valueOf(sfmt));
                }
            }
            catch( NumberFormatException e ) {
                throw new InvalidAttributeException(e.getMessage());
            }
            if( typeArgs.length > 1 ) {
                try {
                    efmt = typeArgs[1];
                    if( efmt == null || efmt.equals("") || efmt.equals("null") ) {
                        efmt = null;
                        end = null;
                    }
                    else {
                        end = new Date(Long.valueOf(efmt));
                    }
                }
                catch( NumberFormatException e) {
                    throw new InvalidAttributeException(e.getMessage());
                }
            }
            else {
                end = null;
            }
        }
        return new DateAttribute(grp, idx, ml, mv, req, start, end, sfmt, efmt);
    }

    static public class DateAttribute extends DataType<Date> {
        /**
         * serialVersionUID
         */
        private static final long serialVersionUID = 3257570607120856115L;

        private ArrayList<Date> choices   = null;
        private Date            endDate   = null;
        private Date            startDate = null;

        private DateAttribute(String grp, Number idx, boolean ml, boolean mv, boolean req, Date start, Date end, String sfmt, String efmt) {
            super(TYPE_NAME, grp, idx, ml, mv, req, sfmt, efmt);
            if( start != null && end != null ) {
                if( start.getTime() > end.getTime() ) {
                    throw new InvalidAttributeException("Invalid date range: " + start + " - " + end);
                }
            }
            startDate = start;
            endDate = end;
            if( startDate != null && endDate != null ) {
                CalendarWrapper s = new CalendarWrapper();
                CalendarWrapper e = new CalendarWrapper();

                s.setDate(start);
                e.setDate(end);
                choices = new ArrayList<Date>();
                while( s.getYear() != e.getYear() && s.getMonth() != e.getMonth() && s.getDayOfMonth() != e.getDayOfMonth() ) {
                    choices.add(s.getDate());
                    s.getCalendar().add(Calendar.DAY_OF_MONTH, 1);
                }
            }
        }

        public Collection<Date> getChoices() {
            return choices;
        }

        @SuppressWarnings("unchecked")
        public DataTypeFactory<Date> getFactory() {
            return (DataTypeFactory<Date>)DataTypeFactory.getInstance(TYPE_NAME);
        }

        public InputType getInputType() {
            return InputType.TIME;
        }

        public Date getValue(Object val) {
            if( val instanceof Date ) {
                return (Date)val;
            }
            else if( val instanceof Long ) {
                return new Date(((Long)val).longValue());
            }
            else if( val instanceof String ) {
                String str = (String)val;
                SimpleDateFormat fmt;

                str = (String)val;
                if( str.equals("") ) {
                    return null;
                }
                fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                fmt.setLenient(true);
                try {
                    return fmt.parse((String)val);
                }
                catch( ParseException e ) {
                    try {
                        long time = Long.parseLong((String)val);

                        return new Date(time);
                    }
                    catch( NumberFormatException e2 ) {
                        if( ((String)val).indexOf("NONE") == -1 ) {
                            throw new InvalidAttributeException(e.getMessage());
                        }
                        return null;
                    }
                }
            }
            else {
                throw new InvalidAttributeException("Unknown time: "+ val);
            }
        }

        public boolean isValidChoice(Date d) {
            if( d == null ) {
                return !isRequired();
            }
            if( startDate == null && endDate == null ) {
                return true;
            }
            if( startDate != null && d.getTime() < startDate.getTime() ) {
                return false;
            }
            if( endDate != null && d.getTime() > endDate.getTime() ) {
                return false;
            }
            return true;
        }

        public String toString() {
            return "Time";
        }
    }
}


text:
import logging
logger = logging.getLogger("tdldk")

def set_log_level(level, handler=None):
    """ Set both tdldk and Bambou log level to the given level

        Args:
            level (logging.level): a logging level
            handler (logging.Handler): a logging handler

        Notes:
            if no handler is provided, it will automatically create a new StreamHandler.

        Examples:
            >>> set_log_level(logging.INFO)
            >>> set_log_level(logging.DEBUG, logging.Streamhandler())
            >>> set_log_level(logging.ERROR)

    """

    from bambou import bambou_logger, pushcenter_logger

    if handler is None:
        handler = logging.StreamHandler()

    bambou_logger.setLevel(level)
    bambou_logger.addHandler(handler)

    pushcenter_logger.setLevel(level)
    pushcenter_logger.addHandler(handler)

    logger.setLevel(level)
    logger.addHandler(handler)


text:
'use strict'

const is = require('./_private/is')
const property = require('./_private/property')
const ConditionViolation = require('./ConditionViolation')
const AbstractContract = require('./AbstractContract')
const assert = require('assert')

/**
 * A PreconditionViolation is the means by which Toryt Contracts tells developers that it detected that a
 * precondition was violated when a contract function was called. The implementation of the contract function
 * that was called, was not executed.
 *
 * If the precondition itself is correct, this is a programming error on the part of the calling function.
 * One should assume the system is now in an undefined state.
 *
 * The developer wants to know
 *

 *
where the contract function was called in source code,

 *
what the arguments were of the instance of the call, and

 *
which precondition was violated in source code (which implies knowing which contract it is a part of).

 *

 *
 * @constructor
 * @param {Function} contractFunction - The contract function that reports this violation
 * @param {Function} condition        - The condition that was violated
 * @param            self             - The this that contractFunction was called on
 * @param {Array} args
 *                The arguments with which the contract function that failed, was called
 */
function PreconditionViolation (contractFunction, condition, self, args) {
  assert(AbstractContract.isAGeneralContractFunction(contractFunction), 'this is a general contract function')
  assert.strictEqual(typeof condition, 'function')
  assert(is.functionArguments(args) || Array.isArray(args), 'args is arguments or array')

  ConditionViolation.apply(this, arguments)
}

// noinspection JSUnresolvedVariable
PreconditionViolation.prototype = new ConditionViolation(
  AbstractContract.root.abstract,
  function () {
    return 'This is a dummy condition in the PreconditionViolation prototype.'
  },
  undefined,
  []
)
PreconditionViolation.prototype.constructor = PreconditionViolation
property.setAndFreeze(PreconditionViolation.prototype, 'name', PreconditionViolation.name)

module.exports = PreconditionViolation


text:
'use strict';

var expect = require('chai').expect;
var Trie = require('../trie');

describe('Trie#add', function(){
  it("should add a word to the Trie", function(){
    var T = new Trie();
    T.add('str');
    T.add('word');
    expect(T.count()).to.equal(2);
  });
});

describe('Trie#find', function(){
  it("should find a word if it exists", function(){
    var T = new Trie();
    var words = ["bell", "bid", "bull", "buy", "sell", "stock", "stop"];
    words.forEach(function(w){
      T.add(w);
    });
    expect(T.find('bella')).to.be.null;
    expect(T.find('bell')).not.to.be.null;
    expect(T.find('stock')).not.to.be.null;
    expect(T.find('stack')).to.be.null;
  });
});

describe('Trie#suggestions', function(){
  it("should get all the words with the passed prefix", function(){
    var T = new Trie();
    var words = ["bell", "bello", "bella", "bx", "ab", "bem", "bc"];
    words.forEach(function(w){
      T.add(w);
    });
    expect(T.suggestions('be').length).to.equal(4);
  });
});


text:
import {ClaritySeedAppHome} from './app.po';

fdescribe('clarity-seed app', function () {

  let expectedMsg: string = 'This is a Clarity seed application. This is the default page that loads for the application.';

  let page: ClaritySeedAppHome;

  beforeEach(() => {
    page = new ClaritySeedAppHome();
  });

  it('should display: ' + expectedMsg, () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual(expectedMsg)
  });
});


text: export { DigitalTrust as default } from "../../";


text:
A00866713

This is an academic project.


text:
// ReSharper disable InconsistentNaming

using System;
using SimplyTestData;
using Xunit;

namespace GettingStarted
{
    public class Greeting
    {
        public string Message { get; set; }
    }

    public class BasicFixture
    {
        private void HelloWorld(Greeting greeting)
        {
            greeting.Message = "Hello, World!";
        }

        [Fact]
        public void Example_01_HelloWorld()
        {
            var greeting = TestData.Create<Greeting>(HelloWorld);

            Assert.Equal("Hello, World!", greeting.Message);
        }

        [Fact]
        public void Example_02_GreetYourFriends()
        {
            var greeting = TestData.Create(Greeting("Hi"), To("Alice"), And("Bob"));

            Assert.Equal("Hi, Alice and Bob!", greeting.Message);
        }

        private Action<Greeting> Greeting(string something)
        {
            return greeting => greeting.Message = something;
        }

        private Action<Greeting> To(string friend)
        {
            return greeting => greeting.Message += ", " + friend;
        }

        private Action<Greeting> And(string friend)
        {
            return greeting => greeting.Message += " and " + friend + "!";
        }
    }
}

// ReSharper restore InconsistentNaming


text:
m4th [![.](https://badge.fury.io/js/m4th.png)](http://badge.fury.io/js/m4th) [![.](https://travis-ci.org/hhelwich/m4th.png?branch=master)](https://travis-ci.org/hhelwich/m4th) [![.](https://coveralls.io/repos/hhelwich/m4th/badge.png)](https://coveralls.io/r/hhelwich/m4th)
====

A library to use in the browser or node.js. It currently contains:

* Basic Matrix operations
* LU decomposition
* UD decomposition (optimized cholesky decomposition)

Browser
-------

To use the library in the browser, you need to include [this](https://raw.github.com/hhelwich/m4th/master/dist/m4th.min.js) JavaScript file:

```html
<script src="m4th.min.js"></script>
```

It exports the global `m4th` object. Now you can access e.g. the matrix constructor with:

```javascript
var M = m4th.matrix;
```

The following browsers are tested:

[![Browser Test Status](https://saucelabs.com/browser-matrix/hhelwich-m4th.svg)](https://saucelabs.com/u/hhelwich-m4th)

node.js
-------

You can install this package with:

```
npm install m4th
```

Now you can load e.g. the matrix constructor with:

```javascript
var M = require('m4th/matrix');
```

Examples
========

Matrix Creation
---------------

Create a 2x3 matrix (2 rows, 3 columns) and a 4x4 matrix with ```undefined``` entries:

```javascript
var A, B;
A = M(2, 3);
B = M(4);
```
Create a 2x2 matrix and a 2x3 matrix with the given content:

```javascript
var A, B;
A = M([
    3,  2,
    1,  0
]);
B = M(2, [
    1,  2,  3,
    4,  5,  7
]);
```

Matrix Entries
--------------

Each matrix has readable ```rows``` and ```columns``` properties:

```javascript
console.log('Matrix A has ' + A.rows + ' rows and ' + A.columns + ' columns.');
```

Matrix entries can be accessed with ```get()``` and ```set()``` (indices start at ```0```):

```javascript
var a = A.get(0, 3); // get entry in row 0 and column 3
A.set(1, 2, 3); // set entry in row 1 and column 2 to value 3
```

You can chain ```set()```:

```javascript
A.set(1, 0, 3).set(1, 1, 4).set(1, 2, 5);
```

Imperative / Functional
-----------------------

Calculations on matrices can be done in imperative or functional style.
For example the [frobenius norm](http://en.wikipedia.org/wiki/Matrix_norm#Frobenius_norm) of a matrix ```A```
can be calculated imperatively:

```javascript
var i, j, a, norm;
norm = 0;
for (i = 0; i < A.rows; i += 1) { // iterate matrix rows
  for (j = 0; j < A.columns; j += 1) { // iterate matrix columns
    a = A.get(i, j);
    norm += a * a;
  }
}
norm = Math.sqrt(norm);
```

But we can do better using ```each()``` which takes a callback as an argument:

```javascript
var norm = 0;
A.each(function (a) { // iterate matrix entries
  norm += a * a;
});
norm = Math.sqrt(norm);
```

In a more functional style the same can be expressed with ```map()``` and ```reduce()```:

```javascript
var square, add, norm;
// helper functions
square = function (x) {
  return x * x;
};
add = function (x, y) {
  return x + y;
};
// calculate norm
norm = Math.sqrt(A.map(square).reduce(add));
```

This now reads nicer than the imperative approach.

If performance is important, you can remove the ```map()``` call (which creates a temporary matrix) and use a single
```reduce()``` instead:

```javascript
var addSquared, norm;
// helper function
addSquared = function (x, y) {
  return x + y * y;
};
// calculate norm
norm = Math.sqrt(A.reduce(addSquared, 0));
```

Matrix Operations
-----------------

```javascript
// calculate some results without changing the matrices A, B and C:
console.log('A*B = ' + A.mult(B));
console.log('B+C = ' + B.add(C));
console.log('C-B = ' + C.minus(B));
console.log('B*3 = ' + B.times(3));
console.log('B^t = ' + B.transp());
console.log('fill B with constant value = ' + B.fill(2));
console.log('copy of A = ' + A.clone());
console.log('A is square? = ' + A.isSquare());
console.log('A has same size as B? = ' + A.isSize(B));
```

map()
-----

Create a 5x5 hilbert matrix:

```javascript
var H = M(5).map(function (h, i, j) {
    return 1 / (i + j + 1);
});
```

LU decomposition
----------------

```javascript
var A, y, LU, x, Ainv;
// create some matrices:
A = M([
    2,  1, -1,
   -3, -1,  2,
   -2,  1,  2
]);

y = M(3, [
    8,
  -11,
   -3
]);

// LU decompose matrix A
LU = m4th.lu(A); // node.js: require('m4th/lu')(A);
// calculate solution for: y = A*x
x = LU.solve(y);
// invert matrix A
Ainv = LU.getInverse();
```

UD decomposition
----------------

```javascript
var A, y, UD, x;
// create some matrices:
A = M([
    2, 1, 1, 3, 2,
    1, 2, 2, 1, 1,
    1, 2, 9, 1, 5,
    3, 1, 1, 7, 1,
    2, 1, 5, 1, 8
]);

y = M(5, [ -2, 4, 3, -5, 1 ]);

// UD decompose matrix A
UD = m4th.ud(A); // node.js: require('m4th/ud')(A);
// calculate solution for: y = A*x
x = UD.solve(y);
```


text:
#ifndef ROCKETCOREXMLPARSETOOLS_H
#define ROCKETCOREXMLPARSETOOLS_H

#include <Rocket/Core/XMLParser.h>

namespace Rocket {
namespace Core {

class Element;

/**
	Tools for aiding in parsing XML documents.

	@author Lloyd Weehuizen
 */

class XMLParseTools
{
public:
	/// Searchs a string for the specified tag
	/// @param tag Tag to find, *must* be in lower case
	/// @param string String to search
	/// @param closing_tag Is it the closing tag we're looking for?
	static const char* FindTag(const char* tag, const char* string, bool closing_tag = false);
	/// Reads the next attribute from the string, advancing the pointer
	/// @param[in,out] string String to read the attribute from, pointer will be advanced passed the read
	/// @param[out] name Name of the attribute read
	/// @param[out] value Value of the attribute read
	static bool ReadAttribute(const char* &string, String& name, String& value);

	/// Applies the named template to the specified element
	/// @param element Element to apply the template to
	/// @param template_name Name of the template to apply, in TEMPLATE:ELEMENT_ID form
	/// @returns Element to continue the parse from
	static Element* ParseTemplate(Element* element, const String& template_name);
};

}
}

#endif


text:
package org.testcontainers.jdbc;

import com.google.common.base.Throwables;
import org.junit.Test;
import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testcontainers.utility.DockerImageName;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicInteger;

import static org.rnorth.visibleassertions.VisibleAssertions.assertEquals;
import static org.rnorth.visibleassertions.VisibleAssertions.assertTrue;
import static org.rnorth.visibleassertions.VisibleAssertions.fail;

public class MissingJdbcDriverTest {

    @Test
    public void shouldFailFastIfNoDriverFound() {
        final MissingDriverContainer container = new MissingDriverContainer();

        try {
            container.start();
            fail("The container is expected to fail to start");
        } catch (Exception e) {
            final Throwable rootCause = Throwables.getRootCause(e);
            assertTrue("ClassNotFoundException is the root cause", rootCause instanceof ClassNotFoundException);
        } finally {
            container.stop();
        }

        assertEquals("only one connection attempt should have been made", 1, container.getConnectionAttempts());
    }

    /**
     * Container class for the purposes of testing, with a known non-existent driver
     */
    static class MissingDriverContainer extends JdbcDatabaseContainer {

        private final AtomicInteger connectionAttempts = new AtomicInteger();

        MissingDriverContainer() {
            super(DockerImageName.parse("mysql:5.7.34"));
            withEnv("MYSQL_ROOT_PASSWORD", "test");
            withExposedPorts(3306);
        }

        @Override
        public String getDriverClassName() {
            return "nonexistent.ClassName";
        }

        @Override
        public String getJdbcUrl() {
            return "";
        }

        @Override
        public String getUsername() {
            return "root";
        }

        @Override
        public String getPassword() {
            return "test";
        }

        @Override
        protected String getTestQueryString() {
            return "";
        }

        @Override
        public Connection createConnection(String queryString) throws SQLException, NoDriverFoundException {
            connectionAttempts.incrementAndGet(); //
            return super.createConnection(queryString);
        }

        /**
         * test window
         * @return how many times a connection was attempted
         */
        int getConnectionAttempts() {
            return connectionAttempts.get();
        }
    }
}


text:
<?php
/** @package    verysimple::Phreeze */

/** import supporting libraries */
require_once("ICache.php");

/**
 * CacheRam is an implementation of a Cache that doesn't actually cache at all
 *
 * @package    verysimple::Phreeze
 * @author     VerySimple Inc.
 * @copyright  1997-2008 VerySimple, Inc.
 * @license    http://www.gnu.org/licenses/lgpl.html  LGPL
 * @version    2.0
 */
class CacheNoCache implements ICache
{
	private $ram = array();

	public function Get($key,$flags=null)
	{
		return null;
	}

	public function Set($key,$val,$flags=null,$timeout=0)
	{
	}

	public function Delete($key)
	{
	}

}

?>


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="io.github.bleoo.androidutils.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn_gravity_animation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:elevation="4dp"
            android:text="Gravity Animation"
            android:textAllCaps="false"
            android:textSize="16sp" />

        <Button
            android:id="@+id/btn_flow_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:elevation="4dp"
            android:text="FlowLayout"
            android:textAllCaps="false"
            android:textSize="16sp" />

        <Button
            android:id="@+id/btn_hold_flow_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:elevation="4dp"
            android:text="HoldFlowLayout"
            android:textAllCaps="false"
            android:textSize="16sp" />

    </LinearLayout>

</ScrollView>


text:
/* global malarkey:false, toastr:false, moment:false */
import config from './index.config';

import routerConfig from './index.route';

import runBlock from './index.run';
import MainController from './main/main.controller';
import NavbarDirective from '../app/components/navbar/navbar.directive';

import Tracks from '../app/components/tracks/tracks.module.js'

angular
  .module('godtracks', [
    'ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngAria', 'restangular', 'ui.router',
    'ngMaterial', 'ngStorage',
    Tracks
  ])
  .constant('toastr', toastr)
  .constant('moment', moment)
  .config(config)

  .config(routerConfig)

  .run(runBlock)
  .controller('MainController', MainController)
  .directive('gtNavbar', () => new NavbarDirective());