text:
package kafkasource

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/cloudevents/sdk-go/v2/event"
	. "github.com/cloudevents/sdk-go/v2/test"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	duckv1 "knative.dev/pkg/apis/duck/v1"
	"knative.dev/reconciler-test/pkg/environment"
	"knative.dev/reconciler-test/pkg/eventshub"
	"knative.dev/reconciler-test/pkg/eventshub/assert"
	"knative.dev/reconciler-test/pkg/feature"
	"knative.dev/reconciler-test/pkg/manifest"
	"knative.dev/reconciler-test/pkg/state"

	kafkaclient "knative.dev/eventing-kafka/pkg/client/injection/client"
	"knative.dev/eventing-kafka/test/rekt/resources/kafkacat"
	"knative.dev/eventing-kafka/test/rekt/resources/kafkasource"
	"knative.dev/eventing-kafka/test/rekt/resources/kafkatopic"
)

var test_mt_source = os.Getenv("TEST_MT_SOURCE")

func MtDataPlaneDelivery() *feature.Feature {
	name := "mt-tenant-test-plain"
	f := feature.NewFeatureNamed("Delivery/" + name)
	delivery := delivery{
		message: kafkaMessage{
			Key:     "0",
			Payload: `{"value":711}`,
		},
		matchers: AllOf(
			HasData([]byte(`{"value":711}`)),
			HasExtension("key", "0"),
		),
	}

	delivery.bootstrapServer = auths["plain"].bootstrapServer
	delivery.auth = auths["plain"]

	f.Setup("set kafka message", func(ctx context.Context, t feature.T) {
		state.SetOrFail(ctx, t, "message", delivery.message)
	})
	f.Setup("set bootstrap server", func(ctx context.Context, t feature.T) {
		state.SetOrFail(ctx, t, "bootstrapServer", delivery.bootstrapServer)
	})

	topicName := feature.MakeRandomK8sName("topic") // A k8s name is also a valid topic name.

	f.Setup("set kafka topic name", func(ctx context.Context, t feature.T) {
		state.SetOrFail(ctx, t, "topicName", topicName)
	})

	f.Setup("install kafka topic", kafkatopic.Install(topicName))

	sinkName := feature.MakeRandomK8sName("sink")
	f.Setup("set sink name", func(ctx context.Context, t feature.T) {
		state.SetOrFail(ctx, t, "sinkName", sinkName)
	})

	f.Setup("install sink", eventshub.Install(sinkName, eventshub.StartReceiver))

	ksopts := []manifest.CfgFn{
		kafkasource.WithBootstrapServers([]string{delivery.bootstrapServer}),
		kafkasource.WithTopics([]string{topicName}),
		kafkasource.WithSink(&duckv1.KReference{
			Kind:       "Service",
			Name:       sinkName,
			APIVersion: "v1",
		}, ""),
	}

	f.Setup("install a kafka source", kafkasource.Install(name, ksopts...))
	f.Requirement("kafka topic must be ready", kafkatopic.IsReady(topicName))
	f.Requirement("kafka source must be ready", kafkasource.IsReady(name))
	f.Assert("different KafkaSource exists on the same pod", sourcesPlaced(name, delivery.matchers))

	return f
}

func sourcesPlaced(name string, matchers EventMatcher) func(ctx context.Context, t feature.T) {
	return func(ctx context.Context, t feature.T) {
		var message kafkaMessage
		state.GetOrFail(ctx, t, "message", &message)

		topicName := state.GetStringOrFail(ctx, t, "topicName")
		sinkName := state.GetStringOrFail(ctx, t, "sinkName")

		if test_mt_source == "1" {
			time.Sleep(10 * time.Second)
		}

		kcopts := []manifest.CfgFn{
			kafkacat.WithBootstrapServer(kafkaBootstrapUrlPlain),
			kafkacat.WithTopic(topicName),
			kafkacat.WithKey(message.Key),
			kafkacat.WithHeaders(message.Headers),
			kafkacat.WithPayload(message.Payload),
		}
		env := environment.FromContext(ctx)
		matchers = AllOf(
			func(have event.Event) error {
				sourceInterface := kafkaclient.Get(ctx).SourcesV1beta1()

				source1, err := sourceInterface.KafkaSources(env.Namespace()).Get(ctx, "mt-tenant-test-plain", metav1.GetOptions{})
				if err != nil {
					return fmt.Errorf("Error when getting Kafka source1")
				}

				source2, err := sourceInterface.KafkaSources(env.Namespace()).Get(ctx, "no-ce-event-plain", metav1.GetOptions{})
				if err != nil {
					return fmt.Errorf("Error when getting Kafka source2")
				}

				if source1.Status.Placements[0].PodName != source2.Status.Placements[0].PodName && len(source2.Status.Placements[0].PodName) != 0 {
					return fmt.Errorf("Two Kafka source do not belong to the same pod")
				}

				return nil
			})

		kafkacat.Install(topicName, kcopts...)(ctx, t)
		assert.OnStore(sinkName).MatchEvent(matchers).Exact(1)(ctx, t)
	}
}


text:
/**
* Represents an OpenTok session. Use the {@link OpenTok#createSession OpenTok.createSession()}
* method to create an OpenTok session. The sessionId property of the Session object
* is the session ID.
*
* @property {String} sessionId The session ID.
*
* @class Session
*/

var Session = function Session(ot, sessionId, properties) {
  var prop;
  this.ot = ot;
  this.sessionId = sessionId;
  for (prop in properties) {
    if ({}.hasOwnProperty.call(properties, prop)) {
      this[prop] = properties[prop];
    }
  }
};

Session.prototype.generateToken = function generateToken(opts) {
  return this.ot.generateToken(this.sessionId, opts);
};

module.exports = Session;

redpajama_set_name: RedPajamaGithub


text:
package edu.gmu.tec.scout.utilities;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import com.github.kovmarci86.android.secure.preferences.encryption.EncryptionAlgorithm;
import com.github.kovmarci86.android.secure.preferences.encryption.EncryptionException;

/**
 * This class is from the following site:
 * http://www.java2s.com/Code/Android/Security/AESEncryption.htm with some
 * modification.
 * @author http://www.java2s.com/Code/Android/Security/AESEncryption.htm
 */
public class Encryption implements EncryptionAlgorithm {

    private SecretKeySpec skeySpec;
    private Cipher cipher;

    /**
     * Initializes with raw key.
     * @param keyraw The raw key. Must NOT be null.
     * @throws UnsupportedEncodingException When no UTF-8 support found.
     * @throws NoSuchAlgorithmException When no MD5 support found.
     * @throws NoSuchPaddingException When the AES/ECB/PKCS5Padding is not supported.
     */
    public Encryption(byte[] keyraw) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException {
        if (keyraw == null) {
            throw new IllegalArgumentException("null key given");
        } else {
            skeySpec = new SecretKeySpec(keyraw, "AES");
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        }
    }

    /**
     * Initializes with a password to use for encrypt.
     * @param passphrase The string password.
     * @throws UnsupportedEncodingException When no UTF-8 support found.
     * @throws NoSuchAlgorithmException When no MD5 support found.
     * @throws NoSuchPaddingException When the AES/ECB/PKCS5Padding is not supported.
     */
    public Encryption(String passphrase) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException {
        byte[] bytesOfMessage = passphrase.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(bytesOfMessage);
        skeySpec = new SecretKeySpec(thedigest, "AES");
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    }

    /**
     * Encrypts the bytes.
     * @param plaintext The bytes to encrypt.
     * @return The encrypted value.
     * @throws EncryptionException On encryption exception.
     */
    @Override
    public synchronized byte[] encrypt(byte[] plaintext) throws EncryptionException {
        // returns byte array encrypted with key
        try {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            return cipher.doFinal(plaintext);
        } catch (InvalidKeyException e) {
            throw new EncryptionException(e);
        } catch (IllegalBlockSizeException e) {
            throw new EncryptionException(e);
        } catch (BadPaddingException e) {
            throw new EncryptionException(e);
        }
    }

    /**
     * Decrypes the cypher.
     * @param ciphertext The data to decrypt.
     * @return The decrypted value.
     * @throws EncryptionException On ecryption exception.
     */
    @Override
    public synchronized byte[] decrypt(byte[] ciphertext) throws EncryptionException {
        // returns byte array decrypted with key
        try {
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            return cipher.doFinal(ciphertext);
        } catch (InvalidKeyException e) {
            throw new EncryptionException(e);
        } catch (IllegalBlockSizeException e) {
            throw new EncryptionException(e);
        } catch (BadPaddingException e) {
            throw new EncryptionException(e);
        }
    }

}


text:
PROJECT = emqttd_auth_riak
PROJECT_DESCRIPTION = emqttd Authentication/ACL against MySQL
PROJECT_VERSION = 2.0

DEPS =  ecpool gen_conf riakc jsx

dep_ecpool   = git https://github.com/emqtt/ecpool master
dep_gen_conf = git https://github.com/emqtt/gen_conf master

BUILD_DEPS = emqttd
dep_emqttd = git https://github.com/emqtt/emqttd

ERLC_OPTS += +'{parse_transform, lager_transform}'

COVER = true

PACKAGES += jsx
pkg_jsx_name = jsx
pkg_jsx_description = An Erlang application for consuming, producing and manipulating JSON.
pkg_jsx_homepage = https://github.com/talentdeficit/jsx
pkg_jsx_fetch = git
pkg_jsx_repo = https://github.com/talentdeficit/jsx
pkg_jsx_commit = master

PACKAGES += riakc
pkg_riakc_name = riakc
pkg_riakc_description = Erlang clients for Riak.
pkg_riakc_homepage = https://github.com/basho/riak-erlang-client
pkg_riakc_fetch = git
pkg_riakc_repo = https://github.com/basho/riak-erlang-client
pkg_riakc_commit = master

PACKAGES += lager
pkg_lager_name = lager
pkg_lager_description = A logging framework for Erlang/OTP.
pkg_lager_homepage = https://github.com/basho/lager
pkg_lager_fetch = git
pkg_lager_repo = https://github.com/basho/lager
pkg_lager_commit = master

include erlang.mk

app:: rebar.config


text:
package simcity.gui.trace;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;

/**
 * This is a class designed to make it easier to send alerts and control them in
 * a specific way without everyone climbing over each other to get print
 * statements out there. It does this by requiring every message to have a tag
 * associated with it. The default are ERROR, WARNING, or INFO, but you can add
 * any you want. The nice part is that you can control which tags actually get
 * printed to the console and which simply get put on to a list.
 *
 * @author Keith DeRuiter
 * @version 2.0
 *
 * @see Alert
 * @see AlertListener
 * @see AlertLevel
 */
public class AlertLog {

	/** Holds the single AlertLog instance. */
	private static AlertLog instance = new AlertLog();

	/** List of all {@link AlertListeners} that should be notified when an alert occurs. */
	private List<AlertListener> registeredAlertListeners;

	/**
	 * The list of {@link AlertLevel} that will print to the System.out/err console when added to the Log.
	 * Defaults to every level printing.
	 */
	private Set<AlertLevel> printedAlertLevels = Collections.synchronizedSet(EnumSet.allOf(AlertLevel.class));

	/** The list of all the Alerts. */
	private List<Alert> alerts = Collections.synchronizedList(new ArrayList<Alert>());

	/**
	 * Private constructor to make AlertLog a singleton, creates a list to hold all alert listeners.
	 * Also sets the default printed types to be errors, warnings, and messages.
	 */
	private AlertLog() {
//		this.printedAlertLevels.add(AlertLevel.ERROR);
//		this.printedAlertLevels.add(AlertLevel.WARNING);
		this.registeredAlertListeners = Collections.synchronizedList(new ArrayList<AlertListener>());
	}

	/**
	 * Gets the one instance of the AlertLog singleton.
	 * @return The one singleton instance of AlertLog.
	 */
	public static AlertLog getInstance() {
		return AlertLog.instance;
	}

	/**
	 * Logs an error using {@link #sendAlert}.
	 * @param tag the {@link AlertTag} saying what group type this alert is tagged as.
	 * @param name The name of the thing sending this alert.
	 * @param message The message of this alert.
	 */
	public void logError(AlertTag tag, String name, String message) {
		this.sendAlert(AlertLevel.ERROR, tag, name, message);
	}

	/**
	 * Logs a warning using {@link #sendAlert}.
	 * @param tag the {@link AlertTag} saying what group type this alert is tagged as.
	 * @param name The name of the thing sending this alert.
	 * @param message The message of this alert.
	 */
	public void logWarning(AlertTag tag, String name, String message) {
		this.sendAlert(AlertLevel.WARNING, tag, name, message);
	}

	/**
	 * Logs info using {@link #sendAlert}.
	 * @param tag the {@link AlertTag} saying what group type this alert is tagged as.
	 * @param name The name of the thing sending this alert.
	 * @param message The message of this alert.
	 */
	public void logInfo(AlertTag tag, String name, String message) {
		this.sendAlert(AlertLevel.INFO, tag, name, message);
	}

	/**
	 * Logs a message using {@link #sendAlert}.
	 * @param tag the {@link AlertTag} saying what group type this alert is tagged as.
	 * @param name The name of the thing sending this alert.
	 * @param message The message of this alert.
	 */
	public void logMessage(AlertTag tag, String name, String message) {
		this.sendAlert(AlertLevel.MESSAGE, tag, name, message);
	}

	/**
	 * Logs a debug alert using {@link #sendAlert}.
	 * @param tag the {@link AlertTag} saying what group type this alert is tagged as.
	 * @param name The name of the thing sending this alert.
	 * @param message The message of this alert.
	 */
	public void logDebug(AlertTag tag, String name, String message) {
		this.sendAlert(AlertLevel.DEBUG, tag, name, message);
	}

	/**
	 * Send an alert to the log.
	 *
	 * @param level The {@link AlertLevel} to log this message with.
	 * @param tag the {@link AlertTag} saying what group type this alert is tagged as.
	 * @param name The name of the thing sending this alert
	 * @param message The message to be logged.
	 */
	public void sendAlert(AlertLevel level, AlertTag tag, String name, String message) {
//		StackTraceElement[] s = new RuntimeException().getStackTrace();
//		String className = s[1].getClassName();

//		String senderClassName = new Throwable().getStackTrace()[1].getClassName();

		Date date = new Date();	//Timestamp

		//Make the alert.  Also prints to std out/err.
		Alert alert = new Alert(level, tag, name, message, date);
		if (this.printedAlertLevels.contains(level)) {
			if (level == AlertLevel.ERROR) {
				System.err.println(alert);
			} else {
				System.out.println(alert);
			}
		}
		this.alerts.add(alert);

		//Notify all people who have told me they want to listen for alerts.
		for(AlertListener al:this.registeredAlertListeners) {
			al.alertOccurred(alert);
		}
	}

	/**
	 * Enable an AlertLevel to the list of types that are printed to the console when an alert is made.
	 * If it is already on the list nothing will change.

	 * NOTE: This only controls printing to the
	 * standard console at the time an alert is generated.
	 *
	 * @param type
	 */
	public void enableAlertLevel(AlertLevel type) {
		this.printedAlertLevels.add(type);
	}

	/**
	 * Disable an AlertType from the list of types that are printed to the console when an alert is made.
	 * If it is not on the list nothing will change.

	 * NOTE: This only controls printing to the
	 * standard System.out/System.err console at the time an alert is generated.
	 *
	 * @param type
	 */
	public void disableAlertLevel(AlertLevel type) {
		this.printedAlertLevels.remove(type);
	}

	/**
	 * Get a copy of the list of all the alerts the AlertLog has collected.
	 *
	 * @return The list of all {@link Alert}s.
	 */
	public List<Alert> getAlerts() {
		return new ArrayList<Alert>(this.alerts);
	}

	/**
	 * Registers someone to be notified when an alert is added.
	 * @param alertListener the listener to register.
	 */
	public void addAlertListener(AlertListener alertListener) {
		if(registeredAlertListeners.contains(alertListener)) {
			return;
		}
		registeredAlertListeners.add(alertListener);
	}
}


text:
package com.sem4ikt.uni.recipefinderchatbot.model.spoonacular;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by mathiaslykkepedersen on 08/03/2017.
 */
public class RecipeModelUnitTest {

    private RecipeModel recipeModel = null;

    @Before
    public void setUp() {
        recipeModel = new RecipeModel();
    }

    @Test
    public void setId() {
        recipeModel.setId(1);

        Assert.assertEquals((int) recipeModel.getId(), 1);
    }

    @Test
    public void setTitle() {
        recipeModel.setTitle("test");

        Assert.assertEquals(recipeModel.getTitle(), "test");
    }

    @Test
    public void setImage() {
        recipeModel.setImage("test");

        Assert.assertEquals(recipeModel.getImage(), "test");
    }

    @Test
    public void setReadyInMintes() {
        recipeModel.setReadyInMinutes(30);

        Assert.assertEquals( (int) recipeModel.getReadyInMinutes(), 30);
    }

    @Test
    public void setImageType() {
        recipeModel.setImageType("test");

        Assert.assertEquals( recipeModel.getImageType(), "test");
    }

    @Test
    public void setSourceName(){
        recipeModel.setSourceName("test");

        Assert.assertEquals( recipeModel.getSourceName(), "test");
    }

    @Test
    public void setCreditText(){
        recipeModel.setCreditText("test");

        Assert.assertEquals( recipeModel.getCreditText(), "test");
    }

    @Test
    public void setSpoonacularSourceUrl(){
        recipeModel.setSpoonacularSourceUrl("test");

        Assert.assertEquals( recipeModel.getSpoonacularSourceUrl(), "test");
    }

    @Test
    public void setGaps(){
        recipeModel.setGaps("test");

        Assert.assertEquals( recipeModel.getGaps(), "test");
    }

    @Test
    public void setSourceUrl(){
        recipeModel.setSourceUrl("test");

        Assert.assertEquals( recipeModel.getSourceUrl(), "test");
    }

    @Test
    public void setAggregateLikes(){
        recipeModel.setAggregateLikes(12);

        Assert.assertEquals( (int) recipeModel.getAggregateLikes(), 12);
    }

    @Test
    public void setServings(){
        recipeModel.setServings(12);

        Assert.assertEquals( (int) recipeModel.getServings(), 12);
    }

    @Test
    public void setWeightWatcherSmartPoints(){
        recipeModel.setWeightWatcherSmartPoints(12);

        Assert.assertEquals( (int) recipeModel.getWeightWatcherSmartPoints(), 12);
    }

    @Test
    public void setInstructions(){
        recipeModel.setInstructions("test");

        Assert.assertEquals( recipeModel.getInstructions(), "test");
    }

    @Test
    public void setExtendedIngredients(){

        ExtendedIngredientModel ingredient = new ExtendedIngredientModel();
        ingredient.setImage("test");

        List<ExtendedIngredientModel> list = new ArrayList<>();

        list.add(ingredient);

        recipeModel.setExtendedIngredients(list);

        Assert.assertEquals( recipeModel.getExtendedIngredients(), list);
    }

    /**-------- Properties test - Booleans---------**/

    @Test
    public void setCheap() {
        recipeModel.setCheap(true);

        Assert.assertEquals( recipeModel.getCheap(), true);
    }

    @Test
    public void setVegan() {
        recipeModel.setVegan(true);

        Assert.assertEquals( recipeModel.getVegan(), true);
    }

    @Test
    public void setVegetarian() {
        recipeModel.setVegetarian(true);

        Assert.assertEquals( recipeModel.getVegetarian(), true);
    }

    @Test
    public void setDairyFree() {
        recipeModel.setDairyFree(true);

        Assert.assertEquals( recipeModel.getDairyFree(), true);
    }

    @Test
    public void setVeryHealthy() {
        recipeModel.setVeryHealthy(true);

        Assert.assertEquals( recipeModel.getVeryHealthy(), true);
    }

    @Test
    public void setVeryPopular() {
        recipeModel.setVeryPopular(true);

        Assert.assertEquals( recipeModel.getVeryPopular(), true);
    }

    @Test
    public void setSustainable() {
        recipeModel.setSustainable(true);

        Assert.assertEquals( recipeModel.getSustainable(), true);
    }

    @Test
    public void setGlutenFree() {
        recipeModel.setGlutenFree(true);

        Assert.assertEquals( recipeModel.getGlutenFree(), true);
    }

    @Test
    public void setKetogenic() {
        recipeModel.setKetogenic(true);

        Assert.assertEquals( recipeModel.getKetogenic(), true);
    }

    @Test
    public void setLowFodmap() {
        recipeModel.setLowFodmap(true);

        Assert.assertEquals( recipeModel.getLowFodmap(), true);
    }

    @Test
    public void setWhole30() {
        recipeModel.setWhole30(true);

        Assert.assertEquals( recipeModel.getWhole30(), true);
    }

    @Test
    public void setPricePerServing() {
        recipeModel.setPricePerServing(23);

        Assert.assertEquals(recipeModel.getPricePerServing(), 23, 23);
    }

    @Test
    public void setHealthScore() {
        recipeModel.setHealthScore(23);

        Assert.assertEquals(recipeModel.getHealthScore(), 23, 23);
    }

    @Test
    public void setSpoonacularScore() {
        recipeModel.setSpoonacularScore(23);

        Assert.assertEquals(recipeModel.getSpoonacularScore(), 23, 23);
    }
}


text:
require 'active_support/basic_object'
require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/object/acts_like'

module ActiveSupport
  # Provides accurate date and time measurements using Date#advance and
  # Time#advance, respectively. It mainly supports the methods on Numeric.
  # Example:
  #
  #   1.month.ago       # equivalent to Time.now.advance(:months => -1)
  class Duration < BasicObject
    attr_accessor :value, :parts

    def initialize(value, parts) #:nodoc:
      @value, @parts = value, parts
    end

    # Adds another Duration or a Numeric to this Duration. Numeric values
    # are treated as seconds.
    def +(other)
      if Duration === other
        Duration.new(value + other.value, @parts + other.parts)
      else
        Duration.new(value + other, @parts + [[:seconds, other]])
      end
    end

    # Subtracts another Duration or a Numeric from this Duration. Numeric
    # values are treated as seconds.
    def -(other)
      self + (-other)
    end

    def -@ #:nodoc:
      Duration.new(-value, parts.map { |type,number| [type, -number] })
    end

    def is_a?(klass) #:nodoc:
      Duration == klass || value.is_a?(klass)
    end
    alias :kind_of? :is_a?

    # Returns true if <tt>other</tt> is also a Duration instance with the
    # same <tt>value</tt>, or if <tt>other == value</tt>.
    def ==(other)
      if Duration === other
        other.value == value
      else
        other == value
      end
    end

    def self.===(other) #:nodoc:
      other.is_a?(Duration)
    rescue ::NoMethodError
      false
    end

    # Calculates a new Time or Date that is as far in the future
    # as this Duration represents.
    def since(time = ::Time.current)
      sum(1, time)
    end
    alias :from_now :since

    # Calculates a new Time or Date that is as far in the past
    # as this Duration represents.
    def ago(time = ::Time.current)
      sum(-1, time)
    end
    alias :until :ago

    def inspect #:nodoc:
      consolidated = parts.inject(::Hash.new(0)) { |h,part| h[part.first] += part.last; h }
      parts = [:years, :months, :days, :minutes, :seconds].map do |length|
        n = consolidated[length]
        "#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
      end.compact
      parts = ["0 seconds"] if parts.empty?
      parts.to_sentence(:locale => :en)
    end

    protected

      def sum(sign, time = ::Time.current) #:nodoc:
        parts.inject(time) do |t,(type,number)|
          if t.acts_like?(:time) || t.acts_like?(:date)
            if type == :seconds
              t.since(sign * number)
            else
              t.advance(type => sign * number)
            end
          else
            raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
          end
        end
      end

    private

      def method_missing(method, *args, &block) #:nodoc:
        value.send(method, *args)
      end
  end
end


text:
namespace TorrentStream
{

	Peer::Peer
	(
		const std::string& ip,
		int port,
		const std::string& id,
		size_t pieceCount,
		size_t pieceLength,
		const std::string& infoHash,
		const std::string& selfId
	) :
		m_ID(id), m_IP(ip), m_PieceCount(pieceCount), m_PieceLength(pieceLength)
	{
		m_Comm = std::make_unique<ASIO::PeerComm>(ip, xs("%", port), infoHash, selfId);
		m_HasPieces.resize(m_PieceCount);
	}

	void Peer::Connect()
	{
		m_Comm->Connect();
	}

	void Peer::Update()
	{
		using ASIO::Peer::MessageType;

		m_Comm->DispatchAllMessages();

		if (m_Downloading && m_Comm->GetState() == ASIO::PeerCommState::Working)
		{
			while (m_InFlight.size() < 10 && m_Requests.size() > 0)
			{
				auto offset = m_Requests.front();
				m_Requests.pop_front();

				auto size = RequestSize;

				auto msg = std::make_unique<ASIO::Peer::Request>(m_PieceIndex, offset, size);
				m_Comm->PushOutgoingMessage(std::move(msg));

				m_InFlight.push_back(offset);
			}

			if (m_Requests.size() == 0 && m_InFlight.size() == 0)
			{
				m_Downloading = false;
				m_Finished = true;
			}
		}

		while (auto msg = m_Comm->PopIncomingMessage())
		{
			if (msg->GetType() == MessageType::Bitfield)
			{
				auto bitfieldMessage = (ASIO::Peer::Bitfield*)msg.get();
				auto bitfield = bitfieldMessage->GetBitfield();

				assert(m_HasPieces.size() <= bitfield.size());

				for (auto i = 0u; i < m_HasPieces.size(); i++)
				{
					m_HasPieces[i] = bitfield[i];
				}
			}
			else if (msg->GetType() == MessageType::Have)
			{
				auto haveMessage = (ASIO::Peer::Have*)msg.get();
				auto index = haveMessage->GetIndex();

				assert(index >= 0 && index < m_PieceCount);
				m_HasPieces[index] = true;
			}
			else if (msg->GetType() == MessageType::Piece)
			{
				auto pieceMessage = (ASIO::Peer::Piece*)msg.get();

				if (pieceMessage->GetIndex() != m_PieceIndex)
				{
					LOG("bad piece index");
					continue;
				}

				if (std::find(m_InFlight.begin(), m_InFlight.end(), pieceMessage->GetBegin()) == m_InFlight.end())
				{
					LOG("bad piece offset");
					continue;
				}

				std::remove(m_InFlight.begin(), m_InFlight.end(), pieceMessage->GetBegin());
				m_InFlight.pop_back();

				auto block = pieceMessage->GetBlock();

				if (block.size() != RequestSize)
				{
					LOG("bad piece size");
					continue;
				}

				m_BandwidthTracker.AddSample(block.size());
				m_PieceData->SubmitData(pieceMessage->GetBegin(), block);
			}
			else if (msg->GetType() == MessageType::Unchoke)
			{
			}
		}
	}

	void Peer::StartDownload(size_t pieceIndex)
	{
		if (m_HasPieces[pieceIndex] == false)
		{
			LOG("cannot StartDownload(), peer doesn't have piece");
		}

		m_Downloading = true;
		m_Finished = false;
		m_PieceIndex = pieceIndex;
		m_PieceData = std::make_unique<Piece>(m_PieceLength);

		m_Requests.clear();
		m_InFlight.clear();
		for (auto i = 0u; i < m_PieceLength; i += RequestSize)
		{
			m_Requests.push_back(i);
		}

		auto msg = std::make_unique<ASIO::Peer::Interested>();
		m_Comm->PushOutgoingMessage(std::move(msg));
	}

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>registrar-servicos-especializados-em-seguranca-e-medicina-do-trabalho</id>
    <dbId>831</dbId>
    <nome>Registrar Serviços Especializados em Segurança e Medicina do Trabalho</nome>
    <sigla>SESMT</sigla>
    <descricao>SESMT – Serviço Especializado em Segurança e Medicina do Trabalho, como o próprio nome já diz, é uma equipe de profissionais em segurança e saúde do trabalho que estão dentro de várias empresas – conforme quantidade de trabalhadores e risco das atividades - para a prevenção de acidentes e doenças decorrentes do exercício do trabalho.
Sua constituição está prevista no Art. 162 da Consolidação das Leis do Trabalho e todo o processo de constituição está na Norma Regulamentadora nº 04, do MTb.</descricao>
    <contato>**E-mail**: sesmt@mte.gov.br</contato>
    <gratuito>true</gratuito>
    <porcentagem>0</porcentagem>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="5582">
            <tipo>Empresas que possuam empregados</tipo>
            <requisitos>O SESMT deve ser constituído nas empresas em razão da quantidade de empregados e do risco da atividade. Você pode saber quantos profissionais tem no SESMT de sua empresa consultando os quadros I e II da [Norma Regulamentadora nº 4](http://trabalho.gov.br/seguranca-e-saude-no-trabalho/normatizacao/normas-regulamentadoras).
As empresas que têm SESMT tem que fazer registrá-los no Ministério do Trabalho, de forma eletrônica.</requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <atendimento-imediato/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="9942">
            <titulo>Cadastrar-se no sistema</titulo>
            <descricao>Em primeiro lugar você deve cadastrar um usuário e senha no sistema SESMT</descricao>
            <documentos>
                <default>
                    <item id="14334">CPF</item>
                    <item id="14335">Data de Nascimento</item>
                    <item id="14336">Endereço de e-mail</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <tempo-total-estimado>
                <atendimento-imediato/>
            </tempo-total-estimado>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="11028" tipo="web">
                        <descricao>http://sesmt.mte.gov.br/Usuario/CadastrarUsuario.aspx</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="9943">
            <titulo>Cadastrar serviços</titulo>
            <descricao>Realizada a inscrição no sistema, você agora irá cadastrar os dados dos SESMTs de sua empresa, assim como os dados dos profissionais que os compõem.</descricao>
            <documentos>
                <default>
                    <item id="14338">Dados da empresa</item>
                    <item id="14339">Dados dos Serviços Especializados em Segurança e Medicina do Trabalho da Empresa</item>
                    <item id="14340">Dados dos profissionais que compõe os serviços.</item>
                </default>
                <caso id="1468" descricao="Outros">
                    <documento>
                        <id>14337</id>
                        <descricao>Você pode encontrar o Manual do usuário do SESMT e um guia de perguntas e respostas na página do [Ministério do Trabalho](http://trabalho.gov.br/seguranca-e-saude-no-trabalho/sistema-sesmt-servicos-especializados-em-engenharia-de-seguranca-e-em-medicina-do-trabalho).
Acesse e tire as suas dúvidas a respeito do funcionamento do Sistema SESMT.</descricao>
                    </documento>
                </caso>
            </documentos>
            <custos>
                <default/>
            </custos>
            <tempo-total-estimado>
                <atendimento-imediato/>
            </tempo-total-estimado>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="11029" tipo="web">
                        <descricao>http://sesmt.mte.gov.br/</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="9944">
            <titulo>Imprimir recibo</titulo>
            <descricao>Após a conclusão de cadastro do SESMT, o sistema irá gerar um recibo, que você poderá imprimir e que é o comprovante de cumprimento desta obrigação legal.</descricao>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <tempo-total-estimado>
                <atendimento-imediato/>
            </tempo-total-estimado>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="11030" tipo="web">
                        <descricao>http://sesmt.mte.gov.br/</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/2844" dbId="37546">
        <nomeOrgao>Ministério do Trabalho  (MTB)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="3" idServicoSegmento="9582">Empresas</item>
        <item idSegmento="4" idServicoSegmento="9583">Demais segmentos (ONGs, organizações sociais, etc)</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Fiscalização do Estado</item>
        <item>Proteção e Benefícios ao Trabalhador</item>
        <item>Relações de Trabalho</item>
        <item>Saúde</item>
        <item>Trabalho</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="18462">Segurança</item>
        <item id="18463">Medicina do Trabalho</item>
        <item id="18464">Cadastro</item>
    </palavras-chave>
    <legislacoes>
        <item id="3394">[Consolidação das Leis do Trabalho - CLT - art. 162](http://www.planalto.gov.br/ccivil_03/Decreto-Lei/Del5452.htm )</item>
        <item id="3395">[Norma Regulamentadora nº 4](http://trabalho.gov.br/seguranca-e-saude-no-trabalho/normatizacao/normas-regulamentadoras)</item>
        <item id="3396">[Portaria SIT nº 559, DE 3 DE AGOSTO DE 2016](http://trabalho.gov.br/images/Documentos/SST/sesmt/portaria-559.pdf)</item>
    </legislacoes>
    <condicoes-acessibilidade>****</condicoes-acessibilidade>
    <tratamento-prioritario>****</tratamento-prioritario>
    <tratamento-dispensado-atendimento>****</tratamento-dispensado-atendimento>
</servico>


text:
import json

from flask import current_app, request

def json_response(data, code=200, headers=None):
    return current_app.response_class(
        response=json.dumps(data),
        headers=headers,
        status=code,
        mimetype='application/json'
    )

def alternate_response(accept, func, *args, **kwargs):
    accept_from_request = request.headers.get('accept')
    if accept == accept_from_request:
        return func(*args, **kwargs)


text:
qr-image
=========

This is yet another QR Code generator.

Overview
--------

  * No dependecies;
  * generate image in `png`, `svg`, `eps` and `pdf` formats;
  * numeric and alphanumeric modes;
  * support UTF-8.

[Releases](https://github.com/alexeyten/qr-image/releases/)

Usage
-----

Example:
```
var qr = require('qr-image');

var qr_svg = qr.image('I love QR!', { type: 'svg' });
qr_svg.pipe(require('fs').createWriteStream('i_love_qr.svg'));
```

[More examples](./examples)

`qr = require('qr-image')`

`qr.image(text, [ec_level | options])` — returns Readable stream with image data.
`qr.matrix(text, [ec_level])` — returns 2D array.

  * `text` — text to encode;
  * `ec_level` — error correction level. One of `L`, `M`, `Q`, `H`. Default `M`.
  * `options` — image options object:
    * `ec_level` — default `M`.
    * `type` — image type. Possible values `png` (default), `svg`, `pdf` and `eps`.
    * `size` (only png) — size of one module in pixels. Default `5`.
    * `margin` (only png) — white space around QR image in modules. Default `4`.
    * `customize` (only png) — function to customize qr bitmap before encoding to PNG.

TODO
----

  * Tests;
  * mixing modes;
  * Kanji (???).


text:
package org.apache.struts.tiles.actions;

import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.DefinitionsFactory;
import org.apache.struts.tiles.DefinitionsFactoryException;
import org.apache.struts.tiles.TilesUtil;

/**
 *
A standard Action that calls the
 * reload() method of our controller servlet to
 * reload its configuration information from the configuration
 * files (which have presumably been updated) dynamically.

 *
 * @version $Rev$ $Date$
 */

public class ReloadDefinitionsAction extends Action {

    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it),
     * with provision for handling exceptions thrown by the business logic.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if the application business logic throws
     *  an exception
     * @since Struts 1.1
     */
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
        throws Exception
    {
        response.setContentType("text/plain");
        PrintWriter writer = response.getWriter();

        try {
          ServletContext context = getServlet().getServletContext();
            DefinitionsFactory factory = TilesUtil.getDefinitionsFactory(request, context);
            factory.setConfig(factory.getConfig(), context);
            writer.println("OK");
        } catch (ClassCastException e) {
            writer.println("FAIL - " + e.toString());
            getServlet().log("ReloadAction", e);
        } catch (DefinitionsFactoryException e) {
            writer.println("FAIL - " + e.toString());
            getServlet().log("ReloadAction", e);
        }

        writer.flush();
        writer.close();

        return (null);

    }

}


text:
// ********************************************************************************************************
// Product Name: DotSpatial.Tools.ModelerToolStrip
// Description:  A tool strip designed to work along with the modeler
//
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is Toolbox.dll for the DotSpatial 4.6/6 ToolManager project
//
// The Initial Developer of this Original Code is Brian Marchionni. Created in Apr, 2009.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace DotSpatial.Controls
{
    /// <summary>
    /// A Brian Marchioni original toolstrip... preloaded with content.
    /// </summary>
    [ToolboxItem(false)]
    public class ModelerToolStrip : ToolStrip
    {
        #region "Private Variables"

        private ToolStripButton _btnAddData;
        private ToolStripButton _btnDelete;
        private ToolStripButton _btnLink;
        private ToolStripButton _btnLoadModel;
        private ToolStripButton _btnNewModel;
        private ToolStripButton _btnRun;
        private ToolStripButton _btnSaveModel;
        private ToolStripButton _btnZoomFullExtent;

        private ToolStripButton _btnZoomIn;
        private ToolStripButton _btnZoomOut;
        private Modeler _modeler;

        #endregion

        #region "Constructor"

        /// <summary>
        /// Creates an instance of the toolstrip
        /// </summary>
        public ModelerToolStrip()
        {
            InitializeComponent();
        }

        #endregion

        #region "properties"

        /// <summary>
        /// Gets or sets the modeler currently associated with the toolstrip
        /// </summary>
        public Modeler Modeler
        {
            get { return _modeler; }
            set { _modeler = value; }
        }

        #endregion

        private void InitializeComponent()
        {
            SuspendLayout();

            //New model button
            _btnNewModel = new ToolStripButton();
            _btnNewModel.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnNewModel.Image = Images.file_new;
            _btnNewModel.ImageTransparentColor = Color.Magenta;
            _btnNewModel.Name = "btnNewModel";
            _btnNewModel.Size = new Size(23, 22);
            _btnNewModel.Text = MessageStrings.ModelTipNew;
            //_btnNewModel.Click

            //save model button
            _btnSaveModel = new ToolStripButton();
            _btnSaveModel.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnSaveModel.Image = Images.file_saveas;
            _btnSaveModel.ImageTransparentColor = Color.Magenta;
            _btnSaveModel.Name = "btnSaveModel";
            _btnSaveModel.Size = new Size(23, 22);
            _btnSaveModel.Text = MessageStrings.ModelTipSave;
            _btnSaveModel.Click += BtnSaveModelClick;

            //Load model button
            _btnLoadModel = new ToolStripButton();
            _btnLoadModel.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnLoadModel.Image = Images.FolderOpen;
            _btnLoadModel.ImageTransparentColor = Color.Magenta;
            _btnLoadModel.Name = "btnLoadModel";
            _btnLoadModel.Size = new Size(23, 22);
            _btnLoadModel.Text = MessageStrings.ModelTipLoad;
            _btnLoadModel.Click += BtnLoadModelClick;

            //Zoom In button
            _btnZoomIn = new ToolStripButton();
            _btnZoomIn.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnZoomIn.Image = Images.zoom_in.ToBitmap();
            _btnZoomIn.ImageTransparentColor = Color.Magenta;
            _btnZoomIn.Name = "btnZoomIn";
            _btnZoomIn.Size = new Size(23, 22);
            _btnZoomIn.Text = MessageStrings.ModelTipZoonIn;
            _btnZoomIn.Click += BtnZoomInClick;

            //Zoom out button
            _btnZoomOut = new ToolStripButton();
            _btnZoomOut.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnZoomOut.Image = Images.zoom_out.ToBitmap();
            _btnZoomOut.ImageTransparentColor = Color.Magenta;
            _btnZoomOut.Name = "btnZoomOut";
            _btnZoomOut.Size = new Size(23, 22);
            _btnZoomOut.Text = MessageStrings.ModelTipZoomOut;
            _btnZoomOut.Click += BtnZoomOutClick;

            //Zoom full extent
            _btnZoomFullExtent = new ToolStripButton();
            _btnZoomFullExtent.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnZoomFullExtent.Image = Images.zoom_full_extent.ToBitmap();
            _btnZoomFullExtent.ImageTransparentColor = Color.Magenta;
            _btnZoomFullExtent.Name = "btnZoomOut";
            _btnZoomFullExtent.Size = new Size(23, 22);
            _btnZoomFullExtent.Text = MessageStrings.ModelTipFullExtent;
            _btnZoomFullExtent.Click += BtnZoomFullExtentClick;

            //Add data button
            _btnAddData = new ToolStripButton();
            _btnAddData.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnAddData.Image = Images.AddLayer;
            _btnAddData.ImageTransparentColor = Color.Magenta;
            _btnAddData.Name = "btnLink";
            _btnAddData.Size = new Size(23, 22);
            _btnAddData.Text = MessageStrings.ModelTipAddData;
            // _btnAddData.Click += new EventHandler(BtnLinkClick);

            //Zoom link tools
            _btnLink = new ToolStripButton();
            _btnLink.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnLink.Image = Images.LinkData;
            _btnLink.ImageTransparentColor = Color.Magenta;
            _btnLink.Name = "btnLink";
            _btnLink.Size = new Size(23, 22);
            _btnLink.Text = MessageStrings.ModelTipLink;
            _btnLink.Click += BtnLinkClick;

            //delete stuff
            _btnDelete = new ToolStripButton();
            _btnDelete.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnDelete.Image = Images.mnuLayerClear;
            _btnDelete.ImageTransparentColor = Color.Magenta;
            _btnDelete.Name = "btnLink";
            _btnDelete.Size = new Size(23, 22);
            _btnDelete.Text = MessageStrings.ModelTipDelete;
            _btnDelete.Click += BtnDeleteClick;

            //delete stuff
            _btnRun = new ToolStripButton();
            _btnRun.DisplayStyle = ToolStripItemDisplayStyle.Image;
            _btnRun.Image = Images.RunModel;
            _btnRun.ImageTransparentColor = Color.Magenta;
            _btnRun.Name = "btnLink";
            _btnRun.Size = new Size(23, 22);
            _btnRun.Text = MessageStrings.ModelTipRunModel;
            _btnRun.Click += BtnRunClick;

            //Adds all the buttons to the toolstrip
            Items.Add(_btnNewModel);
            Items.Add(_btnLoadModel);
            Items.Add(_btnSaveModel);
            Items.Add(new ToolStripSeparator());
            Items.Add(_btnZoomIn);
            Items.Add(_btnZoomOut);
            Items.Add(_btnZoomFullExtent);
            Items.Add(new ToolStripSeparator());
            Items.Add(_btnAddData);
            Items.Add(_btnLink);
            Items.Add(_btnDelete);
            Items.Add(new ToolStripSeparator());
            Items.Add(_btnRun);

            ResumeLayout();
        }

        private void BtnRunClick(object sender, EventArgs e)
        {
            Parent.Enabled = false;
            string error;
            _modeler.ExecuteModel(out error);
            Parent.Enabled = true;
        }

        private void BtnLoadModelClick(object sender, EventArgs e)
        {
            _modeler.LoadModel();
        }

        private void BtnSaveModelClick(object sender, EventArgs e)
        {
            _modeler.SaveModel();
        }

        #region "Envent Handlers"

        //Fires when the user clicks the delete button
        private void BtnDeleteClick(object sender, EventArgs e)
        {
            _modeler.DeleteSelectedElements();
        }

        //Fires when the user clicks the link button
        private void BtnLinkClick(object sender, EventArgs e)
        {
            if (_modeler.EnableLinking)
            {
                _btnLink.Checked = false;
                _modeler.EnableLinking = false;
            }
            else
            {
                _btnLink.Checked = true;
                _modeler.EnableLinking = true;
            }
        }

        //Fires when the user clicks the zoom to full extent button
        private void BtnZoomFullExtentClick(object sender, EventArgs e)
        {
            _modeler.ZoomFullExtent();
        }

        //Fires the zoom in control on the modeler
        private void BtnZoomInClick(object sender, EventArgs e)
        {
            _modeler.ZoomIn();
        }

        //Fires the zoom out control on the modeler
        private void BtnZoomOutClick(object sender, EventArgs e)
        {
            _modeler.ZoomOut();
        }

        #endregion
    }
}


text:
from allauth.socialaccount.providers.oauth.urls import default_urlpatterns

from .provider import BitbucketOAuth2Provider

urlpatterns = default_urlpatterns(BitbucketOAuth2Provider)


text:
package org.kie.workbench.common.forms.common.rendering.client.widgets.decimalBox;

import javax.inject.Inject;

import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasValue;
import org.jboss.errai.common.client.dom.TextInput;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.SinkNative;
import org.jboss.errai.ui.shared.api.annotations.Templated;

@Templated
public class DecimalBoxViewImpl extends Composite implements DecimalBoxView {

    private DecimalBox presenter;

    @Inject
    @DataField
    private TextInput input;

    @Override
    public void setPresenter(DecimalBox presenter) {
        this.presenter = presenter;
    }

    @Override
    public void setValue(String value) {
        input.setValue(value);
    }

    @Override
    public void setEnabled(boolean enabled) {
        input.setDisabled(!enabled);
    }

    public void updateValue(Event event) {
        presenter.notifyValueChange(getTextValue());
    }

    @Override
    public String getTextValue() {
        return input.getValue();
    }

    @Override
    public void setId(String id) {
        input.setId(id);
    }

    @Override
    public void setPlaceholder(String placeHolder) {
        input.setAttribute("placeholder",
                           placeHolder);
    }

    @Override
    public void setMaxLength(Integer maxLength) {
        input.setMaxLength(maxLength);
    }

    public void onKeyDown(Event event) {

        int key = event.getKeyCode();
        boolean isShiftPressed = event.getShiftKey();

        if (presenter.isInvalidKeyCode(key,
                                       isShiftPressed)) {
            event.stopPropagation();
            event.preventDefault();
        }
    }

    @SinkNative(Event.ONKEYDOWN | Event.ONCHANGE)
    @EventHandler("input")
    public void onEvent(Event event) {
        switch (event.getTypeInt()) {
            case Event.ONCHANGE:
                updateValue(event);
                break;
            case Event.ONKEYDOWN:
                onKeyDown(event);
                break;
            default:
                break;
        }
    }

    @Override
    public HasValue<Double> wrapped() {
        return presenter;
    }
}


text:
module Scopy
  module NameScopes
    extend ActiveSupport::Concern

    # note: case-sensitive like operations do not work as expected in Sqlite,
    # which we are using as the test database.
    # see http://goo.gl/Lxxc4m

    included do
      scope :name_like, ->(text, options = {}) do
        cs = options[:case_sensitive]
        where("#{_lhs_name_column(cs)} LIKE ?", "%#{_rhs_name_value(text, cs)}%")
      end

      scope :name_starts_with, ->(text, options = {}) do
        cs = options[:case_sensitive]
        where("#{_lhs_name_column(cs)} LIKE ?", "#{_rhs_name_value(text, cs)}%")
      end
    end

    module ClassMethods
      def _lhs_name_column(case_sensitive)
        case_sensitive ? "#{table_name}.name" : "LOWER(#{table_name}.name)"
      end

      def _rhs_name_value(text, case_sensitive)
        case_sensitive ? text : text.try(:downcase)
      end
    end
  end
end


text:
package com.sleepycat.db;

import com.sleepycat.db.internal.DbConstants;

/**
The recovery operation being performed when {@link com.sleepycat.db.LogRecordHandler#handleLogRecord LogRecordHandler.handleLogRecord} is called.
*/
public final class RecoveryOperation {
    /**
    The log is being read backward to determine which transactions have
    been committed and to abort those operations that were not; undo the
    operation described by the log record.
    */
    public static final RecoveryOperation BACKWARD_ROLL =
        new RecoveryOperation("BACKWARD_ROLL", DbConstants.DB_TXN_BACKWARD_ROLL);
    /**
    The log is being played forward; redo the operation described by the log
    record.

    The FORWARD_ROLL and APPLY operations frequently imply the same actions,
    redoing changes that appear in the log record, although if a recovery
    function is to be used on a replication client where reads may be taking
    place concurrently with the processing of incoming messages, APPLY
    operations should also perform appropriate locking.
    */
    public static final RecoveryOperation FORWARD_ROLL =
        new RecoveryOperation("FORWARD_ROLL", DbConstants.DB_TXN_FORWARD_ROLL);
    /**
    The log is being read backward during a transaction abort; undo the
    operation described by the log record.
    */
    public static final RecoveryOperation ABORT =
        new RecoveryOperation("ABORT", DbConstants.DB_TXN_ABORT);
    /**
    The log is being applied on a replica site; redo the operation
    described by the log record.

    The FORWARD_ROLL and APPLY operations frequently imply the same actions,
    redoing changes that appear in the log record, although if a recovery
    function is to be used on a replication client where reads may be taking
    place concurrently with the processing of incoming messages, APPLY
    operations should also perform appropriate locking.
    */
    public static final RecoveryOperation APPLY =
        new RecoveryOperation("APPLY", DbConstants.DB_TXN_APPLY);
    /**
    The log is being printed for debugging purposes; print the contents of
    this log record in the desired format.
    */
    public static final RecoveryOperation PRINT =
        new RecoveryOperation("PRINT", DbConstants.DB_TXN_PRINT);

    private String operationName;
    private int flag;

    private RecoveryOperation(String operationName, int flag) {
        this.operationName = operationName;
        this.flag = flag;
    }

    /** {@inheritDoc} */
    public String toString() {
        return "RecoveryOperation." + operationName;
    }

    /* This is public only so it can be called from internal/DbEnv.java. */
    /**
    Internal: this is public only so it can be called from an internal
    package.
     *
    @param flag
    the internal flag value to be wrapped in a RecoveryException object
    */
    public static RecoveryOperation fromFlag(int flag) {
        switch (flag) {
        case DbConstants.DB_TXN_BACKWARD_ROLL:
            return BACKWARD_ROLL;
        case DbConstants.DB_TXN_FORWARD_ROLL:
            return FORWARD_ROLL;
        case DbConstants.DB_TXN_ABORT:
            return ABORT;
        case DbConstants.DB_TXN_APPLY:
            return APPLY;
        case DbConstants.DB_TXN_PRINT:
            return PRINT;
        default:
            throw new IllegalArgumentException(
                "Unknown recover operation: " + flag);
        }
    }
}


text:
silex1
======

Learning AngularJS, CSS3, HTML5, Silex and co.


text:
NS_ASSUME_NONNULL_BEGIN

@interface ParseData : NSObject

@property (nonatomic, copy)     NSString        *province;
@property (nonatomic, copy)     NSString        *city;
@property (nonatomic, copy)     NSString        *cityCode;
@property (nonatomic, copy)     NSString        *mobilePrefix;

@property (nonatomic, readonly) NSString        *phoneid;
@property (atomic, assign)      BOOL            success;

- (instancetype)initWithPhoneId:(NSString *)phoneid;

@end

@interface ContactParser : ContactDataModal

+ (instancetype)sharedClient;

- (void)parseContacts;

- (void)addressQueryForNumber:(nullable NSString *)number
                                                   block:(nullable void (^)(BOOL success,  NSDictionary * _Nullable info))block;

@end

NS_ASSUME_NONNULL_END


text:
namespace InControl.NativeProfile
{
	// @cond nodoc
	public class HoriBlueSoloControllerMacProfile : Xbox360DriverMacProfile
	{
		public HoriBlueSoloControllerMacProfile()
		{
			Name = "Hori Blue Solo Controller ";
			Meta = "Hori Blue Solo Controller	on Mac";

			Matchers = new[] {
				new NativeInputDeviceMatcher {
					VendorID = 0x1bad,
					ProductID = 0xfa01,
				},
			};
		}
	}
	// @endcond
}


text:
title: "Isolated Unit Tests with Sinonjs"
path: "/isolated-unit-tests-with-sinonjs/"
date: "2016-03-05T21:02:37.000Z"
date_updated:   2017-01-16T19:59:41.000Z
tags: TDD, JavaScript, Nodejs
---

Units in Unit Testing is the smallest unit of code. But how small? Small enough to be tested. For that matter, Unit Tests need to be isolated and for that you need stubs.

Here I will use a small function and the [Sinonjs](http://sinonjs.org) to try to test it. My function does some checks and finally an HTTP call to an external service while similar functions would hit a DB. But our intention is to test the actual function and we don't want to hit the external service.

In case that you think: "No we should let it hit the external so we can test that too". Well no, remember, we are writing unit tests. You're talking about integration tests, where we test how multiple components interact with each other. Also, this is an external service and our test suite shouldn't test external services. This is a clean separation of concerns. It's not our test suite's responsibility to test anything else that itself.

Here's a simple function:
```js
const request = require('request');

const createToDoItem = function (description) {

  return new Promise(function (resolve, reject) {

    if (!description) {
      return reject(new Error('description is required'));
    }

    request.post({
      url: 'https://todo/items/endpoint',
      body: {
        description: description,
        completed: false
      }
    }, function (err, res, body) {

       if (err) {
         reject(err);
       } else {
         resolve(body);
       }
    });
  });
};
```

So the `createToDoItem` does two things. First it checks for the validity of the required parameter `description` and then contacts the external service that is responsible for storing Todo Items.

Now we need to test that function as a unit, so we have to isolate it. We don't want to contact the external service.

```js
describe('To Do Items', function () {

  describe('Create Items', function () {

    it('requires the description parameter', function (done) {

      createToDoItem()
        .catch(function (err) {

          expect(err).to.be.an.instanceOf(Error);
          expect(err.message).to.equals('description is required');
          done();
        })
        .catch(done);
    });

    it('rejects on error from the remote service', function (done) {

      var stub = sinon.stub(request, post)
        .yields(new Error());

      createToDoItem()
        .catch(function () {

          stub.restore();
          done();
        })
        .catch(done);
    });

    it('resolves on succesfull creation', function (done) {

      var stub = sinon.stub(request, post)
        .yields(null, null, {
          _id: 'ITEM_ID',
          description: 'Remember to write that blog post',
          completed: false
        });

      createToDoItem('Remember to write that blog post')
        .then(function (todo) {

          expect(todo._id).to.equals('ITEM_ID')
          expect(todo.description).to.equals('Remember to write that blog post');
          stub.restore();
          expect(todo.completed).to.be.false;
        })
        .catch(done);
    });
  });
});
```

I hope the code to be self-documented. At first, we call our function without a parameter so the first condition will be true and an error will be thrown. Then we stub the `request` object so it will run the callback function with an error. This will trigger the second condition and reject our promise. Inside the `catch` function, we know that the promise has been rejected. For the end, we stub the callback to return with a null error and a body that will resolve the promise and we test that inside the `then` function. 100% code coverage.

This way we have completely isolated our Unit Under Test and made it blazingly fast to run since we don't make any actual HTTP requests. We pretty much covered the [F.I.R.S.T. principles of Unit Testing](https://pragprog.com/magazines/2012-01/unit-tests-are-first).

Unit tests should be completely isolated.

Always remember the [inverted testing pyramid](http://blogs.agilefaqs.com/2011/02/01/inverting-the-testing-pyramid/). Invest in Unit Testing so to avoid manual system testing. It is expensive.


text:
#include <config.h>

#include <stdio.h>
#include <assert.h>
#include <ctype.h>

#if HAVE_ERRNO_H
#include <errno.h>
#endif

#if HAVE_UNISTD_H
#include <unistd.h>
#endif

#if HAVE_STDLIB_H
#include <stdlib.h>
#endif

#if HAVE_STRING_H
#include <string.h>
#endif

#if HAVE_LIBGEN_H
#include <libgen.h>
#endif

#if HAVE_LOCALE_H
#include <locale.h>
#endif

#include "tds_sysdep_public.h"
#include <sql.h>
#include <sqlext.h>
#include "replacements.h"

#include <freetds/sysdep_private.h>

static char * next_query(void);
static void print_results(SQLHSTMT hStmt);
/* static int get_printable_size(int type, int size); */
static void usage(const char invoked_as[]);

static SQLINTEGER print_error_message(SQLSMALLINT hType, SQLHANDLE handle);
static SQLRETURN odbc_herror(SQLSMALLINT hType, SQLHANDLE handle, SQLRETURN erc, const char func[], const char msg[]);
static SQLRETURN odbc_perror(SQLHSTMT hStmt, SQLRETURN erc, const char func[], const char msg[]);
static const char * prret(SQLRETURN erc);

struct METADATA
{
	char *name, *format_string;
	const char *source;
	SQLSMALLINT type;
	SQLINTEGER nchars;
	SQLULEN size, width;
};
struct DATA { char *buffer; SQLLEN len; int status; };

static int set_format_string(struct METADATA * meta, const char separator[]);

typedef struct _options
{
	int 	fverbose,
		fquiet;
	size_t	odbc_version;
	FILE 	*headers,
		*verbose;
	char 	*servername,
		*database,
		*appname,
		 hostname[128];
	const char *colsep;
	char	*input_filename,
		*output_filename,
		*error_filename;
} OPTIONS;

typedef struct
{
	int connect_timeout, query_timeout;
	char 	*client_hostname,
		*username,
		*password,
		*client_charset;
} LOGINREC;

static LOGINREC* get_login(int argc, char *argv[], OPTIONS *poptions);

/* global variables */
OPTIONS options;
static const char default_colsep[] = "  ";
/* end global variables */

/**
 * The purpose of this program is threefold:
 *
 * 1.  To provide a generalized SQL processor suitable for testing the FreeTDS ODBC driver.
 * 2.  To offer a robust batch-oriented SQL processor suitable for use in a production environment.
 * 3.  To serve as a model example of how to use ODBC functions.
 *
 * These purposes may be somewhat impossible.  The original author is not an experienced ODBC programmer.
 * Nevertheless the first objective can be met and is useful by itself.
 * If others join in, perhaps the others can be met, too.
 */

/**
 * When SQLExecute returns either SQL_ERROR or SQL_SUCCESS_WITH_INFO,
 * an associated SQLSTATE value can be obtained by calling SQLGetDiagRec
 * with a HandleType of SQL_HANDLE_STMT and a Handle of StatementHandle.
 */
static SQLINTEGER
print_error_message(SQLSMALLINT hType, SQLHANDLE handle) {
	int i;
	SQLINTEGER ndiag=0;
	SQLRETURN ret;
	SQLCHAR state[6];
	SQLINTEGER error, maxerror=0;
	SQLCHAR text[1024];
	SQLSMALLINT len;

	ret = SQLGetDiagField(hType, handle, 0, SQL_DIAG_NUMBER, &ndiag, sizeof(ndiag), NULL);
	assert(ret == SQL_SUCCESS);

	for(i=1; i <= ndiag; i++) {
		memset(text, '\0', sizeof(text));
		ret = SQLGetDiagRec(hType, handle, i, state, &error, text, sizeof(text), &len);

		if (ret == SQL_SUCCESS && error == 0) {
			fprintf(stdout, "\"%s\"\n", text);
			continue;
		}

		fprintf(stderr, "%s: error %d: %s: %s\n", options.appname, (int)error, state, text);
		assert(ret == SQL_SUCCESS);

		if (error > maxerror)
			maxerror = error;
	}
	return maxerror;
}

static const char *
prret(SQLRETURN erc)
{
	switch(erc) {
	case SQL_SUCCESS: 		return "SQL_SUCCESS";
	case SQL_SUCCESS_WITH_INFO: 	return "SQL_SUCCESS_WITH_INFO";
	case SQL_ERROR: 		return "SQL_ERROR";
	case SQL_STILL_EXECUTING: 	return "SQL_STILL_EXECUTING";
	case SQL_INVALID_HANDLE: 	return "SQL_INVALID_HANDLE";
	case SQL_NO_DATA: 		return "SQL_NO_DATA";
	}
	fprintf(stderr, "error:%d: prret cannot interpret SQLRETURN code %d\n", __LINE__, erc);
	return "unknown";
}

static SQLRETURN
odbc_herror(SQLSMALLINT hType, SQLHANDLE handle, SQLRETURN erc, const char func[], const char msg[])
{
	char * ercstr;

	assert(func && msg);

	switch(erc) {
	case SQL_SUCCESS:
		return erc;
	case SQL_SUCCESS_WITH_INFO:
		ercstr = "SQL_SUCCESS_WITH_INFO";
		break;
	case SQL_ERROR:
		ercstr = "SQL_ERROR";
		break;
	case SQL_STILL_EXECUTING:
		ercstr = "SQL_STILL_EXECUTING";
		break;
	case SQL_INVALID_HANDLE:
		fprintf(stderr, "%s: error %d: %s: invalid handle: %s\n", options.appname, (int)erc, func, msg);
		exit(EXIT_FAILURE);
	default:
		fprintf(stderr, "%s: error: %d is an unknown return code for %s\n", options.appname, (int)erc, func);
		exit(EXIT_FAILURE);
	}

	fprintf(stderr, "%s: error %d: %s: %s: %s\n", options.appname, (int)erc, func, ercstr, msg);

	print_error_message(hType, handle);

	return erc;
}

static SQLRETURN
odbc_perror(SQLHSTMT hStmt, SQLRETURN erc, const char func[], const char msg[])
{
	return odbc_herror(SQL_HANDLE_STMT, hStmt, erc, func, msg);
}

int
main(int argc, char *argv[])
{
	LOGINREC *login;
	SQLHENV hEnv = 0;
	SQLHDBC hDbc = 0;
	SQLRETURN erc;
	const char *sql;

	setlocale(LC_ALL, "");

	memset(&options, 0, sizeof(options));
	options.headers = stderr;
	login = get_login(argc, argv, &options); /* get command-line parameters and call dblogin() */
	assert(login != NULL);

	/*
	 * Override stdin, stdout, and stderr, as required
	 */
	if (options.input_filename) {
		if (freopen(options.input_filename, "r", stdin) == NULL) {
			fprintf(stderr, "%s: unable to open %s: %s\n", options.appname, options.input_filename, strerror(errno));
			exit(1);
		}
	}

	if (options.output_filename) {
		if (freopen(options.output_filename, "w", stdout) == NULL) {
			fprintf(stderr, "%s: unable to open %s: %s\n", options.appname, options.output_filename, strerror(errno));
			exit(1);
		}
	}

	if (options.error_filename) {
		if (freopen(options.error_filename, "w", stderr) == NULL) {
			fprintf(stderr, "%s: unable to open %s: %s\n", options.appname, options.error_filename, strerror(errno));
			exit(1);
		}
	}

	if (options.fverbose) {
		options.verbose = stderr;
	} else {
		static const char null_device[] = "/dev/null";
		options.verbose = fopen(null_device, "w");
		if (options.verbose == NULL) {
			fprintf(stderr, "%s:%d unable to open %s for verbose operation: %s\n",
					options.appname, __LINE__, null_device, strerror(errno));
			exit(1);
		}
	}

	fprintf(options.verbose, "%s:%d: Verbose operation enabled\n", options.appname, __LINE__);

	/*
	 * Connect to the server
	 */
	if ((erc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv)) != SQL_SUCCESS) {
		odbc_herror(SQL_HANDLE_ENV, hEnv, erc, "SQLAllocHandle", "failed to allocate an environment");
		exit(EXIT_FAILURE);
	}
	assert(hEnv);

	if ((erc = SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)options.odbc_version, SQL_IS_UINTEGER)) != SQL_SUCCESS){
		odbc_herror(SQL_HANDLE_DBC, hDbc, erc, "SQLSetEnvAttr", "failed to set SQL_OV_ODBC3");
		exit(EXIT_FAILURE);
	}

	if ((erc = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc)) != SQL_SUCCESS) {
		odbc_herror(SQL_HANDLE_DBC, hDbc, erc, "SQLAllocHandle", "failed to allocate a connection");
		exit(EXIT_FAILURE);
	}
	assert(hDbc);

	if ((erc = SQLConnect(hDbc, 	(SQLCHAR *) options.servername, SQL_NTS,
					(SQLCHAR *) login->username, SQL_NTS,
					(SQLCHAR *) login->password, SQL_NTS)) != SQL_SUCCESS) {
		odbc_herror(SQL_HANDLE_DBC, hDbc, erc, "SQLConnect", "failed");
		exit(EXIT_FAILURE);
	}

#if 0
	/* Switch to the specified database, if any */
	if (options.database)
		dbuse(dbproc, options.database);
#endif

	/*
	 * Read the queries and write the results
	 */
	while ((sql = next_query()) != NULL ) {
		SQLHSTMT hStmt;

		if ((erc = SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt)) != SQL_SUCCESS) {
			odbc_perror(hStmt, erc, "SQLAllocHandle", "failed to allocate a statement handle");
			exit(EXIT_FAILURE);
		}

		/* "Prepare" the query and send it to the server */
		if ((erc = SQLPrepare(hStmt, (SQLCHAR *) sql, SQL_NTS)) != SQL_SUCCESS) {
			odbc_perror(hStmt, erc, "SQLPrepare", "failed");
			exit(EXIT_FAILURE);
		}

		if((erc = SQLExecute(hStmt)) != SQL_SUCCESS) {
			switch(erc) {
			case SQL_NEED_DATA:
				goto FreeStatement;
			case SQL_SUCCESS_WITH_INFO:
				if (0 != print_error_message(SQL_HANDLE_STMT, hStmt)) {
					fprintf(stderr, "SQLExecute: continuing...\n");
				}
				break;
			default:
				odbc_perror(hStmt, erc, "SQLExecute", "failed");
				exit(EXIT_FAILURE);
			}
		}

		/* Write the output */
		print_results(hStmt);

		FreeStatement:
		if ((erc = SQLFreeHandle(SQL_HANDLE_STMT, hStmt)) != SQL_SUCCESS){
			odbc_perror(hStmt, erc, "SQLFreeHandle", "failed");
			exit(EXIT_FAILURE);
		}
	}

	SQLDisconnect(hDbc);
	SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
	SQLFreeHandle(SQL_HANDLE_ENV, hEnv);

	return 0;
}

static char *
next_query()
{
	char query_line[4096];
	static char *sql = NULL;

	if (feof(stdin))
		return NULL;

	fprintf(options.verbose, "%s:%d: Query:\n", options.appname, __LINE__);

	free(sql);
	sql = NULL;

	while (fgets(query_line, sizeof(query_line), stdin)) {
		/* 'go' or 'GO' separates command batches */
		char *p = query_line;
		if (strncasecmp(p, "go", 2) == 0) {
			for (p+=2; isspace((unsigned char) *p); p++) {
				if (*p == '\n')
					return sql;
			}
		}

		fprintf(options.verbose, "\t%s", query_line);

		/* Add the query line to the command to be sent to the server */
		if (!strlen(query_line))
			continue;
		p = (char *) realloc(sql, 1 + (sql? strlen(sql) : 0) + strlen(query_line));
		if (!p) {
			fprintf(stderr, "%s:%d: could not allocate memory\n", options.appname, __LINE__);
			return NULL;
		}
		if (!sql) {
			strcpy(p, query_line);
		} else {
			strcat(p, query_line);
		}
		sql = p;
	}

	if (feof(stdin))
		return sql;

	if (ferror(stdin)) {
		fprintf(stderr, "%s:%d: next_query() failed\n", options.appname, __LINE__);
		perror(NULL);
		return NULL;
	}

	return sql;
}

static void
free_metadata(struct METADATA *metadata, struct DATA *data, int ncols)
{
	int c;

	for (c=0; c < ncols; c++) {
		free(metadata[c].format_string);
		free(data[c].buffer);
	}
	free(metadata);
	free(data);
}

static const char *
prtype(SQLSMALLINT type)
{
	static char buffer[64];

	switch(type) {
	case SQL_UNKNOWN_TYPE:		return "SQL_UNKNOWN_TYPE";
	case SQL_CHAR:			return "SQL_CHAR";
	case SQL_NUMERIC:		return "SQL_NUMERIC";
	case SQL_DECIMAL:		return "SQL_DECIMAL";
	case SQL_INTEGER:		return "SQL_INTEGER";
	case SQL_SMALLINT:		return "SQL_SMALLINT";
	case SQL_FLOAT:			return "SQL_FLOAT";
	case SQL_REAL:			return "SQL_REAL";
	case SQL_DOUBLE:		return "SQL_DOUBLE";
#if (ODBCVER >= 0x0300)
	case SQL_DATETIME:		return "SQL_DATETIME";
#else
	case SQL_DATE:			return "SQL_DATE";
#endif
	case SQL_VARCHAR:		return "SQL_VARCHAR";
#if (ODBCVER >= 0x0300)
	case SQL_TYPE_DATE:		return "SQL_TYPE_DATE";
	case SQL_TYPE_TIME:		return "SQL_TYPE_TIME";
	case SQL_TYPE_TIMESTAMP:	return "SQL_TYPE_TIMESTAMP";
#endif
#if (ODBCVER >= 0x0300)
	case SQL_INTERVAL:		return "SQL_INTERVAL";
#else
	case SQL_TIME:			return "SQL_TIME";
#endif  /* ODBCVER >= 0x0300 */
	case SQL_TIMESTAMP:		return "SQL_TIMESTAMP";
	case SQL_LONGVARCHAR:		return "SQL_LONGVARCHAR";
	case SQL_BINARY:		return "SQL_BINARY";
	case SQL_VARBINARY:		return "SQL_VARBINARY";
	case SQL_LONGVARBINARY:		return "SQL_LONGVARBINARY";
	case SQL_BIGINT:		return "SQL_BIGINT";
	case SQL_TINYINT:		return "SQL_TINYINT";
	case SQL_BIT:			return "SQL_BIT";
#if (ODBCVER >= 0x0350)
	case SQL_GUID:			return "SQL_GUID";
#endif  /* ODBCVER >= 0x0350 */
	}

	sprintf(buffer, "unknown: %d", (int)type);
	return buffer;
}

#define is_character_data(x)   (x==SQL_CHAR	    || \
				x==SQL_VARCHAR	    || \
				x==SQL_LONGVARCHAR  || \
				x==SQL_WCHAR	    || \
				x==SQL_WVARCHAR     || \
				x==SQL_WLONGVARCHAR)

static SQLLEN
bufsize(const struct METADATA *meta)
{
	assert(meta);
	return meta->size > meta->width? meta->size : meta->width;
}

static void
print_results(SQLHSTMT hStmt)
{
	static const char dashes[] = "----------------------------------------------------------------" /* each line is 64 */
				     "----------------------------------------------------------------"
				     "----------------------------------------------------------------"
				     "----------------------------------------------------------------";

	struct METADATA *metadata = NULL;

	struct DATA *data = NULL;

	SQLSMALLINT ncols = 0;
	RETCODE erc;
	int c, ret;

	/*
	 * Process each resultset
	 */
	do {
		/* free metadata, in case it was previously allocated */
		free_metadata(metadata, data, ncols);
		metadata = NULL;
		data = NULL;
		ncols = 0;

		/*
		 * Allocate memory for metadata and bound columns
		 */
		if ((erc = SQLNumResultCols(hStmt, &ncols)) != SQL_SUCCESS){
			odbc_perror(hStmt, erc, "SQLNumResultCols", "failed");
			exit(EXIT_FAILURE);
		}

		metadata = (struct METADATA*) calloc(ncols, sizeof(struct METADATA));
		assert(metadata);

		data = (struct DATA*) calloc(ncols, sizeof(struct DATA));
		assert(data);

		/*
		 * For each column, get its name, type, and size.
		 * Allocate a buffer to hold the data, and bind the buffer to the column.
		 * "bind" here means to give the address of the buffer we want filled as each row is fetched.
		 */

		fprintf(options.verbose, "Metadata\n");
		fprintf(options.verbose, "%-6s  %-30s  %-10s  %-18s  %-6s  %-6s  \n",
					 "col", "name", "type value", "type name", "size", "varies");
		fprintf(options.verbose, "%.6s  %.30s  %.10s  %.18s  %.6s  %.6s  \n",
					 dashes, dashes, dashes, dashes, dashes, dashes);
		for (c=0; c < ncols; c++) {
			/* Get and print the metadata.  Optional: get only what you need. */
			SQLCHAR name[512];
			SQLSMALLINT namelen, ndigits, fnullable;

			if ((erc = SQLDescribeCol(hStmt, c+1, name, sizeof(name), &namelen,
							&metadata[c].type, &metadata[c].size,
							&ndigits, &fnullable)) != SQL_SUCCESS) {
				odbc_perror(hStmt, erc, "SQLDescribeCol", "failed");
				exit(EXIT_FAILURE);
			}
			assert(namelen < sizeof(name));
			name[namelen] = '\0';
			metadata[c].name = strdup((char *) name);
			metadata[c].width =
				(ndigits >= 0 && (unsigned) ndigits > metadata[c].size)? ndigits : metadata[c].size;

			if (is_character_data(metadata[c].type)) {
				SQLHDESC hDesc;
				SQLINTEGER buflen;

				metadata[c].nchars = metadata[c].size;

				if ((erc = SQLGetStmtAttr(hStmt, SQL_ATTR_IMP_ROW_DESC, &hDesc, sizeof(hDesc), NULL)) != SQL_SUCCESS) {
					odbc_perror(hStmt, erc, "SQLGetStmtAttr", "failed");
					exit(EXIT_FAILURE);
				}
				if ((erc = SQLGetDescField(hDesc, c+1, SQL_DESC_OCTET_LENGTH,
								&metadata[c].size, sizeof(metadata[c].size),
								&buflen)) != SQL_SUCCESS) {
					odbc_perror(hStmt, erc, "SQLGetDescField", "failed");
					exit(EXIT_FAILURE);
				}
				metadata[c].size = metadata[c].size * 2 + 1;
			}

			fprintf(options.verbose, "%6d  %30s  %10d  %18s  %6lu  %6d  \n",
				c+1, metadata[c].name, (int)metadata[c].type, prtype(metadata[c].type),
				(long unsigned int) metadata[c].size,  -1);

#if 0
			fprintf(options.verbose, "%6d  %30s  %30s  %15s  %6d  %6d  \n",
				c+1, metadata[c].name, metadata[c].source, dbprtype(metadata[c].type),
				metadata[c].size,  dbvarylen(dbproc, c+1));

			metadata[c].width = get_printable_size(metadata[c].type, metadata[c].size);
			if (metadata[c].width < strlen(metadata[c].name))
				metadata[c].width = strlen(metadata[c].name);
#endif
			/*
			 * Build the column header format string, based on the column width.
			 * This is just one solution to the question, "How wide should my columns be when I print them out?"
			 */
			ret = set_format_string(&metadata[c], (c+1 < ncols)? options.colsep : "\n");
			if (ret <= 0) {
				fprintf(stderr, "%s:%d: asprintf(), column %d failed\n", options.appname, __LINE__, c+1);
				free_metadata(metadata, data, ncols);
				return;
			}

			/*
			 * Bind the column to our variable.
			 * We bind everything to strings, because we want to convert everything to strings for us.
			 * If you're performing calculations on the data in your application, you'd bind the numeric data
			 * to C integers and floats, etc. instead.
			 *
			 * It is not necessary to bind to every column returned by the query.
			 * Data in unbound columns are simply never copied to the user's buffers and are thus
			 * inaccesible to the application.
			 */

			data[c].buffer = (char *) calloc(1, bufsize(&metadata[c]));
			assert(data[c].buffer);

			if ((erc = SQLBindCol(hStmt, c+1, SQL_C_CHAR, (SQLPOINTER)data[c].buffer,
						bufsize(&metadata[c]), &data[c].len)) != SQL_SUCCESS){
				odbc_perror(hStmt, erc, "SQLBindCol", "failed");
				exit(EXIT_FAILURE);
			}

		}

		if (!options.fquiet) {
			/* Print the column headers to stderr to keep them separate from the data.  */
			for (c=0; c < ncols; c++) {
				fprintf(options.headers, metadata[c].format_string, metadata[c].name);
			}

			/* Underline the column headers.  */
			for (c=0; c < ncols; c++) {
				fprintf(options.headers, metadata[c].format_string, dashes);
			}
		}
		/*
		 * Print the data to stdout.
		 */
		while (ncols > 0 && (erc = SQLFetch(hStmt)) != SQL_NO_DATA) {
			switch(erc) {
			case SQL_SUCCESS_WITH_INFO:
				print_error_message(SQL_HANDLE_STMT, hStmt);
			case SQL_SUCCESS:
				break;
			default:
				odbc_perror(hStmt, erc, "SQLFetch", "failed");
				exit(EXIT_FAILURE);
			}
			for (c=0; c < ncols; c++) {
				switch (data[c].len) { /* handle nulls */
				case SQL_NULL_DATA: /* is null */
					fprintf(stdout, metadata[c].format_string, "NULL");
					break;
				default:
					assert(data[c].len >= 0);
				case SQL_NO_TOTAL:
					fprintf(stdout, metadata[c].format_string, data[c].buffer);
					break;
				}
			}
		}
		if (ncols > 0 && erc == SQL_NO_DATA)
			print_error_message(SQL_HANDLE_STMT, hStmt);

		erc = SQLMoreResults(hStmt);
		fprintf(options.verbose, "SQLMoreResults returned %s\n", prret(erc));
		switch (erc) {
		case SQL_NO_DATA:
			print_error_message(SQL_HANDLE_STMT, hStmt);
			break;
		case SQL_SUCCESS_WITH_INFO:
			print_error_message(SQL_HANDLE_STMT, hStmt);
		case SQL_SUCCESS:
			continue;
		default:
			odbc_perror(hStmt, erc, "SQLMoreResults", "failed");
			exit(EXIT_FAILURE);
		}
	} while (erc != SQL_NO_DATA);

	if (erc != SQL_NO_DATA) {
		assert(erc != SQL_STILL_EXECUTING);
		odbc_perror(hStmt, erc, "SQLMoreResults", "failed");
		exit(EXIT_FAILURE);
	}
	free_metadata(metadata, data, ncols);
}

/**
 * Build the column header format string, based on the column width.
 * This is just one solution to the question, "How wide should my columns be when I print them out?"
 */
static int
set_format_string(struct METADATA * meta, const char separator[])
{
	int ret;
	unsigned width;
	const char *size_and_width;
	assert(meta);

	if(0 == strcmp(options.colsep, default_colsep)) {
		/* right justify numbers, left justify strings */
		size_and_width = is_character_data(meta->type)? "%%-%u.%us%s" : "%%%u.%us%s";

		width = meta->width; /* get_printable_size(meta->type, meta->size); */
		if (width < strlen(meta->name))
			width = strlen(meta->name);

		ret = asprintf(&meta->format_string, size_and_width, width, width, separator);
	} else {
		/* For anything except the default two-space separator, don't justify the strings. */
		ret = asprintf(&meta->format_string, "%%s%s", separator);
	}

	return ret;
}

static void
usage(const char invoked_as[])
{
	fprintf(stderr, "usage:  %s \n"
			"        [-U username] [-P password]\n"
			"        [-S servername] [-D database]\n"
			"        [-i input filename] [-o output filename] [-e error filename]\n"
			, invoked_as);
}

static void
unescape(char arg[])
{
	char *p = arg;
	char escaped = '1'; /* any digit will do for an initial value */
	while ((p = strchr(p, '\\')) != NULL) {

		switch (p[1]) {
		case '0':
			/* FIXME we use strlen() of field/row terminators, which obviously won't work here */
			fprintf(stderr, "bsqlodbc, line %d: NULL terminators ('\\0') not yet supported.\n", __LINE__);
			escaped = '\0';
			break;
		case 't':
			escaped = '\t';
			break;
		case 'r':
			escaped = '\r';
			break;
		case 'n':
			escaped = '\n';
			break;
		case '\\':
			escaped = '\\';
			break;
		default:
			break;
		}

		/* Overwrite the backslash with the intended character, and shift everything down one */
		if (!isdigit((unsigned char) escaped)) {
			*p++ = escaped;
			memmove(p, p+1, 1 + strlen(p+1));
			escaped = '1';
		}
	}
}

static LOGINREC *
get_login(int argc, char *argv[], OPTIONS *options)
{
	LOGINREC *login;
	int ch;

	extern char *optarg;

	assert(options && argv);

	options->appname = basename(argv[0]);
	options->colsep = default_colsep; /* may be overridden by -t */
	options->odbc_version = SQL_OV_ODBC3;	  /* may be overridden by -V */

	login = (LOGINREC *) calloc(1, sizeof(LOGINREC));

	if (!login) {
		fprintf(stderr, "%s: unable to allocate login structure\n", options->appname);
		exit(1);
	}

	if (-1 == gethostname(options->hostname, sizeof(options->hostname))) {
		perror("unable to get hostname");
	}

	while ((ch = getopt(argc, argv, "U:P:S:d:D:i:o:e:t:V:hqv")) != -1) {
		char *p;
		switch (ch) {
		case 'U':
			login->username = strdup(optarg);
			break;
		case 'P':
			login->password = strdup(optarg);
			memset(optarg, 0, strlen(optarg));
			break;
		case 'S':
			options->servername = strdup(optarg);
			break;
		case 'd':
		case 'D':
			options->database = strdup(optarg);
			break;
		case 'i':
			options->input_filename = strdup(optarg);
			break;
		case 'o':
			options->output_filename = strdup(optarg);
			break;
		case 'e':
			options->error_filename = strdup(optarg);
			break;
		case 't':
			unescape(optarg);
			options->colsep = strdup(optarg);
			break;
		case 'h':
			options->headers = stdout;
			break;
		case 'q':
			options->fquiet = 1;
			break;
		case 'V':
			switch(strtol(optarg, &p, 10)) {
			case 3:
				options->odbc_version = SQL_OV_ODBC3
				;
				break;
			case 2:
				options->odbc_version = SQL_OV_ODBC2;
				break;
			default:
				fprintf(stderr, "warning: -V must be 2 or 3, not %s.  Using default of 3\n", optarg);
				break;
			}
		case 'v':
			options->fverbose = 1;
			break;
		case '?':
		default:
			usage(options->appname);
			exit(1);
		}
	}

	if (!options->servername) {
		usage(options->appname);
		exit(1);
	}

	return login;
}


text:
package com.ctrip.xpipe.redis.meta.server.dcchange.impl;

import com.ctrip.xpipe.api.command.Command;
import com.ctrip.xpipe.api.pool.SimpleObjectPool;
import com.ctrip.xpipe.endpoint.DefaultEndPoint;
import com.ctrip.xpipe.netty.commands.NettyClient;
import com.ctrip.xpipe.pool.XpipeNettyClientKeyedObjectPool;
import com.ctrip.xpipe.redis.core.protocal.cmd.ConfigRewrite;
import com.ctrip.xpipe.redis.core.protocal.cmd.ConfigSetCommand.ConfigSetMinSlavesToWrite;
import com.ctrip.xpipe.redis.core.protocal.cmd.transaction.TransactionalCommand;
import com.ctrip.xpipe.redis.meta.server.dcchange.RedisReadonly;

import java.util.concurrent.ScheduledExecutorService;

/**
 * @author wenchao.meng
 *
 * Dec 2, 2016
 */
@Deprecated
public class MinSlavesRedisReadOnly extends AbstractRedisReadOnly implements RedisReadonly{

	public static int READ_ONLY_NUMBER = Integer.MAX_VALUE;

	public static int WRITABLE_NUMBER = 0;

	public MinSlavesRedisReadOnly(String ip, int port, XpipeNettyClientKeyedObjectPool keyedObjectPool, ScheduledExecutorService scheduled) {
		super(ip, port, keyedObjectPool, scheduled);
	}

	@Override
	protected Command<?> createReadOnlyCommand() {
		return createTransactionalCommand(READ_ONLY_NUMBER);
	}

	@Override
	protected Command<?> createWritableCommand() {
		return createTransactionalCommand(WRITABLE_NUMBER);
	}

	private Command<?> createTransactionalCommand(int number){

		SimpleObjectPool<NettyClient> clientPool = keyedObjectPool.getKeyPool(new DefaultEndPoint(ip, port));
		ConfigSetMinSlavesToWrite configSetMinSlavesToWrite = new ConfigSetMinSlavesToWrite(null, number, scheduled);

		return new TransactionalCommand(clientPool, scheduled, configSetMinSlavesToWrite, new ConfigRewrite(null, scheduled));
	}

}


text:
require 'cassie/tasks'

RSpec.describe "cassie:tail rake task" do
  let(:object){ Rake::Task["cassie:tail"] }
  let(:argv){ [] }
  let(:buffer){ StringIO.new }
  let(:log_path){ "some path" }

  before(:each) do
    allow(Cassie::Support::ServerProcess).to receive(:log_path){ log_path }
    allow_any_instance_of(Cassie::Tasks::IO).to receive(:argv){ argv }
    allow_any_instance_of(Cassie::Tasks::IO).to receive(:io){ buffer }
  end
  after(:each){ object.reenable }

  describe "#invoke" do
    it "calls tail -f" do
      expect(Cassie::Support::SystemCommand).to receive(:new){double(run: true)} do |cmd, args|
        expect(cmd).to eq("tail")
        expect(args).to include("-f")
        expect(args).to include(log_path)
      end
      object.invoke
    end
  end
end